TExcelTAD
Home › jQuery › jQuery Utilities

jQuery Utilities

Besides working with elements, jQuery includes utility functions called directly on $ (not on a selection). Many of them predate modern JavaScript array methods — you will see them constantly in existing code, so it pays to know them and their modern equivalents.

$.each(): loop over arrays and objects

js
$.each(collection, function (keyOrIndex, value) { … });

It works on arrays and plain objects. Return false to stop the loop early.

html · try it yourself
<!DOCTYPE html>
<html>
<body style="font-family: sans-serif; font-size: 14px">
  <ul id="list"></ul>
  <dl id="specs"></dl>

  <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
  <script>
    const colors = ["red", "green", "blue", "STOP", "purple"];
    $.each(colors, function (i, color) {
      if (color === "STOP") return false;            // break
      $("<li>").text(i + ": " + color).css("color", color).appendTo("#list");
    });

    const specs = { weight: "250 g", battery: "30 h", bluetooth: "5.3" };
    $.each(specs, function (key, value) {
      $("#specs").append($("<dt>").text(key), $("<dd>").text(value));
    });
    console.log("keys:", Object.keys(specs).length);
  </script>
</body>
</html>

Note: $.each(array, fn) is a utility for any data. $("li").each(fn) is a method that loops over matched elements. They share the same callback signature (index, value).

$.map() and $.grep(): transform and filter

Function Returns Modern equivalent
$.map(array, fn(value, index)) New array of returned values; null/undefined are dropped, returned arrays are flattened array.map() / array.flatMap()
$.grep(array, fn(value, index), invert?) Items for which fn returns true (or false when invert is true) array.filter()
$.inArray(value, array) Index or -1 array.indexOf() / includes()
$.merge(a, b) Appends b's items into a a.push(...b)
$.makeArray(arrayLike) Real array from an array-like (e.g. a NodeList) Array.from()
$.uniqueSort(elements) DOM elements de-duplicated, in document order —

Notice the argument order: $.map and $.grep call your function with (value, index) — the reverse of $.each's (index, value).

html · try it yourself
<!DOCTYPE html>
<html>
<body style="font-family: sans-serif; font-size: 14px">
  <pre id="out"></pre>

  <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
  <script>
    const products = [
      { name: "Espresso Beans", price: 24.5, tags: ["coffee"] },
      { name: "Green Tea", price: 9, tags: ["tea", "organic"] },
      { name: "Mug", price: 12, tags: [] },
      { name: "Oat Milk", price: 3.2, tags: ["vegan", "organic"] }
    ];

    const names = $.map(products, p => p.name);
    const cheapNames = $.map(products, p => (p.price < 10 ? p.name : null));   // null is dropped
    const allTags = $.map(products, p => p.tags);                              // arrays flattened
    const pricey = $.grep(products, p => p.price >= 10);
    const notPricey = $.grep(products, p => p.price >= 10, true);              // inverted

    console.log("names:", names);
    console.log("cheap:", cheapNames);
    console.log("all tags:", allTags);
    console.log("pricey:", $.map(pricey, p => p.name));
    console.log("not pricey:", $.map(notPricey, p => p.name));
    console.log("index of 'tea':", $.inArray("tea", allTags));
    $("#out").text("Unique tags: " + [...new Set(allTags)].join(", "));
  </script>
</body>
</html>

$.extend(): merging objects

$.extend(target, obj1, obj2, …) copies the properties of the later objects into target and returns it. It is the classic way to combine default options with user options — every jQuery plugin does this.

Form Behaviour
$.extend(target, a, b) Shallow merge into target (modifies it!)
$.extend({}, defaults, options) Merge into a new object, leaving defaults untouched
$.extend(true, {}, a, b) Deep merge — nested objects are merged, not replaced
$.fn.extend({ myMethod() {…} }) Adds methods to jQuery objects (plugins)
html · try it yourself
<!DOCTYPE html>
<html>
<body style="font-family: sans-serif; font-size: 13px">
  <pre id="out" style="background:#f4f6f8;padding:8px"></pre>

  <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
  <script>
    const defaults = { speed: 400, loop: false, colors: { bg: "#fff", fg: "#000" } };
    const userOptions = { loop: true, colors: { fg: "#c00" } };

    const shallow = $.extend({}, defaults, userOptions);
    const deep = $.extend(true, {}, defaults, userOptions);

    console.log("shallow colors:", shallow.colors);   // bg is lost!
    console.log("deep colors:", deep.colors);         // bg kept, fg overridden
    console.log("defaults untouched:", defaults.colors.fg === "#000");

    $("#out").text("deep result:\n" + JSON.stringify(deep, null, 2));
  </script>
</body>
</html>

The shallow merge replaces the whole colors object, so bg disappears. The deep merge combines the nested objects. Modern JavaScript has { ...defaults, ...options } for the shallow case and structuredClone for copying, but no built-in deep merge — which is why $.extend(true, …) is still popular.

Type checks and other helpers

Function Purpose
$.isPlainObject(x) true for {} / new Object() literals, not arrays, DOM nodes or class instances
$.isEmptyObject(x) true if the object has no enumerable properties
Array.isArray(x) Use this — $.isArray is deprecated
$.type(x) Deprecated since 3.3 — use typeof, Array.isArray, instanceof
$.trim(s) Deprecated since 3.5 — use s.trim()
$.now() Deprecated — use Date.now()
$.param(obj) Object → query string (a=1&b=2)
$.escapeSelector(s) Escapes special characters for use in a selector
$.contains(parent, child) true if child is inside parent (DOM elements)
$.noop An empty function, handy as a default callback
html · try it yourself
<!DOCTYPE html>
<html>
<body style="font-family: sans-serif; font-size: 14px">
  <div id="weird.id:1">I have a tricky id</div>

  <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
  <script>
    console.log("isPlainObject({}):", $.isPlainObject({}));
    console.log("isPlainObject([]):", $.isPlainObject([]));
    console.log("isEmptyObject({}):", $.isEmptyObject({}));
    console.log("param:", $.param({ q: "red shoes", size: [40, 41] }));

    const id = "weird.id:1";
    console.log("escaped:", "#" + $.escapeSelector(id));
    $("#" + $.escapeSelector(id)).css("color", "crimson");
    console.log("contains:", $.contains(document.body, $("#" + $.escapeSelector(id))[0]));
  </script>
</body>
</html>

Note how $.param encodes arrays as size%5B%5D=40 — that is size[]=40, the convention PHP and Rails understand.

Test yourself

What is the argument order of the callback for $.map(array, fn)?

  1. (index, value)
  2. (value, index)
  3. (value) only
  4. (array, index)

What does $.map([1, 2, 3], n => n === 2 ? null : n) return?

  1. [1, null, 3]
  2. [1, 3]
  3. [null]
  4. [1, 2, 3]

Why use $.extend({}, defaults, options) instead of $.extend(defaults, options)?

  1. It is faster
  2. It avoids modifying the shared defaults object
  3. It performs a deep merge
  4. The second form is a syntax error