Course Content
Advanced JavaScript Mastery
Advanced JavaScript Mastery
Class Declaration
In this section, we will be concentrating on JavaScript classes.
Why Learn Classes in JavaScript?
Classes in JavaScript provide a more organized and cleaner way to create objects, especially for larger applications. They promote code reusability and structure and simplify inheritance. While not mandatory, classes help manage complexity and make code easier to read, maintain, and extend, especially when working with object-oriented principles.
What is a Class in JavaScript?
Think of a class like the blueprint an architect uses to design a house. The blueprint itself isn't a house, but it provides the instructions for building one. Every time you build a new house, you follow the same blueprint, but each house can have unique details—like different colors, materials, or custom features.
In the same way, a class in JavaScript is like a blueprint for creating objects. It defines the structure (properties) and behavior (methods) of those objects. Each time you create an object (an instance) from the class, it follows the same design, but its values can vary, just like how each house can look different.
How to Declare a Class
Declaring a class in JavaScript is simple. Use the class
keyword followed by the name of the class. The class body, where properties and methods are defined, is enclosed in curly braces {}
.
In this example, we declare a class named Animal
. Classes in JavaScript are not hoisted, meaning you must declare the class before using it.
The Constructor Method
If the class is the blueprint, the constructor
is like the construction crew that takes the blueprint and assembles the house. When you build a house (create an object), the crew (constructor
) assembles the foundation, walls, roof, and other components according to the instructions.
Similarly, the constructor
in a class
initializes the object's properties based on the arguments you pass - just like customizing the house’s paint color or floor type. Every time you create a new instance, the constructor
ensures the object is built with the correct details.
class Animal { constructor(name, type) { this.name = name; this.type = type; } } const lion = new Animal('Lion', 'Wild'); console.log(lion.name); // Output: Lion console.log(lion.type); // Output: Wild const pig = new Animal('Pig', 'Domestic'); console.log(pig.name); // Output: Pig console.log(pig.type); // Output: Domestic
The constructor
allows you to pass initial values when creating objects, making it flexible for initializing different objects with custom details.
Thanks for your feedback!