0

What's the difference between:

var add = "Hello";

and

$add = "Hello";

Could you tell me the difference between the two solutions without saying that one of them does not require jQuery ?

Thanks.

Tom
  • 1
  • 1
  • 1
    neither one requires jquery. The one with the `$variable` is just a naming convention some use to indicate it's might be a jquery object. I say might because really a variable can contain anything in javascript and can change. There is no special context to `$` in javascript. Even in jquery `$` is just a variable that could be redefined at a latter date if you chose to. – scrappedcola Sep 19 '14 at 19:11
  • 2
    Neither has anything to do with jQuery. `$add` is just another name. The difference is that the version with `var` is local to the current scope (function, etc.), while the other will be global. – Paul Roub Sep 19 '14 at 19:11
  • 1
    Note that you have 2 questions implied here. Both have already been answered, just separately (See Joseph's and Paul's comments.) – Jonathan Lonowski Sep 19 '14 at 19:12

3 Answers3

1

The first creates a scoped variable--one that's only available inside its parent function.

The second creates a global variable and is not a jQuery object, despite the dollar sign.

isherwood
  • 46,000
  • 15
  • 100
  • 132
0

Naming a variable with a dollar sign is pure JavaScript and doesn't require JQuery. This may be a naming convention (see Why would a JavaScript variable start with a dollar sign?). Omitting 'var' makes the variable global and changes the scope of the variable.

Community
  • 1
  • 1
disperse
  • 976
  • 8
  • 21
0

The var keyword in front of a variable will basically declare that variable within the current scope. But, if that var keyword is missing, Javascript will search up the scope chain to see if there is a variable with that name in a different scope. And, since it finds a variable with the same name – testVar – in the global scope, Javascript will use that variable instead of declaring a new one local to the function.

$var is the name of the variable nothing more, so the proper way would be var $var;

Bojan Petkovski
  • 6,503
  • 1
  • 19
  • 32