Is there a more compact way of checking if a number is within a range?

You could make your own method:

// jquery
$(function() {
    var myNumber = 100;
    try {
        if (myNumber.isBetween(50, 150)) 
            alert(myNumber + " is between 50 and 100.");
        else 
            alert(myNumber + " is not between 50 and 100.");
    } catch (e) {
        alert(e.message());
    }

});

// js prototype
if (typeof(Number.prototype.isBetween) === "undefined") {
    Number.prototype.isBetween = function(min, max, notBoundaries) {
        var between = false;
        if (notBoundaries) {
            if ((this < max) && (this > min)) between = true;
            alert('notBoundaries');
        } else {
            if ((this <= max) && (this >= min)) between = true;
            alert('Boundaries');
        }
        alert('here');
        return between;
    }
}

hope this helps.

Max


In many languages, the second way will be evaluated from left to right incorrectly with regard to what you want.

In C, for instance, 1990 < year will evaluate to 0 or 1, which then becomes 1 < 2099, which is always true, of course.

Javascript is a quite similar to C: 1990 < year returns true or false, and those boolean expressions seem to numerically compare equal to 0 and 1 respectively.

But in C#, it won't even compile, giving you the error:

error CS0019: Operator '<' cannot be applied to operands of type 'bool' and 'int'

You get a similar error from Ruby, while Haskell tells you that you cannot use < twice in the same infix expression.

Off the top of my head, Python is the only language that I'm sure handles the "between" setup that way:

>>> year = 5
>>> 1990 < year < 2099
False
>>> year = 2000
>>> 1990 < year < 2099
True

The bottom line is that the first way (x < y && y < z) is always your safest bet.