Maps and Sets
Missing Map Keys
Provide a fallback when a map lookup is missing.
map-default
`Map.get` returns `undefined` when the key is missing. The nullish coalescing operator `??` can turn that missing value into a clear fallback label.
Missing Map Keys
map_default.js
Replay: real traced execution (multi-file project)
const item = "milk";
const label = new Map([
["tea", "drink"],
["bread", "food"],
]).get(item) ?? "missing";
console.log("item=" + item);
console.log("label=" + label);
const item = "tea";
const label = new Map([
["tea", "drink"],
["bread", "food"],
]).get(item) ?? "missing";
console.log("item=" + item);
console.log("label=" + label);
const item = "bread";
const label = new Map([
["tea", "drink"],
["bread", "food"],
]).get(item) ?? "missing";
console.log("item=" + item);
console.log("label=" + label);
item ← milk, label ← missing
1const item→ milk = "milk"; //@item="tea", "bread"2const label→ missing = new Map([3 ["tea", "drink"],4 ["bread", "food"],5]).get(item→ milk) ?? "missing";67console.log("item=" + itemmilk);8console.log("label=" + labelmissing);outputitem=milk label=missing
item ← tea, label ← drink
1const item→ tea = "tea";2const label→ drink = new Map([3 ["tea", "drink"],4 ["bread", "food"],5]).get(item→ tea) ?? "missing";67console.log("item=" + itemtea);8console.log("label=" + labeldrink);outputitem=tea label=drink
item ← bread, label ← food
1const item→ bread = "bread";2const label→ food = new Map([3 ["tea", "drink"],4 ["bread", "food"],5]).get(item→ bread) ?? "missing";67console.log("item=" + itembread);8console.log("label=" + labelfood);outputitem=bread label=food