The left-shift operator or the bitwise left-shift operator (<<
) in JavaScript shifts each bit of a binary to the left by n
positions. The zeros of the bits are shifted from the right to the left and the leftmost bits will fall off.
For instance, 2 << 1
tells JavaScript to shift the bits of 2 to the left by 1. Hence, 2, which is 0010
, will become 0100
.
number << noOfShifts
number
: This is the number we want to shift the bits of.
noOfShifts
: This is the number of times we want to left-shift the bits of the number number
.
It returns an integer that is the decimal equivalent of the binary gotten after the shifting.
// shift the binary bits of some numbersconsole.log(2 << 1)console.log(10 << 2)console.log(900 << 2)console.log(5 << 3)console.log(200 << 10)
Lines 2–6: We use the bitwise left shift operator to shift the bits of some numbers. Next, we log the results to the console.