Closure Usage

Tutorial 4 of 4

1. Introduction

In this tutorial, we will be exploring the concept of closures in JavaScript. Closures are an important and powerful feature in JavaScript that allow functions to have "private" variables. The function has access to its own scope (variables defined between its curly brackets), the outer function's variables, and the global variables.

What you will learn:
- What closures are and how they work.
- How to create and use closures.
- The practical applications and best practices of using closures.

Prerequisites:
- Basic understanding of JavaScript syntax and functions.
- Familiarity with the concept of scope in JavaScript.

2. Step-by-Step Guide

A closure is a function that has access to its own scope, the scope of the outer function, and the global scope. The closure has access to variables in three separate scopes:

  • Variables in its own scope.
  • Variables in the scope of the outer function.
  • Global variables.

Let's understand this with an example:

function outerFunction(outerVariable) {
  return function innerFunction(innerVariable) {
    console.log('outerVariable:', outerVariable);
    console.log('innerVariable:', innerVariable);
  }
}

const newFunction = outerFunction('outside');
newFunction('inside');  // Logs: outerVariable: outside innerVariable: inside

In the above code, innerFunction is a closure that is defined inside outerFunction and has access to outerFunction's variables and parameters.

3. Code Examples

Example 1:

function greeting(name) {
  let message = 'Hello';
  function sayHello() {
    console.log(message + ' ' + name);
  }
  return sayHello;
}

let greetJohn = greeting('John');
greetJohn(); // Logs: Hello John

In the above code, sayHello is a closure that is defined inside greeting and has access to greeting's variables and parameters.

Example 2:

function counter() {
  let count = 0;
  function incrementCount() {
    count++;
    console.log(count);
  }
  return incrementCount;
}

let count = counter();
count(); // Logs: 1
count(); // Logs: 2

In this example, incrementCount is a closure that is defined inside counter and has access to counter's variables.

4. Summary

In this tutorial, we have learned about closures in JavaScript: what they are, how to create them, and their practical use. Closures are an important feature of JavaScript that allow for powerful and flexible function programming.

Next steps for learning:
- Learn about other advanced JavaScript concepts such as promises and async/await.
- Get hands-on practice with closures by writing your own functions that use them.

Additional resources:
- MDN Web Docs: Closures
- JavaScript.info: Closures

5. Practice Exercises

Exercise 1: Write a function that makes a personalized greeting. This function takes two parameters: name and greeting. It returns a function that logs a message with the name and greeting.

Solution:

function createGreeting(name, greeting) {
  return function() {
    console.log(greeting + ' ' + name);
  }
}

let greetJohn = createGreeting('John', 'Hello');
greetJohn(); // Logs: Hello John

In this exercise, the function returned by createGreeting is a closure because it has access to the name and greeting parameters of the outer function.

Exercise 2: Write a function that creates and manages a counter.

Solution:

function createCounter() {
  let count = 0;
  return function() {
    count++;
    console.log(count);
  }
}

let counter = createCounter();
counter(); // Logs: 1
counter(); // Logs: 2

In this exercise, the function returned by createCounter is a closure because it has access to the count variable of the outer function.

Tips for further practice:
- Try to create a closure with more than one function in the outer function's scope.
- Practice using closures with event handlers and callbacks.