What is the bitwise left-shift (<<) operator in JavaScipt?

Overview

The left-shift operator or the bitwise left-shift operator (<<) in JavaScript shifts each bit of a binary to the left by n positions. The zeros of the bits are shifted from the right to the left and the leftmost bits will fall off.

For instance, 2 << 1 tells JavaScript to shift the bits of 2 to the left by 1. Hence, 2, which is 0010, will become 0100.

Syntax

number << noOfShifts
The syntax for left-shift operator in Ruby

Parameters

number: This is the number we want to shift the bits of.

noOfShifts: This is the number of times we want to left-shift the bits of the number number.

Return value

It returns an integer that is the decimal equivalent of the binary gotten after the shifting.

Example

// shift the binary bits of some numbers
console.log(2 << 1)
console.log(10 << 2)
console.log(900 << 2)
console.log(5 << 3)
console.log(200 << 10)

Explanation

  • Lines 2–6: We use the bitwise left shift operator to shift the bits of some numbers. Next, we log the results to the console.

Copyright ©2024 Educative, Inc. All rights reserved