converting an object to a number
When converting an object to a number it will first check if the valueOf()
method exists if it does and returns a primitive that will will be used.
JavaScript
const a = {
valueOf: function () {
return '12';
}
};
Number(a); // 12
If valueOf()
method doesn’t exist or doesn’t return a primitive value it will check if it has a toString()
method and use the returned value.
JavaScript
const b = {
toString: function () {
return 20;
}
};
Number(b); // 20
const c = {
valueOf: function () {
return function s() {};
},
toString: function () {
return '2';
}
};
Number(c); // 2
If none of the attempts to convert an object to a number can find a primitive value, a TypeError will be thrown.
JavaScript
const d = Object.create(null);
Number(d); // Uncaught TypeError: Cannot convert object to primitive value