Skip to article content
FrontendXLesson 14 / 30

Modules and Imports

Build a precise mental model of JavaScript values, scope, functions, objects, arrays and asynchronous behavior, then implement and debug real utilities from first principles instead of memorizing outputs.

intermediate · about 40 minutes · 6 exercises

  • Predict
  • Explain
  • Implement
  • Debug
  • Test
  • Interview

What you will be able to do

#
  • Explain the difference between named and default exports.
  • Describe how live bindings and module scope affect behavior.
  • Load a module lazily with dynamic import and reason about cycles.

Overview

#

Module scope

Each ES module has its own scope. Top-level variables are not global, and imports are read-only bindings to another module's exports. Code in a module runs once, the first time the module is evaluated.

Named and default exports

A named export is imported by its exact name and supports tree shaking, because a bundler can see which names are used. A default export is imported under any local name and is convenient for a single main value, but it hides the exported name and can make refactoring harder.

snippet.js
// math.js
export const add = (a, b) => a + b;
export default function multiply(a, b) { return a * b; }

// main.js
import multiply, { add } from './math.js';
console.log(add(1, 2), multiply(2, 3)); // 3 6

Live bindings and hoisting

Imported bindings are live: if the exporting module reassigns a variable, importers see the new value. Import and export declarations are hoisted, so a cycle can leave one side with an uninitialized binding until evaluation order resolves it.

snippet.js
const mod = await import('./math.js');
console.log(mod.add(2, 2)); // 4

Dynamic import returns a promise and loads the module on demand. It is the tool for code splitting, conditional features and heavy optional dependencies.

Exercises

#

Reference answers and expected output are authored, not executed in this browser. Nothing you type is run, and there is no Run or Pass control on this page.

  1. Exercise 1Predict

    Given a module that exports a mutable counter and increments it, what does an importer observe after the exporter changes the value?

    Read the code, then choose the best answer. The reference explanation stays hidden until you respond.
    stimulus.javascript
    // counter.js
    export let count = 0;
    export function bump() { count += 1; }
    
    // main.js
    import { count, bump } from './counter.js';
    bump();
    console.log(count);
    Choose the best answer
  2. Exercise 2Explain

    Explain the trade-off between a default export and a named export.

    starter.text
    export default function parse(input) { return input; }

    Reveal the reference answer
    reference.text
    A named export is imported by its exact name, so tooling can find every usage, rename it safely and tree shake unused names. A default export can be imported under any local name, which is convenient for a single main value but hides the real name, makes refactoring harder and can defeat automatic analysis. I default to named exports and use a default only when a module clearly has one primary value.

    Authored expected output: a function named parse

    The answer should connect naming, refactoring and tree shaking to the choice, not just call one style nicer.

  3. Exercise 3Implement

    Implement `loadFeature(enabled)` so it dynamically imports './feature.js' only when enabled and returns the module, or null otherwise.

    starter.javascript
    async function loadFeature(enabled) {
      // your code here
    }

    Reveal the reference answer
    reference.javascript
    async function loadFeature(enabled) {
      if (!enabled) return null;
      const mod = await import('./feature.js');
      return mod;
    }

    Authored expected output: the module when enabled, otherwise null

    Dynamic import returns a promise and defers loading until the call runs, which is how optional features stay out of the initial bundle.

  4. Exercise 4Debug

    Two modules import each other and one logs undefined at startup. Explain the cause and the fix.

    starter.javascript
    // a.js
    import { b } from './b.js';
    export const a = 'A';
    console.log('b is', b);
    
    // b.js
    import { a } from './a.js';
    export const b = 'B';

    Reveal the reference answer
    reference.javascript
    When a.js is evaluated first it imports b.js before its own const a is initialized. b.js runs, imports a but finds it still in the temporal dead zone, and finishes. Control returns to a.js, which now sees b defined. Any access to the not-yet-initialized binding during the cycle is the bug. The fix is to remove the cycle or move the shared value into a third module that neither depends on.

    Authored expected output: b is B

    Live bindings exist during a cycle but are uninitialized until the exporting module evaluates. Breaking the cycle is more reliable than depending on evaluation order.

  5. Exercise 5Test

    Write assertions that prove a namespace import exposes only the named exports.

    starter.javascript
    function assertEqual(actual, expected, label) {
      if (actual !== expected) throw new Error(label + ': expected ' + expected + ' but got ' + actual);
    }

    Reveal the reference answer
    reference.javascript
    const mod = { add: (a, b) => a + b };
    assertEqual(typeof mod.add, 'function', 'named export is present');
    assertEqual('default' in mod, false, 'no default export in this module');
    assertEqual(mod.add(2, 3), 5, 'named export works');
    console.log('all assertions passed');

    Authored expected output: all assertions passed

    A namespace object holds the module's named exports. Checking which keys exist documents the module's public surface and catches accidental defaults.

  6. Exercise 6Interview

    How do you decide where to draw module boundaries in a growing codebase?

    Reveal the reference answer
    reference.text
    I group code by what changes together and expose a narrow public surface, usually named exports, so callers depend on a small contract. I keep cycles out by pushing shared types and constants into a lower module, and I split a module when it starts mixing unrelated responsibilities or when a heavy dependency can be loaded lazily. The goal is that I can move or replace a module without touching its callers.

    The answer should connect cohesion, a narrow public surface, cycle avoidance and lazy loading to maintainability.

Common misconceptions

#
  • Imports copy the exported value at import time rather than tracking it.
  • Default and named exports are interchangeable in every situation.
  • Circular imports always work because modules are hoisted.

Follow-up practice

#
  • javascript-foundations-functions-and-closures
  • javascript-foundations-functional-programming-and-currying

Related resources

#

Your progress

#

Answers, drafts and completion marks are stored only in this browser. Nothing is sent to a server and no account is used.

Verification: authored. Answers and outputs on this page are authored reference material, not executed results.

© 2026 FrontendX. All rights reserved.