1

I have this code. I have written the value of 'i' (in comments) that I expected as the correct output. But the outputs/alerts are different.

Fiddle: http://jsfiddle.net/e2jbno4a/
Code:

var i = 10;

function outer() {
    alert(i); // 10
    var i = 5;
    alert(i); // 5
    function inner() {
        var i = 20;
    }
    inner();
    alert(i); // 5
    if (1) {
        var i = 30;
    }
    alert(i); // 5
    setTimout(function () {
        alert(i); // 5
    }, 100);
}

outer();

Can someone let me know the reason for the output? Or just the pointers where the specific concepts are explained?

Cerbrus
  • 70,800
  • 18
  • 132
  • 147
halkujabra
  • 2,844
  • 3
  • 25
  • 35
  • 1
    http://stackoverflow.com/questions/500431/what-is-the-scope-of-variables-in-javascript plus http://javascriptissexy.com/javascript-variable-scope-and-hoisting-explained/ – Cheery Sep 24 '14 at 06:54
  • The concepts are "lexical scope" and "hoisting" – elclanrs Sep 24 '14 at 06:55

1 Answers1

1

So, step by step:

var i = 10;

function outer() {
    alert(i); // undefined
    var i = 5;
    alert(i); // 5 (i now references the `i` in this function's scope.)
    function inner() {
        var i = 20; // (The `20` is only available in the scope of `inner`)
    }
    inner();
    alert(i); // 5 (So, this `i` still references the `var i = 5;` one)
    if (1) {
        var i = 30;
    }
    alert(i); // 30 (This one actually alerts `30`. There is no block scope in JS)
    setTimeout(function () {
        alert(i); // 5 (This will log `30`, you made a typo in the `setTimeout` call)
    }, 100);
}

outer();
Cerbrus
  • 70,800
  • 18
  • 132
  • 147
  • The answer is wrong. The first one would output undefined. See the example '8' of the duplicate question marked at top. – halkujabra Nov 08 '14 at 02:54