Number(id) or +id result in different values depending on the input value

43 views Asked by At
id: number;

this.id = +id;

When local id is null then +id results in 0
When local id is undfined then +id results in NaN

The same results I get with Number(id) instead of the +id

How can I get consistent/same return value for the not successful conversion into a number?

1

There are 1 answers

1
adeneo On BEST ANSWER

As both 0, null, NaN and undefined are falsy, you could just set the value to something if it's falsy

this.id = (+id) || 0;

console.log( (+0) || 0 )           // 0
console.log( (+null) || 0 )        // 0
console.log( (+undefined) || 0 )   // 0