Debuging Find the Longest Word in a String

Tell us what’s happening:
I’m trying to pass this challenge by:

  1. splitting the input string into an array
  2. have a var ‘long’ start at 1
  3. iterate through the array and replace ‘long’ with the length of any string higher than ‘long’

I’m stuck in one part of the debugging process— when I set the input string to (‘hey dude’) and do console.log(i) I get i=2. I’m confused because my for loop has the condition ‘i < obj.length’ and here obj.length = 2. So I would think I should only go up to 1.

Can someone help me figure out what’s going on?

Thanks

Your code so far


var str= 'hey dude';
function findLongestWordLength(str) {
  var obj = str.split(' ');
  var long = 1;
  for (let i = 0; i < obj.length; i++){
    if (obj[i]>long){
      long = obj[i].length();
      i++;}
    else{
      i++;
    }
  }
  return long;
}

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


var obj = str.split(' ');
var long = 1;
  for (var i = 0; i < obj.length; i++){
    if (obj[i]>long){
      long = obj[i].length();
      i++;}
    else{
      i++;
    }
  }
console.log(i);

Your browser information:

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36.

Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/basic-algorithm-scripting/find-the-longest-word-in-a-string

Why start long at 1? What if a sub array has only negative values?

Your for loop’s 3rd argument (the increment expression) has i++ which will increment i after each iteration. Inside your for loop, both your if and else blocks of code also have i++, so at each iteration, i is being incremented by 2 instead of just 1,

Ah, thanks a lot. The other mistake in there was that my if statement compared “obj[i]” (a string) to “long” a number, when I really needed to compare obj[i].length with long.