Finding the longest word in a string in JavaScript

We are required to write a JavaScript function that takes in a string as the only argument. The function should then iterate through the string and find and return the longest word from the string.

For example ?

If the input string is ?

const str = 'Coding in JavaScript is really fun';

Then the output string should be ?

const output = 'JavaScript';

Using Array.reduce() Method

The most efficient approach uses the reduce() method to iterate through words and track the longest one:

const str = 'Coding in JavaScript is really fun';

const findLongest = (str = '') => {
    const strArr = str.split(' ');
    const word = strArr.reduce((acc, val) => {
        let { length: len } = acc;
        if(val.length > len){
            acc = val;
        }
        return acc;
    }, '');
    return word;
};

console.log(findLongest(str));
JavaScript

Using for Loop Method

A traditional loop approach that's easier to understand:

const str = 'Coding in JavaScript is really fun';

function findLongestWord(str) {
    const words = str.split(' ');
    let longest = '';
    
    for (let i = 0; i < words.length; i++) {
        if (words[i].length > longest.length) {
            longest = words[i];
        }
    }
    
    return longest;
}

console.log(findLongestWord(str));
JavaScript

Using sort() Method

Sort words by length in descending order and return the first element:

const str = 'Coding in JavaScript is really fun';

function findLongestWithSort(str) {
    return str.split(' ').sort((a, b) => b.length - a.length)[0];
}

console.log(findLongestWithSort(str));
JavaScript

Handling Multiple Longest Words

When multiple words have the same maximum length, return all of them:

const str = 'The quick brown fox jumps over lazy dogs';

function findAllLongest(str) {
    const words = str.split(' ');
    const maxLength = Math.max(...words.map(word => word.length));
    return words.filter(word => word.length === maxLength);
}

console.log(findAllLongest(str));
[ 'quick', 'brown', 'jumps' ]

Comparison

Method Readability Performance Use Case
reduce() Medium Good Functional programming style
for loop High Best Simple and straightforward
sort() High Lower One-liner solutions

Conclusion

The for loop method offers the best performance and readability for finding the longest word. Use reduce() for functional programming approaches and sort() for concise one-liner solutions.

Updated on: 2026-03-15T23:19:00+05:30

483 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements