0

I'm learning Javascript, and had this question. Here's some sample code:

var xq = false;
var fooyy = function ttt() {
  var xq = false;
  baryy = function() {
    var xq = true;
    console.log(xq);
    console.log(ttt);
    console.log(fooyy);
    console.log(ttt.xq);
    console.log(fooyy.xq);
    console.log(window.xq);
  }();
};

fooyy();
console.log(xq);
console.log(fooyy.xq);

Looking at the output, my question is, so does it mean that from an inner nested function, properties and variables of outer functions can't be accessed (both in the cases of having the same name and otherwise)? Or if they can, could you explain how and why? (I see that the local and global variables are accessible) Thanks!

1
  • 3
    See Closures Commented Jun 15, 2017 at 9:40

2 Answers 2

1

does it mean that from an inner nested function, properties and variables of outer functions can't be accessed?

No. Those are not properties, they are variables. You tried to access them as properties of the functions, which don't exist.

I see that the local and global variables are accessible. What about variables of outer functions (both in the cases of having the same name and otherwise)?

They can be accessed as long as they have different names. This is known as lexical scope, and works even after the outer function has returned - the inner one will form a closure. You can access them simply by their name, they are local variables.

If you do however have a variable of the same name in your local scope, like in your example the variable xq, that local variable will shadow the variable from the outer scope and make it inaccessible. If you want to access it, you need to rename either variable.

Sign up to request clarification or add additional context in comments.

Comments

0

What you have there is a closure, nicely explained in this SO question.

Also, please have a look at this SO question, where people invested lots of effort to explain what a closure is.

In short, baryy function has access to outer variables.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.