DEV Community

Kush
Kush

Posted on

Introduction to Closure

In simple words, you can remember closure as:

A closure gives you access to an outer function's scope from an inner function.

Closure is considered as the most powerful in all of Javascript programming.
You don't believe me yet? Let's see:

Imagine when you're in a good mood and talking to a friend. Everything seems right and you just greet everyone nicely because you feel like it to be there until someone pisses you off and then imagine talking to that friend or just imagine feeling about the friend. Everything seems falling off and you decide to blurt out.

Just like our code here:

const greet = x => {

  const name = y => {
    // x is an outer variable
    // inner function name has closure over it
    return x + ' ' + y + '!';
  }
  return name;

}


const goodMood = greet('Hello');
// goodMood gets a reference to the inner 'name' function
// because we're returning 'name' function in 'greet' function
// with closure over the 'x' parameter of the outer function 'greet'
const badMood = greet('Get lost');
// badMood gets a reference to the inner 'name' function
// with closure over the 'x' parameter of the outer function 'greet'

let greetDavid = goodMood('David');

console.log(greetDavid); // Hello David!

greetDavid = badMood('David');

console.log(greetDavid); // Get lost David!
Enter fullscreen mode Exit fullscreen mode

goodMood and badMood remember the variable 'Hello' or 'Get Lost' even when we thought the function has stopped running.

That's the power of 'Closure'.

Depressed Pablo Escobar
Hey, I was doing just fine before I met you 🎶 🎶 🎶

Source

Top comments (0)