Algorithms with JavaScript: Closures

in javascript •  4 years ago 

During my first technical interview I was asked about closures in JavaScript. And all I was able to do is to admit that I don’t know anything about closures. And this is how we grow, through failure and feedback. Now I know closure is and will try to explain it to the internet.

Scope

Scope it’s a description of the context inside which variables and functions are accessible and i which is being executed. Basically there are two scopes, global and local.

Global Scope

When something is in global scope it means it is accessible throughout all your code.

var user = "User";
function helloReader () {
   return alert("Someone reading this?");
}

For example, if this code will be run in the web browser then the function scope will be the window. Therefore this function is available in any part of the code as long as it is running inside the web browser window.

Local Scope

By definition, local is something opposed to the global. It’s a code which is accessible only in particular places in your code. For example only inside a function.

function saySomething () {
      var talking = "You can't get me from outside the saySomething function";
return alert(talking);
}
alert(talking); // Throws an error 

In the example above talking accessible only inside saySomething context. If we are going to call this variable outside this function, it will return undefined.

Closures

After we have some understanding of the scope, let’s deal with closures. Closures are expressions which can work with sets of variables within a particular context. We can call expression closure when inner functions refer to the local variables of the outer functions.

function sencence (helloArg) {
  return function (nameArg) {
    return helloArg + nameArg;
  };
}
var hello = sencence('Hello ');
var name = hello("User");
console.log(name)

Let’s follow break it down:

When the sentence function is called, it returns a function definition.
That function closes the context and remembers what the parameter helloArg was at exactly that time (i.e. “Hello ” in the code above)

When the result of calling the sentence function is assigned to the variable hello, it will always know what hello was when it was initially created.

The hello variable above refers to a function which will always combine the value “Hello” to what is being sent in.
That means when hello is called with a value of “User”, it will combine “Hello ” together with “User”, and return “Hello User”.

Self invoking functions

It’s are functions which executes right a way and creates their own closure context:

var expression = function () {
    // Private
    var string = "Initial String";
    return {
     getString: function () {
        return string;
   },
    setString: function (newString) {
     string = newString;
   }
  };
}();

console.log(expression.string); // Undefined
console.log(expression.getString()); // "Initial String"
expression.setString("New String");
console.log(expression.getString()); // "New String"

As you can see we can’t get access to the variable string directly outside of the closure. If we call expression.string it will return undefined. But if we call expression.getString it will return “Initial string”

And great thing about this closure is that we can keep all variables of this closure private and get access to it if we need through self-invoking functions.

Conclusion

I hope that my understanding of the closure is correct and it will be helpful for readers to understand it too. If you have any questions or feedback please share, I will be more than happy to have a dialog and improve our understanding of the JavaScript closures.

You can find samples of the code here.

Authors get paid when people like you upvote their post.
If you enjoyed what you read here, create your account today and start earning FREE STEEM!