Friday, August 9, 2013

JavaScript Conversion between types

JavaScript automatically converts values from one type to another when they are used in an expression. This means that you can combine different types in an expression and JavaScript will try to perform the type conversions that are necessary for the expression to make sense. For example, the expression "test" +5 will convert the numeric 5 to a string "5" and append it to the string "test", producing "test5". JavaScript's automatic type conversion also allows you to assign a value of one type to a variable and then later assign a value of the different type to the same variable.

How does JavaScript convert from one type to another? The process of determining when a conversion should occur and what type of conversion should be made is fairly complex. JavaScript converts values when it evaluates an expression or assigns a value to a variable. When JavaScript assigns a value to a variable it changes the type associated with the variable to the type of the value that is assigns.

When JavaScript evaluates an expression, it parses the expression into its component unary and binary expressions based upon the order of precedence of the operators it contains. It then evaluates the component unary and binary expressions of the parse tree. Figure 2.22 illustrates this process. Each expression is evaluated according to the operators involved. If an operator takes a value of a type that is different than the type of an operand, then the operand is converted to a type that is valid for the operator.

No comments:

Post a Comment