MediumObjects📖 Theory Question

What are native prototypes and how can you safely extend them?

💡

Hint

Array.prototype, String.prototype etc — extending them affects ALL instances; almost always a bad idea

Full Answer

All built-in types (Array, String, Object, Function…) have prototypes with their methods. Every array shares Array.prototype.

// How it works — built-in prototype chain
const arr = [1, 2, 3];
// arr.__proto__ === Array.prototype ✓
// Array.prototype.__proto__ === Object.prototype ✓

// All arrays share Array.prototype methods
arr.map === Array.prototype.map;   // true — same reference

// Checking native prototype
Array.prototype.includes;   // function — built-in
String.prototype.padStart;  // function — built-in

// ❌ Bad: extending native prototypes (prototype pollution risk)
Array.prototype.last = function() { return this[this.length - 1]; };
// Now EVERY array in ALL your code + libraries has .last — collisions!

// ❌ Famous historical mistake: Prototype.js library
// It extended Array.prototype and broke all for...in loops on arrays

// ✅ If you must extend (only in polyfills — check first)
if (!Array.prototype.myMethod) { // always guard with existence check
  Array.prototype.myMethod = function() { ... };
}

// ✅ Better: use utility functions or subclassing
class SuperArray extends Array {
  last() { return this[this.length - 1]; }
}
const sa = new SuperArray(1, 2, 3);
sa.last(); // 3 — only SuperArray instances affected
💡 Rule: never extend native prototypes in application code or libraries. Exception: polyfills (always check for existence first). It's the JS equivalent of monkey-patching — dangerous at scale.

More Objects Questions

EasyHow does prototypal inheritance work in JavaScript?→EasyWhat is the difference between shallow copy and deep copy?→MediumWhat are property descriptors and property flags (writable, enumerable, configurable)?→EasyWhat are getters and setters in JavaScript?→

Practice this in a timed sprint →

5 free questions, no signup required

⚡ Start Sprint