Javascript LET and VAR scopes Example
Javascript LET and VAR scopes Example
For loop
VAR
for (var i=0;i<5 ; i++) {
setTimeout(()=>{console.log(i)},0)
}
Here The Out put will be
// 5 5 5 5 5
var - function scope, and only one shared binding for all of your loop iterations
.
The var is function-scoped, That means it lies within an enclosing function. here it is globalscope; The setTimeout function can access the value of i because of closure. Event Loop Working:
- call-stack get for loop
- call-stack pass each setTimeout Function in to Web API
- After the time out Web API will pass the consol.log in to callback queue.
- callstack will get the each console.log from callback queue.
- console.log check the current value of i (That will be 5)
- print the current value of i
LET
let - block scope and when used in the for loop you get a new binding for each iteration
for (let i=0;i<5 ; i++) {
setTimeout(()=>{console.log(i)},0)
}
Here The Output will be
// 0 1 2 3 4
Comments
Post a Comment