Description

The JavaScript Number method valueOf() returns the primitive value of a number, without changing the original number.

  • It returns a new number and doesn't change the original number.
  • It is commonly used to convert a number object to a primitive number.
  • It is the default method for JavaScript strings and is used internally by JavaScript.

Syntax

The method valueOf() has the below syntax, where num is a string.

num.valueOf()

Parameters

The method valueOf() doesn't allow any parameters.

Result

Returns the primitive value of a number, without changing the original number.

Example 1: Using the Method

The below example shows the basic usage of the method.

var num = 1234;
var numObject = new Number(5678);

// Without using the method
console.log(num);             // Prints: 1234
console.log(numObject);       // Prints: 5678

// Getting the value of a number
console.log(num.valueOf());         // Prints: 1234
console.log(numObject.valueOf());   // Prints: 5678

console.log(Infinity.valueOf());   // Prints: Infinity
console.log(NaN.valueOf());        // Prints: NaN

Output:

1234
5678
1234
5678
Infinity
NaN

Overall

The JavaScript Number method valueOf() returns the primitive value of a number, without changing the original number.

Related Links