An Experiment in Building Our Own Arrays

Ever been debugging in your browser console and log an array’s prototype?

Image for post

Woah, didn’t expect all that, did you? Well, maybe you did. I’ve been working on a React alternative lately, and one thing I’ve been doing to mitigate the size of my virtual DOM is inheriting my virtual DOM objects from null. If you don’t already know, by using Object.create(null) you can create an object with no prototype. Pretty nifty. Kind of, anyway. There are some big drawbacks — try console.log’ing the result. You’ll get a ‘Failed to convert object primitive to string’ error. That’s because console.log relies on Object.prototype’s toString method. So the objects you create this way can be fairly difficult to work with at times and cause unexpected behavior, so be warned!

Anyway, I was looking at the resultant of one of my virtual DOM calls, and I realized that the weightiest part of my virtual object was the array I was using to represent child-objects. Its giant by comparison to the rest of my nully objects! So I had this crazy idea that I could make my own lighter array type, with no prototype, holding only the methods I need to render my DOM elements.

So we all know (?) that Array is just another Object. Look at Array.prototype.prototype for proof of that. Its special though — it can only be keyed by numbers, not strings. It also must have a length property. Let’s envision that in code:

const lightArray = () => Object.assign(
  Object.create(null), {
    length: 0,
    push(item) { this[this.length++] = item }
  })

Create one of those in the browser console — no prototype! And its keyed by numbers. Perfect, now we’re onto something. We could actually stop here if we wanted and use Array.prototype[‘methodname’].call(myArrInstance, args) to take advantage of existing methods, but I’ve heard that there is some overhead to this technique. Thus I’ve opted to implement the methods that I need directly on this object. But first, Array has the convenience of construction:

const myArr = [1, 2, 3]

#software-engineering #javascript #data-science #programming #technology

Arrays Are Objects Too
1.30 GEEK