When writing JavaScript, errors are inevitable, especially as you learn. Understanding the two main types of errors — syntax errors and runtime errors — helps you quickly identify and fix problems in your code.
Syntax errors happen when your code violates the rules of JavaScript’s language structure. They are like grammar mistakes in a sentence.
let x = 10 // Missing semicolon (optional but good practice)
let y = ; // Syntax error: unexpected token ";"
function() { console.log("Hi") } // Missing function name
Browsers catch syntax errors before running the code, so the script won’t execute until you fix them. The browser’s developer console usually shows a clear message pointing to the line with the syntax error, like “Unexpected token” or “Missing )”.
Runtime errors occur when your code is syntactically correct but something goes wrong while the program runs.
let num = 10;
console.log(num.toUpperCase()); // Runtime error: toUpperCase is not a function
let obj = null;
console.log(obj.name); // Runtime error: Cannot read property 'name' of null
Unlike syntax errors, runtime errors occur during execution, which means your script starts but then crashes or behaves unexpectedly. Browsers report runtime errors with messages like “TypeError”, “ReferenceError”, or “RangeError” in the console.
undefined
or null
leads to runtime errors.Knowing the difference between syntax and runtime errors is the first step to effective debugging and writing robust JavaScript code!
try
, catch
, finally
In JavaScript, error handling is crucial for building resilient applications that don't crash unexpectedly. The try
, catch
, and finally
blocks allow you to run code safely and handle errors gracefully when they occur.
try
BlockThe try
block contains the code that might throw an error during execution. If an error occurs inside try
, the normal program flow stops and control moves to the catch
block.
try {
// Code that may cause an error
let result = riskyOperation();
console.log(result);
}
catch
BlockThe catch
block catches the error thrown in the try
block and allows you to handle it without crashing your program.
try {
let data = JSON.parse('invalid JSON string');
} catch (error) {
console.error('Parsing failed:', error.message);
}
Here, instead of the script crashing on invalid JSON, the error is caught and logged.
finally
BlockThe finally
block runs after the try
and catch
blocks, regardless of whether an error occurred or not. Use it for cleanup actions like closing files or releasing resources.
try {
console.log('Trying something risky...');
// Code that may throw
} catch (error) {
console.error('Caught an error:', error);
} finally {
console.log('This always runs, no matter what.');
}
function safeDivide(a, b) {
try {
if (b === 0) {
throw new Error('Cannot divide by zero');
}
return a / b;
} catch (error) {
console.error('Error:', error.message);
return null; // Graceful fallback
} finally {
console.log('Division attempt finished');
}
}
console.log(safeDivide(10, 2)); // Outputs: 5
console.log(safeDivide(10, 0)); // Logs error and outputs: null
try
, catch
, finally
try
to wrap code that may fail (e.g., parsing data, network requests).catch
to handle errors and prevent crashes.finally
for cleanup that must happen no matter what, like closing connections or resetting variables.By using try
, catch
, and finally
, you can make your JavaScript programs more robust, user-friendly, and easier to debug.
throw
StatementIn JavaScript, you can manually trigger errors using the throw
statement. This is useful for signaling exceptional situations in your code that require special handling or to stop execution when something goes wrong.
throw
WorksThe throw
statement lets you generate an error of any type, but typically you throw an Error object or one of its subclasses (like TypeError
, RangeError
). When an error is thrown, the normal flow of the program immediately stops and control jumps to the nearest catch
block (if one exists).
Syntax:
throw expression;
You can create meaningful errors with clear messages to help debugging and communicate problems:
function checkAge(age) {
if (age < 18) {
throw new Error('User must be at least 18 years old.');
}
return 'Access granted';
}
try {
console.log(checkAge(16));
} catch (error) {
console.error('Error:', error.message);
}
Here, throw
creates a new error that stops execution if the age is less than 18. The catch
block then handles it gracefully.
JavaScript has built-in error types you can use for more specific error handling:
throw new TypeError('Expected a number but got a string');
throw new RangeError('Value out of allowed range');
Using specific error types improves clarity when debugging or logging errors.
throw
?throw
throw
with try...catch
blocks to handle errors properly.Manually throwing errors with throw
empowers you to write safer, more predictable JavaScript by explicitly managing when and how your program handles problems.
Debugging is an essential skill for every JavaScript developer. Modern browsers like Chrome and Firefox come with powerful Developer Tools that help you find and fix issues in your code efficiently. Here’s a hands-on guide to get you started with debugging.
F12
or Ctrl + Shift + I
(Windows/Linux) or Cmd + Option + I
(Mac).F12
or Ctrl + Shift + I
(Windows/Linux) or Cmd + Option + I
(Mac).This opens a panel with multiple tabs like Elements, Console, Sources (Chrome) or Debugger (Firefox).
The Console tab shows errors, warnings, and logs:
console.log()
, console.error()
, or console.warn()
in your code to print messages here.Breakpoints pause code execution at a specific line so you can inspect the program’s state.
The code will stop when it reaches this line during execution.
When paused on a breakpoint:
Use the controls to move through your code step-by-step:
Suppose you have this code:
function add(a, b) {
return a + b;
}
let result = add(5, '3');
console.log(result); // Outputs "53" instead of 8
return
line.a
and b
and see that b
is a string.b
to a number before adding.alert()
for cleaner debugging.Mastering Developer Tools gives you powerful insight into your JavaScript code, helping you find bugs faster and write better software!