N javascript cheat sheet: map, filter, reduce, destructuring, spread and rest, async/await and closures - Netscape _ □ ×
Back Forward Home Reload Guides Sign
URL: http://www.nicnonac.com/guides/javascript-cheat-sheet/
☷ javascript cheat sheet: map, filter, reduce, destructuring, spread and rest, async/await and closures - nicnonac guides _□×

← back to guides

javascript cheat sheet: map, filter, reduce, destructuring, spread and rest, async/await and closures

Stacks · 12 min read · posted Nov 30, 2026, 3:30 pm

Most of the JavaScript you read and write every day leans on the same five things: map, filter and reduce, destructuring, spread and rest, async and await, and closures. Once they click, other people's code gets a lot easier to follow.

This is the cheat sheet from the reel. It covers the five things in it. For each one you get when you'd reach for it, the syntax with a small example and what it prints, the mistake that usually bites, and something to practise on.

Every block here was run with Node.js 26.8.1 on macOS, saved as a file and run with node, and the output under it is what Node printed. The first example in each section is the code from the reel. A browser console shows the same values, but formats arrays and objects its own way. The practice problems are all public on LeetCode, in its JavaScript set.

the quick lookup

i want to write
change every item nums.map((n) => n * 2)
keep only some items nums.filter((n) => n > 0)
boil an array down to one value nums.reduce((sum, n) => sum + n, 0)
the first item that matches users.find((u) => u.id === 7)
is any / is every item ... nums.some(...), nums.every(...)
pull fields out of an object const { name, age } = user
rename while pulling out const { name: userName } = user
a default for a missing field const { role = "dev" } = user
the first two items of an array const [a, b] = arr
swap two variables [a, b] = [b, a]
copy an array or an object [...arr], { ...obj }
merge objects, later keys win { ...defaults, ...options }
everything except one field const { password, ...rest } = user
pass an array as separate arguments Math.max(...nums)
take any number of arguments function sum(...nums) {}
wait for a promise const data = await load()
catch a failed await try { await load() } catch (err) {}
run several at once and wait for all await Promise.all([a(), b()])
keep state between calls, private a function that returns a function

what each one gives you back

tool what you get
map a new array, same length, every item changed
filter a new array, the same items, only the ones that pass
reduce one value: a number, a string, an object, anything
destructuring new variables, pulled out by key or by position
spread a new array or object, copied and merged. the original is untouched
rest an array (or object) of whatever is left over
async / await a promise. await pauses the function, not the program
closure a function that still has the variables from where it was made

1. map, filter, reduce

When you reach for it. You have an array and you're about to write a for loop that pushes into another array, or adds things up. If every item changes, it's map. If some items drop out, it's filter. If the whole array becomes one value, it's reduce.

The syntax. Each one takes a function and calls it once per item. None of them change the array you call them on.

const nums = [1, 2, 3, 4, 5];

const doubled = nums
  .map((n) => n * 2);
const evens = nums
  .filter((n) => n % 2 === 0);
const total = nums
  .reduce((s, n) => s + n, 0);

console.log(doubled);
console.log(evens);
console.log(total);
[ 2, 4, 6, 8, 10 ]
[ 2, 4 ]
15

The 0 at the end of reduce is where the total starts. s is the total so far and n is the next item, so it goes 0, 1, 3, 6, 10, 15.

Other shapes. They chain, because map and filter both hand back arrays. find, some and every are the same idea for one item, or a yes or no.

const orders = [
  { item: "book", price: 12, paid: true },
  { item: "cap", price: 20, paid: false },
  { item: "mug", price: 8, paid: true },
];

const paidTotal = orders
  .filter((o) => o.paid)
  .map((o) => o.price)
  .reduce((sum, p) => sum + p, 0);
console.log(paidTotal);

console.log(orders.find((o) => o.price > 10));
console.log(orders.some((o) => !o.paid));
console.log(orders.every((o) => o.price > 5));
20
{ item: 'book', price: 12, paid: true }
true
true

What bites. Curly brackets on an arrow function. Without them the value is returned for you. With them you have to write return, and if you forget, map fills the array with undefined.

console.log([1, 2].map((n) => n * 2));
console.log([1, 2].map((n) => { n * 2; }));
console.log([1, 2].map((n) => { return n * 2; }));
[ 2, 4 ]
[ undefined, undefined ]
[ 2, 4 ]

The other two: map passes the index as a second argument, which quietly breaks functions that take a second argument too, like parseInt. And reduce with no starting value throws on an empty array.

console.log(["1", "2", "3"].map(parseInt));
console.log(["1", "2", "3"].map(Number));

try {
  [].reduce((sum, n) => sum + n);
} catch (err) {
  console.log(err.message);
}
console.log([].reduce((sum, n) => sum + n, 0));
[ 1, NaN, NaN ]
[ 1, 2, 3 ]
Reduce of empty array with no initial value
0

parseInt("2", 1) reads "2" in base 1, which isn't a number. Always give reduce its starting value.

Practise. These ask you to write map, filter and reduce yourself, which is the quickest way to stop mixing them up.

2. destructuring

When you reach for it. You need two or three fields out of an object: an API response, a config, the props of a React component. Or you want the first few items of an array by position.

The syntax. Curly brackets pull from an object by key. Square brackets pull from an array by position. = gives a default for when the value is missing.

const user = {
  name: "Ana",
  city: "Oslo",
};
const { name, role = "dev" }
  = user;

const rgb = [255, 128, 0];
const [r, g] = rgb;

console.log(name, role, r, g);
Ana dev 255 128

This is the one in the reel. user has no role, so the default is used. r and g are the first two items, and the 0 is left alone.

Other shapes. Rename with a colon, reach into nested objects, destructure a function's argument, swap two variables, and skip an array item with an empty slot.

const res = { status: 200, data: { user: { id: 7, name: "Ana" } } };

const { status: code, data: { user } } = res;
console.log(code, user.name);

function greet({ name, greeting = "hi" }) {
  return `${greeting}, ${name}`;
}
console.log(greet({ name: "Ben" }));

let a = 1;
let b = 2;
[a, b] = [b, a];
console.log(a, b);

const [first, , third] = ["x", "y", "z"];
console.log(first, third);
200 Ana
hi, Ben
2 1
x z

In the nested one, only code and user become variables. data is just the path to get there.

What bites. Destructuring something that isn't there. If the object itself is undefined, it throws. A function that destructures its argument throws the same way when it's called with nothing, so give the whole argument a default of {}. And a default only kicks in for undefined. A null comes straight through.

try {
  const { name } = undefined;
} catch (err) {
  console.log(err.message);
}

function setup({ debug = false } = {}) {
  return debug;
}
console.log(setup());

const { role = "dev" } = { role: null };
console.log(role);
Cannot destructure property 'name' of 'undefined' as it is undefined.
false
null

Practise. There's no LeetCode set for this one, so here are four to do in a file and check with node.

  • Pull id and email out of const account = { id: 3, email: "a@b.co", plan: "free" }, with the email in a variable called contact. (const { id, email: contact } = account;)
  • Get the last two items of ["a", "b", "c"] into y and z without using an index. (const [, y, z] = ["a", "b", "c"];)
  • Write area({ w, h = w }) so that area({ w: 3 }) gives 9 and area({ w: 2, h: 5 }) gives 10. (const area = ({ w, h = w }) => w * h;)
  • const { a: { b } } = {} throws. Why? (a is undefined, and you can't pull b out of undefined. Give it a default: const { a: { b } = {} } = {}.)

3. spread and rest

When you reach for it. You want a copy of an array or object with something added or changed, and the original left alone. That's most state updates in React. Or a function should take any number of arguments.

The syntax. It's the same three dots for both. Where values are going in, like an array, an object or a function call, ... spreads them out. Where names are being given, like function parameters or destructuring, ... gathers what's left into one.

const a = [1, 2];
const b = [...a, 3];
console.log(b);

const p = { x: 1, y: 2 };
const q = { ...p, y: 9 };
console.log(q);

const f = (x, ...rest) => rest;
console.log(f(1, 2, 3));
[ 1, 2, 3 ]
{ x: 1, y: 9 }
[ 2, 3 ]

This is the one in the reel. b is a new array and a is still [1, 2]. In q, the y: 9 comes after ...p, so it wins. In f, the first argument goes to x and the rest are collected into an array.

Other shapes. Spread an array into a function call, drop a field with rest, sum any number of arguments, and turn a string or a Set into an array.

const nums = [5, 1, 8];
console.log(Math.max(...nums));

const { password, ...safe } = { id: 1, name: "Ana", password: "secret" };
console.log(safe);

const sum = (...ns) => ns.reduce((s, n) => s + n, 0);
console.log(sum(1, 2, 3, 4));

console.log([..."hey"]);
console.log([...new Set([1, 1, 2, 3, 3])]);
8
{ id: 1, name: 'Ana' }
10
[ 'h', 'e', 'y' ]
[ 1, 2, 3 ]

What bites. Spread makes a shallow copy. The top level is new, but an array or object inside it is still shared with the original, so changing it through the copy changes the original too. structuredClone copies all the way down.

const user = { name: "Ana", tags: ["admin"] };
const copy = { ...user };
copy.name = "Ben";
copy.tags.push("editor");
console.log(user);

const deep = structuredClone(user);
deep.tags.push("owner");
console.log(user.tags, deep.tags);
{ name: 'Ana', tags: [ 'admin', 'editor' ] }
[ 'admin', 'editor' ] [ 'admin', 'editor', 'owner' ]

The name change stayed in the copy. The tag went into both. The other one is order. Later keys win, so { ...p, y: 9 } and { y: 9, ...p } are different objects:

const p = { x: 1, y: 2 };
console.log({ ...p, y: 9 });
console.log({ y: 9, ...p });
{ x: 1, y: 9 }
{ y: 2, x: 1 }

Put the defaults first and the overrides last. A rest parameter has to be the last one too: (...rest, x) is a syntax error.

Practise.

  • 2703. Return Length of Arguments Passed (Easy)
  • Merge const defaults = { theme: "light", size: 2 } with const options = { size: 4 } so options win. ({ ...defaults, ...options } gives { theme: 'light', size: 4 }.)
  • Add 4 to the end of const list = [1, 2, 3] without changing list. (const longer = [...list, 4];)

4. async / await

When you reach for it. Anything that has to wait: a fetch, a file read, a database query, a timer. They all hand you a promise, and await is how you get the value out of it.

The syntax. Put async in front of a function and you can use await inside it. await pauses that function until the promise settles, then hands you the value. The rest of your program keeps running in the meantime.

const sleep = (ms) =>
  new Promise((ok) =>
    setTimeout(ok, ms));

async function load() {
  console.log("start");
  await sleep(100);
  console.log("loaded");
}

load();
console.log("next");
start
next
loaded

This is the one in the reel. It's written start, loaded, next, but it logs start, next, loaded. load() runs until the await, then pauses. Line 12 runs while it waits, and 100 ms later the promise resolves and load() carries on.

Errors. A promise that fails makes await throw, so it's the ordinary try and catch.

async function load(id) {
  if (id < 0) throw new Error("bad id");
  return { id };
}

async function main() {
  try {
    await load(-1);
  } catch (err) {
    console.log("caught:", err.message);
  }
  console.log(await load(3));
}
main();
caught: bad id
{ id: 3 }

Several at once. Two awaits in a row run one after the other. If the second doesn't need the first, start both and wait for them together with Promise.all.

const sleep = (ms, value) =>
  new Promise((ok) => setTimeout(ok, ms, value));

async function main() {
  let t = Date.now();
  const a = await sleep(100, "a");
  const b = await sleep(100, "b");
  console.log("one by one:", Math.round((Date.now() - t) / 100) * 100, "ms");

  t = Date.now();
  const [c, d] = await Promise.all([sleep(100, "c"), sleep(100, "d")]);
  console.log("together:", Math.round((Date.now() - t) / 100) * 100, "ms");
  console.log(a, b, c, d);
}
main();
one by one: 200 ms
together: 100 ms
a b c d

The times are rounded to the nearest 100 ms, because the exact number changes a little from run to run.

What bites. Forgetting the await. An async function always hands back a promise, even when it returns straight away, so without await you're reading a field off the promise.

async function getUser() {
  return { name: "Ana" };
}

async function main() {
  const u = getUser();
  console.log(u);
  console.log(u.name);
  const v = await getUser();
  console.log(v.name);
}
main();
Promise { { name: 'Ana' } }
undefined
Ana

The other one is forEach with an async function. forEach doesn't wait for the promises it gets back, so the code after it runs first. Use for...of when each step should wait, or Promise.all with map when they can all run at once.

const sleep = (ms) => new Promise((ok) => setTimeout(ok, ms));

async function main() {
  [1, 2].forEach(async (n) => {
    await sleep(50);
    console.log("forEach", n);
  });
  console.log("after forEach");

  await sleep(100);

  for (const n of [1, 2]) {
    await sleep(50);
    console.log("for...of", n);
  }
  console.log("after for...of");
}
main();
after forEach
forEach 1
forEach 2
for...of 1
for...of 2
after for...of

Practise.

5. closures

When you reach for it. A function needs to remember something between calls, and nothing else should be able to touch it: a counter, a function that only runs once, a cache, a click handler that knows which button it belongs to.

The idea. A function keeps the variables from where it was made, even after the outer function has returned. Each call of the outer function makes a fresh set.

function counter() {
  let count = 0;
  return () => {
    count += 1;
    return count;
  };
}

const next = counter();
console.log(next());
console.log(next());
console.log(next());

const other = counter();
console.log(other());
1
2
3
1

This is the one in the reel. counter() has finished by the time next() is called, but next still has its count, and it keeps going up. other was made by a second call, so it has its own count that starts at 0. Nothing outside can read or change either one.

Other shapes. A function that only runs once, which is the closure version of a flag:

function once(fn) {
  let done = false;
  let result;
  return (...args) => {
    if (!done) {
      done = true;
      result = fn(...args);
    }
    return result;
  };
}

const init = once(() => {
  console.log("setting up");
  return 42;
});
console.log(init());
console.log(init());
setting up
42
42

What bites. var in a loop. A var is one variable for the whole function, so every callback shares it, and by the time they run the loop has finished. let makes a new variable for each time round the loop.

for (var i = 0; i < 3; i++) {
  setTimeout(() => console.log("var", i), 0);
}
for (let j = 0; j < 3; j++) {
  setTimeout(() => console.log("let", j), 0);
}
var 3
var 3
var 3
let 0
let 1
let 2

Use let and const, and this one never comes up. The other thing to know is that a closure keeps whatever it holds alive. A long-lived event handler that closes over a big array keeps that array in memory for as long as the handler exists.

Practise.

how to practise with this

One section at a time. Copy the first example into a file, run it with node, then change one thing and guess what it prints before you run it again. Guessing first is what makes it stick.

When you read someone else's code, look for these five. A for loop that pushes into a new array is a map or a filter waiting to happen. Three lines of const x = obj.x is one line of destructuring.

honest limitations

Five things isn't all of JavaScript. this, classes, modules, the event loop in depth and the prototype chain all come up too, and TypeScript adds its own layer on top.

All the output here is from Node.js 26.8.1. Browser consoles show the same values formatted their own way, and error messages are worded differently in Firefox and Safari. Everything used here has been in Node for years, apart from structuredClone, which needs Node 17 or newer.

The async section only covers the part you meet every day. Why next logs before loaded comes down to the event loop and the microtask queue, which is worth reading about once these feel easy.

If you're preparing for interviews too, the coding interview cheat sheet and the data structures cheat sheet cover the problem-solving side.

← all guides

Done nicnonac.com 56.6k