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.
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.
Dependencies point one way: presentation → logic → data shapes. Logic never imports DOM code, which keeps it reusable in Node.js, workers and other UIs.
Pass data into functions instead of reading globals (total(cart) rather than total() reading window.cart). Explicit inputs make behaviour obvious and tests trivial.
A thin "controller" (event handlers) translates events into logic calls and state updates, then asks the view to render. Most bugs then fall clearly into one layer.
In larger codebases each layer becomes a module or folder (Lesson 91 covers ES modules), and frameworks follow the same split under names like services, stores and components.
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.
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.
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.
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
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.
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 explanationseparating 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 predictionseparating 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.
Debuggingseparating 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 generationseparating 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 reviewseparating 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.