Tuesday, January 10, 2012

At var with JavaScript

What does the var keyword do in javascript? Well, it's a little known fact that it defines the scope of the variable. Take for instance this js snippet.

<script>
var i = 10;
fun();
function fun()
{
 j = 20;
 var k = 30;
 alert ('in fun scope: ' + i + ' ' + j + ' ' + k);
};
alert ('in global scope: ' + i + ' ' + j + ' ' + k);
</script>

The second alert statement will give a js error since (because of the var keyword next to it) k is defined only within the function. j, on the other hand, retains global scope since we didnt declare it with var.

Reference: http://www.hunlock.com/blogs/Functional_Javascript#quickIDX3

No comments:

Post a Comment