Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

es6 hash array index function call mixed syntax

What kind of ES6 syntax is this?

{
  [ActionTypes.Repo](state, { username, res }) {
    /* ... */
  },

  [ActionTypes.Repo2](state, { username, res }) {
    /* ... */
}

Taken from : https://github.com/quangbuule/redux-example/blob/master/src/js/reducers/Repo.js

like image 982
eguneys Avatar asked Jul 13 '15 11:07

eguneys


1 Answers

Those are method definitions, computed property names and destructuring at work.

Method definitions provide a concise way to create properties that contain functions:

// before
var obj = {
  foo: function() {}
};

// now
var obj = {
   foo() {}
};

That's the same syntax for creating methods in class definitions.

Computed properties allow you to use the result of any expression as property name in an object literal:

var foo='somePropertyName';

// before
var obj = {};
obj[foo] = 42;

// now

var obj = {
  [foo]: 42
};

And of course this also works with method definitions:

var obj = {
  [foo]() {}
};

Destructuring is like pattern matching and makes it easier to refer to nested properties of an array/object if thats all you need:

// before
function foo(obj) {
  var username = obj.username;
  var res = obj.res;
}

// now
function foo({username, res}) {

}
like image 68
Felix Kling Avatar answered Nov 04 '22 22:11

Felix Kling