最新消息:Welcome to the puzzle paradise for programmers! Here, a well-designed puzzle awaits you. From code logic puzzles to algorithmic challenges, each level is closely centered on the programmer's expertise and skills. Whether you're a novice programmer or an experienced tech guru, you'll find your own challenges on this site. In the process of solving puzzles, you can not only exercise your thinking skills, but also deepen your understanding and application of programming knowledge. Come to start this puzzle journey full of wisdom and challenges, with many programmers to compete with each other and show your programming wisdom! Translated with DeepL.com (free version)

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

matteradmin6PV0评论

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> 
Post a comment

comment list (0)

  1. No comments so far