0

I just have a quick question and cant find anything on google. I was going through some code another programmer put together and he declares ALL of his javascript variables with $ in front of them...for instance:

 var $secondary;

Is there a reason for this? Could this cause problems in the future if JQuery ever ends up being used. I'm just curious because I was going to clean it up if so.

Luca
  • 43
  • 1
  • 1
  • 9

6 Answers6

3

Is there a reason for this?

Hard to say. Maybe he came from a PHP background where $ prefixes the variables. Maybe he's a jQuery addict. Who knows? You'd have to ask him. That aside, $ is a perfectly legitimate character to use in a JavaScript variable name but as you noted, it could cause issues with jQuery. But that's why jQuery offers a noConflict() option.

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

$ is a valid variable character, and in PHP all variables start with it. It's possibe that that particular developer uses $ as a "flag" to mean "this is a variable". It has no special meaning.

Niet the Dark Absol
  • 320,036
  • 81
  • 464
  • 592
1

$ just a character that you can use in a variable name. Some people like to use it to denote variables that contain jQuery objects:

var $foo = $('#foo');
var bar = 42;

But that's just a personal preference. It has no special meaning.

Blender
  • 289,723
  • 53
  • 439
  • 496
1

I use this convention too keep track of if a variable is storing a JQuery object. So say the function getJQueryObject() returns a JQuery object and I want to store it.

i.e:

var $myJQobj = getJQueryObject();

Makes it clear that $myJQobj is a JQuery object unlike i.e

var myStr = "hello";

The $ as the first character in the identifier doesn't have any special meaning, you aren't invoking a method like $(), it's just a perfectly valid identifier in JavaScript. But the factthat the $ is used in JQuery makes what I was talking about before even clearer.

HennyH
  • 7,794
  • 2
  • 29
  • 39
1

its just a convention for jQuery DOM selctions.

var $logo = $('a.logo');

it wont cause any issues - it just lets other devs know that you're working with a jQuery wrapped dom element.

random-forest-cat
  • 33,652
  • 11
  • 120
  • 99
0

$ is fine for use in JavaScript. PHP uses the same variable syntax so maybe he was used to it from that.

Phillip Berger
  • 2,317
  • 1
  • 11
  • 30