0

I feel like I come across this a lot and that intuitively, there should be a way to do something like this:

if (userType ==="admin" || userType === "superUser"){
 // do stuff
}

In a more elegant way, like this:

if (userType === ("admin" || "superUser")){
 // do stuff
}

Obviously that^ doesn't work because if the first value resolves to true, it will never check if it's the second ("superuser").

Is there shorthand to do this in a JS if-statement where you wouldn't have to repeat the variable name?

Switch statements don't count! ;D

Joe Roddy
  • 729
  • 6
  • 12

3 Answers3

8

JavaScript doesn't provide out of the box such a syntax.

Now, you can do something of close enough with the Array.includes() method.
It returns true if the element is found in the array.
Otherwise if returns false.

var userTypes = ["admin", "superUser"];
if (userTypes.includes(userType)){
  // do stuff
}

or by inlining the array value :

if (["admin", "superUser"].includes(userType)){
  // do stuff
}
davidxxx
  • 125,838
  • 23
  • 214
  • 215
3

you can use an array with indexOf. something like

if(["superUser", "admin"].indexOf(userType) >= 0){
    //code goes here
}
FabioG
  • 2,936
  • 3
  • 31
  • 50
  • I'm curious if there's an advantage to using '>= 0' rather than the more obvious '!== -1'? It's more obvious, imo, because -1 is what indexOf() returns when the item isn't in the array, which is what we're interested in. Of course, includes() is better than both. – Max Waterman May 25 '20 at 03:40
1

You could use an object for fast checking.

if ({ admin: 1, superUser: 1 }[userType]) {
    // do something if true
}
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
  • Why does this not throw a syntax error? Using `{ admin: 1, superUser: 1}[userType]` on it's own throws one. --- Ah. It's the brackets... never mind. – evolutionxbox Aug 17 '17 at 14:53