re: Math.min returns Infinity? VIEW POST

FULL DISCUSSION
 

Most people think that Math.max() stands for MAXINT. In some languages, MAXINT is the maximum representable integer value.

In JavaScript, you can check your MAXINT using Number.MAX_SAFE_INTEGER.

Actually, Math.max() is a function that returns the max value of a given list of values.

Now, try to think about how would you implement this function. Our own "Math.max" function. It would be something like this:

Math.prototype.max = function () {
  var max = -Infinity;
  for (var i=0; i<arguments.length; i++) {
    if (arguments[i]>max) {
      max = arguments[i];
    }
  }
  return max;
}

Since no arguments are given in a call to Math.max(), then we never iterate the for-loop, and then, -Infinity is returned.

Analogously, the same happens to Math.min().

If you want to read the real Math.max specification, please check the ECMAScript standard: ecma-international.org/ecma-262/6....

 

Thank you, Ricardo for the code as it makes it easier to grasp the concept
and for the link to the ECMAScript Language Specification.

It's funny that all these years using JavaScript, I've never checked out the spec 🙃

code of conduct - report abuse