How to check if a number is between two values?

Javascript

Javascript Problem Overview


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?

Javascript Solutions


Solution 1 - Javascript

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) {
  // ...
}

Solution 2 - Javascript

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:

Solution 3 - Javascript

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(); }

Solution 4 - Javascript

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.

Solution 5 - Javascript

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

}

Solution 6 - Javascript

this is a generic method, you can use everywhere

const isBetween = (num1,num2,value) => value > num1 && value < num2 

Solution 7 - Javascript

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
}

Solution 8 - Javascript

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;)

Solution 9 - Javascript

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.

Solution 10 - Javascript

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();
                }
            }
    });

Solution 11 - Javascript

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

Solution 12 - Javascript

  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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDyckView Question on Stackoverflow
Solution 1 - JavascriptRamView Answer on Stackoverflow
Solution 2 - JavascriptDavid ThomasView Answer on Stackoverflow
Solution 3 - JavascriptDavidView Answer on Stackoverflow
Solution 4 - JavascriptgorodezkiyView Answer on Stackoverflow
Solution 5 - JavascriptHanzla HabibView Answer on Stackoverflow
Solution 6 - JavascriptFahd AllebdiView Answer on Stackoverflow
Solution 7 - JavascriptChinthaka DilanView Answer on Stackoverflow
Solution 8 - Javascriptyukashima huksayView Answer on Stackoverflow
Solution 9 - JavascriptIsaac VegaView Answer on Stackoverflow
Solution 10 - JavascriptWiseGuyView Answer on Stackoverflow
Solution 11 - JavascriptEliav LouskiView Answer on Stackoverflow
Solution 12 - Javascriptmojaba moradiView Answer on Stackoverflow