JavaScript Basics is a series that explore some core concepts that every frontend software engineer should understand. Those concepts are not only important for success in job interviews but also for a career as a developer.

In this section of our JavaScript Basics Series, we will explain a very important concept known as closure. What makes it particularly important that it is not only a core concept of JavaScript itself but also very likely to come up in JavaScript-related interviews. Without further ado let’s get into it! 😃

What is Closure?

One of the better definitions of this is the one provided by Mozilla’s web docs:

closure is a combination of a function bundled together (enclosed) with references to its surrounding state (the lexical environment). In other words, a closure gives you access to an outer function’s scope from an inner function. In JavaScript, closures are created every time a function is created, at function creation time.

In other words, it’s the fact of putting a function inside of another, which gives the enclosed function access to the outer one’s variables. The term ‘lexical environment’ is referring to the scope of the outer function in this case. Let’s illustrates this with an example:

function outer(){
     let outerVar = "outside";

     function inner(){
            let innerVar = "inside";
            console.log("The outer variable is " + outerVar);
     }
 return inner;
}

#closure #javascript #basics #fundamentals #function

JavaScript Basics Series: Closure
1.25 GEEK