Sub topic 1
Why JavaScript Has Keyed Collections
Prerequisites
This chapter assumes you know variables, arrow functions, objects, arrays, for...of loops, the spread operator, and how primitives differ from object references.
The Problem With Plain Objects
Plain objects were long the only way to map keys to values in JavaScript, and they have limits. Object keys must be strings or symbols, so any other key is converted to a string. Inherited properties such as toString can collide with your data. Objects also have no built-in size. ES2015 added Map and Set to fix these problems. A keyed collection is a structure that stores entries by key and keeps them in insertion order.
Map Fundamentals
A Map stores key-value pairs, and any value can be a key, including objects. Because set returns the Map, you can chain calls.
const user = { id: 1 };
const visits = new Map();
visits.set(user, 3).set('total', 10);
console.log(visits.get(user)); // 3
console.log(visits.size); // 2
console.log(visits.has('total')); // true
visits.delete('total');
console.log(visits.size); // 1Set Fundamentals
A Set stores unique values. Adding a value that is already present does nothing.
const roles = new Set(['admin', 'editor']);
roles.add('admin');
console.log(roles.size); // 2
console.log(roles.has('editor')); // true
roles.delete('editor');
console.log(roles.size); // 1How Keys Are Compared: SameValueZero
Both collections decide whether two keys are equal using SameValueZero. It works like === with one exception: NaN equals itself. 0 and -0 count as the same key. Objects are compared by reference, so two separate {} literals are different keys.
const values = new Set([NaN, NaN, 0, -0, '1', 1]);
console.log(values.size); // 4
console.log(values.has(NaN)); // true
const m = new Map();
m.set(-0, 'zero');
console.log(m.get(0)); // 'zero'
console.log(new Set([{}, {}]).size); // 2Iterating Maps: keys, values, entries, and forEach
A Map iterates in insertion order. keys(), values(), and entries() each return an iterator. Looping over the Map directly with for...of gives the same result as entries(). The forEach callback receives the value first and the key second.
const prices = new Map([['apple', 1.2], ['pear', 0.9]]);
console.log([...prices.keys()]); // ['apple', 'pear']
console.log([...prices.values()]); // [1.2, 0.9]
for (const [fruit, price] of prices) {
console.log(fruit, price); // apple 1.2, then pear 0.9
}
prices.forEach((price, fruit) => {
console.log(`${fruit}: ${price}`);
});Exercise
What does new Map([[NaN, 'a'], [NaN, 'b'], ['0', 'c'], [0, 'd']]).size return, and why?
Show answer
It returns 3. SameValueZero treats both NaN keys as the same key, so the second entry overwrites the first. The string '0' and the number 0 are different values, so each gets its own entry.
Exercise
In map.forEach((a, b) => ...), which parameter holds the key?
Show answer
b holds the key. The forEach callback for a Map receives the value first and the key second.