Use Keyed and Unique Collections
Use Keyed and Unique Collections
Map associates keys with values without treating them as ordinary object properties. Set stores unique values. The school can look up a roll number and count distinct enrolled classes.
Before this topic, review Exchange and Validate JSON if its terms are unfamiliar.
What you’ll learn
- Explain use keyed and unique collections through the school example.
- Trace the shown operations and distinguish their result from displayed output.
- Make the practice change and explain its consequence: The keyed mark changes while the class duplicates are still removed by Set.
Work through the school example
This is JavaScript using language features and the host console. Read the initial values, then follow each operation to its displayed result. A declaration names a value, a function call performs an operation, and console.log displays its arguments.
JavaScript · school.js · complete example
const marks = /* @__PURE__ */ new Map([[2, 72]]);
const classes = /* @__PURE__ */ new Set(["10A", "10A", "9B"]);
console.log(marks.get(2));
console.log(classes.size);
Expected output
72
2Run in JavaScript compiler →Recognize the important boundary
Object keys in Map are compared by identity, not by matching their fields. Map and Set need a deliberate representation when serializing to JSON.
Try a small variation
JavaScript · original source for practice
const marks = /* @__PURE__ */ new Map([[2, 72]]);
const classes = /* @__PURE__ */ new Set(["10A", "10A", "9B"]);
console.log(marks.get(2));
console.log(classes.size);
Your task: Replace [[2,72]] with [[2,80]]. Predict the result before running the edited program.
The source is repeated here. If the edit targets the HTML rather than the script, use the markup repeated below; the worked answer also repeats the changed markup.
Worked answer and reasoning
The keyed mark changes while the class duplicates are still removed by Set.
JavaScript · complete worked variation
const marks = /* @__PURE__ */ new Map([[2, 80]]);
const classes = /* @__PURE__ */ new Set(["10A", "10A", "9B"]);
console.log(marks.get(2));
console.log(classes.size);
Expected output
80
2Run in JavaScript compiler →Predict the original program
JavaScript · original program for this question
const marks = /* @__PURE__ */ new Map([[2, 72]]);
const classes = /* @__PURE__ */ new Set(["10A", "10A", "9B"]);
console.log(marks.get(2));
console.log(classes.size);
Keep the useful idea
Map associates keys with values without treating them as ordinary object properties. Set stores unique values. The school can look up a roll number and count distinct enrolled classes.
Check your variation against this explanation: The keyed mark changes while the class duplicates are still removed by Set.
Use the JavaScript array reference library for individual array operations and boundary tests to check a rule independently.
Reaching the recap and completing the quizzes are separate milestones.