JS: var Name Scope

By Xah Lee. Date: . Last updated: .

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

For name declared with var, if it is inside a function, the name is local to nearest outer function brackets {}.

For example,

function () { var x = 3; … }

This is called function-level scope.

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

[see JS: Global Variable]

Note: For name declared with var, curly bracket {} doesn't make the name inside it local.

Following are details.

Global Variable

[see JS: Global Variable]

Function-Level Scope

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

// curly brackets doesn't scope for names declared by 「var」

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

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

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.

Note: your function should start with a lowercase letter, because uppercase function names are constructors by convention. [see JS: Operator “new”]

JS Variable Topic

  1. JS: Variable
  2. JS: let Declaration
  3. JS: const Declaration
  4. JS: var/function Declaration Order
  5. JS: var Name Scope
  6. JS: Global Variable

Function Topic

  1. JS: Define Function
  2. JS: Arrow Function
  3. JS: Function Parameters
  4. JS: var/function Declaration Order
  5. JS: var Name Scope
  6. JS: Function Declaration vs Function Expression
  7. JS: Closure
  8. JS: Functional Programing
  9. JS: Function Call, Apply, Bind
  10. JS: Function Argument Default Value
  11. JS: Function Rest Parameters
  12. JS: Function Argument Destructure

  1. JS: Function Object
  2. JS: Function.prototype
Liket it? Put $5 at patreon.

Or, Buy JavaScript in Depth

Ask me question on patreon