The JavaScript Number object is a wrapper for numeric values. You can use it in combination with the new keyword and set it to a variable to be used later in JavaScript code:
var myNumber = new Number(numeric value);
Alternatively, you can create a Number object simply by setting a variable to a numeric value. This variable will then have access to the properties and methods available to the object.
In addition to storing numeric values, the Number object includes various properties and methods for manipulating or retrieving information about numbers. All of the properties available to the Number object are read-only constants, meaning that their values always remain the same and cannot be changed. Four properties are included in the Number object:
- MAX_VALUE
- MIN_VALUE
- NEGATIVE_INFINITY
- POSITIVE_INFINITY
The MAX_VALUE property returns the value 1.7976931348623157e+308, which is the largest number JavaScript can handle:
document.write(Number.MAX_VALUE);
// Result is: 1.7976931348623157e+308
Alternatively, using MIN_VALUE returns the value 5e-324, which is the smallest number possible in JavaScript:
document.write(Number.MIN_VALUE);
// Result is: 5e-324
NEGATIVE_INFINITY is the largest negative number JavaScript can handle, represented as -Infinity:
document.write(Number.NEGATIVE_INFINITY);
// Result is: -Infinity
The POSITIVE_INFINITY property is anything larger than MAX_VALUE and is represented as Infinity:
document.write(Number.POSITIVE_INFINITY);
// Result is: Infinity
The Number object also has methods that you can use to format or convert numeric values. The methods are:
- toExponential
- toFixed
- toPrecision
- toString
-
valueOf
Each method essentially does exactly as it is named—for example, the toExponential method returns a string representation of a number in exponential form. The uniqueness of each method is in the arguments it excepts. The toExponential method has an optional argument that can be used to set how many significant digits to use, the toFixed method determines the post-decimal precision based on the argument passed, and the toPrecision method determines the significant digits to display based on the argument passed.
Each object in JavaScript includes a toString and valueOf method. The toString method returns a string representation of a number (in this case), but in other objects, it returns a string representation of that object type. The valueOf method returns the primitive value of the object type that calls it—in this case, theNumber object.
The Number object alone might not seem terribly powerful, but it is an essential part of any programming language, and JavaScript is no exception. The JavaScript Number object provides the foundation for any mathematical procedures, which is essentially the foundation of all programming languages.