javascript · level 3 · unit 7 · lesson 1
- meet it
- guess first
- your turn
- fix it
- 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.
guess first
Visitors with repeats. What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
const visits = ["ana", "bo", "ana", "cy", "bo", "ana"];
const unique = new Set(visits);
unique.add("di");
unique.add("ana");
console.log(unique.size, unique.has("bo"), unique.has("zed"));
console.log(unique);
your turn
Your turn. Check the fruit stock fast.
Add any fruit to the middle of the order, then fill in the Set method that checks whether a value is inside.
fix it
The door list crashes. Can you fix it?
membersis a Set, not an array. Does a Set have anincludesmethod?- Sets have their own names for things:
hasinstead ofincludes,sizeinstead oflength. - On line 5, change
members.includes(name)tomembers.has(name), then press run.
nailed it
you can make code do less work. :D
- Count steps: nested loops multiply the work.
- A Set answers
hasquickly and drops duplicates. - Sets use
hasandsize, notincludesandlength.
new words in your collection
- scaling
- lookup
- Set
This lesson isn’t saved. A free account remembers every lesson you finish.