If/else statements can prove very useful in performing conditional operations, yet, they usually become very unwieldy very fast!
Consider this simple function:
function studentGrade(score){
if(score > 50){
return 'Pass!';
};
else{
return 'Fail!';
};
};
For a simple operation like this, an if/else block would make sense. But suppose you had a slightly larger set of data, like the one below:
function elementColor(color){
if (color ==='blue'){
return '#00f';
}
else if(color === 'black'){
return '#000';
}
else if (color === 'red'){
return '#f00';
}
else if(color === 'gray'){
return '#999';
}
else if(color === 'orange'){
return '#ff6600';
}
else{
return '#fff';
}
};
I'm sure you are getting the idea. For every new colour entry, the block gets bigger and more prone to error.
This is where Objects come in. By situating your data entries in an Object, you can perform the same operation.
Like this:
function setElementColor(color){
const colorPalette = {
blue: '#00f',
black: '#000',
red: '#f00',
gray: '#999',
orange: '#ff6600',
};
return colorPalette[color] || '#fff';
};
And that's it. Don't forget to like and comment!
Ciao.
Till next time...
Top comments (2)
You can also use
switch
Yes. That would be preferable to an if/else block