0

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

seems stupid question but just curious.

num = "hello";

alert(num);

why is this possible I didnt initialize the num variable here.

num = "hello";

instead of

var num = "hello";
Community
  • 1
  • 1
user1393669
  • 43
  • 1
  • 2
  • 1
    Please read some documentation: https://developer.mozilla.org/en/JavaScript/Reference/Statements/var and please search before you ask a new question. – Felix Kling May 14 '12 at 11:59

2 Answers2

6

var means "Scope this variable to this function" not "Make it possible to use this variable".

If you leave var off then it will use the variable in the next scope up from the function. If that scope doesn't have the var yourVar then it will keep going up the scope chain until it becomes a global and dangles off the window object (assuming a browser or another JS environment in which the default object is window).

(This changes in strict mode, which you are presumably not using.)

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • Note that in ECMAScript 5 Strict Mode this kind of assignment is disallowed – Ian Gregory May 14 '12 at 12:00
  • so num="hello" is a variable string with hello string? – user1393669 May 14 '12 at 12:00
  • 1
    @user1393669: It's not complicated. All that `var` does is changing the scope of the variable. Nothing else. Apart from scope, `num = 5` is equivalent to `var num = 5` (again, in *non*-strict mode). Also have a look at the question I linked to, it contains further information. – Felix Kling May 14 '12 at 12:02
1

Without the var keyword the variable is created at the global scope (in browsers under window).

If you add the var you just assign the variable to the current scope, which in most cases will be a function scope.

In general it will be better to use a function scope in order to not pollute the global scope and prevent conflicts between multiple variables of the same name!

Sirko
  • 72,589
  • 19
  • 149
  • 183