In the last lesson and exercise, you turned copied blocks into one function, like logTopicCount(), and called it for different topics. Every call showed a correct count on screen. Now someone asks for one more number: how many messages are about delivery or billing, in total?
That sounds like a quick addition. You’ll find out in a moment that it isn’t, and the reason is the most important idea in this lesson: showing a value and handing it back are two different things.
Add Up Two Counts
To add two counts, your program needs them as values it can store and work with. A reasonable first attempt keeps the function as it is, renames it countTopic(), and stores what each call gives back in a variable.
Like the examples in the last lesson, each program here is a separate, complete example for you to read and predict, not one long program, and the output block under it shows what it logs. You’ll type and run code like this in the next exercise, where the website calls a supplied function, as it called weeklyReport() before:
const messages = [
{ id: "M-101", topic: "delivery", text: "Box came late" },
{ id: "M-102", topic: "billing", text: "Charged twice" },
{ id: "M-103", topic: "delivery", text: "Wrong address" },
];
function countTopic(messages, topic) {
let count = 0;
for (const message of messages) {
if (message.topic === topic) {
count = count + 1;
}
}
console.log(topic, count);
}
const deliveryCount = countTopic(messages, "delivery");
const billingCount = countTopic(messages, "billing");
console.log("stored", deliveryCount);
console.log("total", deliveryCount + billingCount);
Before you read the output, decide what the last two lines will show. The function counted 2 and 1, so stored 2 and total 3 seem like safe bets. Here’s what JavaScript actually prints:
delivery 2
billing 1
stored undefined
total NaN
Whoops, that isn’t what you expected! The first two lines are right because the function logged them. But the variable deliveryCount holds undefined, JavaScript’s value for “nothing was put here.” When + adds numbers, undefined turns into NaN, short for Not a Number. It’s a special number value that marks an invalid numeric result, so undefined + undefined gives NaN too.