October 3, 1999 - Type Conversion

Data types are converted automatically in JavaScript during the course of script execution. A variable may hold a numeric value at one point of the script, and a string at another one. The following statements constitute a valid JavaScript script:

var myVar = 12;
myVar = "university";

Although such conversions are allowed in JavaScript, they are not recommended. Mixing strings and numbers is sometimes necessary for certain operations. There are a few rules to remember. First, when an expression including both numbers and strings is evaluated to a single value, that value is a string. The number 6, for example, can be easily converted to the string "6", while the string "horse" cannot be converted to a number. Secondly, JavaScript's interpreter evaluates expressions from left to right, and only parentheses can change the order of evaluation. Convince yourself that the following statements are correct:

Notice that every expression including a string operand yields a string. The + operator is an addition operator when both of its operands are numbers. It is a concatenation operator when one of its operands is a string.