Section 1: Typing
JavaScript (ECMAScript) is a loosely typed language.
- That does not mean that it has no data types, rather that the value of a variable does not need to have a particular type of value assigned to it.
- Further, a variable might not always hold the same type of value.
- JavaScript also freely type-converts values into a type suitable for (or required by) the context of their use.
This does not save the programmer from needing to think about the actual type of values that they are dealing with.
A very common error in browser scripting, for example, is to read the value property of a form control into which the user is expected to type a number and then add that value to another number.
- The problem arises because the data contained within form controls are strings (even if the character sequence represents a number), and an attempt to add that string to a value, even if that value happens to be a number, results in the second value being type-converted into a string and concatenated to the end of the first string value from the form control.
That problem is exacerbated by the dual nature of the + operator being used for both numeric addition and string concatenation.
- The nature of the operation performed is determined by the context, in which case only if both operands are numbers to start with will the + operator perform addition.
- Otherwise it converts all of its operands to strings and performs concatenation.
Section 2: Converting Values to Numbers
Converting values to numbers, especially strings to numbers (since everything entered in a form field is read as a string), is a common requirement.
There are many approaches that can be used to convert values to numbers:
- Any mathematical operator (except the concatenation/addition operator) will force type conversion.
- So conversion of a string to a number might entail performing a mathematical operation on the string representation of the number that would not affect the resulting number, such as adding zero or multiplying by one (remember the additive (0) identity and multiplicative (1) identity?)
- Subtraction and division are defined in terms of addition and multiplication and the same identities hold.
var numValue = stringValue - 0;
var numValue = stringValue * 1;
var numValue = stringValue / 1;
Recommended option: the unary + operator (positive sign) type-converts its operand to a number, and because it does not do any additional mathematical operations, it is the fastest method for type-converting a string into a number.
var numValue = +stringValue;
While unary + is the fastest method for converting a string to a number, yet another method is available that uses the Javascript type-conversion algorithms. The Number constructor can be called with the string value as its argument and its return value is a number representing the result of the type-conversion.
var numValue = Number(stringValue);
The Number constructor is the slowest of the type-converting methods but when speed is not an overriding consideration its use does produce the clearest source code.
Section 3: Parsing to Numbers
parseFloat
An alternative method of converting a string into a number is to use one of the global functions designed to parse a string and return a number.
- The parseFloat function accepts a string argument and returns a floating point number resulting from parsing that string.
- Non-string arguments are first type-converted to a string as described above.
The string parsing functions read the string character by character until they encounter a character that cannot be part of the number, at which point they stop and return a number based on the characters that they have seen that can be part of the number.
With parseFloat, empty strings return NaN along with strings that cannot be subject to numeric interpretation.
- The exponential format is understood and the leading zero in the octal format does not hinder the string's interpretation as a decimal number.
- Hexadecimal strings are interpreted as the number zero because the following "x" cannot be interpreted as part of a number so parsing stops after the leading zero.
parseInt
The parseInt function works in a similar way to parseFloat except that it is trying to interpret its string argument into an integer, and as a result recognizes fewer character as possible candidates to be part of that number.
Beware: because of the number format used by JavaScript, numbers are often represented by near approximations.
- So, for example, 1/2 + 1/3 + 1/6 = 0.9999999999999999, which is almost 1, but parseInt will return zero if asked to act on the result of the operation.
For rounding numbers to integers one of Math.round, Math.ceil and Math.floor are preferable.
Adapted from Javascript Type-Conversion