-6

This is an Extension to the Question. I have tried below code to understand JavaScript scope

var a = function(){
   var aa = 10;
   var x = 13;            
   b = function(){ c = function(){ alert(aa); }; };       
};
a();
b();
c();
alert(typeof x);​ // Undefined
alert(x);​ // Returned me 13.

My query is I have declared variable with var​ inside a global function. As per my understanding x should be local. But it is not acting in that way. Someone please clear my doubt... Please check this fiddle.

11
  • 3
    x is scoped to the function assigned to a. That last alert never actually appears - you get a SyntaxError because x is not defined. Commented Jul 18, 2012 at 13:45
  • 1
    There is no way you will get 13, you will get 'x is not defined' because x is scoped inside a. Maybe you have set x = 13 somewhere in the global scope also. Commented Jul 18, 2012 at 13:46
  • 1
    There is no possible way that that alerts "13". Commented Jul 18, 2012 at 13:46
  • 1
    If you're testing your code in a developer console, you need to be sure to refresh the page to clear any previously set x globals. Commented Jul 18, 2012 at 13:47
  • 1
    @SoI - The fiddle you are linking to is not alerting "13". It alerts "10" because you are alerting the value of aa inside the function assigned to c. Commented Jul 18, 2012 at 13:48

1 Answer 1

3

The following will happen:

An alert popping up, displaying the value of aa = 10

An alert popping up, saying undefined since you are trying to access a variable x from the global scope, however x is only defined in the scope of function a.

An error in your console, ReferenceError: x is not defined.

So, as you assume, x indeed is private, you can't access it globally.

You probably messed something up giving you wrong results.

What might have been the case is that you forgot the var in front of the x which suddenly makes it a member of the global object instead of being restricted to the function-scope. In this case, the last alert would give you 13. However the alert(typeof x) would give you "number" then.

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.