javascript

Type Coercion

Learn about type coercion in JavaScript. Understand how values automatically change between data types and how to control conversions for cleaner code.

9 min read 8 sections Tutorial
Share

Type coercion is when JavaScript automatically changes one type of data into another. This can happen without you even asking for it. Understanding type coercion helps you write code that works correctly and avoids surprising results.

Type Coercion

Type Coercion

In JavaScript, data comes in different types, like numbers or text (strings). Sometimes, JavaScript needs to use a value of one type where another type is expected. When this happens, JavaScript tries to change the data type automatically. This process is called type coercion. It's important to know how it works so your code behaves as you expect.

What is Type Coercion?

Type coercion is JavaScript's way of converting a value from one data type to another, either automatically or when you tell it to.

Automatic Conversion

JavaScript often changes data types on its own without you writing specific conversion code.

Manual Conversion

You can also choose to convert data types yourself using special JavaScript tools.

Avoid Surprises

Learning coercion helps you prevent unexpected errors and make your code more reliable.

Clearer Code

When you understand coercion, you can write code that is easier to read and debug for others.

What is Type Coercion?

Getting Started

What is Type Coercion?

Imagine you have a number, like 5, and a piece of text, like "hello". If you try to add them together in JavaScript, what happens? JavaScript has to decide how to combine them. It cannot add a number and text directly. So, it will change one of them to match the other type. This automatic change is type coercion.

javascript
1// Here, '5' is a number and '10' is a string (text).
2let myNumber = 5;
3let myString = "10";
4
5// JavaScript sees a number and a string with the '+' operator.
6// It changes the number '5' into a string '"5"'.
7// Then, it joins the two strings together.
8let result = myNumber + myString;
9
10console.log(result); // This will print "510", not 15.
11console.log(typeof result); // This will print "string", because the number became a string.

Watch Out for Surprises!

The + operator can be tricky. If one side is a string, it will convert the other side to a string and join them. It will not perform math addition. This is a common mistake for beginners.

Implicit vs. Explicit Coercion

Implicit vs. Explicit Coercion

Type coercion happens in two main ways: implicitly and explicitly. Implicit coercion happens automatically, behind the scenes. You don't write any special code for it. Explicit coercion means you specifically tell JavaScript to change a data type. You use special functions or operators to make this happen.

javascript
1// --- Implicit Coercion (Automatic) ---
2let value1 = "5"; // This is a string
3let value2 = 2; // This is a number
4
5// JavaScript implicitly converts 'value2' (number) to a string '"2"'.
6// Then it concatenates (joins) the two strings.
7let implicitResult = value1 + value2;
8console.log("Implicit Result:", implicitResult); // "52"
9console.log("Implicit Result Type:", typeof implicitResult); // "string"
10
11// --- Explicit Coercion (Manual) ---
12let value3 = "5"; // This is a string
13let value4 = 2; // This is a number
14
15// We explicitly convert 'value3' (string) to a number using Number() function.
16// Now, both values are numbers, so addition works as expected.
17let explicitResult = Number(value3) + value4;
18console.log("Explicit Result:", explicitResult); // 7
19console.log("Explicit Result Type:", typeof explicitResult); // "number"
✗ BadImplicit Coercion (Can be confusing)
let a = "10";
let b = 5;
let result = a / b; // JavaScript tries to make 'a' a number here.
console.log(result); // Output: 2 (string "10" becomes number 10)
✓ GoodExplicit Coercion (Clearer intent)
let a = "10";
let b = 5;
let result = Number(a) / b; // We clearly say to make 'a' a number.
console.log(result); // Output: 2

Converting Data Types Safely

Converting Data Types Safely

When you need to change a data type, it's usually best to do it explicitly. This makes your code easier to understand. JavaScript gives you several ways to convert values. You can turn things into numbers, strings, or booleans (true/false). Choosing the right method depends on what you are trying to do.

Using Global Functions
// Convert to Number
let strNum = "123";
let num = Number(strNum); // num is now 123 (a number)
// Convert to String
let anyNum = 456;
let str = String(anyNum); // str is now "456" (a string)
// Convert to Boolean
let zero = 0;
let bool = Boolean(zero); // bool is now false (0 is 'falsy')
console.log(typeof num, typeof str, typeof bool);
VS
Using Specific Methods
// Convert to Integer (whole number)
let floatStr = "123.45";
let int = parseInt(floatStr); // int is now 123 (ignores decimals)
// Convert to Floating-point (number with decimals)
let intStr = "100";
let float = parseFloat(intStr); // float is now 100 (still a float type)
// Convert anything to String using .toString()
let myNum = 789;
let myStr = myNum.toString(); // myStr is now "789"
console.log(typeof int, typeof float, typeof myStr);

When to Use Which?

Use Number(), String(), Boolean() for general type conversion. Use parseInt() or parseFloat() when you specifically need to convert a string to a whole number or a decimal number. Use .toString() when you have a value and want its string representation.

Type Coercion in Real JavaScript

Type Coercion in Real JavaScript

Type coercion comes up a lot in real-world coding. For example, when users type numbers into a form, those numbers come into your JavaScript code as strings. If you want to do math with them, you must convert them to actual numbers. This is a very common scenario where explicit coercion is necessary.

1

Get User Input

First, imagine you get input from a user. This input is always a string, even if it looks like a number.

javascript
1let userInput = "123"; // User typed '123' into a form field
2

Try Math (Incorrectly)

If you try to do math with the string directly, JavaScript might not do what you expect. The + operator will join strings.

javascript
1let price = "10"; // Price from a database or another input
2let total = userInput + price; // This will be "12310", not 133
3console.log("Incorrect total:", total);
3

Convert to Number (Correctly)

You must explicitly convert the user input to a number before doing math. Use Number() or parseInt().

javascript
1let correctUserInput = Number(userInput); // Convert "123" to 123
2let price = 10; // Make sure price is also a number
3let correctTotal = correctUserInput + price; // Now it's 123 + 10 = 133
4console.log("Correct total:", correctTotal);
4

Handle Invalid Input

What if the user types something that isn't a number? Number() will turn it into NaN (Not a Number). You should check for NaN to avoid errors later.

javascript
1let badInput = "hello";
2let convertedBadInput = Number(badInput); // This becomes NaN
3
4if (isNaN(convertedBadInput)) { // Check if it's NaN
5 console.log("Error: Please enter a valid number.");
6} else {
7 console.log("Valid number:", convertedBadInput);
8}

Ignoring Types Can Break Your Code!

If you don't pay attention to data types and type coercion, your program might calculate wrong totals, display unexpected text, or crash entirely. Always be aware of the data types you are working with.

Common Coercion Rules

Common Coercion Rules

OperationExampleResultWhat Happens
String + Number`"5" + 2``"52"`Number converts to String, then concatenates.
Number + String`5 + "2"``"52"`Number converts to String, then concatenates.
Number - String`5 - "2"``3`String converts to Number, then subtracts.
String == Number`"5" == 5``true`String converts to Number for comparison.
Boolean + Number`true + 1``2``true` becomes `1`, then adds.
Boolean == Number`false == 0``true``false` becomes `0` for comparison.
Null == Undefined`null == undefined``true`These two are considered equal without explicit conversion.
Null == 0`null == 0``false``null` does not convert to `0` for `==`.

Test Your Knowledge

Test Your Knowledge

Test Your Knowledge

Quick Check

What is the result of "10" + 5 in JavaScript?

Quick Check

Which of these will explicitly convert a string "20.5" to a decimal number?

Quick Check

What is the value of true == 1?

Quick Check

Which operator does not perform type coercion before comparison?

Quick Reference

Quick Reference

Quick Reference

Pro Tips
  • 1Type Coercion — The automatic or intentional conversion of a value from one data type to another.
  • 2Implicit Coercion — Happens automatically by JavaScript, often in math operations or comparisons.
  • 3Explicit Coercion — You manually convert types using functions like Number(), String(), or Boolean().
  • 4+ Operator — If any operand is a string, + will concatenate (join) values as strings, not add them mathematically.
  • 5Number() Function — Converts a value to a number. Returns NaN if the conversion fails.
  • 6String() Function — Converts a value to its string representation.
  • 7Boolean() Function — Converts a value to true or false based on its 'truthiness' or 'falsiness'.
  • 8parseInt() / parseFloat() — Specific functions to convert strings to whole numbers or decimal numbers.
  • 9== vs. === — Use === (strict equality) to avoid unexpected type coercion during comparisons. == performs coercion.
  • 10Falsy Values0, "", null, undefined, NaN, and false are considered 'falsy' in a boolean context.

Learn Data Types

Deepen your knowledge of all JavaScript's built-in data types like numbers, strings, and booleans.

Understand Operators

Explore how different JavaScript operators work and how they interact with various data types.

Strict Equality (`===`)

Master the use of strict equality to write safer and more predictable comparison logic.

Error Handling (`NaN`)

Learn how to effectively check for and handle NaN (Not a Number) values in your code.

You've Mastered Type Coercion!

Great job! You now understand how JavaScript changes data types automatically and how to control these changes yourself. This knowledge is a powerful tool for writing robust and bug-free JavaScript programs.

Try it in the Javascript Compiler

Run and experiment with Javascript code right in your browser — no setup needed.

Continue Learning