JavaScript

coding learning websites codepractice

JS Basics

JS Variables & Operators

JS Data Types & Conversion

JS Numbers & Math

JS Strings

JS Dates

JS Arrays

JS Control Flow

JS Loops & Iteration

JS Functions

JS Objects

JS Classes & Modules

JS Async Programming

JS Advanced

JS HTML DOM

JS BOM (Browser Object Model)

JS Web APIs

JS AJAX

JS JSON

JS Graphics & Charts

JavaScript Errors


Errors in JavaScript occur when the code cannot be executed properly due to syntax mistakes, logical problems, or runtime issues. Understanding errors is crucial for debugging and writing robust code. JavaScript provides different error types, error objects, and handling mechanisms to help developers manage and recover from errors.

Errors can be broadly categorized into:

  1. Syntax Errors – Mistakes in the code structure.

  2. Runtime Errors – Errors that occur during code execution.

  3. Logical Errors – The code runs but produces incorrect results.

Common JavaScript Error Types

1. SyntaxError

Occurs when the JavaScript parser detects incorrect syntax.

// Missing closing parenthesis
// console.log("Hello World"; // SyntaxError

// Correct usage
console.log("Hello World"); // Logs: Hello World
  • Syntax errors prevent code from executing.

  • Always check for missing brackets, parentheses, or semicolons.

2. ReferenceError

Occurs when a variable or function is referenced but not defined.

console.log(x); // ReferenceError: x is not defined

let y = 10;
console.log(y); // Logs: 10
  • Reference errors are common when variables are spelled incorrectly or used before declaration.

3. TypeError

Occurs when a value is not of the expected type for an operation.

let num = 5;
num.toUpperCase(); // TypeError: num.toUpperCase is not a function
  • Useful for detecting incorrect function calls or operations.

4. RangeError

Occurs when a number is outside the allowed range.

let arr = new Array(-1); // RangeError: Invalid array length
  • Common when working with arrays, numbers, or recursion.

5. EvalError

Rarely used, occurs when there is improper use of the eval() function.

// eval() misuse example
// let x = eval("2 + 2;"); // Valid use
  • Modern JavaScript rarely needs eval, so EvalError is uncommon.

6. URIError

Occurs when global URI handling functions receive malformed input.

decodeURIComponent("%"); // URIError: URI malformed
  • Happens with encodeURI(), decodeURI(), encodeURIComponent(), decodeURIComponent().

Handling Errors with try…catch

The try…catch statement allows you to handle runtime errors gracefully.

try {
  let result = nonExistentFunction(); // Throws ReferenceError
} catch (error) {
  console.log("An error occurred: " + error.message);
} finally {
  console.log("This block executes regardless of error");
}
  • try – Code that may throw an error.

  • catch – Handles the error. error is an Error object.

  • finally – Executes regardless of success or failure.

Throwing Custom Errors

You can create and throw your own errors using throw.

function divide(a, b) {
  if (b === 0) {
    throw new Error("Division by zero is not allowed");
  }
  return a / b;
}

try {
  console.log(divide(10, 0));
} catch (error) {
  console.log(error.message); // Logs: Division by zero is not allowed
}
  • Custom errors help control program flow and provide meaningful messages.

Error Object Properties

When an error occurs, JavaScript creates an Error object with several properties:

  • name – The type of error (ReferenceError, TypeError, etc.)

  • message – The error description

  • stack – The stack trace showing where the error occurred

try {
  null.f(); // TypeError
} catch (error) {
  console.log(error.name);    // TypeError
  console.log(error.message); // Cannot read property 'f' of null
  console.log(error.stack);   // Stack trace
}
  • The stack trace is useful for debugging complex applications.

Custom Error Classes

In ES6, you can extend the Error class to create custom error types.

class ValidationError extends Error {
  constructor(message) {
    super(message); // Call parent constructor
    this.name = "ValidationError"; 
  }
}

try {
  throw new ValidationError("Invalid input");
} catch (error) {
  console.log(error.name);    // ValidationError
  console.log(error.message); // Invalid input
}
  • Custom errors make code more readable and maintainable.

Best Practices for Handling Errors

  1. Use try…catch for code that may fail, like API calls or file operations.

  2. Provide meaningful messages when throwing errors.

  3. Avoid empty catch blocks – log or handle errors properly.

  4. Validate inputs to prevent runtime errors.

  5. Use custom error classes for specific application errors.

Example: Error Handling with Functions

function getUser(id) {
  if (typeof id !== "number") {
    throw new TypeError("ID must be a number");
  }
  if (id <= 0) {
    throw new RangeError("ID must be positive");
  }
  return { id: id, name: "Alice" };
}

try {
  let user = getUser(-1);
  console.log(user);
} catch (error) {
  console.log(`${error.name}: ${error.message}`);
}
  • This function demonstrates input validation, throwing custom messages, and catching errors.

Summary of the Tutorial 

  • JavaScript errors occur due to syntax, runtime, or logical issues.

  • Common error types: SyntaxError, ReferenceError, TypeError, RangeError, EvalError, URIError.

  • Use try…catch…finally to handle runtime errors gracefully.

  • Throw custom errors for better control and debugging.

  • Error objects provide name, message, and stack properties for detailed information.

  • Custom error classes help structure and maintain large applications.

Understanding JavaScript errors is essential for writing robust, maintainable, and bug-free code. Proper error handling ensures that your applications can recover gracefully and provide meaningful feedback to users.


Practice Questions

  1. Create a function that attempts to access an undefined variable and handle the resulting error using try…catch.

  2. Write code that throws a TypeError when trying to call a number as a function. Catch the error and log its message.

  3. Use RangeError by attempting to create an array with a negative length and handle the error.

  4. Write a function that throws a custom error with throw new Error("Custom error message") if an argument is missing.

  5. Demonstrate a SyntaxError by evaluating an invalid string using eval() inside a try…catch block.

  6. Write code that throws a URIError by passing a malformed URI to decodeURIComponent and catch it.

  7. Create a function that validates input and throws a ValidationError (custom error class) if the input is invalid.

  8. Use finally in a try…catch…finally block to log a message that executes regardless of whether an error occurs.

  9. Write code that tries to access a property of null and handles the resulting TypeError.

  10. Create a function that accepts a number and throws different errors based on the value (e.g., TypeError if not a number, RangeError if negative) and handle all errors with try…catch.


JavaScript

online coding class codepractice

JS Basics

JS Variables & Operators

JS Data Types & Conversion

JS Numbers & Math

JS Strings

JS Dates

JS Arrays

JS Control Flow

JS Loops & Iteration

JS Functions

JS Objects

JS Classes & Modules

JS Async Programming

JS Advanced

JS HTML DOM

JS BOM (Browser Object Model)

JS Web APIs

JS AJAX

JS JSON

JS Graphics & Charts

Go Back Top