Conversion and Coercion in js

Jagdish SeerviJagdish Seervi
2 min read

In JavaScript, type conversion and coercion are two concepts related to how values are converted from one data type to another. While they are often used interchangeably, they represent slightly different processes.

Type Conversion:

Type conversion is the explicit conversion of a value from one data type to another. This happens when you use functions or methods to convert a value from one type to another.

Example:

// Convert a string to a number let str = "123"; let num = Number(str); console.log(num); // Output: 123

// Convert a number to a string let num = 123; let str = String(num); console.log(str); // Output: "123"

Type Coercion:

Type coercion, on the other hand, is the implicit conversion of values between different data types. This happens automatically when values of different types are used together in an expression or operation. Example:

// Number + String let num = 10; let str = "5"; let result = num + str; // JavaScript coerces num to a string and performs concatenation console.log(result); // Output: "105"

// String to Boolean let str = "true"; let bool = !!str; // JavaScript coerces the string to a boolean value console.log(bool); // Output: true

// Addition with Number and Boolean let num = 10; let bool = true; let result = num + bool; // JavaScript coerces bool to a number (true becomes 1) console.log(result); // Output: 11

In the examples above, type conversion involves explicitly converting a value from one type to another using functions like Number(), String(), Boolean(), etc. On the other hand, type coercion refers to the automatic conversion that happens when values of different types are combined in expressions or operations. JavaScript performs type coercion based on its own rules to make sense of the operation, often resulting in unexpected behavior if not handled carefully.

1
Subscribe to my newsletter

Read articles from Jagdish Seervi directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Jagdish Seervi
Jagdish Seervi