DATA TYPE CONVERSION
JavaScript is a dynamically typed language. This means you don't have to specify the data type of a variable when you declare it, and data types are converted automatically as needed during script execution.
So, for example, you could define a variable as follows:
var answer = 42
And later, you could assign the same variable a string value, for example:
answer = "Thanks for all the fish . . ."
Because JavaScript is dynamically typed, this doesn't cause an error message.
In expressions involving numeric and string values with the + operator, JavaScript converts numeric values to strings, as discussed in Lesson 2.
For example, consider the following statements:
x = "The answer is " + 42 // returns "The answer is 42"
JavaScript comments are preceded by //.
In this statement, a string value and a numeric value are concatenated
together -- the numeric value (42) is converted to a string
("42").
In statements involving other operators, JavaScript doesn't convert numeric values to strings. For example:
"37" - 7 // returns 30
however
"37" + 7 // returns 377
Most time, you don't need to be too concerned because JavaScript will figure out from the context of the rest of the code statement what to do with a specific piece of data and whether to treat it as a number or as a string.
The major exception to this is addition. To do a numerical addition, you need to transform your data in some way to make sure that the data is treated as a number and added together, rather than being treated as a string and concatenated.
You can transform your data using the JavaScript's parseInt()
and parseFloat() functions, as well as the other techniques
covered in Lesson 2. In the following section, you look closer at the details
of these useful functions.
