Emmanuel Akinfulubi

JavaScriptBasic

Count character occurrences in a string in JavaScript

Intermediate · 3 min read

Counting how often each character appears in a piece of text is a small job with many uses. Word games check whether you can make a word from your tiles. Password checkers look for too many repeats. Compression tools start by finding the most common characters. And the same pattern counts anything else: votes, page views, words in a document.

In this tutorial you will write countChars(text). It returns a Map, a built-in object that pairs each character with how many times it appears. You will also see why the more obvious tool, a plain object, has a hidden trap. You need to know what a string, a loop and a function are.

Looping over a string

for...of visits a string one character at a time:

JavaScript

for (const ch of 'hey') {
  console.log(ch);
}
// h
// e
// y

Each time round the loop, ch holds the next character. Spaces count as characters too.

What a Map is

A Map stores pairs: a key you look things up by, and a value stored under it. You use three methods and one property:

JavaScript

const ages = new Map();
ages.set('Ada', 36);
console.log(ages.get('Ada'));  // 36
console.log(ages.get('Bola')); // undefined: nothing stored under that key
console.log(ages.size);        // 1

set stores a value, get reads it back, and size tells you how many keys there are. A key you never set gives undefined.

The ?? operator

a ?? b means "use a, but if it is null or undefined, use b instead":

JavaScript

console.log(undefined ?? 0); // 0
console.log(3 ?? 0);         // 3

That is how we will say "the count so far, or 0 if this is the first time we've seen this character".

Here is the exercise. Try it yourself first if you like, or follow the steps.

25 Count how often each character appears

fair

Given a piece of text, count how many times each character occurs. Return something a caller can inspect.

Stuck? Three hints, smallest first
  1. 1. A plain object works, but keys like constructor and toString already exist on it.
  2. 2. new Map() or Object.create(null) avoids that problem entirely.
  3. 3. Map also keeps insertion order and lets you use non-string keys.

Step 1: count with a plain object

Many people reach for a plain object first. It is worth seeing, because it mostly works:

Step 1

function countCharsObject(text) {
  const counts = {};
  for (const ch of text) counts[ch] = (counts[ch] ?? 0) + 1;
  return counts;
}
console.log(countCharsObject('hello')); // { h: 1, e: 1, l: 2, o: 1 }

For each character, read its count so far (or 0), add 1 and store it back.

Step 2: find the trap

A plain object is not truly empty. It inherits a few built-in keys from Object.prototype, the shared parent of every object. One of them is constructor:

JavaScript

const bare = {};
console.log('constructor' in bare); // true, before you have stored anything
console.log(typeof bare.constructor); // function

For single characters you would never hit this, since constructor is not one character long. But use the same code to count words, and the word "constructor" goes wrong:

JavaScript

const counts = {};
counts['constructor'] = (counts['constructor'] ?? 0) + 1;
console.log(counts['constructor']); // function Object() { [native code] }1

The inherited function was not undefined, so ?? used it, and adding 1 to a function turns both into text. Nothing warns you. The count is just garbage.

Step 3: count with a Map

A Map starts genuinely empty. Nothing is inherited as a key, so nothing can collide:

Step 3

function countChars(text) {
  const counts = new Map();
  for (const ch of text) {
    counts.set(ch, (counts.get(ch) ?? 0) + 1);
  }
  return counts;
}
const counts = countChars('hello world');
console.log(counts.get('l')); // 3
console.log(counts.get('o')); // 2
console.log(counts.get(' ')); // 1
console.log(counts.get('z')); // undefined
console.log(counts.size);     // 8

Same idea as Step 1, written with get and set. 'hello world' has 8 different characters, counting the space. A Map also remembers the order in which keys were first added, and its keys can be any value, not only strings.

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

JavaScript

const safe = Object.create(null);
console.log(safe.constructor); // undefined

Step 4: find the most common character

counts.entries() gives every [key, value] pair. Spread them into an array and use reduce to keep the pair with the biggest count:

JavaScript

const counts = new Map([['h', 1], ['e', 1], ['l', 3], ['o', 2]]);
const most = [...counts.entries()].reduce((best, e) => (e[1] > best[1] ? e : best));
console.log(most); // [ 'l', 3 ]

e[1] is the count in each pair. With no starting value, reduce begins with the first pair. That is safe here only because the map isn't empty.

The full solution

The complete answer counts the characters in 'hello world' with a Map, shows the plain-object version and its inherited constructor key, and finds the most common character. Press Run to see the output.

The answer

// A Map has no inherited keys, so nothing can collide.
function countChars(text) {
  const counts = new Map();
  for (const ch of text) {
    counts.set(ch, (counts.get(ch) ?? 0) + 1);
  }
  return counts;
}

// The plain-object version, and the trap it carries.
function countCharsObject(text) {
  const counts = {};
  for (const ch of text) counts[ch] = (counts[ch] ?? 0) + 1;
  return counts;
}

const counts = countChars('hello world');
console.log([...counts.entries()]);

// Why a bare object is risky: these keys already exist on Object.prototype.
const bare = {};
console.log('bare.constructor is', typeof bare.constructor);
console.log('so "constructor" in {} is', 'constructor' in bare);

// Object.create(null) has no prototype, so it behaves like a Map here.
const safe = Object.create(null);
console.log('safe.constructor is', safe.constructor);

const most = [...counts.entries()].reduce((best, e) => (e[1] > best[1] ? e : best));

Output


      
8 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 8 of them and prints ok for each. That output is the proof, and the build fails if a single check fails.

8 checks

test('l appears three times', counts.get('l'), 3);
test('o appears twice', counts.get('o'), 2);
test('the space is counted', counts.get(' '), 1);
test('an absent character is undefined', counts.get('z'), undefined);
test('distinct characters', counts.size, 8);
test('the most common one', most, ['l', 3]);
test('the object version agrees on real characters', countCharsObject('hello').l, 2);
test('but a bare object already has a constructor key', 'constructor' in {}, true);

The last assertion is the reason to reach for Map. With a plain object, 'constructor' in counts is true before you have counted anything, because it is inherited from Object.prototype. For character counting you would probably never notice; for counting user-supplied words you eventually will. Map and Object.create(null) both start genuinely empty.

Common mistakes

  • Using {} to count user-supplied words. Keys like constructor and toString already exist, and their counts come out wrong.
  • Writing counts.get(ch) + 1 without a fallback. The first time, get returns undefined, and undefined + 1 is NaN.
  • Reading a Map with square brackets. counts['l'] doesn't read a Map's entries. Use counts.get('l').

Try it yourself

  1. Make the count ignore case, so 'H' and 'h' are counted together.
  2. Skip spaces, so only real letters are counted.
  3. Count words instead of characters in 'the cat and the hat'. 'the' should come out as 2.

Keep practising

Newsletter

New writing, when it lands.

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