Your First Real JavaScript Program: A Word Frequency Report from Standard Input
Build a complete Node.js program that reads text from standard input, counts words with a Map, ranks them and draws a scaled bar chart, then walk through every line: regular expressions with Unicode, ?? defaults, destructuring, sorting with tie-breakers, padEnd and toFixed.
kvi5hnuCode Sprout team member8 min readOn this page
The tour articles showed the language in small pieces. Now let's put the pieces together into a complete, useful program. It reads any text from standard input, counts how often each word appears, and prints a report with a bar chart:
the ############################## 10 (26.3%)
river ##################### 7 (18.4%)
sea ######### 3 (7.9%)
Programs like this are behind word clouds, search-engine indexes and the "most used words" stats in writing apps. Analyzing word frequency is also a classic interview warm-up ("find the top k frequent words"), so it's worth knowing well.
Don't worry if some syntax is new. The walkthrough after the program explains every line and points to the article that covers each feature in depth.

The program
Press Run. The text comes from the input box (standard input), so you can replace it with anything: a paragraph from a book, song lyrics, your own writing.
const fs = require("node:fs");
const TOP = 8; // how many words to show
const BAR_WIDTH = 30; // length of the longest bar
// 1. Read all of standard input as one string.
const text = fs.readFileSync(0, "utf8");
// 2. Split it into lowercase words. \p{L} matches a letter in any alphabet.
const words = text.toLowerCase().match(/\p{L}+(?:'\p{L}+)?/gu) ?? [];
// 3. Count each word in a Map from word to count.
const counts = new Map();
for (const word of words) {
counts.set(word, (counts.get(word) ?? 0) + 1);
}
// 4. Sort the [word, count] pairs: most frequent first, ties alphabetically.
const ranked = [...counts].sort(
([wordA, countA], [wordB, countB]) => countB - countA || wordA.localeCompare(wordB)
);
// 5. Print a summary and a bar chart scaled to the most frequent word.
const longest = words.reduce((best, w) => (w.length > best.length ? w : best), "");
console.log(`words: ${words.length}, distinct: ${counts.size}, longest: "${longest}"`);
console.log();
const top = ranked.slice(0, TOP);
const maxCount = top[0]?.[1] ?? 0;
const labelWidth = Math.max(...top.map(([word]) => word.length));
for (const [word, count] of top) {
const bar = "#".repeat(Math.round((count / maxCount) * BAR_WIDTH));
const share = ((count / words.length) * 100).toFixed(1);
console.log(`${word.padEnd(labelWidth)} ${bar} ${count} (${share}%)`);
}
words: 38, distinct: 20, longest: "doesn't"
the ############################## 10 (26.3%)
river ##################### 7 (18.4%)
sea ######### 3 (7.9%)
feeds ###### 2 (5.3%)
and ### 1 (2.6%)
arrives ### 1 (2.6%)
by ### 1 (2.6%)
café ### 1 (2.6%)
To run it on your own machine, save it as wordfreq.js and pipe a file into it: node wordfreq.js < essay.txt.
Walkthrough
Step 1: reading the input
const fs = require("node:fs");
const text = fs.readFileSync(0, "utf8");
require("node:fs") loads Node's built-in file system module. The node: prefix makes it clear that this is a built-in module, not a package from npm. readFileSync(0, "utf8") reads everything from file descriptor 0, which is standard input, and decodes the bytes as UTF-8 text. Sync means the program waits until reading finishes, which is fine for a short command-line tool (part 16 covers the asynchronous alternatives used in servers).
Step 2: finding the words
const words = text.toLowerCase().match(/\p{L}+(?:'\p{L}+)?/gu) ?? [];
This one line does a lot:
toLowerCase()makes "The" and "the" count as the same word./.../guis a regular expression, a pattern for matching text.\p{L}means "any letter in any alphabet", socafé,naïveorनदीwork too.+means "one or more", and(?:'\p{L}+)?optionally allows an apostrophe followed by more letters, sodoesn'tstays one word. Thegflag finds all matches, anduturns on Unicode mode, which\p{...}requires. Part 11 has a whole series on regular expressions.matchwith thegflag returns an array of every match, ornullwhen nothing matches (for example, empty input).?? []replaces thatnullwith an empty array, so the rest of the program never has to check fornull.
Step 3: counting with a Map
const counts = new Map();
for (const word of words) {
counts.set(word, (counts.get(word) ?? 0) + 1);
}
A Map stores key/value pairs, here word to count. For each word, counts.get(word) returns the current count, or undefined the first time a word appears. ?? 0 turns that undefined into 0, we add 1, and set stores the new count.
Why a Map and not a plain object? Both work, but a Map is made for exactly this: it has a size, it remembers insertion order, it's easy to loop over, and its keys can't clash with built-in property names. With a plain object, a text containing the word "constructor" would find an inherited function instead of a missing count. Part 11 compares the two.
Step 4: ranking
const ranked = [...counts].sort(
([wordA, countA], [wordB, countB]) => countB - countA || wordA.localeCompare(wordB)
);
[...counts]uses the spread syntax to turn the map into an array of[word, count]pairs, because maps can't be sorted but arrays can.sorttakes a comparison function that receives two elements and returns a negative number if the first should come first, a positive number if the second should, or 0 if they tie.([wordA, countA], [wordB, countB])destructures each pair into named variables right in the parameter list.countB - countAsorts by count, highest first. When two counts are equal, the difference is0, which is falsy, so||moves on towordA.localeCompare(wordB), which compares the words alphabetically. This "||chain" is a compact, common idiom for sorting by several keys.
Step 5: the report
const longest = words.reduce((best, w) => (w.length > best.length ? w : best), "");
reduce walks the array while carrying a value along, here the longest word seen so far, starting from "". Because the comparison uses >, the first word of maximum length wins a tie.
const top = ranked.slice(0, TOP);
const maxCount = top[0]?.[1] ?? 0;
const labelWidth = Math.max(...top.map(([word]) => word.length));
slice(0, TOP)takes the first eight entries (or fewer, if there aren't eight).top[0]?.[1]reads the count of the first entry. If there is no first entry (empty input),?.stops and givesundefined, and?? 0turns that into 0. The bracketed form?.[1]is optional chaining for an index.Math.max(...numbers)spreads an array into separate arguments. The result is the length of the longest label, used to line up the bars.
const bar = "#".repeat(Math.round((count / maxCount) * BAR_WIDTH));
const share = ((count / words.length) * 100).toFixed(1);
console.log(`${word.padEnd(labelWidth)} ${bar} ${count} (${share}%)`);
Each bar's length is proportional to its count, so the most frequent word gets exactly BAR_WIDTH characters. toFixed(1) formats a number with one decimal place (it returns a string), and padEnd adds spaces until the label reaches the given width.
Edge cases worth testing
A program isn't finished until it handles odd input. Try these in the input box:
| Input | What happens | Why |
|---|---|---|
| nothing at all | prints words: 0, distinct: 0, longest: "" and an empty chart | match returns null, ?? [] saves us, and top is empty so the loop doesn't run |
42 apples, 7 pears | only apples and pears are counted | \p{L} matches letters only, not digits |
Don't don't DON'T | one word, count 3 | toLowerCase runs before matching |
| text in Hindi or Greek | works | \p{L} covers every script that has letters |
One limitation remains: some languages, such as Chinese, Japanese and Thai, don't put spaces between words, so a regular expression can't find the word boundaries. JavaScript has a tool for that, Intl.Segmenter, covered with the internationalization API in part 11.
Common questions
Why is everything declared with const, even inside the loop?
for (const word of words) creates a fresh word binding for each iteration, so it never needs reassigning. counts is const because the variable always refers to the same Map, even though the map's contents change. Using const wherever possible makes it obvious which names never change.
What happens if two words have the same count and the same spelling but different case, like "Rain" and "rain"?
They can't both appear: toLowerCase() runs before matching, so both become rain and share one count. If you wanted case-sensitive counting, you'd remove toLowerCase().
Isn't sorting the whole map wasteful when we only want the top 8?
For typical texts, sorting a few thousand distinct words takes well under a millisecond, so the simple approach wins. For millions of distinct items, you'd keep a small min-heap of size k instead, which takes O(n log k) time instead of O(n log n). That's a common follow-up interview question.
Why does localeCompare matter? Couldn't I compare with <?
< compares strings by UTF-16 code units, which puts every uppercase letter before every lowercase one and puts accented letters like é after z. localeCompare uses language-aware rules, so café sorts next to cafe where a reader expects it.
Summary
require("node:fs").readFileSync(0, "utf8")reads standard input in a command-line program.- A regular expression with
\p{L}and theuflag finds words in any alphabet.matchwithgreturns all matches ornull, and?? []normalizes that. - A
Mapis the natural structure for counting:map.set(key, (map.get(key) ?? 0) + 1). - Sort by several keys with a comparator like
b.count - a.count || a.word.localeCompare(b.word). - Spread (
...), destructuring,?.,??,reduce,padEndandtoFixedkeep the code short and readable.
Practice Questions
Change the program so that it ignores very common words like "the", "and" and "a". Where would you put the check?
Answer
Create a set of stop words (shown below) and skip them while counting: inside the loop, if (STOP.has(word)) continue;. Filtering before counting keeps the percentages honest if you also compute them from the filtered list.
const STOP = new Set(["the", "and", "a", "is"]);
What would the sort order be if the comparator were just countB - countA?
Answer
Words with different counts would still be ordered by count. Words with equal counts would keep their original relative order (insertion order from the map, which is first appearance in the text), because JavaScript's sort is guaranteed to be stable since ES2019.
If the input is empty, Math.max(...[]) is evaluated. What does it return, and does it cause a problem here?
Answer
Math.max() with no arguments returns -Infinity. labelWidth becomes -Infinity, but it's only used inside the loop, which doesn't run when top is empty, so nothing breaks. It's still worth knowing, because -Infinity can surface in surprising places.
Why does "doesn't" count as one word, but a word wrapped in single quotes like 'river' doesn't keep its quotes?
Answer
The pattern allows an apostrophe only between letters: \p{L}+(?:'\p{L}+)?. In 'river', the quotes aren't between letters, so the match starts at r and ends at r.
How would you show each word's share with a locale-aware percentage, for example "26.3 %" in French?
Answer
Use Intl.NumberFormat: the code below. Part 11 covers the Intl API.
new Intl.NumberFormat("fr-FR", { style: "percent", maximumFractionDigits: 1 }).format(count / words.length)
Previous: A Quick Tour of JavaScript, Part 2: Functions, Control Flow and Classes
Next: JavaScript Lexical Structure: Case, Whitespace, Comments, Literals, Identifiers and Reserved Words

More in JavaScript Course
Quiz: Modern JavaScript, ES2022 to ES2027 Features
Twenty-four questions on what's new in JavaScript: change-array-by-copy methods, groupBy, Set methods, iterator helpers, Promise.withResolvers and Promise.try, RegExp.escape and the v flag, using declarations, Error.isError, Base64 typed arrays, Temporal, getOrInsert and Iterator.zip.
Quiz: JavaScript's Delicate Details (Spec-Level Edge Cases)
Twenty-eight questions on the fine print of JavaScript, drawn from the ECMAScript specification and MDN: sparse arrays, -0, number limits, JSON edge cases, Date overflow, UTF-16, property attributes, inherited accessors, comparison quirks, labels, regex state and Symbol.toPrimitive.
Quiz: JavaScript Interview Questions (Output Prediction and Core Concepts)
Thirty classic JavaScript interview questions: closures in loops, hoisting and the TDZ, this, the event loop and microtasks, async/await, coercion, sorting and parseInt traps, prototypes, copying, finally, generators and bind. Every answer was verified by running it.
Quiz: JavaScript Course Final Exam (All 17 Parts)
The final exam for the JavaScript course: thirty questions spanning all seventeen parts, from syntax, types and operators through objects, arrays, functions, classes, modules, the standard library, iterators, async code, metaprogramming, browsers, Node.js and tooling.
Discussion
Sign in to ask a question or share what you learned.