Are variables statically or dynamically "scoped" in javascript? Are variables statically or dynamically "scoped" in javascript? javascript javascript

Are variables statically or dynamically "scoped" in javascript?


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.


if your next line is callMe();, then addMe will be 10, and myVar will be 0.

if your next line is runMe();, then addMe will be 20, and myVar will be 10.

Forgive me for asking - what does this have to do with static/dynamic binding? Isn't myVar simply a global variable, and won't the procedural code (unwrap everything onto the call stack) determine the values?


Variables are statically scoped in JavaScript (dynamic scoping is really a pretty messy business: you can read more about it on Wikipedia).

In your case though, you're using a global variable, so all functions will access that same variable. Matthew Flaschen's reply shows how you can change it so the second myVar is actually a different variable.

This Page explains how to declare global vs. local variables in JavaScript, in case you're not too familiar with it. It's different from the way most scripting languages do it. (In summary: the "var" keyword makes a variable local if declared inside a function, otherwise the variable is global.)