medium-blog

JavaScript Closures: A Beginner’s Guide

Linda Haviv

If you are a beginner to JavaScript, you may have heard the term closures before.

Closures are an important concept and many employers ask about this very concept on interviews. In this article, I will help you gain a better understanding of closures.

WHAT IS A CLOSURE?

In JavaScript, functions are not just functions. They are also closures. What that means is that the function body has access to variables that are defined outside.

A closure can be a function defined inside another function (called the parent function) and has access to variables that are declared and defined in the parent function scope.

The closure has access to variables in three scopes:

  1. Variables declared in their own scope
  2. Variables declared in a parent function scope
  3. Variables declared in the global namespace

If you don’t completely understand the definition, that’s ok. Let’s look at some examples to make more sense of this concept in JavaScript.

A function can access all variables defined inside the function, like this:

function myLuckyNumber() {
var a= 4;
return a * a;
}
myLuckyNumber();

This will output: 16

In this example, a is a local variable. A local variable can only be used inside the function where it is defined. It is hidden from other functions and other scripting code.

But a function can also access variables defined outside the function, like this:

var a = 4;
function myLuckyNumber() {
return a * a;
}
myLuckyNumber();

This will also output: 16

In this example, a is a global variable. Javascript notices that there is a reference in a different scope so it keeps it alive. Notice that we don’t pass in any argument and it still outputs 16.

In this example, JavaScript is retaining the state and scope of the variable even after it executes.

This happens because JavaScript functions are closures. We cannot do this in languages that do not have support for closures. In other languages, we would have to the variable as an argument inside the function instead because such a language would not have access to the outer scope.

It’s important to note that myLuckyNumber(); really does have access to the outer variable scope. In the example below if I redefine the variable a, the function output will change accordingly:

var a = 4;
function myLuckyNumber() {
return a * a;
}
a = 6
myLuckyNumber();

This will output: 36

So this example shows that myLuckyNumber(); is not taking a snapshot of the variable when it is declared, rather, it actually reads whatever the variable is at that point in time.

  • **Important Note: Global and local variables with the same name are different variables. Modifying one, does not modify the other.

Older Post Newer Post