Find the Longest Word in a String:

Tell us what’s happening:

My code performs the task prompted, but one of the conditions remains uncomplete [findLongestWordLength("May the force be with you") should return 5)]. BUT my code actually return that.

Your code so far


let arr1, arr2 = []
let x;
function findLongestWordLength(str) {
   arr1 = str.split(' ')
   

for (let i = 0; i < arr1.length; i++){
   
   arr2.push(arr1[i].length)
}
console.log(arr2)
x = Math.max(...arr2)

  return x
}

//console.log(findLongestWordLength(str))--> jumped

findLongestWordLength("May the force be with you")
console.log(x)//return 5

Your browser information:

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

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

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 previous 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

I got this one. But again I have a question: why result value is not be prompted by when the function runs.


function findLongestWordLength(str) {
  let arr1, arr2 = []
     arr1 = str.split(' ')     
     for (let i = 0; i < arr1.length; i++){
   
   arr2.push(arr1[i].length)
}
console.log(arr2)
let result = Math.max(...arr2)

  return result
  console.log(result)//My question here
}

findLongestWordLength("May the force be with you")

once a return statement is executed the function stops and returns a value, things after the return statement are not executed

1 Like