Member-only story
Don’t Use If-Else and Switch in JavaScript, Use Object Literals
Write better conditionals in JavaScript with object literals
Writing complex conditionals in JavaScript has always had the potential to create some pretty messy code. Long lists of if/else
statements or switch
cases can get bloated quickly.
When there are multiple conditions, I find object literals to be the most readable way of structuring code. Let’s have a look at how they work.
As an example, let’s say we have a function that takes a rhyming slang phrase and returns the meaning. Using if/else
statements, it would look like this:
This isn’t great. Not only is it not very readable, but we are also repeating toLowerCase()
for every statement.
We could avoid that repetition by assigning the lowercased rhyme to a variable at the start of the function or alternatively use a switch
statement, which would look like this:
We are now only calling toLowerCase()
once, but this still doesn’t feel that readable. switch
statements can also be prone to errors. In this case, we are just returning a value, but when you have more complex functionality, it can be easy to miss a break
statement and introduce bugs.
An Alternative
You can use an object to achieve the same functionality as above in a much neater way. Let’s have a look at an example: