Menu
Coddy logo textTech

Type Coercion

Part of the Fundamentals section of Coddy's JavaScript journey — lesson 22 of 77.

Type coercion in JavaScript is the automatic conversion of values from one data type to another. This can happen implicitly in certain operations or explicitly when you use functions like String(), Number(), or Boolean().

Implicit type coercion often occurs when you use the loose equality operator == or when you perform operations between different types, like adding a number to a string.

For example:

let result = 5 + "5";
// Holds "55", because the number 5 is implicitly converted to the string "5" and then concatenated
let result = true == 1;
// Holds true, because the boolean true is implicitly converted to the number 1

Explicit type coercion can be done using built-in functions:

  • String(value) converts a value to a string
  • Number(value) converts a value to a number
  • Boolean(value) converts a value to a boolean

For example:

let num = "123";
let str = Number(num) + 7; // Holds 130
console.log(str); 
let bool = true;
let numBool = Number(bool); // Holds 1

Understanding type coercion is crucial for writing correct JavaScript code and avoiding unexpected results.

challenge icon

Challenge

Beginner

You are given a code with several variables of different types.

Your task is to perform type coercion and print the results:

  1. Convert the number num to a string and store it in a variable named a.
  2. Convert the boolean bool to a number and store it in a variable named b.
  3. Convert the string str to a number and store it in a variable named c.
  4. Perform an implicit type coercion by concatenating num with str and store the result in a variable named d.

Use explicit type coercion functions (String(), Number()) for the first three tasks and observe implicit coercion in the last task.

Cheat sheet

Type coercion in JavaScript is the automatic conversion of values from one data type to another.

Implicit type coercion happens automatically in operations:

let result = 5 + "5"; // "55" - number converted to string
let result = true == 1; // true - boolean converted to number

Explicit type coercion uses built-in functions:

  • String(value) converts a value to a string
  • Number(value) converts a value to a number
  • Boolean(value) converts a value to a boolean
let num = "123";
let str = Number(num) + 7; // 130

let bool = true;
let numBool = Number(bool); // 1

Try it yourself

// Given variables
let num = 42
let bool = false
let str = "7"

// Type your code below


// Don't change the line below
console.log(`a = ${a}`)
console.log(`b = ${b}`)
console.log(`c = ${c}`)
console.log(`d = ${d}`)
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals