I came across a code in github like this :
function typeToIcon(type) {
return {
success: 'check',
info: 'info-circle',
warning: 'exclamation-circle',
error: 'exclamation-triangle',
}[type];
}
// Log to console
console.log(typeToIcon('info'));
Can someone explain the working behind this logic? How is it working? What is this called in JS? I have never seen a conditional statement like this before.
3
Answers
Perhaps if you think of the code as
it’ll make sense to you
The code in your question just uses the object inline in the return statement
it return an object which have some keys like: success, info, warning, error.
To access to object by key (in this case is parameter
type
), you need to use square bracket like: objectTypeIcon[type]typeToIcon(‘info’) -> info-circle
ref: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Property_accessors#bracket_notation
It’s not a condition.
This function creates an object with the keys ‘success’, ‘info’, ‘warning’, and ‘error’, and by calling it with the type parameter it is responding with the value hard-coded into that dictionary.
For better understandability, here is the code in a more readable version.