Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why Are Array-Like Objects Used in Javascript Over Native Arrays

It's very common in Javascript to come across Array-Like objects with some similarities to the build in Array type but without all of its methods or features. So much so that there are some tricks to convert Array-Like objects to "real" arrays for further manipulation.

This is even mentioned in Javascript: The Definitive Guide.

The questions is why is this pattern so common? Why not prefer the built-in Array type in all these cases?

like image 356
elasticrat Avatar asked Nov 22 '10 00:11

elasticrat


1 Answers

Well, speaking about core Javascript objects, the arguments is a good example to talk about.

In this case it has been an array-like object since the beginning, appeared in the ECMAScript 1th Edition Specification already as a simple object.

Why? I think at that time there were only four built-in Array methods, and maybe the designer didn't think it worthed too much, later the change was proposed, but Microsoft (part of the TC39 committee) didn't approved the change, the fear of breaking the web has always been present.

Now going to host objects, the DOM, NodeLists come to my mind, I think they didn't wanted to use the native Array type due the dynamic behavior of these objects.

NodeLists generally are live objects, their structure is reflects any change on the underlying DOM structure...

Personally I like array-objects, because they are really lightweight, before ECMAScript 5, there were a lot of restrictions in core methods, regarding the usage of user-defined array-like objects.

For example, the apply method of function objects, in ECMAScript <= 3, allowed only either a real array or an arguments object as its second argument, now in ES5, the following is possible:

var arrayLike = {0: 'hello ', 1:'world', length:2};
(function (a,b) { alert(a+b); }).apply(null, arrayLike);

See also:

  • Why isn't a function's arguments object an array in Javascript?
like image 75
Christian C. Salvadó Avatar answered Nov 14 '22 12:11

Christian C. Salvadó