Why does below JS code prints'undefined' ? Can some one please explain how JS really works ?
var regular = 'regular is assigned';
function prison() {
console.log(regular);
var regular;
}
prison();
Thanks!
var regular = 'regular is assigned';
function prison() {
console.log(regular);
//var regular;
}
prison();
Cause is the commented out keyword.
Javascript move all the variables to the top before executing any code.
In your case, local variable regular is printed instead first declared regular variable.. Documentation
So Your code is executed as follows
var regular = 'regular is assigned';
function prison() {
var regular;//Moved here as per JS Scope
console.log(regular);//Hence it is undefined
}
prison();
What you are seeing is hoisting. Even though you declared the variable after you used it, the variable declaration gets moved to the top of the function. As you would expect local variable override global variables and so it's undefined.
Take the following example:
function hoist(num){
message = "I'm not five"
if(num === 5)
{
var message = "I am five";
}
console.log(message);
}
hoist(5);
console.log(message);
The conosle.log after calling the function throws an exception. Without hoisting, the first assignment to the message variable would create a global variable, but it doesn't. The variable declaration is moved to the top making the assignment to message occur on the local variable and not create a global one.
variable hoisting. Execution will be likefunction prison() { var regular; console.log(regular); variable='VALUE'; }