Javascript extend object I'm looking for a review of the Javascript code which has this specifications:


  Given two objects, the function "extend" adds properties from the 2nd object to the 1st object.


Notes:


Add any keys that are not in the 1st object.
If the 1st object already has a given key, ignore it (do not overwrite the property value).
Do not modify the 2nd object at all.


A runnable version can be found on repl.it.

function extend(obj1, obj2) {
  for (var key in obj2) {
    if (!obj1.hasOwnProperty(key)) {
      obj1[key] = obj2[key];
    }
  }
}
var obj1 = {
  a: 1,
  b: 2
};
var obj2 = {
  b: 4,
  c: 3
};

extend(obj1, obj2);

console.log(obj1); // --&gt; {a: 1, b: 2, c: 3}
console.log(obj2); // --&gt; {b: 4, c: 3}
Assuming that if the first object has a property set to undefined and the rule states no change then your code is almost spot on. 

Some minor changes


The variable key into a const.
Return the extended object.
Vet the arguments.


Thus 

function extend(obj1, obj2) {
    if (obj1 !== null &amp;&amp; typeof obj1 === "object") {
        if (obj2 !== null &amp;&amp; typeof obj2 === "object") {
            for (const key in obj2) { 
                if (!obj1.hasOwnProperty(key)) {
                    obj1[key] = obj2[key];
                }
            }
        }
    }
    return obj1;
}
extend({a: 1, b: undefined}, {b: 1, c: 2}); // returns {a: 1, b: undefined, c: 2}