The left shift "<<" operator
x << y
, shifts x
left by y
bits
shifting 9 (which in binary is 1001
) one bit left results in 10010 (*.toString(2) renders the binary representation)
GIVEN both operands are numbers
WHEN shifting a number left by 0 bits THEN the number stays the same
WHEN shifting 2
left by 1 bit THEN it is like multiplying it by 2, it becomes 4
WHEN shifting the binary 8 (0b1000) two bits left THEN it becomes 32 (0b10_0000)
WHEN shifting a negative number THEN it is like multiplying it by 2**n (2 to the power of n)
GIVEN the operands are NOT only numbers
WHEN bit shifting a string THEN the left operand is coerced (converted) to a number first
WHEN shifting NaN
THEN it is first converted to a 0 and then shifted, so it stays 0
WHEN shifting undefined
THEN it is first converted to 0 and then shifted, so it stays 0
WHEN shifting a number larger than 32 bits THEN it is converted to a 32 bit integer number first
Links
The original ECMAScript 1 specification, "The left shift operator ( << )" is on page 44, chapter 11.7.1 (in a 110 pages PDF).
The MDN page.
Mastodon toot about starting to dive into the rabbit hole about writing this kata.
Related Katas
Unary Operators
Bitwise Shift Operators
- Left Shift "<<"
- Right Shift ">>"
- All bitwise shift operators
Rest operator
Spread operator
Difficulty Level
INTERMEDIATE
First Published
1 September 2023
Stats
10 tests to solve