Go Back   CodingForums.com > :: Client side development > JavaScript programming > DOM and JSON scripting

Before you post, read our: Rules & Posting Guidelines

Reply
 
Thread Tools Rate Thread
Enjoy an ad free experience by logging in. Not a member yet? Register.
Old 01-29-2013, 04:16 PM   PM User | #1
chickentulip
New Coder

 
Join Date: Oct 2010
Location: Toronto
Posts: 95
Thanks: 52
Thanked 0 Times in 0 Posts
chickentulip is an unknown quantity at this point
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.
chickentulip is offline   Reply With Quote
Old 01-29-2013, 04:48 PM   PM User | #2
niralsoni
Regular Coder

 
Join Date: Mar 2008
Location: London
Posts: 129
Thanks: 1
Thanked 31 Times in 31 Posts
niralsoni is an unknown quantity at this point
Refer to - http://www.codeproject.com/Articles/...otchas#noblock
niralsoni is offline   Reply With Quote
Old 01-29-2013, 06:34 PM   PM User | #3
felgall
Master Coder

 
felgall's Avatar
 
Join Date: Sep 2005
Location: Sydney, Australia
Posts: 5,455
Thanks: 0
Thanked 498 Times in 490 Posts
felgall is a jewel in the roughfelgall is a jewel in the roughfelgall is a jewel in the rough
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.
__________________
Stephen
Learn Modern JavaScript - http://javascriptexample.net/
Helping others to solve their computer problem at http://www.felgall.com/
felgall is offline   Reply With Quote
Users who have thanked felgall for this post:
chickentulip (01-30-2013)
Old 01-30-2013, 07:48 AM   PM User | #4
Philip M
Supreme Master coder!

 
Philip M's Avatar
 
Join Date: Jun 2002
Location: London, England
Posts: 17,037
Thanks: 197
Thanked 2,411 Times in 2,389 Posts
Philip M has a spectacular aura aboutPhilip M has a spectacular aura aboutPhilip M has a spectacular aura about
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.
Philip M is offline   Reply With Quote
Old 01-30-2013, 04:22 PM   PM User | #5
sunfighter
Senior Coder

 
Join Date: Jan 2011
Location: Missouri
Posts: 2,383
Thanks: 18
Thanked 350 Times in 349 Posts
sunfighter is on a distinguished road
I have always used "window" to get my globals. Your code would therefore be:
Code:
var a = 123;

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

f();
sunfighter is offline   Reply With Quote
Old 01-30-2013, 06:20 PM   PM User | #6
felgall
Master Coder

 
felgall's Avatar
 
Join Date: Sep 2005
Location: Sydney, Australia
Posts: 5,455
Thanks: 0
Thanked 498 Times in 490 Posts
felgall is a jewel in the roughfelgall is a jewel in the roughfelgall is a jewel in the rough
Quote:
Originally Posted by sunfighter View Post
I have always used "window" to get my globals.
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();
})();
__________________
Stephen
Learn Modern JavaScript - http://javascriptexample.net/
Helping others to solve their computer problem at http://www.felgall.com/

Last edited by felgall; 01-30-2013 at 06:25 PM..
felgall is offline   Reply With Quote
Old 01-30-2013, 07:22 PM   PM User | #7
sunfighter
Senior Coder

 
Join Date: Jan 2011
Location: Missouri
Posts: 2,383
Thanks: 18
Thanked 350 Times in 349 Posts
sunfighter is on a distinguished road
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:
Code:
function f(){
var localelady = window.globalgal;
allows you access it with little to no sweat.
sunfighter is offline   Reply With Quote
Old 01-30-2013, 09:47 PM   PM User | #8
felgall
Master Coder

 
felgall's Avatar
 
Join Date: Sep 2005
Location: Sydney, Australia
Posts: 5,455
Thanks: 0
Thanked 498 Times in 490 Posts
felgall is a jewel in the roughfelgall is a jewel in the roughfelgall is a jewel in the rough
Quote:
Originally Posted by sunfighter View Post
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 $.

Code:
jQuery.noConflict();
(function($) {
// your jQuery code goes here
})(jQuery);
__________________
Stephen
Learn Modern JavaScript - http://javascriptexample.net/
Helping others to solve their computer problem at http://www.felgall.com/

Last edited by felgall; 01-31-2013 at 07:24 AM.. Reason: got things backwards - corrected it and added an example
felgall is offline   Reply With Quote
Old 01-30-2013, 10:29 PM   PM User | #9
rnd me
Senior Coder

 
rnd me's Avatar
 
Join Date: Jun 2007
Location: Urbana
Posts: 3,462
Thanks: 9
Thanked 466 Times in 450 Posts
rnd me is a jewel in the roughrnd me is a jewel in the roughrnd me is a jewel in the rough
Quote:
Originally Posted by felgall View Post
When using JQuery $ should be the only global JavaScript variable in the page.
nope, jQuery is defined also.


@sunfighter:
often some jerk/library decides to use "$", and then adds jQuery to the site. using window.jQuery ensures that you don't mis-apply the unexpected $ var as though it were jQuery.


quick aside:
i like to use self instead of window to hit globals so that the code can run in WebWorker threads if needed and it's less to type.
__________________
my site (updated 5/13)
STATS (2013/5) HTML5:90.2% MOB:14% IE7:0.5% IE8:8.6% IE9:9.8% IE10:10%

Last edited by rnd me; 01-30-2013 at 10:31 PM..
rnd me is offline   Reply With Quote
Old 01-30-2013, 10:35 PM   PM User | #10
rnd me
Senior Coder

 
rnd me's Avatar
 
Join Date: Jun 2007
Location: Urbana
Posts: 3,462
Thanks: 9
Thanked 466 Times in 450 Posts
rnd me is a jewel in the roughrnd me is a jewel in the roughrnd me is a jewel in the rough
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.
__________________
my site (updated 5/13)
STATS (2013/5) HTML5:90.2% MOB:14% IE7:0.5% IE8:8.6% IE9:9.8% IE10:10%
rnd me is offline   Reply With Quote
Old 01-31-2013, 03:51 AM   PM User | #11
sunfighter
Senior Coder

 
Join Date: Jan 2011
Location: Missouri
Posts: 2,383
Thanks: 18
Thanked 350 Times in 349 Posts
sunfighter is on a distinguished road
Quote:
Originally Posted by felgall View Post
So now you are contradicting yourself. You said with global variables you always use window. on the front of the name .....
No, I said:
Quote:
I have always used "window" to get my globals.
Post #5 and it's not been edited.
What I never said was:
Quote:
I use jquery.
I fact, I try not to. 117Kb for the min library is a lot of overhead for a few effects. Now that is not saying I don't or wont use jquery, it says I try not to.
sunfighter is offline   Reply With Quote
Old 01-31-2013, 06:14 AM   PM User | #12
felgall
Master Coder

 
felgall's Avatar
 
Join Date: Sep 2005
Location: Sydney, Australia
Posts: 5,455
Thanks: 0
Thanked 498 Times in 490 Posts
felgall is a jewel in the roughfelgall is a jewel in the roughfelgall is a jewel in the rough
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.

Quote:
Originally Posted by sunfighter View Post
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.
__________________
Stephen
Learn Modern JavaScript - http://javascriptexample.net/
Helping others to solve their computer problem at http://www.felgall.com/

Last edited by felgall; 01-31-2013 at 07:31 AM..
felgall is offline   Reply With Quote
Old 01-31-2013, 06:21 PM   PM User | #13
sunfighter
Senior Coder

 
Join Date: Jan 2011
Location: Missouri
Posts: 2,383
Thanks: 18
Thanked 350 Times in 349 Posts
sunfighter is on a distinguished road
I agree with everything you said in the above post. I can not think of the last time I used a global with one exception and that maybe laughable but it's how I roll so to speak.

When I use ajax I have marcos that input JS code at the start of my <body> to make the ajax object. I set that as a global. Don't need to, but the macros are already set up.
sunfighter is offline   Reply With Quote
Reply

Bookmarks

Jump To Top of Thread


Thread Tools
Rate This Thread
Rate This Thread:

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off

Forum Jump


All times are GMT +1. The time now is 11:32 AM.


Advertisement
Log in to turn off these ads.