0
Challenge · 15Just Enough JavaScript

Map and Set: your hash tools

JavaScriptused in ~100% of apps

This is the lesson that turns slow solutions into fast ones. More problems are solved by remembering what you have already seen than by any other single idea in this course.

Core idea. A Set answers "have I seen this?" instantly, however many things it holds. A Map does the same but stores a value alongside each key. Both keep the type of the key, which objects cannot do.
Playground, this isn't a screenshot
array. Reads every item
seen.includes(x)

// walks the whole list.
// inside a loop, the work
// multiplies.
Set. Knows instantly
seen.has(x)

// same instant at any size.
// inside a loop, the work
// just adds up.
and Map keeps the type of the key
const m = new Map();
m.set(1, "number one");
m.set("1", "text one");
console.log(m.size);   // 2  - kept apart

const o = {};
o[1] = "number one";
o["1"] = "text one";
console.log(Object.keys(o).length);   // 1  - collided
↑ play a little first, then dig in