I'm trying to understand nested forloops and I found this code that should be simple and I want you to make sure I understand it.
var maximum = function(arr){
var out;
for(var i = 0; i < arr.length; i++){
out = true;
console.log(i)
for(var j = 0; j < arr.length; j++){
if(arr[i] < arr[j]){
// console.log(i, j)
out = false;
// console.log(arr[i], arr[j], " out ", out)
}
}
if(out) return arr[i];
}
// return null;
}
console.log(maximum([1,2,5]))
first of all i'm not sure why they define out = true
but I wanted to undestand the looping right now
so for the first iteration
i
is set to 0 and out
is set to true then we go into the second for loop
i= 0
inside the second forloop: for(var j = 0; j < arr.length; j++){
we test (arr[i] < arr[j])
3 time for the length of the array
1st test in the inner loop :arr[0] = 1 < arr[0] = 1 ==false (so we do nothing? shouldn't out remain true and we return if(out) return arr[i];
?)
2nd test in the inner loop arr[0] = 1 < arr[1] = 2 == true.. set out
to false
3rd test in the inner loop arr[0] = 1 < arr[2] = 5 == true .. set out
to false
then we go to make i
1
then we test is arr[i] = 2 < arr[j] which is 1 ? false we dont set out to false
is arr[i] = 2 < arr[j] which is 2 ? false we dont set out to false
is arr[i] = 2 < arr[j] which is 5? true we set out
to true
then we set i
to 2
arr[2] = 5
is arr[2] which is 5 < arr[0] which is 1 this is false so out remains true
is arr[2] which is 5 < arr[1] which is 2 this is false so out remains true
is arr[2] which is 5 < arr[2] which is 5 this is false so out remains true
Is the corrected process for the nested loops?