JavaScript AcademyProfessional Engineering
Level 3 · Interactive Web ApplicationsModule 15: Interactive Application ArchitectureLesson 71 of 150About 45 minutes

Lesson 71: Separating data, logic and presentation

01Opening question

Your app works, but every function reads the DOM, changes data and formats text at the same time. What happens when you need to change one of those?

Keep the question in mind. By the end of the lesson you will be able to answer it, and prove it with working code.

02Start with working code

Three small pieces: data, a rule that knows nothing about the page, and formatting that knows nothing about the rules.

// data
const products = [{ name: "Lamp", price: 30 }, { name: "Mug", price: 8 }];
// logic (no DOM)
const cheap = (list, max) => list.filter((p) => p.price <= max);
// presentation (no rules)
const label = (p) => `${p.name} ($${p.price})`;
console.log(cheap(products, 10).map(label).join(", "));

03Objective and prerequisites

Learning objective: Split a browser app into data, logic and presentation layers, so rules can be tested without a page and the UI can change without touching the rules.

You need: Lesson 70: IndexedDB fundamentals, Lesson 67: Rendering interfaces from state

Skills practised: Browser application architecture, Separating data, logic and presentation.

04Explanation

Separation of concerns means each part of the code has one job. A common split for browser apps is data, logic and presentation.

The data layer holds and saves information (state, storage, network). The logic layer holds the rules (totals, filters, validation) as plain functions.

The presentation layer reads from the DOM, writes to the DOM, and wires up events. It calls the logic; it does not contain the rules.

Logic functions that do not touch the page can be tested with a few console.log checks, or later with a test runner, without opening a browser.

05Definitions

Separation of concerns
Organising code so each part has one responsibility, such as data, rules or display.
Data layer
Code that holds, loads and saves the application's data.
Logic layer
Plain functions with the app's rules, such as calculations, filters and validation, without DOM access.
Presentation layer
Code that renders the interface and handles user events.
Pure function
A function whose result depends only on its inputs and that changes nothing outside itself.

Open the full glossary

06Visual learning object

Application state visualizer. Follow one click through the layers: the event handler calls a rule, the rule returns new state, and the view renders it.

Loading the interactive object…

Open the full Application state visualizer page with its guided experiment.

07Examples

ex-071-01Tangled versus separated Browser page (sandboxed preview)

The same feature written twice: once mixed, once in layers.

// Tangled: rule, data and display in one function
function showTotalTangled() {
  const prices = [...document.querySelectorAll(".price")].map((el) => Number(el.textContent));
  document.querySelector("#a").textContent = "Total: " + prices.reduce((s, p) => s + p, 0);
}
showTotalTangled();
// Separated
const cart = [12, 30];                                   // data
const total = (prices) => prices.reduce((s, p) => s + p, 0); // logic
const renderTotal = (el, value) => { el.textContent = "Total: " + value; }; // presentation
renderTotal(document.querySelector("#b"), total(cart));
console.log(document.querySelector("#a").textContent, "|", document.querySelector("#b").textContent);
console.log(total([1, 2, 3]));
Sample input
None
Expected output
Total: 0 | Total: 42 6
Common mistake
Reading numbers out of the page inside a calculation, which silently returns 0 when the markup changes.
Try this
Add a discount rule to the logic layer only.
Source
examples/ex-071-01-tangled.js

ex-071-02A logic layer with no DOM Browser page (sandboxed preview)

Rules as pure functions are easy to check with quick tests.

const rules = {
  lineTotal: (line) => line.price * line.qty,
  cartTotal: (lines) => lines.reduce((s, l) => s + rules.lineTotal(l), 0),
  freeShipping: (lines) => rules.cartTotal(lines) >= 50
};
const check = (name, actual, expected) => console.log(actual === expected ? "pass" : "FAIL", name);
const lines = [{ price: 20, qty: 2 }, { price: 5, qty: 1 }];
check("cart total", rules.cartTotal(lines), 45);
check("no free shipping under 50", rules.freeShipping(lines), false);
check("free shipping at 50", rules.freeShipping([...lines, { price: 5, qty: 1 }]), true);
Sample input
None
Expected output
pass cart total pass no free shipping under 50 pass free shipping at 50
Common mistake
Putting document.querySelector inside cartTotal, which makes it impossible to test without a page.
Try this
Add a rule for a 10% discount over 100.
Source
examples/ex-071-02-logic-module.js

ex-071-03Event handlers as a thin controller Browser page (sandboxed preview)

The handler reads input, calls logic, updates state and renders. Nothing else.

// data
const state = { expenses: [] };
// logic
const parseAmount = (text) => { const n = Number(text); return Number.isFinite(n) && n > 0 ? n : null; };
const addExpense = (s, amount) => ({ ...s, expenses: [...s.expenses, amount] });
const sum = (s) => s.expenses.reduce((a, b) => a + b, 0);
// presentation
const form = document.querySelector("#f");
let current = state;
function render() { document.querySelector("#total").textContent = "Spent: $" + sum(current); }
form.addEventListener("submit", (event) => {
  event.preventDefault();
  const amount = parseAmount(form.elements.amount.value);
  if (amount === null) return;
  current = addExpense(current, amount);
  render();
});
form.requestSubmit();
form.elements.amount.value = "abc";
form.requestSubmit();
console.log(document.querySelector("#total").textContent, current.expenses.length);
Sample input
None
Expected output
Spent: $40 1
Common mistake
Validating, calculating and formatting all inside the submit handler.
Try this
Add a Clear button that resets state through a logic function.
Source
examples/ex-071-03-controller.js

ex-071-04Changing the view without touching rules Browser page (sandboxed preview)

Two different views render the same data with the same logic.

const tasks = [{ title: "Report", done: true }, { title: "Slides", done: false }];
const pending = (list) => list.filter((t) => !t.done);
function renderList(el, items) {
  el.replaceChildren(...items.map((t) => Object.assign(document.createElement("li"), { textContent: t.title })));
}
function renderTable(el, items) {
  el.replaceChildren(...items.map((t) => {
    const tr = document.createElement("tr");
    tr.append(Object.assign(document.createElement("td"), { textContent: t.title }), Object.assign(document.createElement("td"), { textContent: "pending" }));
    return tr;
  }));
}
renderList(document.querySelector("#list"), pending(tasks));
renderTable(document.querySelector("#table"), pending(tasks));
console.log(document.querySelector("#list").textContent, "|", document.querySelector("#table").textContent);
Sample input
None
Expected output
Slides | Slidespending
Common mistake
Copying the filtering rule into each view, so the two views drift apart.
Try this
Add a card view that uses the same pending rule.
Source
examples/ex-071-04-view-swap.js

08Guided exercises

Three exercises: explore and modify, complete the implementation, then build independently. Tests check behaviour, so any correct solution passes.

Pull the rule out of the handler

Move logic into a pure function.

document.querySelector("#check").addEventListener("click", () => {
  const age = Number(document.querySelector("#age").value);
  document.querySelector("#out").textContent = age >= 18 ? "Welcome" : "Sorry, adults only";
});
document.querySelector("#check").click();
console.log(typeof canEnter === "function" ? canEnter(18) : "no rule");

Three layers for a grade report

Write the logic and presentation separately.

const students = [{ name: "Ana", score: 91 }, { name: "Ben", score: 68 }, { name: "Cy", score: 79 }];
// logic: grade(score) -> "A" (90+), "B" (75+), "C" otherwise
function grade(score) {
  // TODO
}
// presentation: render(list) -> one li per student: "Ana: A"
function render(list) {
  // TODO
}
render(students);
console.log(document.querySelector("#report").textContent);

A layered unit converter

Build a small app with clear layers.

// logic:    kmToMiles(km) -> miles rounded to 2 decimals (1 km = 0.621371 mi)
//           parseKm(text) -> a number >= 0, or null
// view:     showResult(text) -> writes into #result
// controller: on submit (preventDefault) parse, convert or show "Enter a distance"
// Submit "5", then "-1", logging #result each time.

09Prediction

Commit to an answer first, then run the real code to compare.

const applyDiscount = (price, pct) => price - price * pct / 100;
const prices = [100, 40];
console.log(prices.map((p) => applyDiscount(p, 10)).join(" "), prices.join(" "));

What is printed?

10Debugging investigation

Shipping is free for everyone

Free shipping should start at $50, but every order gets it. The rule reads the subtotal from the page.

function freeShipping() {
  const subtotal = Number(document.getElementById("subtotal").textContent);
  return !(subtotal < 50);
}
console.log("free shipping: " + freeShipping());

More cases in the Debugging Detective Laboratory

11Practical scenario

Redesigns without rewrites

A team redesigns its booking app's interface. Because pricing, availability and validation live in plain logic modules with tests, the new UI is built on top of the same functions, and the rules are untouched.

const layers = { data: "state + storage", logic: "rules (tested)", presentation: "new design" };
for (const [k, v] of Object.entries(layers)) console.log(k + ": " + v);

12Knowledge check

1. Which layer should hold a rule like "free shipping over $50"?

  • Presentation
  • Logic
  • CSS
  • HTML

2. Why keep logic functions free of DOM access?

  • They run faster
  • They can be tested and reused without a page
  • The DOM is read-only
  • It is required by browsers

3. Why does total() return 0 after the page was redesigned?

const total = () => [...document.querySelectorAll(".price")].reduce((s, el) => s + Number(el.textContent), 0);
  • It reads prices from elements whose class changed
  • reduce is broken
  • Number fails
  • The cart is empty

4. What should an event handler do in a layered app?

  • Contain all the rules
  • Read input, call logic, update state, render
  • Store data in the DOM
  • Nothing

5. What is printed?

const double = (n) => n * 2;
console.log(double(2));
  • 2
  • 4
  • undefined
  • NaN

6. Two views show the same filtered list. Which is better?

  • Each view filters in its own way
  • Both views call one shared filter function
  • Store the filtered list in the HTML
  • Filter with CSS

13Solutions and tests

Each exercise's solution appears in the exercise once you have run its tests. Solutions are one possible answer: the tests accept any implementation with the same behaviour.

Automated acceptance tests for this lesson

These are the same checks the exercises run. They are visible on purpose: client-side tests help you learn and are not secret.

  • Pull the rule out of the handler: Prints true; The page still works; canEnter(17) is false
  • Three layers for a grade report: Prints the report; Boundaries; grade does not use the DOM
  • A layered unit converter: Prints both results; Logic: conversion; Logic: parsing

Download the whole lesson folder (examples, exercises, solutions, tests) as ZIP

14Source files

The lesson lives in the companion repository at curriculum/level-03-interactive-web-applications/module-15-interactive-application-architecture/lesson-071-separating-data-logic-and-presentation/. Every example on this page is generated from those files.

These links open the files in the GitHub repository (https://github.com/lsvekis/JavaScript-Professional-Engineering-Academy). You can also use the ZIP download above.

15Summary and next steps

  • Split apps into data, logic and presentation.
  • Logic is plain functions with no DOM access.
  • Handlers connect layers: input → logic → state → render.
  • Layered code is easier to test, change and reuse.

16AI learning prompts

Copy a prompt into the AI assistant of your choice. Then verify what it says by running code here. No AI service is connected to this page.

Concept explanation separating data, logic and presentation
Context: I am learning separating data, logic and presentation in JavaScript.
Task: Explain data, logic and presentation layers with a small shopping cart.
Constraints: Beginner-friendly language, short runnable examples, no libraries.
Expected behaviour: I can explain the idea in my own words and predict small programs.
Testing: Finish with three quick questions for me to answer.
Code prediction separating data, logic and presentation drill
Context: I have practised separating data, logic and presentation.
Task: Give me six small functions and ask which layer each belongs to and why.
Constraints: Wait for my answer before revealing each result.
Expected behaviour: Each question has exactly one correct output.
Testing: Explain any I miss with a step-by-step trace.
Debugging separating data, logic and presentation bug
Context: My total calculation broke when a designer renamed a CSS class.
Task: Help me find the cause with questions instead of giving me the fix.
Constraints: Do not rewrite my program.
Expected behaviour: I locate and fix the bug myself.
Testing: Suggest the console.log lines that would reveal the problem.
Exercise generation separating data, logic and presentation practice
Context: I finished the separating data, logic and presentation exercises.
Task: Create three refactoring exercises that move rules out of event handlers.
Constraints: Fictional data and exact expected output.
Expected behaviour: Each exercise has tests I can run.
Testing: Put the solutions in a separate hidden section.
Code review separating data, logic and presentation review
Context: Here is my code that uses separating data, logic and presentation.
Task: Review my app and point out where DOM code, rules and data are mixed.
Constraints: Explain each suggestion briefly and keep behaviour identical.
Expected behaviour: The code is clearer and has no hidden mutation or edge-case bug.
Testing: List the changes in order of importance.