Difference between a defining variable like var $ a = $ () and var a?

Sometimes in jQuery we define a variable as var $a=$() , which is similar to a function declaration. So I want to know if there is any change if we only define the variable as var a ?

+8
javascript jquery coding-style
source share
5 answers

If you mean:

 var a = $(/* Object or Selector gets passed here */) 

Then the only difference will be the name. Developers use $a to indicate that the value is already jQuery -ied. Leaving this, the changes will not function, but will be a disappointment for future developers.

+4
source share

no, this is no different. $a matches a in this context. This is simply the name of the variable.

+2
source share

I usually prefer to name jQuery objects added by the $ sign. This is a convention on recognizing jQuery objects in your code.

But this is just another variable name ;;

 var a = 2; var $a = $('#something'); 
+2
source share

Basically, this is a permissible violation of the Crockford coding convention for javascript. It is used to differentiate jQuery objects from javascript DOM elements.

eg.

 var a = document.getElementById('a'); // DOM element var $a = $(a); // jQuery object for the DOM element with ID 'a' 
+2
source share

$ is a valid character in JS identifiers; it does not matter. $ (obj) wraps an obj object with a jQuery object and decorates obj with a lot of extra steps.

These are legal Javascript variable names:

 $a=1; a$$$=1; $a=1; 

The $ function is an alias for jQuery if you are doing something like:

your HTML:

 <img src='logo.png' id='site_logo'/> 

your js:

 var logo = $('#site_logo'); logo.fadeOut(); 

The fadeOut method does not belong to the img element, but to the jQuery wrapper.

+1
source share

All Articles