Most of the time, operators and functions automatically convert a value to the right type. That’s called “type coercion”.
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 put things right.
In this chapter we don’t cover objects yet. Here we study primitives first. Later, after we learn objects, we’ll see how object conversion works in the chapter Object to primitive conversion.
String conversion happens when we need the string form of a value.
alert(value) does it to show the value.
We can also use a call
String(value) function for that:
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 a
Number(value) function to explicitly convert a
Explicit conversion is usually required when we read a value from a string-based source like a text form, but we expect a number to be entered.
If the string is not a valid number, the result of such conversion is
NaN, for instance:
Numeric conversion rules:
||Whitespaces from the start and the end are removed. Then, if the remaining string is empty, the result is
Please note that
undefined behave differently here:
null becomes a zero, while
Almost all mathematical operations convert values to numbers. With a notable exception of the addition
+. If one of the added values is a string, then another one is also converted to a string.
Then it concatenates (joins) them:
That only happens when one of the arguments is a string. Otherwise, values are converted to numbers.
Boolean conversion is the simplest one.
It happens in logical operations (later we’ll meet condition tests and other kinds of them), but also can be performed manually with the call of
The conversion rule:
- Values that are intuitively “empty”, like
0, an empty string,
- Other values become
There are three most widely used type conversions: to string, to number and to boolean.
ToString – Occurs when we output something, can be performed with
String(value). The conversion to string is usually obvious for primitive values.
ToNumber – 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
ToBoolean – Occurs in logical operations, or 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.