-1

Why does the code output the result as 10 for console.log(i).why didnt it print 1,2..10?

for(i=0;i<10;i++){

    function abc(callback){

    console.log(i); 
    setTimeout(callback,5000);  
    }

}

abc(function (){console.log(i)})
  • 2
    Youre overriding abc 10 times. Just saying – Jonas Wilms Jan 10 '17 at 17:40
  • @Jonasw In order to achieve what OP thinks this code should do there should be a closure :-) – strah Jan 10 '17 at 17:47
  • @strah yep. Ive included it into my answer. But still wrong duplicate marking – Jonas Wilms Jan 10 '17 at 17:48
  • Same reason as in [JavaScript closure inside loops – simple practical example](https://stackoverflow.com/questions/750486/javascript-closure-inside-loops-simple-practical-example), but this is even weirder because it creates function declarations inside a loop, but doesn't call the function until after the loop. – Felix Kling Jan 10 '17 at 17:49
  • The tl;dr is: There is only a single variable `i` in your program. A variable can only have a single value at a time. – Felix Kling Jan 10 '17 at 17:52
  • Possible duplicate of [JavaScript closure inside loops – simple practical example](http://stackoverflow.com/questions/750486/javascript-closure-inside-loops-simple-practical-example) – Andy Ray Jan 10 '17 at 17:54
  • if you are coming from another programming language that represents scope with curly braces, that's not how JavaScript works, your code being executed at global scope, after the for loop you end up with one single variable `i`. might be helpful for you to understand the issue you are having. http://stackoverflow.com/questions/500431/what-is-the-scope-of-variables-in-javascript – azs06 Jan 10 '17 at 18:02

2 Answers2

1

May have a look at hoisting and function scoping. Your code will mainly look like this (in the parsers view)

for(i=0;i<10;i++){}
//i=1
//i=2
//i=3
//...
//i=10
function abc(callback){ 
setTimeout(callback,5000); 
} 

abc(function (){console.log(i)})//i is 10 :0

What i think you want:

    function abc(callback){ 
      for(var i=0;i<10;i++){
        (function(i){//see 'closures in for loops' on SO
          setTimeout(callback,5000); 
        })(i);
      } 
   }

  abc(()=>{alert(i)});//hehe
Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151
0

It is because i has a global scope and after the for loop, when you call the function, the value of i is 10.

strah
  • 6,702
  • 4
  • 33
  • 45
Aditya K
  • 466
  • 4
  • 8