Closure in Javascript

Closure in Javascript

ยท

7 min read

Hello Folks, in this article I'd be talking about closure in javascript. Closures are used in all codebases, and it's very essential to know them. coding a little test made me know when and where to use closures, I found it very exciting unravelling this knowledge.

What is a closure ?

According to MDN docs,

A closure is the combination of a function and the lexical environment within which that function was declared i.e in order words closure gives you access to an outer function scope from an inner function

Now, what does the lexical environment mean,

This refers to the scope or location where a variable is declared within the source code to determine where that variable is available.

Let's dive into some coding samples to get a clearer understanding of closures.

function getName(){
     let name = "jon doe"
     function displayName(){
       console.log(name)
     }
     displayName();
}

getName(); // logs out the variable called inside the displayName function after it has been  executed.

So basically what happened in these lines of code is that our function called getName() holds a local variable and a function, which automatically makes them properties of the lexical environment of the getName() method. Notice that displayName() is a nested function because it's wrapped inside the getName() method and this makes it possible for it to be able to access the variable outside of it.

Nested functions have access to variables declared in their outer scope.

According to MDN (Mozilla Developer Network), it stated that Closures are useful because they let you associate data (the lexical environment) with a function that operates on that data. This has obvious parallels to object-oriented programming, where objects allow you to associate data (the object's properties) with one or more methods.

I hope this was really easy to grasp ๐Ÿ˜‰, Now it can even get trickier cos I learnt something while trying to fix a simple bug for hours.

When we have private methods inside a parent function scope, and we want to access the values in them, we have different ways or methods of doing so, one which is popular amongst our coding style which is using the this keyword, but for the sake of our topic which is closure, I'd be showing the method too so you could be the judge and pick which is easily graspable and more performant.

function Secret(param) {
  let secret = param

  this.getSecret = () => {
    return secret
  }

  this.setSecret = (newSecret) => {
    return (secret = newSecret)
  }

 let logOut = new Secret('hey do yunno my secret')

logOut.getSecret() //would  return the parameter string  set inside the  Secret method

logOut.setSecret('yeah I do know your secret') // this would set the local variable secret to a new value

This style is pretty much okay, in fact, I use it oftentimes in my codebase.

So now how can we access private methods with closures without using the this keyword?

This is where Emulating private methods with closures come in.

going through the MDN docs again, it explained furthermore

Languages such as Java allow you to declare methods as private, meaning that they can be called only by other methods in the same class.

JavaScript does not provide a native way of doing this, but it is possible to emulate private methods using closures. Private methods aren't just useful for restricting access to code. They also provide a powerful way of managing your global namespace.

In order to achieve this, Javascript uses a pattern under the hood called Module design pattern. ** (in my next article I'd dive into breaking down how this pattern works, but for now I'm still conducting research on it).

function Secret(param) {
  let secret = param

  const getSecret = () => {
    return secret
  }
  const setSecret = (newSecret) => {
    return (secret = newSecret)
  }
  return {
    getSecret,
    setSecret,
  }
}

let Logout = new Secret ('hey secret')
Logout.getSecret() // returns the value
Logout.setSecret('new secret alert') // sets the variable with a  new value

I guess you are wondering what's the work of the return object and methods In it, so basically, the return object makes it possible to return the value of the methods. without the return object, there's no way you'd be able to access the inner functions. Some frameworks use this style to mimic encapsulation in object-oriented programming. This is where the revealing module pattern falls in, which I'd explain in my next article.

I hope you were able to understand the power of closures and how to use it. For a deeper understanding, Mozilla Developer Network documentation is the best place to go to ๐Ÿ˜‰