1

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!

Rohit
  • 6,941
  • 17
  • 58
  • 102
  • 3
    Read about `variable hoisting`. Execution will be like `function prison() { var regular; console.log(regular); variable='VALUE'; }` – Rayon Mar 23 '16 at 12:34

4 Answers4

2

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.

Saar Kuriel
  • 572
  • 4
  • 16
1
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();
Gibbs
  • 21,904
  • 13
  • 74
  • 138
1

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.

Lucero
  • 59,176
  • 9
  • 122
  • 152
1

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.

https://jsfiddle.net/Ldbhtv3v/

kemiller2002
  • 113,795
  • 27
  • 197
  • 251