HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptMajor

Find the longest word's length

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
thelengthwordfindlongest

Problem

The challenge is simple:


Return the length of the longest word in the provided sentence.

The solution is just as simple:

function findLongestWord(str) {
  arr = str.split(' ');
  size = 0;
  for (var s in arr) {
    if (arr[s].length > size) {
      size = arr[s].length;
    }
  }
  return size;
}


However, I vaguely remember you're not supposed to use for..in in JavaScript unless absolutely necessary. What would be the more idiomatic approach for this loop?

Solution

First, I'd not name the function findLongestWord as you're not looking for the longest word, but the length of the longest word. Try getLongestWordLength instead.

You're forgetting var for your variables. This makes them shoot up to the global scope and be declared there, and we don't want that to happen. For ES6, there's also let.

for-in is only advisable on objects, and even on objects you guard it with hasOwnProperty. That's because it iterates through prototype properties (things other than the array elements or instance properties). A regular loop (for or while) while incrementing an index until length would be better. But there's an even better approach...

You can create a map of lengths by using map on your split string, returning the length of the strings. Then you use Math.max to get the largest number in the array of lengths. We can use the spread operator (...) to spread the array as arguments to Math.max.

function getLongestWordLength(str){
  return Math.max(...(str.split(' ').map(s => s.length)));
}


The above is ES6 syntax. The ES5 equivalent would look like the following. One notable difference, aside from the more verbose map is the use of apply to provide Math.max with a dynamic set of arguments.



function getLongestWordLength(str) {
return Math.max.apply(Math, str.split(' ').map(function (s) {
return s.length;
}));
}

document.write(getLongestWordLength('The quick brown fox jumps over the lazy doge'));

Code Snippets

function getLongestWordLength(str){
  return Math.max(...(str.split(' ').map(s => s.length)));
}

Context

StackExchange Code Review Q#114795, answer score: 21

Revisions (0)

No revisions yet.