When Things Go Wrong: Error Handling
Sometimes code breaks. An error is a problem that stops your program. JavaScript has tools to handle errors so your page does not just crash.
A try/catch block lets you "try" risky code and "catch" problems:
try {
const data = JSON.parse("not real JSON");
} catch (error) {
console.log("Something went wrong:", error.message);
}Changing the Page: The DOM
The DOM (Document Object Model) is the browser's map of your page. JavaScript can find elements and change them:
const title = document.querySelector('h1');
title.textContent = 'Hello!';querySelector finds the first element that matches, like a CSS selector.
Responding to the User: Events
An event is something the user does, like a click. An event listener waits for it:
const button = document.querySelector('#counter');
button.addEventListener('click', () => {
console.log('You clicked!');
});Callbacks and Asynchronous Thinking
Normally code runs top to bottom. But some things take time, like loading data. A callback is a function you hand over, to run later when the work is done.
Promises: Values That Arrive Later
A promise is an object that stands for a value you do not have yet. It is like a receipt: the value is coming, or something failed.
async/await and Fetching Data
async/await is a cleaner way to work with promises. await means "pause here until the value arrives":
async function loadUser(id) {
const response = await fetch(`https://api.example.com/users/${id}`);
if (!response.ok) {
throw new Error(`HTTP ${response.status}`);
}
return await response.json();
}fetch asks a server for data over the internet.
Prototypes and Classes
A class is a blueprint for making objects with the same shape and behavior:
class Dog {
constructor(name) {
this.name = name;
}
speak() {
return `${this.name} says woof`;
}
}
console.log(new Dog('Rex').speak());Classes are a friendly layer over JavaScript's older prototype system, which is how objects share features with each other.
Organizing Code with Modules
A module is a file that shares selected code with other files. You export what others may use, and import what you need:
// math.js
export function double(n) { return n * 2; }
// main.js
import { double } from './math.js';
console.log(double(5));Show diagram source
graph TD
A[User clicks] --> B[Event listener runs]
B --> C[async function starts]
C --> D[Promise: data arriving]
D --> E[Page updated]Exercise
What does the catch part of a try/catch block do?
Show answer
It runs only if an error happens inside the try block, so you can respond to the problem instead of letting the program crash.
Exercise
What is a promise?
Show answer
An object that represents a value that will arrive later, such as data from a server.
Spotted a mistake, or code that does not work?