Nov

29

JavaScript - Variable Scoping

November 29, 2007 |

Variables should be kept local unless they are truly meant to be globals. Globals in Ajax can be the cause of problems that are difficult to debug.


For example, let’s say we want to write a function that creates a variable with the same name as the global variable and then use it locally, but not change the value of the global version.

Take a look an the following code example:

var fauxConstant = "123";
function badFunction() {
fauxConstant = "456";
}
function goodFunction() {
var fauxConstant = "456";
}
function testIt() {
alert(fauxConstant);
goodFunction();
alert(fauxConstant);
badFunction();
alert(fauxConstant);
}

badFunction, as the function name indicates, doesn’t work that way; it touches the global variable. In goodFunction, fauxConstant is declared locally, so it meets our expectation (see demo). If the intent were to actually have a global variable, then badFunction would be right, since it declares a global variable. In this example, we learned how the variables are scoped in JavaScript. Since there are no true constants in JavaScript, we can only fake it.

Another very important point to know is that any JavaScript variable declared inside a function without the var keyword will continue to exist outside that function. This can create difficult-to-bebug problems, so we must always use the var keyword unless
you specifically don’t need it.

In short, scope your variables locally and use the var keyword whenever possible.



Similar Posts

Comments

Name (required)

Email (required)

Website

Speak your mind

Sponsors




Links