Lesson guide
Learning objectives
- Explain the main purpose of Type Conversions in JavaScript.
- Identify the syntax, APIs, or concepts introduced in this lesson.
- Use the examples to predict how JavaScript will behave before you run similar code.
- Connect this topic to nearby lessons in JavaScript Fundamentals.
Real-world context
This lesson matters when you need to recognize where Type Conversions fits into real JavaScript programs. Most of the time, operators and functions automatically convert the values given to them to the right type.
Key ideas
- Type Conversions is part of the JavaScript Fundamentals chapter, so it builds on the surrounding concepts rather than standing alone.
- Read each code example in two passes: first for the result, then for the rule that explains the result.
- When a section compares similar features, focus on the condition that makes you choose one feature over another.
Key terms
- Type Conversions
- Type
- Conversions
- JavaScript Fundamentals
- JavaScript
Most of the time, operators and functions automatically convert the values given to them to the right type.
For example, 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.
Not talking about objects yet
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
String conversion happens when we need the string form of a value.
For example, alert(value) does it to show the value.
We can also call the String(value) function to convert a value to a string:
let value = true; alert(typeof value); // boolean value = String(value); // now value is a string "true" alert(typeof value); // string
String conversion is mostly obvious. A false becomes "false", null becomes "null", etc.
Numeric Conversion
Numeric conversion in mathematical functions and expressions happens automatically.
For example, when division / is applied to non-numbers:
alert( "6" / "2" ); // 3, strings are converted to numbers
We can use the Number(value) function to explicitly convert a value to a number:
let str = "123"; alert(typeof str); // string let num = Number(str); // becomes a number 123 alert(typeof num); // 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:
let age = Number("an arbitrary string instead of a number"); alert(age); // NaN, conversion failed
Numeric conversion rules:
| Value | Becomes… |
|---|---|
undefined | NaN |
null | 0 |
true and false | 1 and 0 |
string | Whitespaces (includes spaces, tabs \t, newlines \n etc.) from the start and end are removed. If the remaining string is empty, the result is 0. Otherwise, the number is “read” from the string. An error gives NaN. |
Examples:
alert( Number(" 123 ") ); // 123 alert( Number("123z") ); // NaN (error reading a number at "z") alert( Number(true) ); // 1 alert( Number(false) ); // 0
Please note that null and undefined behave differently here: null becomes zero while undefined becomes NaN.
Most mathematical operators also perform such conversion, we’ll see that in the next chapter.
Boolean Conversion
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 Boolean(value).
The conversion rule:
- Values that are intuitively “empty”, like
0, an empty string,null,undefined, andNaN, becomefalse. - Other values become
true.
For instance:
alert( Boolean(1) ); // true alert( Boolean(0) ); // false alert( Boolean("hello") ); // true alert( Boolean("") ); // false
Please note: the string with zero "0" is true
Some languages (namely PHP) treat "0" as false. But in JavaScript, a non-empty string is always true.
alert( Boolean("0") ); // true alert( Boolean(" ") ); // spaces, also true (any non-empty string is true)
Common mistakes
- Skipping the small examples and then missing the exact rule that Type Conversions depends on.
- Copying code without changing one value at a time to see which part controls the result.
- Treating similar-looking syntax or APIs as interchangeable before checking their edge cases.
Summary
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 Number(value).
The conversion follows the rules:
| Value | Becomes… |
|---|---|
undefined | NaN |
null | 0 |
true / false | 1 / 0 |
string | The string is read “as is”, whitespaces (includes spaces, tabs \t, newlines \n etc.) from both sides are ignored. An empty string becomes 0. An error gives NaN. |
Boolean Conversion – Occurs in logical operations. Can be performed with Boolean(value).
Follows the rules:
| Value | Becomes… |
|---|---|
0, null, undefined, NaN, "" | false |
| any other value | true |
Most of these rules are easy to understand and memorize. The notable exceptions where people usually make mistakes are:
undefinedisNaNas a number, not0."0"and space-only strings like" "are true as a boolean.
Objects aren’t covered here. We’ll return to them later in the chapter Object to primitive conversion that is devoted exclusively to objects after we learn more basic things about JavaScript.
Predict
Before running this check, predict every conversion result. The tricky cases are undefined, null, an empty string, "0", and a string that contains only spaces.
Reveal explanation
The output is true: String=true, Number=1, Boolean=true, false: String=false, Number=0, Boolean=false, null: String=null, Number=0, Boolean=false, undefined: String=undefined, Number=NaN, Boolean=false, "": String=, Number=0, Boolean=false, "0": String=0, Number=0, Boolean=true, " ": String= , Number=0, Boolean=true, and "123z": String=123z, Number=NaN, Boolean=true. Numeric conversion trims strings and turns an empty result into 0, but boolean conversion only treats the truly empty string "" as false; any non-empty string, even "0" or spaces, is true.
Try it
Add " 42 " and "false" to the array, then predict their Number(...) and Boolean(...) results. These two values catch many real form-input bugs.
Practice
- Rewrite one example from this lesson without looking at the original, then run it and compare the result.
- Change one input, operator, method call, or option in a code sample and predict what will happen before running it.
- Explain Type Conversions in your own words as if you were reviewing it with another learner.
Keep learning
Continue with Basic operators, maths when you are ready for the next lesson.