DEV Community

Cover image for Simplify if-else statements with Objects
Kenn-stack
Kenn-stack

Posted on

Simplify if-else statements with Objects

If/else statements can prove very useful in performing conditional operations, yet, they usually become very unwieldy very fast!

Consider this simple function:

function studentGrade(score){
    if(score > 50){
        return 'Pass!';
    };

    else{
        return 'Fail!';
    };
};
Enter fullscreen mode Exit fullscreen mode

For a simple operation like this, an if/else block would make sense. But suppose you had a slightly larger set of data, like the one below:

function elementColor(color){
    if (color ==='blue'){
        return '#00f';
    }

    else if(color === 'black'){
        return '#000';
    }

    else if (color === 'red'){
        return '#f00';
    }

    else if(color === 'gray'){
        return '#999';
    }

    else if(color === 'orange'){
        return '#ff6600';
    }

    else{
        return '#fff';
    }
};
Enter fullscreen mode Exit fullscreen mode

I'm sure you are getting the idea. For every new colour entry, the block gets bigger and more prone to error.

This is where Objects come in. By situating your data entries in an Object, you can perform the same operation.

Like this:

function setElementColor(color){
    const colorPalette = {
        blue: '#00f',
        black: '#000',
        red: '#f00',
        gray: '#999',
        orange: '#ff6600',
    };
    return colorPalette[color] || '#fff';    
};
Enter fullscreen mode Exit fullscreen mode

And that's it. Don't forget to like and comment!
Ciao.
Till next time...

Top comments (2)

Collapse
 
alexmustiere profile image
Alex Mustiere

You can also use switch

Collapse
 
kenn-stack profile image
Kenn-stack

Yes. That would be preferable to an if/else block