Name of this switch operator syntax

Issue

I am constantly finding this sort of switch statement in a codebase and not being able to find documentation about it anywhere. Does anyone know the name of this syntax?

import React from 'react'

enum Options {
    FirstOption = 'first',
    SecondOption = 'second'
}

export default function DisplayIcon({selectedOption: string}) {

  const clickFirst = () => {
      // do something
  }

  const clickSecond = () => {
      // do something
  }

  return (
    <Wrapper>
    {
      {
        [Options.FirstOption]: (
          <ClickableIcon onClick={ clickFirst }>
            <Icon type={ IconType.Frist } />
          </ClickableIcon>
        ),
        [Options.SecondOption]: (
          <ClickableIcon onClick={ clickSecond }>
            <Icon type={ IconType.Second } />
          </ClickableIcon>
        ),
      }[selectedOption]
    }
  </Wrapper>
  )
}

Solution

It’s not a switch statement at all, though you’re right it’s being used to select a value. It’s an object literal with computed property names. So it’s building an object, then picking out the property matching selectedOption from that object, all in the same expression.

Here’s a simpler example of the object literal part with computed property names:

const name1 = "a";
const name2 = "b";
const obj = {
    [name1]: "value for a",
    [name2]: "value for b",
};
console.log(obj);

And here’s an example of what that code is doing with building the object and then immediately grabbing one of its properties:

const name1 = "a";
const name2 = "b";
const pickOne = Math.random() < 0.5 ? name1 : name2;
const pickedValue = {
    [name1]: "value for a",
    [name2]: "value for b",
}[pickOne];
console.log(`Picked "${pickOne}": "${pickedValue}"`);

FWIW, I wouldn’t do it that way. I’d either define the object once and reuse it, or use a switch or if/else if or similar in the code prior to the return.

Answered By – T.J. Crowder

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published