Error Propagation in Synchronous Code
You'll learn: how thrown errors automatically travel up through nested function calls until something catches them.
The Call Stack Journey
When you throw an error in JavaScript, it doesn't just stay where it happened. The error propagates (travels upward) through the call stack—the chain of function calls that led to that point. It keeps moving up until it finds a try/catch block willing to handle it.
Think of it like a fire alarm in a tall building: if the alarm goes off on the 5th floor, the signal travels up through the building's systems until someone at a monitoring station catches and handles it. If nobody catches it, the alarm reaches the top and triggers default behavior (in JavaScript's case, crashing the program).
How It Works
function deepFunction() {
throw new Error('Something went wrong');
}
function middleFunction() {
deepFunction(); // Error thrown here, but not caught
}
function topFunction() {
try {
middleFunction(); // Error passes through here too
} catch (error) {
console.log('Caught at the top:', error.message);
}
}
topFunction(); // Logs: "Caught at the top: Something went wrong"
The error is thrown in deepFunction, skips past middleFunction (no try/catch there), and finally gets caught in topFunction.
Uncaught Errors
If no function in the stack has a try/catch block, the error reaches the global level and terminates your program:
function boom() {
throw new Error('Uncaught!');
}
boom(); // Program crashes with unhandled error
Key Takeaway: Errors automatically bubble up the call stack through each function until a try/catch block intercepts them—if none exists, the program crashes.