jQuery API

jQuery.extend()

jQuery.extend( target [, object1] [, objectN] ) Returns: Object

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

  • version added: 1.0jQuery.extend( target [, object1] [, objectN] )

    target An object that will receive the new properties if additional objects are passed in or that will extend the jQuery namespace if it is the sole argument.

    object1An object containing additional properties to merge in.

    objectNAdditional objects containing properties to merge in.

  • version added: 1.1.4jQuery.extend( [deep], target, object1 [, objectN] )

    deepIf true, the merge becomes recursive (aka. deep copy).

    targetThe object to extend. It will receive the new properties.

    object1An object containing additional properties to merge in.

    objectNAdditional objects containing properties to merge in.

When we supply two or more objects to $.extend(), properties from all of the objects are added to the target object.

If only one argument is supplied to $.extend(), this means the target argument was omitted. In this case, the jQuery object itself is assumed to be the target. By doing this, we can add new functions to the jQuery namespace. This can be useful for plugin authors wishing to add new methods to JQuery.

Keep in mind that the target object (first argument) will be modified, and will also be returned from $.extend(). If, however, we want to preserve both of the original objects, we can do so by passing an empty object as the target:

var object = $.extend({}, object1, object2);

The merge performed by $.extend() is not recursive by default; if a property of the first object is itself an object or array, it will be completely overwritten by a property with the same key in the second object. The values are not merged. This can be seen in the example below by examining the value of banana. However, by passing true for the first function argument, objects will be recursively merged. (Passing false for the first argument is not supported.)

Undefined properties are not copied. However, properties inherited from the object's prototype will be copied over. For performance reasons, properties that have values of built-in JavaScript types such as Date or RegExp are not re-constructed, and will appear as plain Objects in the resulting object or array.

Note: When performing a deep extend, Object and Array are extended, however primitive types such string, boolean and number are not. For specific needs that fall outside of this behaviour, it is recommended to write a custom extend method as this will be significantly faster from a performance perspective.

Examples:

Example: Merge two objects, modifying the first.

<!DOCTYPE html>
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
  
<div id="log"></div>

<script>
var object1 = {
  apple: 0,
  banana: {weight: 52, price: 100},
  cherry: 97
};
var object2 = {
  banana: {price: 200},
  durian: 100
};

/* merge object2 into object1 */
$.extend(object1, object2);

var printObj = function(obj) {
  var arr = [];
  $.each(obj, function(key, val) {
    var next = key + ": ";
    next += $.isPlainObject(val) ? printObj(val) : val;
    arr.push( next );
  });
  return "{ " +  arr.join(", ") + " }";
};

$("#log").append( printObj(object1) );
</script>

</body>
</html>

Demo:

Example: Merge two objects recursively, modifying the first.

<!DOCTYPE html>
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
  
<div id="log"></div>

<script>
var object1 = {
  apple: 0,
  banana: {weight: 52, price: 100},
  cherry: 97
};
var object2 = {
  banana: {price: 200},
  durian: 100
};

/* merge object2 into object1, recursively */
$.extend(true, object1, object2);

var printObj = function(obj) {
  var arr = [];
  $.each(obj, function(key, val) {
    var next = key + ": ";
    next += $.isPlainObject(val) ? printObj(val) : val;
    arr.push( next );
  });
  return "{ " +  arr.join(", ") + " }";
};

$("#log").append( printObj(object1) );
</script>

</body>
</html>

Demo:

Example: Merge defaults and options, without modifying the defaults. This is a common plugin development pattern.

<!DOCTYPE html>
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
  
<div id="log"></div>

<script>
var defaults = { validate: false, limit: 5, name: "foo" };
var options = { validate: true, name: "bar" };

/* merge defaults and options, without modifying defaults */
var settings = $.extend({}, defaults, options);

var printObj = function(obj) {
  var arr = [];
  $.each(obj, function(key, val) {
    var next = key + ": ";
    next += $.isPlainObject(val) ? printObj(val) : val;
    arr.push( next );
  });
  return "{ " +  arr.join(", ") + " }";
};


$("#log").append( "<div><b>settings -- </b>" + printObj(settings) + "</div>" );
$("#log").append( "<div><b>options -- </b>" + printObj(options) + "</div>" );

</script>

</body>
</html>

Demo:

Support and Contributions

Need help with jQuery.extend() or have a question about it? Visit the jQuery Forum or the #jquery channel on irc.freenode.net.

Think you've discovered a jQuery bug related to jQuery.extend()? Report it to the jQuery core team.

Found a problem with this documentation? Report it to the jQuery API team.

* All fields are required
  • azoff

    don't forget this little tidbit from the old docs: “If no target is specified, the JQuery namespace itself is extended. This can be useful for plugin authors wishing to add new methods to JQuery”

  • Vance

    would you provide a clone method like this:
    $.clone = function(obj, [deep]) {
    return !obj ? obj : $.extend(!deep, {}, obj); //deep clone by default
    }

    • http://twitter.com/aivopaas Aivo Paas

      I wonder how the non-deep clone would work. Cloning (extending) is always deep if you extend an empty object. Use $.extend(true, {}, obj) to get a clone.

  • http://twitter.com/nikravi Nicolae Racovita

    var copy = $.extend({}, “aString”)
    returns an object like this
    copy = {
    0: “a”,
    1: “S”,
    2: “t”,…
    }
    Wouldn’t it be nice to return the same string?

    • http://twitter.com/Tim_jarratt Tim Jarratt

      Not if you're treating a string as an object – an array of characters. What are you trying to do?

  • myguest

    is there any function which does exactly the opposite of the $.extend method ?
    looked through api, but couldn’t find anything!
    Thanks for any advice!

    • http://paulirish.com Paul Irish

      Nope. You’ll have to manually iterate over an object (with $.each) extracting the values you want and `delete`ing them as you go.

      • test

        This is the test for the cheking and testing for the test..

  • Anonymous

    I think that PHP array merge concepts are more in line with that of mainstream developers. I was looking at extend for about an hour trying to figure out why only one array populated into an array of arrays because both were zero indexed. While this is probably a great tool for combining config files, it’s lousy at combining recordsets from disparate sources. You’re better off renumbering the indexes yourself and merging, if that is your goal.

    • Mark

      jQuery.extend doesn't merge arrays, it merges objects (read: associative arrays or objects in PHP). If you want to “merge” indexed arrays without losing data on overlapping keys you should simply use Array.concat().

  • http://kflorence.myopenid.com/ Kyle Florence

    using extend with deep set to true seems to have some quirks for RegExp. specifically, in my case, it clones the object perfectly except for my /regex/ which it stores as an empty object.

  • Zhouxianglh

    jQuery.extend = jQuery.fn.extend = function()

    extend !== fn.extend ?

  • Pradeep

    How to set values dynamically for setting true or false?
    noData: {
    “embed”: false,
    “object”: false,
    “applet”: true
    },

  • http://twitter.com/thepag Mark Panaghiston

    What happens if you do the following?
    - That is deep copy a jQuery selector.

    myObj = {
    someProp:”myProp”,
    selector: {
    start: $(“#myStart”),
    stop: $(“#myStop”)
    }
    };

    myCopy = $.extend(true,{},myObj);

    I’m concerned whether the myObj.selector object will deep copy the whole of jQuery as part of the process. My initial tests did not show any obvious speed hit, but it is rather a basic test right now.

  • Havvy

    The result for “Example: Merge two objects recursively, modifying the first.” slightly extends past the box on my computer's width causing scrollbars to appear in the results div. Shortening a string in it by one or two characters would remove the scrollbars.

  • Talonsblade

    how would this work on an array of objects? for instance you have 6 objects an array with a different value for a property. would you have to loop through the array to set each objects property?

    • Manish Sharma

      for that you will require to use the concept of [ deep ] If true, it merges two objects recursively. –that means —the same property will be overridden by the later and different ones will be merger

  • G.Kalavathi

    G.Kalavathi
    President
    Rural Physically Handicapped Center for Rehabilitation,
    Nallasiddana Palli (V)K.G. Sathram (P),
    Bangarupalyam (M),
    Chittoor (District ) A.P. India.
    E-mail Address . ruralphysicallyhandicapped@gmail.com

    Rural Physically Handicapped Center for Rehabilitation Non- Profit Organization. There are so many poor Handicapped and Disable persons in our Chittoor District . They are facing so many troubles . lack of finance, food, clothing and shelter. They con not do cooli, they con not do business. Either the Govt or banks or public are not lending money to them with or with out interest to start any kind of task to stand on their own legs. They are leading miserable lives.
    Hence I request you to kindly provide me Financial Assistance to me to start any self- help groups, to help to poor handicapped and disable persons in our chittoor District A.P. India our Organization got income Tax Exemption certificate (80(G) certificates and F.C.R.A certificate please give me a grant application to my organization.

    Thanking you sir,

    Your sincerely

    G.Kalavathi
    President

  • G.Kalavathi

    G.Kalavathi
    President
    Rural Physically Handicapped Center for Rehabilitation,
    Nallasiddana Palli (V)K.G. Sathram (P),
    Bangarupalyam (M),
    Chittoor (District ) A.P. India.
    E-mail Address . ruralphysicallyhandicapped@gmail.com

    Rural Physically Handicapped Center for Rehabilitation Non- Profit Organization. There are so many poor Handicapped and Disable persons in our Chittoor District . They are facing so many troubles . lack of finance, food, clothing and shelter. They con not do cooli, they con not do business. Either the Govt or banks or public are not lending money to them with or with out interest to start any kind of task to stand on their own legs. They are leading miserable lives.
    Hence I request you to kindly provide me Financial Assistance to me to start any self- help groups, to help to poor handicapped and disable persons in our chittoor District A.P. India our Organization got income Tax Exemption certificate (80(G) certificates and F.C.R.A certificate please give me a grant application to my organization.

    Thanking you sir,

    Your sincerely

    G.Kalavathi
    President

  • G.Kalavathi

    G.Kalavathi
    President
    Rural Physically Handicapped Center for Rehabilitation,
    Nallasiddana Palli (V)K.G. Sathram (P),
    Bangarupalyam (M),
    Chittoor (District ) A.P. India.
    E-mail Address . ruralphysicallyhandicapped@gmail.com

    Rural Physically Handicapped Center for Rehabilitation Non- Profit Organization. There are so many poor Handicapped and Disable persons in our Chittoor District . They are facing so many troubles . lack of finance, food, clothing and shelter. They con not do cooli, they con not do business. Either the Govt or banks or public are not lending money to them with or with out interest to start any kind of task to stand on their own legs. They are leading miserable lives.
    Hence I request you to kindly provide me Financial Assistance to me to start any self- help groups, to help to poor handicapped and disable persons in our chittoor District A.P. India our Organization got income Tax Exemption certificate (80(G) certificates and F.C.R.A certificate please give me a grant application to my organization.

    Thanking you sir,

    Your sincerely

    G.Kalavathi
    President

  • Abdul Rehman

    How do we use the property/attributes/methods of a function used in document.onready function ??

  • Mike

    What happens to events binded to “Object1″? Are they copied to the target?

  • Mark

    Why do you call it “extend”, in fact, it is a “merge”?
    Specially, when “deep”: false, it is really a copy/overwrite – nothing related to “extend”.

  • Firerains

    my objA is like this { opts:['a','b','c'], 'text':'sss'} , and objB is { opts:['d']}. when use $.extend(true,{},objA,objB) ,i got the result { opts:['d','b','c'], 'text':'sss'}, but what i want is { opts:['a','b','c','d'], 'text':'sss'} , so, is there anything wrong ?

    • John

      No.

      Extend works on objects not arrays. Since your arrays are being treated as objects, the 'd' with key/index '0' replaces the 'a' with key/index '0'.

    • Toph

      When merging arrays, you might want to try $.merge()

  • http://twitter.com/trevmex Trevor Lalish_Menagh

    I wrote a blog post comparing $.extend to other methods of extending objects. My results from many different browsers can be found at:
    http://trevmex.com/post/253162…

    I am interested in the community's thoughts on the matter.

    Yours,
    Trevor

  • http://twitter.com/trevmex Trevor Lalish_Menagh

    I wrote a blog post comparing $.extend to other methods of extending objects. My results from many different browsers can be found at:
    http://trevmex.com/post/253162…

    I am interested in the community's thoughts on the matter.

    Yours,
    Trevor

  • MCZ

    Hello, could someone please explain to me why

    var a = {};
    console.log(a);
    $.extend(a, { something: 1 });

    is “a” varible already extended although I am checking it BEFORE extend?

  • http://twitter.com/airyweb Tom Sendze

    Have a problem cloning an object

    the original project method gets executed as well.

    http://jsfiddle.net/xEpGg/

  • Manishk Sharma

    pls loook at the Example: Merge two objects recursively, modifying the first

  • gkorobkov

    It's not work. Error message is “invalid object initializer”