Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 13 of 13
  1. #1
    New Coder
    Join Date
    Oct 2010
    Location
    Toronto
    Posts
    95
    Thanks
    52
    Thanked 0 Times in 0 Posts

    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.

  • #2
    Regular Coder
    Join Date
    Mar 2008
    Location
    London
    Posts
    152
    Thanks
    4
    Thanked 42 Times in 42 Posts

  • #3
    Master Coder felgall's Avatar
    Join Date
    Sep 2005
    Location
    Sydney, Australia
    Posts
    6,633
    Thanks
    0
    Thanked 649 Times in 639 Posts
    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/

    Don't forget to start your JavaScript code with "use strict"; which makes it easier to find errors in your code.

  • Users who have thanked felgall for this post:

    chickentulip (01-30-2013)

  • #4
    Supreme Master coder! Philip M's Avatar
    Join Date
    Jun 2002
    Location
    London, England
    Posts
    17,924
    Thanks
    203
    Thanked 2,531 Times in 2,509 Posts
    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.

  • #5
    Senior Coder
    Join Date
    Jan 2011
    Location
    Missouri
    Posts
    4,105
    Thanks
    23
    Thanked 594 Times in 593 Posts
    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();

  • #6
    Master Coder felgall's Avatar
    Join Date
    Sep 2005
    Location
    Sydney, Australia
    Posts
    6,633
    Thanks
    0
    Thanked 649 Times in 639 Posts
    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();
    })();
    Last edited by felgall; 01-30-2013 at 06:25 PM.
    Stephen
    Learn Modern JavaScript - http://javascriptexample.net/
    Helping others to solve their computer problem at http://www.felgall.com/

    Don't forget to start your JavaScript code with "use strict"; which makes it easier to find errors in your code.

  • #7
    Senior Coder
    Join Date
    Jan 2011
    Location
    Missouri
    Posts
    4,105
    Thanks
    23
    Thanked 594 Times in 593 Posts
    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.

  • #8
    Master Coder felgall's Avatar
    Join Date
    Sep 2005
    Location
    Sydney, Australia
    Posts
    6,633
    Thanks
    0
    Thanked 649 Times in 639 Posts
    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);
    Last edited by felgall; 01-31-2013 at 07:24 AM. Reason: got things backwards - corrected it and added an example
    Stephen
    Learn Modern JavaScript - http://javascriptexample.net/
    Helping others to solve their computer problem at http://www.felgall.com/

    Don't forget to start your JavaScript code with "use strict"; which makes it easier to find errors in your code.

  • #9
    Senior Coder rnd me's Avatar
    Join Date
    Jun 2007
    Location
    Urbana
    Posts
    4,301
    Thanks
    10
    Thanked 586 Times in 567 Posts
    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.
    Last edited by rnd me; 01-30-2013 at 10:31 PM.
    my site (updated 13/9/26)
    BROWSER STATS [% share] (2014/5/28) IE7:0.1, IE8:5.3, IE11:8.4, IE9:3.2, IE10:3.2, FF:18.2, CH:46, SF:7.9, NON-MOUSE:32%

  • #10
    Senior Coder rnd me's Avatar
    Join Date
    Jun 2007
    Location
    Urbana
    Posts
    4,301
    Thanks
    10
    Thanked 586 Times in 567 Posts
    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 13/9/26)
    BROWSER STATS [% share] (2014/5/28) IE7:0.1, IE8:5.3, IE11:8.4, IE9:3.2, IE10:3.2, FF:18.2, CH:46, SF:7.9, NON-MOUSE:32%

  • #11
    Senior Coder
    Join Date
    Jan 2011
    Location
    Missouri
    Posts
    4,105
    Thanks
    23
    Thanked 594 Times in 593 Posts
    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:
    I have always used "window" to get my globals.
    Post #5 and it's not been edited.
    What I never said was:
    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.

  • #12
    Master Coder felgall's Avatar
    Join Date
    Sep 2005
    Location
    Sydney, Australia
    Posts
    6,633
    Thanks
    0
    Thanked 649 Times in 639 Posts
    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.
    Last edited by felgall; 01-31-2013 at 07:31 AM.
    Stephen
    Learn Modern JavaScript - http://javascriptexample.net/
    Helping others to solve their computer problem at http://www.felgall.com/

    Don't forget to start your JavaScript code with "use strict"; which makes it easier to find errors in your code.

  • #13
    Senior Coder
    Join Date
    Jan 2011
    Location
    Missouri
    Posts
    4,105
    Thanks
    23
    Thanked 594 Times in 593 Posts
    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.


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •