functions

Three lines that changed how I write loops:

function makeCounter() {
  let n = 0;
  return () => ++n;
}

The inner function keeps n alive after makeCounter returns That is a closure and it is not magic

Declaration and expression

function sum(a, b) { return a + b; }
const multiply = (a, b) => a * b;

Declarations are hoisted Expressions are not Calling before definition works for one and fails for the other

Scope

let and const are block scoped var is function scoped

for (let i = 0; i < 3; i++) {
  // i exists only here
}
// i is gone

With var, the loop variable leaks past the block That caused the famous “prints three threes” bug

Parameters

Default values, rest parameters, and destructuring all reduce boilerplate Use them when they make the call site clearer

Next

Lists in 05 arrays

Posted