How to Make Your Conditional Statements Easier to Read in JavaScript
One of the most powerful tools that all programming languages provide is the ability to conditionally run code, creating branches of code that runs only when certain conditions are met. In JavaScript, as in many other languages, this is called conditionals. JavaScript has 3 primary types of conditionals: If/else blocks, switch statements, and conditional expressions. These 3 tools can help you write some very awesome code.
Just like anything, conditionals done wrong can also lead to some very complicated code that is hard to follow and even harder to maintain. Following some good principles, you can use these conditionals to your advantage.
The Basics of JavaScript Conditionals
As I said earlier, JavaScript has 3 primary types of conditionals. The first is the if/else block. The basic of the if statement is very simple: if the condition is true, the code block will be run. For example:
if (condition){
// code that will be run only if condition is true
}
If blocks also can create two blocks of code, based on the same condition by adding the else
keyword, like this:
if (condition){
// code that will be run only if condition is true
} else {
// otherwise this code will…