Type Coercion (== vs ===, truthy & falsy)
Published by Brayan K
JavaScript has a habit of quietly converting values between types. It's why "5" + 1 is "51" but "5" - 1 is 4. These "WAT" moments confuse beginners, but once you understand the rules they become completely predictable.
Part of the free JavaScript course at LearnCodingFast — hands-on lessons with examples you run in your browser, plus practice exercises and a quick quiz.
Inspect the type before trusting the printed value
A numeric string and a number can look alike in a console while behaving differently in a calculation. Coercion means converting a value to another type. Explicit conversion names the operation in your code; implicit conversion happens because an operator or language context requires it.
const entered = "6";
const quantity = 6;
console.log(entered, typeof entered);
console.log(quantity, typeof quantity);
console.log(entered + 2);
console.log(quantity + 2);
// ✅ Expected output:
// 6 string
// 6 number
// 62
// 8When a total unexpectedly grows by another digit, inspect the operands and their types before changing the arithmetic. Converting the input once at a clear boundary is easier to reason about than hoping each later operator will interpret it the same way.
const entered = "6";
console.log(Number(entered) + 2);
console.log(Number(entered + 2));
console.log(typeof Number(entered));
// ✅ Expected output:
// 8
// 62
// numberThe plus sign depends on the values at that step
For primitive operands, a string on either side of binary + selects concatenation. Without a string, ordinary number-compatible operands undergo numeric addition; BigInt arithmetic has separate rules. Several additions associate from left to right, so an earlier result becomes the next operand.
console.log(2 + 3 + "4");
console.log("2" + 3 + 4);
console.log(2 + (3 + "4"));
console.log("total: " + (2 + 3));
// ✅ Expected output:
// 54
// 234
// 234
// total: 5Subtraction does not provide string concatenation. A numeric string can therefore appear to work with subtraction and then fail your intention when you change the operator to addition. That difference is a reason to convert deliberately, not a reason to use subtraction as a parser.
console.log("8" - 3);
console.log("8" + 3);
console.log(true + 2);
console.log(Number("eight"));
// ✅ Expected output:
// 5
// 83
// 3
// NaNObjects are converted to primitives before the addition decision, and custom conversion hooks can affect that process. Symbols & Well-Known Symbols owns those hooks; the calculations here use primitive operands so each conversion is visible.
Boolean conversion does not read the meaning of text
A condition needs truthiness, not a comparison with the boolean true. The falsy primitive values are false, null, undefined, NaN, positive and negative zero, BigInt zero, and the empty string. Other primitive values are truthy, including a nonempty string that spells "false" or "0".
console.log(Boolean(false), Boolean(null), Boolean(undefined));
console.log(Boolean(NaN), Boolean(0), Boolean(-0));
console.log(Boolean(0n), Boolean(""));
console.log(Boolean("false"), Boolean("0"), Boolean(" "));
console.log(Boolean(-1), Boolean(Infinity));
// ✅ Expected output:
// false false false
// false false false
// false false
// true true true
// true trueOrdinary objects and arrays are truthy even when empty. Browsers retain the unusual legacy exception document.all, so a universal claim that every object is truthy would be too broad. That legacy API is not a pattern to use for application decisions.
const entries = [];
const settings = {};
console.log(Boolean(entries));
console.log(Boolean(settings));
console.log(entries.length === 0);
// ✅ Expected output:
// true
// true
// trueUse an explicit property such as array length when you mean "has items". The structure and operations of these containers belong to Arrays and Objects.
const setting = "false";
console.log(Boolean(setting));
console.log(setting === "true");
if (setting === "true") {
console.log("enabled");
} else {
console.log("disabled");
}
// ✅ Expected output:
// true
// false
// disabledThe final comparison implements a contract that only the exact text "true" enables this setting. It does not validate every other spelling. If misspellings must be rejected rather than disabled, add that as a separate validation rule.
Strict equality keeps type differences visible
Strict equality does not convert a numeric string to a number. Loose equality may perform conversion according to the operand types. A boolean in a loose comparison is converted numerically; this is different from asking whether the other operand is truthy.
console.log("6" === 6);
console.log("6" == 6);
console.log(Boolean("0"));
console.log("0" == false);
console.log("0" === false);
// ✅ Expected output:
// false
// true
// true
// true
// falseThese expressions ask different questions. Do not use value == true as a substitute for a truthiness test. Prefer explicit conversion followed by strict comparison when matching data from sources with different types.
console.log(0 == "");
console.log(0 == "0");
console.log("" == "0");
// ✅ Expected output:
// true
// true
// falseIn the first two comparisons a string is compared with a number and converted. In the last, both operands are strings and their text is compared. The intermediate value does not make the two strings equivalent to each other.
console.log(null == undefined);
console.log(null === undefined);
console.log(null == 0);
console.log(undefined == 0);
// ✅ Expected output:
// true
// false
// false
// falseLoose equality has a special null/undefined match; it does not simply convert every value to a number. For a deliberate nullish test, value === null || value === undefined states both accepted values. Optional Chaining & Nullish Coalescing owns defaults and property access for missing values.
Strict comparison is not deep comparison or numeric validation
Two separately created objects can contain the same fields and still be different objects. Strict equality checks their identity. This is a short boundary reminder; Arrays and Objects owns object references and updates.
const first = { quantity: 2 };
const alias = first;
const second = { quantity: 2 };
console.log(first === alias);
console.log(first === second);
console.log(first.quantity === second.quantity);
// ✅ Expected output:
// true
// false
// trueStrict equality also does not make invalid numeric results valid. NaN fails equality even with itself. Numbers & Math owns NaN detection, finite-number checks and safe integer limits.
const result = Number("not numeric");
console.log(result === NaN);
console.log(result == NaN);
console.log(Number.isNaN(result));
// ✅ Expected output:
// false
// false
// trueConversion can fail instead of producing a useful value
An explicit conversion is a request, not a guarantee of success. Number cannot convert a Symbol to a numeric value. The exact exception below makes that boundary visible; Symbols & Well-Known Symbols owns what symbols represent and where to use them.
const identifier = Symbol("entry");
console.log(Number(identifier));
// ✅ Expected error:
// TypeError: Cannot convert a Symbol value to a numberBigInt and Number operands cannot be mixed directly in arithmetic. BigInt & Number Precision owns choosing a numeric representation and the precision risks of converting between them.
console.log(2n + 3);
// ✅ Expected error:
// TypeError: Cannot mix BigInt and other types, use explicit conversionsTreat an unexpected type as an input-contract problem. Converting every value you receive can hide missing fields, empty input and mistakes in a caller, even when the conversion itself does not throw.
Complete the conversion before comparing quantities
The expected quantity is a number, while the entered quantity is text. Fill the blanks to convert the text and compare the numeric result strictly. The example uses a fixed valid input; checking whether other inputs should be accepted is a separate step.
const entered = " 5 ";
const expected = 5;
const quantity = ___; // 👉 replace ___ with Number(entered)
const matches = ___; // 👉 replace ___ with quantity === expected
console.log(quantity);
console.log(matches);
console.log(typeof quantity);
// ✅ Expected output:
// 5
// true
// numberAccept a quantity without silently treating blank text as zero
Write quantityFromText so it accepts a string, rejects whitespace-only input, converts with Number, and returns the result only if it is a safe positive integer. Return null for rejected input. This contract accepts the numeric string forms supported by Number; it is not restricted to decimal digit characters. Test valid text, leading zeros, blank input, fractional text, an invalid word and a non-string input.
function quantityFromText(raw) {
if (typeof raw !== "string" || raw.trim() === "") {
return null;
}
const quantity = Number(raw);
if (!Number.isSafeInteger(quantity) || quantity < 1) {
return null;
}
return quantity;
}
console.log(quantityFromText("4"));
console.log(quantityFromText("04"));
console.log(quantityFromText(" "));
console.log(quantityFromText("4.5"));
console.log(quantityFromText("four"));
console.log(quantityFromText(4));
// ✅ Expected output:
// 4
// 4
// null
// null
// null
// nullEach guard answers a different question. The type guard protects the trim call; the presence check rejects blank text; the numeric checks enforce the accepted quantity range. A valid conversion alone cannot decide whether the value is suitable for the application.
References: MDN documents addition, falsy values, and equality conversion.
Practice quiz
What does this complete program print? console.log(1 + 2 + "3");
- 33
- 123
- 6
- 15
Answer: 33. The first addition is numeric; its result is then joined to the string.
What does this complete program print? console.log(Number("5") + 1); console.log(Number("5" + 1));
- 51 51
- 6 51
- 6 6
- 51 6
Answer: 6 51. Converting before addition and converting after concatenation operate on different intermediate values.
What does this complete program print? console.log(Boolean("false")); console.log("false" === true);
- false false
- true true
- true false
- false true
Answer: true false. A nonempty string is truthy, but it is not the boolean true under strict equality.
What does this complete program print? console.log("0" == false); console.log(Boolean("0"));
- false true
- true false
- false false
- true true
Answer: true true. Loose equality converts these operands numerically; truthiness considers the nonempty string truthy.
What does this complete program print? console.log(null == undefined); console.log(null == 0);
- true false
- false false
- true true
- false true
Answer: true false. Null and undefined have a special loose-equality match; null is not loosely equal to zero.
What does this complete program print? const value = Number("unknown"); console.log(value === value);
- true
- false
- undefined
- TypeError
Answer: false. The result is NaN, which is unequal to itself even with strict equality.
What does this complete program print? const first = { count: 1 }; const second = { count: 1 }; console.log(first === second);
- true
- 1
- false
- TypeError
Answer: false. Two separately created records have different identities even when their fields match.
What does this complete program print? console.log(Boolean([])); console.log(Boolean(0n));
- false false
- true true
- false true
- true false
Answer: true false. An ordinary empty array is truthy; BigInt zero is a falsy primitive.
Continue this course
- Previous: Conditionals & Operators
- Next: Hoisting — How var and function declarations are 'lifted' — and why let/const aren't
- Quick reference: JavaScript cheat sheet › Variables & Types