Search code examples
ecmascript-6arrow-functions

ES6/8 syntax - arrow functions


The two of the following result in different things although they look like the same thing.

1

const addBlogPost = dispatch => {
    return () => {
        dispatch({type: 'add_blogpost'});
    }
};

2

const addBlogPost = dispatch => dispatch({type: 'add_blogpost'});

Could anyone point out how are they different?


Solution

  • You can use this site to compile es6 arrow functions to vanilla JS to easily see the difference.

    The first one compiles to this

    var addBlogPost = function addBlogPost(dispatch) {
      return function () {
        dispatch({
          type: 'add_blogpost'
        });
      };
    };
    

    While the second compiles to this

    var addBlogPost = function addBlogPost(dispatch) {
      return dispatch({
        type: 'add_blogpost'
      });
    };
    

    The first returns a function that has a dispatch while the second one returns a dispatch directly.