JavaScript Scope
JavaScript scope refers to the context in which variables, functions, and objects are defined. It determines the accessibility and visibility of these elements within the code. Understanding scope is crucial for writing maintainable and error-free JavaScript code.
JavaScript has three types of scope:
- Block scope
- Function scope
- Global scope
Before ES6 (2015), JavaScript had only Global Scope and Function Scope.
ES6 introduced two important new JavaScript keywords: let
and const
.
These two keywords provide Block Scope in JavaScript.
Variables declared inside a { } block cannot be accessed from outside the block.
{ let x = 2; } // x can NOT be used here
JavaScript has function scope: Each function creates a new scope.
Variables defined inside a function are not accessible (visible) from outside the function.
Variables declared with var
, let
and const
are quite similar when declared inside a function.
function varFunction() {
var message = "Hello"; // Function Scope
}
function letFunction() {
let message = "Hello"; // Function Scope
}
function constFunction() {
const message = "Hello"; // Function Scope
}
Variables declared Globally (outside any function) have Global Scope.
Global variables can be accessed from anywhere in a JavaScript program.
Variables declared with var
, let
and const
are quite similar when declared outside a block.
var x = 2; // Global scope let x = 2; // Global scope const x = 2; // Global scope
Comments