JS
JS
Remembering all JavaScript methods can seem overwhelming because there are
so many! However, you don't need to memorize everything. Instead, focus on
understanding key concepts and patterns that will allow you to recall and look up
methods effectively. Here's a guide to help you:
String Methods
.toUpperCase() , .toLowerCase() , .trim() , .slice() , .split() , .includes() ,
.replace() , etc.
Array Methods
.push() , .pop() , .shift() , .unshift() , .splice() ,
, .filter() , .slice() , .map()
Object Methods
Object.keys() , Object.values() , Object.entries() , Object.assign() , Object.freeze() ,
etc.
Math Methods
Math.round() , Math.ceil() , Math.floor() , Math.random() , Math.max() , Math.min() , etc.
Date Methods
.getFullYear() , .getMonth() , .getDate() , .getTime() , .setDate() , .toISOString() , etc.
String Methods
JAVA SCRIPT 1
They typically return a new string (e.g., .slice() , .replace() ) or a boolean
(e.g., .includes() , .startsWith() ).
Array Methods
Methods like .push() , .pop() , and .splice() modify the original array.
Methods like .map() , .filter() , and .slice() return a new array without
modifying the original one.
Math Methods
Math methods often take numbers as arguments and return a number (e.g.,
Math.max() or Math.round() ).
JAVA SCRIPT 2
5. Learn by Doing
The best way to remember methods is to use them often. Build small projects that
require:
String manipulation
Array operations
Object traversal
For example:
7. Rely on Documentation
Nobody remembers every method, not even experienced developers. Instead:
JAVA SCRIPT 3
Use browser DevTools to experiment with methods interactively.
I understand now! You want a more detailed explanation of how to iterate over
each data structure with code examples in the second column. Here's the updated
table with detailed iteration examples:
Data Structure
How to Iterate Important Notes
(Example)
Object {"a": 1, "b": Using for...in loop: for (const key Objects are not
2} in obj) { console.log(key, inherently iterable but
JAVA SCRIPT 4
obj[key]); } Using can be converted into
Object.entries() : for (const [key, arrays of key-value
value] of Object.entries(obj)) { pairs using
console.log(key, value); } Object.entries() .
Arrays of key-value
Using Object.fromEntries() : const pairs (e.g., [[key1,
Array of Key-Value value1], [key2,
obj = Object.fromEntries(array); for
Pairs [["a", 1], ["b", (const [key, value] of value2]] ) can be
2]] Object.entries(obj)) { transformed into
console.log(key, value); }
objects using
Object.fromEntries() .
JAVA SCRIPT 5
array.forEach(item => {
console.log(item); // Outputs: 1, 2, 3
});
Using .forEach() : Iterates through the set, passing each value to a callback
function.
set.forEach(value => {
console.log(value); // Outputs: 1, 2, 3
});
Using for...of loop: Iterates through the key-value pairs in the map.
Using .forEach() : Iterates through the map, passing each key and value to
a callback function.
JAVA SCRIPT 6
}
Using nested for...of loop: Iterates over the array, then uses
Object.entries() to iterate over each object's key-value pairs.
JAVA SCRIPT 7
Using for...of loop: Iterates over the custom iterable.
Using .next() method: Manually calls the next() method to retrieve the
next value from the iterable.
Reusable
A function with
blocks of code,
a declared javascript<br>function greet() {
Named easily
name. Can be console.log("Hello!"); }
Function <br>greet(); referenced in
reused and
debugging or
referenced.
recursion.
A function Callback
without a javascript<br>const add = functionality or
Anonymous
name, often function(a, b) { return a + b; }; dynamically-
Function <br>console.log(add(2, 3));
assigned to assigned
variables. behaviors.
A concise
syntax for Simplified
defining callbacks or
javascript<br>const greet = () =>
Arrow Function functions. console.log("Hi!");<br>greet();
where this
Lexically binds binding is
this (useful in required.
callbacks).
Immediately Encapsulation,
A function that
Invoked javascript<br>(function() { avoiding
is invoked
Function console.log("IIFE executed!"); }) polluting the
immediately ();
Expression global
after definition.
(IIFE) namespace.
JAVA SCRIPT 8
Functions that Managing
can yield infinite
javascript<br>function* numbers()
multiple values sequences,
Generator { yield 1; yield 2; yield 3; }
using yield <br>for (let num of numbers()) lazy evaluation,
Function
and maintain console.log(num); or
state between asynchronous
calls. processes.
javascript<br>function
Object
Functions used Person(name) { this.name = name; }
Constructor creation, often
with new to <br>const person = new
Function Person("Alice"); as a precursor
create objects.
<br>console.log(person.name); to classes.
A function that
returns a
javascript<br>async function Asynchronous
Promise and
Async fetchData() { const data = await operations like
allows fetch('/api'); console.log(data);
Function API calls or
asynchronous }<br>fetchData();
reading files.
code with
await .
A function javascript<br>function
passed as an process(callback) { callback(); } Event handling,
Callback
argument to <br>process(() => asynchronous
Function console.log("Callback
another execution.
executed!"));
function.
Solving
problems with
javascript<br>function
recursive
Recursive A function that factorial(n) { return n === 1 ? 1
: n * factorial(n - 1); } structures,
Function calls itself.
<br>console.log(factorial(5)); such as
factorial or tree
traversal.
A function that
Functional
takes another javascript<br>function
programming
Higher-Order function as an higherOrder(func) { func(); }
constructs like
Function argument or <br>higherOrder(() =>
console.log("Hello from HOF!")); map , reduce ,
returns a
and filter .
function.
JAVA SCRIPT 9
values if no optional
arguments are parameters.
passed.
A function that
Aggregating or
takes an javascript<br>function
processing a
Rest Parameter indefinite sum(...nums) { return
variable
Function number of nums.reduce((a, b) => a + b, 0); }
<br>console.log(sum(1, 2, 3)); number of
arguments
inputs.
using ... .
A function that
retains access javascript<br>function outer() {
to its outer const a = 10; return function Encapsulation,
Closure
scope variables inner() { console.log(a); }; } maintaining
Function <br>const innerFunc = outer();
even after the private state.
<br>innerFunc();
outer function
has executed.
Object-oriented
A function javascript<br>class Person {
programming;
defined inside greet() { console.log("Hi!"); } }
Class Method <br>const p = new Person(); grouping
a JavaScript
<br>p.greet(); behavior inside
class.
classes.
Utility
functions,
A function javascript<br>class MathUtil {
shared
bound to a static add(a, b) { return a + b; }
Static Method }<br>console.log(MathUtil.add(2, methods that
class, not an
3)); don't depend
instance.
on class
instances.
Functional
A function that programming
breaks down javascript<br>const add = a => b for creating
Currying
into multiple => a + b;<br>console.log(add(2) reusable,
Function (3));
unary partially-
functions. applied
functions.
A function that
Handling
returns a javascript<br>function asyncTask()
asynchronous
Promise Promise for { return new Promise(resolve =>
resolve("Task complete!")); } tasks, chaining,
Function handling
<br>asyncTask().then(console.log); and avoiding
asynchronous
callback hell.
tasks.
JAVA SCRIPT 10
Short, inline
An unnamed
operations
Anonymous arrow function, javascript<br>[1, 2, 3].map(num =>
such as in
Arrow Function often used num * 2);
map , filter ,
inline.
and reduce .
Notes:
1. Functions like closures, IIFE, and higher-order functions are fundamental for
advanced JavaScript concepts.
2. Use the appropriate function type depending on your use case, readability,
and maintainability of the code.
Here’s a detailed note with colorful bullets and structured content based on your
explanation of JavaScript's array functions (map, filter, reduce):
2. Doubling Values:
JAVA SCRIPT 11
function double(x) {
return x * 2;
}
const output = ARR.map(double);
console.log(output); // Output: [10, 6, 12]
3. Tripling Values:
function triple(x) {
return x * 3;
}
const output = ARR.map(triple);
console.log(output); // Output: [15, 9, 18]
4. Binary Transformation:
function toBinary(x) {
return x.toString(2);
}
const output = ARR.map(toBinary);
console.log(output); // Output: ['101', '110', '111']
or
JAVA SCRIPT 12
Filter Function: Filtering Arrays
🔵 What is the Array.filter() function?
It returns a new array containing only the elements that satisfy the condition.
Examples of Filtering:
Filtering Odd Numbers:
function isOdd(x) {
return x % 2 !== 0;
}
const output = ARR.filter(isOdd);
console.log(output); // Output: [5, 3]
function isEven(x) {
return x % 2 === 0;
}
const output = ARR.filter(isEven);
console.log(output); // Output: [2, 6]
JAVA SCRIPT 13
reduce() iterates over the array and accumulates a single result.
It’s used when you need to combine elements into a single value (e.g.,
summing, finding max).
2. Sum of Elements:
function findMax(arr) {
let max = 0;
for (let i = 0; i < arr.length; i++) {
if (arr[i] > max) {
max = arr[i];
}
JAVA SCRIPT 14
}
return max;
}
console.log(findMax(ARR)); // Output: 6
🟢 reduce() : Accumulates values from the array into a single result (e.g., sum,
maximum).
In this set of examples, you've been exploring the core functions of JavaScript:
map() , reduce() , and filter() , focusing on how to manipulate and process data
const users = [
{ firstName: 'AI', lastName: 'Smith', age: 26 },
{ firstName: 'Donald', lastName: 'Trump', age: 75 },
{ firstName: 'John', lastName: 'Doe', age: 50 }
];
JAVA SCRIPT 15
r.lastName}`);
console.log(fullNames);
Here, map() is used to iterate over each object in the array and return a new array
of full names by concatenating the firstName and lastName .
const users = [
{ firstName: 'AI', lastName: 'Smith', age: 26 },
{ firstName: 'Donald', lastName: 'Trump', age: 75 },
{ firstName: 'John', lastName: 'Doe', age: 50 },
{ firstName: 'Jane', lastName: 'Doe', age: 26 }
];
console.log(ageCount);
JAVA SCRIPT 16
Here, reduce() iterates over each user object and adds the age to the accumulator
object, keeping track of the count of each unique age.
const users = [
{ firstName: 'AI', lastName: 'Smith', age: 26 },
{ firstName: 'Donald', lastName: 'Trump', age: 75 },
{ firstName: 'John', lastName: 'Doe', age: 50 },
{ firstName: 'Jane', lastName: 'Doe', age: 29 }
];
console.log(firstNamesUnder30);
Here, filter() is used to select users under 30, and map() is then used to extract
the first names of these users.
Homework Challenge:
You were also tasked with achieving the same result (first names of users under
30) using only reduce() instead of filter() and map() combined. This challenge
helps reinforce the power of reduce() to handle complex transformations.
JAVA SCRIPT 17
console.log(firstNamesUnder30WithReduce);
By using reduce() , you're iterating through the array and accumulating the first
names of users whose age is below 30.
Key Takeaways:
map()is used for transforming an array by applying a function to each element
and returning a new array.
filter()is used to create a new array with elements that pass a specific
condition.
🎉Understanding
Welcome Back to Namaste JavaScript - Episode 1:
Callbacks in JavaScript
💥 Episode Overview
In this first episode, we’re going to understand the core concept of callbacks in
JavaScript. We'll explore:
setTimeout(() => {
console.log("This prints after 3 seconds!"); // This will
be delayed
}, 3000); // 3000 milliseconds (3 seconds)
Expected Output:
Hello, World!
This prints immediately after the first line
This prints after 3 seconds!
Explanation:
JAVA SCRIPT 19
During this time, the JavaScript engine continues executing the rest of the
code. After the delay, the callback is invoked, printing the final message.
1. Create an Order: The user adds items to the cart, and an order is created.
Here, we need to ensure each task happens in sequence, and callbacks are
perfect for managing this.
Code Example:
function proceedToPayment() {
console.log("Proceeding to payment...");
}
Flow:
function (callback).
JAVA SCRIPT 20
⚡ The Bad Parts of Callbacks
1. Callback Hell (Pyramid of Doom)
What is Callback Hell?
1. Create Order
2. Proceed to Payment
4. Update Wallet
JAVA SCRIPT 21
createOrder(cartItems, (order) => {
proceedToPayment(order, (paymentStatus) => {
showOrderSummary(paymentStatus, (summary) => {
updateWallet(summary, (walletStatus) => {
console.log("Process Complete!");
});
});
});
});
Problem:
It's called the Pyramid of Doom because the code looks like a pyramid,
making it harder to manage and understand.
JAVA SCRIPT 22
Why is it bad?
Increased Complexity: Each time you add more asynchronous tasks, the level
of nesting increases, making the code harder to debug and maintain.
Hard to Track: You have to track each function call and its associated
callback. This can get confusing when the logic becomes complex.
2. Inversion of Control
What is Inversion of Control?
function proceedToPayment() {
JAVA SCRIPT 23
console.log("Payment Successful!");
}
Problem:
📌 Key Takeaways
1. Good Parts of Callbacks ✅:
Callbacks help manage asynchronous tasks by allowing us to define
actions after the completion of a task (e.g., setTimeout ).
They enable tasks like handling user input, API calls, or delayed actions
in JavaScript.
Homework:
3. Comment: Share your thoughts about the problems with callbacks and
how they could be avoided!
JAVA SCRIPT 24
Introduction to Promises in JavaScript
Promises are essential in modern JavaScript, especially for handling
asynchronous operations. If you're aiming to become proficient in JavaScript,
particularly for frontend development, understanding Promises is critical. They
are commonly asked about in interviews and will make you a better developer.
In this video, we dive deep into the beauty of Promises. Rather than just
explaining them quickly, we'll take our time to explore how they work, how they
solve problems in asynchronous code, and why they are such a game-changer for
JavaScript developers.
1. The Scenario:
Two APIs:
Create Order API: Takes the cart items and returns an order ID.
Both APIs are asynchronous, meaning they take some time to execute and
we don't know how long.
JAVA SCRIPT 25
// Simulating async order creation (it might take time)
setTimeout(() => {
const orderId = '12345';
callback(orderId); // Callback is invoked with order
ID once order is created
}, 2000); // Simulating async operation delay
}
createOrder(cart, proceedToPayment);
Explanation:
This creates a potential problem: What if the callback is never called or called
multiple times? It’s risky to rely on another part of the code to call our callback
correctly, especially when we have no control over it.
JAVA SCRIPT 26
const cart = ['Shoes', 'Pants', 'Kurta'];
createOrder(cart)
.then(proceedToPayment) // Once promise is resolved, pro
ceed to payment
.catch(error => console.log(error)); // Handle any error
s
Explanation:
JAVA SCRIPT 27
✅ Why Promises Are Better
1. Improved Control
With Promises, we don't pass our callback to another function. Instead, we
attach it to a Promise, giving us more control over when the callback gets
called.
The Promise guarantees that it will resolve or reject exactly once — and it will
automatically call the .then() method when the data is available.
2. Cleaner Code
Promises eliminate the callback hell (nested callbacks), leading to cleaner,
more readable code.
It also separates concerns, where the function creates the order and returns a
Promise, and we control how to handle the result using .then() .
JAVA SCRIPT 28
// Using the fetch API to get data from GitHub
fetch('https://api.github.com/users/yourUsername')
.then(response => response.json()) // Parse the JSON res
ponse
.then(data => console.log(data)) // Log the user data
.catch(error => console.error(error)); // Handle errors
Explanation:
When the request is completed, the Promise is fulfilled, and the .then()
method is triggered.
block.
Promise States
Pending: The Promise is still waiting for a result (e.g., when making an API
request).
Fulfilled: The Promise has completed successfully and holds the data.
You can explore the actual Promise object in the browser’s developer tools to see
its states ( pending , fulfilled , rejected ) and results.
🎯 Key Takeaways
Promises are a more reliable and cleaner way to handle asynchronous
operations compared to callbacks.
They provide control over the flow of the program, ensuring that callbacks are
executed only when the data is ready.
With Promises, we avoid the issues of inversion of control and callback hell,
making our code more readable and maintainable.
📚 What’s Next?
In the next video, we'll explore how to chain Promises and handle more complex
asynchronous workflows efficiently, as well as how to use async/await to simplify
Promises even further!
JAVA SCRIPT 29
Promise States
A Promise in JavaScript can have one of three states:
Example:
When a fetch request is made, the returned promise will initially be in the pending
state. After a certain amount of time, if the request succeeds, it transitions to
fulfilled. If there’s an error, it becomes rejected.
When the code runs, JavaScript does not wait for the fetch to complete and
immediately moves to the next line. It logs the promise in its pending state.
This is because fetching data is an asynchronous operation. The promise will
eventually resolve when the data is fetched.
Promise Chaining
Promises also allow you to chain multiple operations, so they can be executed in
sequence. Instead of nesting callbacks (which leads to "callback hell"), promises
allow for cleaner, more readable code.
Example:
Here’s a flow where multiple dependent actions are performed:
1. Create an order.
JAVA SCRIPT 30
or using Arrow fuc
createOrder()
.then(order => proceedToPayment(order))
.then(paymentInfo => showOrderSummary(paymentInfo))
.then(summary => updateWalletBalance(summary))
.catch(error => console.log('Error:', error));
This Promise chaining is preferred over traditional callbacks because it avoids the
"Pyramid of Doom" or callback hell.
JAVA SCRIPT 31
Each .then() in the chain handles the data returned by the previous one. If we
forget to return a promise inside a .then() , it can break the chain and data won’t
pass through correctly.
Example:
createOrder()
.then(order => {
return proceedToPayment(order); // Ensure to return the p
romise
})
.then(payment => showOrderSummary(payment))
.catch(error => console.log('Error:', error));
Better error handling: With .catch() , we can handle errors at the end of a
chain, improving the structure and readability of our code.
JAVA SCRIPT 32
By using promises, JavaScript developers can handle asynchronous tasks without
the headaches of callback hell, creating more reliable and maintainable code.
JAVA SCRIPT 33
Mastering JavaScript Promises: A
Comprehensive Guide with Examples
Promises are one of the most powerful concepts in JavaScript. They make
handling asynchronous operations cleaner and more readable. In this guide, we’ll
JAVA SCRIPT 34
dive deep into how to create and consume promises, handle errors, and perform
promise chaining. By the end, you’ll have the confidence to write and use
promises effectively.
Consuming Promises
Example: E-commerce Order Flow
Let’s consider an e-commerce website where you need to create an order based
on cart items and then proceed to payment.
Workflow:
1. Create an order using the cart items.
2. Receive an orderID .
createOrder(cart)
.then(orderID => {
console.log("Order created with ID:", orderID);
return proceedToPayment(orderID);
})
.then(paymentInfo => {
console.log("Payment successful:", paymentInfo);
})
JAVA SCRIPT 35
.catch(error => {
console.error("Error:", error.message);
});
Creating Promises
To understand promises better, let’s create one from scratch.
function createOrder(cart) {
return new Promise((resolve, reject) => {
// Validate the cart
if (!validateCart(cart)) {
return reject(new Error("Cart is not valid"));
}
function validateCart(cart) {
return cart.length > 0;
}
function proceedToPayment(orderID) {
return new Promise((resolve, reject) => {
// Simulate async payment processing
setTimeout(() => {
resolve(`Payment processed for order ${orderID}`);
}, 3000);
});
}
JAVA SCRIPT 36
Error Handling
Graceful Error Handling
Errors should always be handled gracefully to prevent application crashes. Use
.catch() for handling errors in promises.
Example:
Output:
Promise Chaining
Concept
Promise chaining allows multiple asynchronous tasks to be performed
sequentially, where the output of one is the input to the next.
createOrder(cart)
.then(orderID => {
console.log("Order created with ID:", orderID);
return proceedToPayment(orderID);
})
.then(paymentInfo => {
console.log("Payment successful:", paymentInfo);
return sendConfirmationEmail(paymentInfo);
})
.then(emailStatus => {
JAVA SCRIPT 37
console.log("Confirmation email sent:", emailStatus);
})
.catch(error => {
console.error("Error:", error.message);
});
function sendConfirmationEmail(paymentInfo) {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve(`Email sent for payment: ${paymentInfo}`);
}, 2000);
});
}
Key Takeaways
1. Creating Promises: Use the Promise constructor with resolve and reject to
create custom promises.
Advanced Topics
Promise.all : Handle multiple promises concurrently.
JAVA SCRIPT 38
🔵 Promise Chaining Concept
Promise chaining allows you to run multiple asynchronous tasks in a
sequence, passing data from one step to the next.
You return the result of each asynchronous operation to the next .then()
Example:
createOrder()
.then(orderId => proceedToPayment(orderId))
.then(paymentInfo => showOrderSummary(paymentInfo))
.then(walletInfo => updateWallet(walletInfo))
.catch(error => handleError(error));
Example of mistake:
createOrder()
.then(() => proceedToPayment()) // No return here
.then(paymentInfo => logInfo(paymentInfo));
Corrected Example:
createOrder()
.then(orderId => {
return proceedToPayment(orderId); // Return the pr
omise
})
.then(paymentInfo => {
return showOrderSummary(paymentInfo); // Return th
JAVA SCRIPT 39
e next promise
})
.then(walletInfo => {
return updateWallet(walletInfo); // Return the nex
t promise
});
createOrder()
.then(() => proceedToPayment())
.then(() => showOrderSummary())
.then(() => updateWallet());
createOrder()
.then(orderId => proceedToPayment(orderId))
.then(paymentInfo => showOrderSummary(paymentInfo))
.catch(error => {
console.error('Error:', error);
// Handle error gracefully
});
JAVA SCRIPT 40
createOrder()
.then(orderId => proceedToPayment(orderId))
.catch(error => {
console.error('Error in payment:', error);
})
.then(paymentInfo => showOrderSummary(paymentInfo));
createOrder()
.then(orderId => proceedToPayment(orderId))
.catch(error => {
console.error('Error with order:', error); // Hand
les cart error
})
.then(() => showOrderSummary()) // Continue if cart
validation fails
.then(() => updateWallet());
After .catch() , you can always continue with .then() to execute further
operations.
Example:
createOrder()
.then(orderId => proceedToPayment(orderId))
.catch(error => {
console.error('Error in order:', error);
})
.then(() => showOrderSummary());
JAVA SCRIPT 41
🟢 Best Practices for Promise Handling
Keep the promise chain clean and readable by returning promises in each
.then() .
Handle errors locally if needed, using specific .catch() blocks, and ensure
that a generic .catch() is at the end of the chain to catch unforeseen errors.
Use the new Promise constructor to create promises, where you pass
resolve and reject functions.
2. Catching Errors:
3. Chaining Promises:
Always return the result of each .then() to pass data to the next step.
4. Error Handling:
Handle errors globally at the end or locally at specific steps in the chain.
Use clean chains with returns to avoid nested callbacks and make your
code easier to manage.
Homework Assignment:
Create a Promise chain involving four async APIs: createOrder , proceedToPayment ,
showOrderSummary , and updateWallet .
JAVA SCRIPT 42
This structured approach ensures that promises are used efficiently and helps
avoid common pitfalls in asynchronous programming.
🌟in JavaScript
Script Summary: Understanding async and await
🎥 Introduction
🟣 Welcome to Namaste JavaScript!
🟡 Today's focus is on one of the most awaited topics: async and await in
JavaScript.
Topics Covered:
🔵 What is
?
🔴 What is
async
?
🟢 Behind-the-scenes working.
await
🔵 Error handling in
/ .
🔴 Real-life examples.
async await
🟢 Comparison with
.then() and .catch() .
✨ 1. What is async ?
💡 Definition:
🔷 The keyword is used to define asynchronous functions.
async
JAVA SCRIPT 43
async function getData() {
return "Hello, Async!";
}
💡 Key Points:
1. 🟠 An function always returns a
async . Promise
✅ Explanation:
The getData function returns "Namaste" , which is wrapped in a promise.
✅ Explanation:
If an explicit promise is returned, it is passed as-is, not re-wrapped.
JAVA SCRIPT 44
🔷 The await keyword pauses the execution of the async function until the
promise resolves.
💡 Key Points:
1. 🟢 can only be used inside an
await function.
async
✅ Explanation:
Sequentially handles promises, improving code clarity.
🎓 Example Comparison
JAVA SCRIPT 45
🟢 Using .then()
fetch('https://api.example.com/data')
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error(error));
🔵 Using async/await
✅ Which is better?
For complex chains, async/await is more readable and maintainable.
JAVA SCRIPT 46
}
fetchData();
✅ Benefits:
1. 🟠 Centralized error handling.
🎯 Conclusion:
The combination of async and await simplifies asynchronous programming in
JavaScript, making code more readable and maintainable. Use this knowledge in
your projects and interviews to stand out! 🚀
🎯Async/Await
Explanation with Colorful Emoji and Highlights: Understanding
vs Traditional Promises
🧵 Key Highlights:
1️⃣ Promises Without Async/Await
JAVA SCRIPT 47
10-second delay
});
💡 Execution Flow:
Execution of synchronous code happens first.
console.log("Namaste JavaScript");
promise.then((value) => console.log(value));
🖥️ Output:
Namaste JavaScript
(After 10 seconds) Resolved Value
🔍 Execution Flow:
Synchronous code is executed up to await .
🖥️ Output:
(After 10 seconds) Namaste JavaScript
Resolved Value
JAVA SCRIPT 48
Key Difference: In this case, JavaScript appears to wait before
proceeding to the next line, but only within the async function.
the stack).
🖥️ Output:
JAVA SCRIPT 49
Starting...
(After 5 seconds) P1 Resolved
(After 10 seconds) P2 Resolved
The JavaScript engine is not blocked. Other events or processes can run.
Key Learning: JavaScript never blocks the call stack; it merely suspends
specific function execution temporarily.
🌟 Takeaway Notes:
✅ Async/Await simplifies promise management and introduces sequential
behavior.
🚀 Debugging Tip: Use breakpoints in developer tools to see how the call
stack evolves during promise resolution.
JAVA SCRIPT 50
Here's a detailed, structured, and color-coded explanation of the remaining script
from the YouTube video. It will break down the points, provide code snippets, and
summarize concepts effectively.
Result:
JAVA SCRIPT 51
🔵 4. Debugging with Examples
📋 Example Setup: P1 (20 seconds), P2 (40 seconds):
Call stack becomes empty after initiating await .
🟢
try {
const response = await fetch(API_URL); // Fetch API ca
🔵
ll
const data = await response.json(); // Convert resp
🔴
onse to JSON
console.log(data); // Log JSON res
ult
❌
} catch (error) {
console.error("Error fetching data:", error); // Handl
e errors
}
}
handlePromise();
JAVA SCRIPT 52
const data = await response.json();
console.log(data);
} catch (error) {
console.error("An error occurred:", error);
}
}
handlePromise().catch((error) => {
console.error("Error caught:", error);
});
3. Fetch API returns a promise that can be handled using await or .then .
🔴 Practical Advice:
Use try-catch for better readability and cleaner error handling.
🌟 Motivation to Learn:
These concepts are critical for JS interviews and professional development.
JAVA SCRIPT 53
JAVA SCRIPT 54