Error.prototype.stack
You'll learn how the stack property reveals exactly where an error occurred and the path that led there.
What Is the Stack Property?
When you create or throw an Error object, JavaScript automatically attaches a stack property containing a stack trace—a text record showing the sequence of function calls that led to the error. Think of it like breadcrumbs showing your path through the code before something went wrong.
How It Works
The stack property is a string containing:
- The error message
- The file and line number where the error occurred
- The chain of function calls (the "call stack") leading to that point
function levelThree() {
throw new Error('Something broke!');
}
function levelTwo() {
levelThree();
}
function levelOne() {
levelTwo();
}
try {
levelOne();
} catch (error) {
console.log(error.stack);
// Output (format varies by environment):
// Error: Something broke!
// at levelThree (file.js:2:9)
// at levelTwo (file.js:6:3)
// at levelOne (file.js:10:3)
}
Why It Matters for Debugging
The stack trace shows you not just where the error happened, but how you got there. If levelThree() is called from multiple places, the stack tells you which path triggered the problem.
try {
JSON.parse('invalid json');
} catch (error) {
console.log(error.message); // "Unexpected token i in JSON..."
console.log(error.stack); // Shows the full trace
}
Key Takeaway: The stack property provides a detailed trace of function calls leading to an error, making it essential for debugging complex issues and understanding error context.