Open In App

JavaScript Number() Constructor

Last Updated : 24 May, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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: 

  • object: This parameter holds the objects that will be converted to any type of javascript variable to number type. 

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

Javascript




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.

Javascript




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. 

Javascript




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.

Javascript




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:

  • Google Chrome
  • Firefox
  • Internet Explorer
  • Safari
  • Opera

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



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads