Count how often each word appears

“Word counter”, a Green belt challenge from the CurlyScript Dojo. It uses what Grade 8: Objects: Describing Things With Labels teaches, and 3 tests check your answer.

The challenge

Write wordCount(text) that returns an object with each word (in lowercase) and how many times it appears. Words are separated by spaces.

Example
wordCount("the cat and the hat")
// { the: 2, cat: 1, and: 1, hat: 1 }

Try it

Write your answer below, then press Check my answer. Your code runs right here in your browser, and the tests tell you what works.

What the tests check

  • wordCount("the cat and the hat") gives { the: 2, cat: 1, and: 1, hat: 1 }
  • wordCount("Go go GO") gives { go: 3 }
  • wordCount("hi") gives { hi: 1 }

Hints

Stuck? Open one hint at a time. Try again after each one.

Hint 1

Start with const counts = {}; and loop over text.toLowerCase().split(" ").

Hint 2

counts[word] = (counts[word] || 0) + 1;

A solution

There’s always more than one right way. Read it, make sure you understand it, then try writing it yourself without looking.

Show one possible solution
Solution
function wordCount(text) {
  const counts = {};
  for (const word of text.toLowerCase().split(" ")) {
    counts[word] = (counts[word] || 0) + 1;
  }
  return counts;
}

Learn what you need

This exercise uses what Grade 8: Objects: Describing Things With Labels teaches. Read those notes first if any of it is new.

Practice makes it stick

CurlyScript is a free game that teaches JavaScript from zero: short lessons, an explanation after every answer, and Dojo challenges like this one.

Start learning