How Underscore Extends Object


I’ve planning to learn to write efficient js code. Learning from open source is a good idea. Also, I’ve been confused about how _.extend() differs from extends from ES6 So let’s jump into the really famous JavaScript Utility Library [Underscore.js][]!

Underscore Source

Reviews from code

// An internal function for creating assigner functions.
var createAssigner = function(keysFunc, undefinedOnly) {
  return function(obj) {
    var length = arguments.length;
    if (length < 2 || obj == null) return obj;
    for (var index = 1; index < length; index++) {
      var source = arguments[index],
          keys = keysFunc(source),
          l = keys.length;
      for (var i = 0; i < l; i++) {
        var key = keys[i];
        if (!undefinedOnly || obj[key] === void 0) obj[key] = source[key];
    return obj;


we can find that what _.extend() does is basically looping over property of objects from second one to last one, grabbing properties and put them on first objects. Worth noticing is that it’s shallow copy and it’s copied by reference if source property is object or array