Escaping if-else maze in JavaScript | by Sabesan Sathananthan | Apr, 2024


The important thing benefit of utilizing a lookup desk over conventional conditional buildings like if-else or swap statements is that lookup desk turns a number of situations of comparative logic into knowledge.

const colorHexCode ={
'blue': '#4169E1',
'inexperienced': '#98FF98',
'butter': '#FFE4C9',
'pink': '#E78895',
'default': '#B4B4B8'
}
const setColor = (shade) => {
let colorHexCode = '';
doc.getElementById('button').fashion.shade = colorHexCode[color]? colorHexCode[color]: colorHexCode['default'];
};

within the above instance, there is just one logic examine utilizing a ternary operation for the default fallback.

const colorHexCode = {
blue: '#4169E1',
inexperienced: '#98FF98',
butter: '#FFE4C9',
pink: '#E78895',
default: '#B4B4B8',
};
const setColor = (shade) => colorHexCode['default'];
;

within the above instance, there is just one logic examine however we keep away from ternary operation and use OR operator for the default fallback.

Within the above two examples, the code illustrates the logic as a single operation, making it extra expressive. Moreover, the code turns into simpler to check because of the minimized logic. By consolidating our comparisons into pure knowledge, we guarantee improved maintainability.

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *