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

Constructor Validation

Throwing errors in constructors to prevent invalid object creation with bad arguments.

Constructor Validation

You'll learn how to guard your class constructors by throwing errors when invalid arguments are passed, preventing broken objects from being created.

Why Validate in the Constructor?

A constructor is the gatekeeper for creating new instances. If bad data gets through, you end up with an object in an invalid state. By throwing errors immediately when something's wrong, you catch bugs early and make your code's requirements crystal clear.

Think of it like a bouncer at a club checking IDs—if someone doesn't meet the requirements, they don't get in. Better to be turned away at the door than cause chaos inside.

How It Works

Inside your constructor, check that arguments meet your requirements. If they don't, use throw new Error() to stop object creation:

class BankAccount {
  constructor(balance) {
    if (balance < 0) {
      throw new Error('Balance cannot be negative');
    }
    this.balance = balance;
  }
}

const valid = new BankAccount(100);  // ✓ Works fine
const invalid = new BankAccount(-50); // ✗ Throws error, object never created

You can validate data types, ranges, required fields, or any other rule:

class User {
  constructor(name, age) {
    if (typeof name !== 'string' || name.trim() === '') {
      throw new Error('Name must be a non-empty string');
    }
    if (typeof age !== 'number' || age < 0 || age > 120) {
      throw new Error('Age must be a number between 0 and 120');
    }
    this.name = name;
    this.age = age;
  }
}

Key Takeaway: Throwing errors in constructors prevents invalid objects from existing—validate your inputs at the gate to maintain data integrity and catch mistakes immediately.