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?
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 .
JavaScript operators are used to assign values, compare values, perform arithmetic operations, and more.
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.
=== (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.
=
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With