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!
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!
This is a scope issue.
Inside your function you declared a new scope created.
Javascript hoists the variable decleration to the top function. Since the variable has no value it is undefined
.
The regular
variable created in the window does not exist in the function's scope.
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();
Your function re-defines the variable. It does not matter that this is below the console.log
call - it is always redefined for the full scope.
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.