The Ultimate Guide to JavaScript Algorithms - Lesson #10

JavaScript Algorithms: Finding the Longest Word In a Sentence

Finding the longest word in a string of text is a very common algorithmic challenge in the JavaScript world. In this article we examine three ways to solve this challenge, with each method showcasing varied levels of complexity.

Our goal as always is to determine the fastest i.e the most highly performant approach using JSPerf.

Lets dive right in!

You should already have your development environment setup for this course. Update your cloned repository by running the command git pull. Inside the Beginner folder, navigate to the longestWord folder. Our work for this challenge will be done in here. Make sure to follow along in the index-START.js file.

Given a sentence, return the longest word in the string. E.g

longestWord('Top Shelf Web Development Training') 
//should return 'Development'

As expressed in the challenge statement, the only parameter our longestWord function will receive is the sentence(string of text) to be evaluated.

Within this function, we would loop through every word within the string received and compare their length in order to determine the longest.

Coding time!

Below, we explore 3 approaches to solving this challenge by applying various JavaScript techniques and concepts. They include:

  • Using a For-loop
  • Using the .reduce() method
  • Using the .sort() method

In this approach we first separate the sentence into an array of words using the .split() method. We use the variable maxLength to hold the maximum length encountered at each point of iteration using the for-loop. It is initially set to 0.

See solution below:

function longestWord(text) {
    let wordArray = text.split(' ')
    let maxLength = 0
    let result = ''

    for (let i = 0; i < wordArray.length; i++) {
        if (wordArray[i].length > maxLength) {
            maxLength = wordArray[i].length
            result = wordArray[i]

    return result

Notice that the for loop is set up to execute for as long as the iterator is less than the length of the array. Since array indices are zero-based, if we had an array containing 5 words, that enables us loop through positions 0-4.

Within the for-loop, we check if the length of the current word under evaluation wordArray[i] is greater than our maxLength. If it is, we replace the maxLength with the newly found maximum and store the word in a variable result.

At the end of the iteration, result now holds the longest word in the sentence, hence it is returned as such.

Let's try something more concise.

The .reduce() method is used to execute a certain piece of code (function) on all the elements in an array in order to cummulatively arrive at a single value.

Here, we call the .reduce() method on the array of words in the sentence. This executes our reducer function on every word in the array until the final output is arrived at.

See this below:

function longestWord(text) {
    var result = text.split(' ').reduce((maxLengthWord, currentWord) => {
        if (currentWord.length > maxLengthWord.length) {
            return currentWord
        } else {
            return maxLengthWord
    }, "")
    return result

Within the reducer function, we compare the length of the current word under evaluation with the length of our accumulator variable maxLengthWord which is set to an empty string at the start. Whenever the length of the current word is greater, we return the current word as the new accumulator value otherwise the accumulator retains it's original value into the next comparison.

At the end of the reduction, result now holds the longest word in the sentence and is returned accordingly.

Could this get anymore concise? Let's see.

The .sort() method sorts the elements of an array and returns the sorted array. It receives an optional parameter which is a function that specifies the order in which sorting should be carried out.

In this solution, we use this method to rearrange the array of words from the sentence in the order of decreasing length, such that the first element in the array becomes the longest word.

function longestWord(text) {
    var sortedArray = text.split(' ')
                          .sort((wordA, wordB) => wordB.length - wordA.length)
    return sortedArray[0]

Notice that within our compare function, we subtract the length of the second word from that to the first. This gives us a positive, negative or 0 value that determines which word is longer and by extension which should come before the other.

On completion of the sorting process, we now have a sortedArray with the words arranged in descending order according to their length. We return the word(element) occupying the first position in this array as this is the longest word.

Its validation time!

Testing Correctness with Jest To run the tests for each solution above, run the command below:

npm run test longestWord
  • Using a for-loop

  • Using .reduce()

  • Using .sort()

We did it again! We passed all tests :). Testing Performance with Jest Follow this link to run your own comparison of the algorithms considered in this test. Here's a screenshot of the results:

The screenshot above reveals that the for-Loop and .reduce() implementations perform best and are the fastest with really close performance values. The .sort() method on the other hand, is 83% slower than both methods.

The techniques considered in this challenge are applicable in coding interviews and may be applied in evaluating the complexity of a piece of text.

They may also be used in word games for scoring.

We have successfully considered three ways to determine the longest word in a sentence.

At the end of running our performance tests, we understand that using a for-loop or the .reduce() method solves the problem faster despite their being slightly more verbose than the .sort() method.

For further learning on the techniques and concepts explored in this article, use the links below:

See you in the next one!✌🏿

Want to improve your coding and design skills?

I'm continually researching the best practices and tools for coding.
Join 50,000+ developers looking to make cool stuff.

We value your privacy. 1-click unsubscribe.


What did you think of the article? Let us know!
(these comments are powered by GitHub issues and use 0 trackers)