In the last video, Dana made a what-if budget with structuredClone(), cut groceries to 400, raised fun to 200, and saw that her real budget kept its own limits. Before she plans a month around the what-if, she wants to know which limits are different.
In this lesson, you’ll write a small function that compares two records value by value, and you’ll use it to list the limits the what-if changed. First, see why the two quick checks you may reach for, === and comparing JSON text, can’t answer Dana’s question.
Understand Why the Quick Checks Fall Short
A comparison is only useful if it says “the same” when nothing changed, and === fails that test on objects. As you saw with copies before, === asks whether both sides are the same object, so structuredClone(budget) === budget is false before anyone touches a limit. A Set also compares objects by identity, so a Set holding a record and its copy has two items, not one.
A common shortcut is comparing JSON text with JSON.stringify(a) === JSON.stringify(b), but it’s fragile. The same keys added in a different order can give different text, and the JSON rules from earlier in this course drop undefined properties, so { amount: 38, note: undefined } gives the same text as { amount: 38 }. Keep it for a quick look while testing, and use a real comparison when the answer matters.
Write a Value-by-Value Comparison
To ask “same contents?”, you compare the parts one at a time. The limits object is a flat record: an object whose values are all primitives, such as numbers and strings, with no objects inside. For a flat record, two objects match when they have the same keys and every key holds the same value.
Create compare.js next to whatif.js, with one exported function: