Thuta Learning
JavaScript
IntermediateProgrammingBeginner

OOP Introduction

JavaScriptLesson 1520 min

What you'll walk away with

  • Explain why state (data) and behavior (methods) are grouped into one object
  • Tell encapsulation, inheritance, polymorphism and abstraction apart with one example each
  • Create objects with new from both a constructor function and a class
  • Decide when a class helps and when plain objects and functions are simpler

Explain it simply

Explain it simply

Think of a bank passbook. The book holds your balance (the data), but deposits and withdrawals only happen through the bank counter's procedures (the behavior). You cannot just take a pencil and change the number. OOP is a way of writing programs that does the same thing: it keeps data together with the functions that are allowed to change it, inside one object.

When you need many similar objects, you do not write each one by hand; you stamp them out of a blueprint. In JavaScript that blueprint is a constructor function or a class, and the new keyword creates each fresh object, called an instance.

Problem → Why → Solution

The problem: when data and functions live apart, state goes wrong

In the shopping cart below, the items array and the total sit in one object, but the addItem() function that changes them lives outside it. Another part of the code calls cart.items.push() directly, so nobody updates the total. No error is thrown; the customer simply sees the wrong price.

cart.js
// Data and the function that changes it live apart
const cart = { items: [], total: 0 };

function addItem(cart, name, price) {
  cart.items.push({ name, price });
  cart.total += price;
}

addItem(cart, "Pen", 1.5);
cart.items.push({ name: "Book", price: 12 }); // skips addItem
console.log(cart.items.length, cart.total);    // 2 1.5  <- total is wrong

Why does this happen?

There is a rule, an invariant, that items and total must always change together, but no single place guards that rule. Anyone, anywhere, can edit the data. OOP prevents this kind of bug by bundling the data and its rules into one object and asking everyone to change it only through that object's methods.

Core concept: state plus behavior makes an object

OOP treats a program as a set of objects that talk to each other. Each object has state, the data stored in its properties, and behavior, the methods that use that data. When every thing in your domain, such as a User, an Order or a Cart, is represented by an object, the code starts to read like the real-world situation it models.

PrincipleWhat it meansCart example
EncapsulationBundle data with methods and change it only through themadd() checks the price before storing an item
InheritanceA child class reuses a parent's properties and methodsGiftCart reuses everything Cart can do
PolymorphismOne method name, different behavior per objectcart.total() and giftCart.total() each compute in their own way
AbstractionHide complex details behind a simple interfaceCallers call summary() without knowing how it is computed

JavaScript is not class-based like Java; it is prototype-based. An object reuses methods by linking to another object, its prototype. The class syntax added in ES2015 (ES6) is a more readable way of writing on top of that prototype system: typeof on a class still gives "function". Later lessons in this chapter look at prototypes in detail.

Using OOP does not mean building deep class hierarchies. Composition, where an object owns smaller objects and delegates work to them, is often simpler than inheritance. And when a function has no state of its own and only turns input into output, a plain function is clearer than a class.

Remember too that every instance owns its own state. new Cart("Su Su") and new Cart("Ko Ko") share a blueprint, yet their items arrays are completely separate. Adding a product to one cart never touches the other, which is something global variables cannot give you.

Mental model: a blueprint stamps out guarded objects
  1. Write one blueprint (a class)
  2. new stamps out a fresh instance
  3. Each instance holds its own state
  4. State changes only through methods

One blueprint, many objects, and every object keeps its own separate data.

General pattern

javascript
class Thing {
  constructor(value) {
    this.value = value;        // state
  }
  doSomething() {              // behavior
    return this.value;
  }
}

const instance = new Thing(initialValue);
instance.doSomething();

The constructor sets up a new object's state, and the methods in the class body are behavior every instance can use. new Thing(...) returns an instance, and you call its methods with instance.method().

Example: a constructor function next to a class

This example puts two ways of creating objects side by side. The top half is a constructor function, the style used before class syntax existed, and the bottom half is a modern class. Notice that both rely on the new keyword and on this.

oop-intro.js
// Constructor function (the older way)
function Person(name, age) {
  this.name = name;
  this.age = age;
  this.greet = function () {
    return `Hello, I'm ${this.name}`;
  };
}

const person1 = new Person("Aung Kyaw", 25);
console.log(person1.greet());
console.log(`Age: ${person1.age}`);

// ES6 class (the modern way)
class Animal {
  constructor(name) {
    this.name = name;
  }
  speak() {
    return `${this.name} makes a sound`;
  }
}

const dog = new Animal("Buddy");
console.log(dog.speak());

Code breakdown

  1. Line 2function Person(name, age) {

    The capitalised name is a convention meaning "call me with new". On its own it is an ordinary function.

  2. Line 5this.greet = function () {

    Because greet is created inside the constructor, every new call creates a brand-new function. A thousand instances means a thousand copies of greet; class methods avoid that.

  3. Line 10const person1 = new Person("Aung Kyaw", 25);

    new creates an empty object, runs Person with this pointing at it, and hands the finished object back into person1.

  4. Lines 16-18constructor(name) {

    A class constructor does the same job as the constructor function's body: it sets up the instance's starting state.

  5. Lines 19-21speak() {

    Methods in the class body are shared by every instance rather than copied. Calling dog.speak() makes this refer to dog, so it returns "Buddy makes a sound".

You should see
Hello, I'm Aung Kyaw
Age: 25
Buddy makes a sound

Seeing polymorphism in action

Polymorphism means a caller uses one method name without knowing the object's exact kind, and each object answers in its own way. The loop below never checks which shape it holds; it just calls area(). Adding a new kind of shape later does not require touching the loop at all.

shapes.js
class Square {
  constructor(side) { this.side = side; }
  area() { return this.side * this.side; }
}

class Circle {
  constructor(radius) { this.radius = radius; }
  area() { return Math.PI * this.radius ** 2; }
}

for (const shape of [new Square(3), new Circle(1)]) {
  console.log(shape.constructor.name, shape.area().toFixed(2));
}

In real projects

Where this shows up in real projects

In an e-commerce app, a Cart object owns its items and discount code and only lets them change through add(), remove() and total(). Rules such as "a price is never negative" and "a discount never exceeds the total" are written and tested in one place. The UI component simply calls cart.total() without needing to know how the number is worked out.

OOP is everywhere in the browser too. new Date(), new Map() and new URL("https://...") create instances of built-in classes, and methods like date.getFullYear() are abstraction at work: you use the date without knowing how it is stored inside. Node.js's EventEmitter, or the Player and Enemy objects in a game, are further examples of objects that keep state and behavior together.

Common mistakes

Common mistakes

1. Calling a constructor function without new

Writing const p = Person("Aung Kyaw", 25); creates no new object. In strict mode this is undefined, so this.name = name throws a TypeError; in sloppy mode the properties land on the global object and p is undefined. Calling a class without new throws a TypeError immediately, which is one reason classes are safer.

2. Bypassing the methods and editing properties directly

A direct edit such as cart.items.push(...) or account.balance = 1000000 skips every check the methods perform. Expose a method for changes you want to allow, and protect data that must never be edited from outside with private fields (#), covered in the next lesson.

3. Turning everything into a class

Wrapping a stateless helper like formatPrice(amount) in class PriceFormatter { format() {...} } only adds a new call and more this to worry about. If the logic owns no data, keep it a plain function.

Best practices

Best practices

  • Prefer class syntax over constructor functions in new code: forgetting new becomes an error and methods are shared automatically.
  • Leave an object in a valid state when the constructor finishes; never hand back a half-built instance.
  • Name classes with nouns (Cart, Invoice) and methods with verbs (add, calculateTotal) so that cart.add() reads like a sentence.
  • Give each class one job; once it grows past twenty methods, it is time to split it into smaller classes.

Mini challenge

Mini challenge: a Cart class that guards its rules

Fix the cart bug from the problem section by writing a Cart class that guards its own items and total.

  • constructor(owner) stores the owner and starts with an empty items array
  • add(name, price) rejects a price that is not a positive number and returns a result message
  • total() sums every item's price; do not keep the total in a separate variable
  • summary() returns "<owner> has <n> items, total <2 decimals>"
cart-class.js
class Cart {
  constructor(owner) {
    // TODO: store the owner and start with an empty items array
  }

  add(name, price) {
    // TODO: reject a price that is not a positive number
    // TODO: otherwise store { name, price } and return "Added <name>"
  }

  total() {
    // TODO: add up every item's price
  }

  summary() {
    // TODO: "<owner> has <n> items, total <total with 2 decimals>"
  }
}

// TODO: create a cart, add two good items and one bad one, print the summary

Expected: The console shows these four lines: Added Pen Added Book Rejected Ghost: invalid price Su Su has 2 items, total 13.50

Show hint

Detect a bad price with typeof price !== "number" || price <= 0. In total() you can use reduce((sum, item) => sum + item.price, 0), and summary() can call this.total().

Show solution
cart-class.js
class Cart {
  constructor(owner) {
    this.owner = owner;
    this.items = [];
  }

  add(name, price) {
    if (typeof price !== "number" || price <= 0) {
      return `Rejected ${name}: invalid price`;
    }
    this.items.push({ name, price });
    return `Added ${name}`;
  }

  total() {
    return this.items.reduce((sum, item) => sum + item.price, 0);
  }

  summary() {
    const count = this.items.length;
    return `${this.owner} has ${count} items, total ${this.total().toFixed(2)}`;
  }
}

const cart = new Cart("Su Su");
console.log(cart.add("Pen", 1.5));
console.log(cart.add("Book", 12));
console.log(cart.add("Ghost", -3));
console.log(cart.summary());

Quick quiz 1 / 3

Cart's add() rejects negative prices and items only change through methods. Which OOP principle is this?

Quick quiz 2 / 3

After class Animal {}, what does console.log(typeof Animal) print?

Quick quiz 3 / 3

With the example's Person constructor, after creating person1 and person2, what is person1.greet === person2.greet?

What to remember

  • An object keeps state (properties) and behavior (methods) together.
  • Encapsulation, inheritance, polymorphism and abstraction are the four pillars of OOP.
  • Whether you use a constructor function or a class, new creates a fresh instance.
  • JavaScript is prototype-based and class is syntax on top; composition and plain functions often beat deep hierarchies.

MDN — Using Classes — MDN Web Docs

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.

OOP Introduction | Thuta Learning