JavaScript type conversion reference

JavaScript provides you with built-in methods to convert values from one type to another. Type conversion is commonly required when you want to perform some kind of operation to the values you have in your program. There are two kinds of type conversion in JavaScript based on how they are performed:

  • Implicit conversion, also called type coercion
  • Explicit conversion, which is what you will learn in this tutorial

For example, suppose you want to perform an addition between the price and the tax variable, but they are declared as a string type instead of number type, causing the addition to concatenate the values instead of adding to it:

let price = "20";
let tax = "5";

console.log(price + tax); // "205"

Of course, you can simply change the declaration of both variables as number types, but for this tutorial, let’s pretend they are unchangeable. What you can do for this situation is to convert those string type variables into number types by calling the Number method.

Here’s how you do it:

let price = "20";
let tax = "5";

console.log(Number(price) + Number(tax)); // 25

And that’s what explicit type conversion is all about. Generally, you can convert data or values from one type to another using one of three built-in JavaScript methods:

  • Number()
  • String()
  • Boolean()

The result of these conversion methods will depend on the value you passed as the argument. In the example above, the string variables are correctly converted into number types because they are representative of those numbers. JavaScript will return NaN as value when you passed letters, words, or sentences into the Number variable:

Number("hello"); // NaN
Number(false); // 0
Number(true); // 1

String(2); // "2"
String(true); // "true"
String(false); // "false"

Boolean(0); // false
Boolean(1); // true
Boolean(2); // true

Here’s a JavaScript type conversion table for your reference. Please keep in mind that:

  • Values wrapped in double quotation marks indicate a string type.
  • Values wrapped in braces indicate an object type.
  • Values wrapped in square brackets indicate an array type.
  • true or false indicates real Boolean values
ValueString ConversionNumber ConversionBoolean Conversion
1"1"1true
0"0"0false
"1""1"1true
"0""0"0true
"ten""ten"NaNtrue
true"true"1true
false"false"0false
null"null"0false
undefined"undefined"NaNfalse
''""0false
' '" "0true
[ ]0""true
[20]20"20"true
[10,20]NaN"10,20"true
["twenty"]NaN"twenty"true
["ten","twenty"]NaN"ten,twenty"true
{}"[object Object]"NaNtrue
{name:"Jack"}"[object Object]"NaNtrue

Take your skills to the next level ⚡️

I'm sending out an occasional email with the latest tutorials on programming, web development, and statistics. Drop your email in the box below and I'll send new stuff straight into your inbox!

No spam. Unsubscribe anytime.