JavaScript Type Conversion
JavaScript can change a value from one type to another. You can do it yourself (explicit conversion), or JavaScript does it by itself (implicit conversion, also called coercion).
Explicit conversion
console.log(String(123)); // "123"
console.log(Number("42")); // 42
console.log(Number("abc")); // NaN
console.log(Number("")); // 0
console.log(Boolean("")); // false
console.log(Boolean("0")); // true
console.log(parseInt("42px")); // 42
console.log(parseFloat("3.14abc")); // 3.14
123
42
NaN
0
false
true
42
3.14
NaN means “Not a Number”. parseInt() and parseFloat() read the number at the start of a text and stop at the first wrong character.
Implicit conversion
With the + operator, if one side is a string, the other side is changed to a string too. The other maths operators change text to numbers.
console.log("5" + 2); // "52"
console.log("5" - 2); // 3
console.log("5" * "2"); // 10
console.log(true + 1); // 2
52
3
10
2
== and ===
The == operator converts types before comparing. The === operator compares the value and the type, with no conversion.
console.log(5 == "5");
console.log(5 === "5");
console.log(0 == false);
console.log(0 === false);
true
false
true
false
Truthy and falsy
In a condition every value is treated as true or false. These values are falsy: false, 0, "" (empty string), null, undefined and NaN. Everything else is truthy, even "0" and [].
Summary
- Use
String(),Number()andBoolean()to convert on purpose. "5" + 2gives"52"but"5" - 2gives3.- Use
===to compare. - Next: JavaScript Operators.
| Exercises & Assignments |
|---|
| Write a JavaScript program to add two numbers |
| Write a JavaScript program to swap two variables |