Open In App

Difference Between Scope and Closures in JavaScript

Last Updated : 06 Dec, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

The scope and closures are fundamental concepts that play a crucial role in how variables are accessed and managed within the functions and blocks of code. In this article, we will learn about the difference between scope and closures in JavaScript.

What is Scope?

The Scope in JavaScript refers to the context or environment in which a variable or function is declared and can be accessed. JavaScript uses function-based scope meaning variables declared inside a function are locally scoped in while variables declared outside any function have global scope.

Example: In this example, a variable named message is declared in the global scope, and its value is both set and accessed within a function, demonstrating the concept of global scope in JavaScript.

Javascript




let message;
 
// Declare message in global scope
function GFG() {
  message = "Hello, world!";
  console.log(message);
}
GFG();
 
// Now it's accessible globally
console.log(message);


Output:

Hello, world!
Hello, world!

What are Closures?

The Closures occur in JavaScript when a function “remembers” its lexical scope even if it’s executed the outside that scope. In other words, a closure allows a function to access variables from its containing function and even after the containing function has finished executing.

Example: In this example, a closure is created where the inner function retains access to the “name” variable from its containing “outers” function, allowing it to display a personalized greeting when invoked.

Javascript




function outers() {
    let name = "Kumar";
    function inner() {
        console.log("Hello, " + name + "!");
    }
    return inner;
}
let greeting = outers();
greeting();


Output:

Hello, Kumar!

Difference between scope and closures in JavaScript:

Characteristic

Scope

Closures

Definition

Describes the context of the variable access.

Refers to ability of function to remember and access its lexical scope.

Lifetime of Variables

The Variables in a scope have limited lifetime.

The Variables accessed via closures can persist beyond the lifetime of containing function.

Access

The Variables within a scope are accessible within that scope.

The Closures allow access to variables from their containing function even after that function has exited.

Use Case

Helps prevent variable naming conflicts and provides structured access to variables within the function or block.

Useful for the creating private data maintaining state and implementing advanced patterns like currying and memoization.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads