0

I am new to js and playing around with simple code. When I run the following code

var x=5;
function sum(){
   alert(x);
   var x=10;
   alert(x);
}
sum();

I am getting the alert as "undefined" and 10. But when I am running the following code,

var x=5;
function sum(){
   alert(x);
   x=10;
   alert(x);
}
sum();

I get the alerts as "5" and "10"

Can someone please explain what is happening?

Note: sorry for giving the same code twice. Have changed now :).

Thanks

4
  • 3
    I don't see a difference between the code snippets. I doubt they produce different outputs. Commented Jan 19, 2014 at 20:05
  • The both codes are same !!! Commented Jan 19, 2014 at 20:08
  • @Felix The code is different, the first example uses var x=10 in the function, while the second example doesn't. Commented Jan 20, 2014 at 13:07
  • @Metalskin: Now it is. It wasn't originally: stackoverflow.com/revisions/21221941/1 Commented Jan 20, 2014 at 17:23

1 Answer 1

2

The function you have provided is being affected by hoisting. When you declare a local variable it is hoisted to the top of the function, which leaves x undefined.

When the interpreter encounters the function it hoists the local variable x like:

var x=5;
function sum(){
   var x;
   alert(x); //local x is in scope and undefined
   x=10;
   alert(x);
}
sum();

In the second function you provide, no hoisting occurs because there is only one global variable x and the function alerts the global variable with its assigned value.

So the main difference between the two functions is that the first function uses two variables, a global variable and a local variable, while the second function uses one global variable. In the first function the local variable is hoisted to the top of the function causing it to output undefined for the first alert.

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

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.