Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript scope of variable

var change8 = function()
{
    console.log(a);
    console.log("End of function");
    a = 10;
}

change8();

Return Reference Error

var change8 = function()
{

    console.log(a);
    console.log("End of function");
    var a = 10;
}

change8();

Return Undefined

Why first code return Reference Error But Second code return undefined ?

like image 490
Murad Sofiyev Avatar asked Feb 26 '17 19:02

Murad Sofiyev


2 Answers

Javascript does something called hoisting, in which before it executes, it looks for var declarations and creates those variables. Since you used var a in the second, it creates the variable, but it isn't defined when used. In the first one, a doesn't exist until you create it, so it's a reference error.

like image 184
Jim Deville Avatar answered Oct 19 '22 11:10

Jim Deville


It is called variable hoisting. In JS declared variables are actually hoisted (moved up) to top of the scope they bound to, so in your case they are moved up to beginning of your function. In the second example a is treated as it is actually declared at the top of method before any of the assignments, then assigned to 10 later. So when you print a the variable is defined but its value is not assigned yet.

var change8 = function()
{
    var a;
    console.log(a);
    console.log("End of function");
    a = 10;
}

But in the first example a is not defined with var keyword so a will be treated as a global variable and won't be available until the assignment. Thus when it is called before the assignment the error will occur.

For understanding declaring variables with var keyword check the following answer

like image 42
cubbuk Avatar answered Oct 19 '22 10:10

cubbuk