Javascript Tutorial
Javascript Tutorial Introduction to Javascript JavaScript Code Editors & IDE JavaScript Hello World Example Javascript Syntax and Rules syntax_rules javascript_identifiers JavaScript Keywords & Reserved Words javascript_variables JavaScript Const JavaScript let vs var vs const Data Types in JavaScript JavaScript String Template Literals & String interpolation in JavaScript Tagged Templates in JavaScript String to Number in JavaScript Number Data Type in JavaScript NaN in JavaScript JavaScript Number Min & Max & Safe Values JavaScript EPSILON & Floating point precision Infinity in JavaScript JavaScript Bigint BigInt Vs Number in JavaScript Boolean Data Type in JavaScript Undefined in JavaScript Null in JavaScript Null vs Undefined in JavaScript JavaScript Operators Arithmetic Operators in JavaScript Unary plus & minus operators in JavaScript Increment & Decrement Operators in JavaScript Comparison or Relational operators in JavaScript Strict Equality (==) Loose Equality (===) in JavaScript Ternary Conditional Operator in JavaScript Logical Operators in JavaScript Bitwise Operators in JavaScript Assignment Operators in JavaScript Nullish Coalescing Operator in JavaScript Comma Operator in JavaScript Typeof JavaScript Operator Precedence in JavaScript JavaScript if, else & nested if statement Switch Statement in JavaScript While & Do While Loops in JavaScript For Loop in JavaScript Break statement in JavaScript Continue Statement in JavaScript Arrays in JavaScript Array Constructor in Javascript Sparse Array Vs Dense Array in JavaScript How to merge Arrays in JavaScript Array Methods in JavaScript Functions in JavaScript Function Parameters & Arguments in JavaScript JavaScript Default Parameters Pass by Value and Pass by Reference in Javascript Function Expression in Javascript Nested Functions in JavaScript Immediately-invoked Function Expressions (IIFE) JavaScript Callback Functions Arrow Functions in JavaScript Arguments Object In JavaScript Rest Parameters in JavaScript Objects in Javascript Create Objects in JavaScript JavaScript Object Properties Computed Property Names in JavaScript Object Literal in JavaScript Constructor Function & New Operator in JavaScript Delete Operator in JavaScript hasOwnProperty in JavaScript Using Getters and Setters in Javascript DefineProperty in JavaScript JavaScript Property Descriptors Enumerable, Writable & Configurable Object Destructuring in JavaScript Variable Scope in JavaScript Hoisting in JavaScript Lexical Scope & Closures in JavaScript This in JavaScript Global Object, Window & Globalthis in JavaScript Call function in Javascript Prototype In Javascript Prototype Inheritance in JavaScript Instanceof Operator in JavaScript Spread Operator in JavaScript

Number Data Type in JavaScript

The JavaScript number data type stores the numbers as a double-precision 64-bitnumber The JavaScript has two data types to deal with the Numbers. One is a primitive number data type. The other one is BigInt, which is a recent addition. It does not have separate data types like integers, decimal, float as in the other languages. The JavaScript also have Number object. We also have listed the difference between number Vs Number. The Number object has many properties & methods, which you can make use of and is listed at the end of the article.

Number Data Type

The number data type represents all numbers in JavaScript. It also contains three special values i.e. Not A Number (NaN), positive infinity and negative infinity. The number is a primitive data type in JavaScript

Defining number

There are two ways you can define a primitive number

Using literal syntax

                            
let numVal=100;   //creates a primitive number
                            
                            
                        

Number global function

                            
let numVal=Number(100);   //creates a primitive number
                            
                            
                        

Number object

The JavaScript also has the Number object. The Number object is created using the Number constructor function i.e. by using the newNumber()keyword.

                            
let num = new Number("100");
console.log(num)                //[Number: 100]
 
//***output******
//Number {100}
                            
                            
                        

If you do not use the new keyword, then a primitive number is created

                            
let numObject = new Number("100");
let numVal = Number("100");
 
console.log(numObject)    //object     output  [Number: 100]
console.log(numVal)       //primitive  output  100 
 
 
//**** output ****
//Number {100}
//100          
                            
                        

You can check the type of a variable using the typeof keyword.

                            
let numValue=100;
let numObject = new Number(1500);
 
console.log(typeof numValue)       //number
console.log(typeof numObject)      //object
 
 
//****Output****
//number
//object        
            
                            
                        

number Vs Number

The number is a primitive data type. It is the one you must use. The primitive data type does not have properties or methods.

The Numberis a wrapper object around number. It is created by using the syntax new Number(value). The objects have properties & methods.

NaN

The NaN stands for not a number. It is the result of numerical operations, where result is not a number.

For Example:

A non-numeric value as the argument to the Number’s constructor results in NaN.

                            
console.log(Number("test"));
console.log(0/0)
 
//***output***
//NaN
//NaN       
            
                            
                        

You can read more about it from NaN in JavaScript tutorial

Max, Min & Safe Values

The JavaScript number has its limitation regarding Max Value, Safe Value & Min Value that you can use. The JavaScript uses the MAX_SAFE_INTEGER, MIN_SAFE_INTEGER, MAX_VALUE & MIN_VALUE to represent these values

The above limitations are due the fact that the Javascript stores the numbers as double-precision 64-bit number. Each number can be stored using the total 64-bit memory. Out of 64bits, one is used for the sign, 11 for the exponent and remaining 52 bits are used for the mantissa (significand).

The max integer that we can store in 52 bits is 9007199254740991. It is represented by MAX_SAFE_INTEGER& the minimum value is -9007199254740991 and is represented by MIN_SAFE_INTEGER

                            
 console.log(Number.MAX_SAFE_INTEGER)    //9007199254740991
console.log(Number.MIN_SAFE_INTEGER)    //-9007199254740991
 
 
*** output ****
9007199254740991
-9007199254740991  
            
                            
                        

Any number above this number will result in loss of accuracy. For Example, adding 1 & 2 to the MAX_SAFE_INTEGER results in the same value

                            
console.log(Number.MAX_SAFE_INTEGER+1)
console.log(Number.MAX_SAFE_INTEGER+2)
 
//*** output **
//9007199254740992        
//9007199254740992  
            
                            
                        

You can use the Number.isSafeInteger method to check whether the number is safe.

                            
console.log(Number.isSafeInteger(Number.MAX_SAFE_INTEGER));
console.log(Number.isSafeInteger(Number.MAX_SAFE_INTEGER+1));
 
//*** output **
//true
//false
            
                            
                        

The largest number possible to represent using the number data type is 1.7976931348623157e+308 and it is represented by Number.MAX_VALUE. The lowest number is Number.MIN_VALUE.

                            
console.log(Number.MAX_VALUE)
console.log(Number.MIN_VALUE)
 
****** Output *****
1.7976931348623157e+308
5e-324 
            
                            
                        

The bitwise operators and shift operators operate on 32-bit integers only, so in that case, the max safe integer is 2147483647.

Infinity

The Infinity is the property of the global Number object.

                            
console.log(Number.POSITIVE_INFINITY);
console.log(Number.NEGATIVE_INFINITY);
 
//** output **
//Infinity
//-Infinity
            
                            
                        

Infinity can result in many ways, for example multiplying Number.MAX_VALUE by 2 results in infinity.

                            
let bigNumber=Number.MAX_VALUE * 2;
console.log(bigNumber);
console.log(bigNumber === Number.POSITIVE_INFINITY) 
 
//*** output ***
//Infinity
//true
            
                            
                        

You can use the Number.isFinite method to verify whether the number is finite.

                            
console.log(Number.isFinite(Number.POSITIVE_INFINITY));
console.log(Number.isFinite(100));
 
//***output **
//false
//true 
            
                            
                        

Exponential Notation

We can use exponential notation e to represent a very large or a very small number. For Example 3×10^9 in Exponential notation is 3e9

                            
num1 = 3e9;     //3x10^9
console.log(num1);    //3000000000
 
num2 = 3e-6;   //3/10^6
console.log(num2);   // 0.000003
            
                            
                        

Binary & Hexadecimal numbers

To represent the Hexadecimal numbers prefix them with 0x

                            
num = 0x8f        //hex number
console.log(num); // 143
            
                            
                        

Syntax to represent the Binary numbers ( 0b) introduced in ES6. Prior to that the JavaScript didn’t provide any literal form to represent binary numbers

                            
let num = 0b111;
console.log(num); // 7
 
            
                            
                        

Octal numbers

Since ES6 0o is used to represent the octal number

                            
let num1 = 0o41      //octal number
console.log(num1); // 33
 
 
            
                            
                        

Invalid numbers throws an error.

                            
let num1 = 0o49      //octal number
console.log(num1); // Invalid or unexpected token
 
 
            
                            
                        

But prior to ES6 the octal numbers are prefixed with 0

                            
num1 = 041      //octal number
console.log(num1); // 33
 
 
            
                            
                        

But invalid octal numbers like 049 are treated as decimal numbers

                            
num1 = 049 ;      //octal number
console.log(num1); // 49
 
 
            
                            
                        

You can still use the older syntax in ES6. But if you are using strict mode then using the older syntax will throw an error.

                            
"use strict"
 
num1 = 049 ;       // octal number
console.log(num1); // Decimals with leading zeros are not allowed in strict mode
 
 
            
                            
                        

Number Properties & Methods

Properties

Property Description
EPSILON The value of Number.EPSILON is the difference between 1 and the smallest value greater than 1 that is representable as a Number value, which is approximately: 2.2204460492503130808472633361816 x 10‍−‍16.
MAX_SAFE_INTEGER The value of the largest integer n such that n and n + 1 are both exactly representable as a Number value. The value of Number.MAX_SAFE_INTEGER is 9007199254740991 2^53 − 1.
MAX_VALUE The value of the largest integer n such that n and n + 1 are both exactly representable as a Number value. The value of Number.MAX_SAFE_INTEGER is 9007199254740991 2^53 − 1.
MIN_SAFE_INTEGER The value of the largest integer n such that n and n + 1 are both exactly representable as a Number value. The value of Number.MAX_SAFE_INTEGER is 9007199254740991 2^53 − 1.
MIN_VALUE The closest number to zero that can be represented in JavaScript. Equal to approximately 5.00E-324
NEGATIVE_INFINITY A value that is less than the largest negative number that can be represented in JavaScript. JavaScript displays NEGATIVE_INFINITY values as -infinity.
NaN A value that is not a number. In equality comparisons, NaN does not equal any value, including itself. To test whether a value is equivalent to NaN, use the isNaN function.
POSITIVE_INFINITY A value greater than the largest number that can be represented in JavaScript. JavaScript displays POSITIVE_INFINITY values as infinity.

Methods

Method Description
isFinite Returns true if passed value is finite. Unlike the global isFinite, Number.isFinite doesn't forcibly convert the parameter to a number. Only finite values of the type number, result in true.

@param number — A numeric value.
isInteger Returns true if the value passed is an integer, false otherwise.

@param number — A numeric value.
i``sNaN Returns a Boolean value that indicates whether a value is the reserved value NaN (not a number). Unlike the global isNaN(), Number.isNaN() doesn't forcefully convert the parameter to a number. Only values of the type number, that are also NaN, result in true.

@param number — A numeric value.
isSafeInteger Returns true if the value passed is a safe integer.

@param number — A numeric value.
parseInt Converts A string to an integer.

@param s — A string to convert into a number.

@param radix — A value between 2 and 36 that specifies the base of the number in numString. If this argument is not supplied, strings with a prefix of '0x' are considered hexadecimal. All other strings are considered decimal.
parseFloat Converts a string to a floating-point number.

@param string — A string that contains a floating-point number.

Instance Methods

Method Description
toExponential Returns a string containing a number represented in exponential notation.

@param fractionDigits — Number of digits after the decimal point. Must be in the range 0 - 20, inclusive.
toFixed Returns a string representing a number in fixed-point notation.

@param fractionDigits — Number of digits after the decimal point. Must be in the range 0 - 20, inclusive.
toLocaleString Converts a number to a string by using the current or specified locale.

@param locales — A locale string or array of locale strings that contain one or more language or locale tags. If you include more than one locale string, list them in descending order of priority so that the first entry is the preferred locale. If you omit this parameter, the default locale of the JavaScript runtime is used.

@param options — An object that contains one or more properties that specify comparison options.
toPrecision Returns a string containing a number represented either in exponential or fixed-point notation with a specified number of digits.

@param precision — Number of significant digits. Must be in the range 1 - 21, inclusive.
toString Returns a string representation of an object.

@param radix — Specifies a radix for converting numeric values to strings. This value is only used for numbers.
valueOf Returns the primitive value of the specified object.

Summary

The JavaScript number is a primitive data type stores the numbers as double-precision 64-bit number. The JavaScript also have Number object, which is a wrapper around primitive number. It is always suggested to use the primitive number. The Number object provides several properties, methods etc.

Read More

  1. JavaScript Tutorial
  2. Data Types in JavaScript
  3. JavaScript String
  4. Template Strings & String Interpolation
  5. Tagged Templates
  6. String to Number
  7. String
  8. NaN in JavaScript
  9. Min, Max & Safe Values
  10. EPSILON & Floating Point Precision
  11. Infinity
  12. BigInt
  13. BintInt Vs Number
  14. Boolean Data Type
  15. Undefined