The Object valueOf() method

By

Learn how the JavaScript valueOf() method returns the primitive value of an object, a feature normally used internally by JavaScript and rarely by you.

~~~

Called on an object instance, valueOf() returns the primitive value of it.

A plain object has no primitive value to return, so you get back the object itself:

const person = { name: 'Fred' }
person.valueOf() //{ name: 'Fred' }
person.valueOf() === person //true

This is normally only used internally by JavaScript, and rarely actually invoked in user code.

When does JavaScript call it?

Whenever the language needs to turn an object into a primitive value. Arithmetic is the most common case. If you add an object to a number, JavaScript calls valueOf() on the object behind the scenes.

Built-in wrapper objects override it to return the primitive they wrap. Date is a good example. Its valueOf() returns the timestamp in milliseconds:

const date = new Date('2026-08-07')
date.valueOf() //1786060800000

That’s why you can subtract two dates and get the difference in milliseconds. The subtraction operator converts both dates using valueOf().

Defining your own valueOf()

You can override valueOf() on your own objects. Suppose you have an object that represents a price:

const price = {
  amount: 42,
  valueOf() {
    return this.amount
  }
}

price + 8 //50
price * 2 //84

Every math operation now uses 42 as the value of the object. No need to write price.amount each time.

Be careful with string conversion

You might expect valueOf() to run when you put the object in a template literal. It doesn’t:

`${price}` //'[object Object]'

When JavaScript converts an object to a string, it tries toString() first, and toString() always exists on objects. So your valueOf() never gets a chance to run.

The fix is to define toString() too:

const price = {
  amount: 42,
  valueOf() {
    return this.amount
  },
  toString() {
    return this.amount + ' EUR'
  }
}

`${price}` //'42 EUR'
price + 8 //50

Now string contexts use toString(), and numeric contexts use valueOf().

That said, in most real code you won’t need any of this. Reading price.amount explicitly is clearer than relying on implicit conversion. Knowing how valueOf() works matters most when you’re debugging a weird coercion, not when you’re designing an API.

~~~

Related posts about js: