Menu
Coddy logo textTech

Creating Instances

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

After defining a class, you can create objects based on that class using the new keyword. These objects are called instances.

Let's say we have a simple Person class:

class Person {
  constructor(name, age) {
    this.name = name;
    this.age = age;
  }
  
  greet() {
    return `Hello, my name is ${this.name}`;
  }
}

Create an instance of the Person class:

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

After executing the above code, john is an instance of the Person class with:

  • name property set to "John"
  • age property set to 30

You can access properties and methods of the instance:

console.log(john.name); // Outputs: John
console.log(john.greet()); // Outputs: Hello, my name is John

You can create multiple instances from the same class:

const sarah = new Person("Sarah", 25);
console.log(sarah.name); // Outputs: Sarah
challenge icon

Challenge

You're given a Student class. Your task is to create two student instances in the driver.js file:

  1. Create student1 with name "Sarah" and grade 85
  2. Create student2 with name "Mike" and grade 92

Cheat sheet

To create an instance of a class, use the new keyword:

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

Access properties and methods of an instance using dot notation:

console.log(john.name); // Outputs: John
console.log(john.greet()); // Outputs: Hello, my name is John

You can create multiple instances from the same class:

const sarah = new Person("Sarah", 25);
console.log(sarah.name); // Outputs: Sarah

Try it yourself

import { Student } from './student.js';

// TODO: Create an instance of class Student called student1 with name "Sarah" and grade 85

// TODO: Create an instance of class Student called student2 with name "Mike" and grade 92


// Test code - don't modify
console.log(student1.name);  // Should output "Sarah"
console.log(student2.grade); // Should output 92
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