The JavaScript bitwise AND operator (&) can be used for some real-world tasks, like testing if a number is odd or even.
Odd-even checking might normally be done with a modulo and the number 2.
// Checking 1
> 1 % 2 === 0 ? "Even" : "Odd"
'Odd'
// Checking 2
> 2 % 2 === 0 ? "Even" : "Odd"
'Even'
The bitwise AND is an alternative. When used between two numbers, it returns a new number that has 1’s in each position where both numbers have a 1.
You can use this to compare any number to 1, which has a 1 in the first binary position. Since all odd numbers have a 1 in the first binary position, odd numbers will return 1.
// Checking 1
> (1 & 1) === 1 ? "Odd" : "Even"
'Odd'
// Checking 2
> (2 & 1) === 1 ? "Odd" : "Even"
'Even'
This could be condensed to:
> 1 & 1 ? "Odd" : "Even"
'Odd'