Not familiar with this javascript syntax I came across

I just started a new job, and I have some React code to support, there a file called there authenticationHandlers.jsis 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 have no questions about the functionality of the code, but what does the parenthesis syntax in the lines [events.Erorred.Name]and[events.ClearError.Name]

In other words, what do the brackets mean?

+4
source share
2 answers

This means that you can use the variable as the name of the property:

For instance:

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]();
Run codeHide result
+5
source

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

+2

Source: https://habr.com/ru/post/1655202/


All Articles