Menu
Coddy logo textTech

What is a Class?

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

A class in JavaScript is a blueprint for creating objects with pre-defined properties and methods. Classes were introduced in ES6 and provide a cleaner, more intuitive syntax for creating objects and dealing with inheritance.

Define a simple class:

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

The constructor method is a special method that gets called when an object is created from the class.

Create an instance of the class:

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

Access properties of the created object:

console.log(john.name); // Output: "John"
console.log(john.age);  // Output: 25
challenge icon

Challenge

Create a class named Car with a constructor that takes two parameters: make and model. The constructor should set these values as properties of the object.

Cheat sheet

A class is a blueprint for creating objects with pre-defined properties and methods.

Define a class with a constructor:

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

The constructor method is called when an object is created from the class.

Create an instance of the class:

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

Access properties of the object:

console.log(john.name); // Output: "John"
console.log(john.age);  // Output: 25

Try it yourself

// TODO: Create a class named Car 

// TODO: Add a constructor that takes two parameters: make and model

// TODO: Set these values (make and model) as properties of the object

// Don't modify the code below
const make = inp[0];
const model = inp[1];
const car = new Car(make, model);
console.log(car.make)
console.log(car.model)
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