Search code examples
javascriptprimitiveprimitive-typesvalue-of

Are there any cases where `x.valueOf() === x` could return `false`?


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);


Solution

  • 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.