Return Largest Numbers in Arrays, `undefined` at the end of result array

Tell us what’s happening:

Your code so far

function largestOfFour(arr) {
 let new_arr = [];
 var max = 0;

 for(let i = 0; i<arr.length; i++){

   for(let j = 0 ; j<arr[i].length; j++){
           if(arr[i][j]>max){
               max = arr[i][j];
           }
   }

   console.log(max);
   // new_arr.push(max);
 }
 // return new_arr;
}

console.log(largestOfFour([[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]]));

Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/basic-algorithm-scripting/return-largest-numbers-in-arrays/

if you execute the above code, it will give you : [5,27,39,1001,undefined]. I do not understand where this undefined come from.

I thought what I did was to create a new variable max, then assign it to 0, then use it to compare with all the inner array’s elements. If the elements are bigger than max, assign elements into max. Rinse and repeat.

Where did this undefined come from then?

You can try my code in this editor.
http://pythontutor.com/javascript.html#mode=edit
It will show you step by step how the code is working.

It appears you’re getting an extra value because of your console.log at end of your code.

// this returns undefined because your function doesn’t return anything.
console.log(largestOfFour([[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]]);

1 Like

ahhh I fixed it. Thanks for the info!