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:
// shapes.js
export function areaOfCircle(radius) {
return Math.PI * radius * radius;
}
export function areaOfSquare(side) {
return side * side;
}
export const PI_ROUNDED = 3.14;
// Logger.js
export default class Logger {
constructor(prefix) {
this.prefix = prefix;
}
log(message) {
return `[${this.prefix}] ${message}`;
}
}
export const LOG_LEVELS = ["info", "warn", "error"];
// greet.js
export default function greet(name) {
return `Hello, ${name}!`;
}
Exercises
-
Import
areaOfCircleandPI_ROUNDEDfrom./shapes.js. CallareaOfCircle(2)and log the result. Check: about12.566. -
Import everything from
./shapes.jswithimport * as shapes, then callshapes.areaOfSquare(4). Check:16. -
Import
areaOfSquarefrom./shapes.js, renamed tosquareAreausingas. CallsquareArea(5). Check:25. -
Import the default export from
./Logger.js, create one withnew Logger("APP"), and call.log("Started")on it. Check:[APP] Started. -
Import both the default export and
LOG_LEVELSfrom./Logger.jsin oneimportline. LogLOG_LEVELS.length. Check:3. -
Write an
asyncfunction that dynamically imports./greet.js, calls its default export with"Erin", and logs the result. Check:Hello, Erin!. -
Dynamically import
./greet.jsusing.then()instead ofawait, and log the result of calling its default export with"Sam". Check:Hello, Sam!. -
Create a file
barrel.jsthat re-exportsareaOfCircleandareaOfSquarefrom./shapes.js, and re-exportsLogger’s default export as a named export calledLogger, usingexport { default as Logger } from "./Logger.js". From a separate file, import bothareaOfCircleandLoggerfrom./barrel.jsin 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.