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?
asked Dec 26, 2013 at 22:59
Kevin Meredith
42.1k67 gold badges224 silver badges390 bronze badges
2 Answers 2
root itself is the first argument, thus we don't need to add whatever members is in it to itself.
answered Dec 26, 2013 at 23:01
Sebastian Paaske Tørholm
51.3k11 gold badges103 silver badges123 bronze badges
Sign up to request clarification or add additional context in comments.
1 Comment
cookie monster
IMO,
target would have been a more descriptive name than root.It's already in root. That's the first parameter
answered Dec 26, 2013 at 23:02
Stephen Thomas
14.1k2 gold badges35 silver badges53 bronze badges
Comments
lang-js
argumentsis not a keyword. It's a normal variable (name).root.nameis called first inroot [name] = Batou? I don't understandrootis the object that is passed as first argument tomerge, i.e.{name: "Batou"}. It already contains the propertyname.arguments, but themergefunction above seems confusing to me. Is it an acceptable/passes code review practice in JS?