Everything about variable scope

The scope of variables and functions has the purpose of determining accessibility and the context in which it is being executed. This means that variables and functions can have a global or local scope.
The scope of a variable is interpreted by JavaScript from the innermost scope to the outermost one. In other words JavaScript establishes scopes from the innermost nested scope outwards until it gets to the global ones.

A globally-scoped variable:
var a = 1;
function test() {
  console.log(a);
}

Local scope
var a = 1;
function test() {
  var a = 2;
  console.log(a);
}

Global and Local scope

var a = 1;
(function () {
  console.log(a);
  var a = 2;
  console.log(a);
})();

Share This:

Feel free to leave a comment!

You might alos be interested in: