JavaScript Classes
What is a Class?
In JavaScript, a Class is essentially a blueprint for creating objects. Before ES6 (ECMAScript 2015), JavaScript developers had to use functions and the prototype chain to achieve object-oriented programming. Classes provide a much cleaner, more intuitive syntax for doing this.
You can think of a class like an architectural blueprint for a house. The blueprint itself isn't a house, but it tells you exactly how to build one.
Defining a Class
To define a class in JavaScript, you use the class keyword followed by the name of the class. By convention, class names should always start with a capital letter (PascalCase).
class User {
// We will define properties and methods here
login() {
console.log("User has logged in.");
}
}
Now that we have a User class, we can create actual user objects (instances) from it.
const himanshu = new User();
himanshu.login(); // Outputs: "User has logged in."
Why Use Classes?
When you are building large applications, you will often need to create many objects that share the same structure. For example, in a blog application, every single article will have a title, an author, and content. Instead of writing out an object from scratch every time, a Post class ensures every article is built correctly and shares the same methods.
💡 Himanshu's Tip:
Under the hood, JavaScript classes are actually "syntactic sugar" over JavaScript's existing prototype-based inheritance. This means JavaScript isn't a traditional class-based language like Java or C++, but the class syntax makes it much easier to write and read Object-Oriented code!
Interview Questions
- What is the difference between a class and an object?
- Were classes always a part of JavaScript? If not, when were they introduced?
- What naming convention should you use when naming a class?