Frontend Learning — Stop Writing Messy Conditionals - Use Clean Patterns Instead As frontend developers, we often write multiple if-else or nested conditionals… and over time, they become hard to read and maintain. Why Better approach code is better: - Cleaner and more readable - Easy to scale (just add new key) - Avoids deep nesting - Improves maintainability 🧠 Key Takeaway: Whenever you see multiple condition checks, think: “Can I replace this with a cleaner pattern?” #JavaScript #FrontendDevelopment #CleanCode #WebDevelopment #CodingTips #LearnInPublic #DeveloperJourney
On the left, we have the Strategy pattern, and on the right, a HashMap—these solve two different problems. The left one is essentially for a **state machine** (it might even be better to use a **switch-case** there), while the right one is for **key-value lookups**.
I generally use approach 1 because it is easily understandable.
Your approach is good and clearly understandable but there is some issue in code. Role parameters is missing and it's not wrapped in function so cannot return value. const roleAccess = { admin: "1", user: "2", }; function getRoleAccess(role) { return roleAccess[role] || "no access"; }
Conditionals are fine when they're small, but the moment you're tracing nested if-else blocks just to understand the logic, the code has already won. Thinking in patterns early is one of those habits that quietly separates good code from maintainable code.
roleAccess[role] can break TS type checking. I'd prefer to use an enum in cases like this
instead of || use ??;
This is the kind of small tweak that quietly levels up your code. We’ve all written long if/else chains—they get the job done, but can quickly become hard to read and maintain. Refactoring into a simple lookup just makes the code cleaner, easier to follow, and more flexible when things change. It’s not about being clever, it’s about making things simpler for yourself and anyone else who reads your code later. Really liked this example—simple, practical, and actually useful 🙌
Never heard of switch statement, do you? Ok configs like this make sense sometimes (better the the first example), but it's still not ideal.Usually switch statement gives you more flexibility.Also, if you use Typescript (and you should) enum must be used for RoleAccessLevel.I also recommend using ?? operator instead of || for such cases,