ES6 Classes and Modules in JavaScript
ES6 (ECMAScript 2015) introduced new class and module syntax that added modern Object-Oriented Programming features to JavaScript while maintaining the language's dynamic nature. In this article, we'll discuss how ES6 classes work, how to use inheritance, and how ES modules function - periodically comparing them with the classic function-based approach.
Basic ES6 Class Syntax
In ES6, the class syntax acts as sugar over the underlying prototype-based inheritance. It's simply more readable and closer to the thinking patterns of Java or C# developers.
class Person { constructor(name, age) { this.name = name; this.age = age; }
greet() { console.log(Hi, I'm ${this.name} and I'm ${this.age} years old.); } }
const john = new Person('John', 30); john.greet(); // Hi, I'm John and I'm 30 years old.
Important considerations:
-
The
constructormethod is the main point for initializing the object - All methods are automatically added to the
prototype(not on the object itself)
Inheritance with ES6 Classes
ES6 provides extends and super keywords for creating inheritance.
class Employee extends Person { constructor(name, age, position) { super(name, age); this.position = position; }
describe() { console.log(${this.name} is a ${this.position}.); } }
const anna = new Employee('Anna', 28, 'Developer'); anna.greet(); // Hi, I'm Anna and I'm 28 years old. anna.describe(); // Anna is a Developer.
Notes:
-
supercalls the parent class's constructor - The child class can add or override methods
Static Methods and Properties
Class methods can be static - directly tied to the class rather than the object.
class MathUtil { static add(a, b) { return a + b; } }
console.log(MathUtil.add(5, 3)); // 8
Useful for: defining utility functions or helper methods.
ES6 Modules (import/export)
ES6 modules allow splitting code across files, making it clean and reusable.
Module: math.js
// math.js export function add(a, b) { return a + b; }
export const PI = 3.14159;
Usage: main.js
// main.js import { add, PI } from './math.js';
console.log(add(2, 3)); // 5 console.log(PI); // 3.14159
Alternative: default export
// logger.js export default function log(message) { console.log(`[LOG]: ${message}`); }
// app.js import log from './logger.js'; log('Hello world');
Advantages of modules:
- Scoped variables (don't leak to global scope)
- Code organization and separation of concerns
- Tree-shaking capability - removing unused code from builds
Conclusion
ES6 classes and modules brought structure and organization to JavaScript. They allow writing cleaner, more scalable, and reusable code. With modules, you can organize large projects and separate responsibilities across files.