Skip to main content
Practice Problems

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 trick

Falsy Values in JavaScript

There are exactly 8 falsy values:

ValueType
falseBoolean
0Number
-0Number
0nBigInt
""String (empty)
nullnull
undefinedundefined
NaNNumber

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; // true

Common 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; // false

Important:

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 ready
Premium

A concise answer to help you respond confidently on this topic during an interview.

Finished reading?
Practice Problems