0
0
JavascriptHow-ToBeginner · 3 min read

How to Create Class in JavaScript: Syntax and Examples

In JavaScript, you create a class using the class keyword followed by the class name and curly braces. Inside, you define a constructor method for initializing objects and other methods for behavior.
📐

Syntax

A JavaScript class is defined using the class keyword followed by the class name. Inside the class, the constructor method sets up initial values when creating an object. Other methods define the behavior of the class instances.

  • class ClassName { ... }: Declares the class.
  • constructor(params) { ... }: Initializes new objects.
  • methodName() { ... }: Defines a method for the class.
javascript
class Person {
  constructor(name, age) {
    this.name = name;
    this.age = age;
  }

  greet() {
    return `Hello, my name is ${this.name} and I am ${this.age} years old.`;
  }
}
💻

Example

This example shows how to create a Person class, instantiate an object, and call its method to get a greeting message.

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

  greet() {
    return `Hello, my name is ${this.name} and I am ${this.age} years old.`;
  }
}

const person1 = new Person('Alice', 30);
console.log(person1.greet());
Output
Hello, my name is Alice and I am 30 years old.
⚠️

Common Pitfalls

Common mistakes when creating classes in JavaScript include:

  • Forgetting to use new when creating an instance, which causes this to be undefined.
  • Not defining a constructor method when you need to initialize properties.
  • Using arrow functions for methods, which can cause incorrect this binding.

Always use regular function syntax for methods and the new keyword to create objects.

javascript
/* Wrong: Missing 'new' keyword */
class Car {
  constructor(make) {
    this.make = make;
  }
}

const car1 = Car('Toyota'); // Error: 'this' is undefined

/* Right: Using 'new' keyword */
const car2 = new Car('Toyota');
console.log(car2.make); // Outputs: Toyota
Output
Toyota
📊

Quick Reference

Remember these key points when creating classes in JavaScript:

  • Use class ClassName {} to define a class.
  • Use constructor() to set up initial values.
  • Create methods without the function keyword.
  • Use new ClassName() to create an instance.
  • Do not use arrow functions for class methods.

Key Takeaways

Use the class keyword and constructor method to create classes in JavaScript.
Always use the new keyword to create instances of a class.
Define methods with regular function syntax inside the class, not arrow functions.
The constructor initializes object properties when a new instance is created.
Avoid common mistakes like forgetting new or misusing this inside methods.