Longest word in string help

Tell us what’s happening:
I think I broke something…“May the force be with you” should return 5, and it does. But the challenge won’t let me pass, any ideas?

Your code so far

var longest = 0;
function findLongestWord(str) {
  var a = str.split(' ');    
  for (i=0; i<a.length; i++){    
    if (a[i].length > longest) {
      longest = a[i].length;   
    }
  }
  return longest;
}

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

Your browser information:

Your Browser User Agent is: Mozilla/5.0 (Windows NT 10.0; rv:59.0) Gecko/20100101 Firefox/59.0.

Link to the challenge:
https://www.freecodecamp.org/challenges/find-the-longest-word-in-a-string

I think you are very close.

You can only assign a value to something on the left side of the = sign.
longest = a[i].length ; //...then assign that value to longest
will assign the value of a[i].length into longest (it becomes the new longest)

(Length is a property of an array that you cannot change. For example[1,2,3,4].length would return 4.)

Good luck!

1 Like

a[i].length = longest; In this line you are attempting to set the value of a[i]'s length property to the value of the variable longest. You cannot assign values to a length property.

1 Like

You also end the loop anytime it is bigger than your current longest. Return after the loop.

1 Like

See updated question.

I’ve updated question.

Your code contains global variables that are changed each time the function is run. This means that after each test completes, subsequent tests start with the new value. To fix this, make sure your function doesn’t change any global variables, and declare/assign variables within the function if they need to be changed.

Example:

var myGlobal = [1];
function returnGlobal(arg) {
  myGlobal.push(arg);
  return myGlobal;
} // unreliable - array gets longer each time the function is run

function returnLocal(arg) {
  var myLocal = [1];
  myLocal.push(arg);
  return myLocal;
} // reliable - always returns an array of length 2
1 Like

That worked. But they should reword the second hint: “You will need to figure out a way to keep track globally of the greatest current length.”

I’ve removed the word “globally” from the hint. The Guide section of the forum is being deprecated in favor of an external guide (still in progress).

1 Like

Here is an alternative way:

function findLongestWordLength(str) {
  let x = str.split(' ').reduce((a, b) => {
    return a.length > b.length ? a : b
  })
  return x.length
}

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.