JAVASCRIPT Tutorial

Scope in JS

What is Scope?

Scope determines which parts of your code can access variables declared inside a function. Functions create their own scope, meaning variables declared inside a function are not accessible outside of it.

Types of Scope

  • Function Scope: Variables declared within a function are only accessible within that function.
  • Global Scope: Variables declared outside of any function are accessible from anywhere in the program.

Variable Visibility

  • Local Variables: Variables that are declared within a function.
  • Global Variables: Variables that are declared outside of any function.

Practical Steps for Determining Scope

  1. Identify the function scope by locating the opening and closing curly braces of the function.
  2. Variables declared within the curly braces are local and have function scope.
  3. Variables declared outside of any function scope are global and have global scope.

Example in JavaScript

function myFunction() {
  let localVariable = "This is a local variable";
}

console.log(localVariable); // Error: localVariable is not defined

const globalVariable = "This is a global variable";

console.log(globalVariable); // This will print "This is a global variable"

In this example, the variable localVariable has function scope and cannot be accessed outside of the myFunction() function. The variable globalVariable has global scope and can be accessed from anywhere in the program.