Javascript - Bitwise Left Shift

Introduction

The bitwise left shift operator is << and it shifts all bits in a number to the left by the number of positions.

The following code shifts bits on the number 2 to left for 5 bits.

     10  //2
1000000  //64

var oldValue = 2;             //equal to binary 10 
var newValue = oldValue << 5; //equal to binary 1000000 which is decimal 64 

When the bits are shifted, left shift fills the empty bits with 0s to make the result a complete 32-bit number.

The number 2 
0   0   0   0   0   0   0   0   0   0  0   0   0   0   1   0 
The number 2 shifted to the left five bits (the number 64) 
0   0   0   0   0   0   0   0   0   1  0   0   0   0   0   0 
                                           Padded with zeros 

The left shift preserves the sign of the number. For instance, if -2 is shifted to the left by five spaces, it becomes -64, not positive 64.

Related Topic