sowiq
sowiq

Reputation: 422

Javascript function and variables scope

Quick question, because one thing confused me today. Below is piece of JavaScript code:

var a = [1, 2, 3, 4];

function init() {

    console.log(a);

    if (false) {
        var a = [9, 8, 7];
    }
}

init();

This simple code logs "undefined" in JS console. I found that the reason for this is 5th line:

var a = [9, 8, 7];

Without word var inside that condition, it will log correct result [1, 2, 3, 4].

My question here is: why JavaScript interpreter takes into consideration piece of code which never will be executed?

Example to play with: http://jsfiddle.net/5DPCz/

Upvotes: 0

Views: 35

Answers (2)

Tim
Tim

Reputation: 2450

Your example is equivalent to

var a = [1, 2, 3, 4];

function init() {
    var a;
    console.log(a);

    if (false) {
        a = [9, 8, 7];
    }
}

init();

Now you can see why it prints undefined. The a that is local to the function has not been assigned a value at that point yet.

If you remove the var you turn it into

var a = [1, 2, 3, 4];

function init() {
    console.log(a);

    if (false) {
        a = [9, 8, 7];
    }
}

init();

So a in the function now refers to a from the global scope.

Upvotes: 0

user229044
user229044

Reputation: 239551

You cannot declare variables in the middle of a function in JavaScript; all variables have function scope. Effectively, variable declarations are "hoisted" to the top of the function. Your function will only ever have access to the local variable a regardless of where in the function it is declared.

This is why JSLint (and most other linting tools) will advise you to move all variable declarations to the top of the function; that's where they're effectively written anyways.

Regardless of where in your function you place your var a, your code effectively executes this way:

var a = [1, 2, 3, 4];

function init() {
    var a;

    console.log(a);

    if (false) {
        a = [9, 8, 7];
    }
}

init();

Upvotes: 4

Related Questions