Back to JavaScript
2025-12-059 min read

Class vs Struct (JavaScript)

Learn Class vs Struct (JavaScript) step by step with clear examples and exercises.

Why This Matters

In this extensive guide, we delve into the intricacies of JavaScript classes and structures, understanding their practical applications, common mistakes, and best practices. Mastering these concepts will equip you with the tools necessary to write efficient, maintainable code, tackle real-world programming challenges, and excel in your coding journey.

Why This Matters

Understanding the distinction between JavaScript classes and structures is crucial for writing clean, scalable, and efficient code. Both offer unique advantages depending on your specific use case, and being able to choose the right one can significantly improve your coding experience. Additionally, familiarity with these concepts is essential for tackling real-world programming challenges, debugging complex applications, and preparing for technical interviews.

Prerequisites

Before diving into classes and structures, it's important to have a solid foundation in the following topics:

  1. Basic JavaScript syntax and data types (variables, functions, arrays, objects)
  2. Understanding of control flow statements (if/else, switch, loops)
  3. Familiarity with object-oriented programming concepts (encapsulation, inheritance, polymorphism)
  4. Experience working with ES6 features such as arrow functions, template literals, and destructuring assignments
  5. Understanding of the this keyword and its behavior in JavaScript
  6. Comprehension of common JavaScript design patterns like module patterns and Revealing Module Pattern
  7. Familiarity with modern build tools like Webpack, Babel, and npm

Core Concept

JavaScript Structures

In JavaScript, a structure is essentially an object literal that groups related properties and methods together. It's a simple way to create reusable data structures without the need for classes or prototypes. Here's an example of a structure representing a book:

const book = {
title: "The Catcher in the Rye",
author: "J.D. Salinger",
pages: 278,
read: false,

getTitle() {
return this.title;
},

setTitle(newTitle) {
this.title = newTitle;
}
};

In this example, we've added two methods to our structure: getTitle() and setTitle(). Structures are useful for creating simple data structures that don't require complex behavior or inheritance. However, they lack some of the benefits offered by classes, such as constructor functions, method chaining, and static methods.

Pros of Using Structures:

  1. Simple to define and use
  2. Ideal for small, self-contained objects with minimal behavior
  3. Can be easily converted into classes using tools like Babel

Cons of Using Structures:

  1. Lack of encapsulation (properties are publicly accessible)
  2. No method chaining or constructor functions
  3. Limited inheritance capabilities
  4. Not as intuitive for larger, more complex objects

JavaScript Classes

JavaScript classes provide a more structured way to organize code, offering features like constructors, inheritance, and static methods. Here's an example of a class representing a book:

class Book {
constructor(title, author, pages, read) {
this._title = title;
this._author = author;
this._pages = pages;
this._read = read || false;
}

get title() {
return this._title;
}

set title(newTitle) {
this._title = newTitle;
}

toggleReadStatus() {
this._read = !this._read;
}

static createBook(title, author, pages, read) {
return new Book(title, author, pages, read);
}
}

Classes are ideal for creating complex objects with multiple methods and properties, as well as for implementing inheritance to create hierarchies of related objects.

Pros of Using Classes:

  1. Encapsulation (hiding implementation details)
  2. Method chaining (easier to call multiple methods on an object)
  3. Inheritance (creating hierarchies of related objects)
  4. Static methods (methods that belong to the class itself rather than individual instances)
  5. More intuitive for larger, more complex objects

Cons of Using Classes:

  1. Slightly more verbose syntax compared to structures
  2. May be overkill for simple data structures that don't require complex behavior or inheritance
  3. Requires modern browsers (ES6+) to run without transpilation

Worked Example

Let's compare the use of a structure and a class when managing a library of books:

Using a Structure

const library = [
{
title: "The Catcher in the Rye",
author: "J.D. Salinger",
pages: 278,
read: false
},
// Add more books here...
];

Using a Class

class Book {
constructor(title, author, pages, read) {
this._title = title;
this._author = author;
this._pages = pages;
this._read = read || false;
}

get title() {
return this._title;
}

set title(newTitle) {
this._title = newTitle;
}

toggleReadStatus() {
this._read = !this._read;
}

static createLibrary(booksArray) {
const library = booksArray.map(book => new Book(...book));
return library;
}
}

// Create a library using the Book class
const library = Book.createLibrary([
{ title: "The Catcher in the Rye", author: "J.D. Salinger", pages: 278, read: false },
// Add more books here...
]);

In this example, both approaches can be used to manage a library of books. However, using a class offers benefits like encapsulation (hiding implementation details), method chaining (easier to call multiple methods on an object), and inheritance (creating hierarchies of related objects). Additionally, the createLibrary() static method simplifies the process of creating a library from an array of books.

Common Mistakes

  1. Forgetting to initialize properties in the constructor: When creating a new instance of a class, always make sure to initialize all properties in the constructor.
class Book {
constructor(title, author) {
this._title = title; // Remember to initialize `pages` and `read` as well!
}
}
  1. Misusing inheritance: Inheritance can be a powerful tool, but it's important to use it judiciously. Avoid creating unnecessary hierarchies or overcomplicating your code with excessive inheritance.
  1. Not understanding the difference between classes and structures: It's essential to understand when to use each approach based on the specific requirements of your project.
  1. Incorrectly implementing getters and setters: Make sure that your getters return the correct value and your setters update the corresponding property correctly.
  1. Overusing classes: Remember that structures can be useful for simple data structures that don't require complex behavior or inheritance.
  1. Not using super when overriding methods in subclasses: When overriding a method in a subclass, always call the superclass implementation using the super keyword to ensure proper functionality.
  1. Confusing class properties and instance properties: Class properties (also known as static properties) are shared among all instances of a class, while instance properties belong to individual objects created from the class.
  1. Not understanding the difference between private and public properties: Private properties are not directly accessible outside of the class, while public properties can be accessed by any code that has access to an instance of the class.
  1. Not properly handling errors in constructors: Make sure to handle errors in constructors using try/catch blocks or by throwing custom errors when necessary.
  1. Not considering performance implications: While classes offer many benefits, they can also have a slight performance impact due to their additional syntax and runtime behavior. Be mindful of this when deciding whether to use a class or a structure for a given project.

Practice Questions

  1. Write a structure for representing a person with properties name, age, and occupation. Include methods to get and set the name, age, and occupation.
  2. Convert the person structure from question 1 into a class, adding a method called introduceYourself() that returns a string containing the person's name, age, and occupation.
  3. Create a class for a rectangle with properties width and height, and add a method called calculateArea() that returns the area of the rectangle.
  4. Write a class for a car with properties make, model, year, and color. Add a method called drive() that outputs a message indicating the car is driving, as well as a method called changeColor(newColor) that updates the car's color.
  5. Create a class for an animal with properties name, species, and age. Include a method called makeSound() that outputs a generic animal sound. Then create a subclass Dog that inherits from the Animal class, overrides the makeSound() method to output a specific dog sound, and adds a property breed.
  6. Write a class for a bank account with properties balance, owner, and interestRate. Add methods called deposit(amount), withdraw(amount), and calculateInterest(). Implement the calculateInterest() method to calculate and return the interest earned on the account's balance.
  7. Create a subclass SavingsAccount that inherits from the BankAccount class, adding a property called minimumBalance and overriding the withdraw(amount) method to ensure that the account's balance never falls below the minimum balance.
  8. Write a class for a shopping cart with properties items (an array of objects representing items in the cart), and totalPrice. Add methods called addItem(item), removeItem(item), and calculateTotal(). Implement the calculateTotal() method to calculate and return the total price of all items in the cart.
  9. Create a subclass DiscountedShoppingCart that inherits from the ShoppingCart class, adding a property called discountPercentage (a number representing the percentage discount applied to each item). Override the calculateTotal() method to calculate and return the total price of all items in the cart after applying the discount.
  10. Write a class for a person with properties name, age, occupation, and skills. Add methods called learnSkill(newSkill), forgetSkill(skillToForget), and displaySkills() that outputs a list of the person's current skills.
  11. Create a subclass Student that inherits from the Person class, adding properties enrollmentYear and major. Override the learnSkill(newSkill) method to ensure that students can only learn new skills if they have not already forgotten them.

FAQ

Why use classes instead of structures?

Classes offer benefits like encapsulation, method chaining, inheritance, and static methods, making them ideal for creating complex objects with multiple methods and properties. Additionally, classes provide a more structured way to organize code and can make it easier to manage larger projects.

Can I convert a class into a structure (or vice versa)?

While it's possible to represent some of the functionality of a class using a structure, there are limitations, such as lack of method chaining and encapsulation. It's generally best to choose the appropriate approach based on your specific needs. However, modern JavaScript tools like Babel can automatically convert ES6 classes into ES5-compatible constructor functions for compatibility with older browsers.

What is the difference between a constructor function and a class?

A constructor function is a special function used to create objects in JavaScript, while a class provides a more structured way to organize code with added features like method chaining and inheritance. In modern JavaScript, classes are syntactic sugar for constructor functions. However, constructor functions can be more flexible in certain situations, such as when creating objects without a specific class definition or when working with older browsers that don't support classes natively.

How do I implement private properties and methods in a class?

In JavaScript, there is no true private syntax like in some other languages. However, you can achieve similar behavior by using underscores (_) to denote private properties and by not defining getters or setters for these properties. Private methods can be implemented as methods that are only called within the class itself.

How do I implement static methods in a class?

Static methods are methods that belong to the class itself rather than individual instances of the class. In JavaScript, you can define static methods by prefixing them with the static keyword. Here's an example:

class Book {
static createBook(title, author, pages, read) {
return new Book(title, author, pages, read);
}

// Other methods...
}

In this example, createBook() is a static method that creates a new instance of the Book class without needing to call the constructor directly.

How do I implement inheritance in JavaScript?

Inheritance can be achieved by using the ``

Class vs Struct (JavaScript) | JavaScript | XQA Learn