JavaScript Scope

Scope is the region of a JavaScript program where a variable can be referenced. There are two types of scope in JavaScript:

  • Global scope
  • Local scope

Global Scope

The global scope is the outermost scope in a JavaScript program. Variables declared in the global scope can be accessed from anywhere in the program.

Local Scope

Local scope is the scope of a function or block of code. Variables declared in a local scope can only be accessed from within that scope.

JavaScript Scope Rules

The following are the scope rules in JavaScript:

  • Variables declared in the global scope are available to all functions and blocks of code in the program.
  • Variables declared in a function are only available to that function.
  • Variables declared in a block of code are only available to that block of code.
ADVERTISEMENT
ADVERTISEMENT