Balachandran
Balachandran

Reputation: 9637

Alert is not displaying as expected.!

I just tried to check the scope variation by using the following code, but the result is coming not in an expected way. Can anyone explain what's going on exactly behind this..?

var a = 10;

+ function () {
  a = 5;
  var a;
  alert("inline  " + a); //Expected undefined but it displayed as 5
}();

alert(a); //Expected 5 but it alerted 10

DEMO

Upvotes: 0

Views: 95

Answers (4)

Ryan
Ryan

Reputation: 14659

var hoisting

Because variable declarations (and declarations in general) are processed before any code is executed, declaring a variable anywhere in the code is equivalent to declaring it at the top. This also means that a variable can appear to be used before it's declare

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/var

The compiler understands your code as

var a;
a = 5;

Upvotes: 2

Bluewings
Bluewings

Reputation: 3488

var a = 10; // Global scope

+ function () {
    a = 5; // You are not using Var here .. so it is also a global scope
    var a; // Now you are mentioning your a is Var so scope is changed from global to this function
    alert("inline  " + a); // Printing 5 because you local scope a has value of 5.
}();

alert(a); // Printing 10 because of global scope a has value 10

Upvotes: -1

Ted
Ted

Reputation: 4166

when use "var a" you request global value of variable, use "window.a" to display it:

<script>
var a = 10;

+ function () {
    a = 5;
    var a;
    alert("inline  " + window.a); //Expected undefined but it displayed as 5
}();

</script>

Upvotes: 0

Chris Martin
Chris Martin

Reputation: 30756

The position of a var declaration within a function doesn't matter. These are entirely equivalent:

function () {
    var a;
    a = 5;
}

function () {
    a = 5;
    var a;
}

Upvotes: 2

Related Questions