javascripttypescript2.4

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


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?


Solution

  • 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