-3

I got a role from the back-end If it is equals to "admin" , "staff", "manager" it should go to the if part of the block. otherwise it should go to the else part of the block.

let role = "restaurant";

if(role === "admin" || "manager" || "staff"){
  console.log("IF PART")
  console.log(role)
}
else{
  console.log("ELSE PART")
}

In this scenario it comes to if part. What's wrong with my code?

Zoe
  • 27,060
  • 21
  • 118
  • 148
margherita pizza
  • 6,623
  • 23
  • 84
  • 152

3 Answers3

1

Your if condition is wrong. This should be like

let role = "restaurant";

if(role === "admin" || role === "manager" || role === "staff"){
  console.log("IF PART")
  console.log(role)
}
else{
  console.log("ELSE PART")
}
Lokesh Pandey
  • 1,739
  • 23
  • 50
1

Your if condition is wrong, you are suppose to compare role variable with the role you want to check. As @lokesh mentioned in his code.

(role === "admin" || role === "manager" || role === "staff")

Another way of doing this:

let role = "restaurant";
    
if(["admin", "manager", "staff"].includes(role)){
  console.log("IF PART")
  console.log(role)
}
else{
  console.log("ELSE PART")
}

includes available in majority of browsers for IE you can use indexOf.

Pardeep Dhingra
  • 3,916
  • 7
  • 30
  • 56
1

I think, you can do more accurately as follows

let role = "restaurant";

if (["admin", "manager", "staff"].indexOf(role.toLowerCase()) >= 0) {
  console.log("IF PART")
  console.log(role)
} else {
  console.log("ELSE PART")
}
Lokesh Pandey
  • 1,739
  • 23
  • 50
Azad
  • 5,144
  • 4
  • 28
  • 56