10

Possible Duplicate:
Difference between using var and not using var in JavaScript

What is the difference between using var keyword in java script & without using it for a variable?

For example:

var x = 14;

And x = 14;

Are these same or when we declare var x, its a local variable & when it doesn't have var keyword, then its global?

Thanks!

Community
  • 1
  • 1
Mike
  • 7,606
  • 25
  • 65
  • 82

2 Answers2

13

If var keyword is used within a function or other non-global scope then that variable's scope is not global .

If var keyword is not used before a variable name, then that variable's scope is global .

AsgarAli
  • 2,201
  • 1
  • 20
  • 32
mrk
  • 4,999
  • 3
  • 27
  • 42
  • I'd like to add that this wasn't made a syntax error to prevent new comers of the language from abandoning it. Trivial programs will be ok if you accidentally make a global var and manipulate it throughout the function. – t3dodson Jun 03 '15 at 07:42
  • @TomDDD right, that's not a syntax error but possibly a very confusing logical error. Depends on the actual use. It's the understanding of what happens when leave off `var` that is important and, IMO, what was being asked here – mrk Jun 03 '15 at 14:48
  • I totally agree with you. I was just adding the history of why this "feature" exists. There is never a reason to omit. Even when creating global variables. Make a global variable called `global` and assign things to it like a normal assignment – t3dodson Jun 03 '15 at 17:05
  • Is this true even when that x=2 without var is in some specific function? Would that be global too as a whole – Sana Ahmed Sep 18 '18 at 06:29
3

Variables declared outside a function become GLOBAL, and all scripts and functions on the web page can access it.

Global variables are destroyed when you close the page.

If you declare a variable, without using "var", the variable always becomes GLOBAL.

JAiro
  • 5,914
  • 2
  • 22
  • 21