Skip to content

Word Frequency Counter

Medium ~30 min

What you'll build

A `wordFrequency(text)` function that takes a string, splits it into words, and returns an object mapping each word to its count.

Goals

  • Split a string into words using string methods
  • Use an object as a dictionary (word → count)
  • Loop over an array and accumulate counts
  • Handle case-insensitivity and punctuation

Prerequisites

  • String methods (split, toLowerCase, replace)
  • Objects and property access
  • for loops or for...of loops

Steps

  1. 1

    Normalize the text

    Convert the text to lowercase and remove punctuation so that 'Hello!' and 'hello' are counted as the same word. Use toLowerCase() and a regex replace.

    Code
    function wordFrequency(text) {
      const clean = text.toLowerCase().replace(/[^a-z\s]/g, '');
      return clean;
    }

    Expected result

    wordFrequency('Hello, World!') returns 'hello world'.

  2. 2

    Split into words

    Split the cleaned text on whitespace to get an array of words. The split(' ') method breaks the string at each space.

    Code
      const words = clean.split(' ').filter(w => w.length > 0);

    Expected result

    An array of individual word strings, no empty strings.

  3. 3

    Count with a dictionary object

    Create an empty object counts. Loop over the words array: for each word, if it exists in counts, increment; otherwise, set it to 1. The object acts as a word→count dictionary.

    Code
      const counts = {};
      for (const word of words) {
        if (counts[word]) {
          counts[word]++;
        } else {
          counts[word] = 1;
        }
      }
      return counts;

    Expected result

    wordFrequency('the cat the dog') returns { the: 2, cat: 1, dog: 1 }.

  4. 4

    Test with a sentence

    Call the function with a multi-word sentence and print the result to verify the counts are correct.

    Code
    const result = wordFrequency('the quick brown fox jumps over the lazy dog the fox');
    console.log(result);
    // { the: 3, quick: 1, brown: 1, fox: 2, jumps: 1, over: 1, lazy: 1, dog: 1 }

    Expected result

    An object showing 'the' appears 3 times and 'fox' appears 2 times.

  5. 5

    Add input validation

    At the entry of the main logic, add input validation: check that the input is a valid number and within the allowed range, and show a clear message for invalid input instead of crashing. This is the first line of defense for a robust program.

    Code
    function validateInput(value, min, max) {
      if (typeof value !== "number" || Number.isNaN(value)) {
        throw new Error(`Invalid input: ${value} is not a number`);
      }
      if (value < min || value > max) {
        throw new Error(`Input ${value} out of range [${min}, ${max}]`);
      }
      return value;
    }
    
    // Usage
    const input = validateInput(rawInput, 1, 100);

    Expected result

    Invalid input (non-number or out of range) throws a clear error message; valid input passes through normally.

Try it yourself

What you learned

You used an object as a dictionary to accumulate counts — a fundamental pattern for grouping, tallying, and frequency analysis used in data processing.

Related Resources

Related Lessons

  • Objects

    Objects as dictionaries mapping words to counts.

  • Loops

    for...of loop iterates over the word array.

Related Practice

Look up unfamiliar terms

A beginner-friendly glossary explains jargon in plain English — variables, functions, DOM, Promise, and more.

View glossary

Decode error messages

Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.

View errors

← Back to topic