-2

I am looking through the source of a library I'm working with, and I found something I haven't seen before.

$(item).each(function(child) {
        oddEven = (i & 1);
        targetNode.append(jasper_build_product(this,oddEven));
        i++;
    });

Notice the oddEven = (i & 1);. What does the (i & 1) part do? I'm particularly curious about the ampersand.

Lansana Camara
  • 8,225
  • 8
  • 36
  • 74
  • @AD7six not a duplicate, IMHO – Alnitak Jun 30 '16 at 13:07
  • For reference: [Bitwise AND](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/Bitwise_Operators#Bitwise_AND) – Rajesh Jun 30 '16 at 13:09
  • @Alnitak I'm interested as to your reasoning given the question is what the & means, not necessarily how that determines odd/even (which understanding & answers). – AD7six Jun 30 '16 at 13:13

1 Answers1

2

The & operator is a bitwise AND, and more specifically the expression x & 1 returns the least significant bit (LSB) of the value x.

Since the internal representation of numbers is base-2, an LSB of 1 indicates an odd value, and 0 indicates an even value.

Alnitak
  • 313,276
  • 69
  • 379
  • 466
  • Less technically: `0b0001 & 0b0001` yields 1 (`0b0001` is the binary representation of 1) and `0b0001 & 0b0010` yields 0 (`0b0010` is the binary representation of 2) –  Jun 30 '16 at 13:10
  • @LUH3417 I'm not sure I agree that this is "less technical" :p – Alnitak Jun 30 '16 at 13:10
  • OK, agreed - it's just a different representation of a complicated issue –  Jun 30 '16 at 13:15