A callback function is a function passed as an argument to another function, to be "called back" later.
function sayHello(name) {
console.log("Hello, " + name);
}
function greetUser(callback) {
const userName = "Student";
callback(userName);
}
greetUser(sayHello); // Hello, Student
JavaScript is single-threaded, but it can appear asynchronous using the browser environment (Web APIs, event loop).
Example with setTimeout
:
console.log("1");
setTimeout(() => {
console.log("2 (after 1 second)");
}, 1000);
console.log("3");
// Output: 1, 3, 2
Explanation:
console.log("1")
and console.log("3")
immediately.setTimeout
is handled by the browser's Web API and queued later.Visualize the Call Stack + Callback Queue + Event Loop
This is an example of a scrollable document. Here's an embedded image for visual engagement:
Where synchronous code executes. Functions are pushed and popped in LIFO order (Last In, First Out).
Browser-provided APIs like setTimeout, fetch, DOM events that run outside the main thread.
Holds callbacks from Web APIs, waiting to be executed when the call stack is empty.
Continuously checks if call stack is empty, then moves callbacks from queue to stack.
fetch()
is used to make network requests. It returns a Promise.
fetch('https://api.openbrewerydb.org/breweries')
.then(response => response.json())
.then(data => {
console.log("Breweries:", data.slice(0, 5)); // Show first 5 breweries
})
.catch(error => console.error("Error:", error));
We'll use this in our office hour project next!
We'll build this step-by-step. Here's what we'll do:
fetch
and dynamic DOM manipulationWe'll start this live in office hours — no code yet!