# Object-Oriented JavaScript

Course: [JavaScript](https://www.devtutorials.ai/learn/javascript) · Section: Object-Oriented JavaScript
Source: https://www.devtutorials.ai/learn/javascript/oop/object-oriented-javascript

> Object properties and methods, accessing, adding, removing and displaying members, constructor functions with new and this, classes with constructors, instance properties and instance methods, and static methods and properties.

## What Is Object-Oriented JavaScript?

**OOP (object-oriented programming)** = organising code into objects that hold **data and actions together**.

- **Member** = a named value in an object: a **property** (data) or a **method** (a function).
- **Class** = a plan for making many similar objects.
- **Instance** = one object made from the plan, with `new`.

**Simple lesson:** write the plan once, then make as many objects from it as you need.

### A Real-World Example

A shop has 500 products. Each has a name, a price and a stock count, and each can say its stock value.
One `Product` class describes all of that once.
`new Product("Lunch box", 349)` makes one product; the shop makes 500 the same way.

<figure className="ts-fig">
  <svg viewBox="0 0 560 170" role="img" aria-label="A blueprint labelled class Product stamps out three product objects, each with its own name and price." width="100%">
    <rect x="0" y="0" width="560" height="170" rx="12" fill="#f8fafc" stroke="#e2e8f0" />
    <rect x="30" y="40" width="160" height="90" rx="10" fill="#1e3a8a" />
    <text x="110" y="68" textAnchor="middle" fontSize="13" fill="#ffffff">class Product</text>
    <text x="110" y="90" textAnchor="middle" fontSize="11" fontFamily="monospace" fill="#bfdbfe">constructor(name, price)</text>
    <text x="110" y="108" textAnchor="middle" fontSize="11" fontFamily="monospace" fill="#bfdbfe">stockValue()</text>
    <rect x="260" y="20" width="270" height="34" rx="8" fill="#eff6ff" stroke="#2563eb"><animate attributeName="opacity" values="0;1;1" keyTimes="0;0.2;1" dur="3s" repeatCount="indefinite" /></rect>
    <text x="395" y="42" textAnchor="middle" fontSize="12" fill="#1e40af">new Product("Notebook", 60)<animate attributeName="opacity" values="0;1;1" keyTimes="0;0.2;1" dur="3s" repeatCount="indefinite" /></text>
    <rect x="260" y="68" width="270" height="34" rx="8" fill="#eff6ff" stroke="#2563eb"><animate attributeName="opacity" values="0;0;1;1" keyTimes="0;0.3;0.5;1" dur="3s" repeatCount="indefinite" /></rect>
    <text x="395" y="90" textAnchor="middle" fontSize="12" fill="#1e40af">new Product("Lunch box", 349)<animate attributeName="opacity" values="0;0;1;1" keyTimes="0;0.3;0.5;1" dur="3s" repeatCount="indefinite" /></text>
    <rect x="260" y="116" width="270" height="34" rx="8" fill="#eff6ff" stroke="#2563eb"><animate attributeName="opacity" values="0;0;1;1" keyTimes="0;0.6;0.8;1" dur="3s" repeatCount="indefinite" /></rect>
    <text x="395" y="138" textAnchor="middle" fontSize="12" fill="#1e40af">new Product("Steel bottle", 299)<animate attributeName="opacity" values="0;0;1;1" keyTimes="0;0.6;0.8;1" dur="3s" repeatCount="indefinite" /></text>
  </svg>
  <figcaption>One class, many instances, each with its own data.</figcaption>
</figure>

One box fails on purpose to show the error a class gives without `new`. Its title says so.

## What You Will Learn

1. Object properties and methods, and adding, removing and displaying them.
2. Constructor functions and `new`.
3. Constructor parameters and `this`.
4. Classes: constructor, instances, instance properties and methods.
5. Static methods and static properties.

## JavaScript objects

An **object** groups named values. Think of a library book: details (title, pages) and actions (borrow, return).

### Object properties

A **property** is `name: value` inside `{ }`. The name is also called a **key**.

```js runnable title="An object with four properties"
const book = {
  title: "The Hobbit",
  author: "J. R. R. Tolkien",
  pages: 310,
  available: true,
};

console.log(book.title);
console.log(book.pages);
```

Expected output:

```text
The Hobbit
310
```

### Object methods

A **method** is a function stored as a property. Inside it, `this` is the object it belongs to.

```js runnable title="A method that uses the object's own properties"
const book = {
  title: "The Hobbit",
  available: true,
  borrow() {
    this.available = false;
    return `You borrowed ${this.title}`;
  },
};

console.log(book.borrow());
console.log("Still available?", book.available);
```

Expected output:

```text
You borrowed The Hobbit
Still available? false
```

### Accessing object members

Dot notation (`book.title`) most of the time. Brackets (`book["page count"]`) for spaces or names in variables.

```js runnable title="Dot notation and bracket notation reach the same member"
const book = { title: "Matilda", author: "Roald Dahl", "page count": 240 };

console.log(book.title);
console.log(book["author"]);
console.log(book["page count"]);

const field = "author";
console.log(book[field]);
```

Expected output:

```text
Matilda
Roald Dahl
240
Roald Dahl
```

### Adding properties

Assign to a new name, and the property is added. Assign to an existing name, and it changes.

```js runnable title="Assigning to a new name adds a property"
const book = { title: "Wonder", author: "R. J. Palacio" };

book.pages = 320;
book["genre"] = "Fiction";

console.log(book);
```

Expected output:

```text
{
  "title": "Wonder",
  "author": "R. J. Palacio",
  "pages": 320,
  "genre": "Fiction"
}
```

`const book` still lets you change properties. `const` only stops you from assigning a different object to `book`.

### Removing properties

`delete` removes a property. `in` checks whether the name exists.

```js runnable title="delete removes a property completely"
const book = { title: "Holes", author: "Louis Sachar", shelf: "B4" };

delete book.shelf;

console.log(book);
console.log("Has a shelf?", "shelf" in book);
```

Expected output:

```text
{
  "title": "Holes",
  "author": "Louis Sachar"
}
Has a shelf? false
```

### Displaying objects

- `console.log(obj)`: the whole object.
- `JSON.stringify(obj)`: one line of text.
- `` `${obj}` ``: just `[object Object]`. Use a property instead.
- A loop over `Object.entries(obj)`: your own format.

```js runnable title="Four ways to display the same object"
const book = { title: "Coraline", author: "Neil Gaiman", pages: 162 };

console.log(book);
console.log(JSON.stringify(book));
console.log(`Template string: ${book}`);

for (const [key, value] of Object.entries(book)) {
  console.log(`${key}: ${value}`);
}
```

Expected output:

```text
{
  "title": "Coraline",
  "author": "Neil Gaiman",
  "pages": 162
}
{"title":"Coraline","author":"Neil Gaiman","pages":162}
Template string: [object Object]
title: Coraline
author: Neil Gaiman
pages: 162
```

In a browser console, `console.table()` shows a table (not available in these boxes):

```js
console.table({ title: "Coraline", author: "Neil Gaiman", pages: 162 });
```

```text
┌─────────┬───────────────┐
│ (index) │ Values        │
├─────────┼───────────────┤
│ title   │ 'Coraline'    │
│ author  │ 'Neil Gaiman' │
│ pages   │ 162           │
└─────────┴───────────────┘
```

## Object constructors

Writing 100 similar objects by hand is slow and error-prone. A constructor makes them for you.

### Constructor functions

A normal function that fills in `this`, with a **capital** first letter by convention. No `{ }` object, no `return`.

```js runnable title="A constructor function that builds cars"
function Car(make, model) {
  this.make = make;
  this.model = model;
  this.speed = 0;
}

const myCar = new Car("Tata", "Nexon");
console.log(myCar);
```

Expected output:

```text
{
  "make": "Tata",
  "model": "Nexon",
  "speed": 0
}
```

### Creating objects using `new`

`new` makes an empty object, runs the constructor with `this` set to it, and returns it. Each result is a separate **instance**.

```js runnable title="Each call with new creates a separate object"
function Car(make, model) {
  this.make = make;
  this.model = model;
  this.speed = 0;
}

const first = new Car("Tata", "Nexon");
const second = new Car("Honda", "City");

second.speed = 60;

console.log(first.make, first.speed);
console.log(second.make, second.speed);
console.log("Same object?", first === second);
```

Expected output:

```text
Tata 0
Honda 60
Same object? false
```

Always use `new` with a constructor function. Without it, nothing comes back, and the properties leak onto the global object.

```js runnable title="Forgetting new: no object comes back"
function Car(make, model) {
  this.make = make;
  this.model = model;
}

const forgotNew = Car("Tata", "Nexon");
console.log("What came back:", forgotNew);
console.log("Where make ended up:", globalThis.make);
```

Expected output:

```text
What came back: undefined
Where make ended up: Tata
```

### Constructor parameters

Parameters give each instance its own data. A **default value** fills in a missing one.

```js runnable title="Parameters, with a default for the colour"
function Car(make, model, colour = "white") {
  this.make = make;
  this.model = model;
  this.colour = colour;
}

const taxi = new Car("Maruti", "Dzire", "yellow");
const family = new Car("Hyundai", "Creta");

console.log(taxi.colour);
console.log(family.colour);
```

Expected output:

```text
yellow
white
```

### The `this` keyword

- In a constructor called with `new`: `this` is the new object.
- In `object.method()`: `this` is the object before the dot.

```js runnable title="this is the object before the dot"
function Car(make, model) {
  this.make = make;
  this.model = model;
  this.speed = 0;
  this.accelerate = function (amount) {
    this.speed += amount;
    return `${this.make} ${this.model} is now doing ${this.speed} km/h`;
  };
}

const nexon = new Car("Tata", "Nexon");
const city = new Car("Honda", "City");

console.log(nexon.accelerate(40));
console.log(city.accelerate(25));
console.log(nexon.accelerate(20));
```

Expected output:

```text
Tata Nexon is now doing 40 km/h
Honda City is now doing 25 km/h
Tata Nexon is now doing 60 km/h
```

## JavaScript classes

### Introduction to classes

A **class** is a plan (like a house blueprint). You cannot live in the plan, but you can build many houses from it.

**Why "class"?** It describes a whole class, or category, of things.

### Creating classes

`class Name { constructor() {...} method() {...} }`. Setup and methods sit together in one block.

```js runnable title="A small Product class"
class Product {
  constructor(name, price) {
    this.name = name;
    this.price = price;
  }

  describe() {
    return `${this.name} costs $${this.price}`;
  }
}

const mug = new Product("Coffee mug", 8.5);
console.log(mug.describe());
```

Expected output:

```text
Coffee mug costs $8.5
```

### Constructor method

`constructor` runs **once per `new`**, to set up the object. One per class; leave it out and you get an empty one.

```js runnable title="The constructor runs once for each new object"
class Product {
  constructor(name, price) {
    console.log(`Setting up ${name}...`);
    this.name = name;
    this.price = price;
  }
}

const mug = new Product("Coffee mug", 8.5);
const lamp = new Product("Desk lamp", 24);
console.log("Created:", mug.name, "and", lamp.name);
```

Expected output:

```text
Setting up Coffee mug...
Setting up Desk lamp...
Created: Coffee mug and Desk lamp
```

### Creating object instances

`new Product(...)` makes an instance. `instanceof` checks which class made it.

```js runnable title="Two instances of the same class"
class Product {
  constructor(name, price) {
    this.name = name;
    this.price = price;
  }
}

const mug = new Product("Coffee mug", 8.5);
const lamp = new Product("Desk lamp", 24);

console.log(mug);
console.log("Is lamp a Product?", lamp instanceof Product);
```

Expected output:

```text
{
  "name": "Coffee mug",
  "price": 8.5
}
Is lamp a Product? true
```

A class **refuses** to run without `new`, so the silent mistake becomes a clear error:

```js runnable expect-error title="Calling a class without new throws an error"
class Product {
  constructor(name, price) {
    this.name = name;
    this.price = price;
  }
}

const mug = Product("Coffee mug", 8.5);
```

### Instance properties

Each instance has its own data: set it in the constructor (`this.name = ...`) or as a **class field** (`quantity = 0;`).

```js runnable title="Instance properties from the constructor and from a class field"
class Product {
  quantity = 0;

  constructor(name, price) {
    this.name = name;
    this.price = price;
  }
}

const mug = new Product("Coffee mug", 8.5);
const lamp = new Product("Desk lamp", 24);

mug.quantity = 12;

console.log(mug.name, mug.quantity);
console.log(lamp.name, lamp.quantity);
```

Expected output:

```text
Coffee mug 12
Desk lamp 0
```

### Instance methods

Methods in the class body are stored **once** and shared; inside each call, `this` is the instance that called it.

```js runnable title="Instance methods read and change the instance's own data"
class Product {
  quantity = 0;

  constructor(name, price) {
    this.name = name;
    this.price = price;
  }

  restock(amount) {
    this.quantity += amount;
    return this.quantity;
  }

  stockValue() {
    return this.quantity * this.price;
  }
}

const mug = new Product("Coffee mug", 8.5);
const lamp = new Product("Desk lamp", 24);

mug.restock(10);
lamp.restock(3);

console.log("Mug stock value:", mug.stockValue());
console.log("Lamp stock value:", lamp.stockValue());
console.log("Do they share one method?", mug.stockValue === lamp.stockValue);
```

Expected output:

```text
Mug stock value: 85
Lamp stock value: 72
Do they share one method? true
```

The constructor sets up each instance's own data; methods describe what every instance can do.

## Static members

**Static** = belongs to the **class itself**, not to one instance. Use it through the class name.

### Static methods

Work about the class as a whole, like comparing two products or building one from text. Instances cannot call it.

```js runnable title="A static method is called on the class, not an instance"
class Product {
  constructor(name, price) {
    this.name = name;
    this.price = price;
  }

  static cheaper(first, second) {
    return first.price <= second.price ? first : second;
  }

  static fromText(text) {
    const [name, price] = text.split(":");
    return new Product(name, Number(price));
  }
}

const mug = new Product("Coffee mug", 8.5);
const lamp = Product.fromText("Desk lamp:24");

console.log("Cheaper:", Product.cheaper(mug, lamp).name);
console.log("Built from text:", lamp.name, lamp.price);
console.log("Can an instance call it?", typeof mug.cheaper);
```

Expected output:

```text
Cheaper: Coffee mug
Built from text: Desk lamp 24
Can an instance call it? undefined
```

### Static properties

One shared value for the whole class, like a counter or a currency setting.

```js runnable title="A shared counter and a shared setting"
class Product {
  static count = 0;
  static currency = "USD";

  constructor(name, price) {
    this.name = name;
    this.price = price;
    Product.count += 1;
  }

  label() {
    return `${this.name}: ${this.price} ${Product.currency}`;
  }
}

const mug = new Product("Coffee mug", 8.5);
const lamp = new Product("Desk lamp", 24);
const pen = new Product("Gel pen", 1.25);

console.log("Products created:", Product.count);
console.log(pen.label());
```

Expected output:

```text
Products created: 3
Gel pen: 1.25 USD
```

Inside a class, write `Product.count`, not `this.count`, for a static member.

## Classes on a Web Page

A `Product` class with an instance method and a static counter. Each button calls `sell()` on its own instance.

```js runnable preview="product-list" title="Product objects made from one class"
class Product {
  static count = 0;

  constructor(name, price, stock) {
    this.name = name;
    this.price = price;
    this.stock = stock;
    Product.count += 1;
  }

  sell() {
    if (this.stock > 0) this.stock -= 1;
  }

  label() {
    return `${this.name} — ₹${this.price} (${this.stock > 0 ? this.stock + " left" : "sold out"})`;
  }
}

const products = [new Product("Notebook", 60, 3), new Product("Lunch box", 349, 1), new Product("Steel bottle", 299, 5)];
const list = document.querySelector("#products");
document.querySelector("#status").textContent = `${Product.count} products made from one class`;

for (const product of products) {
  const li = document.createElement("li");
  const text = document.createElement("span");
  const buy = document.createElement("button");
  buy.textContent = "Sell one";
  text.textContent = product.label() + " ";
  buy.addEventListener("click", () => {
    product.sell();
    text.textContent = product.label() + " ";
    console.log(product.name, "stock:", product.stock);
  });
  li.append(text, buy);
  list.append(li);
}
```

**Easy way to remember:** **class** = cookie cutter, **instance** = cookie, **static** = a label on the cutter itself.

## TL;DR

- Objects hold properties (data) and methods (actions); `this` is the object before the dot.
- Constructor functions need `new`; classes throw a clear error without it.
- `constructor` runs once per instance; methods are shared.
- Class fields like `quantity = 0;` give each instance a starting value.
- `static` members belong to the class: `Product.count`, `Product.cheaper(a, b)`.

## Try this

In the static properties example, add `new Product("Notebook", 3)` and change `currency` to `"INR"`. The count becomes 4, and every label shows `INR`.

## Check Yourself

## Common mistakes

| Mistake | Wrong idea | Correct idea | What goes wrong |
|---|---|---|---|
| `Car("Tata", "Nexon")` | `new` is optional | Always `new`, or use a class | `undefined` and stray globals |
| `Product("Mug", 8)` | Classes are functions | Classes need `new` | `cannot be invoked without 'new'` |
| `` `${book}` `` | It prints the object | It prints `[object Object]` | Unreadable output |
| `mug.cheaper(...)` | Instances have static methods | Call `Product.cheaper(...)` | `is not a function` |
| `price` inside a method | Methods see properties directly | Use `this.price` | `undefined` or an error |
| `obj.key = undefined` to remove | That deletes it | Use `delete` | The key stays |

## Quick reference

<div className="tscroll">

| Syntax | Meaning |
|---|---|
| `const book = { title: "Holes" };` | create an object with an object literal |
| `book.title` or `book["title"]` | read a property with dot or bracket notation |
| `book.pages = 233;` | add a new property, or change an existing one |
| `delete book.pages;` | remove a property |
| `"pages" in book` | check whether a property exists |
| `Object.entries(book)` | get every property as a `[key, value]` pair |
| `function Car(make) { this.make = make; }` | a constructor function |
| `new Car("Tata")` | create an instance from a constructor or a class |
| `class Product { constructor(name) { this.name = name; } }` | a class with a constructor method |
| `quantity = 0;` inside a class | a class field, an instance property with a starting value |
| `describe() { ... }` inside a class | an instance method, shared by every instance |
| `static count = 0;` | a static property, stored on the class |
| `static compare(a, b) { ... }` | a static method, called as `ClassName.compare(...)` |
| `mug instanceof Product` | check whether an object was made from a class |

</div>

## Exercises

## What to Remember

- Objects bundle data with behaviour.
- Classes are plans; instances are the objects.
- Static members belong to the class.

Next: **Core OOP Principles**. Encapsulation, inheritance, polymorphism and abstraction.
