Learn JavaScript · lesson 37 of 60 · about 8 minutes
Reading Error Messages
Show the newest comment on Sam's page: find the cause of an error from its message, and recognise ReferenceError, TypeError and SyntaxError.
What you'll learn
- Read an error's type and message
- Recognise common error types
- Use the stack's line number
The newest comment
Sam wants the page to show the newest comment, so a line was added: comments[comments.length - 1].text. It worked, until a new post had no comments yet. Then the whole page stopped with TypeError: Cannot read properties of undefined (reading 'text'), pointing at that line. The message says exactly what went wrong: there was no comment, so there was nothing to read text from. The fix is to check for the comment first, and to say a guest when a comment has no author.
Errors tell you what and where
When JavaScript hits a problem, it throws an error with:
- a type, like TypeError
- a message describing the problem
- a stack showing the file and line number where it happened
Read the type and message first, then jump to that line.
The usual suspects
| Error | Usually means |
|---|---|
| ReferenceError | A name is misspelt or out of scope |
| TypeError | Using a value the wrong way, like calling a non-function or reading a property of undefined |
| SyntaxError | The code itself isn't valid, like a missing bracket |
| RangeError | A number is out of an allowed range |
Catching an error to look at it
try {
const user = undefined;
console.log(user.name);
} catch (err) {
console.log(err.name);
console.log(err.message);
}Output
TypeError
Cannot read properties of undefined (reading 'name')Tip
"Cannot read properties of undefined" is the most common JavaScript error. It means something you expected to be an object wasn't there. Check the thing before the dot.
Check before you read
Reading past the end of an array gives undefined, not an error. The error comes one step later, when you read a property of that undefined. So check the item before using it, with if or ? :, and use ?? for a property that might be missing.
No comments, no crash
const comments = [];
const latest = comments[comments.length - 1];
console.log(latest);
console.log(latest ? latest.text : "No comments yet");
const one = { text: "Nice!" };
console.log(one.author ?? "a guest");Output
undefined
No comments yet
a guestNow try it yourself
This lesson is free in Codiqo, with 9 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.