Jump to content

JavaScript tutorial: Closure and variable scope


Terence
 Share

Recommended Posts

Hello,

I started learning JavaScript this week and I've been mostly using the JavaScript tutorial.  It's been great, thanks a lot to all the authors!

However, unless I'm mistaken and still don't fully understand, there is some information that I think is wrong or misleading about variable scopes.  It prevented me from understanding closures until I worked through other people's code about main loops and did some testing.
 

On the Function Closures page, it says:
"Local variables have short lives. They are created when the function is invoked, and deleted when the function is finished."
And on the Scope page, it says something similar:
"Local variables are deleted when the function is completed."

But a local variable is not deleted when the function is completed if there is a reference to it left somewhere outside the function.
Of course, normally, there are no references to local variables left outside a function so the local variables are deleted upon exit.  But when we declare a local subfunction that access a local variable and then give this subfunction to an outside object, so long as the outside object exist, the local variable of the original function will not be deleted either because it can still be accessed.

I think this exception should be mentioned on both pages to help beginners (like me) understand how a local variable can still be accessed after the function is was declared in has been completed.


I have some prior experience in C and VBA and I find the scopes of variables in JavaScript to be very different (probably due to not having a way of passing non-object variable references in function arguments).

Or maybe I'm wrong, in which case I would be grateful if someone can explain it to me further.
Thanks
Terence

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

×
×
  • Create New...