How to Convert an Object to a Number in JavaScript?

In JavaScript, it is possible to convert an object to a number, given that the object implements either of the following (in the order as they appear below):

  1. [@@toPrimitive]();
  2. Object.prototype.valueOf().

Using [@@toPrimitive]()

You can use the built-in toPrimitive symbol to convert the object to a primitive, for example, like so:

const obj = {
  [Symbol.toPrimitive](hint) {
    if (hint === 'number') {
      return 12345;
    }

    return null;
  }
};

console.log(Number(obj)); // 12345
console.log(+obj); // 12345
console.log(Math.floor(obj)); // 12345

The hint argument to the function specifies the preferred type of the resulting primitive value (which can be one of "number", "string" and "default").

When you specify the return value for the "number" hint, it is used by numeric coercion algorithms (such as, the unary operator +, Number() wrapper object, Math methods, etc.). You can see this in the example above, where using the "hint === 'number'" condition lets you can specify what happens when the object is converted to a number.

You can implement the same in a class, for example, in the following way:

class Foo {
  [Symbol.toPrimitive](hint) {
    if (hint === 'number') {
      return 1234;
    }

    return null;
  }
}

const obj = new Foo();

console.log(Number(obj)); // 12345
console.log(+obj); // 12345
console.log(Math.floor(obj)); // 12345

Using Object.prototype.valueOf()

You can override the Object.prototype.valueOf() method, so that your object can be converted to a primitive value, returning a value that is most meaningful for the object.

Therefore, you can use the Object.prototype.valueOf() method to return a numeric value from an object whenever it's coerced to a number, for example, in the following way:

const obj = {
  valueOf() {
    return 12345;
  }
};

console.log(Number(obj)); // 12345
console.log(+obj); // 12345
console.log(Math.floor(obj)); // 12345

You can implement the same in a class, for example, like so:

class Foo {
  valueOf() {
    return 12345;
  }
}

const obj = new Foo();

console.log(Number(obj)); // 12345
console.log(+obj); // 12345
console.log(Math.floor(obj)); // 12345

Please note that Object.prototype.valueOf() does not provide you much control over the conversion as compared to [@@toPrimitive]() (which lets you return different values, based on the "hint").


This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.