Conditions
Use simple, flat conditions over nested, complex ones
Use simple, flat conditions over nested, complex ones means to use conditions that are easy to read and understand, rather than using conditions with multiple levels of nesting or complexity.
For example, instead of using a nested condition like this:
if (a === 1) {
if (b === 2) {
if (c === 3) {
console.log("A, B, and C all equal 1, 2, and 3, respectively.");
} else {
console.log("A and B equal 1 and 2, but C does not equal 3.");
}
} else {
console.log("A equals 1, but B does not equal 2.");
}
} else {
console.log("A does not equal 1.");
}
It would be better to use a simple, flat condition like this:
if (a === 1 && b === 2 && c === 3) {
console.log("A, B, and C all equal 1, 2, and 3, respectively.");
} else {
console.log("A, B, or C do not equal the expected values.");
}
Use braces to define blocks of code controlled by conditions
Braces clearly indicate the beginning and end of the block of code that is being controlled by the condition, which can help to avoid confusion and prevent errors. Also, they can help to prevent issues with indentation, as the block of code will always be clearly defined, even if it spans multiple lines.
// 🚫 Bad
if (userAge < 21)
redirectToDisneyHomepage()
// 🚫 Bad - Even if it's on the same line
if (userAge < 21) redirectToDisneyHomepage()
// ✅ Good
if (userAge < 21) {
redirectToDisneyHomepage()
}
Use strict comparisons in conditions
Using strict comparisons in conditions can help to avoid unintended type coercion and can make the code more predictable and easier to debug.
Strict comparisons use the triple equals operator (===
) or the exclamation equals operator (!==
) to compare values, and they do not perform type coercion.
This means that the values being compared must be of the same type in order for the comparison to be true.
// 🚫 Bad - Non-strict comparison
if (value1 == value2) {
// Do something
}
// ✅ Good - Strict comparison
if (value1 === value2) {
// Do something
}