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


The key advantage of using a lookup table over traditional conditional structures like if-else or switch statements is that lookup table turns multiple instances of comparative logic into data.

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

in the above example, there is only one logic check using a ternary operation for the default fallback.

const colorHexCode = {
blue: '#4169E1',
green: '#98FF98',
butter: '#FFE4C9',
pink: '#E78895',
default: '#B4B4B8',
};
const setColor = (color) => {
let colorHexCode = '';
document.getElementById('button').style.color = colorHexCode[color] || colorHexCode['default'];
};

in the above example, there is only one logic check but we avoid ternary operation and use OR operator for the default fallback.

In the above two examples, the code illustrates the logic as a single operation, making it more expressive. Additionally, the code becomes easier to test due to the minimized logic. By consolidating our comparisons into pure data, we ensure improved maintainability.



Source link

Leave a Reply

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