JavaScript, Refreshed
Values, types & coercion
Lesson 1 of 5
What you'll learn
- Tell primitives apart from objects, and read them with
typeof - Know when
==coerces and why===is the safer default - Predict what JavaScript treats as truthy or falsy
JavaScript has a small set of primitive types — string, number, boolean, null, undefined, symbol, bigint — plus objects (which includes arrays and functions). Primitives are immutable values; objects are references you can mutate. The typeof operator is your quickest probe, with two famous quirks: typeof null is "object" and a function reports as "function".
typeof "hi"; // "string"
typeof 42; // "number"
typeof true; // "boolean"
typeof undefined; // "undefined"
typeof null; // "object" (a historical bug, never fixed)
typeof [1, 2, 3]; // "object"
typeof function(){};// "function"
Coercion: == vs ===
The loose == operator coerces its operands to a common type before comparing, which produces surprises like 0 == "" being true. The strict === operator compares type and value with no conversion. Reach for === by default; you almost never want the guessing game == plays.
0 == ""; // true — both coerced toward a number
0 === ""; // false — different types, no conversion
1 == "1"; // true
1 === "1"; // false
null == undefined; // true (special case)
Truthy and falsy
In a boolean context, every value is either truthy or falsy. The falsy values are a short, memorizable list: false, 0, -0, 0n, "", null, undefined, and NaN. Everything else — including "0", [], and {} — is truthy.
Empty array is truthy
if ([]) runs the if branch, because an array is an object and objects are always truthy. To check for "has items," test arr.length instead of the array itself.
The challenge prints a few coercion results. Predict each line before you run it, then check yourself.
Guess each value first, then run it. Compare loose vs strict and truthy vs falsy.
Next: how functions capture the variables around them.
Sign in to save your progress across devices.