1

Consider the following snippet in javascript. The output of the following snippet is : The first alert shows "undefined" whereas the second alert shows "2"

var a = 1;
function test(){
    alert(a);
    var a = 2;
    alert(a);
}
test();

Why does the first alert not show the value of the global variable a which is 1?

0

2 Answers 2

4

What you're seeing is variable hoisting in action.

This is how the code is being interpreted:

function test(){
    var a; // a === undefined
    alert(a);
    a = 2;
    alert(a);
}
Sign up to request clarification or add additional context in comments.

Comments

2

It is called "hoisting" in JavaScript. Your function is automatically transformed into this one:

var a = 1;
function test() {
  var a;
  alert(a);
  a = 2;
  alert(a);
}
test();

Nice read about that: http://net.tutsplus.com/tutorials/javascript-ajax/quick-tip-javascript-hoisting-explained/

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.