JS Learning

ES6+ Features

Lesson Progress0%

Section 4 of 4

Classes & Modules

Classes & Modules

Topic Overview

Take your time to understand each concept. Practice with the examples below!

Classes and modules help you organize code like a pro. Classes are blueprints for creating objects, while modules help you split code into separate files.

Classes - Object Blueprints:

Think of a class like a cookie cutter - you define the shape once, then create many cookies (objects) from it.

Basic Class:

class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
greet() {
return `Hi, I'm ${this.name}!`;
}
haveBirthday() {
this.age++;
return `Happy birthday! Now ${this.age} years old.`;
}
}
// Creating instances:
const alice = new Person("Alice", 25);
const bob = new Person("Bob", 30);
alice.greet(); // "Hi, I'm Alice!"
bob.haveBirthday(); // "Happy birthday! Now 31 years old."

Inheritance (extending classes):

class Student extends Person {
constructor(name, age, grade) {
super(name, age); // Call parent constructor
this.grade = grade;
}
study() {
return `${this.name} is studying for grade ${this.grade}`;
}
}
const emma = new Student("Emma", 16, 10);
emma.greet(); // Works! Inherited from Person
emma.study(); // "Emma is studying for grade 10"

Modules - Code Organization:

Modules let you split code into separate files and share functionality between them.

Exporting (sharing from a file):

// math.js
export const add = (a, b) => a + b;
export const multiply = (a, b) => a * b;
// Default export (one per file)
export default class Calculator { }

Importing (using in another file):

// app.js
import { add, multiply } from './math.js';
import Calculator from './math.js';
const sum = add(5, 3);
Why use classes and modules?
Organize related code together
Reuse code efficiently
Keep files manageable
Work in teams more easily
Build larger applications

Ready to practice? Try the exercise below to reinforce your learning!

Try it yourself

Create a simple class with constructor and methods.

Loading...