Global and local scope

what is the Global scope and what is the local scope?

Local scope is the scope inside a function block. If you declared a variable inside a function, that variable will only be visible in that function.

function foo() {
  // this variable is in foo's local scope. Only code inside
  // this function can access this.
  var a = 2;
  // ...
  console.log(a); // 2
}

function bar() {
  // will throw an error, because there's no `a` variable in
  // bar's local scope.
  console.log(a);
}

Global scope is the scope outside any function. If you declared a variable outside any function body, it is in the global scope, and all parts of your code can access it.

var b = 3;

function foo() {
  console.log(b);  // 3; `b` is in the global scope
}

function bar() {
  console.log(b); // 3; also accessible here
}

Be careful with global variables though. All parts of your code can access and change them, and there’s a lot of ways things can go wrong. As much as possible rely on smaller scopes.

I recommend you read Scope and Closures. It gives a detailed explanation about scope.

1 Like