JS: var Name Scope

By Xah Lee. Date: . Last updated: .

name scope” means where the name can be seen. (that is, have meaning.)

Name declared with var has scope to nearest outer function's curly bracket {}.

// Name declared with var has scope to nearest outer function's curly bracket {}.

function f ()  {
    var n = 3;
    {
        var n = 4;
    }
    return n;
};

console.log ( f() ); // prints 4

This variable scoping rule is called function-level scope.

If a var declaration is not inside function, then its scope is global.

[see JS: Global Variable]

Note: the function-level scope applies only for variable declared with var. It does not apply to variable declared with let or const.

Before ES2015 Practices

Using Function to Emulate Block Scope

In pre ES2015 code, you will often see that a function is used purely for the purpose of containing variable inside as local variables, like this:

(function(){ var x; // local var x // … }());

This will create a function, and immediately evaluate it. Here's a example.

function f ()  {
    var n = 3;
    (function(){
        var n = 4;
    })();
    return n;
};

console.log(f()); // prints 3

Function Scope as Namespace

JavaScript pre ES2015 does not have modules or namespace. One hack to achieve namespace is wrapping the entire source code of your package inside a function. Like this:

(function nicePackage () {
    // your source code here
})();

This way, when your package/file is loaded, it only introduces one name into the global space.

JS Variable Topic

  1. JS: let Declaration
  2. JS: const Declaration
  3. JS: var Declaration
  4. JS: var Declaration Order
  5. JS: var Name Scope
  6. JS: Global Variable
Liket it? Put $5 at patreon.

Or, Buy JavaScript in Depth

If you have a question, put $5 at patreon and message me.