1

I'm trying to understand how bitwise operation works in Javascript especially when used as the condition result.

const number = 19 if(number & 1) { console.log('one') } if(number & 2) { console.log('two') } if(number & 4) { console.log('four') } if(number & 8) { console.log('eight') } if(number & 16) { console.log('sixteen') } // one two sixteen if(number & 1 === 1) { console.log('one') } if(number & 2 === 2) { console.log('two') } if(number & 4 === 4) { console.log('four') } if(number & 8 === 8) { console.log('eight') } if(number & 16 === 16) { console.log('sixteen') } // one two four eight sixteen 

The first part of the code produces one two sixteen which I expect it to be. But the second part of the code produces one two four eight sixteen. Since number & 4 should be 0, it should not print out 'four' here, the same for 'eight'. What do I misunderstand here?

1

2 Answers 2

3

You are facing a problem with operator precendence: === has a higher precendence than &. number & 1 === 1 will thus be evaluated as number & (1 === 1).

To solve that you have to add proper grouping:

(number & 1) === 1 
Sign up to request clarification or add additional context in comments.

1 Comment

Do you know the reason why === should have higher precedence than &?
2

According to MDN, The precedence value of === (10) is greater than &(9). That's why 19 & 4 === 4 is executed as 19 & (4 === 4) here.

1 Comment

Do you know the reason why === should have higher precedence than &?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.