Elevate Your JavaScript Skills: Mastering the Magic of Closures ??
Muhammad Gmal
?? Software Engineer | ?? Front-End Developer | JavaScript | React JS | Next JS
??Closures - a concept in JavaScript that might seem complex at first, but is actually a game-changer once you grasp it
?1- Overview and concept
?2- Scoping in javascript
?3- temporal dead zone
?4- Closure in JavaScript
?1. Overview and concept
?? before we start with closures we need to understand Scoping and temporal dead zone
?2. Scoping in javascript
function scope:
Variables declared within a function have function scope. They are only accessible within that function
global scope :
Variables declared outside of any function or block have global scope. They can be accessed and modified from anywhere in your code, including within functions and blocks.
Block Scope (introduced with ES6 using let and const)
Variables declared with let and const within a block (typically enclosed by {}) have block scope. They are only accessible within that block, which includes loops, conditional statements, and functions.
? Practical Example:
领英推荐
? 3. Temporal dead zone :
? Practical Example:
4. ?Closure in JavaScript
?? There are 4 key elements of closures:
?Function Declaration:
Closures are created when you declare a function within another function. The inner function is known as the "nested" or "inner" function, and the outer function is referred to as the "enclosing" or "outer" function.
?Access to Variables:
The inner function has access to its own local variables, as well as the variables declared in the outer function. It can also access global variables.
?Preserved Lexical Scope:
The key feature of closures is that they preserve the lexical scope, which means they remember the scope in which they were created, including all the variables in that scope.
?Independent Instances:
Each closure is an independent instance, so multiple closures created from the same outer function will have their own separate copies of the captured variables.
? Practical Example:
? Explanation: