10 Cleaner Alternatives to if‑else in JavaScript

This guide shows how to replace verbose if‑else chains in JavaScript with cleaner techniques such as object mapping, Array.includes, ternary operators, logical shortcuts, switch statements, Proxy interception, functional patterns, state machines, and decorators, providing concise code examples for each method.

JavaScript
JavaScript
JavaScript
10 Cleaner Alternatives to if‑else in JavaScript

If you rely on traditional if‑else statements for complex conditions, your code can become verbose and hard to maintain; this article presents several concise alternatives.

1. Object mapping instead of if‑else

Traditional version

function getPrice(user) {
  if (user.type === 'vip') {
    return 'VIP price';
  } else if (user.type === 'svip') {
    return 'SVIP price';
  } else if (user.type === 'vvip') {
    return 'VVIP price';
  } else {
    return 'Regular price';
  }
}

Alternative version

const priceStrategy = {
  vip: () => 'VIP price',
  svip: () => 'SVIP price',
  vvip: () => 'VVIP price',
  default: () => 'Regular price'
};

function getPrice(user) {
  return (priceStrategy[user.type] || priceStrategy.default)();
}

2. Using Array.includes for multiple conditions

Traditional version

if (status === 'failed' || status === 'error' || status === 'rejected') {
  handleError();
}

Alternative version

const errorStatus = ['failed', 'error', 'rejected'];
if (errorStatus.includes(status)) {
  handleError();
}

3. Chained ternary operators

4. Clever use of && and || operators

5. Switch pattern matching

6. Using Proxy for condition interception

7. Functional programming approaches

8. State machine pattern

9. Decorator for permission checks

function checkPermission(target, name, descriptor) {
  const original = descriptor.value;
  descriptor.value = function(...args) {
    if (this.user?.hasPermission) {
      return original.apply(this, args);
    }
    throw new Error('No permission');
  };
  return descriptor;
}

class Document {
  @checkPermission
  edit() {
    // edit document
  }
}

Feel free to add more examples.

design-patternsJavaScriptcode refactoringif-elseConditional Logic
JavaScript
Written by

JavaScript

Provides JavaScript enthusiasts with tutorials and experience sharing on web front‑end technologies, including JavaScript, Node.js, Deno, Vue.js, React, Angular, HTML5, CSS3, and more.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.