0

By gut-feeling I know the following to be wrong syntax, or at least not working as intended (tried it), but there is no error thrown either:

var x = 2;
if (1 < x < 3) ...

I guess the VM evaluates part of the expression first, then compares it to the rest, but does anybody actually know (with documentation link, preferably) what exactly is going on here?

Edit: I found a similar question that has solutions of how to write this, but I am actually interested in what is happening behind the scenes here.

1 Answer 1

2

Use this :

if (1 < x && x < 3)

What you were doing was

if (
    (1 < x) // boolean, cast to 0 or 1
    < 3
)

This page from the MDN on operator precedence explains that < is interpreted from left to right.

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

3 Comments

Thanks, I am not actually looking for a solution on how to write this, but for answers explaining what is happening (documentation for it).
@kontur Is my answer clear enough now ? What's missing ?
Why is 1 < x evaluated before x < 3, and why is this not invalid syntax? Or looking at the intuitively expected result, why does this not check if x is within the bounds of 1 and 3.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.