1

In JavaScript

var x = (5 >= 9 >= 0);
console.log(x);
// returns true

What is happening in that statement and what is the reason for that output?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Vishnu
  • 11,614
  • 6
  • 51
  • 90

2 Answers2

3

The Operator precedence and Associativity chart explains what is happening. The expression is evaluated in this order:

/* 1 */ x = (5 >= 9) >= 0;
/* 2 */ x = false >= 0;
/* 3 */ x = true;    

Explanation:

  1. >= is left associative the operator between 5 and 9 is evaluated first.
  2. >= uses abstract comparison which converts boolean to number i.e. false becomes 0 (ref).
  3. The end result is true.
Salman A
  • 262,204
  • 82
  • 430
  • 521
  • 1
    (5>=9) = true? really? – Wilfredo P Dec 26 '14 at 20:34
  • LOL (false >= 0) = false? – Wilfredo P Dec 26 '14 at 20:36
  • 1
    The real question is, why is `false == 0` in non-strict comparison – adeneo Dec 26 '14 at 20:38
  • @adeneo—you're kidding? Because [*ToNumber(false)*](http://ecma-international.org/ecma-262/5.1/#sec-9.3) is zero. – RobG Dec 26 '14 at 21:32
  • @RobG - I'm not kidding, it's probably not very clear to everyone why `false >= 0` returns `true` as it's clearly not the same thing, or false being "more" than zero, it's because of the forced coercion to numbers on both sides, which is interesting. – adeneo Dec 26 '14 at 21:37
  • @adeneo unfortunately there is no `>==` operator :) – Salman A Dec 26 '14 at 21:41
  • @adeneo—the greater–than and less–that operators use the [*abstract relation algorithm*](http://ecma-international.org/ecma-262/5.1/#sec-11.8.5), so there's a not–so–subtle hint that the comparison isn't strict. Maybe there's room for a strict relational comparison? ;-) – RobG Dec 26 '14 at 21:59
3

The true statement, is understood as different from zero... Consequently, false is equals zero...

The statement:

(5>=9>=0)

Turns into

(false >= 0)

Since 5 is lower than 9. Then, if false is equal zero the result is true

EDIT

As explained here (All falsey values in JavaScript), zero is among the falsy values in javascript...

Community
  • 1
  • 1
LcSalazar
  • 16,524
  • 3
  • 37
  • 69