JavaScript is relaxed about types. Ask it to subtract a string from a number and it quietly turns the string into a number; ask it to add them and it turns the number into a string instead. This automatic type conversion (also called coercion) explains strange results such as "5" + 3 giving "53", and it is the reason JavaScript has two equality operators. This lesson shows how conversion works, which values count as true or false, and why you should almost always use ===.
In this lesson you will learn
- Converting explicitly with
Number,parseInt,StringandBoolean - How implicit conversion works with
+and other operators - The falsy values and everything that is truthy
- Why
NaNis never equal to itself - The difference between
==,===andObject.is
You should know data types and operators.
Explicit and Implicit Conversion
"use strict";
// Explicit conversion: say what you want
console.log(Number("42"), Number(" 7 "), Number(""), Number("12px"), Number(true), Number(null), Number(undefined));
console.log(parseInt("12px"), parseFloat("3.75 kg"), parseInt("0x1F"), parseInt("101", 2));
console.log(String(99), (255).toString(16), String(null), String([1, 2]));
console.log(Boolean(0), Boolean(""), Boolean("0"), Boolean([]), Boolean({}));
// Implicit conversion: JavaScript guesses
console.log("5" + 3, "5" - 3, "5" * "2", "10" / 4, true + 1, [] + [], "3" + 4 + 5, 3 + 4 + "5");
// The six falsy values (plus 0n); everything else is truthy
const values = [0, -0, "", null, undefined, NaN, "false", " ", [], {}];
console.log(values.map(v => (v ? "T" : "F")).join(" "));
// NaN is not equal to anything, even itself
const x = Number("abc");
console.log(x === NaN, Number.isNaN(x), isNaN("abc"), Number.isNaN("abc"));
Output
42 7 0 NaN 1 0 NaN
12 3.75 31 5
99 ff null 1,2
false false true true true
53 2 10 2.5 2 345 75
F F F F F F T T T T
false true true false
Number()converts a whole value: spaces around a number are ignored, an empty string becomes 0, and anything else that is not a number becomesNaN(“not a number”).parseIntandparseFloatread digits from the start and stop at the first character they do not understand, so"12px"gives 12. The second argument ofparseIntis the base:parseInt("101", 2)reads binary.String()and.toString()convert to text;(255).toString(16)gives hexadecimal.- With
+, if either side is a string, the other side is converted to a string and the two are joined:"5" + 3is"53". The other arithmetic operators convert to numbers:"5" - 3is 2.[] + []gives an empty string, shown as the extra gap in the output. - Expressions run left to right:
"3" + 4 + 5is"345", but3 + 4 + "5"adds first and gives"75". - Only a few values are falsy:
0,-0,"",null,undefined,NaN(and0n). Everything else is truthy, including"false", a space, an empty array and an empty object. NaN === NaNisfalse. Test withNumber.isNaN(). The older globalisNaN()converts its argument first, so it returnstruefor any non-numeric string.
== vs === vs Object.is
"use strict";
// == converts types before comparing; === does not
const pairs = [
[0, "0"], [0, ""], ["", "0"], [null, undefined], [null, 0],
[false, "0"], [1, true], [NaN, NaN], [[1], 1],
];
console.log("a".padEnd(12), "b".padEnd(12), "==", " ===");
for (const [a, b] of pairs) {
const show = v => (typeof v === "string" ? `"${v}"` : Array.isArray(v) ? `[${v}]` : String(v));
console.log(show(a).padEnd(12), show(b).padEnd(12), String(a == b).padEnd(5), a === b);
}
// Object.is is like === but handles NaN and -0 correctly
console.log(Object.is(NaN, NaN), Object.is(0, -0), 0 === -0);
// Objects are compared by reference, not by content
const p = { x: 1 }, q = { x: 1 }, r = p;
console.log(p === q, p === r, JSON.stringify(p) === JSON.stringify(q));
// Safe user-input check: convert first, then compare strictly
const input = "18";
const age = Number(input);
console.log(Number.isInteger(age) && age >= 18 ? "adult" : "not adult");
Output
a b == ===
0 "0" true false
0 "" true false
"" "0" false false
null undefined true false
null 0 false false
false "0" true false
1 true true false
NaN NaN false false
[1] 1 true false
true false true
false true true
adult
===(strict equality) is true only when both the type and the value match. Every pair in the table exceptNaNandNaNhas different types, so===is false;NaNis never equal to anything.==(loose equality) converts types first, with rules that are hard to remember:0 == ""and0 == "0"are true, yet"" == "0"is false. That breaks the normal logic that if a equals b and a equals c, then b equals c.- The one widely used
==case isvalue == null, which is true for bothnullandundefinedand nothing else. Many teams still prefer writingvalue === null || value === undefined, or using??. Object.isis like===except that it treatsNaNas equal to itself and tells0and-0apart.- Objects and arrays are compared by reference: two objects with the same content are still different objects. Only a variable pointing at the same object is equal.
- For user input, convert explicitly with
Number(), check the result, and then compare strictly.
Conversion Cheat Sheet
| Value | Number(value) | String(value) | Boolean(value) |
|---|---|---|---|
"" | 0 | "" | false |
"42" | 42 | "42" | true |
"abc" | NaN | "abc" | true |
null | 0 | "null" | false |
undefined | NaN | "undefined" | false |
true | 1 | "true" | true |
[] | 0 | "" | true |
[5] | 5 | "5" | true |
Common Mistakes
- Adding numbers read from inputs:
input.valueis always a string, soa.value + b.valuejoins text. Convert withNumber()first. - Checking
if (count)when 0 is a valid value; 0 is falsy. Compare explicitly, or use??for defaults. - Testing for NaN with
===. - Comparing arrays with
===to check if they hold the same items.
Practice Exercises
Exercise 1. Predict the results: "10" * "2", "10" + 2 - 1, true + true.
Show answer
20 (both converted to numbers), 101 ("102" - 1), and 2 (each true becomes 1).
Exercise 2. Write toNumberOrNull(text) that returns a number for valid numeric text and null otherwise, treating an empty string as invalid.
Show answer
function toNumberOrNull(text) {
if (text.trim() === "") return null;
const n = Number(text);
return Number.isFinite(n) ? n : null;
}
Frequently Asked Questions
Should I ever use == in JavaScript?
Most style guides say to use === everywhere. The only common exception is x == null to catch both null and undefined, and even that is a matter of team preference.
What is the difference between Number() and parseInt()?
Number() requires the whole string to be a number and returns NaN otherwise; it also handles decimals. parseInt() reads whole-number digits from the start and ignores the rest, which suits values like "20px" but can hide mistakes.
Summary
+with a string joins text; other operators convert to numbers.- Learn the falsy values; everything else is truthy.
- Use
Number.isNaN, not=== NaN. - Use
===;==applies confusing conversions.
