195

In JavaScript, I'm telling the browser to do something if the window size is greater than 500px. I do it like so:

if (windowsize > 500) {
    // do this
}

This works great, but I would like to apply this same method, but with a range of numbers. So I would like to tell my browser to do stuff if the window size is between 500px and 600px. I know this wouldn't work, but here is how I imagined it:

if (windowsize > 500-600) {
    // do this
}

Is this even possible, within JavaScript?

Dyck
  • 2,569
  • 4
  • 21
  • 21
  • Surely the more correct check would be if ( windowsize >= 500 && windowsize <= 600 ) or if ( !(windowsize < 500 || windowsize > 600) ) – SPlatten Sep 03 '19 at 11:08
  • Does this answer your question? [Check if a value is within a range of numbers](https://stackoverflow.com/questions/6454198/check-if-a-value-is-within-a-range-of-numbers) – betontalpfa Sep 09 '20 at 14:52
  • Does this answer your question? [What's the most elegant way to cap a number to a segment?](https://stackoverflow.com/questions/11409895/whats-the-most-elegant-way-to-cap-a-number-to-a-segment) – Carson Jul 18 '21 at 16:17

12 Answers12

295

Tests whether windowsize is greater than 500 and lesser than 600 meaning that neither values 500 or 600 itself will result in the condition becoming true.

if (windowsize > 500 && windowsize < 600) {
  // ...
}
Ram
  • 143,282
  • 16
  • 168
  • 197
  • 1
    thanks undefined, just to confirm this will do what I want within the browser when the window size is greater then 500px and less than 600px, essentially functioning within the range of 500-600px only, correct? (I'm not too good with this stuff lol) – Dyck Feb 05 '13 at 23:14
  • 1
    @Dyck Yes, it does so :), note that jQuery is only a JavaScript library. – Ram Feb 05 '13 at 23:17
  • 7
    Mind that this condition is only true when `windowsize` is at least 501px and at most 599px. **500px and 600px are excluded.** Add equality to comparisons if you want inclusive of these values. – Robert Koritnik Oct 07 '15 at 14:05
  • 6
    Just a detail, but is more readable the following way: `if(500 < windowsize && windowsize < 600)` – Giovanni Benussi Jun 17 '16 at 14:45
  • Wow, this is miraculous! – Leap Hawk Oct 28 '20 at 05:15
  • This is not the real answer – M_Farahmand May 04 '22 at 14:18
149

I had a moment, so, although you've already accepted an answer, I thought I'd contribute the following:

Number.prototype.between = function(a, b) {
  var min = Math.min.apply(Math, [a, b]),
    max = Math.max.apply(Math, [a, b]);
  return this > min && this < max;
};

var windowSize = 550;

console.log(windowSize.between(500, 600));

JS Fiddle demo.

Or, if you'd prefer to have the option to check a number is in the defined range including the end-points:

Number.prototype.between = function(a, b, inclusive) {
  var min = Math.min.apply(Math, [a, b]),
    max = Math.max.apply(Math, [a, b]);
  return inclusive ? this >= min && this <= max : this > min && this < max;
};

var windowSize = 500;

console.log(windowSize.between(500, 603, true));

JS Fiddle demo.

Edited to add a minor amendment to the above, given that – as noted in the comments –

Function.prototype.apply() is slow! Besides calling it when you have a fixed amount of arguments is pointless…

it was worth removing the use of Function.prototype.apply(), which yields the amended versions of the above methods, firstly without the 'inclusive' option:

Number.prototype.between = function(a, b) {
  var min = Math.min(a, b),
    max = Math.max(a, b);

  return this > min && this < max;
};

var windowSize = 550;

console.log(windowSize.between(500, 600));

JS Fiddle demo.

And with the 'inclusive' option:

Number.prototype.between = function(a, b, inclusive) {
  var min = Math.min(a, b),
    max = Math.max(a, b);

  return inclusive ? this >= min && this <= max : this > min && this < max;
}

var windowSize = 500;

console.log(windowSize.between(500, 603, true));

JS Fiddle demo.

References:

David Thomas
  • 249,100
  • 51
  • 377
  • 410
  • 8
    why use apply instead of calling directly like `Main.min(a,b)`? Function.prototype.apply is slow! Besides calling it when you have a fixed amount of arguments is pointless. – Steel Brain May 17 '15 at 01:36
  • I'm going to add this to my default toolbox - very handy and thanks for this contribution! – SidOfc Jun 10 '15 at 12:48
  • @SteelBrain: you have a point! I've updated the answer to reflect that, though I suspect that I had - initially - a *reason* for using `Function.prototype.apply()`, but I can't think what it was, or might have been. – David Thomas Jun 10 '15 at 14:54
  • @DavidThomas There's still a lot of those occurrences in your answer. I think you've only corrected a few. :) – Steel Brain Jun 10 '15 at 18:12
  • Nice solution. Just nitpicking here, but would instead prefer `return min < this && this < max` as it feels more correct, seeing as `this` is sandwiched between the comparison operators. – puiu Dec 10 '15 at 23:20
  • 11
    it's MUCH better to create a function that doesn't modify the `Number` object. This is an anti-pattern and will come and bite you if ECMA standards change to include a `Number.between()` function, or if another library or another piece of code defines `Number.prototype.between` elsewhere with a different definition. Instead, make a helper function and use that! – Monarch Wadia Jan 25 '17 at 20:19
  • 4
    @MonarchWadia While your point makes sense that modifying/extending native objects is bad practice, I feel it's a bit redundant having this preached everywhere (no offense). I can't count the times I've seen "don't modify native objects". For me, this is like someone selling household knives warning the buyer about the possible dangers of the knife every single time he/she sells one like its the seller's responsibility if there's any harm. The dangers should be common knowledge. It should be up to the user if he/she ignores them or not. – akinuri Jun 19 '18 at 06:45
  • Why would you want to do all of that? – René Roth Jul 05 '22 at 07:57
116

I prefer to put the variable on the inside to give an extra hint that the code is validating my variable is between a range values

if (500 < size && size < 600) { doStuff(); }
David
  • 1,887
  • 2
  • 13
  • 14
36

It's an old question, however might be useful for someone like me.

lodash has _.inRange() function https://lodash.com/docs/4.17.4#inRange

Example:

_.inRange(3, 2, 4);
// => true

Please note that this method utilizes the Lodash utility library, and requires access to an installed version of Lodash.

Chaya Cooper
  • 2,566
  • 2
  • 38
  • 67
gorodezkiy
  • 3,299
  • 2
  • 34
  • 42
  • 3
    Please be aware than the end value is not included. eg. `_.inRange(10, 0, 10) // => false` – Lucio Mar 29 '19 at 00:56
  • As the OP limited the question scope to `Javascript`, it's worth noting that this method utilizes the `Lodash` utility library, and requires access to an installed version of Lodash. – Chaya Cooper Sep 20 '19 at 01:11
7

You can do it simply

if (windowsize > 500 && windowsize < 600) {
//your logic
}

Or if you want clean code You can write your own function in your main js file of any common place.

Number.prototype.between = function(a, b) {
 var min = Math.min.apply(Math, [a, b]),
    max = Math.max.apply(Math, [a, b]);
  return this > min && this < max;
};

Then you can call it like this

if(windowsize.between(500, 600)){
 //your logic
}
5

I know there's an accepted answer, but I want to provide some ways that can be useful in certain scenarios. If we want to check whether n is between x and y, we can do:

x <= n && n <= y
(x - n) * (y - n) <= 0

The second one is very useful when you're trying to get the same result even if you swap x and y.

Isaac Vega
  • 300
  • 3
  • 6
4

You can use Multiple clause in if condition instead of writing

if (windowsize > 500-600) {
    // do this
}

because this really makes no sense logically JavaScript will read your if condition like

windowSize > -100 

because it calculates 500-600 to -100

You should use && for strict checking both cases for example which will look like this

if( windowSize > 500 && windowSize < 600 ){

// Then doo something

}
Hanzla Habib
  • 3,457
  • 25
  • 25
4

Here is the shortest method possible:

if (Math.abs(v-550)<50) console.log('short')
if ((v-500)*(v-600)<0) console.log('short')

Parametrized:

if (Math.abs(v-max+v-min)<max+min) console.log('short')
if ((v-min)*(v-max)<0) console.log('short')

You can divide both sides by 2 if you don't understand how the first one works;)

yukashima huksay
  • 5,834
  • 7
  • 45
  • 78
4

this is a generic method, you can use everywhere

const isBetween = (num1,num2,value) => value > num1 && value < num2 
Fahd Allebdi
  • 354
  • 4
  • 7
0

I just implemented this bit of jQuery to show and hide bootstrap modal values. Different fields are displayed based on the value range of a users textbox entry.

$(document).ready(function () {
    jQuery.noConflict();
    var Ammount = document.getElementById('Ammount');

    $("#addtocart").click(function () {

            if ($(Ammount).val() >= 250 && $(Ammount).val() <= 499) {
                {
                    $('#myModal').modal();
                    $("#myModalLabelbronze").show();
                    $("#myModalLabelsilver").hide();
                    $("#myModalLabelgold").hide();
                    $("#myModalPbronze").show();
                    $("#myModalPSilver").hide();
                    $("#myModalPGold").hide();
                }
            }
    });
WiseGuy
  • 409
  • 1
  • 8
  • 19
  • 9
    Using jQuery for trivial functions was in 2013 maybe an option but isn't today – mgamsjager Jun 09 '16 at 08:40
  • 3
    True but I am afraid people will still use it today – mgamsjager Jul 11 '16 at 12:50
  • 1
    Out of curiosity: why is jQuery worse to use for trivial functions now than then? – Julix Oct 14 '16 at 00:44
  • 2
    @Julix mostly performance, albeit negligible in this case. The general point would be "don't use jQuery when it is not necessary" but these comments are not the place to (re)start the debate. have fun with this though :) http://i.stack.imgur.com/sGhaO.gif – Luca Oct 18 '16 at 15:43
  • 1
    This is just an implementation of the solution. OP already has access to the values. So jQuery `$().val()` is irrelevant and not necessary. But again, in the original version of the question, OP mentions jQuery, for a simple arithmetic check. (sigh) That's the first mistake. – akinuri Jun 19 '18 at 06:55
0

just like David answer but i needed inclusive for either a or b. so my sol:

export const between = (num: number, a: number, b: number, inclusiveA = true, inclusiveB = true): boolean => {
  if (a > b) [a, b, inclusiveA, inclusiveB] = [b, a, inclusiveB, inclusiveA];
  if (a == b && (inclusiveA || inclusiveB)) [inclusiveA, inclusiveB] = [true, true];
  return (inclusiveA ? num >= a : num > a) && (inclusiveB ? num <= b : num < b);
};

if (require.main === module) {
  console.log(between(12, 15, 10)); //true
  console.log(between(15, 15, 10)); //true
  console.log(between(15, 10, 15)); //true
  console.log(between(10, 10, 15, false)); //false
  console.log(between(15, 10, 10, true, false)); //false
  
  //edge case: if a==b then enough that either of the edges is inclusive
  console.log(between(10, 10, 10, true, false)); //true
}

its also typescript and not javascript

Eliav Louski
  • 3,593
  • 2
  • 28
  • 52
0

  function handleBetween(number, calc) {
        let [a, b] = calc;
        let min = Math.min(a, b), max = Math.max(a, b);
        return number > min && number < max;
    }

    if(510 >500 && 510 <600){
    console.log(`510 >500 && 510 <600 is true`)
    }


    if(610 >500 && 610 <600){
    // false
    console.log(`610 >500 && 610 <600 is true`)
    } else console.log(`610 >500 && 610 <600 is false`)


    
     console.log(handleBetween(510, [500, 600])); // true
     console.log(handleBetween(610, [500, 600])); // false