logo
logo

Count Characters

Easy

Count Characters

Easy

Write a function that takes a string and returns an object that counts the number of occurrences of each character in the string using a for loop.

For example, if we call
countCharacters('hello')
, the function would return the following object:
{
  h: 1,
  e: 1,
  l: 2,
  o: 1
}

Console
Submit
Solution
00:00

Solution Walkthrough for Count Characters

countCharacters
that takes a string
str
as an argument and returns an object that counts the number of occurrences of each character in the input string using a for loop.

Here's how it works:

Inside the loop, the function uses the
charAt()
method to get the character at the current index
i
in the string, and assigns it to a variable called
char
.
const char = str.charAt(i);
The function then checks if the current character already exists as a key in the
counts
object. If it does, it increments its count by 1. If it doesn't, it sets its count to 1.
counts[char] = counts[char] ? counts[char] + 1 : 1;
This line of code uses a ternary operator to check if
counts[char]
is truthy. If it is, it increments its value by 1 (
counts[char] + 1
). If it's falsy (i.e. undefined), it sets its value to 1.