Most people think that Math.max() stands for MAXINT. In some languages, MAXINT is the maximum representable integer value.
Math.max()
In JavaScript, you can check your MAXINT using Number.MAX_SAFE_INTEGER.
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.max
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.
-Infinity
Analogously, the same happens to Math.min().
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 🙃
Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment's permalink.
Hide child comments as well
Confirm
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
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: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 🙃