javascript closures for dummies

Understanding JavaScript Closures: A Beginner's Guide

By Joseph Allen
AD

JavaScript closures can seem like a mouthful, especially with no prior exposure to the concept. But don't worry, we're here to demystify this powerful tool and make you a closure pro by the end of this article. Think of a closure as a secretive function that hides and protects its data.

Imagine you're at a fancy restaurant, and you order a secret dish that the waiter won't let anyone else see. In JavaScript, a closure is like that secret dish - it allows functions to have secret (hidden) data, which doesn't get disturbed even when the function is invoked multiple times. Sounds interesting? Let's dig deeper.

Understanding Closures: The Magic Recipe

Before we dive into closures, let's prepare some ingredients - functions and variables. You already know that in JavaScript, functions can be both, values of variables and even returned as values from other functions.

AD
Understanding Closures in JavaScript
Understanding Closures in JavaScript
Back to Basics - JavaScript Closures
Back to Basics - JavaScript Closures
What are Closures in JavaScript?
What are Closures in JavaScript?

Now, in a closure, these functions capture (or 'close over') the scope in which they're born. This means they keep remember the variables that existed in their creation environment, even when the outer function returns and that environment is supposedly destroyed. Mind-blowing, right? Let's break this down.

Closures in Action: A Simple Example

Here's a simple closure in action:

Javascript Closure tutorial ( Closures Explained )
Javascript Closure tutorial ( Closures Explained )
Here’s What You Have To Know About JavaScript Closuers
Here’s What You Have To Know About JavaScript Closuers
How JavaScript Closure Can Make You Sick?
How JavaScript Closure Can Make You Sick?

function makeCounter() {
  let count = 0; // This variable is hidden in the scope of makeCounter

  return function() {
    return count++;
  };
}

In this code, we create a closure, makeCounter, which returns another function (the counter). This inner function remembers the 'count' variable even after makeCounter's scope is gone. Try it out - create multiple counters and see how they remember their individual counts.

Closures and Scope: Hiding & Protecting Data

Closures protect data by making variables private or 'hidden'. Here's an example:

AD

function createMessage() {
  let greeting = 'Hello';

  return function(name) {
    return `${greeting}, ${name}!`;
  };
}

const sayHi = createMessage();

console.log(sayHi('Alice')); // 'Hello, Alice!'
console.log(sayHi('Bob'));   // 'Hello, Bob!'

In this example, 'greeting' is secret and protected within the createMessage closure. It's inaccessible outside but is still accessible within the returned sayHi function.

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
Post by @im-a-developer · 1 image
Post by @im-a-developer · 1 image
What is Closure in JavaScript?
What is Closure in JavaScript?
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
an image of a black screen with the text closure
an image of a black screen with the text closure
JavaScript Closures Explained in 5 Minutes
JavaScript Closures Explained in 5 Minutes

The Power of Closures: Chaining & Memoization

Closures have another superpower - memoization. This allows us to cache results of expensive function calls, dramatically improving performance. Let's see closures in action with these cool techniques.

Memoization is like having a magic notebook that stores results of calculations you've done before, so you don't have to do them again. It's particularly useful for repeated, heavy computations, like factorial calculations:

AD

Memoizing Function Calls: The Magic Notebook

Here's a simple memoization example:

How JavaScript closures work under the hood [Dmitry Frank]
How JavaScript closures work under the hood [Dmitry Frank]

function memoize(fn) {
  const cache = {};

  return function(...args) {
    if (cache[args]) {
      return cache[args];
    }

    return cache[args] = fn(...args);
  };
}

const factorial = memoize(n => {
  if (n === 1) return 1;
  return n * factorial(n - 1);
});

In this example, the memoize closure wraps the factorial function, caching previous results, and reusing them for identical inputs.

Chaining Closures: Building Complex Functions

Closures let us create powerful, chained functions with minimal effort. Here's an example of creating a 'reverse' function with chained closures:

AD

function reverse(str) {
  return (function(s) {
    return (function(s) {
      return Array.from(s).reverse().join('');
    })(s.split(''));
  })(str);
}

In this function, each closure captures the result of the last function, passing it down to the next. It's like having a secret assembly line of functions that pass data back and forth!

And there you have it - you're now a JavaScript closure pro! So next time you need to hide data, memoize results, or create complex functions, don't forget to reach for a good old closure. Happy coding!

AD