Filter returns a new array and leaves the original collection available when the controls change. This example assumes every title is a string; validate external data before reaching this function. Decide explicitly which fields search should match and how an empty query behaves.
Render User-Controlled Text as Text
const title = document.createElement('h2');
title.textContent = resource.title;
container.append(title);
Text content displays the supplied value without interpreting it as HTML. Do not replace this with innerHTML for untrusted strings. URLs, styles, and other contexts need their own validation; safe text rendering is one boundary, not a universal sanitisation method.
Check a Fetch Response and Its Shape
async function loadResources() {
const response = await fetch('./resources.json');
if (!response.ok) throw new Error(`HTTP ${response.status}`);
const data = await response.json();
if (!Array.isArray(data)) throw new Error('Expected a resource list');
return data;
}
A network request can resolve even when the server returns an error status. JSON parsing can also fail independently. This short example checks the top-level shape; a real collection should validate the fields each interface uses. The caller still needs loading and error states.
Report Storage Failure Honestly
function saveProgress(value) {
try {
localStorage.setItem('practice-progress', JSON.stringify(value));
return { ok: true };
} catch {
return { ok: false, message: 'Progress could not be saved in this browser.' };
}
}
Browser storage can fail because of policy, availability, or capacity. Return a result the interface can use rather than showing success unconditionally. Local storage belongs to an origin and browser profile; it is not an account backup or a shared database.
Handle a Form through Its Submit Event
form.addEventListener('submit', (event) => {
event.preventDefault();
if (!form.reportValidity()) return;
const data = new FormData(form);
const title = String(data.get('title') ?? '').trim();
output.textContent = title || 'Add a title first.';
});
Handling submit supports the native form interaction, including keyboard submission. Named controls supply FormData values. Client-side checks improve feedback but do not establish trust for a server. Use visible labels and connect any custom error message to its field.