Back to JavaScript Notes
Topic #102

JS Type Coercion

Type coercion converts values implicitly during operations, famously with == and +. Mastering its rules eliminates a class of bugs.

Type Coercion

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

Type coercion happens when you perform an operation on different data types, and the JavaScript engine tries to make them "fit" together.

Example

let result1 = ('5' + '2'); // = 52

let result2 = ('5' - '2'); // = 3

Coercion is implicit (handled automatically by the engine), while type conversion is explicit (you manually use functions like Number() or String()).

Because JavaScript is weakly typed, it doesn't throw errors when types don't match; it just tries to coerce them.


String Coercion (+)

If any part of a + operation is a string, JavaScript converts everything to strings and concatenates them.

let x = "5" + 2 // x = "52"

Numeric Coercion

Other arithmetic operators (-, *, /, %) and the unary plus (+x) force values into numbers.

let x = "5" - 2 // x = 3

Boolean Coercion

Values are coerced to booleans in logical contexts like if statements or using the double-NOT operator (!!).

Falsy values: 0, "", null, undefined, NaN, and false.

Truthy values: Everything else (including empty objects {} and arrays []).


Loose Equality (==)

This operator performs coercion to find a "common type" before comparing.

let x = (5 == "5") // x = true

Best Practices to Avoid Bugs

Use === (Strict Equality): This checks both value and type without coercion, preventing weird results.

Be Explicit: Instead of relying on automatic behavior, use MDN's recommended conversion methods like Number() or String() to make your intent clear.

Watch for NaN

If a string cannot be converted to a valid number, like "abc" - 1), the result is NaN (Not-a-Number).

Want to go beyond the notes?

Join Coding Now Tech Institute's JavaScript course — live mentorship, real projects, and 100% placement support.

Enroll Now — Free Demo Available

JS Type Coercion – FAQs

Quick answers about learning JS Type Coercion in JavaScript.

This free note from Coding Now Tech Institute explains JS Type Coercion in JavaScript — concept, syntax and worked code examples you can copy, run and revise before interviews.
Yes. Every JavaScript topic on Coding Now Tech Institute, including JS Type Coercion, is 100% free with no signup required.
With focused practice, most students grasp JS Type Coercion in 1–3 days from these notes; pairing it with Coding Now Tech Institute's mentor-led course takes you to job-ready depth faster.
Use the code examples in this note, then ask doubts for free on the Coding Now Tech Institute Community (/community) — expert instructors answer within 24 hours.
Call NowEnroll Now