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 !!!
Top comments (4)
switch case
. Alsoswitch case
has a problem from fall through. This is solved in Kotlin.Thanks for your feedback. I haven't worked on python yet and the cautions that you mentioned are worth considering.
Ever heard of "switch"?
Yeah heard of and this could also be an alternative to switch case. I know switch case has better performance time than this alternative.