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
JavaScript Arrays
JavaScript Array Methods
JavaScript Objects
Exercises & Assignments
Write a JavaScript program to find the sum and average of array elements
Write a JavaScript program to find the largest and smallest number in an array
Write a JavaScript program to remove duplicates from an array
Write a JavaScript program to filter even numbers and double them
Write a JavaScript program to count the frequency of words in a sentence
Interview Questions & Answers
What is the difference between map and forEach?
What is the difference between slice and splice?
What is the difference between shallow copy and deep copy in JavaScript?
What is the difference between spread and rest operators?
What are Map and Set in JavaScript?
How do you check if a variable is an array in JavaScript?