-2

Why do we use the keyword: 'var' when the code works very well without using it.

JavaScript:

window.onload = compare;


function compare() {
     cool = "45";     
     alert(cool +1)    // I can alert it or do anything else without using 'var'
}

Here, a string is stored in 'cool' and I can do anything with it as if it was a variable. Isn't it a variable here? If it is, then what difference does the keyword 'var' makes?

Navneet Saini
  • 934
  • 4
  • 16
  • 33
  • 4
    Same as: http://stackoverflow.com/questions/1470488/difference-between-using-var-and-not-using-var-in-javascript – lurker May 24 '13 at 02:50

1 Answers1

1

When you omit the var keyword you're doing an "implicit declaration". This is not recommended as this type of declaration has global scope. If you want a locally scoped variable you need to use the var keyword.

Dane O'Connor
  • 75,180
  • 37
  • 119
  • 173