Search code examples
javascriptfunctionglobal-variableslocalprivate

Global and Local and Private Functions (Javascript)


I am currently reading a book on Javascript by Pragmatic, and I'm confused about one thing. They have a section on how to make variables global, local, or private.

  1. What is the difference between local and private variables? Is there one?

  2. How does one make a variable global or local, They said something about putting 'var =' before it, but it was very vague.


Solution

    1. None, People use "private" because they are mistaken and are meant to say "local"

    2. local variables are defined as

    var foo = "local";

    global variables are a properties of the global scope object (which is window in the browser)

    window.foo = "global";

    The fact you can do foo = "global"; without first declaring variable foo with var foo is a "bug". This is fixed in ES5 strict mode.

    (function () { "use strict"; foo = 42; })()

    gives ReferenceError: foo is not defined

    Note that you can make variables global by declaring them in outer most scope

    var foo = "global";
    function bar() {
      var foo = "local";
    }
    

    It should be noted that you shouldn't have any code in outer most scope, ever. You should be wrapping all your scope in anonymous functions so that you get "module level scope". This means you have a per file based top level scope. This is part of the module pattern.