Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript syntax: variable declaration with "<<" or ">>"

I had a look at Jason Davies's Word Cloud source on Github and within the index.js there are some variables that are declared like this:

cw = 1 << 11 >> 5,
ch = 1 << 11;

I noticed this pattern: value before "<<" multiplies the value after "<<";
value after "<<" is a 2 to the power of the value specified;
value after ">>" (following "<<") divides that number before (which is also 2 two the power of the value);

I was curious:

  1. in general what are the uses for this type of declaration and where does it come from

  2. how does it add value to the code in the rest of the Jason Davies' layout?

like image 494
vzR Avatar asked Jul 19 '26 19:07

vzR


1 Answers

See this link

Basically, << and >> do bit-wise shifts. If you do a << b, it will represent a as a number in base 2 (0s and 1s) and shift all the digits to the left by b positions. This is mathematically equivalent to

a * 2^b

The >> is the same principle, but it shifts to the right. It's almost analogous to a division by a factor of 2, but there's a special case when the intial number is odd: it floors the result.

⌊(a / 2^b)⌋

If you have 1 << 11 >> 5, the left and right shifts cancel each other, we end up in reality with

1 << 6 === 64 === 1 * 2^6
like image 180
jonathanGB Avatar answered Jul 22 '26 10:07

jonathanGB