4

Using node-mysql I have the following code:

for (var i = 0; i < 10; i++) {
    connection.query('select 1', function(err, rows) {
        console.log('#' + i);
    });
}

I expected the result to be #0, #1, ..., #9 but the actual result is #10 printed 10 times. It is obvious it is printing the value of i at the moment of the callback's execution instead of the callback creation. How can I implement my desired result?

SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
ibrabeicker
  • 1,786
  • 2
  • 19
  • 31
  • `for (var i=0; i<10; ++i) (function(i){connection.query('select 1', function(err, rows){console.log('#' + i)})})(i);` – Jared Smith Dec 27 '17 at 18:41

1 Answers1

5

Declare i with let:

var i => let i

for (let i = 0; i < 10; i++) {
David Vicente
  • 3,091
  • 1
  • 17
  • 27
  • 1
    Can you explain why this makes a difference? – jordanm Dec 27 '17 at 18:28
  • 1
    The difference is scoping. var is scoped to the nearest function block and let is scoped to the nearest enclosing block, which can be smaller than a function block. Both are global if outside any block. https://stackoverflow.com/questions/762011/whats-the-difference-between-using-let-and-var-to-declare-a-variable – David Vicente Dec 27 '17 at 18:29
  • 2
    That won't actually help; you still only have one variable. – SLaks Dec 27 '17 at 18:35
  • But with let it only scopes the loop block. So I think it is what he was looking for – David Vicente Dec 27 '17 at 18:46
  • 1
    @SLaks: JS defines `let` variables declared in the head of a `for` statement, in the loop's body. There's no intermediate scope created, like you'd find in some languages. –  Dec 27 '17 at 18:46