Skip to content
The Chat Archive
gpt-3.5-turbo-0301· OpenAI WildChat-4.8M (AI2)

how can i avoid adding ternary statements like this const icon = type === "SUCCESS" ?…

  1. User

    how can i avoid adding ternary statements like this const icon = type === "SUCCESS" ? successIcon : warningIcon; const alt = type === "SUCCESS" ? "Success icon" : "Warning icon";

  2. Assistant

    There are a few ways to avoid ternary statements like this:

    1. Use switch statements instead:
    let icon, alt;
    switch (type) {
      case "SUCCESS":
        icon = successIcon;
        alt = "Success icon";
        break;
      case "WARNING":
        icon = warningIcon;
        alt = "Warning icon";
        break;
      default:
        icon = defaultIcon;
        alt = "Default icon";
    }
    
    1. Use an object to map values:
    const iconMap = {
      SUCCESS: {
        icon: successIcon,
        alt: "Success icon"
      },
      WARNING: {
        icon: warningIcon,
        alt: "Warning icon"
      },
      DEFAULT: {
        icon: defaultIcon,
        alt: "Default icon"
      }
    };
    
    const {icon, alt} = iconMap[type] || iconMap.DEFAULT;
    
    1. Use a function to handle the logic:
    function getIconAndAlt(type) {
      if (type === "SUCCESS") {
        return {icon: successIcon, alt: "Success icon"};
      } else if (type === "WARNING") {
        return {icon: warningIcon, alt: "Warning icon"};
      } else {
        return {icon: defaultIcon, alt: "Default icon"};
      }
    }
    
    const {icon, alt} = getIconAndAlt(type);