Reputation: 15362
What is the advantage of nodeList
s and arguments
being just "array-like"?
Upvotes: 1
Views: 262
Reputation: 183211
In each case, the object has some behaviors that an actual array could not have.
In the case of NodeList
, some node-lists are "live" collections, meaning that even after creation, they continue to reflect later changes to the underlying DOM. (For example, if node
is a node, then node.childNodes
is a node-list that always contains its current children.)
In the case of arguments
, when you assign to its elements, this actually assigns to the corresponding local variables. For example, this function always returns 3
, no matter what argument is passed in:
function returnThree(i) {
arguments[0] = 3;
return i;
}
(You can even pass arguments
as an argument to another function, and let it assign to your local variables!)
(Note: Whether these behaviors are actually "advantages" is perhaps a matter for debate.)
Upvotes: 1
Reputation:
arguments
not being a true array is a historical artifact. Although as pointed out in another answer, it has the callee
property, and can be proxied onto the actual arguments, in and of itself that would not have prevented it from being a true array. For more discussion, see Why isn't a function's arguments object an array in Javascript?. It is also worth pointing out that the toString
method on arguments
behaves differently than an array.
NodeList
is not part of JS per se; it's a DOM data interface definition, which is designed to be used from many languages and environments. If it were to be an array in JS implementations, one would probably want it to be of a type subclassed from Array, but JS does not support subclassing Array very well. Also, in such cases, we would have the slightly odd situation of a DOM datatype which in JS differs (extends) the definition of the specified data interface. It is true, as pointed out in other answers, that NodeList
may be "live", but again, that in itself would not prevent it being a true array.
ES6 provides functions such as Array.from
which will ease some of the pain.
Upvotes: 1