I’ve written a code and the result surprises me.
for(var i = 0; i < 6; i++) {
console.log(i & 2)
}
For this code, it says: 0 0 2 2 0 0
I don’t understand why doesn’t it say: 0 1 0 1 0 1
Can someone explain to me please? (Also please tell me how can I get the modulo of the i-s, which would be 0 1 0 1 0 1.)
Thank you!
The code you want:
for( var i=0; i<6; i++) {
console.log(i%2)
}
The “&” operator is a “bitwise” operator. It was executing a logical AND.
if you are familiar with binary digits, this tells you what you where doing:
000 AND 010 = 000 (binary) = 0 (decimal)
001 AND 010 = 000 (binary) = 0 (decimal)
010 AND 010 = 010 (binary) = 2 (decimal)
011 AND 010 = 010 (binary) = 2 (decimal)
100 AND 010 = 000 (binary) = 0 (decimal)
101 AND 010 = 000 (binary) = 0 (decimal)
More on javascript operators Here: http://www.w3schools.com/js/js_comparisons.asp