Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are variables statically or dynamically "scoped" in javascript?

Or more specific to what I need:

If I call a function from within another function, is it going to pull the variable from within the calling function, or from the level above? Ex:

myVar=0;  function runMe(){     myVar = 10;     callMe(); }  function callMe(){    addMe = myVar+10; } 

What does myVar end up being if callMe() is called through runMe()?

like image 431
kylex Avatar asked Jun 06 '09 04:06

kylex


1 Answers

Jeff is right. Note that this is not actually a good test of static scoping (which JS does have). A better one would be:

myVar=0;  function runMe(){     var myVar = 10;     callMe(); }  function callMe(){    addMe = myVar+10; }  runMe(); alert(addMe); alert(myVar); 

In a statically scoped language (like JS), that alerts 10, and 0. The var myVar (local variable) in runMe shadows the global myVar in that function. However, it has no effect in callMe, so callMe uses the global myVar which is still at 0.

In a dynamically scoped language (unlike JS), callMe would inherit scope from runMe, so addMe would become 20. Note that myVar would still be 0 at the alert, because the alert does not inherit scope from either function.

like image 101
Matthew Flaschen Avatar answered Sep 28 '22 03:09

Matthew Flaschen