JavaScript: Number valueOf() method
This JavaScript tutorial explains how to use the Number method called valueOf() with syntax and examples.
Description
In JavaScript, valueOf() is a Number method that is used to return the primitive value of a Number object. Because valueOf() is a method of the Number object, it must be invoked through a particular instance of the Number class.
Syntax
In JavaScript, the syntax for the valueOf() method is:
number.valueOf();
Parameters or Arguments
There are no parameters or arguments for the valueOf() method.
Returns
The valueOf() method returns the primitive value of the calling Number object.
Note
- The valueOf() method does not change the value of the original number.
Example
Let's take a look at an example of how to use the valueOf() method in JavaScript.
For example:
var totn_number = new Number(123);
console.log(totn_number);
console.log(totn_number.valueOf());
In this example, we have declared a Number object called totn_number that is assigned the value of 123. We have then invoked the valueOf() method of the totn_number variable to return its primitive value.
We have written the output of the valueOf() method to the web browser console log, for demonstration purposes, to show what the valueOf() method returns.
The following will be output to the web browser console log:
Number {123} 123
In this example, the first output to the console log shows the Number object. Whereas, the second output to the console log shows 123 which is the primitive value of the totn_number Number object.
Advertisements