Table of contents
Introduction
Closure is one of the most important features of JavaScript that's why every interview question list available on the internet for web developers has this question. I think no Web development interview gets completed without this question "What is Closure or Explain Closure in JavaScript?".
The definition of JavaScript is quite simple and straight but in reality, it gets complex when we go deeper into it.
Definition
A closure is the 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.
Explanation
JavaScript allows you to create nested functions and allows the inner function to access the variable and functions declared or defined in the outer function and all the variables and functions that the outer function has access to.
However, the outer function does not have access to the variables and functions defined inside the inner function.
Explanation with Code
let name = "Radhe";
function namefunction(){
console.log(name)
}
namefunction()
Here const named "Radhe" is present outside of the function despite this, the namefunction can easily access the name variable
function outerfunction(){
var o = "This is local variable of outer function "
console.log(o)
function innerfunction(){
var i = "This is local variable of inner function"
console.log(i)
console.log(o)
}
innerfunction()
}
outerfunction()
When we run this code we can see below result in our console
This is local variable of outer function
This is local variable of inner function
This is local variable of outer function
This code indicates that we can access the outside variables and functions in the inner functions but vice-versa is not true. We can't access functions and variables of inner functions from outer functions.