Understand Closures in JavaScript

So what the heck are closures? πŸ€”πŸ’­ They're not as crazy as they sound, trust me. You may have even used them plenty of times without even realizing it! Let me try to explain this as simple as possible: A closure is basically a reference to a function's lexical environment or scope even after that function has already returned. A closure allows an inner function to access the variables and parameters of its outer function even if that outer function has already returned! Okay, I guess it didn't sound that simple πŸ˜… Let me explain with code!

A pretty cool example πŸ‘€

function outer(){
  var outerVariable = "I am still accessible!";
  
  function inner(){
  	console.log(outerVariable);
  }
  
  return inner;
}

So... what's going on here? 😰

  1. We declared a function called "outer" containing one variable in its lexical environment called "outerVariable." This is our outer function.
  2. We declared a function called "inner" which simply logs out the outerVariable. This is our inner function.
  3. Outer returns the function inner. (Note: we are not calling the function, we are returning the function itself!)

Now, let's create a Closure πŸ§™

function outer(){
  var outerVariable = "I am still accessible!";
  
  function inner(){
  	console.log(outerVariable);
  }
  
  return inner;
}

var closure = outer(); // calling this returns the function 'inner';
console.log(closure);

Here we create a variable called closure and set it equal to the invocation of the outer function. Clearly, we can see that the outer function returns the inner function. Here is what the console looks like:

console

Now, let's call this function:

var closure = outer(); // calling this returns the function 'inner'
closure(); // I am still accessible!

This is what a closure is. Even though the outer function was already called, the inner function still had access to its outer function's variables! You might be thinking "Why would I even need this? How is this practical?" Great question, it's because closures allow us to create private variables which is great for security and encapsulation!

Congrats! πŸŽ‰

Now you know what closures are! This is still a general overview of what closures are in JavaScript so please continue to practice and experiment! I hope this tutorial was helpful! πŸ€“ See ya later!

~ Faraaz