DEV Community

Murtaza Nathani
Murtaza Nathani

Posted on

Best way to learn Closure in JavaScript ?

There are tons of resources out on the web which explain what closure is...

I will cut the crap of giving this:

a function inside a function bla bla... is closure.

Instead what I will do is to give you a 1 minute snippet that you need to scan and understand the output of the below 👇 code will be (without running on compiler or looking into the answer).

Once done we can check the answer and learn the concept of it.
Please feel free to comment, would love to respond and learn together.


let cachedFunc = null

function log(message) {
  if (!cachedFunc) {
    // creates a function that closes over `message`
    // keep in mind `message` inside `log` is different
    // on each call
    cachedFunc = () => console.log(message)
  }
  cachedFunc();
}

log("hello")
log("goodbye")
Enter fullscreen mode Exit fullscreen mode

Check the answer below compare:

Click to expand the Answer

Step by step execution:

  1. cachedFunc is declared with null, and a function log.

  2. On calling log("hello"), the context of calling log function is same as the cachedFunc declared, so it will find it's value to null as declared in outer scope.

  3. Inside the if condition it will update the cachedFunc to a inline function which prints argument message to console.

  4. Then it calls cachedFunc method which results in the message "hello".

  5. On the second call log("goodbye") will not initialize the method again.

    So it will call the method that was in previous scope, in which the value of message is "hello" and that's why it will print the same "hello" again.


Further explanation related to Reactjs:

Under the hood, useCallback works in a very similar way. On the first render, React saves the function you pass to useCallback somewhere and will always return that function.

Every other render will have your saved function, and will "remember" the scope it was created in, including the old value.

Without useCallback or adding dependencies to it, a new function would be created on each render or change in the dependencies, which means it would be able to refer to new with an up-to-date value.



Here is the link to codepen to further play with it :)

Regards.

Discussion (0)