Modules and Classes in JavaScript
Organizing Code with Modules
Modules in JavaScript provide a way to organize and structure code by encapsulating related functionality into separate files. This modular approach helps maintainability, readability, and reusability.
Creating a Module (exampleModule.js):
// exampleModule.js
// Private variable
let privateVar = "I am private";
// Public function
function publicFunction() {
console.log("This is a public function");
}
// Public variable
export let publicVar = "I am public";
// Exporting a function
export function exportedFunction() {
console.log("I am an exported function");
}Using the Module in Another File:
// main.js
// Importing variables and functions from the module
import { publicVar, exportedFunction } from "./exampleModule";
console.log(publicVar); // Outputs: I am public
exportedFunction(); // Outputs: I am an exported functionThe import and export keywords are used to specify what to import or export between modules.
Creating and Using Classes
Classes in JavaScript provide a way to define objects and their behaviors, enabling the creation of more structured and reusable code.
Example Class (Person.js):
// Person.js
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
sayHello() {
console.log(`Hello, my name is ${this.name} and I am ${this.age} years old.`);
}
}
export default Person;Using the Class in Another File:
// main.js
// Importing the class
import Person from "./Person";
// Creating an instance of the class
const john = new Person("John", 30);
// Using the class method
john.sayHello(); // Outputs: Hello, my name is John and I am 30 years old.Here, the Person class is defined in a separate file and then imported into another file for instantiation and use.
By leveraging modules and classes, JavaScript developers can create well-organized, reusable, and maintainable code. This modular and object-oriented approach is particularly beneficial in larger codebases and team-based development, providing a clear structure for code organization and promoting code separation and encapsulation.