Machine Coding · Lesson 5 of 12 · 4 min
Displaying Dynamic Data: Todo List
This is the classic machine coding problem. Your goal is to show a clean separation between state and view.
The Core Pattern: State → Render
The foundation for any dynamic UI is a one-way data flow. Your application state is the single source of truth, and the view is a direct, predictable function of that state.
When the state changes, you don't manually find and patch the DOM. You re-render the entire component. For a simple todo list, this means a render() function that takes the current array of todos, clears the list, and rebuilds it from scratch.
// The application's state
let todos: Todo[] = [ /* ...initial todos */ ];
const todoListElement = document.getElementById('todo-list');
// The render function: a pure function of state
function render() {
// Naive but simple: clear everything
todoListElement.innerHTML = '';
// Rebuild the list from the state array
todos.forEach(todo => {
const listItem = document.createElement('li');
// ... create and append children for the todo item
todoListElement.appendChild(listItem);
});
}
// Any action that changes data must end with a call to render()
function addTodo(text: string) {
// ... update the `todos` array
render();
}
The trap: Manually manipulating the DOM to add, remove, or update a single <li>. This is brittle and doesn't scale. Your code becomes a series of imperative patches instead of a declarative reflection of the state. Always re-render from the state.
Updating State Immutably
How you update your state array is critical. Never modify the array in place. Always create a new array. This principle, called immutability, makes state changes explicit and predictable. Frameworks like React rely on this to detect changes.
For adding an item, use the spread syntax:
todos = [...todos, newTodo];
For updating an item (like toggling completion), use .map() to create a new array with the modified item:
todos = todos.map(todo => todo.id === id ? { ...todo, completed: !todo.completed } : todo);
For deleting an item, use .filter() to create a new array without the item:
todos = todos.filter(todo => todo.id !== id);
The trap: Using mutating methods like push(), splice(), or directly assigning to an index (todos[i].completed = true). This leads to subtle bugs where the UI doesn't update because the array reference hasn't changed, fooling simple change-detection mechanisms.
Rendering Lists: Keys are Not Optional
When you re-render a list, clearing innerHTML and rebuilding is simple but inefficient. It destroys and recreates every DOM node, losing state like input focus or CSS animations.
Frameworks solve this with a reconciliation algorithm (the "virtual DOM diff"). To make this algorithm efficient, it needs your help. You must provide a stable, unique key for each item in the list. The key tells the renderer, "This DOM node corresponds to this specific data item."
Without keys, the renderer has to guess. With keys, it can intelligently move, update, or remove only the nodes that have actually changed.
In an interview, when asked how to render a list efficiently, your answer must mention keyed updates.
- Keyed Updates: Explain that you assign a stable, unique ID from the data (like
todo.id) to each element in the list.- Reconciliation: This allows the rendering engine to identify which items are new, which were removed, and which just moved, minimizing direct DOM mutations. It avoids re-creating every single element on every render.
The trap: Using the array index as a key. An item's index changes if you add, remove, or reorder items. Using an unstable key like the index is often worse than using no key at all, leading to incorrect UI state and performance issues.
The Full Implementation
This code ties everything together: event handling, immutable state updates, and a full re-render after each change. Note the use of data-id as a stand-in for a framework key.
interface Todo {
id: string;
text: string;
completed: boolean;
}
// State
let todos: Todo[] = [
{ id: '1', text: 'Learn Machine Coding', completed: true },
{ id: '2', text: 'Practice Interview Questions', completed: false },
];
// Get DOM elements once
const listEl = document.getElementById('todo-list') as HTMLUListElement;
const inputEl = document.getElementById('new-todo-input') as HTMLInputElement;
const addBtn = document.getElementById('add-todo-button') as HTMLButtonElement;
// Render function
function render() {
listEl.innerHTML = '';
todos.forEach(todo => {
const li = document.createElement('li');
li.setAttribute('data-id', todo.id);
li.innerHTML = `
<input type="checkbox" ${todo.completed ? 'checked' : ''}>
<span class="todo-text ${todo.completed ? 'completed' : ''}">${todo.text}</span>
<button class="delete-button">Delete</button>
`;
listEl.appendChild(li);
});
}
// State update functions
function addTodo(text: string) {
const newTodo: Todo = { id: Date.now().toString(), text, completed: false };
todos = [...todos, newTodo];
render();
}
function toggleTodo(id: string) {
todos = todos.map(t => t.id === id ? { ...t, completed: !t.completed } : t);
render();
}
function deleteTodo(id: string) {
todos = todos.filter(t => t.id !== id);
render();
}
// Event listeners
addBtn.addEventListener('click', () => {
const text = inputEl.value.trim();
if (text) {
addTodo(text);
inputEl.value = '';
}
});
listEl.addEventListener('click', (e) => {
const target = e.target as HTMLElement;
const parentLi = target.closest('li');
if (!parentLi) return;
const todoId = parentLi.getAttribute('data-id');
if (target.matches('input[type="checkbox"]')) {
toggleTodo(todoId);
} else if (target.matches('.delete-button')) {
deleteTodo(todoId);
}
});
// Initial render
render();
The State-Update-Render Loop
This diagram shows the unidirectional data flow you should describe in an interview. Every user action follows the same path.
When you build this in an interview, talk through the loop. "The user clicks 'add', which triggers an event handler. The handler doesn't touch the DOM. It creates a new todo object, updates the state array immutably, and then calls
render. Therenderfunction is responsible for making the DOM match the new state." This demonstrates a clear, structured approach.
Try it
Modify the code to allow editing a todo. When a user double-clicks the <span> with the todo text, replace it with an <input> field. When they press Enter or blur the input, update the state and re-render. This will take you about 20 minutes.
Next: Now that we can display and manage a list, we'll learn how to derive filtered views from our source data in Filtering & Searching Data.
Lock it in — apply this lesson under interview conditions.