0

Please, can you explain me why the following lines of code, print letter E many times, instead of A,B,C,D,E ?

I don't understand what's going on. I've tried many things, but i get either errors, or undefined values.

var values = ['A','B','C','D','E'];
var myfunctions = [];

for (var i = 0;i < values.length;i++){
    var letter = values[i];
    console.log(letter);
    myfunctions.push( function(){
        console.log(letter);
    });

};

for (var j = 0;j < values.length;j++){
    myfunctions[j]();
};

http://jsfiddle.net/jvrLnsur/

JGutierrezC
  • 4,398
  • 5
  • 25
  • 42
  • 1
    You only have one variable called `letter` and it has the value `'E` when you call your functions. If you want each function to have its own `letter` you could create an IIFE that scopes `letter` and returns a new function: http://jsfiddle.net/jvrLnsur/2/ – Paul Jun 12 '15 at 00:16
  • What is an IIFE and why that happens? Shouldn't it store the current value of for loop, for every run? – JGutierrezC Jun 12 '15 at 02:14
  • An [IIFE](http://en.wikipedia.org/wiki/Immediately-invoked_function_expression) is a function expression that is executed immediately after the expression is evaluated. Perhaps I should've linked to this as a duplicate instead: http://stackoverflow.com/questions/750486/javascript-closure-inside-loops-simple-practical-example – Paul Jun 12 '15 at 02:35
  • 1
    You have a function that looks like `function(){ console.log(letter); }`, and when you execute that function `letter` has the value `'E'`. Here is a similar example, with the loop unrolled and a few simplifications: http://jsfiddle.net/yj72ymxv/ . It should be obvious that it prints `C C` not `A B`. You wouldn't expect that to print `A B`, because when the functions are called `letter === 'C'`. What matters is the value of `letter` when the statement `console.log( letter )` executes, not the value when the functions are defined. – Paul Jun 12 '15 at 02:43
  • I hope that helps clear things up. – Paul Jun 12 '15 at 02:47

0 Answers0