# Modern JavaScript — Classes, Inheritance, Modules, Map and Set

Source: https://skills101.in/learn/web-development/webdev-classes-modules-map-set — Skills101 free tutorial (Web Development). Updated 2026-11-21.

Small scripts can live in one file with a few functions. Real projects — a React app, an Express API — have hundreds of files. Modern JavaScript (ES6 and later, often written "ES2015+") gives you three tools for organising them: **classes** to group data with behaviour, **modules** to split code into files, and the **Map** and **Set** collections. You will see all three in every codebase you join.

## 1. Classes: a blueprint for objects

A **class** describes what an object holds (its **fields**) and what it can do (its **methods**). `new` creates an object (an **instance**) from it, and runs the `constructor`.

```javascript
class Student {
  constructor(name, marks) {
    this.name = name;
    this.marks = marks;
  }

  average() {
    const sum = this.marks.reduce((a, b) => a + b, 0);
    return sum / this.marks.length;
  }

  get grade() {                       // a getter: used like a property
    return this.average() >= 75 ? "Distinction" : "Pass";
  }
}

const asha = new Student("Asha", [88, 92, 79]);
console.log(asha.name, asha.average().toFixed(1), asha.grade);
console.log(typeof Student, asha instanceof Student);
```

```text
Asha 86.3 Distinction
function true
```

- Methods are written without the word `function`.
- A **getter** (`get grade()`) runs code but is read like a property: `asha.grade`, not `asha.grade()`.
- `typeof Student` is `"function"`: a class is special syntax over JavaScript's older **prototype** system (section 3).

## 2. Static and private members

```javascript
class BankAccount {
  static bankName = "Skills Bank";      // belongs to the class, not each object
  #balance = 0;                         // private: only code inside the class can use it

  constructor(owner) {
    this.owner = owner;
  }

  deposit(amount) {
    if (amount <= 0) throw new Error("Amount must be positive");
    this.#balance += amount;
    return this;                        // returning this allows chaining
  }

  get balance() {
    return this.#balance;
  }

  static compare(a, b) {
    return a.balance - b.balance;
  }
}

const ravi = new BankAccount("Ravi").deposit(500).deposit(250);
const neha = new BankAccount("Neha").deposit(900);
console.log(BankAccount.bankName, ravi.balance, neha.balance);
console.log(BankAccount.compare(ravi, neha) < 0 ? "Neha has more" : "Ravi has more");
console.log(Object.keys(ravi));
```

```text
Skills Bank 750 900
Neha has more
[ 'owner' ]
```

| Member | Written as | Accessed as | Use for |
|---|---|---|---|
| instance field | `this.owner = …` | `ravi.owner` | data each object has |
| private field | `#balance` | only inside the class | data that must not be changed from outside |
| static field/method | `static bankName` | `BankAccount.bankName` | shared constants, helper functions |
| getter | `get balance()` | `ravi.balance` | computed or read-only values |

`Object.keys(ravi)` lists only `owner`: private fields are truly hidden. Trying `ravi.#balance` outside the class is a **syntax error** — the program will not even start. This is **encapsulation**, the same OOP idea you meet in Java with `private`.

## 3. Inheritance with extends and super

A class can **extend** another, reusing its fields and methods and adding or changing some.

```javascript
class Course {
  constructor(title, price) {
    this.title = title;
    this.price = price;
  }
  label() {
    return `${this.title} — ₹${this.price}`;
  }
}

class LiveCourse extends Course {
  constructor(title, price, startDate) {
    super(title, price);               // must call the parent constructor first
    this.startDate = startDate;
  }
  label() {                            // override, but reuse the parent's version
    return `${super.label()} (starts ${this.startDate})`;
  }
}

const items = [new Course("SQL Basics", 499), new LiveCourse("Java Bootcamp", 9999, "6 Dec")];
for (const c of items) console.log(c.label());
console.log(items[1] instanceof Course);
console.log(Object.getPrototypeOf(LiveCourse.prototype) === Course.prototype);
```

```text
SQL Basics — ₹499
Java Bootcamp — ₹9999 (starts 6 Dec)
true
true
```

![LiveCourse.prototype links to Course.prototype, which links to Object.prototype; looking up label on a LiveCourse object finds LiveCourse's own label first, and super.label() reaches Course's version](https://skills101.in/learn-img/web-development/prototype-chain.svg)

- In a child constructor you must call `super(...)` **before** using `this`.
- Calling `label()` on each item runs the right version for that object — this is **polymorphism**.
- Under the hood, objects are linked in a **prototype chain**. When a method is not found on the object, JavaScript looks at its prototype, then that prototype's prototype, and so on — the same "look outward" idea as the scope chain.

**Tip:** prefer **composition** (an object that *has* other objects) over deep inheritance chains. One or two levels of `extends` is common; five is a warning sign.

## 4. Modules: splitting code into files

A **module** is a file with its own scope. Nothing inside it is visible to other files unless you **export** it, and other files must **import** it.

![price.js exports GST, withGst and a default formatRupees; app.js imports formatRupees, withGst and GST from ./price.js; anything not exported stays private](https://skills101.in/learn-img/web-development/module-graph.svg)

```javascript
// price.js
export const GST = 0.18;
export function withGst(amount) {
  return Math.round(amount * (1 + GST));
}
export default function formatRupees(n) {
  return "₹" + n.toLocaleString("en-IN");
}
```

```javascript
// app.js
import formatRupees, { withGst, GST } from "./price.js";
import * as price from "./price.js";

console.log(formatRupees(withGst(4999)));   // ₹5,899
console.log(GST === price.GST);              // true
```

| Export style | Export | Import |
|---|---|---|
| **named** (many per file) | `export function withGst…` | `import { withGst } from "./price.js"` |
| **default** (one per file) | `export default function…` | `import anyName from "./price.js"` |
| rename | | `import { withGst as addTax } from …` |
| everything | | `import * as price from …` |

Named exports are usually preferred: the names are checked, and editors can auto-import them.

### ES modules vs CommonJS

You will see two module systems in Node.js projects:

| | ES modules (ESM) | CommonJS (CJS) |
|---|---|---|
| Syntax | `import` / `export` | `require()` / `module.exports` |
| Where | browsers, React, modern Node | older Node code, many tutorials |
| Turn it on in Node | `"type": "module"` in package.json, or `.mjs` files | default for `.js` files |

```javascript
// CommonJS: works in a plain .js file run with node
const path = require("path");
module.exports = { join: path.join };
console.log(typeof module.exports.join);
```

```text
function
```

In the browser, load a module with `<script type="module" src="app.js"></script>`. Module scripts are deferred automatically and run in strict mode.

## 5. Map and Set

Plain objects and arrays can do a lot, but two built-in collections are often a better fit.

```javascript
const attendance = ["Asha", "Ravi", "Asha", "Neha", "Ravi", "Asha"];

const unique = new Set(attendance);              // removes duplicates
console.log(unique.size, [...unique]);
console.log(unique.has("Neha"));

const count = new Map();
for (const name of attendance) {
  count.set(name, (count.get(name) ?? 0) + 1);
}
console.log(count);
console.log([...count].sort((a, b) => b[1] - a[1])[0]);
```

```text
3 [ 'Asha', 'Ravi', 'Neha' ]
true
Map(3) { 'Asha' => 3, 'Ravi' => 2, 'Neha' => 1 }
[ 'Asha', 3 ]
```

| Use | When |
|---|---|
| `Set` | a collection of **unique** values; fast `has` checks |
| `Map` | key → value pairs where keys can be **any type** (numbers, objects); keeps insertion order; has `size` |
| plain object | fixed, known keys (a user record), and anything you send as JSON |

`Map` and `Set` do not convert to JSON directly — `JSON.stringify(new Map())` gives `"{}"`. Convert first, for example with `Object.fromEntries(map)`.

## Common mistakes

- Forgetting `new` when creating an instance (`Student("Asha")` throws a TypeError for classes).
- Using `this` in a child constructor before calling `super()`.
- Mixing `require` and `import` in the same file without understanding which system the project uses.
- Forgetting the `.js` extension in browser and Node ESM imports (`"./price"` fails; `"./price.js"` works).
- Using an object as a dictionary with user-supplied keys like `"__proto__"`; a `Map` avoids that problem.

## Quick recap

- `class` + `constructor` + methods; `new` creates instances; getters look like properties.
- `static` belongs to the class; `#private` fields cannot be touched from outside.
- `extends` + `super()` for inheritance; objects are linked by the prototype chain.
- ES modules: `export` / `import` (named and default); CommonJS: `require` / `module.exports`.
- `Set` for unique values; `Map` for flexible key → value pairs.


Practice quiz and free certificate: https://skills101.in/learn/web-development/webdev-classes-modules-map-set