If this is your first visit, be sure to
check out the FAQ by clicking the
link above. You may have to register
before you can post: click the register link above to proceed. To start viewing messages,
select the forum that you want to visit from the selection below.

Enjoy an ad free experience by logging in. Not a member yet? Register.

global vs local-Please help to understand the principle

I was wondering if you could take a look at the code below that i have found in a book:

Code:

var a = 123;
function f() {
alert(a);
var a = 1;
alert(a);
}
f();

When the function f is called, the first alert shows underfined and the second shows 1. The books says this happens because "inside the function the local scope is more important than the global scope. So a local variable overwrites any global variable with the same name. At the time of the first alert() a was not yet defined (hence the value undefined) but it still existed in the local space."

I have a problem understanding how it works. My question, is at what stage, the local variable overwrites a global variable? At the stage of defining the function or calling it? I just want to have a clear picture in my heads what is going on. thank you very much.

All the local variables referenced within a function are declared as local variables before any of the code in the function runs. Effectively it is as if you had one var at the top of the function with all of the variables declared using var within the function as a comma separated list after it - as that is where all the declarations run it makes your code easier to read if you actually put the declarations there.

With modern strict JavaScript all variables need to be declared and your script will fail to run if you try to use one that isn't declared. Also by wrapping ALL of your code in anonymous functions you can avoid using global variables almost completely - with only one or two being needed to provide access to shared libraries.

A strict and unobtrusive version of that code would look like this:

Code:

(function() {"use strict";
var a = 123;
function f() {
var a; // declaration moved to where it is actually run
alert(a); // used just to demonstrate that at this point the local variable is declared but undefined
a = 1;
alert(a);
}
f();
})();

With that code the first variable set to 123 is local to the outer function and so will not clash with any similarly named variable in any other script you add to the same web page.

Users who have thanked felgall for this post:

It is very poor practice to use two variables with the same name, even if one is local and the other global. There is absolutely no reason for doing this. Also, it is best to devise variable names which are meaningful and indicate the content - not meaningless "a", but (say) "firstnumber" or "customernumber".

All the code given in this post has been tested and is intended to address the question asked.
Unless stated otherwise it is not just a demonstration.

Your JavaScript shouldn't be using many global variables at all. For example if you are using jQuery then the only global variable you should have in your code is jQuery. Would you really reference that as window.jQuery rather than simply as JQuery throughout your code?

With the OP's code written properly neither variable would be global and trying to reference the nonexistant window.a variable would stop the script from running at all.

Code:

(function() {"use strict";
var a = 123;
function f() {
var a; // declaration moved to where it is actually run
alert(window.a); // this would prevent the script running as no such variable exists
a = 1;
alert(a);
}
f();
})();

I really don't know where your coming from Stephen. Why would anyone use window.jQuery? I personally use the $ sign. I'm sure you do also.
and I never used

Code:

function f() {
var a; // declaration moved to where it is actually run
alert(window.a);

and never would.

It was not about the "use strict" statement that you introduced. It was just showing that window.variable can be used to get a global variable into a local variable with little work like:
globalgal being a global variable and:

I really don't know where your coming from Stephen. Why would anyone use window.jQuery? I personally use the $ sign. .

So now you are contradicting yourself. You said with global variables you always use window. on the front of the name and now you have contradicted that and said that for the one global variable you need when using JQuery you use $. So in fact you don't use window. on the front of the only global variable that you ought to have when using JQuery.

When using JQuery - jQuery should be the only global JavaScript variable in the page. There is no need to have $ defined as well. After all you only need to reference the global variable twice and one of those is to turn off $.

think of local and global variable names much like you would a person's name. If you are talking around the water cooler and you say "barack is doing a good job", the other folks will likely assume you mean barack obama. If however, your CEO is named barack, they will probably assume the more local barack, and think of their boss. In that case, you would have to say barack obama to differentiate between the global barack (obama) and the local barack (your boss).

Javascript is the same way; it assumes that you always mean those closest to you unless instructed otherwise.

Just noticed and corrected an error in what I said before - of course jQuery is the only global variable that you would use if using that library. After all you only need to reference it twice and the first of those is to turn off the global $ variable so it can be reused. You wouldn't bother referencing window.jQuery and of course $ is not a global variable once the first statement runs and so if you use jQuery you need exactly two global references to jQuery - there is no possibility of confusion between global and local variables because those are the only two references to the variable.

Originally Posted by sunfighter

Now that is not saying I don't or wont use jquery, it says I try not to.

So what library do you use that results in your needing to have global variables? Only if a library creates more than one global variable and doesn't provide an option to turn the extras off or if you use multiple libraries do you end up with more than one global variable in your web page.

The point I have been trying to make is that UNLESS you use a library like JQuery where you need one or two global variables to access the library, there is no reason to have any global variables at all.

If you don't have a library to access then simply wrap all your code inside an anonymous function and then none of the variables will be global any more - and so will be unable to clash with similarly named variables in other scripts.

Personally I just name my global variables differently to the variables I use locally - so $A, $B, $D, $E, and $O are the main globals that my scripts reference because those are the objects that I have created that provide most of the common functionality that my scripts use. Adding window. on the front of the variable names in those instances seems somewhat redundant - particularly as I usually pass whichever ones are being used as parameters into the anonymous function so that there isn't anywhere that calls them globally other than as a parameter to a self executing anonymous function. Each global variable gets referenced exactly one per script.

When each global variable is only referenced once in the standard wrapper around your code there is absolutely no point whatever in prefixing it with window. - the fact that it is being passed into your script as a parameter is sufficient to identify that it is global.