SyntaxStudy
Sign Up
jQuery jQuery $.extend() — Object Merging
jQuery Intermediate 5 min read

jQuery $.extend() — Object Merging

$.extend() copies properties from one or more source objects into a target object. It is the jQuery equivalent of the modern spread operator ({ ...defaults, ...options }) and is the standard pattern for implementing plugin option merging in jQuery code.

Shallow vs Deep Merge

By default $.extend(target, src) performs a shallow merge — nested objects are copied by reference, not recursively merged. Pass true as the first argument for a deep (recursive) merge: $.extend(true, target, src).

Plugin Options Pattern

When writing a jQuery plugin or a component constructor, define a defaults object and merge caller-supplied options over them. Using $.extend({}, defaults, options) — with an empty object as the first argument — creates a fresh object without mutating either defaults or options.

  • $.extend(target, src) — shallow merge into target
  • $.extend(true, target, src) — deep recursive merge
  • $.extend({}, defaults, options) — safe, non-mutating merge
  • Returns the merged target object
Example
// Merge two objects
var base    = { color: 'blue', size: 'medium' };
var override = { color: 'red', weight: 'bold' };
var result  = $.extend({}, base, override);
console.log(result);
// { color: "red", size: "medium", weight: "bold" }

// Plugin defaults pattern
var defaults = { speed: 400, easing: 'swing', loop: false };

function createSlider(options) {
    var settings = $.extend({}, defaults, options);
    console.log(settings.speed);  // caller value or 400
    console.log(settings.easing); // caller value or 'swing'
}
createSlider({ speed: 800, loop: true });

// Deep merge for nested objects
var config = { ajax: { timeout: 5000, retry: false } };
var patch   = { ajax: { retry: true } };
var merged  = $.extend(true, {}, config, patch);
console.log(merged.ajax.timeout); // 5000 (preserved)
Pro Tip

Always pass {} as the first argument to $.extend() so you get a new object and leave the originals unmodified.