An if else alternative
Mitesh Kamat

Mitesh Kamat @miteshkamat27

About: Front End Engineer | Big fan of JavaScript

Location:
India
Joined:
Jan 22, 2020

An if else alternative

Publish Date: Apr 13 '20
5 4

Introduction

This post is about suggesting an alternative to the traditional if else statement.

Consider this if else block

let block= 'j',
    name= '';
if ( block === 'j' )
    name = 'JavaScript';
else if ( block === 'k' )
    name = 'KnockoutJS';
else
    name = 'Guest';

Now, the alternative would be this

let block = 'j';
let name = ({
 j: 'JavaScript',
 k: 'KnockoutJS',
})[block] || 'Guest'
console.log(name);

//Output:
JavaScript

It delivers the same functionality. We are fetching a value from an object literal based on it's key.

We will break it down for understanding.
Consider,

let setValue = 'second';
let points = {
 first: 1,
 second: 2
};

let plot = points[setValue] || 3;

We use this in day to day coding so we can easily relate to the alternative.

The property values can be function too.

let test = 'b';
let fn = ({
a: () => { console.log('first')},
b: () => { console.log('second')}
})[test] || (() => {console.log('outside defined values')})

fn();
//output:
second

Since the properties are functions , you need call the properties as function.

We can also include this in an IIFE.

let test = 'x';
( ( {
    a: () => {
        console.log( 'function a' );
    },
    b: () => {
        console.log( 'function b' );
    },
} )[ test] || ( () => { console.log( 'default function' ); } ) )();

//Output:
default function

Thanks for reading this post.
Cheers !!!

Comments 4 total

  • Pacharapol Withayasakpunt
    Pacharapol WithayasakpuntApr 13, 2020
    • This also works in Python, where there is no switch case. Also switch case has a problem from fall through. This is solved in Kotlin.
    • Cautions are
      • Store function handler itself, not the result
        • Be careful of pre-choice computations
    • Mitesh Kamat
      Mitesh KamatApr 14, 2020

      Thanks for your feedback. I haven't worked on python yet and the cautions that you mentioned are worth considering.

  • punund
    punundApr 13, 2020

    Ever heard of "switch"?

    • Mitesh Kamat
      Mitesh KamatApr 14, 2020

      Yeah heard of and this could also be an alternative to switch case. I know switch case has better performance time than this alternative.

Add comment