2

I tried following code:

var a = 5;

function x() {
  console.log(a);
}

x();

It runs as expected and prints 5.

But i changed the code so the global variable a will be overwrite as follows:

var a = 5;

function x() {
  console.log(a);
  var a = 1;
}

x();

It prints undefined. It doesn't make sense for me since the overwrite should be happened right after console.log(a). So what is the problem?

2 Answers 2

5

This is happening because your second a variable is being 'hoisted' to the top of the function and it hides the first a. What is actually happening is this:

var a = 5;

function x() {
  var a;
  console.log(a);
  a = 1;
}

x();

Here is an article on hoisting from adequately good for further reading on the subject.

Sign up to request clarification or add additional context in comments.

5 Comments

When variable gets hoisted its value also doesnt get hoisted? For example why wasnt the expression var a =1; hoisted. And why just var a;
The value isn't hoisted because you set it at that position, consider an example of initialising a variable to be equal to the contents of another variable which wouldn't have been filled at the start of the function. Setting it to 1 would break the flow of the program.
Wew. It is still hard for me to accept the scoping & hoisting concept. I come from java and i think javascript scoping is a little bit strange. Anyway thanks for the answer and the article.
jslint.com actually complains if you don't define all of a function's variables at the beginning, the thinking behind that is you wouldn't run into these sort of issues that would be very difficult to debug.
Cool. So for the best practice, all variables inside a function should be declared at the top. I got it.
0
var a = 5;

function x() {
    var a = 1;
console.log(a);
}

x();

you need to initalize variable a before console.log();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.