In this video, you saw why a counter declared outside a function gives a wrong count on the second call, and how declaring it inside the function fixes that. Here’s what to keep from it.
Key Points
- When the counter is declared outside the function, every call shares that one
count. The delivery call leaves it at2, so the billing call starts from2and reports3instead of1. Nothing crashes, so the wrong number can slip into a report. - The fix is to move one line: declare
let count = 0;inside the function, at the top of its body. - Each call gets its own variables, like a fresh room: the parameters
messagesandtopichold that call’s arguments, andcountstarts at0. When the call returns, the room closes and itscountis gone. countis declared insidecountTopic(), so it can only be used inside that function’s braces. The code that calls the function can’t read it, so a line after the calls that logscountstops withReferenceError: count is not defined. To use a count outside, return it and keep it indeliveryCountorbillingCount.- The rule: declare a variable inside the function that needs it, and every call gets a fresh one. When you read a reporting function, whoever wrote it, check where each counter is declared.
Final Code
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;
}
}
return count;
}
const deliveryCount = countTopic(messages, "delivery");
const billingCount = countTopic(messages, "billing");
console.log("delivery", deliveryCount);
console.log("billing", billingCount);