JavaScript Shortcuts: A Basic Guide

Original author: Parathan Thiyagalingam
  • Transfer
We present to your attention a translation of the Parathan Thiyagalingam article published on medium.freecodecamp.org. Want to know how JavaScript closures work? Look under the cat!


Photo by Austin Distel with Unsplash A

closure is a combination of all the variables in scope at the time the function was created. To use closure, you need to create a nested function, that is, a function inside the function. The inner function will have access to the variables in the scope of the outer function even after the outer function completes. (It is the closure that provides this access.) Each time a function is created, the closure is also created.

Before you begin to understand the concept of closures, consider what are the scope chains in JavaScript.

As a rule, there are two types of visibility areas: global and local.

In JavaScript, a variable inside a function is not accessible externally - unlike, for example, variables within a block (in conditions like ifand while).

Based on this, a function in JavaScript has a scope, but a block does not.

var a = 10;
functionapp(){
   var b = 2;
   console.log(a); // 10console.log(b); // 2
}
console.log(b); //   ReferenceError: b is not defined
app();

As we already know, a is a global variable, and b is local, that is, used only by a function app. Outside the local scope, we do not have access to the local variable.

How to use a nested function (function inside a function)


var a = 10;
functionapp(){
     var b = 2;
     var d = 3;
  functionadd(){
     var c = a + b;
   }
 return add;
}
var x = app();
console.dir(x);

In the example above app, this is a parent function, add- a child function .

  • Instead of console.log, console.dir is used to display all the properties of the selected object .
  • The variable x is assigned to the function app, which then returns the function add. This allows you to see all the properties of the function object add.

If you open the console in a browser, you will find the object Closureinside the data array Scopes.



Since the inner function addhas access to the variables b and d , which belong to the outer function, these two variables will be added to the object Closureas a reference.
Consider another closure example.

var a = 10;
var startFunc;
functionapp(){
      var b = 2;
   functionadd(){
      var c = a + b;
      console.log(c);
   }
   startFunc = add();
}
app(); // Invoke the app function
startFunc; 
// as the app function invoked above will assign the add function to startFunc & console the value of c

  • A global function is startFuncassigned a function addthat is a child of the parent function app.
  • This becomes possible only after calling the app function. Otherwise, the function startFuncwill behave like a global variable without an assigned value.

How to use closures in JavaScript


Many of us, using closures when writing code, do not fully understand why they do this. JavaScript lacks the public , protected, and private modifiers that are in object-oriented programming languages. Therefore, to block access to the namespace for external code, we are forced to resort to the help of functions.

And since we are talking about functions - the immediately called function (IIFE) starts immediately after the announcement. She doesn’t even need to be called.

The IIFE syntax looks like this:

(function(){
             //variables & scope that inside the function 
})();

Consider this example:

var studnetEnrollment = (function () {
    //private variables which no one can change//except the function declared below.var count = 0;
     var prefix = "S";
    // returning a named function expressionfunctioninnerFunc() {
         count = count + 1;
         return prefix + count;
     };
 return innerFunc;
})();
var x = studnetEnrollment(); // S1console.log(x);
var y = studnetEnrollment(); // S2 console.log(y);

countand prefix- two private variables that cannot be changed. Access to them is open only for an internal function (in our case, this is a function innerFunc).

  • The first time the function studentEnrollmentis called, the function innerFuncincreases the value of the variable countto 1.
  • The second time, the value count increases from 1 to 2.
  • All this is possible only through closure.

Conclusion


A closure is a set of variables of an external function, due to which the scope of the internal function gets access to these variables. This protects the global namespace.

The closure functionality allows developers to write clean code - such as in object-oriented programming languages, code in which global and local variables are not confused.



Have a nice coding!

Also popular now: