I have seen the following two variable initializations to create an empty jQuery object. Is there a major difference or advantage to use one over the other?
var a = $({});
var b = $();
If you meant $([])
, that's something from the old days where calling $()
was actually equivalent to $(document)
(which was an undocumented feature). So to get an empty set, you'd have to call $([])
. This was changed in jQuery 1.4; the documented functionality of $()
is now to return an empty set.
Passing objects to the jQuery constructor is an entirely different beast. $({})
doesn't create an empty jQuery object. It creates a jQuery object with a length of 1; the selected item is the object itself.
Passing JS objects to the jQuery constructor lets you take advantage of a more esoteric feature of jQuery: binding and triggering events on (non-DOM) objects.
For example:
var obj = { some: 'stuff' };
$(obj).on('someevent', function() { ... });
$(obj).trigger('someevent');
Either way, if your goal is to instantiate a new, empty jQuery object, use $()
.
I think you mean:
var a = $([]); //<- array not object
var b = $();
No advantage that I know of, the first one is the old version, since 1.4 you can use the later.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With