Understanding Bitwise Shifts in JavaScript: << and >>
A practical guide to left and right shift operators in JavaScript
Bitwise operators are powerful but often overlooked features in JavaScript. While they’re not common in everyday web development, understanding them can unlock performance optimizations and help you better understand how computers handle numbers at a low level.
What Are <<
and >>
?
<<
(left shift) and >>
(right shift) are operators that move bits left or right in a number’s binary representation.
// Left Shift (<<)
let num = 5; // Binary: 00000101
let shifted = num << 1; // Binary: 00001010 (decimal: 10)
// Right Shift (>>)
let num2 = 10; // Binary: 00001010
let shifted2 = num2 >> 1; // Binary: 00000101 (decimal: 5)
Left Shift <<
: Quick Multiplication
Left shifting multiplies a number by 2 for each position shifted: