JavaScript is famously loose with types — it will happily add a number to a string and give you something legal but wrong. Knowing the type rules turns its weirdness into predictability.
JS has 7 primitive types — number, string, boolean, undefined, null, bigint, symbol — plus objects (including arrays and functions). Always compare with === (no type coercion); == converts types first and produces famous surprises.
const n = 42; // number — ints and floats are ONE type const pi = 3.14; // also number const s = "hello"; // string const ok = true; // boolean let notSet; // undefined — declared, no value const empty = null; // null — intentional "nothing" console.log(typeof n); // "number" console.log(typeof empty); // "object" ← famous historical bug!
console.log(5 === "5"); // false — different types, sane console.log(5 == "5"); // true — == coerced the string! console.log(0 == ""); // true (!!) console.log(null == undefined); // true console.log(null === undefined); // false // Rule: === and !== always. No exceptions worth learning.
console.log("5" + 1); // "51" — + prefers strings
console.log("5" - 1); // 4 — - forces numbers
console.log(Number("42")); // 42 — explicit is better
console.log(parseInt("42px")); // 42 — reads leading digits
console.log(Number("abc")); // NaN
console.log(NaN === NaN); // false! use Number.isNaN(x)// exactly 6 falsy values: false, 0, "", null, undefined, NaN
if (!"") console.log("empty string is falsy");
if ([]) console.log("empty ARRAY is truthy!"); // gotcha
if ({}) console.log("empty object is truthy too");
const name = userInput || "Guest"; // default-value idiom
const safe = userInput ?? "Guest"; // ?? ignores 0 and ""undefined means 'no value was ever assigned' (JavaScript's doing); null means 'intentionally empty' (the programmer's doing).
It's a bug from JavaScript's first version in 1995, kept forever for backward compatibility.
Practically never. Some style guides allow x == null to catch both null and undefined, but x === null || x === undefined is clearer.
Not-a-Number — the result of failed numeric operations like Number("abc"). It's the only value not equal to itself; detect it with Number.isNaN().