Type Casting & Coercion

  • 22.1 Perform type coercion at the beginning of the statement.

  • 22.2 Strings: eslint: no-new-wrappers

    1. // => this.reviewScore = 9;
    2. // bad
    3. const totalScore = new String(this.reviewScore); // typeof totalScore is "object" not "string"
    4. // bad
    5. const totalScore = this.reviewScore + ''; // invokes this.reviewScore.valueOf()
    6. // bad
    7. const totalScore = this.reviewScore.toString(); // isn’t guaranteed to return a string
    8. // good
    9. const totalScore = String(this.reviewScore);

  • 22.3 Numbers: Use Number for type casting and parseInt always with a radix for parsing strings. eslint: radix no-new-wrappers

    1. const inputValue = '4';
    2. // bad
    3. const val = new Number(inputValue);
    4. // bad
    5. const val = +inputValue;
    6. // bad
    7. const val = inputValue >> 0;
    8. // bad
    9. const val = parseInt(inputValue);
    10. // good
    11. const val = Number(inputValue);
    12. // good
    13. const val = parseInt(inputValue, 10);

  • 22.4 If for whatever reason you are doing something wild and parseInt is your bottleneck and need to use Bitshift for performance reasons, leave a comment explaining why and what you’re doing.

    1. // good
    2. /**
    3. * parseInt was the reason my code was slow.
    4. * Bitshifting the String to coerce it to a
    5. * Number made it a lot faster.
    6. */
    7. const val = inputValue >> 0;

  • 22.5 Note: Be careful when using bitshift operations. Numbers are represented as 64-bit values, but bitshift operations always return a 32-bit integer (source). Bitshift can lead to unexpected behavior for integer values larger than 32 bits. Discussion. Largest signed 32-bit Int is 2,147,483,647:

    1. 2147483647 >> 0; // => 2147483647
    2. 2147483648 >> 0; // => -2147483648
    3. 2147483649 >> 0; // => -2147483647

  • 22.6 Booleans: eslint: no-new-wrappers

    1. const age = 0;
    2. // bad
    3. const hasAge = new Boolean(age);
    4. // good
    5. const hasAge = Boolean(age);
    6. // best
    7. const hasAge = !!age;