Monday, June 20, 2011

Rule of Thumb : Declaring variables

"var" is the keyword used for declaring a variable. It lets you define an number, string , datetime value or an object or function.


Example(s):

var a1;
var a2 = 10;
var a3 = 1.23;
var a4 = "hello world";
var a5 = true;
var a6 = {prop1:'some values', prop2: 'some other values', prop3 : true} ;


var a7 = new Object();
var fn1 = function() { return "hello world"};


what happens if we use in the following way
 ax=10;

Well well, the above line adds a variable name "ax" in the global scope. At a glance it can pretend to be an trivial mistake, but that is not the case, rather it is of very high importance, since such statement can make the global scope dirty and making the code fault prone and fragile.

Lets take another example for more clarity:


function sayHello(username){
  strn = "Hello " + username;
  return strn;
};


console.log( sayHello( 'kris' ) );
console.log( strn ); //=> "hello kris"

*console is a class available in almost all browsers but not in all browser for development/debugging purpose.

The above javascript function "sayHello" adds a variable "strn" to the global scope.

The following change of declaring the variable with "var" will make sure that the variable "strn" is applicable to local scope only.

Examples: 
function sayHello(username){
  var strn = "Hello " + username;
  return strn;
};


console.log( sayHello( 'kris' ) );
console.log( strn ); //=> undefined
Hence the scope of  local variable is managed correctly.

So we conclude this post with the memoirs of golden rule of variable declaration in javascript.

No comments:

Post a Comment

There was an error in this gadget