Working of closures in JavaScript ?
Working of closures in JavaScript ?
I completed my post-graduation in 2013 in the engineering field. Engineering is the application of science and math to solve problems. Engineers figure out how things work and find practical uses for scientific discoveries. Scientists and inventors often get the credit for innovations that advance the human condition, but it is engineers who are instrumental in making those innovations available to the world. I love pet animals such as dogs, cats, etc.
Aryan Kumar
21-Jul-2023A closure in JavaScript is a function that has access to the variables in its enclosing scope, even after the enclosing scope has been closed. In other words, a closure is a function that "remembers" the variables from the scope in which it was created, even after that scope has been destroyed.
Closures are created when a function is created within another function. For example, the following code creates a closure:
In this code, the
outerFunction()
function creates a closure by creating theinnerFunction()
function within its scope. TheinnerFunction()
function has access to thename
variable from theouterFunction()
scope, even though theouterFunction()
function has already been executed.Closures can be used to create reusable functions that can access data from other functions. For example, the following code creates a closure that can be used to get the current user's name:
In this code, the
getName()
function creates a closure that returns thegetUserName()
function. ThegetUserName()
function has access to thename
variable from thegetName()
scope, even though thegetName()
function has already been executed.The
getUser()
function then calls thegetUserName()
function to get the current user's name.Closures are a powerful tool that can be used to create reusable and efficient JavaScript code.