JavaScript Number valueOf() Method
The JavaScript Number valueOf() method is used to retrieve the primitive value of a number. JavaScript usually calls this method internally and not explicitly in web code. We can invoke this method on a reference variable also on an object like Number.valueOf().
The JavaScript valueOf() method applies to various class objects such as String, Number, Array, TypedArray, and more.
Syntax
Following is the syntax of JavaScript Number valueOf() method −
valueOf()
Parameters
- It does not accept any parameters.
Return value
This method returns a number representing the primitive value of the specified "Number" object.
Example 1
The following example demonstrate the usage of the JavaScript Number valueOf() method.
<html>
<head>
<title>JavaScript Number valueOf() Method</title>
</head>
<body>
<script>
let n = Number.valueOf();
document.write("Primitive value = ", n);
</script>
</body>
</html>
Output
The following program will return the primitive value as −
Primitive value = function Number() { [native code] }
Example 2
The following is another example of the JavaScript Number valueOf() method. Using this method, we are trying to invoke this method on an instance of a number object to retrieve the primitive value of the number 10.
<html>
<head>
<title>JavaScript valueOf() Method</title>
</head>
<body>
<script>
let newobj = new Number(10);
document.write("Type = " , typeof(newobj));
//using valueOf() method..
const num = newobj.valueOf();
document.write("<br>Value of num = ",num);
document.write("<br>Type of num variable = ", typeof(num));
</script>
</body>
</html>
Output
Once the above program is executed, it will produce the following output −
Type = object Value of num = 10 Type of num variable = number
Example 3
Let's invoke this method on a variable named n, which has the value 20 to retrieve the primitive value of this number.
<html>
<head>
<title>JavaScript valueOf() Method</title>
</head>
<body>
<script>
let numObj = new Number(20);
document.write("Number value = ", numObj);
let n = numObj.valueOf();
document.write("<br>Primitive value = ", n);
</script>
</body>
</html>
Output
The above program returns the primitive value as 20.
Number value = 20 Primitive value = 20