Could someone explain to me how does this work. In find highest number method every number is larger than -Infinity. Why does it take the highest number? Same with lowest number finder, how does it selects lowest number, all of the numbers are smaller than Infinity.
//find highest number
var Numbers = [1, 2, 101, 45, 55, 1443];
var l = Numbers.length;
var max = -Infinity;
var i;
for (i = 0; l > i; i++) {
if (Numbers[i] > max) {
max = Numbers[i];
}
}
console.info(max);
//find lowest number
var Numbers = [1, 2, 101, 45, 55, 1443];
var l = Numbers.length;
var max = Infinity;
var i;
for (i = 0; l > i; i++) {
if (Numbers[i] < max) {
max = Numbers[i];
}
}
console.info(max);
The key is here.
if (Numbers[i] > max) {
max = Numbers[i];
}
If the current number is greater than the current maximum number then we make that the max number. And we continue until we go trough the entire array.
Starting with -Infinity ensures that any value in the array will be greater or equal to it.
For the minimum it's the same but we always keep the smallest value we find in the list.
Infinity and -Infinity are values javascript provides, they are greater or smaller than any other value of type Number. You can find more about them here.
You could debug your code and see exactly what's happening step by step. Check this link on how to do that in Chrome.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With