Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why use an array-like object in Javascript?

I get that since javascript allows numeric keys for objects, the existence of array-like objects is therefore technically possible, but why did they ever become common?

Maybe the thought was that these array-like objects don't just have numeric keys, e.g. arguments has the callee property, so they can't be proper arrays to accommodate those properties.

But in javascript, it's perfectly valid to treat an array as an object and use non-numeric keys:

var myArguments = []; 
myArguments[0] = 0; 
myArguments['callee'] = function(){console.log('callee')};

If the object is array-like and would benefit from having access to the functions it would otherwise inherit from the array prototype, what would be advantage of making it an array-like object instead?


Edit: in case it wasn't clear in my question, an array like object would be something like the arguments object that has sequential numeric properties starting from zero, and has a length property that is one less than the highest numeric key. It also doesn't inherit from the array prototype, and doesn't provide access to array methods.

like image 683
martin Avatar asked Jun 04 '26 02:06

martin


1 Answers

I think the biggest advantage of using Array-Like object, is an object itself. An object has less overhead than an Array. Can read: Array vs. Object efficiency in JavaScript

The other advantage of using objects, Language does not have to create/allocate contiguous memory as in Array. The object is more dynamic in nature. The array has to create a memory block in advance. and update on overload.

Read more: How are the JavaScript Arrays internally resizing?

Another factor, I think lookup in a map or object is faster.

like image 197
xdeepakv Avatar answered Jun 05 '26 16:06

xdeepakv



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!