Course contentsShow
← JavaScript
Lesson 274 of 2,7238. Type CoercionFree lesson

What is Type Coercion?

Understanding implicit type conversion and how JavaScript automatically converts values between types.

What is Type Coercion?

You'll learn: What type coercion is and how JavaScript automatically converts values between different types.

What is Type Coercion?

Type coercion is JavaScript's way of automatically converting a value from one type to another when needed. Instead of throwing an error when you try to use incompatible types together, JavaScript often tries to be "helpful" by converting values behind the scenes.

Think of it like a translator at a multilingual meeting. When someone speaks French and another speaks Spanish, the translator converts the message so both can understand—even if something gets slightly lost in translation.

Why Does Coercion Happen?

JavaScript is a loosely typed language. When you perform operations that expect a certain type (like adding numbers or checking if something is true), JavaScript will try to convert values to make the operation work.

For example, when you use + with a number and a string, JavaScript coerces the number into a string:

5 + "10"  // "510" (number 5 becomes string "5")

Similarly, when you use comparison operators, JavaScript may convert types to make the comparison possible:

"5" == 5  // true (string "5" coerced to number 5)

Implicit vs Explicit

Implicit coercion happens automatically—JavaScript does it for you without asking. Explicit coercion is when you deliberately convert types using constructors like Number(), String(), or Boolean().

You've already seen coercion in action with truthy/falsy values, double negation (!!), and the behavior of == versus ===.

Key Takeaway: Type coercion is JavaScript's automatic conversion of values between types, which can be helpful but sometimes leads to unexpected results if you don't understand when and how it happens.