Search⌘ K
AI Features

Modules in JavaScript

Explore how JavaScript modules enable you to encapsulate and share code across files using export and import keywords. Learn the difference between named and default exports and how modular code improves your projects' readability and scalability.

JavaScript modules are reusable, encapsulated pieces of code that can be imported or exported between files. They help organize large codebases into smaller, manageable parts, improving readability and maintainability. Modules also prevent variable and function name conflicts by creating separate scopes.

Exporting in JavaScript

Exports allow us to make functions, objects, or variables available to other modules. There are two main types of exports:

  • Named exports: Allow us to export multiple items by name.

  • Default export: Allow us to export a single item as the default for the module.

// Named exports
export const name = "JavaScript";
export function greet() {
console.log("Hello!");
}
// Default export
const version = "ES6";
export default version;
Syntax for exporting modules

Importing in JavaScript

Imports allow us to use code from other modules in the current module. We can ...