closures in javascript example

Closures in JavaScript: Example Explained

By Brian Lewis
AD
Closures in JavaScript are a powerful concept that can be quite confusing for beginners. However, understanding them is crucial for writing clean, efficient, and dynamic code. In this article, we'll explore the world of closures with examples to help you grasp this essential JavaScript feature.

Understanding Closures at a Glance

In JavaScript, a closure is the combination of a function and the lexical environment within which that function was declared. In simple terms, it's like a function that remembers and has access to the variables in its own scope, the outer function's scope, and the global scope, even after the outer function has returned.

Think of closures as functions that have access to their own scope, the scope of the outer function, and the global scope. They "close over" the variables in their environment, hence the name 'closure'.

Functional Scope

Before diving into closures, let's first understand functional scope in JavaScript. In JavaScript, variables defined inside a function are function-scoped, meaning they're only accessible within that function.

AD
What are Closures in JavaScript?
What are Closures in JavaScript?
Closure in JavaScript – Explained with Examples
Closure in JavaScript – Explained with Examples
the text reads, understanding closures in jawscript - javescript in plain english
the text reads, understanding closures in jawscript - javescript in plain english

Here's a simple example:

{{code}}

function outer() {
  let innerVar = 'Hello';
  console.log(innerVar);
}

outer(); // Logs: Hello

console.log(innerVar); // ReferenceError: innerVar is not defined

Preserving Scope with Closures

Now, let's see how closures help preserve scope. Consider the following code:

Back to Basics - JavaScript Closures
Back to Basics - JavaScript Closures
Here’s What You Have To Know About JavaScript Closuers
Here’s What You Have To Know About JavaScript Closuers
javascript - Closure in Javascript and its use
javascript - Closure in Javascript and its use
{{code}}

function outer() {
  let innerVar = 'Hello';
  
  return function() {
    console.log(innerVar);
  };
}

const innerFunc = outer();

innerFunc(); // Logs: Hello

In this example, even though the `outer` function has finished executing, the returned function (our closure) still has access to `innerVar`. This is because our closure "closes over" the `outer` function's scope, preserving access to `innerVar`.

Practical Applications of Closures

Closures have many practical applications in JavaScript. They enable a variety of design patterns and can help write more efficient, dynamic, and clean code.

AD

Let's look at two common use cases: creating private variables and implementing the factory function pattern.

Javascript Closure tutorial ( Closures Explained )
Javascript Closure tutorial ( Closures Explained )
How JavaScript Closure Can Make You Sick?
How JavaScript Closure Can Make You Sick?
How do JavaScript closures work?
How do JavaScript closures work?
What Is Closure In Javascript, Javascript Closure Example, How To Use Closures In Javascript, Javascript Closure Explanation, Javascript Practice Questions, Choosing Between Java And Javascript, Javascript Programming Concepts, Recursive Javascript Function, Javascript Apply Call Bind Difference
What Is Closure In Javascript, Javascript Closure Example, How To Use Closures In Javascript, Javascript Closure Explanation, Javascript Practice Questions, Choosing Between Java And Javascript, Javascript Programming Concepts, Recursive Javascript Function, Javascript Apply Call Bind Difference
a piece of paper with some type of text on it and an image of a backpack
a piece of paper with some type of text on it and an image of a backpack
Understanding JavaScript Closures: A Comprehensive Guide – Djamware
Understanding JavaScript Closures: A Comprehensive Guide – Djamware

Private Variables with Closures

Even though JavaScript doesn't support private variables natively, we can simulate them using closures:

{{code}}

const Counter = (function() {
  let count = 0;
  
  return {
    increment: function() { count++; },
    decrement: function() { count--; },
    getCount: function() { return count; }
    }; )
}());

Counter.increment();
Counter.decrement();
console.log(Counter.getCount()); // Logs: 0

In this example, `count` is a private variable that cannot be accessed directly, but its state can be manipulated using the public methods `increment`, `decrement`, and `getCount`.

AD

Factory Function Pattern with Closures

The factory function pattern is another practical application of closures. It allows you to create multiple isolated, immutable objects from a single function:

Javascript switch case example
Javascript switch case example
{{code}}

function createCircle(radius) {
  return {
    getArea: function() { return Math.PI * radius * radius; },
    getCircumference: function() { return 2 * Math.PI * radius; }
    }
}

const circle1 = createCircle(5);
const circle2 = createCircle(10);

console.log(circle1.getArea()); // Logs: 78.53981633974483
console.log(circle2.getArea()); // Logs: 314.1592653589793

Here, each `circle` object created by `createCircle` has its own `radius` variable, and each object has access to its own `radius` within its methods.

Mastering closures is a significant step towards becoming a proficient JavaScript developer. They might seem complex at first, but practicing various use cases and familiarizing yourself with their behavior will help you harness their power effectively. Keep exploring and happy coding!

AD
AD