Line two loops through the parent array, largest becomes 1. Then in line 4 we try to loop through the first child array ([1,12,13,4]). The if statement, the first time checks if 1 (child array, first value) is bigger than 1, it's not. Then it check if 12 (child array, second value) is bigger than 1, it is. Then it return 12. END OF CODE.
That's why you can't return arr[i][j].
Now if we do not return it, but instead replace the large number we have something like this
By the time the loops are done largest will end up being 16. So if the task was to find the largest number in all the arrays that would work (scoping problems excluded).
What we need though is to return the largest number from each array
functionlargestOfFour(arr){varresults=[];for(i=0;i<arr.length;i++){// loop 1varlargest=arr[i][0];for(j=0;j<arr[i].length;j++){// loop 2if(arr[i][j]>largest){largest=arr[i][j];}}// this runs only when loop 2 finishes (continuation of loop 1)// largest will be a13, then a 16results[i]=largest}// this runs when loop 1 finishesreturnresults}
results[i] = largest stores the larges number from the first array, then the largest number from the second array (plain english). Then, knowing that there are no more arrays to check, those two big numbers are return (at the end of all the operations)
Because the function would stop there!
i
never turns2
, the function stops/dies oncereturn
runs. Now here is an array:And this is your solution (you provided in the comments)
Line two loops through the parent array,
largest
becomes1
. Then in line 4 we try to loop through the first child array ([1,12,13,4]
). The if statement, the first time checks if1
(child array, first value) is bigger than1
, it's not. Then it check if12
(child array, second value) is bigger than1
, it is. Then it return12
. END OF CODE.That's why you can't return
arr[i][j]
.Now if we do not return it, but instead replace the large number we have something like this
By the time the loops are done
largest
will end up being16
. So if the task was to find the largest number in all the arrays that would work (scoping problems excluded).What we need though is to return the largest number from each array
results[i] = largest
stores the larges number from the first array, then the largest number from the second array (plain english). Then, knowing that there are no more arrays to check, those two big numbers are return (at the end of all the operations)Thank you! This was so helpful and cleared it up for me!