0

I'm working with JS, I was trying to implement an algorithm while I realize that I could use myVar & 1 to return 0 or 1 according to the parity of the number in myVar.

var a = 0 & 1;
var b = 1 & 1;
var c = 42 & 1;
var d = 65 & 1;

console.log(a); //display 0
console.log(b); //display 1
console.log(c); //display 0
console.log(d); //display 1

https://jsfiddle.net/bzjvpyjk/

I don't understand what's happening behind it. How does it work?

Is it clear or even useful to do it?

Alex
  • 2,927
  • 8
  • 37
  • 56

1 Answers1

1
// 9 is 00000000000000000000000000001001
var expr1 = 9;

// 5 is 00000000000000000000000000000101
var expr2 = 5;

// 1 is 00000000000000000000000000000001
var result = expr1 & expr2;// performing and(&) operation

 document.write(result);
// Output: 1

For more info https://msdn.microsoft.com/en-us/library/dazfy1f3(v=vs.94).aspx

Anoop LL
  • 1,548
  • 2
  • 21
  • 32