JavaScript (JS) Bytes 1

JS

Hi, this is going to be a series, where i will be talking about leveraging the power of JavaScript in its essence and thereby developing resourceful apps. JavaScript is the language of the browsers. Despite being available for almost two decades only few have mastered the intricacies of understanding how JavaScript is different from other Object Oriented Languages, and how much it benefits the developer community if mastered from get-go. 

The more we delve deep into JavaScript, the more we appreciate it's beauty

Today we will be looking at closures? This is the most widely used misnomer in JavaScript semantics. In a nutshell Closures allow lexical scoping thereby allowing the context of a function/object to be saved and stored for later purpose. 

Let us understand it better with an example: Open your Developer Tools and follow along !

//Js bytes Closures
function maker(x) {
    return function(y) {
        return x * y;
    }
}
var t5 = maker(5);
var t10 = maker(10);
console.log(t5(5));
console.log(t10(5));

Here we have a function called maker which returns another function. At first we store the lexical content of 5 in variable t5, and lexical content of 10 in variable t10. By doing so, we have separated out the concerns for the different invocations and saved them for later usage. 

Hence while printing in the console, we will get the result as 25 and 50 respectively.

In some programming languages, the local variables within a function exist only for the duration of that function's execution.

However, because the code still works as expected, this is obviously not the case in JavaScript.

The reason is that functions in JavaScript form closures. A closure is the combination of a function and the lexical environment within which that function was declared. This environment consists of any local variables that were in-scope at the time the closure was created.

Here t5 and t10 are both closures. They share the same function body definition, but store different lexical environments. In t5's lexical environment, x is 5, while in the lexical environment for t10x is 10.

That's closure for you! Stay tuned as we equip with more powerful tools which will allow us to write better JavaScript and save the Internet from Callback Storm. Till next time !

 

Add new comment

Restricted HTML

  • Allowed HTML tags: <a href hreflang> <em> <strong> <cite> <blockquote cite> <code> <ul type> <ol start type> <li> <dl> <dt> <dd> <h2 id> <h3 id> <h4 id> <h5 id> <h6 id>
  • Lines and paragraphs break automatically.
  • Web page addresses and email addresses turn into links automatically.
CAPTCHA
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.