Errors aren't failures. They're the computer telling you exactly what went wrong and where. Learning to read error messages calmly is one of the most valuable skills a developer can have, and it turns hours of guessing into minutes of fixing.
There are two sides to this lesson. The first is reading and fixing the errors in your own code. The second is handling problems that can happen while a program runs, such as bad data or a lost network connection. For those, try...catch lets your program recover gracefully instead of stopping.
How to read an error message
Uncaught TypeError: Cannot read properties of undefined (reading 'name') (line 7)- Type:
TypeErrortells you what kind of problem it is. - Message: you tried to read
.namefrom something that wasundefined. - Location: line 7. Look at that line, and at the values of the variables it uses.
The line in the message is where the problem showed up, which isn't always where it started. If line 7 reads user.name, the real question is why user was undefined, and the answer may be a few lines earlier.
The JavaScript errors you'll meet most
| Error | Usually means |
|---|---|
ReferenceError: x is not defined | A typo in a name, or a variable used outside its scope |
TypeError: x is not a function | Calling something that isn't a function, often a typo like .lenght() |
TypeError: Cannot read properties of undefined | Reading a property of something that doesn't exist yet |
SyntaxError: Unexpected token | A missing bracket, quote or comma, so the code can't even start |
RangeError | A number out of range (or, on this site, an infinite loop that was stopped) |
try...catch...finally
try {
// code that might fail
} catch (error) {
// runs only if something in try threw an error
console.log(error.message);
} finally {
// always runs (optional), useful for cleaning up
}catch stops the error from crashing the rest of your program. Use it around code that can fail for reasons outside your control, such as reading JSON or loading data. Don't wrap everything in try to hide bugs; a bug should be fixed, not silenced.
Throwing your own errors
function withdraw(amount) {
if (amount <= 0) {
throw new Error("Amount must be positive");
}
// …
}throw stops the function immediately and passes the error to the nearest catch. Throwing a clear error with a helpful message makes problems much easier to track down than letting bad data travel silently through your program.
JavaScript Errors Syntax
Error handling
try {
riskyThing();
} catch (error) {
console.error(error.name, error.message);
} finally {
cleanUp();
}
throw new Error("Something went wrong");JavaScript Errors Summary
- An error message tells you the type of problem, what happened and where.
ReferenceError,TypeErrorandSyntaxErrorare the errors you'll see most.try...catchhandles errors at run time;finallyalways runs.throw new Error("message")signals a problem from your own code.- Use the console,
debuggerand simplification to find the cause.
JavaScript Errors Examples
Each example runs in the page. Edit the code and press Run to see what changes.
Errors in action
Run it and read each error message. Then fix them one by one.
const user = { name: "Ava" };
console.log(user.name);
console.log(user.address);
console.log(user.address.city);
console.log("This never runs");Line-by-line explanation
- Line 3Works.
- Line 4Missing property →
undefined(not an error yet). - Line 5Reading
.cityofundefined→ TypeError. The script stops here. - Line 6Never reached. Try
user.address?.cityon line 5.
Recovering with try…catch
const inputs = ["42", "seven", "1e3"];
function toNumber(text) {
const n = Number(text);
if (Number.isNaN(n)) {
throw new Error(`"${text}" is not a number`);
}
return n;
}
for (const text of inputs) {
try {
console.log("✅", toNumber(text));
} catch (error) {
console.log("❌", error.message);
} finally {
console.log("checked:", text);
}
}Line-by-line explanation
- Lines 5 to 7Throw a helpful custom error for bad input.
- Lines 12 to 13Try the risky call.
- Lines 14 to 15If it throws, show the message and carry on with the next input.
- Lines 16 to 18
finallyruns either way.
Error types
const tests = [
() => undefinedVariable,
() => null.length,
() => (5).toUpperCase(),
() => new Array(-1),
];
tests.forEach((test, i) => {
try {
test();
} catch (error) {
console.log(`${i + 1}. ${error.name}: ${error.message}`);
}
});Line-by-line explanation
- Line 2Using a name that doesn't exist → ReferenceError.
- Line 3Reading a property of null → TypeError.
- Line 4Numbers don't have toUpperCase → TypeError.
- Line 5An impossible array length → RangeError.
Common JavaScript Errors Mistakes
Empty catch blocks
try {
saveSettings();
} catch (e) {}try {
saveSettings();
} catch (error) {
console.error("Couldn't save settings:", error);
showMessage("Sorry, your settings weren't saved.");
}Silently swallowing errors hides bugs. At least log them, and tell the user if it affects them.
Using try…catch for syntax errors
try {
const x = ; // SyntaxError: the whole script won't even start
} catch (e) {}// Fix syntax errors in the code. try/catch only handles errors while code runs.Throwing strings
throw "Not allowed";throw new Error("Not allowed");Error objects include a stack trace showing where the problem happened.
JavaScript Errors in Real Projects
Errors in production
Real apps wrap risky operations, such as network requests, parsing uploaded files and reading storage, in error handling. They show friendly messages to visitors and send the technical details to monitoring tools so developers can fix them. Learning to read error details calmly is a real advantage.
JavaScript Errors Exercises
Answer each one and check it instantly. If you get stuck, open the hint before the answer.
Catch the error and print its message.
{
JSON.parse("{bad json}");
} (error) {
console.log(error.message);
}
try { } catch (error) { } handles run-time errors.What does ReferenceError: total is not defined usually mean?
What does this print?
try {
console.log("A");
throw new Error("B");
console.log("C");
} catch (e) {
console.log(e.message);
} finally {
console.log("D");
}divide(10, 0) should throw an Error with the message Cannot divide by zero, and the code should catch it and log that message. Fix it.
function divide(a, b) {
if (b === 0) {
return "Cannot divide by zero";
}
return a / b;
}
try {
divide(10, 0);
} catch (error) {
console.log(error.message);
}- divide(10, 2) is 5
- divide(1, 0) throws an Error
- Logs the message
JavaScript Errors Quiz
3 questions to check what you learned.
When does the
finallyblock run?- Always
- Only if there was an error
- Only if there was no error
- Never
Which error do you get from
null.length?- ReferenceError
- SyntaxError
- RangeError
- TypeError
Can try…catch catch a SyntaxError in the same script?
- Yes, always
- No. Syntax errors stop the script before it runs
- Only in functions
- Only with finally
JavaScript Errors Challenge
Validate an age
Write checkAge(age) that:
- Throws
new Error("Age must be a number")ifageisn't a number (typeof) - Throws
new Error("Age must be between 0 and 120")if it's out of range - Otherwise returns
"OK"
Then call it inside try…catch with "twelve" and log the error message.
- Valid age returns "OK"
- Non-number throws the right message
- Out-of-range throws the right message
- Logs the caught message