How to Read an Error Report
Many mistakes in JavaScript do not stop the program. A missing property gives undefined, and a bad number conversion gives NaN. But some operations cannot continue at all. Then JavaScript throws an error: it stops the program and prints a report about what went wrong.
Here is the error you will see most often:
function firstItem(order) {
return order.items[0];
}
const order = { total: 120 };
console.log("processing order");
console.log(firstItem(order));
Output:
processing order
/box/index.js:2
return order.items[0];
^
TypeError: Cannot read properties of undefined (reading '0')
at firstItem (/box/index.js:2:21)
at Object.<anonymous> (/box/index.js:7:13)
The real report goes on with more at lines. They point inside Node itself and start with node:internal, so they are left out here. You can ignore them too.
Read the report in three steps.
1. The error line tells you what went wrong. TypeError: Cannot read properties of undefined (reading '0') means: something was undefined, and the code tried to read [0] from it. The first lines of the report show the line of code, and the caret ^ points at the exact spot. So order.items was undefined, because this order has no items.
Reading a missing property is fine. It just gives undefined. The crash comes one step later, when the code uses that undefined as if it were an array. Most JavaScript crashes happen at exactly this point.
2. The at lines tell you where. This list is called the stack trace. It shows the function calls that were running, with the newest call at the top. The crash happened inside firstItem, on line 2. And firstItem was called from line 7. The two numbers after the file name are the line and the column. Look for the lines that point to your own file, /box/index.js.
3. The normal output tells you when. processing order was printed, so everything before the crash ran. Nothing after it ran.
Now the fix is easy to plan. Line 2 expects items, and line 7 passes an order without them. You could use ?. to skip the missing value, or you could stop with a clear message. The next two lessons show how to catch errors and how to throw your own.
The exercise shows this same report. Pick the answer that reads it correctly.