-1

In the function outer, I am returning a function that uses the same name as a variable declared/defined inside outer.

Why then is a closure not created? Why does the following code print undefined, and not Yolo!?

function inner(){
    console.log('theVar', theVar);
}

function outer(){
    var theVar = 'Yolo!';
    return inner;
}

console.log('Starting...');
outer()();
CodyBugstein
  • 21,984
  • 61
  • 207
  • 363
  • Because `theVar` is not in the scope of `inner()`. The fact that you're returning the function reference from `outer` is irrelevant to what `inner` has access to. – VLAZ Sep 17 '18 at 18:12
  • 1
    Because you haven't defined `inner` *inside* `outer`. https://jsfiddle.net/khrismuc/upchb9dv/ –  Sep 17 '18 at 18:12
  • 1
    A closure is created where the function is **declared** (see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/function) not in all places it is assigned – Denys Séguret Sep 17 '18 at 18:12
  • 2
    Read the text of the `lexical-scope` tag that you yourself added. They're called *lexical* closures for a reason. – Jared Smith Sep 17 '18 at 18:16
  • `function a() { var x = 5; } function b() { console.log(x); } a(); b()` - would you expect these to log the value `5` just because the variables have the same name? No, the `var x` declares a *local* variable – Bergi Sep 17 '18 at 18:17
  • Ok thanks for clearing that up. I see it more clearly now – CodyBugstein Sep 17 '18 at 18:21

1 Answers1

0

var declarations inside a function scope are only accessible within that function, in your case outer()

kamp
  • 375
  • 3
  • 13