D Dev Notebook

JavaScript Scope

JS

In JavaScript, scope refers to where variables are accessible. In simpler terms, it’s about which parts of your code can “see” or use your variables.

Types of JavaScript Scope:

There are mainly three types of scopes:

  1. Global Scope
  2. Local (Function) Scope
  3. Block Scope

1. Global Scope

  • Variables defined outside any function or block.
  • Accessible from anywhere in your JavaScript code.
let globalVar = "I'm global!";

function printVar() {
    console.log(globalVar); // Accessible here
}

printVar(); // Output: I'm global!
console.log(globalVar); // Output: I'm global!

2. Local (Function) Scope

  • Variables defined inside a function.
  • Accessible only within that function.
function myFunction() {
    let localVar = "I'm local!";
    console.log(localVar); // Accessible here
}

myFunction(); // Output: I'm local!
console.log(localVar); // Error! localVar is not accessible here

3. Block Scope

  • Variables defined with let or const inside blocks (loops, conditionals).
  • Only accessible within that block.
if (true) {
    let blockVar = "I'm block-scoped!";
    console.log(blockVar); // Accessible here
}

console.log(blockVar); // Error! blockVar is not accessible here

Example with all scopes:

combined practice example to clearly show Global, Local, and Block scopes together:

// Global scope
let animal = "Lion";

function showAnimal() {
    // Local (Function) scope
    let animal = "Tiger";
    console.log("Inside function:", animal); // Tiger
    
    if (true) {
        // Block scope
        let animal = "Elephant";
        console.log("Inside block:", animal); // Elephant
    }

    console.log("After block in function:", animal); // Tiger
}

showAnimal();

console.log("Outside function:", animal); // Lion

//output
Inside function: Tiger
Inside block: Elephant
After block in function: Tiger
Outside function: Lion

On this page