Friday, 16 August 2013

Variable scope in JavaScript

In JavaScript, variables can be declared in two ways, implicit declaration and explicit declaration.

var x;

This was an explicit declaration. The keyword var indicates the next symbol is a new identifier in the current scope.

x = 100;

This was an implicit declaration. There is no need to always explicitly define a variable before using it. A variable can be implicitly defined by simply referring to it without using the var keyword.

The second piece of code assigns the variable to the global scope, meaning it will be accessible by all blocks,  functions, and statements. In general, it is better to avoid implicit variables.

Now, let us come to Variable Scope. The scope of a variable refers to the portions of the program where it can be directly accessed. 

When variables are defined explicitly, they are accessible by all parts of the program, so they have global  scope . If a variable’s scope is limited to its function, it has local scope . The scope to which a variable  belongs is called its context.

<script type="text/javascript">
var os = "Windows";

function myOs()
{
  var os = "Linux";
  document.write(os + "<br />");
}

myOs();
document.write(os + "<br />");
</script>


The output of the above code is:

Linux
Windows

The output above is a matter of variable scoping. When the function myOs() is called, the interpreter first checks whether there is a variable 'os' defined in the local scope (the function context). If it doesn’t find it, it moves up the hierarchy of scopes until it reaches the global scope (the window object in a browser), checking along the way. If instead it actually does find this variable declared in the local scope, it uses that one instead of any others of the same name that might appear higher up in the scope chain.

In the above example, since a variable 'os' is declared within the function, it is used and the global variable 'os' remains untouched.

<script type="text/javascript">
var os = "Windows";

function myOs()
{
  os = "Linux";  //no var here
  document.write(os + "<br />");
}

myOs();
document.write(os + "<br />");
</script>


The output of the above code is:

Linux
Linux

In the last code snippet, the variable 'os' inside the function myOs() is not declared explicitly in the local scope. So, the global scope is used thus reassigning the global variable 'os'.


document.write() overwrites the entire page

document.write is a function which basically outputs whatever is given to it. But sometimes, improper usage may overwrite the entire page d...