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 ?
-
developer.mozilla.org/en-US/docs/Glossary/HoistingAlexander Nied– Alexander Nied2017年02月26日 19:51:43 +00:00Commented Feb 26, 2017 at 19:51
4 Answers 4
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.
4 Comments
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
5 Comments
a to window which is the global object, then js search through hierarchy when you log a and find it on window object thus prints it. Since you have attached it to window object before calling it you don't get an exception, if you try otherwise you will get an exception.var change8 = function()
{
console.log(a);
console.log("End of function");
a = 10;
}
change8();
variable a is assigned undefined in the global context since JavaScript only hoists declarations, not initializations. Consider the same code as -
var a; // is = undefined
// in global context
var change8 = function()
{
console.log(a);
console.log("End of function");
a = 10;
}
change8();
Hence you'll get - Uncaught ReferenceError: a is not defined
This won't happen in 2nd code because you've explicitly declared your variable with var. Read more about hoisting here.
4 Comments
It is because,in the first snippet you are using 'a' before declaring it with var, thus 'a' belongs to the global scope, hence a reference error when you call your method because 'a' will only be in the global scope when the third line 'a = 10' was executed
In the second one 'a' is undefined because it is being used before it was declared using var, albeit it is still in the function's scope, when function is called during run-time, the first line 'console.log(a)' does not know 'a'