szh
szh

Reputation: 166

What is the syntax {object}[index] called?

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

Upvotes: 1

Views: 121

Answers (2)

Alexey Victorov
Alexey Victorov

Reputation: 433

{
    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.

Upvotes: -1

Mureinik
Mureinik

Reputation: 311143

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

Upvotes: 2

Related Questions