& is bitwise AND
This operator expects two numbers and retuns a number. In case they are not numbers, they are cast to numbers.
How does it work? Wikipedia has an answer: https://en.wikipedia.org/wiki/Bitwise_operation#AND
General rule: Avoid. Don't use it. It rarely has place in a maintainable and readable JS code.
&& is logical AND
It expects two arguments and returns:
- First term that evaluates to false
- Last term otherwise (if all are true-y)
Here are some examples:
0 && false 0 (both are false-y, but 0 is the first)
true && false false (second one is false-y)
true && true true (both are true-y)
true && 20 20 (both are true-y)
If you only ever use it on Boolean, this is exactly the AND operator from mathematical logic.
&& operator chaining
The reason this operator is defined as above is operator chaining. You are able to chain this operator and still keep the above rules.
true && 20 && 0 && 100 0 (it is the first false-y)
10 && 20 && true && 100 100 (last one, since all are true-y)
true && false && alert("I am quiet!")
This statement doesn't alert anything and
false is returned. Therefore, you could use the
&& operator as a shorter replacement for an if statement. These are equivalent:
if (user.isLoggedIn()) alert("Hello!")
user.isLoggedIn() && alert("Hello!")
Almost all JS compressors use this trick to save 2 bytes.