TreeviewCopyright © aleen42 all right reserved, powered by aleen42

Type Casting & Coercion Back

1. Strings

const reviewScrore = 9;

/**
 * bad
 */
const totalScore = reviewScore + '';

/**
 * good
 */
const totalScore = String(reviewScore);

2. Numbers

  • To use Number for type casting and parseInt always with a radix for parsing strings.
const inputValue = '4';

/**
 * bad
 */
const val = new Number(inputValue);
const val = +inputValue;
const val = parseInt(inputValue);

/**
 * good
 */
const val = Number(inputValue);
const val = parseInt(inputValue, 10);
  • 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.
/**
 * parseInt was the reason my code was slow.
 * Bitshifting the String to coerce it to a
 * Number made it a lot faster.
 */
const val = inputValue >> 0;
  • Notice that: when using Bitshift, you should care more about the problem of overflow
/**
 * Largest signed 32-bit Int is 2,147,483,647
 */
2147483647 >> 0 /** => 2147483647   */
2147483648 >> 0 /** => -2147483648  */
2147483649 >> 0 /** => -2147483647  */

3. Booleans

const age = 0;

/**
 * bad
 */
const hasAge = new Boolean(age);

/**
 * good
 */
const hasAge = Boolean(age);
const hasAge = !!age;

results matching ""

    No results matching ""