Welcome to Javascript closure

Welcome to Javascript closure

Introduction

As a fresher you might have heard of closure right, but what exactly is closure and why it is important to understand it.

What is a closure?

It is the combination of a function bundled together with references to its surrounding state. 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.

We use closures through out our program but are not aware of it. So we will learn here more.

// Basic example of closure
function greetings() {
     var name = "Jowel";
    function hello() {
        console.log('Hi' + ' ' + name); //Inner function accessing the outer function variable 
    }
    hello();
}
greetings(); // Hi Jowel

Here greetings is an outer function and hello is an inner function, and a variable "name" is created in the scope of outer function. So due to the concept of closure the inner function can access the variable "name" and used it to console log it. Similar to this, the inner function can access the arguments, variables and functions of the outer function.

// Example of closure with arguments
function greetings(name) {
    function hello() {
        console.log('Hi' + ' ' + name); //Inner function accessing the outer function arguments
    }
    hello();
}
greetings('John'); // Hi Jowel

Data privacy with closures

Closure is also majorly used for data privacy, which means we can keep the variables and functions private for a particular scope and not let it access outside of that scope. Which helps in building robust and less bug program.

In some situation we might only want a variable for a particular function, so it should not be accessible outside of its scope.

// Example of data privacy with closures
function greetings() {
   let name = "Jowel"
    function hello() {
        console.log('Hi' + ' ' + name); //Inner function accessing the outer function arguments
    }
    hello();
}
console.log(name); // name is not defined
greetings(); // Hi Jowel

Here when we are trying to console log "name" outside of greetings function it says "name is not defined" because it has been kept private in the greetings scope due to closure. So you can only access the "name" variable inside the greetings scope.

Summary

  • The inner function of a program has access to all the variables, arguments and functions of its outer function
  • The variables can be kept private in a scope, i.e The outer function cannot access the variables inside an inner function

Overview

This was a basic explanation of what closure is in javascript, It is a core concept which is necessary to understand for strong a foundation. If you want to learn more about closures you can visit this link