pishpish
pishpish

Reputation: 2614

When to nest functions in javascript?

If I am not worried about polluting the global scope and the only place where function b() is getting called from is function a(), which of the following is in terms of performance a better solution?

var v;
function a()
{
    function b()
    {
        v*=v;
    }
    v=5;
    b();
}
a();

or

var v;
function a()
{
    v=5;
    b();
}
function b()
{
    v*=v;
}
a();

Upvotes: 0

Views: 331

Answers (2)

pishpish
pishpish

Reputation: 2614

Looking at my question three years later, I wish to provide a more satisfactory answer.

If the inner function will be used elsewhere, don't nest it. For obvious reasons.

function a(){
  // ...
}
function b(){
  // ...
  a();
}

a();
b();

If the inner function will not be used elsewhere, nest it. It looks cleaner, and increases the outer function's logical integrity (relevant stuff is visually enclosed).

function b(){
  function a(){
    // ...
  }

  // ...
  a();
}

b();

If the inner function will not be used elsewhere and the outer function will be called more than once, make a closure out of it and define the inner in the enclosed scope. This way it won't be redefined on each call. This makes more sense when the inner function is complicated and/or the outer function is called many times.

var b = (function b(){
  function a(){
    // ...
  }

  return function(){
    // ...
    a();
  };
}());

b();
b();

Other performance impacts are negligible.

Upvotes: 1

Domenico De Felice
Domenico De Felice

Reputation: 465

When you use a symbol, its associated value is looked for in the chain of environments, starting from the inner one and moving outwards. This means that the inner (local) environment is found first than the global one but there is no real difference in performance.

To choose which solution to adopt just ask yourself:

  • the inner function could be useful to some other function in the future?

and if not,

  • can I abstract the inner function in a way that creates a more general function that could be useful elsewhere?

Upvotes: 2

Related Questions