Jasmine Butaka
Jasmine Butaka

Reputation: 9

Trouble figuring out Javascript & operator

So I am new to Javascript, in my first Intro to Javascript class. I just found what the & operator does and came across this definition:

The & operator returns a one in each bit position for which the corresponding bits of both operands are ones.

I was also able to find descriptions of == and === on this website on a question that has been previously answered. On this link here: Wikipedia Bitwise_operation#AND

It explains that 1 & 1 is the same as 1 x 1, simple multiplication. So my question is then why is 10 & 5 == 0 and 10 & 6 == 2

Wouldn't it be 10 & 5 == 50 and 10 & 6 == 60?

What am I failing to understand?

Upvotes: 0

Views: 65

Answers (4)

Alwaysblue
Alwaysblue

Reputation: 11890

So 10 should be something like this 1010 and 5 should be something like this 0101

Now, if you find & or And for both of them, You should get something like 0000 which is zero

Similarly for 6, it should be 0110

which should give & or And for both of them as 0010 which happens to be 2

Note: for And we have the following rule

0 & 0 === 0
0 & 1 === 0
1 & 1 === 1

Try going through w3c article: https://www.w3schools.com/jsref/jsref_operators.asp

Upvotes: -1

CertainPerformance
CertainPerformance

Reputation: 371019

It's only the binary bits in each position (the 1s and 0s) that are multiplied.

For example, with 10 & 5:

10 = 1010 in binary

5 = 0101 in binary

Now multiply each digit against the other digit in the same position:

(1 x 0) (0 x 1) (1 x 0) (0 x 1)

= 0000

= 0 in decimal

console.log(10 & 5)

With 10 & 6:

10 = 1010 in binary

6 = 0110 in binary

Now multiply each digit against the other digit in the same position:

(1 x 0) (0 x 1) (1 x 1) (0 x 0)

= 0010

= 2 in decimal

console.log(10 & 6)

Upvotes: 2

Ben West
Ben West

Reputation: 4596

It’s equivalent to multiplication per bit.

0 & 0 === 0
0 & 1 === 0
1 & 1 === 1

So your example of 10 & 5 is:

  1010
& 0101
= 0000

Upvotes: 1

Philippe Sultan
Philippe Sultan

Reputation: 2348

If you switch from base 10 to base 2, which is required when comparing numbers bitwise, then it is clearer :

10 & 5 becomes 1010 & 0101 which equals 0000 in base 2, 0 in base 10

10 & 6 becomes 1010 & 0110 which equals 0010 in base 2, 2 in base 10

Hope this helps!

Upvotes: 0

Related Questions