11.7.1 The Left Shift Operator

2010-05-17

Do a bitwise shift on the left operation by the amount specified by the right operand.

ShiftExpression : ShiftExpression << AdditiveExpression

Code: (Meta Ecma)
function evaluate(ShiftExpression << AdditiveExpression) {
var lref = evaluate(ShiftExpression);
var lval = GetValue(lref);
var rref = evaluate(AdditiveExpression);
var rval = GetValue(rref);
var lnum = ToInt32(lval);
var rnum = ToInt32(rval);
var shiftCount = rnum & 0x1F; // only use first five bits (max 32 bits matter)
return lnum << shiftCount; // :) returns a 32bit signed integer
}

For example, take 14 << 3. 14 in binary is 00000000000000000000000000001110. Shifting that 3 bits to the left results in 00000000000000000000000001110000, which equals 112. Every shift equals a multiplication by 2 (14*2*2*2=112). This is often used as an alternative (and in the early computing days faster) way of multiplying a number by a power of two.

The sign of the number is not affected by this operation.

Code: (Meta Ecma)
var n = 500;
alert(n + " " + (n.toString(2))); // 500 111110100
alert((n<<5) + " " + ((n<<5).toString(2))); // 16000 11111010000000
alert((n<<6) + " " + ((n<<6).toString(2))); // 32000 111110100000000
n = -500;
alert(n + " " + (n.toString(2))); // -500 -111110100
alert((n<<5) + " " + ((n<<5).toString(2))); // -16000 -11111010000000
alert((n<<6) + " " + ((n<<6).toString(2))); // -32000 -111110100000000