Logo

dev-resources.site

for different kinds of informations.

Let's Understand JavaScript Closures: A Fundamental Concept

Published at
7/9/2024
Categories
javascript
closures
Author
readwanmd
Categories
2 categories in total
javascript
open
closures
open
Author
9 person written this
readwanmd
open
Let's Understand JavaScript Closures: A Fundamental Concept

Closures are a powerful feature in JavaScript that allow functions to retain access to their lexical scope, even when the function is executed outside that scope. This can sound abstract, but with some simple examples, you'll see how closures can be both intuitive and incredibly useful in real-world applications.

What is a Closure?

A closure is created whenever a function is created - every function has an associated closure.
When a function is defined within another function, and the inner function retains access to the outer function’s variables. Essentially, a closure gives you access to an outer function’s scope from an inner function.

Here’s a simple definition:

  • Closure: A combination of a function and its lexical environment within which that function was declared.

Basic Example

Let’s start with a basic example to illustrate the concept of closures:

function outerFunction() {
  let outerVariable = 'I am from the outer function';

  function innerFunction() {
    console.log(outerVariable);
  }

  return innerFunction;
}

const myClosure = outerFunction();
myClosure();  // Outputs: I am from the outer function
Enter fullscreen mode Exit fullscreen mode

In this example:

  • outerFunction contains a variable outerVariable and an inner function innerFunction.
  • innerFunction accesses outerVariable and logs it to the console.
  • outerFunction returns innerFunction, and we store it in myClosure.
  • When myClosure is called, it still has access to outerVariable even though outerFunction has finished executing. This is a closure in action.

Real-World Example: Creating Private Variables

Closures are often used to create private variables in JavaScript. Here’s an example of how you can use closures to encapsulate data and provide a controlled interface to interact with it:

function createCounter() {
  let count = 0;

  return {
    increment: function() {
      count++;
      console.log(count);
    },
    decrement: function() {
      count--;
      console.log(count);
    },
    getCount: function() {
      return count;
    }
  };
}

const counter = createCounter();
counter.increment(); // Outputs: 1
counter.increment(); // Outputs: 2
counter.decrement(); // Outputs: 1
console.log(counter.getCount()); // Outputs: 1
Enter fullscreen mode Exit fullscreen mode

In this example:

  • createCounter function defines a variable count and returns an object with three methods: increment, decrement, and getCount.
  • The methods increment and decrement modify count, while getCount returns its current value.
  • The count variable is private to createCounter and cannot be accessed directly from outside. This encapsulation is made possible by closures.

Real-World Example: Delayed Execution

Closures are also useful for functions that need to remember the context in which they were created, such as setting up delayed execution with setTimeout:

function greet(name) {
  return function() {
    console.log('Hello, ' + name);
  };
}

const delayedGreeting = greet('Alice');
setTimeout(delayedGreeting, 2000); // Outputs: Hello, Alice after 2 seconds
Enter fullscreen mode Exit fullscreen mode

In this example:

  • greet function returns another function that logs a greeting message.
  • delayedGreeting stores the returned function with the captured name variable.
  • setTimeout executes delayedGreeting after 2 seconds, and it still has access to name (Alice) due to the closure.

Conclusion

Closures are a fundamental concept in JavaScript that allow functions to access their lexical scope even after the outer function has finished executing. They enable powerful patterns such as data encapsulation, private variables, and delayed execution.

And Finally,

Please don’t hesitate to point out any mistakes in my writing and any errors in my logic.

I’m appreciative that you read my piece.

closures Article's
30 articles in total
Favicon
Understanding Closures in PHP: Key Differences and Use Cases
Favicon
JavaScript Closures in Depth: Unlocking the Power of Lexical Scope
Favicon
Understanding Closures in JavaScript
Favicon
Mastering Closures and Decorators in Python: From Basics to Advanced
Favicon
Understanding Closure in JavaScript.
Favicon
Let's Understand JavaScript Closures: A Fundamental Concept
Favicon
Memoization in JavaScript
Favicon
Closures: Performance implications
Favicon
Closures: Lifting the hood
Favicon
A Practical Introduction to Closures in JavaScript
Favicon
Unlocking New Possibilities: Rust Compiler Backend Brings Closures to the .NET Universe!
Favicon
📦🔓Closures in JavaScript visualized
Favicon
useClosure() {work, backwards in returnValuesAsInput (backwards, work)}
Favicon
Mastering Closures in JavaScript: A Comprehensive Guide
Favicon
# "JavaScript Closures: Demystified."
Favicon
Closures - JavaScript
Favicon
Exploring Advanced JavaScript Techniques: Closures, Prototypes, and Hoisting
Favicon
Unlocking JavaScript Magic: A Beginner's Guide to Closures
Favicon
JavaScript Closures: Understanding the Power of Functions
Favicon
Closures in javascript
Favicon
JavaScript Closure
Favicon
Groovy Gotchas - Loops, Closures, Scope, and Jenkins DSLs
Favicon
Understanding closures in JavaScript
Favicon
Javascript Currying and partials
Favicon
The ultimate explanation of closures
Favicon
Understanding Closures in JavaScript
Favicon
Closures and Memoization
Favicon
A Simple Explanation of JavaScript "Closures"
Favicon
Hoisting with closures example
Favicon
Closures in JavaScript

Featured ones: