Using a hash map instead of a switch statement

Tuesday, February 07, 2023

Exploring Hash maps Over Switch Statements in JavaScript


In the realm of JavaScript, developers often seek more readable, maintainable, and efficient ways to handle conditional logic. A recent trend is the use of hash maps over traditional switch statements. This post delves into a practical example to highlight the benefits of this approach.

The Code

The provided code demonstrates a function named choose. It utilizes a hash map (an object in JavaScript) to manage different cases. The hash map contains functions as values, keyed by strings. There's also a default key to handle cases where the key doesn't exist in the map.

Advantages of Using Hash maps

  1. Readability: Hash maps can be more straightforward to read, especially for those familiar with JavaScript's object notation.

  2. Consistency with JavaScript Patterns: Unlike switch statements, which are somewhat unique in JavaScript's syntax, hash maps align well with common JavaScript patterns.

  3. Portability: Hash maps can be easily passed around as objects, enhancing code modularity.

  4. Flexibility: Additional benefits include easier modification and extension of logic without the need to alter a complex switch statement.

Example in Action

The code example shows the function choose being called with different keys. The output is determined by the existence of the key in the hash map. If the key exists, the corresponding function is executed. If not, the default function is called.


Switching to hash maps from switch statements can offer several advantages in JavaScript programming. It aligns well with the language's paradigms and offers improved readability and flexibility. As with any coding technique, the best approach depends on the specific context and requirements of the project.

Hash map...

// returns the default if the key doesn't exist
function choose(key) {
    const data = {
        abc: () => "Yep - key exists",
        def: () => data["abc"](), // duplicates abc
        default: () => "Nope - default!"

    return data[data[key] ? key : "default"]();

Versus the traditional switch statement...

function choose(key) {
    switch (key) {
        case 'abc':
            return "Yep - key exists";
        case 'def':
            return choose("abc"); // duplicates abc
            return "Nope - default!";

Check out this CodePen to see it in action