Q6: Count Character Frequencies in a String

Count the occurrence of each character in a string by accumulating counts inside a plain object map, initializing unseen characters to zero.

Character Frequency Counter
function charFrequency(str) {
  const freq = {};
  for (let char of str) {
    freq[char] = (freq[char] || 0) + 1;
  }
  return freq;
}

console.log(charFrequency('hello')); // { h: 1, e: 1, l: 2, o: 1 }
💡 The expression (freq[char] || 0) ensures that unvisited characters start at 0 before adding 1.
Key Takeaways
  • Uses logical OR (||) to initialize missing object keys to zero.
  • Runs in linear O(n) time complexity relative to string length.
Knowledge Check

What value does freq[char] || 0 evaluate to if char is not yet present in the freq map?