Start learning free

LESSON 281 OF 671 · FUNCTIONS & CLASSES

Constructors in JavaScript

Lesson

TL ; DR:

  • A constructor is a special method that runs automatically when you create an object with new. It's used to set up the object's properties.


  • In JavaScript, the constructor is a method literally named constructor, defined inside the class:

    class Dog {
        constructor(name, age) {
            this.name = name;
            this.age = age;
        }
    }
    

  • Then create objects with arguments: new Dog("Rex", 4) — the constructor fills in the properties for you.



Full lesson:

In the previous lesson you set properties one at a time after creating the object:

let dog = new Dog();
dog.name = "Rex";
dog.age = 4;

That works, but it's verbose and easy to forget. Constructors let you initialize the properties the moment new Dog(...) is called.


Defining a constructor

In JavaScript, the constructor is a method named exactly constructor:

class Dog {
    constructor(name, age) {
        this.name = name;
        this.age = age;
    }
}

The this keyword

this is a built-in reference to the object being created. this.name = name means "set the name property on this new object to the value of the name parameter".


Calling the constructor

let rex  = new Dog("Rex", 4);
let luna = new Dog("Luna", 7);

By the time these lines finish, rex.name is already "Rex", rex.age is 4, and the same for Luna.


Your task

Inside the Dog class, define a constructor that takes name and age and assigns them with this. Then below the class, create two dogs:

let rex  = new Dog("Rex", 4);
let luna = new Dog("Luna", 7);

Expected output:

Rex is 4
Luna is 7
STEP 1 OF 2
    Ctrl + Enter to check