What is this function doing

function extend(dest){ 
 var source, attr; 
 for (var i = 1; i < arguments.length; i++){ 
   source = arguments[i]; 
   for (attr in source){ 
     dest[attr] = source[attr]; 
   } 
 } 
} 
 
var obj1 = { 
 obj1Prop: true 
}; 
 
var obj2 = { 
 obj2Prop: true 
}; 
 
extend(obj1, obj2); 

I want to know what this function is doing and when/why you would use it. Specifically the line I am having the most difficulty with is:

  dest[attr] = source[attr]; 

so above this you put all your args into source and now iterating through each element/object in source and doing what exactly? the first time of the loop what is happening, and what is happening on the second run?

Hello
This are some results of the extend function

extend(obj1, obj2);
-> undefined
dest
->ReferenceError: dest is not defined debugger eval code:1:1
obj1
->Object { obj1Prop: true, obj2Prop: true }
obj2
->Object { obj2Prop: true }

It seams that extend accept an undefined number of objects and regroup all there properties in the first passed object.
but extend is not a pure function!!

Hi @oussama-jlassi,

I came across the word pure function through your reply and went to look up on it. So my understanding of a pure function is that it must always function like a mapper, is that right?

Hello dondon
a pure function is like a function in mathematics
for each input the result is a single output, and does not change there inputs.
in the extend function example :
there is no return statements , and dest (i.e the first object in the sequence of arguments ) is modified .

1 Like

It’s called shallow key/value merging. Similar to Object.assign and the object spread operator.

The first object will receive the key/value pairs of the second object; and once it done, it will also receive the ones from the 3rd argument and so on until there’s no arguments left. With the particularity that it overwrites existing k/v pairs. For example if destination object has a prop called “foo” and the next source object also has it, the destination will overwrite its value with the value of source.

Equivalents:

// With object.assign
// developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign
const extend = (...args) => Object.assign.apply(null, args)

// With the spread operator
// developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax
const extend = (dest, ...srcs) =>
  srcs.reduce((ext, src) => ({...ext, ...src}), dest)