2

I know this is silly but anyways I came across this code here in SO.

var total = 0;
for (var i = 0; i < someArray.length; i++) {
   total += someArray[i] << 0;
}

This is getting the sum of array's values. But i do not understand the last line.

total += someArray[i] << 0;
               //-----^^--here

What << means ? am i missing something all this while. and yes!! why <<.

bipen
  • 36,319
  • 9
  • 49
  • 62
  • 1
    See this answer - http://stackoverflow.com/a/1828469/1586880 – dsgriffin Jun 20 '13 at 21:18
  • 1
    Bitwise left shift: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Bitwise_Operators – Ian Jun 20 '13 at 21:18
  • Guys, I suppose the answer should explain **why** `<< 0` – zerkms Jun 20 '13 at 21:18
  • 2
    @zerkms I agree, but the OP doesn't seem to ask that, even though that definitely seems to be the concern – Ian Jun 20 '13 at 21:19
  • @user2246674 I never said they shouldn't :) I agree with that 100%! I was just pointing out what the OP literally said – Ian Jun 20 '13 at 21:20
  • What are the contents of `someArray`? It either is used to cast numbers to 32-bit integers, or oddly to convert strings to numbers – Bergi Jun 20 '13 at 21:20

3 Answers3

7

The next question would be "why << 0"?

All bitwise / bitshift operators in JavaScript invoke [ToInt32] on both arguments.

Thus, x << 0 (as in this case), x | 0, and ~~x have the effect of coercing the value to an integer within [0, 2^32).

Compare this to +x which merely coerces x into a number.

user2246674
  • 7,621
  • 25
  • 28
5

<< and >> are bitshift operations, taking an integer number and shifting all the bits left (<<) or right (>>) by 1 bit. If followed by another number, the shift happens for that many bits, so 256 << 4 shifts the bitpatter for 256 left by 4 bits (filling the bit patter from the right with four zeros).

Most programming languages support these operators, and you usually have no reason to use them unless you're writing code that has to act on bit patterns for (usually super-fast) integer operations.

As a nice quirk in JavaScript, if you apply bitwise operations to a number, it gets forced to an integer, so shifting by 0 bits, or taking the or operation with 0, ... | 0 will turn "a number" into an 32 bit integer number.

Mike 'Pomax' Kamermans
  • 49,297
  • 16
  • 112
  • 153
1

In your example, the left-shift bitwise operator is being used to force the value into a 32-bit integer. From the MDN page I just linked:

Shift operators convert their operands to 32-bit integers in big-endian order and return a result of the same type as the left operand.

Usually, numbers in JavaScript are double precision floats.

bfavaretto
  • 71,580
  • 16
  • 111
  • 150