124

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)

Martin Thoma
  • 124,992
  • 159
  • 614
  • 958
  • 1
    If you are wondering why we don't use bitwise operations instead of logical operators, consider 4 & 1 = 0. Using two arrays of length 4 and 1; bitwise: `fruits.length & veggies.length === 0`, and boolean: `fruits.length && veggies.length === true`. – Tom Anderson Dec 02 '20 at 05:48

4 Answers4

196

& 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 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

&& 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:

  • First term that evaluates to false
  • Last term otherwise (if all are true-y)

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.

Rok Kralj
  • 46,826
  • 10
  • 71
  • 80
  • 7
    && doesn't return boolean in JavaScript. – Sanghyun Lee Sep 05 '11 at 15:39
  • 2
    AFAIK, `&&` returns the first value, if it is false-y, and the second value otherwise. – duri Sep 05 '11 at 15:45
  • 2
    Answer completely revised. – Rok Kralj Apr 08 '14 at 18:25
  • 1
    If it returns first value, then i don't understand how can I run this: **if ($('#form1').parsley().validate() == true && $('#form2').parsley().validate() == true) { // do something if both forms are valid }** because it will exit in first function if it is false and never will validate second form, how then to run that IF statement ? – user991 Jun 17 '14 at 20:21
  • 2
    @user777 Isn't is irrelevant whether or not the second form is validated if your operation should only occur upon both validating? If the first form fails the whole operation is invalid. However this is really a completely separate question because this thread is all about _returning_, not using in _if statements_. – Ryan Williams Jul 18 '14 at 14:24
  • @Sanghyun Lee, I believe it does... type code below in Chrome Console. (1 && 1) returns 1 (true && true) returns true (0 && 0) returns 0 (false && false) returns false – MMJ Feb 10 '22 at 20:17
  • @MMJ what I meant is that `&&` returns the first falsy value or the second value. It could be a boolean or not depending on the first or second value. – Sanghyun Lee Feb 10 '22 at 21:09
  • 1
    @Sanghyun Lee, got it ;) – MMJ Mar 04 '22 at 00:14
  • @SanghyunLee Even better, you can imagine it as a chain of terms, it returns the first one that evaluates to false (or the last one). – Rok Kralj Oct 15 '22 at 23:53
36

& is the bitwise "and". This means that if you have two numbers converted to binary, the result is a number that has the 1 digit at the positions where both numbers have 1.

  100011  //35
& 111001  //57
---------
  100001  //35 & 57 == 33
duri
  • 14,991
  • 3
  • 44
  • 49
  • Another thing to bear in mind is that Javascript will cast any oversized values to within range if bitwise-anded with itself. Eg, `const b = 99999999999999999; console.log(b & b); // 1569325056` - this can be useful when working with things like hashing functions which often deal with huge esoteric numbers – Matt Fletcher Jul 20 '23 at 15:26
-2

To determine whether two boolean values put together are true or false, if you want to check them both (like validation on the web page), you may use the & operator. & is bitwise AND.

With the && operator, once it finds the first value is false, it will end evaluation and not to check the second value.

  • 4
    You don't use bitwise AND (`&`) when working with boolean values. Refer to the other answers on appropriate use of this operator. – FtDRbwLXw6 Sep 20 '12 at 06:31
  • 1
    @drrcknlsn, I read the other answers but the explanation here works very well, could you provide more info about your claim?? – azerafati Jun 22 '14 at 13:54
  • 1
    @Bludream: The explanation in this answer is wrong. You do not use bitwise operators for logical (boolean) comparisons. You use logical (boolean) operators. They do different (although similar) things, expect different inputs, produce different outputs, and have different operator precedence. – FtDRbwLXw6 Jun 22 '14 at 22:41
  • 2
    I would agree it's bad practice but using & with boolean values will work. false evaluates to 0 and true evaluates to 1. I don't see anything that is technically incorrect with this answer as you "may" use &, it's just not recommended. – dashingdove Oct 29 '20 at 05:02
-4

With all the lofty, detailed insights throughout, they have mostly missed the truth that there is a conditional evaluation where ONLY the single & will work. The practical layman's answer that solved my head beating on an IF statement string of MULTIPLE chained && each !== to a condition was causing FAILURE and needed to legitimately use the single &. I thank Jake Wayne (and Russ) for their unfairly downvoted answer that got it right given that where there is more than one && that !== it has already ceased its evaluation and proceeds no further after the first evaluation is found ==!. With the && it thinks its job is done after the first evaluation shows !== [eg. false]. My failing code was

IF ((sessionStorage.myLable !== "LableStringA") && (sessionStorage.myLable !== "LableStringB") && (sessionStorage.myLableZ !== "LableStringA") && (sessionStorage.myLableZ !== "LableStringB")) { ...)

Here, properly substituting and using a single & for the && it was both practically in the real world and technically the correct answer. Thank you again Jake Wayne (and Russ) for the insight and understanding of code.

SecretAgentMan
  • 2,856
  • 7
  • 21
  • 41
GladHeart
  • 51
  • 9
  • 2
    I don't recommend using something 'just because it works' if you don't understand it. You are just setting yourself up for trouble later when it ends up not working and you can't debug it. Or even worse you try to use it in a job interview and they look at you like ಠ_ಠ. If your conditionals aren't evaluating how you expect, you have a logic error. There is no reason to evaluate all 4 conditionals if the first returns false because the combined conditional can never evaluate to true in that case – Brandon Oct 21 '19 at 01:39
  • Thanks Brandon. I don't question your overall concerns. I do always defer to and institute the === convention. Here however, ALL four evaluations were necessary contrary to your last well meant comment. All four evaluations needed to be !== and were used in that format within the parenthesis. It was the concatenating && that would not preform as high logic expected. Using a single & was read correctly by the compilers on all major OS's I tested. – GladHeart Oct 22 '19 at 02:41
  • As a follow up as to why it seems to and does elegantly work, it would be in the clarity of Russ&Jake's falsely disparaged answer. All four evaluations need to be evaluated. Using the && stops/aborts when the first evaluation is false. Using the single & lets it continue to necessarily evaluate the remaining three conditions. As Russ&Jake said, "With the "&&" operator, once it finds the first value is false, it will end evaluation and not to check the second value.". Whereas, " if you want to check them [all] (like validation on the web page), you may use the "&" operator. "&" is bitwise AND" – GladHeart Oct 23 '19 at 00:49
  • 1
    If you need to check them all, you could also structure your logic as `if (!(sessionStorage.myLable === "LableStringA" || sessionStorage.myLable === "LableStringB") || !(sessionStorage.myLableZ === "LableStringA" || sessionStorage.myLableZ === "LableStringB")) { // fail validation}` which seems to be more clear as to what you intend (I'm assuming you want to ensure the values of myLable are one of the two values, or fail validation). Unless your conditions have side effects, there is no reason you need to evaluate them all. The operator is working as intended, but your logic was flipped – Brandon Oct 24 '19 at 03:21
  • Ty for the follow up Brandon. With respects, it still misses the necessity of the conditions in my case where looking for === could be one of dozens of possibilities on each of the four validations. Simply, it is if none of four do not contain a specific page marker value, I fall back to running a script to compensate for its lack thereof. All four MUST all show as ==!. It is not that "assuming you want to ensure the values of myLable are one of the two values", it is in fact that myLable is one of many in a haystack of possibilities. Therefore non-equivalence is a single question needed 4x. – GladHeart Oct 25 '19 at 16:00
  • The value of "a && b && c && d" == "a & b & c & d" for boolean values of a, b, c, and d, because true == 1 and false == 0. They are _always_ the same. If there are four doors, and someone asks if at least one of the doors is not "blue", there is no legitimate reason to check all four doors. You check the first door, if it's not "blue", check the next one, and so on until you find a "blue" door or conclude that none of the doors are blue. – Tom Anderson Dec 02 '20 at 05:38
  • In other words, if all four MUST show as !==, you may stop as soon as one of the four does not show as !==, because without checking all of them, you can conclude that the expectation of "all four MUST show as !==" has not been met. – Tom Anderson Dec 02 '20 at 05:41
  • Hi Tom. It's not that I disagree with your logic or thinking, it just does not in the least apply to the specifics of my application and does not void my point. I am not looking for (good analogy BTW) a "blue door". I have a haystack of colors. I am trying to look specifically that there are not any of four specific doors, say the blue one, a red one, a green one, and a pink one. If NONE of those four are verified as present then I take appropriate action to compensate. Each has to be individually specified because they are not all blue. Nor, when expedient or necessary is use of bitwise evil. – GladHeart Dec 04 '20 at 00:59
  • The only reason to run each condition branch is to ensure side effects occur. The conditions you have coded in your example do not indicate any side-effect as they are just checking an object field against a literal string. W/o side effects, the need for each condition to evaluate is no longer valid. The interpretation of each sub-condition in `CondA & CondB & CondC & CondD` is `(((CondA & CondB) & CondC) & CondD)`; given this structure, if any one inner branch evaluates to `false`, the whole thing will be `false` by just looking at the truth tables. No need to eval the remaining expressions. – MadcapJake Aug 16 '22 at 21:16