JavaScript scope


A scope can be defined as the region of the execution, a region where the expressions and values can be referenced.

There are two scopes in JavaScript that are global and local:

  • Local scope
  • Global scope

Global Scope: In the global scope, the variable can be accessed from any part of the JavaScript code.

Local Scope: In the local scope, the variable can be accessed within a function where it is declared.

In the function's body, the precedence of the local variable is more than the global variable with the same name. If the name of the function's local variable is same as the name of the global variable, then the local variable hides the global variable.

Example

// code here can NOT use carName

function myFunction() {
  var carName = "Volvo";

  // code here CAN use carName

}

Example -

Example -

myFunction();

// code here can use carName

function myFunction() {
  carName = "Volvo";
}