What are Closures?
The Closures occur in JavaScript when a function “remembers” its lexical scope even if it’s executed the outside that scope. In other words, a closure allows a function to access variables from its containing function and even after the containing function has finished executing.
Example: In this example, a closure is created where the inner function retains access to the “name” variable from its containing “outers” function, allowing it to display a personalized greeting when invoked.
Javascript
function outers() { let name = "Kumar" ; function inner() { console.log( "Hello, " + name + "!" ); } return inner; } let greeting = outers(); greeting(); |
Output:
Hello, Kumar!
Difference Between Scope and Closures in JavaScript
The scope and closures are fundamental concepts that play a crucial role in how variables are accessed and managed within the functions and blocks of code. In this article, we will learn about the difference between scope and closures in JavaScript.