Member-only story
Clean Up Your Code by Removing ‘if-else’ Statements
A step-by-step guide to making your JavaScript code more elegant.
When we write JavaScript code, we often encounter the situation of complex logic judgment. Generally, you can use if/else or switch to implement multiple conditional judgments, but there will be a problem: With the increase of logic complexity, if/else and switch in the code will become more and more bloated. This article will take you to try to write more elegant judgment logic.
A simple scenario: Suppose Jon is waiting for the result of an exam, and he plans a vacation based on his exam score.
The exam result is divided into 4 rankings: A, B, C, and D:
- If Jon gets an A, he rewards himself and goes for travel happily.
- If Jon gets a B, the reward drops to normal shopping.
- If Jon gets a C, he stays home and watches TV.
- If Jon gets a D, he’ll go to the library and work on the subject.
If we had to write a function to describe this behavior, what would you write?
if-else
It would be natural to use the if-else statement to write code like this: