What is JavaScript Number.MAX_VALUE?
Other languages like Java and C++ have a float, double, integer, etc., to store different numerical values, but JavaScript only has one type to store all numerical values.
In this shot, we will discuss the MAX_VALUE property of JavaScript Number, which returns the highest numerical value possible.
Syntax
var num = Number.MAX_VALUE;
Number.MAX_VALUE returns a value of 1.7976931348623157e+308, which is the highest numerical value in JavaScript. You can create a variable and store it for use.
Code
Below is the code to print the value returned by Numer.MAX_VALUE.
var num = Number.MAX_VALUE;console.log(num);
The value that is greater than Number.MAX_VALUE is infinite; let’s check if this is true or not.
var num = Number.MAX_VALUEconsole.log(num)var i = 1/0;console.log(i)console.log(i<num)
Explanation
- Line 2 gives a numerical value, which we get from
Number.MAX_VALUE. - Line 3 generates an infinite value. We can also use the
POSITIVE_INFINITEproperty to get infinity. - The last line of output is false because we are comparing
num(highest numerical value) toi(infinite).
Number.MAX_value is very useful while coding, and you will mostly see it in data structures and algorithms.
Example
The example below demonstrates how to use Number.MAX_value to find the smallest value in an array.
var num = Number.MAX_VALUE;let array = [23,52,12,31,432,121,442]for(var i of array){if(i < num){num = i;}}console.log(num)
Explanation
In the example above, we are finding the smallest element of the array. We use Number.MAX_VALUE to initialize a variable that will be compared to the first or any element of the list that will always be smaller than MAX_VALUE. The only case where the value will be greater than MAX_VALUE is when the value is infinite.
-
In line 1, we store the value returned by
Number.MAX_VALUEin a variable namednum. -
In line 3, we declare an array of size 7 with random values.
-
In line 5, we iterate through the
array. -
In line 6, we have an
ifcondition to check if the value is smaller or not. If it is smaller, we replace the value with the current value in thenumvariable. -
In line 7, if the condition is true, then we store the value of the array in
num. -
In line 11, after the completion of the
forloop we get the smallest number from the array in thenumvariable.