Most of the time, operators and functions automatically convert the values given to them to the right type.
alert automatically converts any value to a string to show it. Mathematical operations convert values to numbers.
There are also cases when we need to explicitly convert a value to the expected type.
In this chapter, we won’t cover objects. For now we’ll just be talking about primitives.
Later, after we learn about objects, in the chapter Object to primitive conversion we’ll see how objects fit in.
String conversion happens when we need the string form of a value.
alert(value) does it to show the value.
We can also call the
String(value) function to convert a value to a string:
String conversion is mostly obvious. A
Numeric conversion happens in mathematical functions and expressions automatically.
For example, when division
/ is applied to non-numbers:
We can use the
Number(value) function to explicitly convert a
value to a number:
Explicit conversion is usually required when we read a value from a string-based source like a text form but expect a number to be entered.
If the string is not a valid number, the result of such a conversion is
NaN. For instance:
Numeric conversion rules:
||Whitespaces from the start and end are removed. If the remaining string is empty, the result is
Please note that
undefined behave differently here:
null becomes zero while
Most mathematical operators also perform such conversion, we’ll see that in the next chapter.
Boolean conversion is the simplest one.
It happens in logical operations (later we’ll meet condition tests and other similar things) but can also be performed explicitly with a call to
The conversion rule:
- Values that are intuitively “empty”, like
0, an empty string,
- Other values become
The three most widely used type conversions are to string, to number, and to boolean.
String Conversion – Occurs when we output something. Can be performed with
String(value). The conversion to string is usually obvious for primitive values.
Numeric Conversion – Occurs in math operations. Can be performed with
The conversion follows the rules:
||The string is read “as is”, whitespaces from both sides are ignored. An empty string becomes
Boolean Conversion – Occurs in logical operations. Can be performed with
Follows the rules:
|any other value||
Most of these rules are easy to understand and memorize. The notable exceptions where people usually make mistakes are:
NaNas a number, not
"0"and space-only strings like
" "are true as a boolean.