ES6 Classes and Modules
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.
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:
constructor
method is the main point for initializing the object
prototype
(not on the object itself)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:
super
calls the parent class's constructor
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 allow splitting code across files, making it clean and reusable.
// math.js export function add(a, b) { return a + b; }
export const PI = 3.14159;
// 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:
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.