Count Matching Messages

In the video Visit Each Message With for…of, your loop asked every message the delivery question and logged messages 7 and 9 as selected. Your report doesn’t want a log, though. It wants one number, “2 delivery messages”, that you can still explain afterward.

By the end of this lesson, you’ll be able to write a loop that counts every message meeting a condition, choose const or let for each name in it, and explain why the count starts where it does.

Keep a Running Count With let

To count, you need a name whose value changes as the loop runs. So far, you’ve made every name with const, which names a value once and keeps it. The keyword let also declares a name, but you can point it at a new value later.

Here are messages 7, 8, and 9 again, followed by a count. The last line, count on its own, asks the Console to show the value the name points at once the loop has finished:

Language: JavaScript
> const messages = [
…   { id: 7, topic: "delivery", status: "approved" },
…   { id: 8, topic: "billing", status: "approved" },
…   { id: 9, topic: "delivery", status: "pending" },
… ];
undefined
> let count = 0;
undefined
> for (const message of messages) {
…   if (message.topic === "delivery") {
…     count = count + 1;
…   }
… }
… count
2

Two delivery messages, so the count is 2. Each part of the counting has its own place:

  • Before the loop: let count = 0; declares the name once and starts it at zero. Before any message has been checked, zero matches is the honest answer.
  • On each pass: The if asks the question, and only a match runs count = count + 1;.
  • After the loop: count holds the finished answer, ready to use.

JavaScript evaluates the right-hand side of count = count + 1; first. It reads the number count points at now, adds one, and only then does = point count at the result. The name works like a label you move to a new number, not a box you add things to.

Here’s how count changes across the three passes:

Pass message.id topic Match? count after the pass
1 7 "delivery" yes 1
2 8 "billing" no 1
3 9 "delivery" yes 2

Locked learning resources

Join us and get access to thousands of tutorials and a community of expert JavaScript developers.

Unlock This Lesson

Already a member? Sign-In

Locked learning resources

The full lesson is for members only. Join us and get access to thousands of tutorials and a community of expert JavaScript developers.

Unlock This Lesson

Already a member? Sign-In

Become a Member to join the conversation.