Find the Longest Word in a String (All results as expected, but not pass!)

Find the Longest Word in a String (All results as expected, but not pass!)
0

#1

Hello campers,
below is my code attached. When you run it, returns all the expected results at console. However, “findLongestWord(“May the force be with you”) should return 5” item in the exercise isn’t passed, although the result is also correct at console.
I wait for your suggestions!

Saludos

var comp = "";

function findLongestWord(str) {
  var strArr = str.split(" ");
  for (var i = 0; i < strArr.length; i++) {
    if (strArr[i].length > comp.length) {
      comp = strArr[i];
    }
  }
  return comp.length;
}

findLongestWord("May the force be with you");

SOLVED



function findLongestWord(str) {
  var comp = "";
  var strArr = str.split(" ");
  for (var i = 0; i < strArr.length; i++) {
    if (strArr[i].length > comp.length) {
      comp = strArr[i];
    }
  }
  return comp.length;
}

findLongestWord("May the force be with you");

#2

copy all your code.
refresh the page.
delete all the old code.
paste new copy of code.

sometimes this works.


#3

I tried refreshing browser and reseting my code, the problem persists.


#4

Solved! I read an answer from another topic that you were involved that helped me. I’m trying to understand the behavior of global variables here (var comp = "";)


#5

To be honest, this isn’t how the function would be in the real life, but it’s usefull in the exemple.
var comp = ""; serves as a temporary var to store the biggest word, and it is initialized to an empty string so the first strArr[i].length > comp.length will have comp.length at 0 (so it will always store the first word of strArr)
Also, comp is never reset so if you were calling twice findLongestWord you could have false results !

In practise you could have

function findLongestWord (str) {
   var max = 0, 
       strArr = str.split(" ");
    for (var i = 0; i < strArr.length; i++) {
        if (strArr[i].length > max) {
            max = strArr[i].length;
        }
    }
    return max;
}

And at higher level

function findLongestWord (str) { 
    var max = 0, 
        strArr = str.split(" "); 
    strArr.forEach(function (elt) { 
        max = (elt.length > max) ? elt.length : max;
    }); 
    return max;
}