DEV Community

Mitesh Kamat
Mitesh Kamat

Posted on

An if else alternative


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';
    name = 'Guest';

Now, the alternative would be this

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


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.

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')})


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' ); } ) )();

default function

Thanks for reading this post.
Cheers !!!

Top comments (4)

patarapolw profile image
Pacharapol Withayasakpunt • Edited
  • 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
miteshkamat27 profile image
Mitesh Kamat

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

punund profile image

Ever heard of "switch"?

miteshkamat27 profile image
Mitesh Kamat

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