Start learning free

LESSON 178 OF 344 · OBJECT-ORIENTED PROGRAMMING

Constructors in JavaScript: constructor() and this

Lesson Read the full explanation

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

    JAVASCRIPT · OBJECT-ORIENTED PROGRAMMING

    Constructors in JavaScript, explained

    Why constructors exist

    Without a constructor, you create an object first and fill it in afterwards:

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

    This works, but it is verbose, and it is easy to forget a line and end up with a dog that has no age. A constructor is a special method that runs automatically, once, at the moment an object is created with new. It receives the arguments you pass and sets up the object's properties, so a new object is complete from the first moment it exists.

    Defining a constructor

    In JavaScript the constructor is a method with the exact name constructor, written inside the class body:

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

    A class can have only one constructor. Writing two is a SyntaxError ("A class may only have one constructor"). To support optional values, use default parameters, such as constructor(name, age = 1), instead of a second constructor.

    The this keyword

    Inside a constructor, this refers to the object that is being created. The line this.name = name reads: set the name property on this new object to the value of the name parameter. The left side, this.name, is the property, and the right side, name, is the parameter. They only share a spelling by convention.

    The this. prefix matters. Without it, the assignment changes only the parameter, which disappears when the constructor ends:

    class Dog {
        constructor(name, age) {
            name = name;   // assigns the parameter to itself
            age = age;
        }
    }
    
    console.log(new Dog("Rex", 4));   // Dog {}
    

    The object comes out empty, and reading .name from it later gives undefined.

    Calling the constructor

    You pass the arguments to new, in the same order as the parameters:

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

    When these lines finish, rex.name is already "Rex" and rex.age is 4, and the same holds for Luna with her own values. Each object gets its own copy of the properties.

    Arguments follow normal JavaScript function rules. If you pass fewer than the constructor expects, the missing parameters are undefined, with no error: new Dog("Rex") gives a dog whose age is undefined. Extra arguments are ignored. A constructor can also check its inputs and throw an error when a value is not acceptable, so an invalid object is never built.

    Properties that don't come from arguments

    A constructor can also set properties that the caller doesn't supply. Create them inside the constructor, not outside, so that every object gets its own copy. For example, this.tricks = []; gives each dog a separate empty list. Adding "sit" to one dog's list leaves every other dog's list empty.

    The exercise, step by step

    1. Write the constructor. Inside the Dog class, define constructor(name, age) and use this.name and this.age to store the two parameters.
    2. Create the two dogs. Below the class, write let rex = new Dog("Rex", 4); and let luna = new Dog("Luna", 7);. The lines that print them are already in the starter code.

    The solution in JavaScript

    class Dog {
        constructor(name, age) {
            this.name = name;
            this.age = age;
        }
    }
    
    let rex = new Dog("Rex", 4);
    let luna = new Dog("Luna", 7);
    console.log(rex.name + " is " + rex.age);
    console.log(luna.name + " is " + luna.age);
    

    The output is:

    Rex is 4
    Luna is 7
    

    Common mistakes

    • Misspelling the method name. Only a method named exactly constructor is the constructor. Writing Constructor or init creates an ordinary method that new never calls on its own.
    • Forgetting this. As shown above, the properties are never set and the object stays empty.
    • Using the function keyword. Write constructor(name, age) { ... } inside the class, not function constructor.
    • Passing arguments in the wrong order. new Dog(4, "Rex") runs without any error and stores the age as the name. JavaScript does not check types, so the order is up to you.
    • Calling the class without new. Dog("Rex", 4) throws TypeError: Class constructor Dog cannot be invoked without 'new'.
    • Returning a value from the constructor. A constructor does not need return. Returning an object from it replaces the one new built, which is almost never what you want, so leave it out.

    Key takeaways

    • The constructor is a method named constructor that runs automatically when you use new.
    • Inside it, this is the new object, and this.name = name stores a parameter as a property.
    • A class has at most one constructor; use default parameters for optional values.
    • Missing arguments become undefined, and nothing in JavaScript checks their types.
    Keep going with JavaScriptAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free