Type coercion in JavaScript (implicit vs explicit)
What is Type Coercion?
Type coercion is the automatic or manual conversion of a value from one data type to another. JavaScript is a weakly typed language, so it frequently performs type conversions behind the scenes.
Explicit Coercion (Type Casting)
When you intentionally convert a type using built-in functions:
To String
javascript
String(123); // "123"
String(true); // "true"
String(null); // "null"
String(undefined); // "undefined"
(123).toString(); // "123"To Number
javascript
Number("123"); // 123
Number("abc"); // NaN
Number(true); // 1
Number(false); // 0
Number(null); // 0
Number(undefined); // NaN
Number(""); // 0
parseInt("42px"); // 42
parseFloat("3.14"); // 3.14
+"42"; // 42 (unary plus)To Boolean
javascript
Boolean(0); // false
Boolean(""); // false
Boolean(null); // false
Boolean(undefined); // false
Boolean(NaN); // false
Boolean(1); // true
Boolean("hello"); // true
Boolean({}); // true
Boolean([]); // true
!!value; // double NOT trickFalsy Values in JavaScript
There are exactly 8 falsy values:
| Value | Type |
|---|---|
false | Boolean |
0 | Number |
-0 | Number |
0n | BigInt |
"" | String (empty) |
null | null |
undefined | undefined |
NaN | Number |
Everything else is truthy, including [], {}, "0", "false".
Implicit Coercion
When JavaScript automatically converts types during operations:
String Concatenation (+)
javascript
"5" + 3; // "53" (number → string)
"5" + true; // "5true"
"5" + null; // "5null"
"5" + {}; // "5[object Object]"Numeric Context (-, *, /, %)
javascript
"5" - 3; // 2 (string → number)
"5" * 2; // 10
"5" / "2"; // 2.5
true + 1; // 2
false + 1; // 1
null + 5; // 5 (null → 0)Comparison Coercion
javascript
"5" == 5; // true (string → number)
null == undefined; // true (special rule)
null == 0; // false (null only equals undefined)
"" == 0; // true
"0" == false; // true
[] == false; // trueCommon Interview Traps
javascript
[] + []; // "" (empty string)
[] + {}; // "[object Object]"
{} + []; // 0 (block + unary plus)
true + true; // 2
"2" + "2" - "2"; // 20 ("22" - "2" = 20)
null == undefined; // true
null === undefined; // false
NaN === NaN; // falseImportant:
Always use strict equality (===) to avoid unexpected coercion. When you need type conversion, do it explicitly with Number(), String(), or Boolean() for clarity.
Short Answer
Interview readyPremium
A concise answer to help you respond confidently on this topic during an interview.