Object-oriented programming (OOP) is an incredibly useful paradigm for structuring code. It allows you to create reusable components with encapsulated logic and organize codebases around objects instead of just functions.
While JavaScript doesn’t have classes built-in like other languages, it does support the basic building blocks of OOP like objects, methods, and inheritance. Mastering these core concepts can level up your JS skills drastically.
Let’s walk through the fundamentals for writing object-oriented JavaScript!
Objects 101
Objects in JavaScript are simply collections of key-value pairs. You define an object with curly braces {} and give it properties using the syntax name: value:
const person = {
name: "Alice",
age: 25
};
The person object here has a name property set to “Alice” and an age property set to 25.
You can access these properties using either dot notation or square bracket syntax:
console.log(person.name); // "Alice"
console.log(person["age"]); // 25