Errors are inevitable in programming. JavaScript provides robust tools for catching, handling, and debugging errors effectively.
The try block contains code that may throw an error. The catch block handles it. The finally block always runs:
try {
let result = riskyOperation();
console.log(result);
} catch (error) {
console.error("Something went wrong:", error.message);
} finally {
console.log("This always runs — cleanup code here");
}
try/catch around code that can fail — like network requests, file operations, or JSON parsing. The finally block is perfect for cleanup (closing connections, hiding spinners).
Use throw to create custom errors:
function divide(a, b) {
if (b === 0) {
throw new Error("Division by zero is not allowed");
}
if (typeof a !== "number" || typeof b !== "number") {
throw new TypeError("Both arguments must be numbers");
}
return a / b;
}
try {
console.log(divide(10, 0));
} catch (err) {
console.error(err.name + ":", err.message);
}
JavaScript has several built-in error constructors:
// Standard errors you'll encounter:
new Error("Generic error");
new SyntaxError("Invalid syntax");
new ReferenceError("Variable not defined");
new TypeError("Wrong type");
new RangeError("Value out of range");
new URIError("Invalid URI");
debugger StatementInsert debugger; in your code to pause execution and inspect variables in the browser's developer tools:
function calculateTotal(items) {
let total = 0;
for (let item of items) {
debugger; // Execution pauses here
total += item.price;
}
return total;
}
The console offers much more than just log:
console.log("Standard log message");
console.info("Informational message");
console.warn("Warning — something might be wrong");
console.error("Error — something definitely went wrong");
// Tabular output for arrays of objects
const users = [
{ name: "Alice", age: 30 },
{ name: "Bob", age: 25 }
];
console.table(users);
// Grouping related logs
console.group("User Details");
console.log("Name: Alice");
console.log("Age: 30");
console.groupEnd();
// Timing operations
console.time("loop");
for (let i = 0; i < 1000000; i++) {}
console.timeEnd("loop");
Modern browsers include powerful developer tools. Key panels include:
Press F12 or Ctrl+Shift+I to open DevTools in most browsers.
Consistent code style improves readability. Common conventions include:
// Use 2 spaces for indentation
// Use semicolons consistently
// Use camelCase for variables and functions
// Use PascalCase for classes
// Use descriptive names
const MAX_SIZE = 100; // Constants in UPPER_SNAKE_CASE
function fetchUserData(userId) {
// ...
}
Enable strict mode with "use strict"; at the top of a script or function. It catches common mistakes and prevents unsafe actions:
"use strict";
// These would throw errors in strict mode:
// x = 10; // ReferenceError (no var/let/const)
// delete Object.prototype; // TypeError (cannot delete)
JavaScript follows the ECMAScript (ES) specification:
strict modelet, const, arrow functions, classes, modulesUse Babel or TypeScript to transpile modern JS for older browser support.
safeJSONParse(str) that attempts to parse a JSON string inside a try/catch. If parsing fails, log a descriptive error and return null. Test it with valid JSON ('{"name":"Alice"}') and invalid JSON ('not json'). Also add a console.table showing at least three test cases with their results.