Calculate the frequency of characters in a string using Javascript

If you want to check how many times a character in a string appeared then you can use below code. It will print the object of string letters with their occuring frequency value.

const str = 'CoNgratulations';

const letters = {};
for (let char of str.toLowerCase()) {
    letters[char] = letters[char] + 1 || 1;


In the code snippet, there is string str which contains some characters in it. We have converted the string to lowecase so that it does now confuse with capital letters and return the right rest.

We are looping through the string characters and adding 1 in each iteration in the letters object.

Live Demo

Was this helpful?