What's the difference between & and && in JavaScript?
Solution 1
&
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 && false 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.
Solution 2
&
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
Martin Thoma
I also have a blog about Code, the Web and Cyberculture (medium as well) and a career profile on Stackoverflow. My interests are mainly machine-learning, neural-networks, data-analysis, python, and in general backend development. I love building secure and maintainable systems.
Updated on February 11, 2022Comments
-
Martin Thoma over 2 years
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 logicaland
which gives me always the second value if both aretrue
.But what is
&
?(By the way,
&&
seems to beand
in Python;&
seems to be&
in Python)-
Tom Anderson over 3 yearsIf 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
.
-
-
Sanghyun Lee over 12 years&& doesn't return boolean in JavaScript.
-
duri over 12 yearsAFAIK,
&&
returns the first value, if it is false-y, and the second value otherwise. -
FtDRbwLXw6 over 11 yearsYou don't use bitwise AND (
&
) when working with boolean values. Refer to the other answers on appropriate use of this operator. -
Rok Kralj about 10 yearsAnswer completely revised.
-
user991 almost 10 yearsIf 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 ?
-
azerafati almost 10 years@drrcknlsn, I read the other answers but the explanation here works very well, could you provide more info about your claim??
-
FtDRbwLXw6 almost 10 years@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.
-
Ryan Williams almost 10 years@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.
-
Brandon over 4 yearsI 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
-
GladHeart over 4 yearsThanks 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 over 4 yearsAs 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"
-
Brandon over 4 yearsIf 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 -
GladHeart over 4 yearsTy 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.
-
dyoung over 3 yearsI 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.
-
Tom Anderson over 3 yearsThe 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 over 3 yearsIn 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.
-
GladHeart over 3 yearsHi 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.
-
MMJ over 2 years@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
-
Sanghyun Lee over 2 years@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. -
MMJ about 2 years@Sanghyun Lee, got it ;)