-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 stands with Ukraine
  • 25,310
  • 18
  • 114
  • 149
Pathum Kalhan
  • 5,597
  • 21
  • 62
  • 114

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,621
  • 24
  • 39
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,860
  • 7
  • 28
  • 53
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,621
  • 24
  • 39
Azad
  • 4,966
  • 3
  • 27
  • 53