Poogy
Poogy

Reputation: 2767

declaring a function inside a function - javascript

I'm trying to build a middleware in redux to handle api requests.

While looking for inspiration I found this code: redux api middleware

export default store => next => action => {
  const callAsync = action[CALL_API];

  if(typeof callAsync === 'undefined') {
    return next(action);
  }

  .
  .
  .

  function actionWith(data) {
    const finalAction = assign({}, action, data);
    delete finalAction[CALL_API];

    return finalAction;
  }

  next(actionWith({ type: types.REQUEST }));
  .
  .
  .
}

My question is: Why is the function actionWith decalared inside of the main function? Wouldn't it be more simple if the function was decalared outside and one will pass the function the action object also?

What is the benefit here?

Upvotes: 0

Views: 45

Answers (1)

apsillers
apsillers

Reputation: 115940

Wouldn't it be more simple if the function was decalared outside and one will pass the function the action object also?

You are correct: you could have take actionWith outside of the outer function as long as you supplied action as an argument (actionWith(data, action)).

The functionality would be the same. However, the primary concern I have is maintainability: if you needed to modify the inner function to do something that required yet another variable from the outer function , you'd need to add another argument. If the duty of the function is closely tied to the internals of the outer function, leaving it in gives you ready access to the outer function's variables when you need to modify the code.

I would balance this concern of extra arguments (which generally favors keeping the function internal) against the usefulness of having the function available to other part of the code (which would favor taking it outside, for increased visibility). For example, if I had many outer functions that each had their own internal copies of actionWith, it would be better to have them to share a single version of actionWith.

That is, if I had

function outer1(action) {
    function actionWith(data) { ... }
    actionWith(thing);
}

function outer2(action) {
    function actionWith(data) { ... }
    actionWith(thing);
}

From a maintainability perspective, I would rather have

function actionWith(action, data) { ... }

function outer1(action) {
    actionWith(action, thing);
}

function outer2(action) {
    actionWith(action, thing);
}

Upvotes: 2

Related Questions