← Back to JavaScript
15

Classes in JavaScript: constructor, methods and instances

Learn how to use `class` syntax to create objects with the same structure, initialize properties through a constructor and encapsulate behavior inside instance methods.

📘 Theory

When a class actually helps

Use classes when you need several entities with the same data and behavior.

If you only have one configuration object, a literal object is usually enough. If you need many projects, users, tasks or products, a class reduces repetition and makes the contract easier to read.

A class also helps keep data and behavior together, which makes maintenance easier when the feature grows.

1

Mold

2

Instance

3

Method

Constructor and `new`

The constructor initializes each instance with the data it needs.

1

The `constructor` runs automatically when you call `new ClassName(...)`. That is where you assign the initial properties with `this`.

2

Every call to `new` creates an independent object, even when all of them come from the same class.

Instance methods

A method reads or changes the state of one specific instance.

1

Inside a method, `this` points to the instance that runs it. That is why `landing.toggleFavorite()` only changes `landing` and not the rest.

2

This pattern avoids duplicating external helper functions that always need the same object passed in as an argument.

🧪 Learn by doing

Example Guided example: create two projects Define a class and create two instances with different initial values.
Example Interactive demo: projects created with `class` Create instances, render cards and mark projects as favorites through a class method.

🏁 Challenges

Challenge Challenge: a Task class Create a class with a constructor and a method to complete a task.

What is this?

I'm Cristian Eslava and I sometimes build websites so both you and I can learn and experiment. culTest

I made this in February 2026 to make learning easier for my students. The idea is to learn web development by practicing and to keep expanding the project with new topics, tests and challenges.

It draws inspiration from MDN, W3Schools, CodePen, Manz and many other web development references. I wanted to combine useful theory, runnable examples, challenges and the testing system I had already built for culTest. culTest

If you liked it, if you didn't, or if you want to get in touch, write to me at cristianeslava@gmail.com