Understanding JavaScript Classes

Introduction: Why Classes in JavaScript?

When you first start programming, you often write code that executes line by line. As your projects grow, you might find yourself managing many related variables and functions. For example, if you are building an application with many users, you might have many names and greeting functions scattered around. This can become messy very quickly.

Object-Oriented Programming, or OOP, solves this problem by grouping data and behavior together. In JavaScript, we use a class as a blueprint. Imagine a blueprint for a house; the blueprint is not the house itself, but it tells you how to build one. Similarly, a class tells JavaScript how to create objects that contain specific information and can perform specific actions. This approach makes your code much more organized and professional.

Defining a Class with the class Keyword

To create this blueprint, we use the class keyword followed by a name. By convention, class names start with a capital letter. Inside the class, we use a special method called the constructor. This is a unique function that runs automatically whenever you create a new version of your class.

"use strict";

class Greeter {
  constructor(name) {
    this.name = name;
  }
}

In this example, the Greeter class has a constructor that takes a name as an argument. The keyword this refers to the specific object being created. By writing this.name = name, we are telling JavaScript to take the name we provided and save it inside that specific object. This allows every object created from this blueprint to remember its own unique data.

Adding Methods to a Class

A class is not just for storing data; it is also for defining behavior. We can add functions to our class, which are called methods when they live inside a class. These methods can access the data we stored in the constructor by using the this keyword again.

class Greeter {
  constructor(name) {
    this.name = name;
  }
  
  hello() {
    return `Hi, ${this.name}`;
  }
}

The hello method belongs to the Greeter class. When it runs, it looks at this.name to see which name belongs to the current object. It then returns a friendly string. Notice that we do not use the function keyword when defining methods inside a class; we simply write the name of the method followed by parentheses.

Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal