4

I just started a new job and I have some React code to maintain, there's a file called authenticationHandlers.js this is what the code looks like inside the file.

const events = require("./authenticationEvents.js");

const authenticationHandlers = {
    [events.Errored.Name](prev, event) {
         const update = {
             UnauthorizedError: event.Error
        };

        return Object.assign({}, prev, update);
    },
    [events.ClearError.Name](prev, event) {
        const update = {
            UnauthorizedError: null
        };

        return Object.assign({}, prev, update);
    }
};

module.exports = authenticationHandlers;

I don't really have any questions about the functionality of the code but what does the bracket syntax do at lines [events.Erorred.Name] and [events.ClearError.Name]

In other words what do the brackets mean?

Josh Siegl
  • 675
  • 1
  • 9
  • 16

2 Answers2

5

It is so that you can use a variable as a property name:

For example:

const a = 'banana';
const fnName = 'pudding';

const b = {
    [a]: 42,
    [fnName]() {
        console.log(`I am logging from ${fnName}`);
    }
};

console.log(b); //{banana: 42, pudding: fn}
b[fnName]();
Naftali aka Neal
  • 138,754
  • 36
  • 231
  • 295
2

That is called computed property names. See http://es6-features.org/#ComputedPropertyNames

Maurice
  • 27,324
  • 5
  • 46
  • 61