0% found this document useful (0 votes)
4 views12 pages

Understanding DOM Events and Asynchronous JavaScript

The document covers various aspects of DOM events, including event delegation, bubbling, and capturing, as well as asynchronous programming concepts like the call stack, promises, and async/await. It explains how to handle API requests using AJAX, Fetch, and Axios, along with HTTP verbs for resource manipulation. Additionally, it addresses callback hell and provides examples to illustrate each concept.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as ODT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views12 pages

Understanding DOM Events and Asynchronous JavaScript

The document covers various aspects of DOM events, including event delegation, bubbling, and capturing, as well as asynchronous programming concepts like the call stack, promises, and async/await. It explains how to handle API requests using AJAX, Fetch, and Axios, along with HTTP verbs for resource manipulation. Additionally, it addresses callback hell and provides examples to illustrate each concept.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as ODT, PDF, TXT or read online on Scribd

DOM Events

Event Delegation
Event delegation is a technique used to attach event listeners to a parent element instead of
individual child elements. This approach reduces the number of event listeners and improves
performance.

Example:

<!-- HTML -->


<ul id="list">
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
</ul>

// JavaScript
const list = [Link]('list');

[Link]('click', function(event) {
if ([Link] === 'LI') {
[Link]('List item clicked:', [Link]);
}
});

Event Bubbling and Capturing


Event bubbling and capturing are two phases of event propagation in the DOM.

- Event Capturing: The event propagates from the root element to the target element.
- Event Bubbling: The event propagates from the target element to the root element.

Example:

<!-- HTML -->


<div id="container">
<p id="paragraph">Hello World!</p>
</div>
// JavaScript
const container = [Link]('container');
const paragraph = [Link]('paragraph');

// Event capturing
[Link]('click', function() {
[Link]('Container clicked (capturing)');
}, true);

[Link]('click', function() {
[Link]('Paragraph clicked (capturing)');
}, true);

// Event bubbling
[Link]('click', function() {
[Link]('Container clicked (bubbling)');
});

[Link]('click', function() {
[Link]('Paragraph clicked (bubbling)');
});

Asynchronous Programming
Call Stack
The call stack is a data structure that keeps track of the functions that are currently being
executed. When a function is called, it is added to the top of the call stack. When a function
completes its execution, it is removed from the call stack.

Example:

function a() {
[Link]('Function a');
b();
}

function b() {
[Link]('Function b');
c();
}

function c() {
[Link]('Function c');
}
a();

Visualization
Visualization of the call stack can help in understanding the execution flow of functions.

Example:

Call Stack:
- c (currently executing)
- b (waiting to complete)
- a (waiting to complete)

Breakpoints
Breakpoints are used to pause the execution of code at a specific point. This allows developers
to inspect variables and the call stack.

Example:

function a() {
[Link]('Function a');
debugger; // Breakpoint
b();
}

Single-Threaded
JavaScript is single-threaded, meaning it can only execute one task at a time. This is in contrast
to multi-threaded languages, which can execute multiple tasks concurrently.

Example:

function a() {
[Link]('Function a');
// Simulate a long-running task
for (let i = 0; i < 100000000; i++) {}
[Link]('Function a completed');
}

a();
[Link]('Next task');
Callback Hell
Callback hell refers to the situation where callbacks are nested within each other, making the
code difficult to read and maintain.

Example:

function a(callback) {
[Link]('Function a');
callback(function() {
[Link]('Callback 1');
callback(function() {
[Link]('Callback 2');
});
});
}

a(function(callback) {
[Link]('Callback 0');
callback();
});

Promises
Promises are used to handle asynchronous operations in a more manageable way. A promise
represents a value that may not be available yet, but will be resolved at some point in the future.

Example:

function a() {
return new Promise((resolve, reject) => {
[Link]('Function a');
// Simulate a long-running task
setTimeout(() => {
resolve('Result from function a');
}, 2000);
});
}

a().then((result) => {
[Link]('Result:', result);
});
Resolve and Reject
The resolve function is used to resolve a promise with a value, while the reject function is used
to reject a promise with an error.

Example:

function a() {
return new Promise((resolve, reject) => {
[Link]('Function a');
// Simulate a long-running task
setTimeout(() => {
// Resolve the promise
resolve('Result from function a');
// Reject the promise
// reject(new Error('Error in function a'));
}, 2000);
});
}

a().then((result) => {
console

[2:44 pm, 10/2/2025] Manu: Here is the continuation of the explanation:

State
A promise can be in one of three states:

1. Pending: Initial state, neither fulfilled nor rejected.


2. Fulfilled: Successful operation, promise is resolved.
3. Rejected: Failed operation, promise is rejected.

Example:

function a() {
return new Promise((resolve, reject) => {
[Link]('Function a');
// Simulate a long-running task
setTimeout(() => {
resolve('Result from function a');
}, 2000);
});
}
const promise = a();
[Link](promise); // Promise { <pending> }

Then and Catch


The then() method is used to handle the resolved value of a promise, while the catch() method
is used to handle any errors that may have occurred.

Example:

function a() {
return new Promise((resolve, reject) => {
[Link]('Function a');
// Simulate a long-running task
setTimeout(() => {
resolve('Result from function a');
}, 2000);
});
}

a()
.then((result) => {
[Link]('Result:', result);
})
.catch((error) => {
[Link]('Error:', error);
});

Promise Chaining
Promise chaining allows you to chain multiple promises together, creating a sequence of
asynchronous operations.

Example:

function a() {
return new Promise((resolve, reject) => {
[Link]('Function a');
// Simulate a long-running task
setTimeout(() => {
resolve('Result from function a');
}, 2000);
});
}

function b(result) {
return new Promise((resolve, reject) => {
[Link]('Function b');
// Simulate a long-running task
setTimeout(() => {
resolve('Result from function b: ' + result);
}, 2000);
});
}

a()
.then((result) => {
return b(result);
})
.then((result) => {
[Link]('Final result:', result);
})
.catch((error) => {
[Link]('Error:', error);
});

Async Functions
Async functions are a way to write asynchronous code that's easier to read and maintain.

Example:

async function a() {


[Link]('Function a');
// Simulate a long-running task
const result = await new Promise((resolve, reject) => {
setTimeout(() => {
resolve('Result from function a');
}, 2000);
});
return result;
}

async function main() {


try {
const result = await a();
[Link]('Result:', result);
} catch (error) {
[Link]('Error:', error);
}
}

main();

Async and Await


The async keyword is used to define an async function, while the await keyword is used to
pause the execution of an async function until a promise is resolved.

Example:

async function a() {


[Link]('Function a');
// Simulate a long-running task
const result = await new Promise((resolve, reject) => {
setTimeout(() => {
resolve('Result from function a');
}, 2000);
});
return result;
}

async function main() {


try {
const result = await a();
[Link]('Result:', result);
} catch (error) {
[Link]('Error:', error);
}
}

main();

Handling Rejections with Await


When using await with promises, you can use try-catch blocks to handle rejections.

Example:
async function a() {
[Link]('Function a');
// Simulate a long-running task
const result = await new Promise((resolve, reject) => {
setTimeout(() => {
reject(new Error('Error in function a'));
}, 2000);
});
return result;
}

async function main() {


try {
const result = await a();
[Link]('Result:', result);
} catch (error) {
[Link]('Error:', error);
}
}

main();

APIs
An API (Application Programming Interface) is a set of rules and protocols that allows different
applications to communicate with each other.

Example:

// API endpoint
const apiUrl = '[Link]

// Make a GET request to the API endpoint


fetch(apiUrl)
.then((response) => [Link]())
.then((data) => [Link](data))
.catch((error) => [Link](error));

JSON
JSON (JavaScript Object Notation) is a lightweight data interchange format that is easy to read
and write.

Example:

// JSON data
const jsonData = {
"name": "John Doe",
"

[2:44 pm, 10/2/2025] Manu: Here is the continuation of the explanation:

AJAX
AJAX (Asynchronous JavaScript and XML) is a technique used to update parts of a web page
without requiring a full page reload.

Example:

// Create an XMLHttpRequest object


const xhr = new XMLHttpRequest();

// Define the callback function


[Link] = function() {
if ([Link] >= 200 && [Link] < 300) {
[Link]([Link]);
} else {
[Link]([Link]);
}
};

// Define the error callback function


[Link] = function() {
[Link]([Link]);
};

// Open the request


[Link]('GET', '[Link] true);

// Send the request


[Link]();

HTTP Verbs
HTTP verbs are used to define the action that should be performed on a resource. The most
common HTTP verbs are:

- GET: Retrieve a resource


- POST: Create a new resource
- PUT: Update an existing resource
- DELETE: Delete a resource

Example:

// Create an XMLHttpRequest object


const xhr = new XMLHttpRequest();

// Define the callback function


[Link] = function() {
if ([Link] >= 200 && [Link] < 300) {
[Link]([Link]);
} else {
[Link]([Link]);
}
};

// Define the error callback function


[Link] = function() {
[Link]([Link]);
};

// Open the request with the HTTP verb


[Link]('POST', '[Link] true);

// Set the request headers


[Link]('Content-Type', 'application/json');

// Send the request with the data


[Link]([Link]({ name: 'John Doe', age: 30 }));

Fetch
The Fetch API provides an easy, logical way to fetch resources asynchronously across the
network. It returns a Promise that resolves to the Response to that request, whether it is
successful or not.

Example:
// Fetch API
fetch('[Link]
.then((response) => [Link]())
.then((data) => [Link](data))
.catch((error) => [Link](error));

Axios
Axios is a popular JavaScript library used for making HTTP requests from [Link] or
XMLHttpRequests from the browser. It provides an easy-to-use API for sending HTTP requests
and interacting with web servers.

Example:

// Axios
[Link]('[Link]
.then((response) => [Link]([Link]))
.catch((error) => [Link](error));

I hope this completes the explanation of all the topics. Let me know if you have any further
questions!

You might also like