Day 1 · Concept 02
let, const, types & coercion
Never var. const by default. let when you reassign. Seven primitive types plus objects. The truthy/falsy table catches everyone — learn it once.
1 · The three keywords
var oldStyle = 1; // function-scoped, hoisted, avoid
let canChange = 2; // block-scoped, can reassign
const fixed = 3; // block-scoped, can't reassign
canChange = 20; // OK
// fixed = 30; // TypeError: Assignment to constant variable
const arr = [1, 2];
arr.push(3); // OK — const only blocks reassignment, not mutation
console.log(arr); // [1, 2, 3]The rule: const first; let if you reassign; never var in new code.
2 · The eight types
| Type | Example | typeof |
|---|---|---|
| undefined | undefined | "undefined" |
| null | null | "object" (historical bug) |
| boolean | true / false | "boolean" |
| number | 42, 3.14, NaN | "number" |
| bigint | 10n | "bigint" |
| string | "hi" | "string" |
| symbol | Symbol("k") | "symbol" |
| object | {}, [], functions | "object" / "function" |
3 · Truthy and falsy
// Falsy values — the whole list
const falsy = [false, 0, -0, '', null, undefined, NaN];
for (const v of falsy) {
if (!v) console.log(JSON.stringify(v), 'is falsy');
}
// Everything else is truthy — including:
console.log(!![]); // true — empty array is truthy
console.log(!!{}); // true — empty object is truthy
console.log(!!"false"); // true — the string "false" is truthyThe non-obvious traps. Empty array
[] is truthy; empty
object {} is truthy; the string "false" is truthy
(it's a non-empty string).4 · Coercion — when types meet
// + with a string concatenates
console.log(1 + "2"); // "12"
console.log("a" + 1 + 2); // "a12"
console.log(1 + 2 + "a"); // "3a"
// Other operators coerce to number
console.log("5" - 1); // 4
console.log("5" * "2"); // 10
// Boolean context coerces with !!
console.log(!!"hi"); // true
console.log(!!0); // false5 · Common mistakes
constdoesn't deep-freeze.const x = [1]; x.push(2);works.- Number precision.
0.1 + 0.2 === 0.3isfalse. Use integers for money or a decimal library. - typeof null === "object". A 1995 bug, preserved. Test with
x === null. - parseInt without radix. Old gotcha.
parseInt("08")used to be 0 in older engines. UseparseInt(s, 10)orNumber(s).
6 · When it clicks
constis your default reach.- You predict
typeofand coercion results without running them. - You see
varin legacy code and know what footguns to watch for.
Found this useful?