Question:

Describe what closures are and use at least two examples to demonstrate how they work.


Closures are a built in feature of the JavaScript language. We don’t actually create a closure but are taking advantage of how JavaScript works. Let’s get rid of any confusion you may have about closures in this short article.

When we have a function within another function like the one below we can use closures to let inner function have access to outside functions variables and parameters.

function greet(saySomething) {

 var greetPerson = function (name) {
     return  saySomething + " " + name;
 };
  return greetPerson;
 }
 
 var sayHello = greet("Hello"); /
 
 console.log(sayHello("Oscar"));

The code above executes and creates a global execution context. It gets to the line var sayHello = greet("Hello") that invokes the greet function with the parameter “Hello”. Since the greet function returns another function it’s kick off the call stack and greetPerson is added to execution context. Although greet was kicked off the parameter of "Hello" remains behind because this is what JavaScript does on its own. An inner function has access to the parent variable and parameters. when we get to the line return saySomething + " " + name; JavaScript goes up the scope and finds saySomething. Then it uses it in the return statement.

So when we get to the last line of code JavaScript knows we want “Oscar” to be for the inner function because we already passed one for greet. It would be same as writing greet("Hello")("Oscar") but makes the code easier to read.

Closures are also very useful in callbacks :

function setAlarm(message, timeout) {
    
   function handle() {
     console.log(message);
   }
  
   setTimeout(handle, timeout);
  }

setAlarm("Wake UP!", 800);
  

Here we use closures in another function to get access to the message since it will be on a new stack. That covers this article I hope this made it more clear on what JavaScript closures are useful for and why there an important part of the language.