IF statement as an assignment expression in JavaScript
The JSLint Error Explanations doc ( https://jslinterrors.com/unexpected-assignment-expression ) says that if we evaluate an assignment expression (x = 0), the IF body will never be executed (y = 1).
var x, y;
if (x = 0) {
y = 1;
}
"The body of the if statement will not be executed because the assignment expression results in undefined, which is false."
But I could prove otherwise in if (x = 1) { y = 1; }
. Is it a JS version issue?
UPDATE
In fact, I made the mistake of assuming that the assignment result could be used as a test value. What I could actually prove in the console was an assignment returning a value like in x = 1 outputting 1.
source to share
In this article, both correct and . It is correct that the body if
will not be injected with help if (x = 0)
, but it is incorrect when it says why.
The wrong part is highlighted:
Rather than checking if a variable has a
x
value0
, the above example assigns a value0
x
. The body of the if statement will not be executed because the assignment expression results inundefined
, which is false (sic).
It just isn't right. The result of the assignment expression is the assigned value, not undefined
, therefore, if (x = 0)
will not enter the body if
(because 0
false), but if (x = 1)
will (because it is 1
true).
Is it a JS version issue?
No, that's always the case. Someone just made a mistake in these documents.
In fact, I made the mistake of assuming that the assignment result could be used as a test value.
It wasn't a mistake, you can - and sometimes you want to. This is quite common, for example:
while ((thing = getMeTheNextThing()) != null) {
// ...do something with `thing`
}
It also uses the result of the task as a test. Sometimes people even write like this:
while (thing = getMeTheNextThing()) {
// ...do something with `thing`
}
... although I never do it because it's just too easy to see it as ==
messing up.
Note that it is very rare that you need to assign a variable in an expression if
. This is true, but it is very rare, and most style guides will tell you to break down assignment and branch.
Almost always, when you see if (x = 0)
, what the author wanted to write was if (x == 0)
or if (x === 0)
. That is, they wanted to validate the value x
, not assign a new value x
.
An example of what the JSLint docs mean about assigning zero:
var x;
snippet.log("first test: using 0");
if (x = 0) {
snippet.log("entered if body");
} else {
snippet.log("entered else body");
}
snippet.log("second test: using 1");
if (x = 1) {
snippet.log("entered if body");
} else {
snippet.log("entered else body");
}
<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
source to share