changed changed - 1 month ago 9
Javascript Question

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();

Answer

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.