-2

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);
Ran Eldan
  • 1,350
  • 11
  • 25
Muhammad Umer
  • 2,228
  • 2
  • 18
  • 17

4 Answers4

3

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".

Brian Ball
  • 12,268
  • 3
  • 40
  • 51
  • i just found that out that you can remove element using `element.remove();` Even though it is not listed in MDN reference. How unreliable. I can't find any information on it anymore. Like browser support. – Muhammad Umer Jul 09 '13 at 23:52
2

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.

Igor
  • 33,276
  • 14
  • 79
  • 112
0

They are different. If you do not use var, the variable always becomes global. Generally a bad idea.

Jeff Storey
  • 56,312
  • 72
  • 233
  • 406
0

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.

Pete Scott
  • 1,516
  • 10
  • 10