Vera
Vera

Reputation: 283

Closure in for loop

I don't understand why this doesn't work:

function returnVerse(x){
   return function(x) {console.log(x);};
}

for(var x = 9; x>=0; x--){
   return returnVerse(x)();
}

I just get undefined as a result.

I've been inspiring myself from this: JavaScript closure inside loops – simple practical example

I understand that this is a scope issue, so I'm trying to create a closure, what am I not getting here?

Thanks in advance!

Upvotes: 0

Views: 38

Answers (1)

adeneo
adeneo

Reputation: 318162

The last function you're returning is the last one you're calling, and it's called with just (), meaning no arguments, yet you've specified an argument in the inner function, and it's undefined.

function returnVerse(x){
                 //  ^ outer argument

   return function(x) { 
                // ^ inner argument overwrites outer argument

       console.log(x); // undefined
   };

}

for(var x = 9; x>=0; x--){
   return returnVerse(x)();
                //    ↑  ^ innner argument not passed, "undefined"
                      outer argument   
}

Just don't specify an argument in the inner function, and the argument from the outer function will be in scope, and enclosed (closure)

function returnVerse(x){
   return function() {console.log(x);};
}

for(var x=9; x>=0; x--){
   returnVerse(x)();
}

Also, returning from the for loop makes little sense, and means it only runs once

Upvotes: 3

Related Questions