Count and Look Up With an Object

In the previous lesson, you walked through objects that already existed, such as a recipe’s fields, with Object.keys(), Object.values(), and Object.entries(). Sam now wants something the box doesn’t hold yet: how many recipes it has in each category. That answer is an object too, but nobody types it in. Your code builds it, one recipe at a time.

In this lesson, you’ll use an object as a tally that counts as it goes, and as a lookup table that answers “How much do I have?” for an ingredient name your code receives. You’ll also check whether a key exists and remove one when it no longer belongs. Start with the count Sam asked for: How many soups, mains, bakes, and desserts are in the box?

Count Recipes Per Category

A count per category needs one number for every category, and the categories come from the data. An object fits. Each category becomes a key, and its value is the count so far. Every time the loop meets a recipe, it adds one to that recipe’s category count.

The recipes below keep only their name and category fields. Here’s the first attempt most people write, adding one to the category’s count on every pass:

Language: JavaScript
const recipes = [
  { name: "Grandma Ines's lentil soup", category: "soup" },
  { name: "Sunday roast chicken", category: "main" },
  { name: "Banana bread", category: "baking" },
  { name: "Weeknight fried rice", category: "main" },
  { name: "Lemon drizzle cake", category: "dessert" },
];

const counts = {};
for (const recipe of recipes) {
  const category = recipe.category;
  counts[category] = counts[category] + 1;
}
console.log(counts);

Run it in a practice tab like the one from the previous lesson: open a new tab, go to about:blank, and open the Console with Ctrl+Shift+J, or Cmd+Option+J on macOS. Type the code in rather than pasting it, press Shift+Enter between lines, and press Enter at the end. The keys are right, but every count is broken:

Language: Program Output
{soup: NaN, main: NaN, baking: NaN, dessert: NaN}

This broken version is deliberate because every tally has to handle the reason it fails. Why is every count NaN, short for “not a number,” even for main, which appears twice? Look at the very first pass. The object is empty, so counts["soup"] reads a key that isn’t there yet, and reading a missing key gives undefined.

Each example in this lesson stands on its own, so reload the practice tab before each one. A fresh page means nothing from the last example, such as an old counts, is left over. Reload now, then type this in:

Language: JavaScript
> const counts = {};
undefined
> counts["soup"]
undefined
> counts["soup"] + 1
NaN

The first undefined is only the Console’s echo of the const line, which has no value to show. The second comes from reading the missing key. Adding a number to undefined gives NaN, and NaN plus one is still NaN. So main starts as NaN on its first pass and stays that way on its second.

The loop needs a starting value for a key it hasn’t seen yet. The nullish coalescing operator, written ??, gives you one. It gives the value on its left, unless that’s undefined or null. Then it gives the value on its right.

So counts[category] ?? 0 is the count so far, or 0 for a new category. Reload the practice tab and type the loop again with that one change:

Language: JavaScript
const recipes = [
  { name: "Grandma Ines's lentil soup", category: "soup" },
  { name: "Sunday roast chicken", category: "main" },
  { name: "Banana bread", category: "baking" },
  { name: "Weeknight fried rice", category: "main" },
  { name: "Lemon drizzle cake", category: "dessert" },
];

const counts = {};
for (const recipe of recipes) {
  const category = recipe.category;
  counts[category] = (counts[category] ?? 0) + 1;
}
console.log(counts);

This time, each category starts at 0 on its first pass, and the loop adds one on every pass:

Language: Program Output
{soup: 1, main: 2, baking: 1, dessert: 1}

The parentheses around counts[category] ?? 0 make ?? pick the starting value first, and then + 1 adds to it. That one line is the whole tally pattern, and it works for any set of ordinary names you know, such as Sam’s categories.

To watch both versions build counts one pass at a time, press Step below with line 4 set to counts[category] + 1, then switch to (counts[category] ?? 0) + 1 and step through the passes again:

Interactive diagram — enable JavaScript to view.

With + 1 alone, pass 1 reads counts[category] for soup as undefined and stores NaN, and main is still NaN after its second pass. With ?? 0, pass 1 starts soup from 0 and stores 1, and main goes from 1 to 2 on pass 4.

The final log can’t show you that reading a missing key gives undefined, or that a starting value lets the first pass produce a count of 1.

If the first pass for a new category still feels slippery, use the next button to open a conversation with the AI mentor. On each pass of the ?? 0 loop, you say the old count, the value ?? picks, and the count that gets stored, and the mentor tells you whether you’re right:

Look Up Amounts in Sam’s Pantry

The tally is a different kind of object from a recipe. A recipe is a record, the kind of object Records With Objects covers: its keys are fixed fields you know while writing the code, such as name and servings, each holding a different kind of value. You read them with a dot, as in recipe.name.

The tally is a lookup table: its keys are data, every value means the same thing, and your code usually gets the key from somewhere else, so you look up values with square brackets.

Sam’s pantry is another lookup table. It maps each ingredient to how much Sam has, in the unit the recipes use: grams of lentils, whole onions, and liters of stock. When a recipe calls for an ingredient, the code looks its name up. Reload the practice tab and try it:

Language: JavaScript
> const pantry = { lentils: 500, onion: 3, stock: 2 };
undefined
> const ingredient = "lentils";
undefined
> pantry[ingredient]
500
> pantry["rice"]
undefined
> pantry["rice"] ?? 0
0

pantry[ingredient] uses whatever name the variable holds, which is what makes a lookup table useful. Rice isn’t in the pantry, so its lookup gives undefined, and ?? 0 turns that into the 0 Sam really has.

Other times, you need to know whether a key is there at all. Object.hasOwn(pantry, "rice") answers that: true if the object has its own key with that name, and false otherwise. The in operator asks almost the same question, "lentils" in pantry, with one difference you can see in the Console, after another reload of the practice tab:

Language: JavaScript
> const pantry = { lentils: 500, onion: 3, stock: 2 };
undefined
> Object.hasOwn(pantry, "lentils")
true
> "lentils" in pantry
true
> Object.hasOwn(pantry, "toString")
false
> "toString" in pantry
true

Sam never put a toString key in the pantry, yet in says it’s there. An object you write with curly braces, like this pantry, inherits a few built-in names like toString from JavaScript itself, and in counts those too, while Object.hasOwn() only counts the keys the object holds.

For a lookup table, where keys come from data, Object.hasOwn() is the safer check.

Those inherited names are also why this lesson’s lookup tables stick to keys you know, such as Sam’s categories and ingredients. Square brackets read inherited names too, so pantry["toString"] gives a built-in function instead of undefined, and a tally of a category called toString would go wrong. In older code, you’ll see pantry.hasOwnProperty("lentils"), the earlier form of the same check.

A lookup and an existence check answer different questions, and the difference shows when an amount is 0. To practice telling them apart, use the next button to open a conversation with the AI mentor. It gives you a pantry with onions recorded at 0 and no rice, and you say which lookup or check answers Sam’s question about each:

Remove an Ingredient With delete

A lookup table changes over time, and some keys stop belonging in it. Sam has stopped buying stock altogether, so the pantry shouldn’t list it anymore. An ingredient Sam has only run out of stays, at 0. Adding a key works like any assignment, pantry.rice = 1000, and the delete operator takes a key out again. Reload the practice tab and try it:

Language: JavaScript
> const pantry = { lentils: 500, onion: 3, stock: 2 };
undefined
> delete pantry.stock
true
> Object.keys(pantry)
(2) ['lentils', 'onion']
> Object.hasOwn(pantry, "stock")
false

delete removes a key the object holds itself, not an inherited name like toString. The true it returns only means the removal was allowed. delete returns true even when there was no such key, so check with Object.hasOwn() that the key is gone. Here, Object.keys() lists only lentils and onion, and Object.hasOwn() says false.

Watch out for pantry.stock = undefined instead, which leaves the key in place holding undefined, so Object.keys() still lists stock.

Now combine the tally and the lookup yourself. Reload the practice tab and retype the second tally loop with two more recipes: Pea and mint soup in the soup category, and Blueberry pancakes in a new breakfast category.

Then add a wanted constant holding breakfast as a string. Write two lines of your own, one looking up that category’s count and one checking whether counts has that key.

The tally should now show two soups and one breakfast. The lookup should give 1, and the check true.

Press Up until the const wanted line returns, change the name to salad, and run your two lines again. The Console accepts a repeated const in a new entry, unlike a script file. Now the lookup gives undefined, and the check false. A starting value of 0 makes the lookup give 0 instead.

You can now count with an object, look up values by a key from your data, check whether a key exists, and remove one. So far, every value you’ve looked up sat right at the top of its object. A real recipe holds a whole list of ingredients inside it, though, and in Follow a Path Into Nested Data, you’ll reach into a recipe for data like that.

Become a Member to join the conversation.