Word Frequency Counter
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
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.
Codefunction wordFrequency(text) { const clean = text.toLowerCase().replace(/[^a-z\s]/g, ''); return clean; }Expected result
wordFrequency('Hello, World!') returns 'hello world'.
- 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.
Codeconst words = clean.split(' ').filter(w => w.length > 0);Expected result
An array of individual word strings, no empty strings.
- 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.Codeconst 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
Test with a sentence
Call the function with a multi-word sentence and print the result to verify the counts are correct.
Codeconst 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
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.
Codefunction 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.
Hint
Wrap the call site in try/catch to show a friendly error to the user.
Try it yourself
function wordFrequency(text) {
// TODO: normalize, split, count, return object
return {};
}function wordFrequency(text) {
const clean = text.toLowerCase().replace(/[^a-z\s]/g, '');
const words = clean.split(' ').filter(w => w.length > 0);
const counts = {};
for (const word of words) {
counts[word] = (counts[word] || 0) + 1;
}
return counts;
}
console.log(wordFrequency('the quick brown fox jumps over the lazy dog the fox'));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
Related Practice
- Object Property Access Quiz
Practice accessing object properties.
Look up unfamiliar terms
A beginner-friendly glossary explains jargon in plain English — variables, functions, DOM, Promise, and more.
Decode error messages
Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.