Modules

Organize your code with ES modules and understand import/export syntax.

Present State

ES Modules (ESM) have become the standard for structuring JavaScript code into reusable, maintainable components. Unlike older script-based approaches, modules enable clean separation of concerns by allowing explicit import and export of functionality. Modern browsers and Node.js natively support ES modules, promoting better code organization and reuse.

Code Example

Example of defining and using ES modules with import and export:

ES Modules: Export and Import

// file: mathUtils.js
export function add(a, b) {
  return a + b;
}

export const PI = 3.14159;

// file: app.js
import { add, PI } from './mathUtils.js';

console.log('Add:', add(2, 3)); // 5
console.log('PI:', PI);         // 3.14159
          

This code demonstrates:

  • How to export functions and constants using export.
  • How to import specific exports using import { ... } from.
  • Modular code organization improving maintainability and reuse.
  • The use of relative paths and the .js extension in imports.

Description

JavaScript ES Modules provide a standard way to structure and share code across files.

  • Export: Marks functions, variables, or classes as available for use in other files.
  • Import: Brings in exported code from other modules.
  • Supports named exports (multiple exports) and default exports (single export per file).
  • Helps avoid polluting the global namespace.
  • Supported natively in browsers with type="module" in script tags, and in Node.js with .mjs files or proper configuration.

Applications

  • Building scalable web applications by separating concerns.
  • Sharing utilities and helper functions across projects.
  • Using third-party libraries and frameworks that use modules.
  • Enabling tree shaking for optimized bundling.
  • Facilitating code maintenance and collaboration in teams.

Multiple Choice Questions

Q1: Which keyword is used to export a function in ES modules?

  • A. import
  • B. export
  • C. require
  • D. module.exports

Answer: B. export

Q2: How do you import a named export called foo from utils.js?

  • A. import foo from './utils.js'
  • B. import { foo } from './utils.js'
  • C. require('foo')
  • D. export { foo }

Answer: B. import { foo } from './utils.js'

Q3: What is the correct way to import a default export?

  • A. import foo from './module.js'
  • B. import { default as foo } from './module.js'
  • C. Both A and B
  • D. export default foo

Answer: C. Both A and B

Q4: What attribute must be added to a <script> tag to use ES modules in browsers?

  • A. async
  • B. defer
  • C. type="module"
  • D. src

Answer: C. type="module"