JavaScript NEGATIVE_INFINITY and POSITIVE_INFINITY Properties
This tutorial describes the NEGATIVE_INFINITY and POSITIVE_INFINITY properties of JavaScript's Number object. The value of NEGATIVE_INFINITY and POSITIVE_INFINITY are read-only: they cannot be changed by your scripts; they are returned by JavaScript whenever a function or operation returns a number larger than the MAX_VALUE the JavaScript interpreter can handle.
POSITIVE_INFINITY vs. MAX_VALUE — The value of the MAX_VALUE property is the largest number your JavaScript interpreter can handle. Larger value will be viewed as POSITIVE_INFINITY.
NEGATIVE_INFINITY vs. MIN_VALUE — The value of the MIN_VALUE property is the smallest (closest to zero) number your JavaScript interpreter can handle, while NEGATIVE_INFINITY is the largest negative number the JavaScript interpreter can represent.
JavaScript Number Scale
The number scale below illustrate where JavaScript's number property constants fit in. It is useful to remember that MIN_VALUE is not the largest negative number: it is the smallest positive number JavaScript can represent.
Generating an Infinite Result with JavaScript Numberss
We know that JavaScript will return POSITIVE_INFINITY whenever it should return a number larger than the value it can handle (MAX_VALUE). The script below attempts to add MAX_VALUE to itself, which by definition will be out of range. (MAX_VALUE is the largest number JavaScript can handle.)
alert( Number.MAX_VALUE + Number.MAX_VALUE );
Since the value of MAX_VALUE is finite, we know that doubling it cannot yield an infinite result. Yet JavaScript returned:
The JavaScript keyword Infinity points to the same internal value as POSITIVE_INFINITY. For practical purposes, "Infinity
" can be used interchangeably with "Number.POSITIVE_INFINITY
" in your scripts.
The script below illustrate how the JavaScript interpreter understands the concept of infinity (anything out of bound is infinite).
alert( Number.NEGATIVE_INFINITY === -2 * Number.MAX_VALUE );
In other words: according to the JavaScript interpreter, is negative infinity identical to the negative double of the finite MAX_VALUE property?
Number.POSITIVE_INFINITY vs. Infinity
Infinity is a JavaScript reserved keyword introduced in ECMAScript version 2; it does not supersede Number.POSITIVE_INFINITY, and can be used in its place. Both point to the exact same internal value, as demonstrated below.
// Check if Infinity is identical to POSITIVE_INFINITY
alert( Infinity === Number.POSITIVE_INFINITY );
// The same holds true for negative Infinity
alert( -Infinity === -Number.POSITIVE_INFINITY );
Both lines of script return the same result:
Test the NEGATIVE_INFINITY and POSITIVE_INFINITY Properties
Interactively test the NEGATIVE_INFINITY and POSITIVE_INFINITY properties by editing the JavaScript code below and clicking the Test NEGATIVE_INFINITY and POSITIVE_INFINITY button.
Browser support: NEGATIVE_INFINITY & POSITIVE_INFINITY | |||
---|---|---|---|