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
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:
Now, here's the kicker: when JavaScript compares true to a number, it turns true into 1.
So what's really happening is:
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.
The above is the detailed content of Why does lt; lt; eturn true but gt; gt; eturn false in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!