Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does $([]) mean in jQuery

Tags:

jquery

I have come across the following jQuery code but could not understand it. What does the following code, specially the "$([])" part in the last line mean ?

var instrument = $("#instrument"),
    quantity = $("#quantity"),
    orderType = $("#orderType"),
    price = $("#price"),
    validityDate = $("#validityDate"),
    allFields = $([]).add(instrument).add(quantity).add(orderType).add(price).add(validityDate)
like image 221
MD Sayem Ahmed Avatar asked Apr 13 '10 12:04

MD Sayem Ahmed


2 Answers

Looks like it's defining an array, then add()ing the DOM elements to it. From the manual:

Given a jQuery object that represents a set of DOM elements, the .add() method constructs a new jQuery object from the union of those elements and the ones passed into the method. The argument to .add() can be pretty much anything that $() accepts, including a jQuery selector expression, references to DOM elements, or an HTML snippet.

[] is an empty javascript array. As frunsi notes, this is not correct usage, and the [] definition is not required to create an empty set of elements, in 1.4 $() will do ths for you.

like image 176
Andy Avatar answered Oct 04 '22 22:10

Andy


It creates an empty jQuery set. This kind of usage is wrong, though it may work. The [] is superfluous.

Correct would be just $().

Returning an Empty Set

As of jQuery 1.4, calling the jQuery() method with no arguments returns an empty jQuery set. In previous versions of jQuery, this would return a set containing the document node.

http://api.jquery.com/jQuery/

like image 28
Frunsi Avatar answered Oct 04 '22 21:10

Frunsi