DEV Community

Midhul P
Midhul P

Posted on

1

How to use JavaScript Classes in real projects

JavaScript classes are a great way to organize code. Let’s see how you can use them in a simple To-Do List app.

Declaring a Class

We define a Task class to manage tasks:

class Task {
  constructor(description, dueDate) {
    this.description = description;
    this.dueDate = dueDate;
    this.isDone = false;
  }

  markAsDone() {
    this.isDone = true;
  }
}
Enter fullscreen mode Exit fullscreen mode

Creating Instances

You can create tasks like this:

const task1 = new Task('Write blog post', '2023-11-15');
task1.markAsDone();
console.log(task1); 
// Task { description: 'Write blog post', dueDate: '2023-11-15', isDone: true }
Enter fullscreen mode Exit fullscreen mode

Inheritance

Extend the Task class for specific types of tasks:

class ShoppingTask extends Task {
  constructor(description, dueDate, items) {
    super(description, dueDate);
    this.items = items;
  }
}

const shoppingTask = new ShoppingTask('Buy groceries', '2023-11-20', ['Apples', 'Milk']);
console.log(shoppingTask); 
Enter fullscreen mode Exit fullscreen mode

Static Methods & Getters/Setters

You can add static methods for sorting tasks and use getters and setters to manage data validation.

For a more detailed guide, check out my full post on Medium: How to Use JavaScript Classes in Real Projects.

AWS Q Developer image

Your AI Code Assistant

Generate and update README files, create data-flow diagrams, and keep your project fully documented. Built to handle large projects, Amazon Q Developer works alongside you from idea to production code.

Get started free in your IDE

Top comments (0)

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →