Table of contents
1.
Introduction
2.
What is Type Coercion?
3.
Implicit vs. Explicit Coercion
3.1.
Implicit Coercion
3.2.
Explicit Coercion
4.
Rule of Type Coercion
4.1.
Rule 1: String Concatenation Takes Precedence
4.2.
Rule 2: Loose Equality (`==`) Performs Type Coercion
4.3.
Rule 3: Arithmetic Operations Convert Strings to Numbers
4.4.
Rule 4: Boolean Coercion Follows Truthy & Falsy Rules
4.5.
Rule 5: Logical Operators Perform Coercion
5.
Number to String Conversion
5.1.
Example 1: Implicit Conversion
5.2.
Example 2: Explicit Conversion
6.
String to Number Conversion
6.1.
Example 1: Implicit Conversion
6.2.
Example 2: Explicit Conversion Using Number()
6.3.
Example 3: Using parseInt() and parseFloat()
7.
Boolean to Number Conversion
7.1.
Example 1: Implicit Conversion
7.2.
Example 2: Explicit Conversion Using Number()
8.
The Equality Operator
8.1.
Example 1: Loose Equality (==)
8.2.
Example 2: Strict Equality (===)
9.
Frequently Asked Questions
9.1.
What is type coercion in JavaScript?
9.2.
How does the equality operator (==) work in JavaScript?
9.3.
How can I explicitly convert a string to a number in JavaScript?
10.
Conclusion
Last Updated: Feb 23, 2025
Medium

Type Coercion in JavaScript

Author Gaurav Gandhi
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

Type Coercion in JavaScript is the automatic conversion of one data type to another. It occurs when an operation involves different types, such as adding a number and a string, where JavaScript converts the number into a string. There are implicit coercion (done automatically) and explicit coercion (done using functions like Number(), String(), or Boolean()). 

Type Coercion in JavaScript

In this article, you will learn how type coercion works with examples.

What is Type Coercion?

Type coercion is a mechanism in JavaScript where the language automatically converts one data type into another to make an operation possible. For instance, when you try to add a number and a string, JavaScript doesn’t throw an error. Instead, it converts the number into a string and then performs the operation. This automatic conversion can sometimes lead to unexpected results if you’re not aware of how it works.

Let’s take a simple example to understand this better. Suppose you have the following code:

let num = 5;
let str = "10";
let result = num + str;
console.log(result); 
You can also try this code with Online Javascript Compiler
Run Code


 Output: 

"510"

 

In this case, JavaScript converts the number `5` into a string and then concatenates it with `"10"`. The output is `"510"`, which might not be what you intended if you were expecting a numerical addition. This is an example of type coercion in action.

Another common scenario is when comparing values using loose equality (`==`). JavaScript tries to convert both sides to a common type before making the comparison. For example:

console.log(1 == "1"); 
You can also try this code with Online Javascript Compiler
Run Code

 

Output:

 true

 

Here, JavaScript converts the string `"1"` into a number before comparing it with `1`. That’s why the result is `true`. However, if you use strict equality (`===`), no type coercion happens, and the result would be `false` because the types are different.

Implicit vs. Explicit Coercion

Type coercion in JavaScript can happen in two ways: implicitly or explicitly. Implicit coercion is when JavaScript automatically converts data types during operations, while explicit coercion is when the developer manually converts one type to another using specific methods or functions.

Implicit Coercion

Implicit coercion occurs without the programmer directly asking for it. This often happens during operations like addition, subtraction, or comparisons. For example, when you mix strings and numbers, JavaScript will convert the number into a string to complete the operation.

For example: 

let num = 20;
let str = " apples";
let result = num + str;
console.log(result); 
You can also try this code with Online Javascript Compiler
Run Code

 

Output: 

"20 apples"

 

In this case, JavaScript converts `20` into a string and then concatenates it with `" apples"`. This behavior is automatic and doesn’t require any extra code from the developer.

Another common example of implicit coercion happens with boolean values in conditional statements. JavaScript converts non-boolean values into `true` or `false` based on their "truthy" or "falsy" nature. For example:

let value = "";
if (value) {
  console.log("This will not run");
} else {
  console.log("Empty string is falsy"); 
}
You can also try this code with Online Javascript Compiler
Run Code


Output: 

"Empty string is falsy"

 

Here, the empty string `""` is considered falsy, so JavaScript implicitly converts it to `false`.

Explicit Coercion

Explicit coercion, on the other hand, is when the developer intentionally converts one data type into another. This is done using built-in JavaScript functions like `String()`, `Number()`, or `Boolean()`. Explicit coercion gives you more control over how the conversion happens.

For example, if you want to ensure that a value is treated as a number, you can use the `Number()` function:

let str = "42";
let num = Number(str);
console.log(num); 
console.log(typeof num); 
You can also try this code with Online Javascript Compiler
Run Code

 

Output: 

42
"number"

 

In this case, the string `"42"` is explicitly converted into the number `42`. Similarly, you can convert a number into a string using the `String()` function:

let num = 100;
let str = String(num);
console.log(str);
console.log(typeof str); 
You can also try this code with Online Javascript Compiler
Run Code

 

Output: 

100
"string"

 

Explicit coercion is especially useful when you want to avoid unexpected results caused by implicit conversions. For example, if you’re working with user input from a form, it’s often a good idea to explicitly convert the input into the desired type before performing operations.

Let’s take an example of handling user input:

let userInput = "50"; // Assume this comes from a form
let age = Number(userInput); // Explicitly convert to a number
if (age > 18) {
  console.log("You are an adult");
} else {
  console.log("You are a minor");
}

 

By explicitly converting `userInput` to a number, you ensure that the comparison works as expected.

Rule of Type Coercion

Type coercion in JavaScript follows specific rules that determine how values are converted during operations. These rules apply to both implicit and explicit coercion. Understanding these rules helps you predict how JavaScript will handle different data types in various scenarios.

Rule 1: String Concatenation Takes Precedence

When you use the `+` operator with a string and another data type, JavaScript converts the other data type into a string. This is because the `+` operator is primarily used for string concatenation when one operand is a string.

For example:

let num = 10;
let str = " apples";
let result = num + str;
console.log(result); 
You can also try this code with Online Javascript Compiler
Run Code

 

Output: 

"10 apples"

 

In this case, the number `10` is converted into a string, and then it is concatenated with `" apples"`. This behavior happens automatically due to the presence of a string in the operation.

Rule 2: Loose Equality (`==`) Performs Type Coercion

The loose equality operator (`==`) compares two values after converting them to a common type. This can lead to unexpected results if you’re not aware of the conversion rules.

For example:

console.log(0 == ""); 
console.log(false == "0"); 
console.log(null == undefined); 
You can also try this code with Online Javascript Compiler
Run Code

 

Output: 

true
true
true

 

In the first example, the empty string `""` is converted to `0`, so the comparison returns `true`. In the second example, the string `"0"` is converted to a number, and since `false` is equivalent to `0`, the result is `true`. The third example shows that `null` and `undefined` are considered equal under loose equality.

To avoid confusion, it’s often recommended to use strict equality (`===`), which does not perform type coercion:

console.log(0 === ""); 
console.log(false === "0"); 
console.log(null === undefined); 
You can also try this code with Online Javascript Compiler
Run Code

 
Output: 

false
false
false

Rule 3: Arithmetic Operations Convert Strings to Numbers

When performing arithmetic operations like subtraction, multiplication, or division, JavaScript tries to convert strings into numbers. If the string cannot be converted into a valid number, the result will be `NaN` (Not-a-Number).

For example:

let str1 = "20";
let str2 = "10";
let result = str1 - str2;
console.log(result); 
You can also try this code with Online Javascript Compiler
Run Code

 

Output:

10

 

In this case, both strings `"20"` and `"10"` are converted into numbers before the subtraction operation. However, if the string contains non-numeric characters, the result will be `NaN`:

let invalidStr = "abc";
let num = 5;
let result = invalidStr - num;
console.log(result); 
You can also try this code with Online Javascript Compiler
Run Code

 

Output: 

NaN

Rule 4: Boolean Coercion Follows Truthy & Falsy Rules

JavaScript uses truthy and falsy values to determine the boolean equivalent of non-boolean data types. Falsy values include `false`, `0`, `""` (empty string), `null`, `undefined`, and `NaN`. All other values are considered truthy.

For example:

if ("hello") {
  console.log("This is truthy"); 
}

if (0) {
  console.log("This will not run");
} else {
  console.log("0 is falsy"); 
}
You can also try this code with Online Javascript Compiler
Run Code

 

Output

"This is truthy"
 "0 is falsy"

 

In the first `if` statement, the string `"hello"` is truthy, so the code inside the block runs. In the second `if` statement, `0` is falsy, so the `else` block executes.

Rule 5: Logical Operators Perform Coercion

Logical operators like `||` (OR) and `&&` (AND) also perform type coercion based on truthy and falsy values. The `||` operator returns the first truthy value, while the `&&` operator returns the first falsy value or the last value if all are truthy.

For example:

let result1 = "" || "default";
console.log(result1); 

let result2 = "value" && "anotherValue";
console.log(result2); 
You can also try this code with Online Javascript Compiler
Run Code

 

Output

"Default"
"anotherValue"

In the first example, the empty string `""` is falsy, so the `||` operator returns `"default"`. In the second example, both `"value"` and `"anotherValue"` are truthy, so the `&&` operator returns the last value, `"anotherValue"`.

Number to String Conversion

When a number is converted into a string, JavaScript automatically calls the .toString() method or performs implicit conversion using string concatenation.

Example 1: Implicit Conversion

let num = 42;
let str = num + ""; // Implicit conversion
console.log(str);
console.log(typeof str); 
You can also try this code with Online Javascript Compiler
Run Code


Output: 

"42"
"string"

Example 2: Explicit Conversion

let num = 42;
let str = String(num); // Explicit conversion
console.log(str); 
console.log(typeof str); 
You can also try this code with Online Javascript Compiler
Run Code


Output: 

"42"
"string"

String to Number Conversion

String values can be converted to numbers using implicit or explicit methods. JavaScript attempts to parse the string as a number whenever mathematical operations are performed.

Example 1: Implicit Conversion

let str y= "100";
let num = str * 1; // Implicit conversion
console.log(num);
console.log(tpeof num);
You can also try this code with Online Javascript Compiler
Run Code

 

Output: 

100
"number"

Example 2: Explicit Conversion Using Number()

let str = "100";
let num = Number(str); // Explicit conversion
console.log(num); 
console.log(typeof num); 
You can also try this code with Online Javascript Compiler
Run Code

 

Output: 

100
"number"

Example 3: Using parseInt() and parseFloat()

let str1 = "123";
let str2 = "123.45";

console.log(parseInt(str1)); 
console.log(parseFloat(str2)); 
You can also try this code with Online Javascript Compiler
Run Code

 

Output

123
123.45

Boolean to Number Conversion

Boolean values true and false can be converted into numbers. true is converted to 1, and false is converted to 0.

Example 1: Implicit Conversion

let bool1 = true;
let bool2 = false;

console.log(bool1 * 1); 
console.log(bool2 * 1); 
You can also try this code with Online Javascript Compiler
Run Code


Output: 

1
0

Example 2: Explicit Conversion Using Number()

let bool1 = true;
let bool2 = false;

console.log(Number(bool1)); 
console.log(Number(bool2)); 
You can also try this code with Online Javascript Compiler
Run Code


Output: 

1
0

The Equality Operator

The == (loose equality) operator performs type coercion, meaning different data types can be compared after JavaScript converts them into a common type. The === (strict equality) operator, on the other hand, checks both value and type without coercion.

Example 1: Loose Equality (==)

console.log("5" == 5); 
console.log(false == 0); 
console.log(null == undefined); 
You can also try this code with Online Javascript Compiler
Run Code

 

Output

true
true
true

Example 2: Strict Equality (===)

console.log("5" === 5); 
console.log(false === 0); 
console.log(null === undefined); 
You can also try this code with Online Javascript Compiler
Run Code

 

 Output: 

false
false
false 

Frequently Asked Questions

What is type coercion in JavaScript?

Type coercion in JavaScript is the automatic or explicit conversion of one data type into another, such as converting a string to a number or a boolean to a number.

How does the equality operator (==) work in JavaScript?

The loose equality operator (==) converts both values to a common type before comparison, while the strict equality operator (===) checks both value and type without conversion.

How can I explicitly convert a string to a number in JavaScript?

You can use Number(), parseInt(), or parseFloat() to explicitly convert a string to a number, ensuring that type conversion happens in a controlled manner.

Conclusion

In this article, we learned Type Coercion in JavaScript, which is the automatic conversion of one data type to another. JavaScript performs implicit coercion (e.g., converting numbers to strings) and explicit coercion using functions like Number(), String(), and Boolean(). Understanding type coercion helps developers write cleaner, bug-free code by controlling data type conversions effectively.

Live masterclass