Code Organization

Foundations · Prereqs: JS Essentials
--- theme: default routerMode: hash favicon: https://oim3690.github.io/favicon.svg titleTemplate: "%s - OIM3690" title: "Code Organization" info: | why split files, project structure, export/import (ES modules), script type=module, comments <br><br> <b>Custom:</b> <kbd>t</kbd> Timer · <kbd>T</kbd> Start/pause · <kbd>w</kbd> Draw <br> <b>Slidev:</b> <kbd>o</kbd> Overview · <kbd>d</kbd> Dark mode · <kbd>f</kbd> Fullscreen · <kbd>←</kbd> <kbd>→</kbd> Navigate --- # Code Organization Splitting a growing project into files that make sense. --- # Why Separate Files? As a project grows, one giant `script.js` gets hard to work with: - Hard to find anything - Easy to break unrelated code while editing - Painful to reuse a piece somewhere else Split code by **what it does**: data in one file, page logic in another. --- # Separation of Concerns Each language has one job, keep them in separate files: - **HTML** = structure (what is on the page) - **CSS** = style (how it looks) - **JavaScript** = behavior (what it does) Inline styles and inline `onclick` work for tiny demos but get messy fast. The same idea applies inside your JS: data, logic, and rendering each in their own place. --- # Project File Structure A common layout for a small project: ``` my-project/ ├── index.html ├── css/ │ └── styles.css ├── js/ │ ├── data.js │ └── main.js └── images/ └── logo.png ``` Pages at the root, styles in `css/`, scripts in `js/`, images in `images/`. --- # export / import Share values between files. One file **exports**, another **imports**: ```js // js/data.js export const snacks = [ { name: "Chips", price: 2.5 }, { name: "Trail Mix", price: 3.25 }, ]; ``` ```js // js/main.js import { snacks } from "./data.js"; for (const snack of snacks) { console.log(snack.name); } ``` `export` makes a value available; `import` pulls it in by name. --- # Wiring It Up: type="module" `import` only works in a **module script**. Link just the entry file: ```html <body> <!-- main.js imports data.js itself, you do not link data.js --> <script type="module" src="js/main.js"></script> </body> ``` - Without `type="module"`, `import` throws a syntax error - Modules need a **server**, open the page with **Live Server** (`file://` blocks them) If you see *"Cannot use import statement outside a module,"* you forgot `type="module"` on the script tag. --- # ✏️ Your Turn: Import Your Local Data Create `data-app.html`, `js/data.js`, and `js/main.js` in your **oim3690** repo. **By hand, no AI:** ```js // js/data.js export const items = ["one", "two", "three"]; ``` ```js // js/main.js import { items } from "./data.js"; console.log(items); ``` In `data-app.html` link only main: `<script type="module" src="js/main.js"></script>`. Open with **Live Server**. **Then with AI:** fill `data.js` with fake data (a grocery list? movies?), then have AI build a small page in `main.js` that renders it. --- # Comments and TODOs Comments explain **why**, not what the code already says: ```js // Convert first, form inputs are always strings const total = Number(input.value) * quantity; // TODO: handle the empty-cart case ``` - Explain tricky decisions, not obvious lines - `TODO:` marks unfinished work, your editor can list every one --- # DRY: Don't Repeat Yourself When you copy-paste the same code, turn it into a function: ```js // Repetitive, the rate is written three times const tax1 = price1 * 0.06; const tax2 = price2 * 0.06; const tax3 = price3 * 0.06; // DRY, one place to read and to change function addTax(price) { return price * 0.06; } ``` Change the rate or fix a bug **once**, not in three places. --- # Name Your Magic Numbers A bare number (a "magic number") hides its meaning: ```js // What is 0.06? Why 5? total = price * 0.06; if (cart.length > 5) { freeShipping(); } // Named: clear, and changed in one place const TAX_RATE = 0.06; const FREE_SHIPPING_MIN = 5; total = price * TAX_RATE; ``` Put important values in a named `const` at the top, not scattered through the code. --- # Keep It Small and Simple - **One job each**: a function or file that does one thing is easy to name, reuse, and fix - **Do not over-engineer**: write the simplest thing that works, you can add more later - **Write for humans**: code is read far more often than it is written > 🤖 **AI tip:** AI often writes more code than you need. If its solution feels too complex to follow, ask for "the simplest version that works." --- # Testing (with AI) Check your code works for real inputs, not just the happy path: - Try edge cases: empty input, `0`, a huge number, weird text - Fix whatever breaks No framework needed yet. **Ask AI:** "What edge cases should I test for this function?", try them, and later have AI write automated tests for you. --- # ✏️ Your Turn: Review Your Own Code Open a project you have built (the oim3690 repo, or one of your MPs). Look at it as an organizer: - One giant file, or split sensibly? - Repeated code that could become a function (DRY)? - Where would `export` / `import` help? In your **learning log**, note one thing done well and one thing to improve. **Then with AI:** ask it to review the file's organization and suggest one change. Decide if you agree. --- # Key Takeaways 1. **Separation of concerns**: HTML structure, CSS style, JS behavior 2. Split a growing project into files **by what they do** 3. `export` shares a value; `import` pulls it in (needs `type="module"` + a server) 4. **DRY** and **named constants**: change a value in one place 5. Keep it **small and simple**; comment the **why**; write for humans 6. **Test** real inputs and edge cases, ask AI what to check --- # References - [MDN: JavaScript modules](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Modules) - [MDN: export](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/export) - [JavaScript.info: Modules](https://javascript.info/modules-intro)

Topics Covered

  • separation of concerns / why split files
  • export / import (ES modules) + script type=module
  • comments and TODOs
  • DRY, named constants, keep it simple
  • testing with AI

Content Slides Open fullscreen ↗

Taught In

  • Wednesday, 7/1 — Code organization (modules + good code) · Project velocity · live-coding round