JavaScript Type Coercion
Understand how JavaScript converts types automatically and avoid common equality and comparison bugs.
TL;DR
- 01Compare values with strict
===to prevent implicit coercion. - 02Identify truthy and falsy variables inside conditional blocks.
- 03Convert data types explicitly using
Number,String, orBoolean.
Tips
- 01Always use strict comparison operators to prevent JavaScript from silently converting types behind your back.
- 02Convert numeric values explicitly using the standard
Number()constructor to ensure clean mathematical operations.
Warnings
- 01Remember that empty arrays and objects evaluate as truthy values inside conditional expressions.
- 02Adding numbers and strings triggers implicit string concatenation instead of expected arithmetic addition.
Loose vs Strict Equality
Strict equalityCompares values and types directly with zero implicit conversion.
console.log(1 === 1); // true
console.log(1 === "1"); // falseLoose equalityConverts operand types automatically before comparing values.
console.log(1 == "1"); // true
console.log(0 == false); // trueNullish checksUses loose equality to check for both null and undefined variables at once.
function isMissing(v) {
return v == null;
}NaN comparisonUses Number.isNaN because NaN never equals itself under comparison.
console.log(NaN === NaN); // false
console.log(Number.isNaN(NaN)); // trueTruthy and Falsy Values
Falsy listLists all eight falsy values which evaluate to false in boolean contexts.
const falsy = [
false, 0, -0, 0n, "", null, undefined, NaN
];Empty collectionsVerifies that empty arrays and objects evaluate as truthy.
if ([]) console.log("runs"); // true
if ({}) console.log("runs"); // trueLength verificationChecks array lengths explicitly rather than relying on list truthiness.
const list = [];
if (list.length === 0) {
console.log("empty");
}Double negationCoerces values into strict booleans using two logical NOT operators.
console.log(!!"text"); // true
console.log(!!0); // falseImplicit Conversion
String concatenationConverts numbers to strings when executing addition with string operands.
console.log(1 + "1"); // "11"
console.log("a" + 1); // "a1"Numeric coercionCoerces string values to numbers when using subtraction or division operators.
console.log("5" - 2); // 3
console.log("5" * "2"); // 10Relational operatorsConverts strings to numbers during numeric comparison evaluation checks.
console.log("10" > 5); // trueTemplate interpolationCoerces embedded variables to strings inside template literal strings.
const age = 30;
console.log(`Age: ${age}`); // "Age: 30"Explicit Conversion
Boolean()Converts any variable type into a true or false boolean value.
Boolean(""); // false
Boolean("0"); // true (non-empty)Number()Parses strings or values into numbers, returning NaN on invalid characters.
Number("42"); // 42
Number("abc"); // NaNString()Converts numbers, null, or undefined values into matching literal strings.
String(42); // "42"
String(null); // "null"parseInt()Parses numbers from strings with trailing non-numeric characters.
parseInt("42px", 10); // 42
Number("42px"); // NaNIn Practice
Converts raw form inputs explicitly to process user ages, avoiding implicit coercion bugs and checking for NaN failures.
- 01Convert the input value to a string explicitly and trim surrounding whitespace.
- 02Verify that the cleaned string is not empty before parsing.
- 03Coerce the string to a number using the explicit
Numberconstructor. - 04Check if the resulting number is
NaNto detect invalid input characters. - 05Return the verified number or a fallback null value.
function processAgeInput(inputValue) {
const cleanString = String(inputValue).trim();
if (!cleanString) return null;
const parsedNumber = Number(cleanString);
if (Number.isNaN(parsedNumber)) return null;
return parsedNumber;
}FAQ
Loose equality == converts operand types before comparison. Strict equality === compares values and types directly. Strict equality is recommended to avoid unpredictable conversion bugs.
Loose equality coerces both operands toward numbers. The empty array converts to an empty string, then to zero. The boolean false also becomes zero. Since both evaluate to zero, they match.
Falsy values are false, 0, -0, 0n, empty strings, null, undefined, and NaN. All other values are truthy. This includes empty arrays, empty objects, and the string '0'.
The plus operator triggers string concatenation if either operand is a string. JavaScript converts the number to a string and links them. Use subtraction or explicit conversion to do math.
Do not use equality operators, because NaN never equals anything, including itself. Use the Number.isNaN() method instead. This method correctly determines if a value is not a number.