Enforce the use of Math.trunc instead of bitwise operators ​
💼 This rule is enabled in the ✅ recommended config.
🔧💡 This rule is automatically fixable by the --fix CLI option and manually fixable by editor suggestions.
Enforces a convention of using Math.trunc() instead of bitwise operations for clarity and more reliable results. It prevents the use of the following bitwise operations:
x | 0(bitwise ORwith 0)~~x(twobitwise NOT)x >> 0(Signed Right Shiftwith 0)x << 0(Left Shiftwith 0)x ^ 0(bitwise XOR Shiftwith 0)
These hacks help truncate numbers but they are not clear and do not work in some cases.
This rule is fixable, unless the left-hand side in assignment has side effect.
Fail ​
js
const foo = 37.4;
console.log(foo | 0);js
const foo = 37.4;
console.log(~~bar);js
let foo = 37.4;
foo |= 0;js
const foo = 37.4;
console.log(foo << 0);js
const foo = 37.4;
console.log(foo >> 0);js
const foo = {bar: 37.4};
console.log(foo.bar ^ 0);Pass ​
js
const foo = 37.4;
console.log(Math.trunc(foo));js
const foo = 37.4;
console.log(foo | 3);js
let foo = 37.4;
foo = Math.trunc(foo);js
const foo = 37.4;
console.log(~foo);js
const foo = 37.4;
console.log(foo >> 3);js
const foo = 37.4;
console.log(foo << 3);js
const foo = 37.4;
console.log(foo ^ 3);