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 ?
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With