0
let obj = {
    toString() {
        return "2";
    }
};

let n = +obj; 

alert(n);

Since +obj requires a number, shouldn't it use the valueOf() prototype for type conversion which returns the object. Instead it uses the toString() method and alerts 2. Please why is this so?

Israel
  • 77
  • 7

2 Answers2

2

Since +obj requires a number, shouldn't it use the valueOf() prototype for type conversion which returns the object.

It actually does call the valueOf method. But since - as you say - it returns an object, not a primitive value, it is found useless. Then, the alternative is called: toString(), which does return a primitive value that is subsequently cast to a number.

You can try

const obj1 = {
    valueOf() { console.log("valueOf 1"); return this; },
    toString() { console.log("toString 1"); return "1"; },
};
console.log(+obj1);

const obj2 = {
    valueOf() { console.log("valueOf 2"); return 2; },
    toString() { console.log("toString 2"); return "2"; },
};
console.log(+obj2);
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
-2

Your should to change de toString() function by parseInt() function to get NaN response.

let obj = {
    parseInt() {
        return "2";
    }
};

let n = +obj; 

alert(n);
judlup
  • 119
  • 2
  • 15