What You'll Learn
You'll learn how the left shift operator (<<) slides bits to the left in binary, filling empty spots with zeros—a fast way to multiply by powers of 2.
How Left Shift Works
The left shift operator (<<) takes a number, looks at its binary representation, and physically moves all the bits to the left by a specified number of positions. The empty spaces on the right get filled with zeros.
Think of it like a conveyor belt: if you have items lined up and shift them all one position to the left, new empty spots appear on the right. In binary, those empty spots become zeros.
The Syntax
let result = number << positions;
The number is what you're shifting, and positions tells how many spots to move left.
Examples in Action
let x = 5; // Binary: 101
let shifted = x << 1; // Binary: 1010 (which is 10)
// 5 shifted left by 1 becomes 10
let y = 3; // Binary: 11
let result = y << 2; // Binary: 1100 (which is 12)
// 3 shifted left by 2 becomes 12
The Multiplication Pattern
Each left shift by one position doubles the number (multiplies by 2). Shifting by two positions multiplies by 4 (2²). Shifting by three multiplies by 8 (2³).
let a = 7;
console.log(a << 1); // 14 (7 × 2)
console.log(a << 2); // 28 (7 × 4)
console.log(a << 3); // 56 (7 × 8)
This happens because in binary, moving digits left increases their place value—just like in decimal, 5 becomes 50 when you "shift" it left and add a zero.
When Bits "Fall Off"
JavaScript uses 32-bit signed integers for bitwise operations. If bits shift beyond the 32nd position, they simply disappear off the left edge.
Key Takeaway: The left shift operator (<<) moves bits left, filling with zeros, and effectively multiplies your number by 2 for each position shifted.