0

Secrets of the JavaScript Ninja explains the arguments keyword with the merge() function:

function merge(root){
 for (var i = 1; i < arguments.length; i++) { // starts at i = 1, not 0
   for (var key in arguments[i]) {
     root[key] = arguments[i][key];
   }
 }
 return root;
}

var merged = merge(
 {name: "Batou"},
 {city: "Niihama"});

Note the assertions:

assert(merged.name == "Batou", 
    "The original name is intact.");
assert(merged.city == "Niihama", 
    "And the city has been copied over.");

Why does merged.name equal Batou rather than undefined?

Since, as I understand, merge() does not look at the first argument in the outer for-loop, how does the name: Batou get added to root?

5
  • FWIW, arguments is not a keyword. It's a normal variable (name). Commented Dec 26, 2013 at 23:47
  • So root.name is called first in root [name] = Batou? I don't understand Commented Dec 27, 2013 at 1:58
  • 1
    No, root is the object that is passed as first argument to merge, i.e. {name: "Batou"}. It already contains the property name. Commented Dec 27, 2013 at 1:58
  • perhaps it's due to inexperience with arguments, but the merge function above seems confusing to me. Is it an acceptable/passes code review practice in JS? Commented Dec 27, 2013 at 2:42
  • I updated the title - thanks, Felix King. Commented Dec 27, 2013 at 3:31

2 Answers 2

4

root itself is the first argument, thus we don't need to add whatever members is in it to itself.

1
  • IMO, target would have been a more descriptive name than root. Commented Dec 26, 2013 at 23:13
1

It's already in root. That's the first parameter

Not the answer you're looking for? Browse other questions tagged or ask your own question.