Using a loop, write a function getTheRange which finds the range (difference between high and low) of arr . The value returned should be an array with the low, high, and range.

I got some help on stackoverflow and the final answer ended up looking like this:

const getTheRange = (arr) => {
let low = arr[0],
high = arr[0];
for (let i = 1; i < arr.length; i++) {
if (arr[i] < low) {. //need need understanding from here down//
low = arr[i];
} else {
high = arr[i];
}
}
let range = high - low;
return [low, high, range];
};
console.log(getTheRange([3, 2, 5, 4, 7, 9, 10])); // expect log [2, 10, 8]

Can someone plz just explain this? I donâ€™t seem to understand how we set low and high = arr[0], then ask in the loop arr[i] < low ? and from there how does the code know this is the lowest value?

Sorry for question! Just really trying to understand the answer

@salomonj11
Please remove the dot (.) after the comment: . //need need understandingâ€¦

So the code can run

Explanation:

Have a reference value to compare with for low and high: let low = arr[0], high = arr[0]; // comma (,) was used to avoid using let againâ€¦ DRY principle.

Note: it can be any index within the arrayâ€¦ Aim is a reference to compare
Try: let low = arr[5], high = arr[5]; â€¦in this case: low = 9, high = 9 in the console â€¦then here let i = 0 is the first point not let i = 1

Loop through all numbers in the arr:
since i = 0 - the initial value to compare, start with let i = 1
as you go through, looping ask the questions:

is 2 (arr[1]) < 3
is 5 (arr[2]) < 3
is 4 (arr[3]) < 3
â€¦
is 10 (arr[6]) < 3