Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Coercing an object to a number – how is it?

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading