front-end mastery - closure scope

Jordan Binskin

2019/09/28

Categories: front-end javascript Tags: closures javascript

Closures

Okay, so if you’re reading my blog for the first time this article with quickly address what is a ‘closure’, or closure scope.

I’ve alluded or mention closure’s in other articles such as: - https://www.jordanbinskin.com/post/2019/11/04/front-end-mastery-immediately-invoked-function-expressions-iife/ - https://www.jordanbinskin.com/post/2019/10/01/front-end-mastery-amd-vs-commonjs-vs-esmodules/

Today I will address them directly, what concepts in JavaScript they relate to, with the hope of improving both our understandings better.

A closure occurs when a function is enclosed with references to its environment (the more JavaScripty term is lexical scope/environment - the rules of this environment grant a function access to it’s outer scope).

The semantics will vary depending on the developer that you ask, but main benefit of a closure is a function will ‘remember’ and have access to its enclosing function scope, even after the outer function has returned. The simplest of examples is below:

function multiplier (multiple) {
  return function (num) {
    debugger; // I added this so if you run the snippet you'll be able to see the value of multiple kept in the closure scope
    return multiple * num;
  }
}

let doubler = multiplier(2);
let tripler = multiplier(3);

doubler(5)
// 10
tripler(5)
// 15

The function above provides a good practical example closure scope. In this scenario I wanted to create a function that would allow me to easily create functions (these are referred to as closures) that act as different multipliers.

I do this by first declaring a function that takes in a multiple as an argument and then returns a second function (the closure).

So to set up a function that can double a number that the user provides, I first declare a variable ‘doubler’ which will be the name of my new function and I pass it a value of 2, as to double a number is to times it by 2 (bam the closure is created).

Now value of doubler is the function which multiplier returns which returns a number multiplied by the multiple. Thanks to the closure scope created, this means that my function that is bound to doubler can still remember (via closure scope access) the multiple variable passed in to multiplier even after multiplier returns (thanks to the lexical scope).

I can now use doubler and pass through any number to return it’s double.