October 3, 1999 - Type Conversion
October 3, 1999 Type Conversion Tips: October 1999
Yehuda Shiran, Ph.D.
|
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:
8 + 8 // 16
"8" + 8 // "88"
8 + "8" // "88"
"8" + "8" // "88"
8 + 8 + "8" // "168"
8 + "8" + 8 // "888"
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.