02 / 20 · Day 1
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

js declarations.js
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

TypeExampletypeof
undefinedundefined"undefined"
nullnull"object" (historical bug)
booleantrue / false"boolean"
number42, 3.14, NaN"number"
bigint10n"bigint"
string"hi""string"
symbolSymbol("k")"symbol"
object{}, [], functions"object" / "function"

3 · Truthy and falsy

js truthy.js
// 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 truthy
The 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

js coercion.js
// + 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);           // false

5 · Common mistakes

  • const doesn't deep-freeze. const x = [1]; x.push(2); works.
  • Number precision. 0.1 + 0.2 === 0.3 is false. 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. Use parseInt(s, 10) or Number(s).

6 · When it clicks

  • const is your default reach.
  • You predict typeof and coercion results without running them.
  • You see var in legacy code and know what footguns to watch for.
Found this useful?