0

I wrote this code:

if (10 < prompt("Enter a number from 10 to 30") < 30) {
    alert("Ok");
}

The problem is it always returns true (if I enter any number). Could anybody explain why?

5
  • numbers aren't strings and vice-versa. Commented Apr 4, 2014 at 19:31
  • 2
    why write code like this?????? Commented Apr 4, 2014 at 19:32
  • 1
    Perhaps you've entered an alternate universe where all numbers are between 10 and 30? Commented Apr 4, 2014 at 19:35
  • @TMcKeown: Actually, I could see why someone with a mathematical background might write something like this. It's common to specify bounded ranges something like this: (10 <= x < 30), which means x, where x is >= 10 and x is < 30. Perhaps nicael is a math major? Commented Apr 4, 2014 at 23:51
  • maybe but it's a simple piece of logic that is being turned into something unnecessarily overly complicated. Commented Apr 5, 2014 at 0:36

3 Answers 3

7

Because it is parsed as

(10 < prompt(...)) < 30

since (10 < prompt(...)) is a boolean expression that converts to 0 or 1 in a numeric context, this is either

0 < 30

or

1 < 30

both of which are true.

Sign up to request clarification or add additional context in comments.

Comments

5

In javascript there aren't a < b < c comparisons. You must use a < b && b < c:

var num = prompt("Enter a number from 10 to 30");
if(10<num && num<30) alert("Ok");

2 Comments

There are a < b < c comparisons because everything can be interpreted as numbers. They just don't do what OP expected, or what they do in other languages like Python
@NiklasB. Yeah, I meant comparisons in a mathematical way.
4

This is not the right way to test if a variable is between two values.

10<prompt("Enter a number from 10 to 30")<30

Parses as

(10 < prompt("Enter a number from 10 to 30")) < 30

The problem is that that first bit, (10 < ...), will return either true or false. However, both when comparing Booleans to integers, true is coerced to 1, and false is coerced to 0. So in the next part of the statement 0 < 30 and 1 < 30 will both return true.

Try this:

var value = prompt("Enter a number from 10 to 30");
if(value > 10 && value < 30) { alert("Ok"); }

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.