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.
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.
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)
Number.MAX_VALUE
.POSITIVE_INFINITE
property to get infinity.num
(highest numerical value) to i
(infinite).Number.MAX_value
is very useful while coding, and you will mostly see it in data structures and algorithms.
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)
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_VALUE
in a variable named num
.
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 if
condition to check if the value is smaller or not. If it is smaller, we replace the value with the current value in the num
variable.
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 for
loop we get the smallest number from the array in the num
variable.