I mean the browser does it very properly
I don't approve it, because putting var makes reading the code very easy.
if I do this will it work?
a=2;
console.log(a);
I mean the browser does it very properly
I don't approve it, because putting var makes reading the code very easy.
if I do this will it work?
a=2;
console.log(a);
If you don't use the var
keyword, then the variable will be global. If you are declaring the variable to be global, then it is not needed.
It is generally considered bad practice to declare variables to be global. When you do so, it is often referred to as "polluting the global namespace".
Yes, the drawback is that it becomes a "global" variable (a property of window
), and if it's (unintentionally) used later, this may cause issues. If you have particularly large objects, then it may cause memory issues as well, unless you explicitly manage them.
As good code practice, it's typically best to constrain variables to the tightest scope possible for best readability.
They are different. If you do not use var
, the variable always becomes global. Generally a bad idea.
when not using var, javascript will assume the variable is in the global namespace.
Thus:
a = 'abc';
function x() { a = 'def'; }
will overwrite "a", even though it is being run from inside a function. Sometimes that's what you want, but sometimes it isn't.
a = 'abc';
function x() { var a = 'def'; }
THAT will prevent "a" from being overwritten (the "a" inside of the function is a different variable).
In other words, always use var when declaring a new variable and you won't accidently overwrite existing variables.