Sometimes in JQuery we define variable as var $a=$()
which is like declaring a function. So i want to know does it make any change if we define variable as var a
only?
-
Do you just mean "without the $ symbol"? If so, then it makes no difference, it's just a convention used to sometimes indicate that you're using a jQuery object.– James AllardiceOct 3, 2012 at 20:22
5 Answers
If you mean:
var a = $(/* Object or Selector gets passed here */)
Then the only difference would be the name. Developers use $a
to indicate that the value is already jQuery
-ied. Leaving it off changes no functionality but would be a dis-service to future developers.
-
$() is a shortcut for the jQuery function. It is either passed an object or a selector. api.jquery.com/jQuery Oct 3, 2012 at 20:26
no, it is no different. $a
is the same as a
in that context. It's simply a variable name.
Generally I prefer naming jQuery objects prepended with a $ sign.. It's a convention to recognize jQuery objects in your code..
But it's just another variable name ;;
var a = 2;
var $a = $('#something');
Basically this is an allowed violation of Crockford's coding convention for javascript. It is used to differentiate jQuery objects from javascript DOM elements.
E.g.
var a = document.getElementById('a'); // DOM element
var $a = $(a); // jQuery object for the DOM element with ID 'a'
$ is an allowed character in JS identifiers, it makes no difference. $(obj) wraps the object obj with a jQuery object, and decorates obj with a lot of additional behavior.
These are legal Javascript variable names:
$a=1;
a$$$=1;
$a=1;
The function $ is an alias for jQuery, if you do something like:
your HTML:
<img src='logo.png' id='site_logo'/>
your JS:
var logo = $('#site_logo');
logo.fadeOut();
The method fadeOut doesn't belongs to the img element, but to the jQuery wrapper.