Can't find a lesson to learn Closure

I have just finished Intermediate Javascript course and was looking for a lesson to learn Closure and Lexical Environment. I’d really appreciate it if you tell me where to find them! Thank you.

Hi,

Not sure if cc has a specific lesson dedicated to it, but you can always check the MDN docs and even play around in the code spaces they provide: Closures - JavaScript | MDN

1 Like

One term that is oft repeated is, “execution context”. In JS the term simply translates to “environment”, or “lexical scope”. A lexicon is a lookup object, or in programming lingo, a namespace. Functions have their own namespace, and it is not shared with any scope above them. They are their own execution context. This gives us the simplest form of closure, a confined execution context.

The next level of closure is variable persistence. We see this in factory functions when a function is returned with user provided constants. Now we have a function with closure around both execution context and constants.

Now we get to the real juice that gives jQuery its alias, $, which I’ll leave the reader to discover in their own research.

Bottom line, this is a technique for protecting things. Keep that philosophy in mind, and if you cannot find practical application, just now, don’t let it hold you up in the learning path.

1 Like

My favourite example of a factory function that returns a function is the log factory

const logFactory = base => x => Math.log(x) / Math.log(base)
const log2 = logFactory(2)
console.log(log2(64))
6

These functions are totally disposable, and moot…

console.log(logFactory(2)(64))
<- 6
console.log(logFactory(8)(64))
<- 2

The factory is able to issue a disposable function, yet our goal is achieved,

This suggests we can remove some of the mystery and use log(base, value) as our template for any call.

const log = (b, v) => logFactory(b)(v);
console.log(log(2, 64))
console.log(log(8, 64))
6
2

Closure exists around a state. It is not a panacea. It is our objective to capitalize on this in a dynamic environment, while leaving a minuscule memory footprint.

1 Like

Thank you very much! After reading your comment and some other videos about Closure, I think I am getting to know about it. haven’t gotten a clear sense yet though :wink: By the way, for that arrow function for const logFactory, I am curious if I understood it right.

function logFactory(base) {
  function (x) {
    Math.log(x) / Math.log(base);
  }
}

A factory function returns a function. Where is the return in that function?

function logFactory(base) {
  return function (x) {
    Math.log(x) / Math.log(base);
  }
}

oops. is this?

1 Like