Will `if(x=y)` Ever Return false, or fail In JavaScript?
This is a theoretical question, as I can't imagine any practical uses.
I made a bold statement today saying that in JavaScript, the following will always return true:
if (x=y){
//code
}
And the //code
, whatever it is, will always be executed.
This is the classic typo of not entering ==
or even ===
.
This feature can also be demonstrated in C/C++, but being more strongly-typed languages than JavaScript, i开发者_如何学JAVAt is not hard to think instances where this assignment will fail.
However, in JavaScript, given two variables x
and y
, I was struggling to think of an occation where this would fail, or the proceding conditional code block would not execute.
Anyone?
It (x=y) would evaluate to false if y=0, y=null, y=undefined or y=false.
Edit: Also if y=NaN
Edit: Also if y=""
The conditional block "x=y" will always execute. But in javascript "false", undefined, null, and 0 evaluate to false. So whenever y is one of those values, the "//code" will not be executed.
js
js> if(x=y){
print('hello');
}
typein:1: ReferenceError: y is not defined
js>
精彩评论