Javascript Module 15
Javascript Module 15
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.
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:
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, ...);
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 :
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:
Code syntax :
setInterval(function, interval, param1, param2, ...);
Code Example :
let counter = 0;
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
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.
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.
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]