Question Bank
JavaScript Set and Map Values Output: Two Explanations Quiz
Difficulty: Medium
Two seeded explanations of how `Set` and `Map` expose their values via iterators and what `console.log` prints when you call `.values()` on each, plus two companions on insertion-order guarantees and on de-duplication semantics.
JavaScript Set and Map Values Output: Two Explanations Quiz
Two seeded explanations of how `Set` and `Map` expose their values via iterators and what `console.log` prints when you call `.values()` on each, plus two companions on insertion-order guarantees and on de-duplication semantics.
540 views
13
Explain in plain terms what mySet.values() and myMap.values() return, then describe how Node's console.log represents each.
Examples
Example 1:
Input:
const mySet = new Set([1, 2, 3]);
const myMap = new Map([['x', 1], ['y', 2], ['z', 3]]);
console.log(mySet.values());
console.log(myMap.values());
Output:
[Set Iterator] { 1, 2, 3 }
[Map Iterator] { 1, 2, 3 }
Explanation: values() returns iterator objects, not arrays; Node prints them in a compact iterator-shaped form.Walk through what mySet.entries() and myMap.entries() produce. Why do Set entries pair each value with itself, and what does this say about Set and Map being interchangeable iteration sources?
Examples
Example 1:
Input:
for (const e of new Set([1, 2, 3]).entries()) console.log(e);
for (const e of new Map([['x', 1], ['y', 2]]).entries()) console.log(e);
Output:
[ 1, 1 ]
[ 2, 2 ]
[ 3, 3 ]
[ 'x', 1 ]
[ 'y', 2 ]
Explanation: Set has no separate keys, so each entry is [value, value]; Map entries are [key, value].Predict the output of inserting four numbers into a Set and then iterating it. Explain how Set guarantees uniqueness and preserves insertion order.
Examples
Example 1:
Input:
const s = new Set();
s.add(2); s.add(1); s.add(2); s.add(3);
console.log([...s]);
Output: [ 2, 1, 3 ]
Explanation: the second add(2) is a no-op because 2 is already in the set; iteration follows first-insertion order.Predict what each Map lookup prints, and explain why Map keys retain identity while plain-object keys would not.
Examples
Example 1:
Input:
const keyObj = { id: 1 };
const m = new Map();
m.set(keyObj, 'first');
m.set('1', 'second');
m.set(1, 'third');
console.log(m.get(keyObj));
console.log(m.get('1'));
console.log(m.get(1));
console.log(m.get({ id: 1 }));
Output:
first
second
third
undefined
Explanation: Map keys use reference identity for objects and SameValueZero for primitives, so a freshly built {id:1} is a different key.