DEV Community

Cover image for Why does 1 < 2 < 3 return true but 3 > 2 > 1 return false in JavaScript?
Jaydeep Pipaliya
Jaydeep Pipaliya

Posted on

1

Why does 1 < 2 < 3 return true but 3 > 2 > 1 return false in JavaScript?

Hey, JavaScript fans! Have you ever had one of those moments where your code does something weird and you're left scratching your head? Well, I've got a good one for you today.

Check this out:

console.log(1 < 2 < 3);  // true
console.log(3 > 2 > 1);  // false
Enter fullscreen mode Exit fullscreen mode

Wait, what? The second one is false? But 3 is greater than 2, and 2 is greater than 1, right? So what's going on here?

Let's break it down:

  1. JavaScript reads these comparisons from left to right.
  2. For 1 < 2 < 3:
    • First, it does 1 < 2. That's true.
    • Then it does true < 3.
  3. For 3 > 2 > 1:
    • First, it does 3 > 2. That's true.
    • Then it does true > 1.

Now, here's the kicker: when JavaScript compares true to a number, it turns true into 1.

So what's really happening is:

  1. true < 3 becomes 1 < 3, which is true.
  2. true > 1 becomes 1 > 1, which is false.

And that's why we get true for the first one and false for the second one.

Crazy, right?

So, what can we learn from this? When you're doing multiple comparisons, it's better to be clear. Instead of 3 > 2 > 1, you could write (3 > 2) && (2 > 1). It's a bit longer, but at least it does what you expect.

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay