CodingNic

Modules & Code Organization

Exercises

Modules & Code Organization 35 min read

Exercises

Objectives

This chapter introduces no new concepts. It’s a chance to practice everything from this module: named exports, default exports, organizing files, and dynamic imports.

All exercises assume these files exist:

javascript
// shapes.js
export function areaOfCircle(radius) {
  return Math.PI * radius * radius;
}

export function areaOfSquare(side) {
  return side * side;
}

export const PI_ROUNDED = 3.14;
javascript
// Logger.js
export default class Logger {
  constructor(prefix) {
    this.prefix = prefix;
  }
  log(message) {
    return `[${this.prefix}] ${message}`;
  }
}

export const LOG_LEVELS = ["info", "warn", "error"];
javascript
// greet.js
export default function greet(name) {
  return `Hello, ${name}!`;
}

Exercises

  1. Import areaOfCircle and PI_ROUNDED from ./shapes.js. Call areaOfCircle(2) and log the result. Check: about 12.566.

  2. Import everything from ./shapes.js with import * as shapes, then call shapes.areaOfSquare(4). Check: 16.

  3. Import areaOfSquare from ./shapes.js, renamed to squareArea using as. Call squareArea(5). Check: 25.

  4. Import the default export from ./Logger.js, create one with new Logger("APP"), and call .log("Started") on it. Check: [APP] Started.

  5. Import both the default export and LOG_LEVELS from ./Logger.js in one import line. Log LOG_LEVELS.length. Check: 3.

  6. Write an async function that dynamically imports ./greet.js, calls its default export with "Erin", and logs the result. Check: Hello, Erin!.

  7. Dynamically import ./greet.js using .then() instead of await, and log the result of calling its default export with "Sam". Check: Hello, Sam!.

  8. Create a file barrel.js that re-exports areaOfCircle and areaOfSquare from ./shapes.js, and re-exports Logger’s default export as a named export called Logger, using export { default as Logger } from "./Logger.js". From a separate file, import both areaOfCircle and Logger from ./barrel.js in a single line, and use each one.

Recap

You can now split code across files with named and default exports, organize a small project by responsibility, keep internal state private to a module, re-export through a barrel file, and load a module on demand with a dynamic import. That’s the full toolkit for structuring a project bigger than one file.

Next module: Browser APIs, local storage, geolocation, the clipboard, and more.