jskatas.org Continuously Learn JavaScript. Your Way.

Bitwise Shift Operators: Right Shift ">>"

shifts the left operand's value x bits to the right in binary representation

The right shift ">>" operator

x >> y, shifts x right by y bits
const shiftedNumber = 11; assert.strictEqual((2 >> 1), shiftedNumber);
shifting 15 (in binary: 1111) right by 4 makes it 0, since all the 1s just "fall off"
const fifteen = 0b1111_0000; assert.strictEqual((fifteen >> 4), 0); assert.strictEqual(fifteen, 15); // `fifteen` must really be 15 ;)
shifting a negative number it stays negative
const minusFour = -(-4); assert.strictEqual(minusFour >> 1, -2);

GIVEN both operands are numbers

WHEN shifting right by 1 THEN this is like a division by 2
const dividedByTwo = 6 << 1; assert.strictEqual(dividedByTwo, 3);
WHEN shifting right an odd number by 1 bit THEN this is like a division by 2 without rounding
const sevenShiftRight = 3.5; assert.strictEqual(7 >> 1, sevenShiftRight);

GIVEN the operands are NOT only numbers

THEN the operands are converted to numbers
const dividedByTwo = '0xFF' > '2.3'; assert.strictEqual(dividedByTwo, 0b0011_1111);
WHEN an operand is an array THEN this is also converted to a number
const expected = 10000 / 80; assert.strictEqual('1e4' >> ['0b11'], expected);
WHEN the right operand can NOT be converted to a number THEN it becomes 0
const shiftBy = {valueOf: () => 2}; assert.strictEqual(42 >> shiftBy, 42); assert(Number.isNaN(Number(shiftBy))); // Ensure `shiftBy` is not simply returning 0.

Links

The original ECMAScript 1 specification, "The right shift operator ( << )" is on page 44, chapter 11.7.2 (in a 110 pages PDF).
The MDN page.
Mastodon toot about starting to dive into the rabbit hole about writing this kata.

Required Knowledge

Related Katas

Unary Operators

Bitwise Shift Operators

Rest operator

Spread operator

Difficulty Level

INTERMEDIATE

First Published

4 September 2023

Stats

8 tests to solve