Best Practices for Conditional Statements in JavaScript

Best Practices for Conditional Statements in JavaScript

This article explains the best practices for conditional statements in JavaScript.

YouTube Video

Best Practices for Conditional Statements in JavaScript

if statements are a fundamental control structure in JavaScript programs. However, as code becomes more complex, the number of if statements can increase, making the code harder to read. This time, we will delve into the best practices for designing if statements properly in JavaScript to enhance readability and maintainability.

Simplify code using flags.

Simplify conditions involving multiple criteria by using boolean values.

Examples to Avoid

1// Bad Example
2if (isUserLoggedIn && user.hasPaymentInfo && user.cartItems.length > 0) {
3    console.log('Proceed to checkout');
4}

Improved Examples

Use flags to clarify conditions.

1// Good Example
2const canProceedToCheckout = isUserLoggedIn && user.hasPaymentInfo && user.cartItems.length > 0;
3
4if (canProceedToCheckout) {
5    console.log('Proceed to checkout');
6}

Keep Conditional Statements Simple

When a conditional expression becomes complex, code readability decreases, so it is necessary to keep the condition simple.

Examples to Avoid

1// Bad example
2if (user && user.isLoggedIn &&
3    user.permissions && user.permissions.includes('admin')) {
4    console.log('Welcome, admin!');
5}

Improved Examples

By breaking down the condition into variables with specific meanings, you can clarify its intent.

1// Good Example
2const isUserLoggedIn = user?.isLoggedIn;
3const hasAdminPermission = user?.permissions?.includes('admin');
4
5if (isUserLoggedIn && hasAdminPermission) {
6    console.log('Welcome, admin!');
7}

Clarify the precedence of logical operators

In JavaScript if statements, misunderstanding the precedence of logical operators can lead to unintended behavior.

Examples to Avoid

1// Bad example
2if (isAdmin && isActive || isPremium) {
3    // The precedence of `&&` is higher than `||`,
4    // so this expression is interpreted as
5    // ((isAdmin && isActive) || isPremium)
6    console.log("Access granted");
7} else {
8    console.log("Access denied");
9}

Improved Examples

When the precedence of operators is unclear, you can use parentheses appropriately to clarify.

1// Good Example
2if (isAdmin && (isActive || isPremium)) {
3    console.log("Access granted");
4} else {
5    console.log("Access denied");
6}

Utilizing short-circuit evaluation

JavaScript supports short-circuit evaluation for both the && (AND) and || (OR) operators. Short-circuit evaluation means that when the result of a condition is determined during evaluation, the remaining part is not evaluated.

  • AND (&&): If the left-hand side is evaluated as false, the right-hand side is not evaluated and its value is returned.
  • OR (||): If the left-hand side is evaluated as true, the right-hand side is not evaluated and its value is returned.

Examples to Avoid

1// Bad Example
2if (user?.someComplexFunction() && user?.isLoggedIn) {
3    // ...
4}

Improved Examples

In this code, the user?.someComplexFunction() function is called even if user?.isLoggedIn is false.

Understanding short-circuit evaluation can help you avoid unnecessary computations and write efficient code.

1// Good Example
2if (user?.isLoggedIn && user?.someComplexFunction()) {
3    // ...
4}

Minimize the Use of else Statements

else statements can increase cognitive load when tracking the code. Instead, consider utilizing early returns.

Examples to Avoid

1// Bad Example
2function getUserRole(user) {
3    if (!user) {
4        return 'Guest';
5    } else {
6        return user.role;
7    }
8}

Improved Examples

Clarify conditions with early returns.

1// Good Example
2function getUserRole(user) {
3    if (!user) return 'Guest';
4    return user.role;
5}

Proper Use of the Ternary Operator

For simple conditions, using a ternary operator can shorten your code. However, avoid nesting or complex logic.

Examples to Avoid

1// Bad Example
2let message = user.isLoggedIn ? user.isAdmin ?
3                    'Welcome, admin!'
4                    : 'Welcome, user!'
5                    : 'Please log in.';

Improved Examples

Prioritize readability by splitting conditions.

1// Good Example
2if (!user.isLoggedIn) {
3    message = 'Please log in.';
4} else if (user.isAdmin) {
5    message = 'Welcome, admin!';
6} else {
7    message = 'Welcome, user!';
8}

Utilizing default values and short-circuit evaluation

Use default values and short-circuit evaluation to reduce branching and simplify code.

Examples to Avoid

1// Bad Example
2let displayName;
3if (user && user.name) {
4    displayName = user.name;
5} else {
6    displayName = 'Guest';
7}

Improved Examples

In this case, using logical operators makes it more concise.

1// Good Example
2displayName = user?.name || 'Guest';

Properly differentiate between when to use switch statements.

When multiple conditions are needed, switch statements can make intentions clearer.

Examples to Avoid

 1// Bad Example
 2if (status === 'success') {
 3    console.log('Operation was successful.');
 4} else if (status === 'error') {
 5    console.error('There was an error.');
 6} else if (status === 'pending') {
 7    console.log('Operation is still pending.');
 8} else {
 9    console.log('Unknown status.');
10}

Improved Examples

Using switch statements can help organize code.

 1// Good Example
 2switch (status) {
 3    case 'success':
 4        console.log('Operation was successful.');
 5        break;
 6    case 'error':
 7        console.error('There was an error.');
 8        break;
 9    case 'pending':
10        console.log('Operation is still pending.');
11        break;
12    default:
13        console.log('Unknown status.');
14}

Utilizing guard clauses with early exit conditions

A guard clause is a technique that uses if statements to exit a function early.

Examples to Avoid

1// Bad Example
2function processOrder(order) {
3    if (order && order.isValid) {
4        if (order.items && order.items.length > 0) {
5            // Continue processing
6        }
7    }
8}

Improved Examples

Use guard clauses to reduce nesting.

1// Good Example
2function processOrder(order) {
3    if (!order?.isValid) return;
4    if (!order.items?.length) return;
5
6    // Continue processing
7}

Write comments to clarify intentions.

For complex conditions or critical branches, add concise and clear comments to convey the code's intent.

Examples to Avoid

1// Bad Example
2if (stock > 10 && !isRestricted) {
3    console.log('Available for purchase.');
4}

Improved Examples

Add comments to make intentions clear.

1// Good Example
2// The product must have at least 10 items in stock
3// and not be on the restricted list.
4if (stock > 10 && !isRestricted) {
5    console.log('Available for purchase.');
6}

Conclusion

Effectively using JavaScript's if statements can greatly improve code readability and maintainability.

You can follow along with the above article using Visual Studio Code on our YouTube channel. Please also check out the YouTube channel.

YouTube Video