Closures

Closures

Not the kind you ask for when they say it's over ๐Ÿ˜’

ยท

2 min read

In the beginning, was a function

We all have at some point, spent what seemed like hours, fixated on a block of code, lost.

Closures dramatically show up in algorithms and APIs, so thankfully, now that I understand how they work, comprehending and writing Javascript on an intermediate level no longer seems as impossible as it used to.

Let me walk you through my thinking process in 3 rules ๐Ÿ˜Ž

Take a look at the code snippet below ๐Ÿ‘‡๐Ÿพ

function myClosure(i) {

  let within = i;
  return () = > within;
}
let yourClosure = myClosure(6);
console.log(yourClosure());

There are two functions in that block of code.

The first myClosure() is global, and the parameter i passed into it is assigned to the variable within.

The other, is an enclosed arrow function that returns the variable within.

By implication, the global function myClosure() references it's parameter i as a variable within it, and i is returned everytime myClosure() is called.

So, rule 1 ๐Ÿ“

At the core of every closure is that it references a variable within it, in this case, starboy i,

Next, you'll see, that the return value of the global function myClosure() is stored in an outer variable/argumentyourClosure()

In other words, yourClosure() stores
( ) => within;

So, rule 2 ๐Ÿ“

When a closure is called, it responds to the outer environment (yourClosure()), not what's inside it.

To make it make more sense, I've introduced a parameter to the enclosed arrow function in the snippet below ๐Ÿ‘‡๐Ÿพ

function myClosure(i) {

let within = i;
return (newGuy)=> within += newGuy;
}
let yourClosure = myClosure(6);
console.log(yourClosure(8));

At this point, yourClosure() once called, its accompanying argument 8 (which represents newGuy) is added to i(read: 6), and console logs //14

and.. rule 3 ๐Ÿ“

For everytime a closure is called, the references within it are created without affecting previous or subsequent calls.

Final example below ๐Ÿ‘‡๐Ÿพ

function myClosure(i) {

let within = i;
return (newGuy)=> within += newGuy;
}

let yourClosure = myClosure(6);
let extra closure = myClosure(7)

console.log(yourClosure(8));
console.log(extraClosure(9))

Console comfortably logs two separate values, //14 and //16both dependent on myClosure without rivalry or jealousy.

There you have it

Closures ๐Ÿ˜…

I imagine that the rough examples could be re-written into a small scale API for an imaginary food truck.

I'll probably jump on that.

Till then, adios ๐Ÿš€๐Ÿš€.