Emmanuel Akinfulubi

JavaScriptFunction

Count each letter in a string in JavaScript

Beginner · 4 min read

Counting how many times each letter appears in a text is called making a tally, or a frequency count. For 'banana' the answer is b: 1, a: 3, n: 2. The same pattern counts votes, words in an essay, products in an order, or error types in a log file. Once you know it, you will use it everywhere.

In this tutorial you will write letterCounts, which returns an object with one key per character. You will learn the one line every tally is built on, a hidden problem with plain objects, and a Map version. You need to know what an object and a for loop are.

Objects as tally sheets

An object stores values under names called keys. You can read and write a key with square brackets, using a variable for the key name:

JavaScript

const counts = {};
const c = 'a';
counts[c] = 1;
console.log(counts);    // { a: 1 }
console.log(counts.b);  // undefined

Reading a key that was never set gives undefined. That is the first thing to handle: the first time you meet a letter, there is no count yet.

Here is the exercise. Try it yourself first if you like, or read on and we will build it together.

17 Count each letter’s occurrences

easy

Report how many times each letter appears in a string.

Stuck? Three hints, smallest first
  1. 1. Build an object keyed by character, incrementing as you go.
  2. 2. counts[c] = (counts[c] ?? 0) + 1 handles the first occurrence.
  3. 3. A plain object inherits keys like toString; Object.create(null) or a Map does not.

Step 1: walk through the characters

for...of gives you each character of a string in turn:

Step 1

for (const c of 'abc') console.log(c);

That prints a, b and c on separate lines. Now each character needs adding to the tally.

Step 2: the tally line

For each character, the new count is "the old count plus one". If there is no old count yet, treat it as 0:

Step 2

const tally = {};
for (const c of 'banana') tally[c] = (tally[c] ?? 0) + 1;
console.log(tally); // { b: 1, a: 3, n: 2 }

?? is the nullish coalescing operator. x ?? 0 gives x, unless x is null or undefined, in which case it gives 0. So the first a turns undefined into 0 + 1, and the next ones add 1 to the real count.

counts[c] = (counts[c] ?? 0) + 1 is worth memorizing. It is the whole tally pattern in one line.

Step 3: a hidden problem with {}

A plain object made with {} isn't really empty. It inherits built-in properties from a shared parent object, its prototype. toString is one of them:

Step 3

const plain = {};
console.log(typeof plain.toString); // 'function'
console.log(plain.toString ?? 0);   // the toString function, not 0

So if your tally ever meets a key called toString, constructor or valueOf, it starts from a function instead of 0. Counting the characters of a string only creates one-letter keys, so it is safe here. But the same pattern is used for counting words or names, and there it really breaks.

Step 4: an object with no prototype

Object.create(null) makes an object with no parent at all, so it has no inherited keys:

Step 4

function letterCounts(text) {
  const counts = Object.create(null);
  for (const c of text) counts[c] = (counts[c] ?? 0) + 1;
  return counts;
}
const result = letterCounts('banana');
console.log(Object.getPrototypeOf(result)); // null
console.log(result.a, result.n, result.b);  // 3 2 1
console.log({ ...letterCounts('aA') });     // { a: 1, A: 1 }

Object.getPrototypeOf confirms the parent is null. The { ...counts } in the last line copies the counts into an ordinary object, which prints in the usual way. Notice that a and A are counted separately: they are different characters.

Step 5: count only letters, ignoring case

Usually the question is about letters, not every character. Lower-case the text, then remove anything that isn't a to z with a regular expression before counting:

Step 5

const lettersOnly = (text) => letterCounts(text.toLowerCase().replace(/[^a-z]/g, ''));
console.log({ ...lettersOnly('Hello, World!') }); // { h: 1, e: 1, l: 3, o: 2, w: 1, r: 1, d: 1 }

/[^a-z]/g means "every character that is not a small letter". Spaces, commas and the ! are gone, and H and W were counted as h and w.

Step 6: the Map version

A Map is a collection built for this job. It has no inherited keys, keeps keys in the order they were added, and has get and set methods:

Step 6

function letterCountsMap(text) {
  const counts = new Map();
  for (const c of text) counts.set(c, (counts.get(c) ?? 0) + 1);
  return counts;
}
console.log([...letterCountsMap('banana')]); // [ [ 'b', 1 ], [ 'a', 3 ], [ 'n', 2 ] ]

Same tally line, written with get and set. Spreading a Map gives an array of [key, count] pairs.

The full solution

The panel has letterCounts, letterCountsMap, lettersOnly and a sorted helper that lists the most common characters first. It prints the counts for 'banana' and 'Hello, World!', the top three letters, and the toString example. Press Run to see them.

The answer

function letterCounts(text) {
  // Object.create(null) has no prototype, so a character sequence like
  // "constructor" cannot collide with an inherited property.
  const counts = Object.create(null);
  for (const c of text) counts[c] = (counts[c] ?? 0) + 1;
  return counts;
}

// A Map, which keeps insertion order and any key type.
function letterCountsMap(text) {
  const counts = new Map();
  for (const c of text) counts.set(c, (counts.get(c) ?? 0) + 1);
  return counts;
}

// Letters only, case-folded, which is usually the actual question.
const lettersOnly = (text) => letterCounts(text.toLowerCase().replace(/[^a-z]/g, ''));

const sorted = (counts) => Object.entries(counts).sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0], 'en'));

console.log("letterCounts('banana')  =", { ...letterCounts('banana') });
console.log("lettersOnly('Hello, World!') =", { ...lettersOnly('Hello, World!') });
console.log('most common first:', sorted(lettersOnly('Hello, World!')).slice(0, 3));
console.log('--- why Object.create(null) ---');
const plain = {};
console.log("a plain object already 'has' toString:", typeof plain.toString);
console.log('so counting the word "toString" would start from a function, not 0');
const bare = letterCounts('toString');
console.log('with a bare object it counts properly:', { ...bare });

Output


      
17 checks that prove this answer

You do not have to read these. They are part of the answer panel above, so pressing Run there executes all 17 of them and prints ok for each. That output is the proof, and the build fails if a single check fails.

17 checks

test('banana', { ...letterCounts('banana') }, { b: 1, a: 3, n: 2 });
test('the counts add up to the length', Object.values(letterCounts('banana')).reduce((a, b) => a + b, 0), 6);
test('an empty string gives no counts', { ...letterCounts('') }, {});
test('one character', { ...letterCounts('a') }, { a: 1 });
test('it is case-sensitive by default', { ...letterCounts('aA') }, { a: 1, A: 1 });
test('while the letters-only version folds case', { ...lettersOnly('aA') }, { a: 2 });
test('and drops punctuation', { ...lettersOnly('a!a') }, { a: 2 });
test('spaces are counted by the plain version', letterCounts('a a')[' '], 1);
test('but not by the letters-only one', lettersOnly('a a')[' '], undefined);
test('every distinct character gets a key', Object.keys(letterCounts('banana')).length, 3);
test('the Map version agrees', [...letterCountsMap('banana')], [['b', 1], ['a', 3], ['n', 2]]);
test('and keeps first-seen order', [...letterCountsMap('banana').keys()], ['b', 'a', 'n']);
test('a plain object would inherit toString', typeof {}.toString, 'function');
test('so a bare object is used instead', letterCounts('toString').t, 2);
test('and its prototype really is null', Object.getPrototypeOf(letterCounts('x')), null);
test('sorting by count gives the most common first', sorted(lettersOnly('Hello, World!'))[0], ['l', 3]);
test('most common in banana', sorted(letterCounts('banana'))[0], ['a', 3]);

counts[c] = (counts[c] ?? 0) + 1 is the shape to memorise for any tally. Using ?? rather than || matters in general, though not here — || would also replace a legitimate 0, and counts start at 1 so it happens to be safe.

Object.create(null) is the detail worth taking seriously. A plain {} inherits toString, constructor, valueOf and more, so a tally keyed by arbitrary text can collide with an inherited property. The assertions confirm the prototype is null and that counting the word 'toString' works. With user-supplied keys this stops being theoretical, and __proto__ as a key on a plain object is a known source of bugs.

A Map is the other good answer: it keeps insertion order for every key type, has no inherited keys at all, and reports size directly.

Common mistakes

  • Writing counts[c]++ with no starting value. undefined + 1 is NaN, so every count becomes NaN.
  • Using counts.c instead of counts[c]. The dot form reads a key literally named c, not the letter stored in the variable.
  • Using {} for keys that come from users. Words like constructor collide with inherited properties. Use Object.create(null) or a Map.

Try it yourself

  1. Count the words in 'the cat and the hat' instead of the letters. (Hint: split(' ') first.)
  2. Find the most common letter in 'mississippi' using Object.entries and sort.
  3. Write sameLetters(a, b) that returns true when two words have exactly the same letter counts.

Keep practising

Newsletter

New writing, when it lands.

Occasional notes on shipping software with AI agents. No schedule, no filler, unsubscribe in one click.