Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does i << 1 mean in Javascript? [duplicate]

I was going through some code for prime numbers on Stack and found this.

I tried experimenting with this for sometime and figured this :

var i = 5;
var j = 0;

If i write j = i << 1, all it does is assigns (i * 2) ie - 10 in this case to j

If i write j = i << 2, (i * 2) * 2 ie - 10 * 2 .....and so on.

Now i have a doubt what actually this operator does ?

I tried googling this, but did not find any straight solution to this.

like image 402
Janak Avatar asked Aug 01 '26 13:08

Janak


1 Answers

Those are Bitwise Operators in Javascript.

Bitwise operators treat their operands as a sequence of 32 bits (zeros and ones), rather than as decimal, hexadecimal, or octal numbers. For example, the decimal number nine has a binary representation of 1001. Bitwise operators perform their operations on such binary representations, but they return standard JavaScript numerical values.

Left Shift Operator :

a << b : Shifts a in binary representation b (< 32) bits to the left, shifting in zeros from the right.

like image 64
AllTooSir Avatar answered Aug 04 '26 02:08

AllTooSir



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!