Ad

Why Put An Object Key In Square Brackets (not Destructuring)?

- 1 answer

Look at the example here:

https://github.com/rackt/redux/blob/master/examples/real-world/actions/index.js

return {
    [CALL_API]: {
      types: [ USER_REQUEST, USER_SUCCESS, USER_FAILURE ],
      endpoint: `users/${login}`,
      schema: Schemas.USER
    }
}

CALL_API is in square brackets so I assumed maybe it was an array and this was a destructuring thing.

But CALL_API is defined as

export const CALL_API = Symbol('Call API')

So it's not an array or anything. I've also seen the use of square braces with non-symbols. So what's the difference between

CALL_API: {}

and

[CALL_API]: {}
Ad

Answer

This is a computed property - it's the equivalent of:

let result = {}
result[CALL_API] = { ... };
return result;

Combining this with Symbol lets the library author create a protocol that will not collide with other protocols (e. g. if the protocol was a string "call" then it could collide with other libraries that use someObject.call for their (unrelated) protocols - as well as colliding with Function.prototype.call.)

Ad
source: stackoverflow.com
Ad