ajsie
ajsie

Reputation: 79666

Javascript expression bug (0 <= 14 < 10)?

How can this be true?

0 <= 14 < 10

I need to evaluate that a number is in between 0 and 10.

But this breaks my logic.

Shouldn't that expression be false?

Upvotes: 2

Views: 135

Answers (6)

Mateen Ulhaq
Mateen Ulhaq

Reputation: 27191

It's not a bug. It's the way the expression is parsed.

It goes left to right:

0 <= 14 < 10
true < 10
1 < 10
true

As you can see, 0 <= 14 is true, so that's what it's replaced with. true is equal to 1 in JavaScript, and most other C-derived languages.


What you should use is:

(0 <= 14) && (14 < 10)

Upvotes: 3

Naftali
Naftali

Reputation: 146302

NO. That is true.

0 <= 14 is true (same as int(1)) and 1 < 10 is true

do this instead:

if(variable > 0 && variable < 10) {
   //do something
}

Upvotes: 0

Matt Greer
Matt Greer

Reputation: 62027

This expression is not evaluating the way you expect it to. It's equivalent to

 ((0 <= 14) < 10)

So the first one evaluates and returns true, so you then have true < 10, and true < 10 evaluates to true in JavaScript

Upvotes: 0

CrayonViolent
CrayonViolent

Reputation: 32532

0 <= 14 < 10
(0 <= 14) < 10
true < 10
1 < 10
true

Upvotes: 0

Greg Hewgill
Greg Hewgill

Reputation: 992707

This expression:

0 <= 14 < 10

is the same as

(0 <= 14) < 10

which is

1 < 10

true.

What you can do instead is:

if (0 <= x && x < 10) { ...

Python is the only programming language I can think of right now where the expression x < y < z does what you expect it to do.

Upvotes: 11

Related Questions