Course contentsShow
← JavaScript
Lesson 776 of 2,72318. ClassesFree lesson

Extending Built-in Classes

Creating custom subclasses of Array, Error, or other built-ins and their quirks.

Extending Built-in Classes

You'll learn how to create custom subclasses of JavaScript's built-in classes like Array and Error, and understand the special considerations involved.

What This Means

JavaScript lets you extend native classes (Array, Error, Map, etc.) to create specialized versions with custom behavior. This works just like extending your own classes with extends, but built-in classes have some unique quirks you need to know about.

Creating Custom Built-in Subclasses

You can subclass Array, Error, or any built-in class:

class MyArray extends Array {
  first() {
    return this[0];
  }
  
  last() {
    return this[this.length - 1];
  }
}

const arr = new MyArray(1, 2, 3);
console.log(arr.first()); // 1
console.log(arr.last());  // 3
arr.push(4);
console.log(arr.length);  // 4 — built-in behavior works!
class ValidationError extends Error {
  constructor(message) {
    super(message);
    this.name = 'ValidationError';
  }
}

throw new ValidationError('Invalid input');
// Works with try-catch like regular Error

Important Quirks

Built-in array methods like map() or filter() return instances of your subclass, not plain Arrays:

const myArr = new MyArray(1, 2, 3);
const doubled = myArr.map(x => x * 2);
console.log(doubled instanceof MyArray); // true
console.log(doubled.first()); // 2 — your custom method still works

This happens because built-ins use a special internal mechanism to preserve the subclass type through operations.

Key Takeaway: You can extend built-in classes to add custom functionality, and JavaScript automatically preserves your subclass type through native operations—making Array, Error, and other built-ins extensible foundations for specialized data structures.