Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any specific reason behind using $ with variable in jQuery

Tags:

jquery

I know it's a silly question but I am a bit confused with this. For example, if I have an input with an ID: rad1, is there any difference between below lines of code?

var $a = $('#rad1')

or

var a = $('#rad1')
like image 216
Exception Avatar asked Apr 18 '12 07:04

Exception


People also ask

What are the reasons of naming a variable?

A variable is a symbolic name for (or reference to) information. The variable's name represents what information the variable contains. They are called variables because the represented information can change but the operations on the variable remain the same.

Are there variables in jQuery?

JavaScript (jQuery) variable will have only two scopes. Global Variables − A global variable has global scope which means it is defined everywhere in your JavaScript code. Local Variables − A local variable will be visible only within a function where it is defined.

What is $variable in jQuery?

It has no special meaning. jQuery sets the global $ variable to an object with a number of special behaviors, so variables beginning with $ are often reserved for variables or values related to jQuery. This is not enforced at any level, though. You're free to use $ in variable names wherever and however you like.

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.


4 Answers

No there is no real difference.

It's just a convention that helps you remember that a isn't the DOM element but it's a jQuery object.

var a = document.getElementById('a');
a.innerHTML  //fine

var $a = $('#a');
$a.html()   // fine

Ohhh, and by the way, neither a or $a are good variable names ... you should use meaningful variable names not abc characters.


Read the jQuery info tag on this very same site:

Variable Naming Conventions

jQuery wrapped variables are usually named starting with '$' to distinguish them from standard JavaScript objects.

var $this = $(this);
like image 168
gdoron is supporting Monica Avatar answered Sep 30 '22 13:09

gdoron is supporting Monica


It's only for showing that it's a Jquery variable.

Declaring $a you're showing that your variable is for JQuery objects, it's just a notation. So the most readable thing will be to declare Jquery variable with $ notation

var $obj=$("#obj");

And DOM element without $ notation

var obj = document.getElementById("obj");
like image 44
Chuck Norris Avatar answered Sep 30 '22 11:09

Chuck Norris


There's no difference. It's just a coding convention to help identify that the variable represents a jquery wrapped object.

like image 40
kinakuta Avatar answered Sep 30 '22 13:09

kinakuta


No difference its just coding convention , check this

like image 22
Govind Malviya Avatar answered Sep 30 '22 12:09

Govind Malviya