Question

In the following code, the for-loop starts with i = 1. How come the name property of the merged object is properly set?

function merge(root){
  for ( var i = 1; i < arguments.length; i++ ){
    for ( var key in arguments[i] ){
      console.log(i); // returns 1 then 2 (not 0)
      root[key] = arguments[i][key];
    }
  }
  return root;
}

var merged = merge({name: "John"}, {city: "Boston"},{age: 13});
console.log( merged.name ); // "John" ?
console.log( merged.city ); // "Boston" - OK 
console.log( merged.age ); // 13 - OK 

If I set the loop start with i = 2, merged.city returns undefined (as expected), while merged.name still returns "John".

function merge(root){
  for ( var i = 2; i < arguments.length; i++ ){
    for ( var key in arguments[i] ){
      console.log(i); // returns 2
      root[key] = arguments[i][key];
    }
  }
  return root;
}

var merged = merge({name: "John"}, {city: "Boston"},{age: 13});
console.log( merged.name ); // "John" - ?
console.log( merged.city ); // undefined - OK
console.log( merged.age ); // 13 - OK

How is that possible?

Was it helpful?

Solution

The parameter root refers to the object {name: "John"}. This is also arguments[0]. That's why we skip it and start at arguments[1] — all of the subsequent arguments are merged into it.

OTHER TIPS

You probably missed the fact that your method accepts a parameter you then return

function merge(root) {
  ...
  return root

so that when you feed it with

merge( {name: "John"}, ...

it will use {name: "John"} as root and merge other arguments into it.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top