I read an article on coercing objects to primitives and it said that JavaScript first tries to convert an object to a string. If it fails, then it tries to convert it to a number. But I can’t imagine converting an object to a number, or does it mean arrays? Since arrays are objects it’s totally clear to me. But if it means objects like obj = {a: 1} then I’d like to get some examples, please.
>Solution :
Indeed it does convert, but only for an object that has a valueOf mehtod that returns a number or a numeric string (e.g., "234") or a toString method that also returns a numeric string. Otherwise you’ll get a NaN which means Not a Number but ironically typeof NaN = "number".
const obj = {
valueOf: () => 234
}
// credit: @pilchard
const another_obj = {
toString: () => "123"
}
const num_a = +obj;
const num_b = +another_obj;
console.log(num_a, num_b);