Jason Knight
1 min readNov 8, 2021

--

Your example checking the same variable over and over again SCREAMS for the use of either case, or an object lookup.

There's nothing wrong with single ternary any more than using logical or on assignment/return. Also since alert returns undefined, there is no reason you couldn't alert() instead of "", skipping your entire latter statement.

The "variable for nothing" not helping matters much either. Just return the confirm on each one rather than having the "ask" variable. Short-circuits out the logic too.

using case I’d do it thus:

function confirmHeirarchy(identity) {
switch (identity) {
case "Employee":
return confirm("You confirm that you are an employee?");
case "Manager":
return confirm(""Are you sure you are a manager?");
case "Director":
return confirm("Are you really sure you are director? Please confirm.");
case "Intern":
return confirm("You fonfirm that you are an intern?");
}
alert("Unknown Heriarchal Position");
}

No extra wasteful variables, far more legible, etc, etc.

Though in production these days I’d probably do this.

function confirmHeirarchy(identity) {
identity = confirmHeirarchy.responses[identity];
return identity ? confirm(identity) : alert("Unknown Heriarchal Position");
}
confirmHeirarchy.responses = {
Employee : "You confirm that you are an employee?",
Manager : "Are you sure you are a manager?",
Director : "Are you really sure you are director? Please confirm.",
Intern : "You fonfirm that you are an intern?"
};

Reusing the identity argument to avoid making new allocations, a ternary since there’s only two types of states, and an easy object containing our key/value pairs.

--

--

Jason Knight
Jason Knight

Written by Jason Knight

Accessibility and Efficiency Consultant, Web Developer, Musician, and just general pain in the arse

No responses yet