🟑 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