arrays

MethodAddsRemovesEndStart
pushyesnoyesno
popnoyesyesno
unshiftyesnonoyes
shiftnoyesnoyes

That table is the quick reference The method names are easy to mix up under pressure

Mutation

const ports = [22, 80, 443];
ports.push(8080);
ports.pop();
ports.shift();

push and unshift return the new length pop and shift return the removed value

Iteration

for (const p of ports) {
  console.log(p);
}

Use for...of for values Use for...in for keys and accept that it walks the prototype chain too

Transform

[1, 2, 3].map((n) => n * 2);
[1, 2, 3].filter((n) => n > 1);
[1, 2, 3].reduce((a, b) => a + b, 0);

Results:

[2, 4, 6]
[2, 3]
6

map transforms filter selects reduce collapses Always pass an initial value to reduce on an array that might be empty

Next

Unique values and keyed data in 06 sets and maps

Posted