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

Roy
  • 15
  • 3

1 Answers1

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.

Kevin Bowersox
  • 93,289
  • 19
  • 159
  • 189