Learn JavaScript · lesson 19 of 60 · about 8 minutes
Running Totals and Searching
Count the words in a visitor's comment: keep a running count inside a loop, and search for something with a found flag.
What you'll learn
- Accumulate a total
- Count matches
- Search with a found flag
How long is that comment?
Sam wants the comment box to say how many words a visitor has typed, so nobody posts an essay by accident. The page has to go through the comment character by character and keep count as it goes.
The accumulator pattern
To total things up:
1. Start a variable at 0 before the loop
2. Add to it inside the loop
3. Use it after the loop
Sum and count
let total = 0;
let evens = 0;
for (let i = 1; i <= 6; i++) {
total += i;
if (i % 2 === 0) evens++;
}
console.log(total, evens);Output
21 3Counting words
A word starts at a character that isn't a space and comes first, or comes straight after a space. Count those starts, and extra spaces at the ends or in the middle can't fool the count.
The word count on Sam's page
const commentText = "Great post, thanks Sam!";
let wordCount = 0;
for (let i = 0; i < commentText.length; i++) {
const startsWord = commentText[i] !== " " && (i === 0 || commentText[i - 1] === " ");
if (startsWord) {
wordCount++;
}
}
const wordLabel = wordCount === 1 ? "word" : "words";
document.querySelector("#comment-count").textContent = `Your comment: ${wordCount} ${wordLabel}`;Searching with a flag
A flag is a boolean that starts false and flips to true when you find what you're looking for.
Is there a multiple of 7?
let found = false;
for (let n = 20; n <= 30; n++) {
if (n % 7 === 0) {
found = true;
console.log("Found", n);
break;
}
}
console.log(found);Output
Found 21
trueTip
Start a total or a count at 0, a product at 1 and a flag at false, all before the loop. Inside the loop, they'd start again on every lap.
Now try it yourself
This lesson is free in Codiqo, with 10 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.