Help with failed test with correct output

Tell us what’s happening:

Your code so far

var x = "";
var result = 0;
function findLongestWord(str) {
  array = str.split(' ');
  for (var i = 0; i < array.length; i++) {
    x = array[i];
    if (x.length > result)
      result = x.length; 
  return result;

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/66.0.3359.139 Safari/537.36.

Link to the challenge:

One of the tests keeps failing even though I keep getting the right output.

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.


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

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

Ok thanks that made it work. I ave another challenge where I was having a similar issue but this didnt fix this one.

function titleCase(str) {
var array = [];
var result = "";
  str = str.toLowerCase();
  array = str.split(" ");
  for (var i = 0; i < array.length; i++) {
    result  = result + " " + array[i].substring(0, 1).toUpperCase() + array[i].substring(1, array[i].length);
  return result;

titleCase("I'm a little tea pot");

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.


It looks like you are adding an extra space at the beginning of result.