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
Output of the above program is

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
Output of the above program is

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);
Output of the above program is

true
false
true
false

Note: Always use === and !==. They avoid the strange results of implicit conversion.

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() and Boolean() to convert on purpose.
  • "5" + 2 gives "52" but "5" - 2 gives 3.
  • Use === to compare.
  • Next: JavaScript Operators.

Congratulations! Chapter Finished. Learn more about the similar topics:
Exercises & Assignments
Write a JavaScript program to add two numbers
Write a JavaScript program to swap two variables
Interview Questions & Answers
What are the data types in JavaScript?
What is the difference between == and === in JavaScript?
What is NaN in JavaScript?
What is the difference between null and undefined?
What is scope in JavaScript?
What is the difference between var, let and const?
What is hoisting in JavaScript?