开发者

Why does "alert(3>2>1)" alert "false" [duplicate]

This question already has answers here: Why does (0 < 5 < 3) return true? (14 answers) 开发者_如何学C Closed 4 years ago.

I would like to ask why

alert(3>2>1);  // (1)

Is returning FALSE in Javascript.

I know that the correct is:

alert(3>2 && 2>1); // (2)

But the code 1 should return either an error message or either TRUE! Is there a specific reason that this equation returns FALSE?


If you add parentheses to show how JavaScript is interpreting it, it gets much clearer:

alert( (3 > 2) > 1 );

Let's pick this apart. First, it evaluates 3 > 2. Yes, three is greater than two. Therefore, you now have this:

alert( true > 1 );

true is coerced into a number. That number happens to be 1. 1 > 1 is obviously false. Therefore, the result is:

alert( false );


First 3>2 evaluates to TRUE, which is probably implicitly converted to 1, so you end up with 1>1, which is FALSE.

You might want an error here, but Javascript is very weakly typed, so it will try to do implicit conversions, without complaining.

EDIT:

So you're asking why the programming language syntax does not always coincide with the mathematical notation? I would say (1) they have different priorities and (2) it makes more sense for the compiler to do it another way.

This is not uncommon though:

  • "x = 3" (statement) and x = 3 (assignment)
  • "x >> 1" (much more than 1) and x >> 1 (bitshift)
  • "a | b" (a divides b) and a | b (bitwise OR).

The list goes on...


It's being evaluated like:

+(3>2) > 1

Which is the same as:

+(true) > 1

Which finally is:

1 > 1 = false

But hey, at least 3 > 2 > 0 will work ;)


Lets break it down fundamentally, its two > operators with same precedence, So which one runs first?

JavaScript has Operator precedence assigned, As per Operator precedence table downloaded from MDN

Greater than(>) (11 in table) runs left to right, so 3>2 runs first which evaluates to TRUE

so now we have TRUE > 1,

when JavaScript sees two different types of values(bool and number here) for comparison, type coercion will happen which means TRUE will be coerced(type conversion) to 1,

So JavaScript will run as 1>1 which will result as FALSE

Why does "alert(3>2>1)" alert "false" [duplicate]


Please find answer Below:

3 > 2 > 1 === true;

The > operator has a higher precedence than === and is left-to-right associative. If we add the implicit parentheses we get this:

((3 > 2) > 1) === true;

This evaluates further to:

((3 > 2) > 1) === true;
(true > 1) === true;
false === true;
false;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜