Why "alert (3> 2> 1)" alert "false"
I would like to ask why
alert(3>2>1); // (1) Returns false in javascript
I know this is correct:
alert(3>2 && 2>1); // (2) But code 1 should return either an error message or TRUE! Is there a specific reason this equation returns FALSE?
If you add parentheses to show how JavaScript interprets it, it becomes much clearer:
alert( (3 > 2) > 1 ); Drop it separately. First he evaluates 3 > 2 . Yes, three is more than two. Therefore, you have the following:
alert( true > 1 ); true forced to a number. This is the number 1 . 1 > 1 is obviously wrong. Therefore, the result:
alert( false ); The first 3>2 evaluates to TRUE, which is probably implicitly converted to 1, so you get 1>1 , which is FALSE.
An error may occur here, but Javascript is very weakly typed, so it will try to do implicit conversions without complaining.
EDIT:
So, you ask why the syntax of a programming language does not always coincide with the mathematical notation? I would say (1) that they have different priorities, and (2) it makes sense for the compiler to do it differently.
This is not uncommon:
- "x = 3" (instruction) and
x = 3(assignment) - "x → 1" (much larger than 1) and
x >> 1(bit shift) - "a | b" (a divides b) and
a | ba | b(bitwise OR).
The list goes on ...
Estimated as:
+(3>2) > 1 This is the same as:
+(true) > 1 Finally:
1 > 1 = false But hey, at least 3 > 2 > 0 will work;)
Let's break it first, its two> operator with the same priority. So which one is executed first?
JavaScript has operator priority, according to the operator priority table loaded with MDN
More than (>) (11 in the table) is executed from left to right, so 3> 2 is executed first, which evaluates to TRUE
now we have TRUE> 1,
when JavaScript sees two different types of values (bool and number here) for comparison, a type coercion will occur, which means that TRUE will be forced (type conversion) to 1,
So, JavaScript will work as 1> 1, which will display as FALSE
