JavaScriptAdvanced JavaScript Concepts

JavaScript Modules (import & export)

Learn JavaScript modules, how to use export and import, and how modular code helps build scalable, maintainable, and professional JavaScript applications.

What are Modules in JavaScript?Link to this section

Modules allow JavaScript code to be split into separate files, where each file handles a specific responsibility. This makes code easier to manage, reuse, and maintain. Instead of writing all code in one large file, modules help organize logic into meaningful units.

Why Modules are Important?Link to this section

Modules help developers:
  • Avoid global scope pollution
  • Reuse code across files
  • Improve readability and structure
  • Scale applications easily
Modern frameworks and large applications rely heavily on modular architecture.

What is export?Link to this section

The export keyword is used to share variables, functions, or classes from one file so they can be used in another file.

tip

Named exports allow exporting multiple values from a single file.

What is import?Link to this section

The import keyword is used to bring exported code into another file.

note

The imported names must match the exported names exactly.

Default Export:Link to this section

A file can have only one default export, which is commonly used for primary functionality.

note

Default exports can be imported using any name.

Mixing Named and Default Exports:Link to this section

A module can have both named and default exports.

Module Scope:Link to this section

Each module has its own scope. Variables declared in a module are not global unless explicitly exported. This prevents accidental conflicts and improves security.

Using Modules in the Browser:Link to this section

To use JavaScript modules in the browser, scripts must be marked as modules. Explanation text: Scripts are loaded with type="module" so the browser understands module syntax.

Modules in Real-World Applications:Link to this section

Modules are used for:
  • Utility functions
  • API services
  • UI components
  • Configuration files
  • Business logic separation

tip

If a file grows too large, it’s a good candidate to become multiple modules.

Common Module Mistakes:Link to this section

  • Forgetting to export required items
  • Incorrect import paths
  • Mixing module and non-module scripts
  • Circular dependencies

warning

Incorrect module paths are one of the most common runtime errors in JavaScript projects.
Check Your Understanding
Question 1 of 4

What is the purpose of JavaScript modules?

Practice Challenges

medium
  • Create a module that exports a function to calculate the square of a number.
  • Import multiple named exports from a module and use them.
  • Split a large JavaScript file into two meaningful modules.
  • Create a module with a default export for a calculator function.