Unit 8: Sets, Maps & JSON
Better boxes for data.
Unit 8 of 10 in JavaScript for kids. Its 5 lessons are Sets, Maps, Sorting & Object Tools, JSON and Collection Champion — below is everything each one explains, and a question or two from it to try.
Every sample on this page was run before it shipped, the same way the app runs it, and prints exactly what it says it prints.
This unit opens with a fortnight’s trial of everything — no card needed — or with a family plan, bought in the iPhone app. The first two units of every track are free for ever. Try it in the app.
🎯 Sets
A box that refuses duplicates
A Set keeps each value at most once, exactly like a Python set. add puts one in, has checks, size counts — note size, not length.
JavaScript
const seen = new Set();
seen.add("red");
seen.add("blue");
seen.add("red");
console.log(seen.size);
console.log(seen.has("blue"));
It prints
2 true
Throwing away duplicates
Pour an array into a Set and spread it back out, and you have the same list with the repeats gone — in the order they first appeared.
JavaScript
const colours = ["red", "blue", "red", "green"];
const unique = [...new Set(colours)];
console.log(unique);
It prints
[ 'red', 'blue', 'green' ]
Looping and removing
for...of walks a Set just like an array, and delete takes one back out.
JavaScript
const s = new Set(["a", "b"]);
s.delete("a");
for (const item of s) {
console.log(item);
}
It prints
b
Try it yourself
What makes a Set different from an array?
- It can only hold numbers
- It never keeps the same value twice
- It cannot be looped over
- It is always sorted
What does this print?
JavaScript
const s = new Set([1, 2, 2, 3]);
console.log(s.size);
Answer them in the app
🗺️ Maps
Names pointing at values, done properly
A Map is like an object, but you use set and get, it knows its own size, and it keeps its keys in the order you added them.
JavaScript
const ages = new Map();
ages.set("Al", 9);
ages.set("Bo", 11);
console.log(ages.get("Al"));
console.log(ages.size);
It prints
9 2
Walking through the pairs
Looping a Map hands you [key, value] two at a time, so unpacking them in the loop reads beautifully.
JavaScript
const score = new Map([
["Al", 3],
["Bo", 5],
]);
for (const [name, n] of score) {
console.log(`${name}: ${n}`);
}
It prints
Al: 3 Bo: 5
Try it yourself
Which line reads a value out of a Map called ages?
- ages.Al
- ages["Al"]
- ages.get("Al")
- ages(0)
What does this print?
JavaScript
const m = new Map();
m.set("a", 1);
m.set("a", 2);
console.log(m.size, m.get("a"));
Answer them in the app
🔢 Sorting & Object Tools
Looking at an object from outside
Object.keys gives the names, Object.values gives the values, and both come back as ordinary arrays you can loop or count.
JavaScript
const pet = { name: "Rex", legs: 4 };
console.log(Object.keys(pet));
console.log(Object.values(pet));
It prints
[ 'name', 'legs' ] [ 'Rex', 4 ]
The sorting trap
Plain sort() compares values as text, so 10 lands before 9. Give it (a, b) => a - b and it compares them as numbers.
JavaScript
const nums = [10, 9, 1];
console.log([...nums].sort());
console.log([...nums].sort((a, b) => a - b));
It prints
[ 1, 10, 9 ] [ 1, 9, 10 ]
Sorting objects
The compare function can look inside each item, so you can sort by any field. b.score - a.score puts the biggest first.
JavaScript
const kids = [
{ name: "Al", score: 8 },
{ name: "Bo", score: 12 },
];
kids.sort((a, b) => b.score - a.score);
console.log(kids[0].name);
It prints
Bo
Try it yourself
What does this print?
JavaScript
console.log(Object.keys({ a: 1, b: 2 }).length);
Why does plain sort() put 10 before 9?
- It sorts backwards
- It compares them as text, and "1" comes before "9"
- It is broken
- 10 is smaller
Answer them in the app
📄 JSON
Turning data into text
Only text can travel over the internet or into a file. JSON.stringify flattens an object into text — and the result really is a string, as typeof shows.
JavaScript
const pet = { name: "Rex", legs: 4 };
const text = JSON.stringify(pet);
console.log(text);
console.log(typeof text);
It prints
{"name":"Rex","legs":4}
string
And back again
JSON.parse turns that text back into a real object you can reach into. Before it, pet.legs + 1 would have glued rather than added.
JavaScript
const text = '{"name":"Rex","legs":4}';
const pet = JSON.parse(text);
console.log(pet.name);
console.log(pet.legs + 1);
It prints
Rex 5
Try it yourself
Why does JSON exist?
- To make code shorter
- Because data has to become plain text to be saved or sent, then rebuilt at the other end
- To hide your data
- To speed up loops
What does this print?
JavaScript
console.log(JSON.stringify([1, 2, 3]));
Answer them in the app
🏆 Collection Champion
Try it yourself
What does this print?
JavaScript
const a = [1, 2, 3];
const b = [3, 4];
console.log([...new Set([...a, ...b])]);
What does this print?
JavaScript
const m = new Map();
for (const w of ["a", "b", "a"]) {
m.set(w, (m.get(w) ?? 0) + 1);
}
console.log(m.get("a"), m.size);
Answer them in the app