
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Finding Average Word Length of Sentences in JavaScript
We are required to write a JavaScript function that takes in a string of strings 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
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'));
Output
Following is the output in the console −
5.00 4.00
Advertisements