JS: var's name scope

By Xah Lee. Date: . Last updated: .

function-level scope

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

If a var declaration is not inside function, then its scope is global. 〔see Global Variable

This variable scoping rule is called function-level scope.

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 {}.

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

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

Using Function to Emulate Block Scope

before ECMAScript 2015 , you will often see that a function is used purely for the purpose of containing variable inside as local variables, like this:

/*
hack of creating local variable before js 2015, is by creating a local function and eval it right away
*/
(function () {
 var x; // local var x
 // do something
})();

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

before ECMAScript 2015 , it 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.

JavaScript. variable