JS Type Conversion

JavaScript Type Conversion

JavaScript is a dynamically typed language, which means it often tries to automatically convert values from one data type to another. This process is called Type Coercion.

While automatic conversion can be convenient, it can also lead to unexpected bugs. To write robust code, it's important to understand both automatic (implicit) and manual (explicit) type conversion.


1. Converting to Strings

The easiest way to explicitly convert any value to a string is to use the global String() function.

Converting to String

console.log(String(123));       // "123"
console.log(String(true));      // "true"
console.log(String(null));      // "null"
console.log(String(undefined)); // "undefined"

Alternatively, the toString() method can be used, but it will throw an error on null and undefined.

Implicit String Conversion

Implicit conversion to a string happens most often when using the + operator with a string.

Implicit String Conversion

let result = '5' + 5; // The number 5 is coerced to a string '5'
console.log(result); // "55"

2. Converting to Numbers

To explicitly convert a value to a number, use the global Number() function.

Converting to Number

console.log(Number("3.14"));    // 3.14
console.log(Number(" "));        // 0
console.log(Number(""));         // 0
console.log(Number("99 88"));    // NaN
console.log(Number("hello"));   // NaN
console.log(Number(true));      // 1
console.log(Number(false));     // 0
console.log(Number(null));      // 0
console.log(Number(undefined)); // NaN

Implicit Number Conversion

Implicit conversion to a number happens in mathematical expressions (except for + with a string).

Implicit Number Conversion

console.log('6' / '2'); // 3
console.log('6' - 2);   // 4

3. Converting to Booleans

To explicitly convert a value to a boolean, use the global Boolean() function. The rules are simple: any value that is not "falsy" will convert to true.

Falsy Values

There are only a handful of values in JavaScript that convert to false:

Everything else is "truthy" and converts to true! This includes empty arrays [] and empty objects {}.

Converting to Boolean

// Falsy values
console.log(Boolean(0));          // false
console.log(Boolean(""));         // false
console.log(Boolean(null));       // false

// Truthy values console.log(Boolean(1)); // true console.log(Boolean("hello")); // true console.log(Boolean({})); // true

Implicit Boolean Conversion

Implicit conversion to a boolean happens in logical contexts, like inside an if statement.

Implicit Boolean Conversion

if ("hello") {
  // This code runs because "hello" is truthy
  console.log("This will be printed!");
}

Exercise

?

Which of the following values is considered "truthy" in JavaScript and will convert to `true`?