Return Largest Numbers in Arrays (

Tell us what’s happening:

Hi guys,

I’m back with something I do not entirely understand. I always use atom to write my formula’s as it’s easier to keep track of what I do. Anyway, I have written the code, tested it, copied it into freeCodeCamp editor, tested it, the outcome is exactly what they want yet still not recognized as a correct answer. The result is an array with the highest number of each separate array.

What am I missing this time?

Your code so far


function largestOfFour(arr) {
  for (var i = 0; i < arr.length; i++) {
    highNum.push(Math.max.apply(0, arr[i]));
  }
  return highNum;
}

largestOfFour([[4, 9, 1, 3], [13, 35, 18, 26], [32, 35, 97, 39], [1000000, 1001, 857, 1]]);

Your browser information:

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

Link to the challenge:
https://www.freecodecamp.org/challenges/return-largest-numbers-in-arrays

Hmm, when I moved the variable ‘highNum’ inside the function (so change it from global to local) it did the job. Could anyone please explain to me why in this case it matters for the variable to be local instead of global? Because when I did a console.log test in my own browser with both the variable being global and local, it came up with the same result.

Your code contained 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.

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
2 Likes

You meant previous ? :stuck_out_tongue:

1 Like

That’s more accurate I think.

Thank you for your reply. I think I get it, I did a test run with the same function and global variable, but now by calling the function with a different array. It added both arrays to the same global variable.

Thanks, it required me to make a test run here before I understood what you said, but now I do.