JavaScript Errors & Debugging

Read error messages, handle failures with try/catch and throw your own errors.

Lesson 46 of 56Intermediate13 min read

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

Text
Uncaught TypeError: Cannot read properties of undefined (reading 'name') (line 7)
  1. Type: TypeError tells you what kind of problem it is.
  2. Message: you tried to read .name from something that was undefined.
  3. 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

ErrorUsually means
ReferenceError: x is not definedA typo in a name, or a variable used outside its scope
TypeError: x is not a functionCalling something that isn't a function, often a typo like .lenght()
TypeError: Cannot read properties of undefinedReading a property of something that doesn't exist yet
SyntaxError: Unexpected tokenA missing bracket, quote or comma, so the code can't even start
RangeErrorA number out of range (or, on this site, an infinite loop that was stopped)

try...catch...finally

JavaScript
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

JavaScript
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, TypeError and SyntaxError are the errors you'll see most.
  • try...catch handles errors at run time; finally always runs.
  • throw new Error("message") signals a problem from your own code.
  • Use the console, debugger and simplification to find the cause.

JavaScript Errors Examples

Each example runs in the page. Edit the code and press Run to see what changes.

Example 1

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");
ConsoleEdit the code, then press Run or Ctrl+Enter
Line-by-line explanation
  1. Line 3Works.
  2. Line 4Missing property → undefined (not an error yet).
  3. Line 5Reading .city of undefined → TypeError. The script stops here.
  4. Line 6Never reached. Try user.address?.city on line 5.
Example 2

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);
  }
}
ConsoleEdit the code, then press Run or Ctrl+Enter
Line-by-line explanation
  1. Lines 5 to 7Throw a helpful custom error for bad input.
  2. Lines 12 to 13Try the risky call.
  3. Lines 14 to 15If it throws, show the message and carry on with the next input.
  4. Lines 16 to 18finally runs either way.
Example 3

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}`);
  }
});
ConsoleEdit the code, then press Run or Ctrl+Enter
Line-by-line explanation
  1. Line 2Using a name that doesn't exist → ReferenceError.
  2. Line 3Reading a property of null → TypeError.
  3. Line 4Numbers don't have toUpperCase → TypeError.
  4. Line 5An impossible array length → RangeError.

Common JavaScript Errors Mistakes

Empty catch blocks

Don't
try {
  saveSettings();
} catch (e) {}
Do
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

Don't
try {
  const x = ;   // SyntaxError: the whole script won't even start
} catch (e) {}
Do
// Fix syntax errors in the code. try/catch only handles errors while code runs.

Throwing strings

Don't
throw "Not allowed";
Do
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.

Fill in the blankseasy

Catch the error and print its message.

 {
  JSON.parse("{bad json}");
}  (error) {
  console.log(error.message);
}
Multiple choiceeasy

What does ReferenceError: total is not defined usually mean?

Predict the outputmedium

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");
}
Fix the bugmedium

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);
}
ConsoleEdit the code, then press Run or Ctrl+Enter
Checks
  • divide(10, 2) is 5
  • divide(1, 0) throws an Error
  • Logs the message

JavaScript Errors Quiz

3 questions to check what you learned.

  1. When does the finally block run?

    • Always
    • Only if there was an error
    • Only if there was no error
    • Never
  2. Which error do you get from null.length?

    • ReferenceError
    • SyntaxError
    • RangeError
    • TypeError
  3. 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:

  1. Throws new Error("Age must be a number") if age isn't a number (typeof)
  2. Throws new Error("Age must be between 0 and 120") if it's out of range
  3. Otherwise returns "OK"

Then call it inside try…catch with "twelve" and log the error message.

ConsoleEdit the code, then press Run or Ctrl+Enter
Checks
  • Valid age returns "OK"
  • Non-number throws the right message
  • Out-of-range throws the right message
  • Logs the caught message