Dangers of missing var keyword in Javascript

Javascript is wonderful, but yes, it does have many aspects which if left ignored then can have bad implications. One such thing is the keyword ‘var’. var is used to declare variables in Javascript using following syntax:

var variableName;


var variableName = variableValue;

var keyword should be used whenever you create a new variable and it should be particularly used when variables are being declared inside a function.

If, when declaring a variable inside a function, use of var is omitted then such a variable becomes global in scope by default. Yes, you read it right – not using var when declaring a variable will make that variable global!

Once a variable becomes global, its kind of available to all and modifiable from any source. Such a thing can have terrible consequences and can adversely affect results expected from your script.

Such a stuff also makes a script difficult to debug, particularly so, if the script is too large.

Note that everytime omission of var is not intentional. As Javascript does not indicate whenever a variable becomes global, thus, worse is the case when var is omitted by mistake, as this further complicates the complete script execution and debugging.

Therefore, as a good practice of writing code in Javascript, it is always advised to ensure that var is always used whenever declaring a variable.


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s