Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript syntax which looks like Array function: [variable] ({ key }, arg) { }

I was ask to study the code of employer, In the code, the employer did something like this:

export const actions = {
  [ACTIONS.ITEM_LIST.LOAD.name] ({commit}, payload) {
    const type = payload

Now, In this, I am unable to rectify this line of code

 [ACTIONS.ITEM_LIST.LOAD.name] ({commit}, payload) {

Like is it a function or what? Can someone explain me the above syntax?

like image 988
anny123 Avatar asked Oct 27 '22 19:10

anny123


1 Answers

New-ish JavaScript allows property names in object literal expressions (what that { } block initializing actions is called) to compute property names from expressions by allowing [ ] for property names instead of identifiers or string constants as in the past.

So what that means is that ACTIONS.ITEM_LIST.LOAD.name should be evaluated, and the string value of whatever that ends up being is used as the name of the function property of the object. (That too is a new-ish feature of the language; formerly properties had to be name : value strictly).

Now inside the formal parameter list to that function, {commit} is a destructuring formal parameter. What it means is that the function expects that the first argument will be an object, and so inside the function the parameter (variable) commit should be bound to the value of that object's "commit" property (or undefined if there is no such property).

So if we assume for example purposes that ACTIONS.ITEM_LIST.LOAD.name evaluates to the string "xyz", then one would be able to call:

var result = actions.xyz({ foo: "bar", commit: "everything" }, somePayload);

and in the function the string "everything" would be the value of the commit parameter.

like image 75
Pointy Avatar answered Oct 31 '22 08:10

Pointy