How does the extend() function work in jQuery?

Multiple Parameters

The documentation isn't precise in explaining how extend works, so I ran a little test:

var a = {foo: 1, bar: 1};
var b = {foo: 2, baz: 2};
var c = {foo: 3};
var r = jQuery.extend(a,b,c);
console.log("A: Foo=" + a.foo + " Bar=" + a.bar + " Baz=" + a.baz);
console.log("B: Foo=" + b.foo + " Bar=" + b.bar + " Baz=" + b.baz);
console.log("C: Foo=" + c.foo + " Bar=" + c.bar + " Baz=" + c.baz);
console.log("R: Foo=" + r.foo + " Bar=" + r.bar + " Baz=" + r.baz);
console.log("A === R?: " + (a === r));

(The console.log function is intended to work in Firebug; replace it with alert() or some other output function if you like).

The results are:

A: Foo=3 Bar=1 Baz=2
B: Foo=2 Bar=undefined Baz=2
C: Foo=3 Bar=undefined Baz=undefined
R: Foo=3 Bar=1 Baz=2
A === R?: true

By this we can see that jQuery.extend():

  • Starts with the object provided by the first parameter.
  • Adds to it any property in the second parameter. If the property already exists in the first parameter, it is overwritten. The object for the second parameter is unchanged.
  • Repeats the above with any subsequent parameter.
  • Returns the first parameter.

This is useful for combining user and default option-objects together to get a complete set of options:

function foo(userOptions) {
  var defaultOptions = {
    foo: 2,
    bar: 2
  };
  var someOtherDefaultOptions = {
    baz: 3
  };

  var allOptions = jQuery.extend(
    defaultOptions,
    someOtherDefaultOptions,
    userOptions
  );
  doSomething(allOptions);
}

foo({foo:1, baz:1});

Note that "null" is a valid value for overwriting, but "undefined" isn't. You might be able to make use of this.

var a = {foo: "a", bar: "a"};
var b = {foo: null, bar: undefined};
jQuery.extend(a,b);
console.log("A: Foo=" + a.foo + " Bar=" + a.bar);

Results in:

A: Foo=null Bar=a

Single Parameter

If you pass just one object to jQuery.extend(), then jQuery assumes that the jQuery object itself is the "first" parameter (ie: the one to be modified), and your object is the "second" (ie: the one to add to the first). So:

console.log( "Before: " + jQuery.foo );
jQuery.extend({foo:1});
console.log( "After: " + jQuery.foo );

Results in:

Before: undefined
After: 1

It merges the content of one object to another. If we pass two objects, second object properties are added to the first object / first parameter

Ex: $.extend(object1, object2);

Now object1 contains properties of object2

If we want to merge two objects, then we need to pass empty object in the first parameter

Ex: var newObject = $.extend({}, object1, object2);

Now newObject contains both properties of object1 and object2.


From jQuery Documentation

Merge the contents of two or more objects together into the first object.

In a plugin context: If the user does not set the optional parameters for the function, then a default value will be used instead.


How does extend() work in jQuery? [Resolved]

jQuery have deep copy and light copy. The first boolean decide it, true for deep and false for light.

For example:

  • jQuery.extend(false, {'a' : {'a1': 1}}, {'a': {'a2': 2}})

    the result will be: {'a': {'a2': 2}} because this is light copy just compare level 1.

    enter image description here

  • jQuery.extend(true, {'a' : {'a1': 1}}, {'a': {'a2': 2}})

    the result will be: {'a': {'a1': 1, 'a2': 2}} This is deep copy with many level of object (just like level of array)

    enter image description here

  • jQuery.extend(a,b,c) with a, b, c is object or array. The flow overrite will be b->a, c ->a (b overrite a, c override a ...) this function will return a and a also change value too.

Advanced Examples:

  • jQuery.extend({'number_param': 1})

    In case you just pass one param. jQuery will extend itself. console.log(jQuery['number_param']) will output 1.

    enter image description here

  • jQuery.extend(1, {'number_param': '2'}); This example is not append jQuery itself. The first parameter must be boolean. In this case it will return {'number_param': '2'} and jQuery not get updated.

    enter image description here

  • jQuery.extend(a, b, c, d ,e , f); The order merge will be . b ->a , c -> a, d -> a, e -> a, f ->a (b override a, c override a ...) . And result return will be a.

    with a= {'p': 1}. jQuery.extend(a, {'p': 2},{'p': 3},{'p': 4},{'p': 5}) will return a, and a = {'p': 6}. The number parameters pass to this function is unlimited.

    enter image description here


The purpose is to extend an existing object. For e.g. if we have a template object and we want to extend that by adding more properties or override existing properties, jquery extend can be useful.

var carObjectTemplate = {
"make": "honda",
"model":"city",
"mileage":"20",
"variant":"petrol"

};

now if we want to extend it, $.extend(true, {"color":"red"}, carObjectTemplate, {"model": 'amaze'}); it will give us ouput, extending carObjectTemplate and adding

{"color":"red"} property and overriding "model" property from "city" to "amaze"

first boolean parameter true/false is to indicate if we need a deep or shallow copy