Skip to content
Tutorials Center
My learning

Topics

Lesson 34 of 56 ยท Plugins and Utilities

Utility Functions

Learn the jQuery utility functions: $.extend (shallow and deep), $.each, $.map, $.grep, $.inArray, $.isPlainObject, and which old helpers are deprecated in favour of native JavaScript.

Most of jQuery works on collections of page elements, but a second group of functions lives directly on the $ object and works on plain data: arrays, objects and functions. They are called utilities, and you call them as $.each(...), not $("li").each(...). Many were written long before modern JavaScript had arrays with map(), filter() and includes(), so a good part of this lesson is knowing which ones you still need and which have a native replacement.

The utilities that remain useful are $.extend, $.each, $.map, $.grep, $.inArray, $.isPlainObject and $.noop. The rest, from $.trim to $.isArray, are deprecated and you should recognize them in old code and replace them. You will use $.extend heavily when you write plugins, and the iteration helpers build on working with collections.

Still worth using

$.extend Merge objects, even deeply.
$.each Loop arrays and objects alike.
$.grep Filter an array by a test.
$.map Transform and flatten values.
1 / 2

$.extend: merging objects

$.extend(target, ...sources) copies the properties of the source objects onto the target and returns the target. Later sources win over earlier ones. It is the classic way to apply default options.

JavaScript
var defaults = { color: "blue", size: 10 };
var options  = { size: 20 };

var settings = $.extend({}, defaults, options);
// { color: "blue", size: 20 }   defaults and options are untouched

Always pass an empty object as the first argument when you want a new object. If you write $.extend(defaults, options) the defaults object itself is modified, which is a common source of bugs.

By default the copy is shallow: nested objects are shared by reference, not duplicated. Pass true as the first argument for a deep merge, which recurses into nested plain objects and arrays.

Two details are worth remembering. Properties whose value is undefined are skipped, but null is copied. And in a deep merge, arrays are merged index by index rather than replaced, so [1, 2, 3] merged with [9] gives [9, 2, 3].

Modern JavaScript offers Object.assign({}, a, b) and the spread syntax { ...a, ...b } for shallow merges, and structuredClone() for deep copies. $.extend(true, ...) remains handy for merging nested options.

Shallow versus deep extend

$.each, $.map and $.grep

These three work on arrays and, for $.each, on objects too.

$.each(collection, callback) runs the callback for every item. Arrays and array-likes give (index, value); objects give (key, value). Return false from the callback to stop early. It returns the original collection, so it is for side effects.

JavaScript
$.each(["a", "b"], function (index, value) { console.log(index, value); });
$.each({ x: 1, y: 2 }, function (key, value) { console.log(key, value); });

Be careful not to confuse it with the element method .each() from Working with Collections, where this is the element. In $.each over an array, this is also the item, but prefer the second argument; this boxes primitives (a string becomes a String object).

$.map(array, callback) builds a new array from the callback's return values. The argument order is (value, index), the opposite of $.each. Returning null or undefined drops the item, and returning an array flattens it into the result, which makes $.map handy for expanding one item into several. Native Array.prototype.map() does neither, so check which behaviour you want.

$.grep(array, callback, invert) keeps the items for which the callback returns true. With invert set to true it keeps the items that fail. The callback receives (value, index).

JavaScript
var prices = [4, 12, 7, 30];
var cheap  = $.grep(prices, function (p) { return p < 10; });          // [4, 7]
var tax    = $.map(prices, function (p) { return p * 1.2; });          // each increased by 20%
var pairs  = $.map([1, 2], function (n) { return [n, n * 10]; });      // [1, 10, 2, 20]

$.inArray and type checks

$.inArray(value, array) returns the index of the value, or -1 when it is missing. This trips people up, because 0 (found at the start) is falsy. Always compare with -1, or use the modern array.includes(value) which returns a boolean.

$.isPlainObject(x) is true for objects created with {} or new Object() and false for arrays, null, DOM nodes, class instances and functions. It is the check $.extend uses to decide whether to recurse, and it is still current API.

Iterating, mapping and filtering data

$.proxy and $.noop

$.proxy(function, context) returns a function whose this is fixed to the given context. In old code you will see $.proxy(this.handler, this) as a way to keep this pointing at an object inside an event handler. It has been deprecated since jQuery 3.3; use function.bind(context) or an arrow function, which keeps this automatically.

$.noop is an empty function. It is not deprecated and is useful as a default callback so you can call options.onDone() without checking whether it exists:

JavaScript
var settings = $.extend({ onDone: $.noop }, options);
settings.onDone();

Deprecated utilities and their replacements

Deprecated functions still work in jQuery 3 (most will be removed in jQuery 4), but they add nothing over native code. Learn the replacements so you can modernize old scripts:

Old call Replacement
$.trim(s) (deprecated 3.5) s.trim()
$.isArray(x) (deprecated 3.2) Array.isArray(x)
$.parseJSON(s) (deprecated 3.0) JSON.parse(s)
$.isFunction(x) (deprecated 3.3) typeof x === "function"
$.isNumeric(x) (deprecated 3.3) Number.isFinite(Number(x)) plus a check for empty strings
$.isWindow(x) (deprecated 3.3) x != null && x === x.window
$.type(x) (deprecated 3.3) typeof x, Array.isArray(x), x === null
$.now() (deprecated 3.3) Date.now()
$.proxy(fn, ctx) (deprecated 3.3) fn.bind(ctx)
$.camelCase(s) (deprecated 3.3) a small string function

How do you find these calls in a big codebase? Include the jQuery Migrate plugin during development. It prints a console warning for every deprecated feature you use, with a stack trace, so you can fix them one by one. The jQuery 3 changes lesson shows how to set it up.

Native replacements side by side

Legacy properties: jquery, length, context, fx and support

Besides functions, jQuery objects and the jQuery function carry a few properties you will see in old code and in debugging sessions.

Property What it is Status
$.fn.jquery or $("p").jquery the version string, such as "3.7.1" fine; use it to check which copy loaded
$("p").length how many elements the collection holds fine; .size() was removed in 3.0
$("p").context, .selector the node and selector the object was created from removed in 3.0
$.fx.off true makes every animation finish instantly fine; mainly for tests
$.fx.interval milliseconds between animation frames (default 13) deprecated in 3.0; jQuery uses requestAnimationFrame
$.support the results of feature tests jQuery ran for itself deprecated for outside use

The most useful of these in daily work is length: if ($(".error").length) { ... } is the classic way to ask "did the selector find anything?". An empty collection is still truthy, so if ($(".error")) is always true, which is a frequent bug.

$.fx.off is worth a closer look because it saves time in test suites: set it to true and .fadeOut(), .slideUp() and .animate() complete immediately, so a test can check the final state without waiting. Remember to set it back afterwards.

$.support once held dozens of browser feature flags ($.support.opacity, $.support.boxModel). Browser sniffing and feature flags like this are an anti-pattern: they were removed as browsers converged, and the few remaining entries describe jQuery's internals. Detect features yourself, in the way the platform recommends:

JavaScript
if ("IntersectionObserver" in window) { /* use it */ }
if (CSS.supports("display", "grid")) { /* use grid */ }
if (matchMedia("(prefers-reduced-motion: reduce)").matches) { $.fx.off = true; }

The last line shows a real use of $.fx.off: respect users who ask for less motion.

Reading jQuery's own properties

The animation asked for five seconds and the width was already 300 on the next line, which is exactly what $.fx.off does.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why should the first argument of $.extend usually be an empty object?

    $.extend changes and returns its first argument. Passing {} keeps the original defaults intact.
  2. 2. What does the argument order of $.map's callback look like?

    $.map passes the value first and the index second, the opposite order of $.each.
  3. 3. $.inArray("x", ["x", "y"]) returns 0. How should you test whether the value was found?

    It returns the index, and 0 is falsy even though the value was found. -1 means not found. Array.prototype.includes returns a plain boolean.
  4. 4. Which replacement is correct for the deprecated $.trim(text)?

    String.prototype.trim is built into JavaScript, so the jQuery wrapper is unnecessary.
  5. 5. What happens when a $.map callback returns an array?

    $.map flattens returned arrays by one level and drops null and undefined, which differs from native Array.prototype.map.

Summary

  • Utilities live on $ and work on data, not elements: $.extend, $.each, $.map, $.grep, $.inArray, $.isPlainObject and $.noop are still useful.
  • $.extend({}, defaults, options) merges without modifying defaults; pass true first for a deep merge.
  • $.each breaks on return false; $.map takes (value, index), drops null and flattens arrays; $.grep filters.
  • $.inArray returns an index, so compare against -1.
  • Replace $.trim, $.isArray, $.parseJSON, $.isFunction, $.type, $.now and $.proxy with native JavaScript, and use jQuery Migrate to find them.

With these tools you are ready to package your own code as a plugin in Writing Your Own Plugin.