3

What is the difference between $one and var one in JavaScript? Because both works.

Example:

$one = 'hello word!';

var one = 'hello word!';

Working example: http://jsfiddle.net/rS9PR/

nmsdvid
  • 2,832
  • 2
  • 21
  • 21

8 Answers8

3

Nothing special about $; just another variable name. The use of "var" tells the interpreter that the variable has a local scope. WIthout var => global. ie; accessed from anywhere within the page.

Akshaya Shanbhogue
  • 1,438
  • 1
  • 13
  • 25
2

var one guarantees that the variable is set to local scope.

By default $one will assign the variable to global scope.

naivists
  • 32,681
  • 5
  • 61
  • 85
Don Albrecht
  • 1,222
  • 1
  • 8
  • 12
0

They're both variable names. In JavaScript the $ character is a valid character for a variable name. The var keyword just sets the scope on the variable names one in your example.

The $ has grown popular due to its use in different JavaScript libraries like jQuery, however it's a perfectly valid variable name character to use.

j08691
  • 204,283
  • 31
  • 260
  • 272
0

There is no difference, a variable name may contain a $ sign in it. You have just declared two different variables - $one and one.

upd: as per @yi_H comment- the two variables actually have different scopes. var keyword is used to declare a variable in current scope, however if you omit the var, it is defined in the global namespace

naivists
  • 32,681
  • 5
  • 61
  • 85
0

$one is defined in the global scope and will be visible in every function. var one is defined in its enclosing scope and is not visible outside.

Sahil Muthoo
  • 12,033
  • 2
  • 29
  • 38
0

Some people use "$" as a prefix to indicate jQuery object, like:

$text = $("#myTextElement");
Adaz
  • 1,627
  • 12
  • 14
0

Both names are valid identifiers, no difference. For the use of the var keyword see What is the purpose of the var keyword and when to use it (or omit it)?

Community
  • 1
  • 1
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
0

The $ in $one does not mean anything special. It is just another normal JavaScript variable. There is a convention among some developers where the prefix variables with $ to indicate that the variable holds a jQuery object. This is purely for style and readability and does not have a technical or syntactical impact.

When you omit the var from a declaration, a browser will attach the variable to the global object:

foo = 'bar';
alert(window.foo); // 'bar'

This has some pretty significant implications for any site that has more than a trivial amount of JavaScript (a category that has been growing rapidly over the last few years). The best practice is to always declare your variables with var to prevent a number of problems later on down the road.

See: What is the scope of variables in JavaScript? for more detail on variable scope.

Community
  • 1
  • 1
Jeff
  • 13,943
  • 11
  • 55
  • 103