Write a JavaScript program to count the frequency of words in a sentence

Description: Count each word of the sentence “to be or not to be”.

Hint:

  • Split the sentence into words.
  • Use an object where the word is the key and the count is the value.

JavaScript word frequency program

const sentence = "to be or not to be";
const counts = {};

for (const word of sentence.split(" ")) {
  counts[word] = (counts[word] || 0) + 1;
}

console.log(counts);

Output:

Tutorials Class - Output Window

{ to: 2, be: 2, or: 1, not: 1 }

How it works

  • counts[word] || 0 gives 0 for a new word, and then 1 is added.
  • Objects keep the order in which keys were added.

Learn more about the similar topics:
Tutorials
No Content Found.
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.