Find the Longest Word in a String-- code critique

Tell us what’s happening:
Hey everyone, my code works but doesn’t even remotely look like the answers provided. Can anyone offer feedback? I know “it works” should be my primary motivator, but I also want my code to be readable to others and useful outside of this exercise. Thank you for your thoughts!

Your code so far

function findLongestWord(str) {
  var array = str.split(" ");
  return {
    return word.length;
  }).sort(function(a, b) {
    return a - b;

findLongestWord("The quick brown fox jumped over the lazy dog");

Link to the challenge:

As the saying goes, theres more than one way to skin a cat!

I like those chained, single-line returns personally, and in this case, you are avoiding a nested for loop, so it’s pretty concise. Good work! I can’t even remember if I got this one…

What would happen if there was a hyphenated word or grammatical error in the string though? (that’s probably too in depth, just thought I’d provoke your thoughts!)

Your code has been blurred out to avoid spoiling a full working solution for other campers who may not yet want to see a complete solution. In the future, if you post a full passing solution to a challenge and have questions about it, please surround it with [spoiler] and [/spoiler] tags on the line above and below your solution code.

Thank you.

Sorry! Will remember next time :sweat_smile:

Good thoughts with the hyphenation! This splits by space, so the hyphenated word would definitely take the top space. Hyphenated words are, technically, one word, so grammatically it would be correct. I can see how that would be frustrating for a user though. Hmmm… thanks for the brain prod :slight_smile:

Since you are making use of the higher order function map, why not try reduce and avoid the extra sort part?
The less iterations your code performs, the faster it is.

1 Like