Search code examples
javascriptarraysobjectprototypeproto

Javascript: Object.create(null) For Arrays (Array.create(null) Equivalent)


It is easy to initialize an object with a blank prototype: Object.create(null). But, arrays don't have a convenient Array.create method like Objects do. So, what would be the array equivalent of Object.create?

What would be the best way to initialize a blank array regarding the accessing speed* of the resulting array? Or, would the accessing speed* in said blank array be slower than the accessing speed* a regularly [] initialized array?

Any and all constructive responses are greatly appreciated.


*What is meant by 'accessing speed' is how fast properties can be read from, and written to, the array.


Solution

  • There's no point in creating an array with a blank (or any other customised) prototype. The use case for Object.create(null) is a map1 where no prototype interferes with properties, but we don't have that problem with arrays and their integer indices.
    If you insisted to do so,

    Object.setPrototypeOf([], null)
    

    will achieve this but create a very weird object that will break a lot of code that expects arrays to have certain methods.

    Or, would the property access speed in said blank array be slower than that of a regularly initialized array?

    Yes, quite likely - weird objects always have a good chance of not being optimised as well as standard objects. In any case, it won't be faster.

    1: Of course, they're deprecated in favour of true Maps now.