Right shift operator

Right shift operator?

In JavaScript, the right shift operator (>>) is a bitwise operator used to shift the bits of a number to the right by a specified number of positions. It performs a bitwise shift operation on the binary representation of the number.

Right shift operator example

const num = 12; // Binary representation: 1100
const shiftedRight = num >> 2; // Shifting right by 2 positions

console.log(shiftedRight); // Output: 3 (Binary representation: 0011)


// The right shift operator can be used to divide a number by a power of 2. For example, the following code divides 100 by 4 using the right shift operator:

const num = 100;
const dividedNum = num >> 2;
console.log(dividedNum); // Output: 25

Useful properties right shift operator:

Positive numbers: When using the right shift operator with positive numbers, it performs a logical shift to the right, adding zero bits to the left.
Negative numbers: For negative numbers, the right shift operator performs an arithmetic shift. It fills the vacant positions by copying the sign bit (the leftmost bit) so that the sign of the number remains the same.