What's the difference between & and && in JavaScript?

Martin Thoma picture Martin Thoma · Sep 5, 2011 · Viewed 82.4k times · Source

What's the difference between & and && in JavaScript?

Example-Code:

var first  = 123;
var second = false;
var third  = 456;
var fourth = "abc";
var fifth  = true;
alert(first & second); // 0
alert(first & third);  // 72
alert(first & fourth); // 0
alert(first & fifth);  // 1

alert(first && second); // false
alert(first && third);  // 456
alert(first && fourth); // abc
alert(first && fifth);  // true

It seems like && is a logical "and" which gives me always the second value if both are true.

But what is &?

(By the way, && seems to be "and" in Python; & seems to be & in Python.)

Answer

Rok Kralj picture Rok Kralj · Sep 5, 2011

& 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

Note: In Javascript, the usage of this operator is discouraged, since there's no integer data type, just floating point. Thus floats are converted to integers prior to every operation, making it slow. Also, it has no real use in typical web applications and produces unreadable code.

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)

&& short-circuiting

As can be seen from the definition, as soon as you find that one term is false-y, you needn't to care about the following terms. Javascript even takes this a notch further, the terms are not even evaluated. This is called short circuiting.

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.