0% found this document useful (0 votes)
2 views11 pages

Javascript Module 15

The document provides an overview of JavaScript memory management, detailing the differences between heap and stack memory, and explaining how asynchronous operations, event loops, and event propagation work. It covers key concepts like execution context, microtask and callback queues, and event bubbling and capturing, emphasizing their importance in writing efficient JavaScript code. Additionally, it includes examples of asynchronous functions such as setTimeout and setInterval, and how event propagation can be controlled in the DOM.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views11 pages

Javascript Module 15

The document provides an overview of JavaScript memory management, detailing the differences between heap and stack memory, and explaining how asynchronous operations, event loops, and event propagation work. It covers key concepts like execution context, microtask and callback queues, and event bubbling and capturing, emphasizing their importance in writing efficient JavaScript code. Additionally, it includes examples of asynchronous functions such as setTimeout and setInterval, and how event propagation can be controlled in the DOM.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 11

Software Training and Placement Center

Javascript DOM internals, Asynchronous Javascript , Event loop, Task


Queue, Execution Context , Heap Memory , Stack Memory etc.

Heap and Stack Memories :

In JavaScript, memory is managed differently compared to lower-level languages like C or C++.


JavaScript is a garbage-collected language, which means that developers don't need to manage memory
allocation and deallocation explicitly. Instead, the JavaScript engine takes care of memory management,
including allocating memory for variables and objects, and reclaiming memory that is no longer in use
through a process called garbage collection.

However, it's helpful to understand the concepts of heap memory and stack memory, as they still play a
role in how JavaScript code is executed and how memory is managed internally by the JavaScript engine:

Heap Memory:
• The heap is a region of memory used for dynamic memory allocation, where objects, closures,
and other data structures are stored.
• In JavaScript, objects and complex data types are allocated memory on the heap. This includes
arrays, objects, functions, and other dynamically created data structures.
• Memory allocated on the heap is accessed through references, which are stored on the stack or
in registers.
• Memory on the heap is managed by the garbage collector, which periodically scans the heap for
objects that are no longer referenced by the program and frees up memory by reclaiming those
objects.

Stack Memory:
• The stack is a region of memory used for static memory allocation and function call
management.
• In JavaScript, stack memory is used to store primitive data types (such as numbers, booleans,
and strings), as well as function call frames and local variables.
• Each time a function is called, a new stack frame is pushed onto the stack, containing
information such as the function's arguments, local variables, and return address.
• When a function returns, its stack frame is popped from the stack, and control returns to the
calling function.
• The stack operates in a last-in-first-out (LIFO) manner, meaning that the most recently called
function is the first to return.

Relationship:

• In JavaScript, references to objects stored on the heap are typically stored on the stack or in
registers.
• Primitive values stored on the stack can be directly accessed and manipulated, while complex
data types (objects) are accessed indirectly through references.

Address : ByteSplash Training and Placement Center, 4th Floor, No 92/9, PR Layout, Marathahalli, Bengaluru, Karnataka, 560037
Mobile : +91 8660803099 / +91 6301062858 , Email : [email protected]
Software Training and Placement Center

• JavaScript engines use a combination of heap memory and stack memory to manage the
execution of JavaScript code and the allocation of memory for variables and objects.

Understanding the concepts of heap memory and stack memory can provide insights into how memory
is managed internally by the JavaScript engine, but developers don't need to explicitly manage memory
allocation and deallocation in JavaScript code. Instead, they can focus on writing clean, efficient code,
and let the JavaScript engine handle memory management behind the scenes.

Stack and Heap Memory Snapshots:

Asynchronous Operations:
Asynchronous operations in JavaScript allow certain tasks to be executed independently of the main
program flow. These tasks include I/O operations like fetching data from a server, reading from a file, or
waiting for user input. Instead of blocking the execution of subsequent code while waiting for these
tasks to complete, JavaScript allows the program to continue executing other code concurrently.

Asynchronous JavaScript allows you to perform tasks without blocking the main thread, enabling non-
blocking I/O operations and concurrent execution of code. Here are some common examples of
asynchronous JavaScript with explanations:

Code :

Address : ByteSplash Training and Placement Center, 4th Floor, No 92/9, PR Layout, Marathahalli, Bengaluru, Karnataka, 560037
Mobile : +91 8660803099 / +91 6301062858 , Email : [email protected]
Software Training and Placement Center

1. setTimeout()

Code :
console.log('Start');

setTimeout(() => {
console.log('Inside setTimeout');
}, 2000);

console.log('End');

2. Event Listeners:

Code :
console.log('Start');

document.getElementById('myButton').addEventListener('click', () => {
console.log('Button clicked');
});

console.log('End');

Explanation: Event listeners are asynchronous in nature. In this example, "Start" and "End" are
logged immediately, while "Button clicked" is logged when the button with ID "myButton" is clicked

Asynchronous JavaScript allows you to write code that performs tasks in the background, improving
responsiveness and user experience in web applications. Understanding and effectively using
asynchronous patterns is essential for building modern web applications.

setTimeout() and setInterval():


setTimeout and setInterval are both JavaScript functions used to execute code asynchronously after
a certain delay or at regular intervals, respectively. Let's explore each of them:

setTimeout:
The setTimeout function is used to execute a function or evaluate an expression after a specified
delay in milliseconds.

Code Syntax :
setTimeout(function, delay, param1, param2, ...);

function: A function to be executed after the delay.

Address : ByteSplash Training and Placement Center, 4th Floor, No 92/9, PR Layout, Marathahalli, Bengaluru, Karnataka, 560037
Mobile : +91 8660803099 / +91 6301062858 , Email : [email protected]
Software Training and Placement Center

delay: The delay in milliseconds before the function is executed.


param1, param2, ...: Optional additional parameters to be passed to the function.

Code :
console.log('Start');

setTimeout(() => {
console.log('Inside setTimeout');
}, 2000);

console.log('End');

In this example, "Start" and "End" are logged immediately, while "Inside setTimeout" is
logged after a delay of 2 seconds.

setInterval:

The setInterval function is used to repeatedly execute a function or evaluate an expression


at a specified interval.

Code syntax :
setInterval(function, interval, param1, param2, ...);

function: A function to be repeatedly executed.


interval: The interval in milliseconds between each execution of the function.
param1, param2, ...: Optional additional parameters to be passed to the function.

Code Example :
let counter = 0;

const intervalId = setInterval(() => {


console.log('Counter:', counter);
counter++;
}, 1000);

// To stop the interval after 5 seconds


setTimeout(() => {
clearInterval(intervalId);
console.log('Interval stopped');
}, 5000);

Address : ByteSplash Training and Placement Center, 4th Floor, No 92/9, PR Layout, Marathahalli, Bengaluru, Karnataka, 560037
Mobile : +91 8660803099 / +91 6301062858 , Email : [email protected]
Software Training and Placement Center

In this example, the function passed to setInterval is executed every 1 second, logging the value of
the counter. After 5 seconds, the clearInterval function is called to stop the interval, and "Interval
stopped" is logged.

Conclusion:
setTimeout and setInterval are powerful tools for executing code asynchronously after a delay or at
regular intervals, respectively. However, they should be used carefully to avoid performance issues
and ensure optimal user experience in web applications.

Browser Memory - Call Stack , MicroStack Queue, Macro Task queue, Event Loop etc.
Event Loop:
The event loop is a fundamental mechanism in JavaScript that continuously checks the call stack
and the task queue, ensuring that tasks are executed in the correct order. It allows JavaScript to
handle asynchronous tasks efficiently without blocking the main program flow.

Address : ByteSplash Training and Placement Center, 4th Floor, No 92/9, PR Layout, Marathahalli, Bengaluru, Karnataka, 560037
Mobile : +91 8660803099 / +91 6301062858 , Email : [email protected]
Software Training and Placement Center

Callback Queue (Task Queue / Macrotask Queue):


• The callback queue holds tasks that are less urgent or have a lower priority compared to
microtasks.
• Tasks in the callback queue include I/O operations like fetching data from a server (fetch),
user interactions such as click events, and asynchronous functions like setTimeout and
setInterval.
• When the call stack is empty, tasks from the callback queue are processed one by one,
starting with the oldest task in the queue.
• The callback queue ensures that asynchronous tasks are executed in the correct order and
do not block the main thread.

Microtask Queue:
• The microtask queue holds tasks with higher priority than regular tasks in the callback
queue.
• Microtasks are executed before regular tasks in the event loop, ensuring that they are
processed as soon as possible.
• Tasks in the microtask queue include promise callbacks (then() and catch() methods), async
functions, and certain DOM events like mutationObserver.
• Microtasks are often used for handling promise resolutions, updating the UI, and executing
critical tasks that should not be delayed.

Differences:
• Priority: Microtasks have higher priority than regular tasks in the callback queue. They are
executed before regular tasks, ensuring that critical tasks are processed as soon as possible.
• Order of Execution: Microtasks are always executed before regular tasks in the event loop,
while regular tasks are processed after the microtask queue is empty.
• Use Cases: Microtasks are typically used for handling promise resolutions, updating the UI,
and executing critical tasks that should not be delayed, while regular tasks in the callback
queue include I/O operations, user interactions, and asynchronous functions.
Example Code :

Address : ByteSplash Training and Placement Center, 4th Floor, No 92/9, PR Layout, Marathahalli, Bengaluru, Karnataka, 560037
Mobile : +91 8660803099 / +91 6301062858 , Email : [email protected]
Software Training and Placement Center

console.log('Start');

setTimeout(() => {
console.log('setTimeout (callback queue)');
}, 0);

Promise.resolve().then(() => {
console.log('Promise (microtask queue)');
});

console.log('End');

Output :
Start
End
Promise (microtask queue)
setTimeout (callback queue)

In this example, the microtask (Promise) is executed before the regular task (setTimeout) in the
event loop, demonstrating the priority difference between microtasks and regular tasks.

Understanding the differences between the callback queue and the microtask queue is crucial
for writing efficient and responsive JavaScript code, especially when dealing with asynchronous
operations and managing code execution order. By leveraging both types of queues effectively,
developers can ensure smooth and optimal performance in web applications.

Execution Context:
Execution context refers to the environment in which JavaScript code is executed. Each time a
function is invoked, a new execution context is created, which includes the function's scope
chain, variable environment, and reference to the outer lexical environment. The execution
context maintains the state of the function's execution, including local variables, arguments,
and the value of this.

How They Work Together:


• When JavaScript code is executed, it creates the initial execution context (global
execution context) and starts executing code line by line.
• Asynchronous operations (e.g., setTimeout, fetch) are encountered, and their
corresponding callback functions are registered to be executed later.
• When an asynchronous operation completes or a callback function is ready to be
executed, the event loop adds the task to the task queue or task tracker, depending on
the type of task.
• The event loop continuously checks the call stack. When the call stack is empty, it
moves tasks from the task tracker to the call stack first and then from the task queue.

Address : ByteSplash Training and Placement Center, 4th Floor, No 92/9, PR Layout, Marathahalli, Bengaluru, Karnataka, 560037
Mobile : +91 8660803099 / +91 6301062858 , Email : [email protected]
Software Training and Placement Center

• Tasks in the call stack are executed one by one, and the process continues until all tasks
are completed.

Look for the below image for working animation :

Click here to check file :https://media.licdn.com/dms/image/D4D22AQH994OiKI-l1g/feedshare-


shrink_1280/0/1713292150380?e=1720051200&v=beta&t=oR-
t0pW93HDV4s4aDkcavnGvjavBobqOp9CzdkaZAJU

Event Bubbling , Event Capturing and Event Propogation:

Event bubbling, capturing, and propagation are essential concepts in event handling in JavaScript and
are crucial for understanding how events propagate through the DOM hierarchy. Let's explore each of
these concepts:

Event Propagation:
Event propagation refers to the process by which events traverse through the DOM hierarchy from the
target element to its ancestors (bubbling) or from the top-level ancestor to the target element
(capturing). This propagation mechanism allows multiple elements to respond to the same event.

Address : ByteSplash Training and Placement Center, 4th Floor, No 92/9, PR Layout, Marathahalli, Bengaluru, Karnataka, 560037
Mobile : +91 8660803099 / +91 6301062858 , Email : [email protected]
Software Training and Placement Center

Event Bubbling:
Event bubbling is the default behavior in which an event is first handled by the target element that
triggered the event, and then it bubbles up through its ancestors in the DOM hierarchy, triggering
corresponding event handlers on each ancestor element up to the root of the document.

Code :
<div id="parent">
<button id="child">Click me</button>
</div>

<script>
document.getElementById('parent').addEventListener('click', function() {
console.log('Parent clicked');
});

document.getElementById('child').addEventListener('click', function() {
console.log('Child clicked');
});
</script>

In this example, if you click the button with the id "child," the event will first trigger the event handler
attached to the button (child), then bubble up to the parent div, triggering its event handler.

Event Capturing:
Event capturing is the opposite of event bubbling. During the capturing phase, the event starts at the
top-level ancestor of the target element and propagates down through the DOM hierarchy until it
reaches the target element.

Address : ByteSplash Training and Placement Center, 4th Floor, No 92/9, PR Layout, Marathahalli, Bengaluru, Karnataka, 560037
Mobile : +91 8660803099 / +91 6301062858 , Email : [email protected]
Software Training and Placement Center

Code :
<div id="parent">
<button id="child">Click me</button>
</div>

<script>
document.getElementById('parent').addEventListener('click', function() {
console.log('Parent clicked');
}, true); // true indicates capturing phase

document.getElementById('child').addEventListener('click', function() {
console.log('Child clicked');
}, true); // true indicates capturing phase
</script>

In this example, if you click the button with the id "child," the event will first trigger the event handler
attached to the parent div during the capturing phase, and then it will propagate down to the button,
triggering its event handler.

Working Model :

Stopping Propagation:
You can stop event propagation using the stopPropagation() method on the event object. This prevents
the event from further propagation in both the capturing and bubbling phases.

Address : ByteSplash Training and Placement Center, 4th Floor, No 92/9, PR Layout, Marathahalli, Bengaluru, Karnataka, 560037
Mobile : +91 8660803099 / +91 6301062858 , Email : [email protected]
Software Training and Placement Center

Understanding event bubbling, capturing, and propagation is essential for effective event handling in
JavaScript, allowing you to control how events are processed and responded to within the DOM
hierarchy.

Address : ByteSplash Training and Placement Center, 4th Floor, No 92/9, PR Layout, Marathahalli, Bengaluru, Karnataka, 560037
Mobile : +91 8660803099 / +91 6301062858 , Email : [email protected]

You might also like