geopl
geopl

Reputation: 209

JavaScript unexpected variable scope behavior

I would to know something about a scope behavior.

For example I have a variable and a function:

var test = 1;
function scope(){
    alert(test);
    test=2;
}
scope();
alert(test);

This will display 1 and 2. No problem. But if I do this:

var test = 1;
function scope(){
    alert(test);
    var test = 2;
}
scope();
alert(test);

This will display 'undefined' and '1'. Why does the variable come out as 'undefined'?

Upvotes: 5

Views: 236

Answers (2)

thefourtheye
thefourtheye

Reputation: 239443

In the first case, you havn't created any local variable but accessed the test defined from the global scope.

var test = 1;        // Global Test - GT

function scope() {
    alert(test);     // Accesses GT
    test = 2;        // Assigns to GT
}
scope();
alert(test);         // Accesses GT

But in the second case, you are creating a new variable, but accessing it before assigning a value it. By default, all the unassigned variables will have undefined.

In JavaScript, variables are scoped to the functions in which they are declared. So, when you use var variable_name in a function, you are creating new variable and it will be accessible to all parts of the function. Also, you are creating a variable with the same name as the global variable. When JavaScript looks up for the variable test, it will first search the local scope of the function and it will be found there. So, local test variable will be used.

alert(test);     // value will be `undefined` till a value is assigned.
var test = 2;    // Declared a new variable and assigned value here

This behavior is called variable hoisting.

Upvotes: 3

Royi Namir
Royi Namir

Reputation: 148524

Hoisting :

your second code :

var test = 1;
function scope(){
    alert(test);
    var test = 2;
}
scope();
alert(test);

is actually :

var test = 1;
function scope(){
    var test;
    alert(test);
    test = 2;
}
scope();
alert(test);

same catch here :

var test = 1;
function scope(){
    if (typeof test =="undefined") alert(2)

    var test = 2;
}
scope();
alert(test);

Upvotes: 2

Related Questions