-1

Why does this javascript code output the same result?

var myAlerts = [];

  for (var i = 0; i < 5; i++) {
     myAlerts.push(
        function inner() {
            alert(i);
        }
     );
 }

   myAlerts[0](); // 5
   myAlerts[1](); // 5
   myAlerts[2](); // 5
   myAlerts[3](); // 5
   myAlerts[4](); // 5

I'd expect to see in 1, 2, 3, 4. It feels like it's something related to lexical scoping, but what's the real reason behind?

Can someone explain exactly how this piece of code work behind the scenes?

DaFois
  • 2,197
  • 8
  • 26
  • 43
leonardofed
  • 936
  • 2
  • 9
  • 24
  • 1
    Possible duplicate of [JavaScript closure inside loops – simple practical example](https://stackoverflow.com/questions/750486/javascript-closure-inside-loops-simple-practical-example) – CBroe Jun 18 '18 at 14:08
  • By the time each function is being called, `i` is already set to 5 because the function has finished iterating. – Dexygen Jun 18 '18 at 14:10

1 Answers1

-1

This will produce the expected results.

 var myAlerts = [];
    
     for (var i = 0; i < 5; i++) {
         myAlerts.push(alert(i));
     }
    
       myAlerts[0](); // 5
       myAlerts[1](); // 5
       myAlerts[2](); // 5
       myAlerts[3](); // 5
       myAlerts[4](); 

By using the function inner() i is set to the same variable once it is called outside of your loop

let allows you to declare variables that are limited in scope to the block, statement, or expression on which it is used. This is unlike the var keyword, which defines a variable globally, or locally to an entire function regardless of block scope. An explanation of why the name "let" was chosen can be found here.

You can also use:

var myAlerts = [];
    
     for (let i = 0; i < 5; i++) {
        
         myAlerts.push(
         function inner(){
         alert(i)
         });
     }
    
       myAlerts[0](); // 5
       myAlerts[1](); // 5
       myAlerts[2](); // 5
       myAlerts[3](); // 5
       myAlerts[4]();
Josh Adams
  • 2,113
  • 2
  • 13
  • 25