HTML CSS Bootstrap JavaScript jQuery MySQL PHP Data Mining

JavaScript Scope

Scope determines the accessibility (visibility) of variables. In JavaScript there are three types of scope: Block scope, Function scope, and Global scope.


1. Block Scope (ES6)

Before ES6 (2015), JavaScript had only Global Scope and Function Scope. ES6 introduced let and const, which provide Block Scope. Variables declared inside a {} block cannot be accessed from outside the block.

{
  let x = 2;
}
// x can NOT be used here

2. Function Scope (Local Scope)

Variables defined inside a function are not accessible (visible) from outside the function. Variables declared with var, let, and const are very similar when declared inside a function.

function myFunction() {
  let carName = "Volvo"; // Local Scope
}
// carName can NOT be used here

3. Global Scope

A variable declared outside a function, becomes GLOBAL. A global variable has global scope: All scripts and functions on a web page can access it.

let carName = "Volvo"; // Global Scope

function myFunction() {
  // code here can use carName
}
Automatically Global: If you assign a value to a variable that has not been declared, it will automatically become a GLOBAL variable. Always declare your variables to avoid this "pollution"!

The Variable Lifecycle

  • Local variables are created when a function starts, and deleted when the function is completed.
  • Global variables are deleted when you close the browser window (or tab).
  • Arguments (parameters) of a function behave like local variables.

Key Points to Remember

  • Scope is about where you can "see" a variable
  • Use Block Scope (let/const) to prevent variable leakage
  • Global variables belong to the window object in browsers
  • Function parameters are local to that function
  • Minimize the use of global variables to avoid naming conflicts
  • Strict mode "use strict"; prevents accidentally creating global variables