Longest word in string help

Longest word in string help
0

#1

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:


#2

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!


#3

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.


#4

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


#5

See updated question.


#6

I’ve updated question.


#7

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

#8

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.”


#9

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).


#10

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
}

#11

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.