Before we dive into these concepts, we need to understand how scoping works in JavaScript:

Scoping determines the accessibility (visibility) of variables at different parts of your code.

Types of Scope in JavaScript

  1. Global Scope
  2. Function Scope
  3. Block Scope
  4. Lexical Scope

Global Scope: Variables declared outside any function or block are in the global scope. They can be accessed from anywhere in the code.

let globalVariable = "I'm global!";

function accessGlobal() {
    console.log(globalVariable); // Accessible
}

accessGlobal(); // Output: I'm global!
console.log(globalVariable); // Output: I'm global!

Function Scope: Variables declared inside a function using var, let, or const are accessible only within that function.

function exampleFunction() {
    var functionScoped = "I'm only accessible within this function.";
    console.log(functionScoped); // Output: I'm only accessible within this function.
}

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

Block Scope: Variables declared with let or const are block-scoped, meaning they are accessible only within the block ({ ... }) in which they are defined.

{
    let blockScoped = "I'm block-scoped!";
    console.log(blockScoped); // Output: I'm block-scoped!
}
console.log(blockScoped); // Error: blockScoped is not defined
{
    var notBlockScoped = "I'm not block-scoped!";
}
console.log(notBlockScoped); // Output: I'm not block-scoped!