javascriptbitwise-operatorslogical-operators

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


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)


Solution

  • & is bitwise AND

    This operator is almost never used in JavaScript. Other programming languages (like C and Java) use it for performance reasons or to work with binary data. In JavaScript, it has questionable performance, and we rarely work with binary data.

    This operator expects two numbers and returns 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

    && is logical AND

    Most usually, programmers use this operator to check if both conditions are true, for example:

    true && true        // returns true
    true && false       // returns false
    

    However, in JavaScript, it is extended to allow any data type and any number of terms. It returns:

    Here are some examples:

    true && false && true         // returns false
    true && 20 && 0 && false      // returns 0 (it is first false-y)
    10 && "Rok" && true && 100    // returns 100 (as all are true-y)
    

    && short-circuiting

    As can be seen from above, as soon as you find one that term is false-y, you needn't to care about the following terms. This allows Javascript to stop evaluation altogether. This is called short circuiting.

    This statement doesn't alert anything and false is returned:

    true && false && alert("I am quiet!")     // returns false
    

    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.