The Number valueOf() method

By

Learn how the JavaScript Number valueOf() method returns the primitive number value wrapped inside a Number object, turning that object back into a number.

~~~

valueOf() returns the primitive number value wrapped inside a Number object:

const age = new Number(36)
typeof age //object
age.valueOf() //36
typeof age.valueOf() //number

Why does this method exist?

Numbers in JavaScript come in two forms. There are primitive values, like 36, and there are Number objects, created with the new Number() constructor.

You almost always work with primitives. When you call a method on one, like (36).toFixed(2), JavaScript wraps the primitive in a temporary Number object, calls the method, then throws the wrapper away.

valueOf() goes in the other direction. It unwraps a Number object and hands you back the primitive.

When JavaScript calls it for you

You rarely call valueOf() yourself. JavaScript calls it automatically whenever an object needs to act as a number, for example in a math operation:

const price = new Number(20)
price + 5 //25

The + operator asked the object for its primitive value, and valueOf() provided it.

You can use the same mechanism in your own objects. Give an object a valueOf() method and it can take part in math:

const cart = {
  items: 3,
  valueOf() {
    return this.items
  }
}

cart * 10 //30

Be careful comparing Number objects

Here’s the pitfall. Objects are compared by reference, not by value:

const a = new Number(36)
const b = new Number(36)

a === b //false
a === 36 //false
a.valueOf() === 36 //true

Two Number objects are never strictly equal, even when they wrap the same value. The second comparison fails too, because === never converts an object to a primitive.

There’s a related trap with conditionals. Objects are always truthy, so new Number(0) passes an if check, while the primitive 0 does not.

The real fix is to avoid new Number() entirely. Use plain literals, and when you need to convert a string to a number, call Number() without new:

Number('36') //36, a primitive

In practice you’ll reach for valueOf() when an old library hands you a Number object and you want a clean primitive to compare or store.

~~~

Related posts about js: