Collect unique words in a Set and count them in a Map.
JavaScript · beginner · 6 min · 14 steps · free
const seen = new Set();
const counts = new Map();
const words = ['red', 'blue', 'red', 'green'];
for (const w of words) {
seen.add(w);
counts.set(w, (counts.get(w) ?? 0) + 1);
}
console.log(seen.size, [...seen]);
console.log(counts.get('red'), counts.has('pink'));seen is created and points to a new Set: [].counts is created and points to a new Map: {}.words is created and points to a new Array: ["red", "blue", "red", "green"].w begins.seen.add("red"): the Set now holds red.counts.get("red") is undefined, so ?? 0 gives 0; the Map stores red → 1.w changes from "red" to "blue". "blue" is added to the end of the Set that seen points to.blue with the value 1 is added to the Map that counts points to.w changes from "red" to "green". "green" is added to the end of the Set that seen points to.green with the value 1 is added to the Map that counts points to.w goes out of scope and disappears. It prints 3 [ 'red', 'blue', 'green' ].2 false.Answer: 2
Answer: undefined
← How this Works · The Event Loop →