1

In React, I use this kind of syntax often for conditional rendering:

const exampleState = 1;

const retval = {
    0: "Value for state 0",
    1: "Value for state 1",
    2: "Value for state 2",
}[exampleState]

// this returns "Value for state 1"

What is this syntax called?

Edit: added const retval to make it actually valid code

wwsalmon
  • 146
  • 12
  • 1
    Does this answer your question? [What does this symbol mean in JavaScript?](https://stackoverflow.com/questions/9549780/what-does-this-symbol-mean-in-javascript) – Ivar Nov 18 '20 at 20:54
  • 1
    In this case "invalid". Although, I assume you mean [bracket syntax](https://stackoverflow.com/questions/4968406/javascript-property-access-dot-notation-vs-brackets). It's a type or property access. – VLAZ Nov 18 '20 at 20:56
  • 2
    There is nothing special about this syntax. You have just declared an object but it is a temporary as you didn’t assign it to a variable. You then just get the property with key 1 of the temporary object. – Paul Rooney Nov 18 '20 at 20:56
  • @VLAZ fixed the code. Bracket syntax is it, I was just overthinking it and trying to find a name for a specific shorthand when it's just an object declared and accessed in the same line as Paul Rooney says above. Thanks for the quick reply! – wwsalmon Nov 18 '20 at 21:19
  • @PaulRooney super simple once you point it out, I was just overthinking it before, thanks for the quick reply! – wwsalmon Nov 18 '20 at 21:20

2 Answers2

2

The { } block defines an object. The [] part is a bracket notation of a property accessor.

Mureinik
  • 252,575
  • 45
  • 248
  • 283
  • "*The { } block defines an object*" only in this case, it defines a block with labels. – VLAZ Nov 18 '20 at 20:56
  • 1
    @Teemu If one uses *literally* the same code as OP shows, then `{ }` does *not* define an object but a code block. A `{` in the beginning of the line will not interpreted as an object literal syntax. Since this will be parsed as a code block, the `0:` should be [a label](https://stackoverflow.com/questions/39655737/what-does-the-javascript-syntax-foo-mean). However, a label cannot start with a number, therefore the code in the OP will throw a syntax error. Nothing to do with object's keys, as there *aren't* any objects or keys defined. – VLAZ Nov 18 '20 at 21:06
  • This is what I needed, somehow I didn't realize that it was this simple and I was looking for some short of shorthand to call it...thanks! – wwsalmon Nov 18 '20 at 21:15
-1
{
    0: "Value for state 0",
    1: "Value for state 1",
    2: "Value for state 2",
}

is a key: value pair object.

So your code returns the value of key 0 from this object.

Alexey Victorov
  • 242
  • 1
  • 9