What is the purpose of the first boolean parameter in $ .extend

advertisements

Initially i have a doubt how $.extend works. I referred to this question.But I'm confused about the following code segment

$.extend(true,{},{foo:2})
$.extend({},{foo:2})

Both return {foo:2}.

I am very clear about second code statement. How does first statement work? What is the difference between first and second statement? If both are same, What is the purpose of first statement? If not, why does both returns same result?

Any suggestions?


It creates a deep copy, I think an example could show you what it does

var log = (function() {
  var $log = $('#log');
  return function(msg) {
    $('<p/>', {
      text: msg
    }).appendTo($log)
  }
})();

function test(deep) {
  var obj = {
    prop1: 1,
    obj12: {
      prop1: 1
    }
  };

  var cpy = deep ? $.extend(true, {}, obj) : $.extend({}, obj);

  cpy.obj12.prop1 = 'changed';
  log(JSON.stringify(obj));
  log(JSON.stringify(cpy));
}
log('without the deep param')
test();
log('with deep')
test(true);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="log"></div>

If you look at the generated results the obj12 value is actually copied to cpy when deep was not used.