Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When/why to prefix variables with "$" when using jQuery? [duplicate]

Possible Duplicate:
Why would a javascript variable start with a dollar sign?

I see people using the dollar sign in front of variables when using jQuery. Is there any reason behind this? I'm I missing something basic or is it just a common practice?

like image 861
elclanrs Avatar asked Jun 02 '11 01:06

elclanrs


People also ask

Can JavaScript variables begin with?

Naming Conventions for JavaScript VariablesA variable name must start with a letter, underscore ( _ ), or dollar sign ( $ ). A variable name cannot start with a number. A variable name can only contain alpha-numeric characters ( A-z , 0-9 ) and underscores. A variable name cannot contain spaces.

What is ${} used for in JavaScript?

It can be used easily as a replacement. Secondly it allows for the introduction of a variable without concatenating (which is what you will use it for in this lesson). This is done using ${var} to add the variable string in-line to your current string.

What is the significance of in front of a variable name?

It's just a coding convention and it allows you to quickly reference what type the variable is later in the code.

What is dollar variable in JavaScript?

The dollar sign ($) and the underscore (_) characters are JavaScript identifiers, which just means that they identify an object in the same way a name would. The objects they identify include things such as variables, functions, properties, events, and objects.


2 Answers

It's a common reference to a jQuery wrapped object. It makes reading the code easier to know which variables are jQuery wrapped.

//Item has been "cached" for later use in the script as a jQuery object. var $item = $(this); 
like image 182
Scott Harwell Avatar answered Oct 08 '22 23:10

Scott Harwell


For me a common practice is this:

If a variable is private I use an underscore like this:

(function(){      var _foo = "bar"; })()

If it's public I'll use no underscore:

var foo = "bar"

And if it's a jQuery selector I'll use the $:

var $foo = $('bar'); //then you can access it like this $foo.attr('id')

It's just coding convention and it allows you to quickly reference what type the variable is later in the code.

like image 41
locrizak Avatar answered Oct 09 '22 00:10

locrizak