Menu
Coddy logo textTech

The new Keyword

Part of the Object Oriented Programming section of Coddy's JavaScript journey — lesson 5 of 56.

The new keyword in JavaScript is used to create instances of constructor functions, which act as templates for creating objects.

Create a constructor function for a Person:

function Person(name, age) {
  this.name = name;
  this.age = age;
  this.greet = function() {
    return "Hello, my name is " + this.name;
  };
}

Use the new keyword to create an instance:

const john = new Person("John", 30);

After executing the above code, john is an object with properties and a method:

  • john.name is "John"
  • john.age is 30
  • john.greet() returns "Hello, my name is John"

Without the new keyword, this would refer to the global object (or undefined in strict mode), not the new instance.

challenge icon

Challenge

Create a Car Object and Print Its Description

You're given a constructor function that creates car objects. Your task is to:

  1. Create a new car object using the new keyword, pass "Honda" as the name and 2018 as the year
  2. Call the getDescription method on your car object
  3. Print the result to the console

Cheat sheet

The new keyword creates instances of constructor functions, which act as templates for objects.

Define a constructor function:

function Person(name, age) {
  this.name = name;
  this.age = age;
  this.greet = function() {
    return "Hello, my name is " + this.name;
  };
}

Create an instance using new:

const john = new Person("John", 30);

Access properties and methods:

john.name // "John"
john.age // 30
john.greet() // "Hello, my name is John"

Without new, this refers to the global object (or undefined in strict mode) instead of the new instance.

Try it yourself

function Car(name, year) {
    this.name = name;
    this.year = year;
    
    this.getDescription = function() {
        return "This is a " + this.name + " from " + this.year;
    };
}

// TODO: Create a new car object using the new keyword, pass "Honda" as the name and 2018 as the year

// TODO: Call the getDescription method on your car object and print the result to the console



quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Object Oriented Programming