0

I'm trying to understand the valueOf() method.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/valueOf

Is there a situation where a variable of any type could return false for the following check ?

x.valueOf() === x

const obj = {};
const str = "abc";
const strNum = "123";
const number = 123;
const arrStr = ["a","b","c"];
const arrNum = [1,2,3];

console.log(obj.valueOf() === obj);
console.log(str.valueOf() === str);
console.log(strNum.valueOf() === strNum);
console.log(number.valueOf() === number);
console.log(arrStr.valueOf() === arrStr);
console.log(arrNum.valueOf() === arrNum);
cbdeveloper
  • 27,898
  • 37
  • 155
  • 336

1 Answers1

2

A variable with a custom valueOf method could return a value which fails the test:

const obj = {
  valueOf() {
    return NaN;
  }
};
console.log(obj.valueOf() === obj);

A number wrapped in an object would also return false:

const obj = new Number(5);
console.log(obj.valueOf() === obj);

The MDN documentation looks misleading. Object.prototype.valueOf will return an object or throw an error - see the specification.

Keep in mind that when calling valueOf on non-objects, like numbers/strings/booleans, you'll be invoking the valueOf method of that particular primitive (eg Number.prototype.valueOf), rather than Object.prototype.valueOf.

CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
  • Thanks. But with the standard `valueOf()` method it will be always `true` ? – cbdeveloper Mar 18 '20 at 09:47
  • 1
    @cbdeveloper *if* you're calling the standard one from the Object prototype. That's not at all guaranteed, for example `Object.create(null)` will produce a plain object without a `valueOf` method, since there will be no prototype. So, you'd get an error when calling `noProtoObj.valueOf()` – VLAZ Mar 18 '20 at 09:49
  • @VLAZ thanks! There's still one thing I don't understand: [MDN says](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/valueOf) : _The valueOf() method returns the **primitive value** of the specified object._. If objects are not primitive values, how can objects are returned from the `valueOf` method? The primitive value of an object is the object itself? – cbdeveloper Mar 18 '20 at 09:52
  • @cbdeveloper a further paragraph answers that: "*If an object has no primitive value, valueOf returns the object itself.*" – VLAZ Mar 18 '20 at 09:53
  • @VLAZ my bad! Will read the doc more carefully next time! Thanks a lot VLAZ – cbdeveloper Mar 18 '20 at 09:58