1

I want to know why alert x is a 'undifined', why is not 10.

var x = 10;
function foo(){
    alert("foo---" + x);
};
(function(){
   alert("this === window---" + (this === window));
   alert("window.x---" + window.x);
   alert("this.x---" + this.x)
   alert("x---" + x); //undifined ? why
   var x = 20;
   foo.call(); //10
})();
Taven_lxc
  • 41
  • 2
  • Has to do with scope see here: http://stackoverflow.com/questions/500431/what-is-the-scope-of-variables-in-javascript –  May 13 '16 at 13:01

2 Answers2

0
var x = 10;
function foo(){
    alert("foo---" + x);
};
(function(){
   alert("this === window---" + (this === window));
   alert("window.x---" + window.x);
   alert("this.x---" + this.x)
   alert("x---" + x); //undifined ? why
  // var x = 20; // Comment this variable 
   foo.call(); //10
})();

when you define variable name x and assign some value then this function is call and in all other alert you define as like window, this but when you give alert only x then in jquery it will not able to which x you want alert and in jquery window.x it will take that first x value same in first function "foo" but in second function where x is define after alert so alert is undefined

if you give alert on x then it will give undefined because you also define same variable after alert in that function

Vishal
  • 21
  • 4
0

This caused because of a feature of javascript called variable hoisting link.

So when the interpreter is interpreting your code, this occurs at runtime.

var x = 10;
function foo(){
 alert("foo---" + x);
};
(function(){
  var x;
  alert("this === window---" + (this === window));
  alert("window.x---" + window.x);
  alert("this.x---" + this.x)
  alert("x---" + x); //undifined ? why
  x = 20;
  foo.call(); //10
 })();

As you can see from above, the variable declaration var x is moved to the top leaving the assignment. Therefore, when you call alert("x---" + x) the variable x is not yet defined.

Eni Arinde
  • 555
  • 5
  • 6