0
0
JavascriptProgramBeginner · 2 min read

JavaScript Program to Find Longest Word in String

Use string.split(' ') to split the string into words, then loop through to find the longest word by comparing lengths, like words.reduce((a, b) => a.length >= b.length ? a : b).
📋

Examples

InputI love coding
Outputcoding
InputJavaScript is awesome
OutputJavaScript
Inputa bb ccc dddd eeeee
Outputeeeee
🧠

How to Think About It

To find the longest word, first split the sentence into individual words using spaces. Then check each word's length and keep track of the longest one found so far. At the end, return the word with the greatest length.
📐

Algorithm

1
Get the input string.
2
Split the string into words using space as separator.
3
Initialize a variable to hold the longest word found so far.
4
Loop through each word and compare its length with the longest word.
5
If current word is longer, update the longest word variable.
6
Return the longest word after checking all words.
💻

Code

javascript
function findLongestWord(str) {
  const words = str.split(' ');
  let longest = '';
  for (const word of words) {
    if (word.length > longest.length) {
      longest = word;
    }
  }
  return longest;
}

console.log(findLongestWord('JavaScript is awesome'));
Output
JavaScript
🔍

Dry Run

Let's trace 'JavaScript is awesome' through the code

1

Split string

words = ['JavaScript', 'is', 'awesome']

2

Initialize longest

longest = ''

3

Check 'JavaScript'

longest = 'JavaScript' (length 10)

4

Check 'is'

longest stays 'JavaScript' (10 > 2)

5

Check 'awesome'

longest stays 'JavaScript' (10 > 7)

6

Return longest

return 'JavaScript'

WordLongest Word So Far
JavaScriptJavaScript
isJavaScript
awesomeJavaScript
💡

Why This Works

Step 1: Split the string

Splitting the string by spaces creates an array of words to check individually.

Step 2: Compare word lengths

Each word's length is compared to the current longest word to find the biggest.

Step 3: Return longest word

After checking all words, the longest one is returned as the result.

🔄

Alternative Approaches

Using reduce method
javascript
function findLongestWord(str) {
  return str.split(' ').reduce((longest, current) => current.length > longest.length ? current : longest, '');
}
console.log(findLongestWord('JavaScript is awesome'));
This method is concise and uses functional programming but may be less clear for beginners.
Using forEach loop
javascript
function findLongestWord(str) {
  let longest = '';
  str.split(' ').forEach(word => {
    if (word.length > longest.length) longest = word;
  });
  return longest;
}
console.log(findLongestWord('JavaScript is awesome'));
Using forEach is similar to for-of but uses a callback function.

Complexity: O(n) time, O(n) space

Time Complexity

The program loops through all words once, so time grows linearly with the number of words.

Space Complexity

Splitting the string creates an array of words, so space grows linearly with input size.

Which Approach is Fastest?

All approaches have similar time and space complexity; reduce is concise but for-loop is more explicit.

ApproachTimeSpaceBest For
For-loopO(n)O(n)Clarity and beginners
Reduce methodO(n)O(n)Concise functional style
forEach loopO(n)O(n)Callback style iteration
💡
Always split the string into words before checking their lengths.
⚠️
Forgetting to split the string into words and trying to compare the whole string length.