×

javascript · level 3 · unit 7 · lesson 1

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. nailed it

Tap a green word if you get lost.

meet it

Fast code does fewer steps, so count them.

Speed is rarely about clever tricks. It is about how many steps your code takes, and how that number grows as the data grows. That growth is called . A loop inside a loop over 1,000 items can mean a million steps.

includes on an array checks items one by one, so every in a big array is slow. A is built for this: set.has(value) jumps straight to the answer. A Set also drops repeats, so new Set(list) removes duplicates.

const banned = ["spam", "scam", "junk"];
const words = ["hi", "spam", "hello", "junk", "spam"];
let steps = 0;
for (const word of words) {
  for (const bad of banned) {
    steps++;
    if (word === bad) { break; }
  }
}
console.log(`Nested loops: ${steps} steps`);
const bannedSet = new Set(banned);
const flagged = words.filter((word) => bannedSet.has(word));
console.log(`Set: ${words.length} lookups, flagged ${flagged.length}`);
console.log([...new Set(words)]);

Spread a Set into an array, like [...new Set(words)], to see what is inside it.