JavaScript / JavaScript Object-Oriented Programming (OOP)

Creating Classes and Objects

This tutorial focuses on creating classes and objects in JavaScript. It provides step-by-step instructions and practical examples.

Tutorial 2 of 5 5 resources in this section

Section overview

5 resources

Introduces OOP principles in JavaScript, including classes, objects, and inheritance.

1. Introduction

In this tutorial, we will delve into creating classes and objects in JavaScript. The primary goal is to equip you with the knowledge to define and create your own classes, and instantiate objects from them in a real-world context.

By the end of this tutorial, you will learn:

  • What classes and objects are in JavaScript
  • How to define classes and create objects
  • How to apply methods and properties to a class

The prerequisites for this tutorial are a basic understanding of JavaScript syntax and knowledge of fundamental programming concepts such as variables, functions and control flow.

2. Step-by-Step Guide

Classes and Objects

In JavaScript, classes are a template for creating objects. They encapsulate data with code to manipulate that data. Classes in JS are built on prototypes but also have some syntax and semantics that are not shared with ES5 class-like semantics.

An object is an instance of a class. When a class is defined, no memory is allocated but when it is instantiated (i.e., an object is created) memory is allocated.

Defining a Class

To define a class in JavaScript, you use the class keyword, followed by the name of the class with a pair of curly braces {}.

class MyClass {
  // class methods and properties go here
}

Creating an Object

After a class is defined, you can use the new keyword to create an object from the class.

let obj = new MyClass();

3. Code Examples

Example 1: Defining a Class and Creating an Object

class Car {
  constructor(brand) {  // Constructor method is a special method for creating and initializing an object
    this.carBrand = brand;  // this keyword refers to the object it belongs to
  }
  present() {  // Class method
    return `I have a ${this.carBrand}`;
  }
}

let myCar = new Car("Toyota");
console.log(myCar.present());  // Logs: "I have a Toyota"

In this example, Car is a class and myCar is an object of the Car class. The Car class has a constructor which accepts a brand parameter and a method present to display the car's brand.

Example 2: Using Class Properties

class Car {
  constructor(brand) {
    this.carBrand = brand;
    this.year = new Date().getFullYear();  // Current year
  }
  age() {
    return `This ${this.carBrand} is ${new Date().getFullYear() - this.year} years old.`;
  }
}

let myCar = new Car("Toyota");
console.log(myCar.age());  // Logs: "This Toyota is 0 years old."

In this example, we added another property year to the Car class and a method age to calculate the car's age.

4. Summary

In this tutorial, you have learned the basics of creating classes and objects in JavaScript. You have also learned how to define methods and properties for a class and how to instantiate an object from a class.

The next steps in your learning could be understanding inheritance in JavaScript, and how classes can be extended. You may also wish to learn more about other features of ES6, such as arrow functions and promises.

5. Practice Exercises

  1. Define a class Rectangle that accepts width and height as parameters. Add a method area to calculate the area of the rectangle.

  2. Create an instance of Rectangle and calculate the area.

Solution

class Rectangle {
  constructor(width, height) {
    this.width = width;
    this.height = height;
  }
  area() {
    return this.width * this.height;
  }
}

let myRectangle = new Rectangle(5, 6);
console.log(myRectangle.area());  // Logs: 30

In this solution, we've created a Rectangle class with width and height properties. We've also added a method area that returns the product of width and height. When we create an instance of Rectangle and call the area method, it logs the area of the rectangle.

Need Help Implementing This?

We build custom systems, plugins, and scalable infrastructure.

Discuss Your Project

Related topics

Keep learning with adjacent tracks.

View category

HTML

Learn the fundamental building blocks of the web using HTML.

Explore

CSS

Master CSS to style and format web pages effectively.

Explore

Python

Explore Python for web development, data analysis, and automation.

Explore

SQL

Learn SQL to manage and query relational databases.

Explore

PHP

Master PHP to build dynamic and secure web applications.

Explore

Popular tools

Helpful utilities for quick tasks.

Browse tools

Watermark Generator

Add watermarks to images easily.

Use tool

Text Diff Checker

Compare two pieces of text to find differences.

Use tool

Interest/EMI Calculator

Calculate interest and EMI for loans and investments.

Use tool

Scientific Calculator

Perform advanced math operations.

Use tool

JavaScript Minifier & Beautifier

Minify or beautify JavaScript code.

Use tool

Latest articles

Fresh insights from the CodiWiki team.

Visit blog

AI in Drug Discovery: Accelerating Medical Breakthroughs

In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…

Read article

AI in Retail: Personalized Shopping and Inventory Management

In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …

Read article

AI in Public Safety: Predictive Policing and Crime Prevention

In the realm of public safety, the integration of Artificial Intelligence (AI) stands as a beacon of innovati…

Read article

AI in Mental Health: Assisting with Therapy and Diagnostics

In the realm of mental health, the integration of Artificial Intelligence (AI) stands as a beacon of hope and…

Read article

AI in Legal Compliance: Ensuring Regulatory Adherence

In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…

Read article

Need help implementing this?

Get senior engineering support to ship it cleanly and on time.

Get Implementation Help