& VS && operators, | vs || operators

What is the difference between these operators in JS?

I’ve found some incredibly stupid behavior with the single character versions.

To illustrate:

Code:
console.log(true&true)
Output:
1

Alright, this makes sense, if 1 represents true and 0 represents false, seems like there’s not a major difference.

Code:
console.log(true&17)
Output:
1

I guess since 17 exists and isn’t Null/NaN/etc. it makes sense.

Code
console.log(true&6)
Output:
0

Why are even numbers suddenly falsy?

I tried with the more “normal” && operator.

Code:
console.log(true&&6)
Output:
6

:face_with_monocle:

The same unexplained outcomes are seen with the OR operator.

& is indeed very different than &&

Generally, you should use && and forget about & unless you really need to be doing bit manipulation.

An even number has its last bit as 0, so bitwise & with the boolean literal true will give 0

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.