Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is the Javascript operator "&&" so weird?

a = 1;
b = "1";
if (a == b && a = 1) {
    console.log("a==b");
}

The Javascript code above will result in an error in the if statement in Google Chrome 26.0.1410.43:

Uncaught ReferenceError: Invalid left-hand side in assignment

I think this is because the variable a in the second part of the statement &&, a=1 cannot be assigned. However, when I try the code below, I'm totally confused!

a = 1;
b = "1";
if (a = 1 && a == b) {
    console.log("a==b");
}

Why is the one statement right but the other statement wrong?

like image 305
sherlock Avatar asked May 18 '13 07:05

sherlock


People also ask

What does '!' Mean in JavaScript?

The ! symbol is used to indicate whether the expression defined is false or not. For example, !( 5==4) would return true , since 5 is not equal to 4. The equivalent in English would be not .

Why is operator used in JavaScript?

JavaScript operators are used to assign values, compare values, perform arithmetic operations, and more.

What is ____ operator in JavaScript?

JavaScript includes operators that perform some operation on single or multiple operands (data value) and produce a result. JavaScript includes various categories of operators: Arithmetic operators, Comparison operators, Logical operators, Assignment operators, Conditional operators.

What is === operator in JavaScript with example?

=== (Triple equals) is a strict equality comparison operator in JavaScript, which returns false for the values which are not of a similar type. This operator performs type casting for equality. If we compare 2 with “2” using ===, then it will return a false value.


2 Answers

= has lower operator precendence than both && and ==, which means that your first assignment turns into

if ((a == b && a) = 1) {

Since you can't assign to an expression in this way, this will give you an error.

like image 187
Joachim Isaksson Avatar answered Oct 22 '22 18:10

Joachim Isaksson


The second version is parsed as a = (1 && a == b); that is, the result of the expression 1 && a == b is assigned to a.

The first version does not work because the lefthand side of the assignment is not parsed as you expected. It parses the expression as if you're trying to assign a value to everything on the righthand side--(a == b && a) = 1.

This is all based on the precedence of the various operators. The problem here stems from the fact that = has a lower precedence than the other operators.

like image 21
Tikhon Jelvis Avatar answered Oct 22 '22 16:10

Tikhon Jelvis