Menu
Coddy logo textTech

Properties and Methods

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

Classes in JavaScript allow us to define properties and methods that will be shared by all instances of the class.

Create a class with properties:

class Car {
  constructor(make, model) {
    this.make = make;
    this.model = model;
  }
}

When creating an instance, the constructor sets these properties:

const myCar = new Car('Toyota', 'Corolla');
console.log(myCar.make);  // Output: 'Toyota'
console.log(myCar.model); // Output: 'Corolla'

Add a method to the class:

class Car {
  constructor(make, model) {
    this.make = make;
    this.model = model;
  }
  
  getDescription() {
    return `This car is a ${this.make} ${this.model}.`;
  }
}

Now we can call this method on any instance:

const myCar = new Car('Toyota', 'Corolla');
console.log(myCar.getDescription()); // Output: 'This car is a Toyota Corolla.'
challenge icon

Challenge

Create a class named Book in the book.js file with the following:

  1. A constructor that takes title, author, and pages parameters and sets them as properties.
  2. A method called getInfo that returns a string in the format: “Title: [title], Author: [author], Pages: [pages]”
  3. Export the class by adding `export` in front of the `class` declaration

Cheat sheet

Classes in JavaScript define properties and methods shared by all instances.

Create a class with a constructor:

class Car {
  constructor(make, model) {
    this.make = make;
    this.model = model;
  }
}

Create an instance using new:

const myCar = new Car('Toyota', 'Corolla');
console.log(myCar.make);  // Output: 'Toyota'

Add methods to a class:

class Car {
  constructor(make, model) {
    this.make = make;
    this.model = model;
  }
  
  getDescription() {
    return `This car is a ${this.make} ${this.model}.`;
  }
}

Call methods on instances:

const myCar = new Car('Toyota', 'Corolla');
console.log(myCar.getDescription()); // Output: 'This car is a Toyota Corolla.'

Export a class:

export class Car {
  // class definition
}

Try it yourself

import { Book } from './book.js';

// Test (do not modify this part)
const book = new Book("JavaScript Basics", "John Doe", 200);
console.log(book.getInfo());
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