skip to Main Content

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


  1. Perhaps if you think of the code as

    const lookup = {
      success: 'check',
      info: 'info-circle',
      warning: 'exclamation-circle',
      error: 'exclamation-triangle',
    };
    
    function typeToIcon(type) {
      return lookup[type];
    }
    
    console.log(typeToIcon('info'));

    it’ll make sense to you

    The code in your question just uses the object inline in the return statement

    Login or Signup to reply.
  2. 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

    Login or Signup to reply.
  3. 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.

    function typeToIcon(type) {
      dict =  {
        success: 'check',
        info: 'info-circle',
        warning: 'exclamation-circle',
        error: 'exclamation-triangle',
      };
      value = dict[type];
      return value;
    }
    
    // Log to console
    console.log(typeToIcon('info'));
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search