0

I've been using javascript & jQuery for a month. But I am still not getting what is the difference between using var variable and without declaring var.

var data = 10;
data = 10;

What is difference between the two statements above? And why? Please explain to me in detail.

JohnIdol
  • 48,899
  • 61
  • 158
  • 242
Gunjan Patel
  • 2,342
  • 4
  • 24
  • 45
  • 1
    first you declare a variable and assign value. In second you just assign new value to already existing variable which holds data – virendrao Mar 02 '15 at 09:35
  • in the second line data = 10; you are just reassigning data variable to hold the value 10.. – Lucky Mar 02 '15 at 09:36
  • Have you tried to google this? [Using the title of your question returns quite a number of relevant results.](https://www.google.com/search?q=In+javascript+why+we+use+var+for+declaring+variable%3F&ie=utf-8&oe=utf-8&gws_rd=cr&ei=Zi_0VMX_Dcr3UInSgugO) – Sascha Wolf Mar 02 '15 at 09:37
  • @higunjan This link may helps for this kind of questions: http://shamansir.github.io/JavaScript-Garden/en/ – S Panfilov Mar 02 '15 at 09:43

3 Answers3

2

Declaring a variable without var keyword will make it global, meaning it will be available for all the functions and object in the module it was declared . needless to say, this cause a lot of troubles and should be avoided.

Declaring a variable with var keyword will limit the scope of the variable to the scope it was declared in.

David Haim
  • 25,446
  • 3
  • 44
  • 78
2

The difference is that with the "var" keyword you declare the variable in the current scope. On top level scope (window) you won't notice much difference of course. I think an example makes that clearer:

// declares "data" on window scope
var data = 10;

function foo() {
  // overwrites the "global" data to 20.
  data = 20;

  // declares a scoped variable "scopedData" inside of this function and sets it to 25
  var scopedData = 25;

  alert(data);
  alert(scopedData);
}
// scoped data is undefined here because it was scoped to the function.
alert(scopedData);

Also note that all "var" declarations need to be unique inside of their scope and that the execution is moved up to be beginning of the scope. See this article for more information: http://www.adequatelygood.com/JavaScript-Scoping-and-Hoisting.html

ChristianM
  • 1,793
  • 12
  • 23
0

We use it because it is a language construct to improve readability, it stems from 'older' dynamically typed languages (such as Beginners All Symbolic Instruction Code, aka basic. )

var is similar to the basic 'dim' statement from a syntax perspective.

It is considered good practice to use it due to the fact that if it is omitted within a scope it will propagate to the global scope (although there is absolutely no effect if used in the global scope. )

Damian Nikodem
  • 1,324
  • 10
  • 26