Beyond if‑else: 9 Cleaner JavaScript Patterns for Conditional Logic

This article presents nine practical JavaScript techniques—ranging from object maps and Array.includes to ternary chains, logical operators, switch statements, Proxy, functional patterns, state machines, and decorators—that replace verbose if‑else statements with cleaner, more maintainable code.

JavaScript
JavaScript
JavaScript
Beyond if‑else: 9 Cleaner JavaScript Patterns for Conditional Logic

1. Object mapping instead of if‑else

Traditional version

function getPrice(user) {
  if (user.type === 'vip') {
    return 'VIP价格';
  } else if (user.type === 'svip') {
    return 'SVIP价格';
  } else if (user.type === 'vvip') {
    return 'VVIP价格';
  } else {
    return '普通价格';
  }
}

Alternative version

const priceStrategy = {
  vip: () => 'VIP价格',
  svip: () => 'SVIP价格',
  vvip: () => 'VVIP价格',
  default: () => '普通价格'
};

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 operator

Traditional version

Alternative version

4. Clever use of && and || operators

5. Switch pattern matching

6. Using Proxy for condition interception

7. Functional programming methods

8. State machine pattern

9. Using decorators to handle permissions

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() {
    // 编辑文档
  }
}
JavaScriptcode refactoringbest practicesConditional LogicProgramming Patterns
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.