3

I have found myself writing a lot of functions comprising of nested functions.

I like to use this pattern when doing so, as I find them easy to find again using the eclipse outline view

var outer_func = function(){

  var inner_func1 = function(){
  //code
  }
  var inner_func2 = function(){
  //code
  }

}

My question: Is there any scoping differences if I drop the var keyword from the nested/inner functions?

thanks for any advice.

Chin
  • 12,582
  • 38
  • 102
  • 152

3 Answers3

1

If you leave off the inner var keyword, then you will be creating global functions named inner_func1 and inner_func2. Keep the var.

Ned Batchelder
  • 364,293
  • 75
  • 561
  • 662
1

Yes, the "inner" functions will become global when the outer function is executed. In general, it is better to use function declarations because they are processed first.

function outer() {
  function inner() {
  }
  ...
}

Only use expressions where you have a need to define a function at some later time, e.g. based on some condition that is not known until later.

RobG
  • 142,382
  • 31
  • 172
  • 209
1

Functions are their own domain, local variables are only exposed down the execution stack. (or what most refer to as the proverbial 'scope') If a variable is declared without locality (being local.), it goes straight to window (global) object and is not trash collected upon function completion. So for instance:

function somefunc(){
   var a;
   function nested(){
      a=2;//this will edit parent function's variable a
   }
   function anothernested(){
      var b=5;//this will create local variable in nested function
      c=3;//this will create global variable
   }
   nested();
   console.log(a);
}
TERMtm
  • 1,903
  • 3
  • 23
  • 29
  • Please only use terms that are relevant to ECMA-262. Indiscriminate use of jargon only confuses ("own domain", "down the execution stack", "locality", etc.). The word you are looking for is *scope*. – RobG Jun 20 '12 at 03:46
  • Thanks, fixed, however 'stack' is perfectly valid. For instance what this website is named after. – TERMtm Jun 20 '12 at 07:43
  • Yes, [Execution contexts](http://es5.github.com/#x10.3) form a stack. [Scope](http://es5.github.com/#x8.6.2) includes the variables of the stacked [lexical environments](http://es5.github.com/#x10.2) but may include other variables, e.g. using closures and [with statements](http://es5.github.com/#x12.10)). Stacks are also used as a control mechanism to determine where a function returns to. In that context, it's completely different to scope (e.g. called functions don't have access to the variables of the function that called them, they are in the same stack but have a different scope). – RobG Jun 20 '12 at 23:15
  • Well ok, I yield, thx for info. – TERMtm Jun 21 '12 at 01:33