Wojciech Abacki
Wojciech Abacki

Reputation: 251

How to not repeat == many times

This is my example

if(someString == 'string1' || someString == 'string2' || someString == 'string3' || someString == 'string4');

Is there any trick to using shorter syntax?

Upvotes: 0

Views: 67

Answers (8)

Coffee
Coffee

Reputation: 1

ES6 includes will do it

const options = ['string1','string2','string3'];

if (options.includes(someString)) {
  // do something
}

Upvotes: 0

developer_hatch
developer_hatch

Reputation: 16224

You can use include and add all the possibilities into an array:

var matches = ['string1', 'string2', 'string3', 'string4'];
var something = 'string2';
var isInArray = matches.includes(something);
console.log(isInArray); // true

Upvotes: 0

llama
llama

Reputation: 2537

Create a pre-defined Set of the values you want to check, and use the .has() method to test for it:

var vals = new Set(['string1', 'string2', 'string3', 'string4']);
var someString = "string2";
var otherString = "stringX";

console.log(vals.has(someString));  // true
console.log(vals.has(otherString)); // false

So with an if statement, it would look like this:

if (vals.has(someString)) {
  // your code
}

Upvotes: 1

Walter White
Walter White

Reputation: 1026

if(["str1","str2","str3","str4"].includes(someString)){
}

Upvotes: 2

user8811940
user8811940

Reputation:

switch (someString) {
case "string1":
case "string2":
case "string3":
case "string4":
   // do something
   break;
default:
   // this would the else
}
  • Note the missing breaks on purpose

Upvotes: 0

FluffyNights
FluffyNights

Reputation: 292

there is nothing like if(string == "str1" || "str2" || ..., at least not in the languages i know, and it actually makes sense there isn't, because everything is a logical expression. if you have a large number of comparisons, you can do something like

strings = ["str1", "str2", "str3", ...];
var match = false;
for(var i = 0; i < string.length; i++){
if(strings[i] == someString){ match = true; break; }
}
if(match){ ... do something }

if you only have primitive objects and non-complex comparisons (just finding something), you can use string / array methods as well

Upvotes: 0

Obsidian Age
Obsidian Age

Reputation: 42304

You could always put the possible values into an array, and then check whether the string matches any of the values in the array:

var someString = 'string2';
var possibleValues = ["string1", "string2", "string3", "string4"];

if (possibleValues.indexOf(someString) > -1) {
  console.log('Matched at index: ' + possibleValues.indexOf(someString));
}

Upvotes: 1

bluehipy
bluehipy

Reputation: 2294

Yes :))

['s1', 's2', 's3', 's4'].indexOf(s) != -1

Upvotes: 1

Related Questions