Help With Find the Longest Word in a String

Help With Find the Longest Word in a String
0.0 0

#1

I get the correct output each time I run this code, however for some reason the (“May the force be with you”) requirement will not clear even though I get 5 every time. Can anyone suggest what the problem could be?

Your code so far


function findLongestWord(str) {
	
	newArray = str.split(' ');
	 newArray.forEach(function(newArray)  {
  if (newArray.length > longestString) {
		longestString = newArray.length;
		}
		
		});
		return longestString;
	}

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

Your browser information:

Your Browser User Agent is: Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.146 Safari/537.36.

Link to the challenge:


#2

This is the full code.

var longestString = 0;

function findLongestWord(str) {
	
	newArray = str.split(' ');
	 newArray.forEach(function(newArray)  {
  if (newArray.length > longestString) {
		longestString = newArray.length;
		}
		
		});
		return longestString;
	}

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

#3

I’ve edited your post for readability. When you enter a code block into the forum, precede it with a line of three backticks and follow it with a line of three backticks to make easier to read. See this post to find the backtick on your keyboard. The “preformatted text” tool in the editor (</>) will also add backticks around text.


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

#4

Thank you Ariel, this makes so much more sense now. I still haven’t quite got a grasp on Global and Local Variables. I really really really really appreciate your help.