Open In App

JavaScript Number() Constructor

Javascript Number() Constructor is used to create a new number object but, if we call it as a function on another data type it will perform type conversion to number if possible.

Syntax:



Number(object)

Parameters: This function accepts a single parameter as mentioned above and described below: 

Return Values: The number() constructor returns the number format for any type of javascript variable.



Below are examples of the Number() Constructor:

Example 1: In this example, we will create a new number using Number Constructor




function func() {
    let a = new Number(5);
    console.log(a);
}
func();

Output:

Number {5}

Example 2: In this example, we will convert a  Number String to Number using Number constructor as a function.




function func() {
    // Original string
    let a = "10";
     
    let value = Number(a);
    console.log(value);
}
func();

Output:

10

Example 3: In this example, we will convert the date into a number, and the conversion will return the converted date in milliseconds. 




function func() {
    let value = Number(new Date("2017-09-30"));
    console.log(value);
}
func();

Output:

1506729600000

Example 4: In this example, we will convert a  Non-Number String to a Number using the Number constructor as a function.




function func() {
    let value = Number("John");
    console.log(value);
}
func();

Output: The conversion fails as no number value is detected when conversion takes place

NaN

Supported Browsers:

We have a complete list of JavaScript Number constructor, properties, and methods list, to know more about the numbers please go through that article.


Article Tags :