Alternatives to if...else Statements in JavaScript (Japanese)

When performing conditional branching in JavaScript, there are various alternative methods in addition to if...else statements. Here, we introduce several ways to substitute if...else statements.

Methods

  1. Switch Statement

  2. Ternary Operator

  3. Jump/Dispatch Tables

  4. Immediately Invoked Function Expressions


Switch Statement

The switch statement searches for the value of a specific expression and executes the corresponding code block. It is convenient when comparing multiple conditions.

Switch

let day = "Monday";
switch (day) {
    case "Monday":
        console.log("It's the beginning of the week.");
        break;
    case "Friday":
        console.log("It's almost the weekend!");
        break;
    default:
        console.log("It's a regular day.");
}

Ternary Operator

The ternary operator checks a condition, and if the condition is true, it executes the first expression; otherwise, it executes the second expression.

Ternary Operator

let age = 18;
let status = (age >= 18) ? "Adult" : "Minor";
console.log(status); // 출력: "Adult"

Jump / Dispatch Table

Jump tables or dispatch tables store pairs of values and functions in an object. They allow for quick retrieval and execution of functions based on values. This simplifies complex conditional logic.

Jump / Dispatch Table

const operations = {
    '+': (a, b) => a + b,
    '-': (a, b) => a - b,
    '*': (a, b) => a * b,
    '/': (a, b) => a / b
};

let operator = '+';
let result = operations[operator](5, 3);
console.log(result); // 8

Dynamic Dispatch

Dynamic dispatch is a method of executing specific versions of methods based on the type of an object. This is primarily used in object-oriented programming.

Dynamic Dispatch

class Shape {
    draw() {
        console.log("Drawing a shape.");
    }
}

class Circle extends Shape {
    draw() {
        console.log("Drawing a circle.");
    }
}

class Square extends Shape {
    draw() {
        console.log("Drawing a square.");
    }
}

let shape = new Circle();
shape.draw(); // 출력: "Drawing a circle."

These alternative methods can make the code more concise and readable while providing better performance in specific situations. As a developer, learning these various approaches allows you to choose the appropriate method based on the context.