Object-Oriented Programming in JavaScript
Introduction
Object-oriented programming (OOP) organizes code around objects that combine data and behavior. Procedural code focuses on steps and functions. JavaScript supports both styles—and ES6 classes are syntactic sugar over prototypes. This chapter explains when OOP helps and how it fits the language you already use with objects and functions.
Prerequisites
Procedural vs Object-Oriented
Procedural — functions operate on separate data:
Object-oriented — data and methods live together:
Both are valid—choose clarity for the problem size.
Class and Object
- Class — blueprint (defines fields and methods)
- Object (instance) — one concrete thing built from that blueprint
Why Use Classes
Use classes when you have:
- Repeated structure — many users, orders, or nodes with the same fields
- Shared behavior —
save(),validate(),render()on each instance - Inheritance — specialized types extend a base (see inheritance)
For one-off config blobs, a plain object literal is often enough.
Encapsulation (Grouping + Hiding)
Keep related state inside the object; expose only what callers need:
Closures (see closures) are another way to hide state without classes.
JavaScript Is Multi-Paradigm
You will mix:
- Object literals and classes
- Functions and higher-order methods
- Modules and async APIs later in the course
Mini Example: Modeling a Task
FAQ
Is JavaScript “really” OOP?
Yes—objects and prototypes are core; class is the familiar syntax on top.
Should I avoid classes in favor of only functions?
Many codebases use both—classes for entity models, pure functions for transforms.
Class vs factory function?
Factories return plain objects without new; classes help when you need inheritance and instanceof.
What comes next?
Classes in JavaScript—syntax, instances, and methods.