Hey guys . I hope someone can help me explain why my code is outputting:
[ , , , , 1000000 ]
Here is the code:
function largestOfFour(arr) {
var results = [];
for (var n = 0; n < arr.length; n++) {
var largestNumber = arr[n][0];
for (var sb = 1; sb < arr[n].length; sb++) {
if (arr[n][sb] > largestNumber) {
largestNumber = arr[n][sb];
}
}
}
results[n] = largestNumber;
return results;
}
console.log(largestOfFour([[4, 9, 1, 3], [13, 35, 18, 26], [32, 35, 97, 39], [1000000, 1001, 857, 1]]));
I have the solution for the code above but I am just intentionally breaking the code by moving results[n] = largestNumber; outside of the outer for loop to just understand the code better.
What I want to know is why isn’t the code just spitting out [1000000] and instead is spitting out [ , , , , 1000000 ]. Where did the commas suddenly appear from?
You set up an empty array results. Then the loop runs four times (arr.length).
n is 0
set a variable largestNumber to 4.
Loop 3 times.
9 > 4, largestNumber is set to 9.
1 < 9, largestNumber is still 9.
3 < 9, largestNumber is still 9.
n is 1
set a variable largestNumber to 13.
Loop 3 times.
35 > 13, largestNumber is set to 35.
…etc etc.
On last element: n is 3
set a variable largestNumber to 1000000.
Loop 3 times.
1000000 is larger than anything else in the array, so largestNumber stays as 1000000.
Set results[3] (n is 3 at this point) to largestNumber, which is 1000000. Return that (results is an array with a value set at index 3)
I would advise using let, not var, because it will then fail predictably instead of how it’s failing at the minute. If you use let, then the variables n and largestNumber will be scoped inside the loop only. So results[n] = largestNumber will just error because those two variables won’t be accessible. At the minute, those variables are leaking out of the loop, so you’re actually getting a [wrong] result instead of the function breaking (as it really should). An error instead should make it clear[er] that something in your code is in the wrong place.