ChApter 1 ■ JAvASCrIpt You Need to KNow
JavaScript is very flexible with types, and it allows you significant freedoms, but the tradeoff is that what is going
on behind the scenes is not always obvious. For example, you have already seen that the + operator performs double
duty: it can do addition and it can also do string concatenation. With that in mind, examine the following code
snippet. Can you predict its output?
// Will this produce the number 2 or the string "11"?
console.log("1" + 1);
The output is:
11
From this, we can deduce that JavaScript must have converted the number value to a string value and performed
a concatenation operation, as opposed to an addition operation.
At times, as you might imagine, we want some control over types. Fortunately, JavaScript comes with the right
tools. Table 1-2 shows just a few of the tools you have at your disposal.
Table 1-2. A Few Built-in Type-Related Utilities
Function / Operator Description
typeof Allows you to ask the data type of its operand. It can provide the following values:
"number"
"string"
"boolean"
"object"
"undefined"
null
parseInt The parseInt() function parses a string and returns a number. If it cannot return a number,
it will return NaN (Not a Number).
toString Converts a value, such as a number, to a string
isNaN The isNaN function can tell you if a given value is not a number. For example,
isNaN('three') will return true; isNaN(3) will return false.
Listing 1-15 shows each of these in action.
Listing 1-15. Type Conversion Examples
<!DOCTYPE html>