Code Structure
A small script can be a list of statements, but as it grows it needs a shape: a clear place where it starts, related code kept together, and as few global names as possible. This page covers how a page loads its scripts, a simple layout for a single script file, and how ES modules split a program across files.
Loading the script
Section titled “Loading the script”A plain <script src> in the <head> stops the browser from building the page while the script downloads and runs, and the script cannot see any element that comes after it. There are three ways round this:
- Put the
<script>element at the end of the<body>, which is the oldest approach. - Add
defer, which downloads the script while the page is being built and runs it once the HTML has been read, just before theDOMContentLoadedevent. Deferred scripts run in the order they appear. - Use
type="module", which is deferred automatically and also makes the script a module, as described later on this page.
With defer or type="module", the elements already exist when the script runs, so there is no need to wait for DOMContentLoaded. The async attribute also downloads in the background, but it runs the script as soon as it arrives, in no fixed order, which suits independent scripts such as analytics rather than a page’s own code.
Laying out a script
Section titled “Laying out a script”One layout that keeps a classic script readable is to put the settings first, then the state, then the functions, and to start everything from a single init function at the end. This example is a reading list, and the HTML loads its script with defer.
<form id="add-book"> <input name="title" placeholder="Book title" required> <button>Add</button></form><ul id="reading-list"></ul><p id="book-count"></p><script src="reading-list.js" defer></script>(() => { // Settings const MAX_BOOKS = 5;
// State const books = [];
// Functions const render = () => { const items = books.map((title) => { const item = document.createElement('li'); item.textContent = title; return item; }); document.getElementById('reading-list').replaceChildren(...items); document.getElementById('book-count').textContent = `${books.length} of ${MAX_BOOKS} books`; };
const addBook = (event) => { event.preventDefault(); if (books.length >= MAX_BOOKS) return; books.push(event.target.elements.title.value.trim()); event.target.reset(); render(); };
// Start const init = () => { document.getElementById('add-book').addEventListener('submit', addBook); render(); };
init();})();Saving the two blocks as an HTML file and reading-list.js in the same folder and opening the page shows 0 of 5 books. Each title submitted is added to the list and the count goes up, until the fifth, after which the form adds nothing more. The whole script sits inside an IIFE, so it adds no global names at all, and IIFEs vs Namespaced Objects compares this with putting the functions on a namespace object instead.
A script that runs in the browser cannot keep anything secret. Anyone can read its source, so an API key that must stay private belongs on a server, not in a constant at the top of a script.
Splitting code into modules
Section titled “Splitting code into modules”An ES module is a file that has its own scope and shares only what it exports. Another module uses those values with import. A module can have any number of named exports and at most one default export, and the importing file chooses its own name for the default.
export const CURRENCY = 'GBP';
export const formatPrice = (pence) => new Intl.NumberFormat('en-GB', { style: 'currency', currency: CURRENCY }).format(pence / 100);
const roundToPence = (amount) => Math.round(amount);
export default function applyDiscount(pence, percent) { return roundToPence(pence * (1 - percent / 100));}import applyDiscount, { formatPrice, CURRENCY } from './format.js';import * as format from './format.js';
const price = 2499;console.log(CURRENCY, formatPrice(price));console.log(formatPrice(applyDiscount(price, 15)));console.log(Object.keys(format));Running main.js prints:
GBP £24.99£21.24[ 'CURRENCY', 'default', 'formatPrice' ]roundToPence is not exported, so it is private to format.js, and it does not appear among the keys of the format object that import * as creates. Named imports go in braces and must use the exported names, although as can rename them, as in import { formatPrice as price }. The default import, applyDiscount here, takes no braces.
A page loads only the entry module, and the browser fetches the files it imports:
<script type="module" src="main.js"></script>Modules differ from classic scripts in several ways:
- They are always in strict mode.
- Their top-level variables are not global, so two modules can each have a
const totalwithout a clash. - Each module runs once, however many other modules import it.
- Browsers fetch them under the CORS rules, so a page opened straight from a file on disk, with a
file://address, cannot load them. Serve the folder with a local web server instead. - Import paths in the browser need the full file name, including
.js, and must start with./,../or/unless an import map defines a bare name.
In Node.js, a file is a module when its name ends in .mjs, or when it ends in .js and the nearest package.json contains "type": "module". Current versions of Node.js also treat a .js file as a module when it has no such setting but contains import or export statements.
Steve Griffith covers this topic in his video JS Code Structure Moving Beyond Beginner.