Hello everyone,๐
If you are new to JavaScript, it can be little bit of challenging to understand some core and Advance topics ๐คทโโ๏ธ. But don't worry keep your fingers crossed๐ค because in this article you'll get full information regarding Advanced JS Topics๐.
โก 1. Closures:
๐ MDN Def: A closure is the combination of a function bundled together (enclosed) with references to its surrounding state (the lexical environment).
Doesn't sound great to you???๐ค Don't worry. Stay tuned.๐ฅ
So, Basically a function bind together with its lexical environment or lexical scope is known as Closer. Let's see what exactly is lexical scope.
โกThe word lexical refers to the fact that lexical scoping uses the location where a variable is declared. Nested functions have access to variables declared in their outer scope.
โก Running this code has exactly the same effect as the previous example of the x() function above.
โก What's different (and interesting) is that the displayName() inner function is returned from the outer function before being executed. The reason is that functions in JavaScript form closures. A closure is the combination of a function and the lexical environment within which that function was declared.
โ Every closure has three scopes:
- Local Scope (Own scope).
- Outer Functions Scope.
- Global Scope.
โ Let's say a function can access some variables of it's lexical environment or parent scope, the function actually remembers the reference of variable but it's value.
Let's look at the code:
Now you might have a bit understanding of Closures right.๐
โ let's see some of uses of Closures:
- Module design pattern.
- Currying.
- Functions like once.
- Memoize.
- Maintaining state in Async World.
- setTimeouts.
- Iterators.
- and so on.......!.
{ .....
..
... to be continued.
}
Top comments (0)