Largest and smallest word in a string - JavaScript

We need to write a JavaScript function that takes a string and returns an array containing the smallest and largest words from the string based on their length.

For example, if we have the string:

const str = "Hardships often prepare ordinary people for an extraordinary destiny";

The output should be:

const output = ["an", "extraordinary"];

The word "an" has 2 characters (smallest) and "extraordinary" has 13 characters (largest).

Example

Here's the complete implementation:

const str = "Hardships often prepare ordinary people for an extraordinary destiny";

const largestSmallest = str => {
    const strArr = str.split(" ");
    let min = strArr[0];
    let max = strArr[0];
    
    for(let i = 1; i  max.length){
            max = strArr[i];
        }
    }
    return [min, max];
};

console.log(largestSmallest(str));
[ 'an', 'extraordinary' ]

How It Works

The function follows these steps:

  1. Split the string: str.split(" ") converts the string into an array of words
  2. Initialize variables: Set both min and max to the first word
  3. Compare lengths: Loop through remaining words and update min and max based on word length
  4. Return result: Return an array with the smallest and largest words

Alternative Approach Using reduce()

Here's a more functional programming approach:

const str = "Hardships often prepare ordinary people for an extraordinary destiny";

const largestSmallestReduce = str => {
    const words = str.split(" ");
    
    return words.reduce((result, word) => {
        if (word.length  result[1].length) result[1] = word;
        return result;
    }, [words[0], words[0]]);
};

console.log(largestSmallestReduce(str));
[ 'an', 'extraordinary' ]

Edge Cases

The function handles various scenarios:

// Single word
console.log(largestSmallest("Hello"));

// Multiple words with same length
console.log(largestSmallest("cat dog fox"));

// Empty string handling
const handleEmpty = str => {
    if (!str.trim()) return ["", ""];
    return largestSmallest(str);
};

console.log(handleEmpty("JavaScript is awesome"));
[ 'Hello', 'Hello' ]
[ 'cat', 'cat' ]
[ 'is', 'JavaScript' ]

Conclusion

This function efficiently finds the smallest and largest words by splitting the string and comparing word lengths. Both the loop-based and functional approaches work well, with the choice depending on your coding style preference.

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

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements