Wednesday, May 23, 2012

LEAKING GLOBAL VARIABLE IN JAVASCRIPT

Hi Friends ,

This post is about a very common mistake that is made by the JS programmers who are caught unaware of what they are trying to accomplish.

The most common mistake with a java script variable  is sometimes programmers use them as global variables and as such their values persist for the entire program and does not work the way it is supposed to .


Yesterday, while i was working with a piece of JS code , i encountered this problem .

I had this piece of code :

function FUNC()
{
   K = 100;
}

FUNC();

console.log("K is :" +K); // O/P : 100

But the expected output is undefined since the variable 'K' is a local variable and hence must not be visible else where except the method where it is used .

This is the screen shot that came up in my console :

Now this is called accidental leaking of global variable .
I wanted to have my variable K as a local variable but i have used it as a global variable.
Hence , all this fuss .

So , the important thing that needs to be done is, if we intend to use a variable as a local variable , then we must use the 'var' statement .


function FUNC()
{
  var  K = 100;

}


FUNC();



console.log("K is :" +K);

As a result, this is what i got :


And this is the correct and expected result.

This small mistake messed up my application big time . So remember to use VAR in such cases.

Goodbye,

Have a good day .



No comments:

Post a Comment