CodeQL documentation

Shift out of range

ID: js/shift-out-of-range
Kind: problem
Security severity: 
Severity: error
Precision: very-high
Tags:
   - reliability
   - correctness
   - external/cwe/cwe-197
Query suites:
   - javascript-security-and-quality.qls

Click to see the query in the CodeQL repository

Shift operations in JavaScript operate on 32-bit values only, so it is not possible to shift by more than 31 positions. If the right operand of a shift operator is greater than 31, the left operand is actually only shifted by that value modulo 32.

Recommendation

Use standard library functions such as Math.pow to perform the required shifting. Alternatively, you can use the BigInt type if it is available on your platform.

Example

The following code snippet attempts to assign x the value 240 (1099511627776). In fact, however, the left operand 1 is only shifted by 8 (that is, 40 modulo 32), so x ends up being assigned the value 28 (256).

var x = 1<<40;

A better solution would be to use Math.pow as follows:

var x = Math.pow(2, 40);

Note, however, that JavaScript internally represents large numbers as floating point numbers, so numbers with a magnitude larger than 253 will be represented imprecisely.

References

  • © GitHub, Inc.
  • Terms
  • Privacy