Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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'?

like image 278
geopl Avatar asked Mar 26 '14 14:03

geopl


People also ask

What is the incorrect scope of variable in JavaScript?

Any variable that you declare inside a function is said to have Local Scope. You can access a local variable can within a function. If you try to access any variable defined inside a function from outside or another function, it throws an error.

Which two factors determine the scope of a variable in JavaScript?

A function in JavaScript defines a scope for variables declared using var , let and const . Any variable declared within that function is only accessible from that function and any nested functions. A code block ( if , for , etc.) defines a scope only for variables declared with the let and const keywords.

What is $scope in JavaScript?

Scope in JavaScript refers to the current context of code, which determines the accessibility of variables to JavaScript. The two types of scope are local and global: Global variables are those declared outside of a block. Local variables are those declared inside of a block.

What are the three types of scopes in JavaScript?

JavaScript has 3 types of scope: Block scope. Function scope. Global scope.


1 Answers

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.

like image 165
thefourtheye Avatar answered Sep 25 '22 21:09

thefourtheye