Can anyone please explain how this line works.
a & 3 || (b, c)
Does the first part translate to:
a = a & 3;
or is that a ternary code and if true b is returned, else c? thanks
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
(Note on terminology: In
1 + 2, 1 and 2 are “operands” and + is an “operator”)The first operator in that expression (
&) is a bitwise ‘and’: https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Operators/Bitwise_OperatorsThe second operator (
||) is a logical ‘or’, which returns the first operand if it’s truthy (if it would pass anifcheck), and the second one otherwise.The third one (
,) is the comma operator, which simply returns the second operand.So, in plain English: Take the bitwise ‘and’ of
awith3(which is 11 in binary), meaning that the resulting value will be one of 0, 1, 2, or 3 depending on the value of the first two bits ina. If it is not zero, return that value. Otherwise, returnc, butbwill also be evaluated.For example, if
ais 2, thena & 3will be 10 & 11 == 10 (since 1 & 1 == 1 and 0 & 1 == 0), which is 2 and truthy (the only falsy number is 0 or 0.0), so that will be the return value of the whole expression, andbandcwill not even be evaluated. On the other hand, ifais 4, thena & 3will be 100 & 11 == 000, which is falsy, so(b, c)will be evaluated and the result will be thatcis the return value.