Javascript LET and VAR scopes Example

code.md

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:

  1. call-stack get for loop
  2. call-stack pass each setTimeout Function in to Web API
  3. After the time out Web API will pass the consol.log in to callback queue.
  4. callstack will get the each console.log from callback queue.
  5. console.log check the current value of i (That will be 5)
  6. 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

Popular Posts