Background
Closures in Javascript
It's important to note that it is not just a function but a combination of function + referenced to its lexical environment.
Let's take a simple example:
(() => { var name = "Aniket"; const displayName = () => { console.log(name); } displayName(); })()
The (()=>{})() is a self-executing function. Inside it, you can see an anonymous function defined using the arrow operator. Inside this function, we have defined a variable called name and again an anonymous function called displayName which prints the name variable in the console.
What is interesting to note here is that even though the variable name is local to the outermost anonymous function we can still access it inside the displayName method, this is possible due to closures. When we created an anonymous function & assigned it to the displayName const variable it actually created a closure that comprised of the function itself + the reference to the lexical environment which includes the name variable defined in the outer scope.
NOTE: Nested functions have access to variables declared in their outer scope.
Understanding scopes
Here check variable even though was defined inside the if block has become a global scoped variable (Unlike other languages like Java where it would have created a local scoped variable).
- let - defines a variable local to the scope
- const - defines a constant variable again local to the scope.
Interesting examples
Now let's see some interesting examples before we wind this up.
See the below examples & predict the output
const myName = ["Aniket", "Abhijit", "Awantika"]; for(var i; i<myName.length;i++) { setTimeout(function(){ console.log('Name: ' + myName[i] + 'at index:' + i); },3000) }
The output is
It prints undefined as Name & index as 3 all the three times the loop executes. Let's try to understand why this happened: When we pass a custom function inside setTimeout it creates a closure of the function bundled with the captured environment from the out functions scope. Three closures are created by the loop but each shares the same lexical environment which has the variable "i" with changing values. This is because the "i" variable is defined as var and has a global scope. The value of "i" in the passed function is determined when it is actually executed after the timeout completes (when it comes from the event loop). Since the loop has already been completed by the time these closures from the event loop are executed "i" points to 3 and there is no such index in that array as the size is 3 and the index range from 0 to 2. Hence it prints "i" as 3 and the name as "undefined" three times - one for each closure created in the loop.
You can fix this by using a wrapper function to be passed inside setTimeout API argument which will create its own closure with the actual local value of "i" and pass it to the event table instead of just the original closure which is pointing to global scoped "I". Eg see below where I have given two ways one using function keyword and one using anonymous function
Or you could simply change var to let in the for loop which will create a block-scoped variable instead of a global scope and changes will still work fine.
No comments:
Post a Comment