0
0
Javascriptprogramming~5 mins

Closures in Javascript

Choose your learning style9 modes available
Introduction

A closure lets a function remember the variables from the place where it was created, even if it runs somewhere else later.

When you want to keep some data private inside a function.
When you want to create a function that remembers a value between calls.
When you want to make a function factory that creates similar functions with different settings.
When you want to avoid using global variables but still share data between functions.
Syntax
Javascript
function outer() {
  let secret = 'hidden';
  function inner() {
    console.log(secret);
  }
  return inner;
}
The inner function can access variables from the outer function even after the outer function finishes.
Closures happen automatically when a function accesses variables from its outer scope.
Examples
This example creates a counter function that remembers the count variable between calls.
Javascript
function makeCounter() {
  let count = 0;
  return function() {
    count += 1;
    return count;
  };
}

const counter = makeCounter();
console.log(counter()); // 1
console.log(counter()); // 2
This example creates a greeting function that remembers the name given when it was created.
Javascript
function greet(name) {
  return function(message) {
    console.log(`${message}, ${name}!`);
  };
}

const greetAlice = greet('Alice');
greetAlice('Hello'); // Hello, Alice!
Sample Program

This program creates a function that adds 5 to any number given. The inner function remembers the value 5 from the outer function.

Javascript
function createAdder(x) {
  return function(y) {
    return x + y;
  };
}

const addFive = createAdder(5);
console.log(addFive(10));
console.log(addFive(3));
OutputSuccess
Important Notes

Closures keep variables alive even after the outer function ends.

Be careful not to create memory leaks by holding onto large data unintentionally.

Summary

Closures let functions remember variables from where they were created.

They are useful for data privacy and creating flexible functions.

Closures happen automatically when inner functions use outer variables.