JavaScript type conversion reference

JavaScript has multiple built-in methods to convert your data or values from one type to another. Here's a list of reference for them

Posted on January 23, 2021

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
' '" "0true
[ ]0""true
{}"[object Object]"NaNtrue
{name:"Jack"}"[object Object]"NaNtrue

Related articles:

Grab the free JavaScript book today 👍

Learn the building blocks of JavaScript programming language like data types, functions, objects, arrays and classes.

Use the knowledge from the book to build a small but solid program.

Learn more