Type Casting & Coercion
- Perform type coercion at the beginning of the statement.
- Strings:
const totalScore = this.reviewScore + '';
const totalScore = String(this.reviewScore);
- Numbers: Use
Number
for type casting and parseInt
always with a radix for parsing strings. eslint: radix
const inputValue = '4';
const val = new Number(inputValue);
const val = +inputValue;
const val = inputValue >> 0;
const val = parseInt(inputValue);
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.
const val = inputValue >> 0;
- 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:
2147483647 >> 0
2147483648 >> 0
2147483649 >> 0
const age = 0;
const hasAge = new Boolean(age);
const hasAge = Boolean(age);
const hasAge = !!age;