For loop Basic JavaScript

Good morning,

I am a little confused on the logic of a `for loop`. If you have to find the min and max number of an array how would a for loop be used to iterate through the loop in a function? Here is example code for max number. ----- `.sort() is not allowed to be used`.

``````function max(numbers) {
let maximum = numbers[0];
for (let i = 0; i < numbers.length; i++) {
let current = numbers[i];
if (current > maximum) {
maximum = current;
}
}
return maximum
}
``````

the conditional `i < number.lenghts;` I understand that each time through the program will run until the condition is false. However, I am confused as to how the program knows where the end of the array is if we don’t know the end. the first time through the loop it says is `0 < numbers.length` how does it know if we don’t know the length?

Any help would be appreciated. Kind Regards!

also .math cannot be used.

Let’s look at the main line of the for loop:

`for (let i = 0; i < numbers.length; i++)`

This has 3 parts.

`let i = 0` initialises a counter for us.

`i < numbers.length` is a condition for continuing the loop. It basically says if the counter is less than the number representing the length of the array then keep executing the commands in the block that follows.

`i++` increments the counter.

However, I am confused as to how the program knows where the end of the array is if we don’t know the end. the first time through the loop it says is 0 < numbers.length how does it know if we don’t know the length?

We know the length of the array because that’s exactly what `numbers.length` tells us.

Eg.

``````let arr = [1,2,3]
console.log(arr.length) // 3
``````