1

I am wondering why, when working with arrays I usually work with instance methods such as .split, .indexOf, .map while when working with objects, I mostly use static methods on the Object class?

I count 21 static methods for the Object class, and just 3 for Arrays, of which 2 are concerned with creation rather than manipulation.

The only explanation I can come up with, is that since everything inherits from Object in JS, the designers wanted to keep those Object objects as lightweight as possible.

Flip
  • 6,233
  • 7
  • 46
  • 75
  • that's wrong, Arrays can also have Objects usage – Mister Jojo Apr 02 '21 at 13:09
  • Quite the contrary - not everything inherits from object and static methods can be applied to objects created from `null`, consider e.g. `a = Object.create(null); Object.seal(a)` – georg Apr 02 '21 at 13:11

1 Answers1

4

The only explanation I can come up with, is that since everything inherits from Object in JS, the designers wanted to keep those Object objects as lightweight as possible.

That's it exactly. You don't want to fill up Object.prototype with a bunch of methods, because they'd be on everything that's an object (or at least, everything that's an object that inherits from Object.prototype, which all objects do by default though you can prevent it with Object.create).

There's a second, more subtle reason: Because you don't want basic operations altered by objects in the general case. That's one reason you see people avoiding using the hasOwnProperty method on an object and instead using it directly from Object.prototype:

if (Object.prototype.hasOwnProperty.call(obj, "name")) {
    // ...
}

The author of the code above wanted to avoid the possibility that hasOwnProperty had been redefined for obj such that it would lie. :-)

const obj = {
    hasOwnProperty() {
        return true;
    }
};

console.log(obj.hasOwnProperty("foo"));                        // true
console.log(Object.prototype.hasOwnProperty.call(obj, "foo")); // false, which is correct
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875