最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

conditional operator - Will `if(x=y)` Ever Return false, or fail In JavaScript? - Stack Overflow

programmeradmin1浏览0评论

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, it 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?

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, it 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?

Share Improve this question asked Nov 4, 2010 at 8:55 Mutation PersonMutation Person 30.5k18 gold badges100 silver badges165 bronze badges 1
  • For the downvoter: If you ever return, please explain why. Downvotes without explanation are pretty useless. – Mutation Person Commented Nov 4, 2010 at 9:35
Add a ment  | 

3 Answers 3

Reset to default 14

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> 
发布评论

评论列表(0)

  1. 暂无评论