Scope and Closures

Introduction

Scope and closures are fundamental concepts in JavaScript that control how variables are accessed and how functions interact with their surrounding environment. Understanding these concepts is essential for writing clean, efficient, and bug free code.

What is Scope

Scope determines where variables can be accessed in a program. It defines the visibility and lifetime of variables.

Types of Scope

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

Function Scope
Variables declared inside a function are only accessible within that function.

Block Scope
Variables declared using let and const inside a block such as loops or conditionals are limited to that block.

Example of Scope

let globalVar = "I am global";

function testScope() {
let functionVar = "I am inside function";

if (true) {
let blockVar = "I am inside block";
console.log(globalVar);
console.log(functionVar);
console.log(blockVar);
}

// console.log(blockVar); This will cause an error
}

testScope();

What is Closure

A closure is created when a function remembers variables from its outer scope even after the outer function has finished executing.

Closures allow functions to access and preserve data in a controlled way.

Example of Closure

function outerFunction() {
let count = 0;

return function innerFunction() {
count++;
console.log(count);
};
}

const counter = outerFunction();

counter();
counter();
counter();

How Closures Work

When the outer function runs, it creates a local variable. The inner function keeps a reference to that variable even after the outer function has completed. This allows the inner function to use and update the variable later.

Benefits of Closures

Data privacy and encapsulation
Helps create reusable functions
Useful in event handlers and callbacks
Maintains state in asynchronous programming

Real World Use Case

Closures are commonly used in counters, timers, and maintaining state in applications without exposing variables globally.

Conclusion

Scope and closures are powerful features of JavaScript that help manage variable access and maintain data. Mastering them improves code structure, readability, and performance.

Home ยป Intermediate JavaScript > Functions > Scope and Closures