#1 Data Analytics Program in India
₹2,499₹1,499Enroll Now
4 min read
Question 20 of 50easy

What are JavaScript Modules?

Understanding ES6 modules import/export.

What You'll Learn

  • Named exports
  • Default exports
  • Dynamic imports

Named Exports

code.jsJavaScript
// math.js
export const PI = 3.14159;
export function add(a, b) {
  return a + b;
}
export function multiply(a, b) {
  return a * b;
}

// main.js
import { PI, add, multiply } from './math.js';
import { add as sum } from './math.js'; // Rename
import * as math from './math.js'; // Import all
math.add(1, 2);

Default Export

code.jsJavaScript
// User.js
export default class User {
  constructor(name) {
    this.name = name;
  }
}

// main.js
import User from './User.js';
import MyUser from './User.js'; // Can use any name

Mixed Exports

code.jsJavaScript
// api.js
export default function fetchData() { }
export const BASE_URL = 'https://api.example.com';

// main.js
import fetchData, { BASE_URL } from './api.js';

Dynamic Imports

code.jsJavaScript
// Lazy loading
const button = document.querySelector('#loadModule');
button.addEventListener('click', async () => {
  const module = await import('./heavyModule.js');
  module.doSomething();
});

// Conditional import
if (condition) {
  const { feature } = await import('./feature.js');
}