Coding: Finding the Longest Word in a Sentence using JavaScript

Monu Kumar Modi
The Fresh Writes
Published in
3 min readJan 23, 2023

--

In this post, we will be discussing how to find the longest word in a sentence using JavaScript. We will be using the built-in JavaScript function split() and a for loop to iterate through the words in the sentence, comparing the lengths of each word to determine which one is the longest.

First, we define a variable str which contains the sentence we want to analyze. Next, we use the split() function to break the sentence into an array of individual words. This function takes a parameter, in this case a space, which is used as the delimiter to split the sentence into an array.

Next, we define a variable longest and initialize it as an empty string. This variable will be used to store the longest word as we iterate through the array of words.

We then use a for loop to iterate through the array of words. Within the loop, we use an if statement to compare the length of the current word to the length of the word stored in the longest variable. If the current word is longer than the word stored in longest, we update the longest variable to the current word.

Finally, we use the console.log() function to output the longest word to the console.

Complete Code:

let str = "Find longest word from a sentence";
let words =…

--

--