-
Hajipur, Bihar, 844101
Hajipur, Bihar, 844101
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 Functions
Function Definitions
Function Parameters
Function Invocation
Function Call
Function Apply
Function Bind
Function Closures
JS Arrow Function
JS Objects
JS Objects
JS Object Properties
JS Object Methods
JS Object Display
JS Object Constructors
Object Definitions
Object Get / Set
Object Prototypes
Object Protection
JS Classes & Modules
JS Async Programming
JS Advanced
JS Destructuring
JS Bitwise
JS RegExp
JS Precedence
JS Errors
JS Scope
JS Hoisting
JS Strict Mode
JS this Keyword
JS HTML DOM
DOM Intro
DOM Methods
DOM Document
DOM Elements
DOM HTML
DOM Forms
DOM CSS
DOM Animations
DOM Events
DOM Event Listener
DOM Navigation
DOM Nodes
DOM Collections
DOM Node Lists
JS BOM (Browser Object Model)
JS Web APIs
Web API Intro
Web Validation API
Web History API
Web Storage API
Web Worker API
Web Fetch API
Web Geolocation API
JS AJAX
AJAX Intro
AJAX XMLHttp
AJAX Request
AJAX Response
AJAX XML File
AJAX PHP
AJAX ASP
AJAX Database
AJAX Applications
AJAX Examples
JS JSON
JSON Intro
JSON Syntax
JSON vs XML
JSON Data Types
JSON Parse
JSON Stringify
JSON Objects
JSON Arrays
JSON Server
JSON PHP
JSON HTML
JSON JSONP
JS Graphics & Charts
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:
Syntax Errors – Mistakes in the code structure.
Runtime Errors – Errors that occur during code execution.
Logical Errors – The code runs but produces incorrect results.
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.
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.
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.
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.
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.
Occurs when global URI handling functions receive malformed input.
decodeURIComponent("%"); // URIError: URI malformed
Happens with encodeURI()
, decodeURI()
, encodeURIComponent()
, decodeURIComponent()
.
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.
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.
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.
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.
Use try…catch for code that may fail, like API calls or file operations.
Provide meaningful messages when throwing errors.
Avoid empty catch blocks – log or handle errors properly.
Validate inputs to prevent runtime errors.
Use custom error classes for specific application errors.
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.
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.
Create a function that attempts to access an undefined variable and handle the resulting error using try…catch
.
Write code that throws a TypeError
when trying to call a number as a function. Catch the error and log its message.
Use RangeError
by attempting to create an array with a negative length and handle the error.
Write a function that throws a custom error with throw new Error("Custom error message")
if an argument is missing.
Demonstrate a SyntaxError
by evaluating an invalid string using eval()
inside a try…catch
block.
Write code that throws a URIError
by passing a malformed URI to decodeURIComponent
and catch it.
Create a function that validates input and throws a ValidationError
(custom error class) if the input is invalid.
Use finally
in a try…catch…finally
block to log a message that executes regardless of whether an error occurs.
Write code that tries to access a property of null
and handles the resulting TypeError
.
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
.
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 Functions
Function Definitions
Function Parameters
Function Invocation
Function Call
Function Apply
Function Bind
Function Closures
JS Arrow Function
JS Objects
JS Objects
JS Object Properties
JS Object Methods
JS Object Display
JS Object Constructors
Object Definitions
Object Get / Set
Object Prototypes
Object Protection
JS Classes & Modules
JS Async Programming
JS Advanced
JS Destructuring
JS Bitwise
JS RegExp
JS Precedence
JS Errors
JS Scope
JS Hoisting
JS Strict Mode
JS this Keyword
JS HTML DOM
DOM Intro
DOM Methods
DOM Document
DOM Elements
DOM HTML
DOM Forms
DOM CSS
DOM Animations
DOM Events
DOM Event Listener
DOM Navigation
DOM Nodes
DOM Collections
DOM Node Lists
JS BOM (Browser Object Model)
JS Web APIs
Web API Intro
Web Validation API
Web History API
Web Storage API
Web Worker API
Web Fetch API
Web Geolocation API
JS AJAX
AJAX Intro
AJAX XMLHttp
AJAX Request
AJAX Response
AJAX XML File
AJAX PHP
AJAX ASP
AJAX Database
AJAX Applications
AJAX Examples
JS JSON
JSON Intro
JSON Syntax
JSON vs XML
JSON Data Types
JSON Parse
JSON Stringify
JSON Objects
JSON Arrays
JSON Server
JSON PHP
JSON HTML
JSON JSONP
JS Graphics & Charts