Variables in JavaScript and the var keyword

JavaScript has a feature that it is not compulsory to declare variables. As long as you don't use functions for writing code, this might be a convenience. However, as you start writing serious code in JavaScript and start using function, then it becomes important to understand the implications of this feature.

One implication is that unplanned use of variables inside functions without using the 'var' keyword places them inside the global scope instead of the windows scope. Code with all variables in global scope can have unwanted and unexpected side effects e.g. unintentionally overwriting an important global variable with a new value inside a function. This can be prevented by using the 'var' keyword for declaring the variables explicitly to keep them in the local scope.

Another weird feature of JavaScript is that it is allowed to re-declare a variable using the 'var' keyword and not considered a mistake. Inside a function, all the declarations of the same variable in JavaScript are treated as if it is a single declaration for that variable. I don't know of any other programming language that allows this. This was done to keep JavaScript simple for the novices. However, to avoid confusion and for the sake of readability, declaring all the local variables in JavaScript with 'var' keyword right at the start of the function is a good habit worth cultivating - you may recall that C won't compile if it is done in any other way. This also conditions you to write your code in a planned manner.

You can also declare variables with 'var' keyword in the global scope for the sake of consistency and readability so that your code is easier to understand and maintain.

One more thing - you cannot delete the variables created with 'var' keyword using the 'delete' operator. On the other hand, variables created without the 'var' keyword can be deleted with 'delete' operator.