Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Defining variables in jQuery

Can someone explain the difference between using a $ when defining variables in jQuery and not. Does it have any impact on performance?

var $someVar = $("a");
var someVar = $("a");

Also, what is the difference in calling variables with and without $(someVar) For example:

$(someVar).html();
someVar.html();
like image 686
RyanLynch Avatar asked Feb 27 '23 18:02

RyanLynch


2 Answers

In your first snippet, there is no difference between those two. It's just a "notification" that this variable is holding a wrappet set of jQuery objects, which is commonly used by some developers.

In your second snippet you are actually doing two different things. You are wrapping someVar into a jQuery object and then access a jQuery method (html()). In this example someVar could contain a DOM element or a selector string like "#some_element_id".

The other line assumes that someVar already IS a jQuery object, otherwise this call would fail.

like image 77
jAndy Avatar answered Mar 02 '23 23:03

jAndy


There is no performance difference, it's just an identifier. $foo is often used to refer to jquery objects by experienced authors so as to not confuse them with non-jquery objects in complex scripts.

As for the $() wrapping, you can reference a DOMElement and wrap it in jQuery, eg

var e = document.body; $(e).hide()

If we tried e.hide() there would be no defined method as the body element doesn't have that method, it's only provided by the jQuery prototype chain.

like image 39
meder omuraliev Avatar answered Mar 02 '23 22:03

meder omuraliev