DEV Community

Discussion on: Stop! Put Down That Ternary, Lines Are Free

Collapse
 
jayjeckel profile image
Jay Jeckel

No, pjotre86 is completely right.

If we have an alien manager as the admin, then the variable values are:

isAdmin = true;
isManager = true;
isAlien = true;
Enter fullscreen mode Exit fullscreen mode

The ternary version returns the correct result, "All Allowed", because our alien manager is an admin.

const result = isAdmin ? "All Allowed" : isManager ? "Some Allowed" : isAlien ? "Run" : "Not Allowed";
// result == "All Allowed"
Enter fullscreen mode Exit fullscreen mode

However, the offered serial if statements return the wrong result value, "Run", treating our manager as a low permissioned alien instead of a high permissioned admin.

let result = "Not Allowed";
if (isAdmin) { result = "All Allowed"; }
// result == "All Allowed"
if (isManager) { result = "Some Allowed"; }
// oops, the admin is also a manager, so now result == "Some Allowed"
if (isAlien) { result = "Run"; }
// oops again, the admin manager is also an alien, so now result == "Run"
Enter fullscreen mode Exit fullscreen mode

If the ternary is going to be converted into if statements, then they should be if-else statements.

let result = "Not Allowed";
if (isAdmin) { result = "All Allowed"; }
else if (isManager) { result = "Some Allowed"; }
else if (isAlien) { result = "Run"; }
// result == "All Allowed"
Enter fullscreen mode Exit fullscreen mode

Now our alien manager is rightly given their admin level permissions.