HOME C C++ PYTHON JAVA HTML CSS JAVASCRIPT BOOTSTRAP JQUERY REACT PHP SQL AJAX JSON DATA SCIENCE AI

JavaScript Scope

In JavaScript, scope refers to the visibility and accessibility of variables within a program.
It defines the region of a program where a particular variable can be accessed. JavaScript has function-level scope, which means that variables defined inside a function are only accessible within that function.
However, starting from ECMAScript 6 (ES6), JavaScript also supports block-scoped variables declared using the let and const keywords.

Global Scope:

Variables declared outside of any function have global scope, meaning they are accessible from anywhere in the codebase, including within functio.

Example

let globalVariable = "I'm a global variable";

function myFunction() {
    console.log(globalVariable); // Output: "I'm a global variable"
}

myFunction();

Local Scope (Function Scope):

Variables declared inside a function have local scope, meaning they are accessible only within that function.

Example

function myFunction() {
    let localVariable = "I'm a local variable";
    console.log(localVariable); // Output: "I'm a local variable"
}

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

Block Scope (ES6):

Variables declared using let and const keywords have block scope, meaning they are accessible only within the block in which they are defined (typically enclosed within curly braces {}).
This includes loops (for, while, do...while) and conditional statements (if, else, switch).

Example

if (true) {
    let blockScopedVariable = "I'm a block-scoped variable";
    console.log(blockScopedVariable); // Output: "I'm a block-scoped variable"
}

console.log(blockScopedVariable); // ReferenceError: blockScopedVariable is not defined