-1

I was looking into how to find the min and max value in an array (without using Math) and I came across this code in a forum:

var array = [4, 2, 3, 4]
var min = arrayMin(array);
out.innerHTML = min;

function arrayMin(arr) {
  var len = arr.length, min = Infinity;
  while (len--) {
    if (arr[len] < min) {
      min = arr[len];
    }
  }
  return min;
};
<p id="out"></p>

I can't really wrap my head around it and understand it fully, especially the infinity part. Could someone be so nice and explain it as simple as possible?

Meek
  • 87
  • 11

2 Answers2

3

The logic seems to be fine. The code you have added gives minimum value. min is initialised to Infinity and min is updated as you traverse through array.

Lets take a look at what happens for first array element.

4 < Infinity //index = 0 min becomes 4
2 < 4 //index = 1 min becomes 2

and so on the code will output minimum value.

Shubham Gupta
  • 2,596
  • 1
  • 8
  • 19
1

Infinity is a property of the global object, or in other words, a variable in global scope.

The initial value of Infinity is Number.POSITIVE_INFINITY. The value Infinity (positive infinity) is greater than any other number. Mathematically, this value behaves the same as infinity; for example, any positive number multiplied by Infinity equals Infinity, and any number divided by Infinity equals 0.

So, what the above function is doing is creating a temporary variable called min that keeps track of the smallest number. When the first comparison is made, it will overwrite the value of min every time since Infinity is higher than any other number. Then, it continues to iterate through the array making the same evaluation until it exits.

Here is an inline snippet demonstrating how this works:

var array = [4, 2, 3, 4]
var min = arrayMin(array);

function arrayMin(arr) {
  var len = arr.length, min = Infinity;
  while (len--) {
    console.log(min);
    if (arr[len] < min) {
      min = arr[len];
    }
  }
  return min;
};

You can read more about Infinity here.

Adam Chubbuck
  • 1,612
  • 10
  • 27