0

Having the following for-loop:

for (var i = 0; i < 3; ++i) {
    console.log(i, p);
    var p;
    p = 42;
}

I was expecting the output to be:

0 undefined
0 undefined
0 undefined

But actually, the output is:

0 undefined
0 42
0 42

Since we're using var p (to redeclare p) next line, why isn't p undefined (always) in the console.log line?

Nuvi Pannu
  • 142
  • 9
  • 1
    http://stackoverflow.com/questions/500431/what-is-the-scope-of-variables-in-javascript, `there is no such thing as block level scope in js.` – Bharadwaj Jan 14 '16 at 05:57
  • @Bharadwaj Actually, in ES6 we have `let`. – Ionică Bizău Jan 14 '16 at 05:59
  • @IonicăBizău yes, the example which is given by OP suites part of that answer. – Bharadwaj Jan 14 '16 at 06:01
  • Are you asking this out of curiosity? Hoisting-related issues like this won't be an issue if you declare variables at the top as you most likely should. This particular problem could have been analyzed quite easily by stepping through your code with a debugger. You would have noticed after "executing" the second `var p;` that the value of `p` did not change. –  Jan 14 '16 at 06:01

1 Answers1

6

due to variable hoisting and your variable being function scoped rather than block scoped.

your for loop is translated to

var p;
for (var i = 0; i < 3; ++i) {
    console.log(i, p);
    p = 42;
}

which means first time p is accessed it is undefined,

Next time it is already initialized in the current function scope so it will be keep the initialized value.

gurvinder372
  • 66,980
  • 10
  • 72
  • 94
  • @IonicăBizău got it! w3schools -> bad :) I thought it was adequately explaining the point though – gurvinder372 Jan 14 '16 at 05:58
  • 1
    Actually, not exactly. The `var p;` is hoisted **above** the for loop (to the top of whatever function it resides in). –  Jan 14 '16 at 05:59