Finding average word length of sentences - JavaScript

We are required to write a JavaScript function that takes in a string of words joined by whitespaces. The function should calculate and return the average length of all the words present in the string rounded to two decimal places.

Understanding the Problem

To find the average word length, we need to:

  • Split the string into individual words
  • Calculate the total length of all words (excluding spaces)
  • Divide by the number of words
  • Round the result to two decimal places

Example

Following is the code:

const str = 'This sentence will be used to calculate average word length';

const averageWordLength = str => {
    if(!str.includes(' ')){
        return str.length;
    };
    const { length: strLen } = str;
    const { length: numWords } = str.split(' ');
    const average = (strLen - numWords + 1) / numWords;
    return average.toFixed(2);
};

console.log(averageWordLength(str));
console.log(averageWordLength('test test'));
5.00
4.00

How It Works

The algorithm works by:

  • Single word check: If no spaces exist, return the length of the single word
  • Total character count: Get the length of the entire string including spaces
  • Word count: Split by spaces to count words
  • Calculate average: (total characters - spaces + 1) / word count

Alternative Approach

Here's a more straightforward method that directly calculates word lengths:

const averageWordLengthDirect = str => {
    const words = str.trim().split(' ').filter(word => word.length > 0);
    const totalLength = words.reduce((sum, word) => sum + word.length, 0);
    const average = totalLength / words.length;
    return average.toFixed(2);
};

console.log(averageWordLengthDirect('This sentence will be used to calculate average word length'));
console.log(averageWordLengthDirect('hello world programming'));
5.00
6.33

Handling Edge Cases

const robustAverageWordLength = str => {
    if (!str || str.trim() === '') return '0.00';
    
    const words = str.trim().split(/\s+/).filter(word => word.length > 0);
    if (words.length === 0) return '0.00';
    
    const totalLength = words.reduce((sum, word) => sum + word.length, 0);
    return (totalLength / words.length).toFixed(2);
};

console.log(robustAverageWordLength(''));                    // Empty string
console.log(robustAverageWordLength('   '));                // Only spaces
console.log(robustAverageWordLength('hello   world   js')); // Multiple spaces
0.00
0.00
4.33

Conclusion

The average word length can be calculated using string manipulation and basic arithmetic. The robust approach handles edge cases and multiple spaces, making it more reliable for real-world applications.

Updated on: 2026-03-15T23:18:59+05:30

529 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements