Var Or No Var

Over the past few weeks, I have been working with Dojo Toolkit. Dojo is a powerful javascript toolkit. In javascript, the var keyword is used to declare (or create) variables, but it is not required. What’s the difference between these two statements:

a. var x =17;
b. x = 17;

Short answer. Statement (a) is to create variable as a local variable and statement (b) is to create variable in the global scope.

Long answer. A variable declared outside a function is a global variable and a variable declared by assignment inside a function is also a global variable. A variable declared with var inside a function
is a local variable, and is accessible only within that function.

For example, look at this code,

<script type="text/javascript">
x1 = 2;
var y1 = 2;

function setX2()
{
x2 = 3;
var y2 = 3;
}
</script>

Both x1 and y1 are global variable and are accessible everywhere in the global scope. But variable y2 is a local variable and x2 is global. Basically, to var or not to var is legal declaration. But it’s a good practice to use var because the variable is scoped to the correct execution context.

Leave a Reply