8

In javascript I am doing the following which works fine.

if (myVar == 25 || myVar == 26 || myVar == 27 || myVar == 28)
 {
   //do something
 }

How can I shorten it? something like the following.

if (myVar IN ('25','26','27','28')) {
    //do something
   }

or

if(myVar.indexOf("25","26","27","28") > -1) ) {//do something}

6 Answers 6

25

You can use Array.indexOf(), it returns the first index at which a given element can be found in the array, or -1 if it is not present.

Use

var arr = [25, 26, 27, 28];
console.log(arr.indexOf(25) > -1);
console.log(arr.indexOf(31) > -1);


Array.includes() method can also be used it returns boolean.

var arr = [25, 26, 27, 28];
console.log(arr.includes(25));
console.log(arr.includes(31));

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

Comments

9

Just try with:

if ( [25, 26, 27, 28].indexOf(myVar) > -1 ) {}

2 Comments

As indicated in that thread, if you're using jQuery, you can use `$.inArray(
3

Other way :

myVar = (myVar == parseInt(myVar) ? myVar : false); //to check if variable is an integer and not float
if ( myVar >= 25 && myVar <= 28){}

Live demo

Edit based on the comment of Anthony Grist

This way works if you know what those values are going to be (i.e. they're not dynamic) and your array contains a series of consecutive numeric values.

2 Comments

> 24 && < 29 is even shorter :)
Fine if you know what those values are going to be (i.e. they're not dynamic) and your array contains a series of consecutive numeric values.
3

Since indexOf(), has some browser compatibility issues and requires an extra step (of comparing the result to -1), an alternative, cross-browser approach is the following jQuery utility method (if you include jQuery in your project) :

if($.inArray(myVar, [25, 26, 27, 28]) > -1) {
     // ... do something ... 
}

Comments

1

if ( [25, 26, 27, 28].indexOf(myVar) > -1 ) {}

Array.indexOf will work fine for all modern browsers(FF, Chrome, >IE8), just a word of caution is that Array.indexOf will not work for IE8. If you want to make it work in IE8 please use the below code:

window.onload = function() {

if (!Array.prototype.indexOf) {

Array.prototype.indexOf = function(elt /*, from*/) {
  var len = this.length >>> 0;
  var from = Number(arguments[1]) || 0;
  from = (from < 0) ? Math.ceil(from) : Math.floor(from);
  if (from < 0) {
    from += len;
  }
  for (; from < len; from++) {
    if (from in this && this[from] === elt){
      return from;
  }
}
return -1;

};

}

}

Comments

0
var validValues = [25, 26, 27, 28]
var myVar = 25

if (validValues.includes(myVar)) {
    //do something
}

Comments

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.