0% found this document useful (0 votes)
51 views73 pages

ECMAScript Features and JavaScript Basics

ECMAScript (ES) is a standard for scripting languages like JavaScript, defining its syntax and behavior. Key updates include ES5 to ES12, introducing features like promises, async/await, and various array methods. The document also covers JavaScript concepts such as generator functions, promises, callbacks, loops, strict mode, maps, and DOM access methods.
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)
51 views73 pages

ECMAScript Features and JavaScript Basics

ECMAScript (ES) is a standard for scripting languages like JavaScript, defining its syntax and behavior. Key updates include ES5 to ES12, introducing features like promises, async/await, and various array methods. The document also covers JavaScript concepts such as generator functions, promises, callbacks, loops, strict mode, maps, and DOM access methods.
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

ECMAScript (ES) refers to a standard specification for scripting languages like

JavaScript. ES defines the syntax, semantics, and behavior of JavaScript,


ensuring consistency across different implementations (like web browsers,
[Link], etc.)

Key Updates:

1.​ ES5 (ECMAScript 5) – Released in 2009:


○​ Introduced methods like forEach, map, filter, reduce, and strict
mode ('use strict') for better error handling.
○​ Also added [Link], [Link], and JSON
support.
2.​ ES6 (ECMAScript 2015) – A major update with many new features:-
○​ Let & Const: Block-scoped variable declarations.
○​ Arrow Functions: Shorter syntax for functions.
○​ Template Literals: String interpolation with ${}.
○​ Destructuring: Unpack values from arrays/objects.
○​ Classes: Syntactic sugar for creating objects and inheritance.
○​ Promises: For easier handling of asynchronous code.
3.​ ES7 (ECMAScript 2016):
○​ Introduced the ** (exponentiation) operator and
[Link] method.
4.​ ES8 (ECMAScript 2017):
○​ Added async/await for simpler asynchronous code and
[Link]/[Link].
5.​ ES9 (ECMAScript 2018):

Introduced features like rest/spread properties, asynchronous iteration, and


[Link]().

6.​ ES10 (ECMAScript 2019):


○​ Included [Link], [Link],
[Link], and improved [Link].
7.​ ES11 (ECMAScript 2020):
○​ Added optional chaining (?.), nullish coalescing (??), and BigInt for
larger numbers.
8.​ ES12 (ECMAScript 2021):
○​ Features like Logical Assignment Operators, WeakRefs, and
[Link].
A generator function in JavaScript is a special type of function that can pause
its execution and continue it later. This is achieved using the yield keyword, which
allows the function to return an temporary result and resume from where it left
off.

// Generator function
function* myGenerator() {
[Link]('Start of generator');
yield 1; // Pauses here and returns 1
[Link]('Middle of generator');
yield 2; // Pauses again and returns 2
[Link]('End of generator');
yield 3; // Pauses again and returns 3
return 'Done'; // Returns final value and completes the generator
}

// Create a generator object


const gen = myGenerator();

// Using next() to resume and get values from the generator


[Link]([Link]().value); // Output: Start of generator \n 1
[Link]([Link]().value); // Output: Middle of generator \n 2
[Link]([Link]().value); // Output: End of generator \n 3
[Link]([Link]().value); // Output: Done

A Promise is a JavaScript object that represents the result of an asynchronous


operation, which can either succeed (resolve) or fail (reject).

A Promise is a JavaScript object that represents the result of an asynchronous


operation, which can either succeed (resolve) or fail (reject).

const myPromise = new Promise((resolve, reject) => {


let success = true; // Simulate success or failure
if (success) {
resolve("Operation Successful!");
} else {
reject("Operation Failed!");
}
});
myPromise
.then((result) => {
[Link](result); // Logs: "Operation Successful!"
})
.catch((error) => {
[Link](error); // Logs: "Operation Failed!" if rejected
})
.finally(() => {
[Link]("This runs no matter what!"); // Always runs after the promise is settled
});

resolve is called when the operation succeeds.


reject is called when the operation fails.
.then() handles the success case.
.catch() handles the failure case.

Callbacks ​
A callback is a function you pass into another function as an argument. It gets executed
once a task (like an API request or event) finishes.​
They're simple to use for small tasks, like waiting for a button click or reading a file.​
But when you have many callbacks in a row, the code becomes hard to follow and
manage, creating something called "callback hell."
Promises:​
A promise is an object that represents a task that will finish in the future, either
successfully or with an error.​
You can use .then() to handle the result if it’s successful, and .catch() for handling
errors.​
Promises are much cleaner than callbacks because they allow you to chain tasks and
handle errors easily, making the code more readable.
Async/Await:​
Async/Await is a newer way to work with promises that makes your code look simpler
and easier to read.​
By using async before a function, it automatically returns a promise, and using await
inside the function makes it wait for the promise to finish before continuing.​
This method is great for tasks that depend on each other, like logging in, fetching data,
and then showing the user’s profile, as it makes the code look more like normal,
sequential code

JavaScript mein, [Link]() aur [Link]() dono asynchronous


operations ko handle karne ke liye use hote hain, lekin dono mein thoda difference hai:
1.​ [Link]():
○​ [Link]() multiple promises ko ek saath handle karta hai aur tab
resolve hota hai jab saare promises resolve ho jaate hain.
○​ Agar koi bhi ek promise reject hota hai, to [Link]() turant reject ho
jaata hai, aur baaki promises ka result nahi milta.
○​ Example:

javascript​
Copy code​
const promise1 = [Link](3);
const promise2 = [Link](4);
const promise3 = new Promise((resolve, reject) => setTimeout(resolve,
100, 'foo'));

[Link]([promise1, promise2, promise3]).then((values) => {


[Link](values); // [3, 4, 'foo']
}).catch((error) => {
[Link](error); // Agar koi promise reject hota hai
});

[Link]():

○​ [Link]() bhi multiple promises ko handle karta hai, lekin


ye tab resolve hota hai jab saare promises settle ho jaate hain (chahe
resolve ho ya reject).
○​ Isme agar koi promise reject ho jaata hai to bhi baaki promises ke result
milte hain.
○​ Result ek array hota hai jisme har promise ka status (fulfilled ya
rejected) aur value ya reason hota hai.

const promise1 = [Link](3);


const promise2 = [Link]('Error');
const promise3 = new Promise((resolve, reject) => setTimeout(resolve,
100, 'foo'));

[Link]([promise1, promise2, promise3]).then((results) => {


[Link](results);
// [
// { status: 'fulfilled', value: 3 },
// { status: 'rejected', reason: 'Error' },
// { status: 'fulfilled', value: 'foo' }
// ]
});

2.​

Key Differences:

●​ [Link](): Agar koi promise reject hota hai, to baaki promises ki execution
stop ho jaati hai.
●​ [Link](): Sabhi promises ko check karta hai aur unka result deta
hai, chahe wo resolve ho ya reject ho.

The latest stable version of React is 18.2.0, which is the most recent version released in
the 18.x series. React 18 introduced several new features, such as Suspense
improvements, concurrent rendering, and the useTransition hook for better handling
state updates. It is designed to work seamlessly with both client-side and server-side

The latest stable version of [Link] is v20.3.0. This release brings several updates,
including improved performance, enhanced debugging tools, and better support for
modern JavaScript features like ES modules. [Link] v20.x is recommended for most
projects looking for a stable and performant version​

for loop: Repeats a block of code a specified number of times, using an initializer, condition, and
increment/decrement expression.

while loop: Repeats a block of code as long as a specified condition evaluates to true; the
condition is checked before each iteration.

do...while loop: Similar to a while loop, but guarantees that the code block executes at least
once before checking the condition.

for...of loop: Iterates over iterable objects (like arrays and strings), providing access to the
values without needing an index.
for...in loop: Iterates over the enumerable properties of an object, allowing access to the keys
(or indices) of the properties.

// 1. for loop
[Link]("For Loop:");
for (let i = 0; i < 5; i++) {
[Link](i); // Outputs: 0, 1, 2, 3, 4
}

// 2. while loop
[Link]("While Loop:");
let j = 0;
while (j < 5) {
[Link](j); // Outputs: 0, 1, 2, 3, 4
j++;
}

// 3. do...while loop
[Link]("Do...While Loop:");
let k = 0;
do {
[Link](k); // Outputs: 0, 1, 2, 3, 4
k++;
} while (k < 5);

// 4. for...of loop
[Link]("For...Of Loop:");
let arr = ['a', 'b', 'c', 'd', 'e'];
for (let value of arr) {
[Link](value); // Outputs: a, b, c, d, e
}

// 5. for...in loop
[Link]("For...In Loop:");
let obj = { x: 1, y: 2, z: 3 };
for (let key in obj) {
[Link](key, obj[key]); // Outputs: x 1, y 2, z 3
}
///////////////////////////////////////////////////////////////////////////////////////////////////////

Strict mode is a way to run JavaScript in a stricter set of rules. When enabled, it helps catch
errors and unsafe actions that could lead to bugs, such as:
Disallowing the use of undeclared variables.
Preventing duplicate parameter names in functions.
Making this undefined in functions that are not called with an object.
You enable strict mode by adding "use strict"; at the beginning of your script or function.

"use strict"; // Enables strict mode


// Example of preventing undeclared variable assignment
function testStrictMode() {
x = 10; // Throws an error: "x is not defined"
}

////////////////////////////////////////////////////////////////////////////////

Feature has Method includes Method

Data Type Sets, Maps Arrays, Strings


Use Case Checking existence of a value or key Checking existence of a value or
substring
Return Type Returns true or false Returns true or false
testStrictMode();

JavaScript में Map एक बिल्ट-इन ऑब्जेक्ट है जो की-वैल्यू पेयर्स (key-value pairs) का एक कलेक्शन होता
है , ठीक वैसे ही जैसे एक ऑब्जेक्ट होता है । हालांकि, Map में कुछ महत्वपर्ण
ू अंतर और फायदे हैं जो इसे विशिष्ट
उपयोग के मामलों के लिए अधिक बेहतर बनाते हैं।

Map क्या होता है ?

एक Map एक ऑर्डर्ड लिस्ट की तरह है जहां हर आइटम में एक की और उससे जड़


ु ी एक वैल्यू होती है । यह
पारं परिक JavaScript ऑब्जेक्ट के समान लगता है , लेकिन Map अधिक लचीला और शक्तिशाली है जब कीज़
की बात आती है ।

मख्
ु य विशेषताएँ:

1.​ कीज़ का प्रकार (Any Key Type): Map की सबसे बड़ी विशेषता यह है कि इसकी कीज़ किसी भी डेटा
ू यंस, फंक्शन्स, ऑब्जेक्ट्स (यहाँ तक कि null और
टाइप की हो सकती हैं – स्ट्रिं ग्स, नंबर्स, बलि
undefined भी) भी की के रूप में उपयोग किए जा सकते हैं। पारं परिक ऑब्जेक्ट में , कीज़ हमेशा
स्ट्रिं ग्स (या Symbols) होती हैं।
// A. Set के साथ has() का उदाहरण
const fruits = new Set(['apple', 'banana', 'orange']);

[Link]('--- [Link]() ---');


[Link]([Link]('banana')); // Output: true (क्योंकि 'banana' Set में है )
[Link]([Link]('grape')); // Output: false (क्योंकि 'grape' Set में नहीं है )
[Link]([Link]('Apple')); // Output: false (केस-सेंसिटिव है )

// B. Map के साथ has() का उदाहरण


const userRoles = new Map();
[Link]('Alice', 'Admin');
[Link]('Bob', 'Editor');
[Link]('Charlie', 'Viewer');

[Link]('\n--- [Link]() ---');


[Link]([Link]('Alice')); // Output: true (क्योंकि 'Alice' की Map में है )
[Link]([Link]('David')); // Output: false (क्योंकि 'David' की Map में नहीं है )
[Link]([Link]('Admin')); // Output: false (has() कीज़ के लिए है , वैल्यू के लिए नहीं)

// Example: Creating a Map with some initial key-value pairs


const myMap = new Map([
['a', 1],
['b', 23],
['c', 5],
]);

[Link]('d', 3); // Adds a new key-value pair to the Map


[Link](myMap);
/* Outputs something like:
Map(4) {
'a' => 1,
'b' => 23,
'c' => 5,
'd' => 3
}
*/
[Link]([Link]('d')); // Checks if a key exists in the Map, Outputs: true
[Link]([Link](3)); // Checks if 3 is a key (it's not), Outputs: false

const numbers = [1, 2, 3, 4, 5]; [Link]([Link](3)); // Output: true (3 is in the


array) [Link]([Link](8));

////////////////////////////////////////////////////////////
BigInt: A JavaScript data type that allows you to represent and manipulate integers larger than
2 power53− 1(9007199254740991) with arbitrary precision.

const bigInt1 = 1234567890123456789012345678901234567890n; // ek iss tarike se or


const bigInt2 = 1000000000000000000000000000000000000n; // और एक BigInt

// जोड़ना
const sum = bigInt1 + bigInt2;
[Link]("Sum:", sum); // Sum: 1234567890123456789022345678901234567890n

// घटाना
const difference = bigInt1 - bigInt2;
[Link]("Difference:", difference); // Difference:
1234567890123456789000000000001234567890n

// गण
ु ा करना
const product = bigInt1 * bigInt2;
[Link]("Product:", product); // बहुत बड़ा मान

// भाग दे ना
const quotient = bigInt1 / 2n;
[Link]("Quotient:", quotient); // Quotient:
617283945061728394506172839450617283945n

///////////////////////////////////////////////////////////////

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>DOM Access Methods</title> <style>
.highlight {
background-color: yellow;
border: 2px solid orange;
}
</style>
</head>
<body>

<div id="myId">This is a div with ID "myId".</div>


<div class="myClass">This is the first div with class "myClass".</div>
<div class="myClass">This is the second div with class "myClass".</div>
<p>This is a paragraph.</p>
<div>
<span>This is a span inside a div.</span>
</div>

<script>
// Accessing elements using different DOM methods

// 1. getElementById: Access an element by its ID


const elementById = [Link]('myId');
[Link]('Element by ID:', elementById);
// Output: <div id="myId">This is a div with ID "myId".</div>

// 2. getElementsByClassName: Access elements by their class name


(returns a live HTMLCollection)
const elementsByClassName = [Link]('myClass');
[Link]('Elements by Class Name:', elementsByClassName);
// Output: HTMLCollection(2) [[Link], [Link]]
// Here, the output shows a collection of 2 div elements with the class
"myClass".

// 3. getElementsByTagName: Access elements by their tag name (returns


a live HTMLCollection)
const elementsByTagName = [Link]('div');
[Link]('Elements by Tag Name:', elementsByTagName);

// Output (corrected): HTMLCollection(3) [div#myId, [Link],


[Link], div] (the last div with span)
// 4. querySelector: Access the first element matching a CSS selector
const firstElement = [Link]('.myClass');
[Link]('First Element using querySelector:', firstElement);
// Output: <div class="myClass">This is the first div with class
"myClass".</div>

// 5. querySelectorAll: Access all elements matching a CSS selector


(returns a static NodeList)
const allElements = [Link]('[Link]');
[Link]('All Elements using querySelectorAll:', allElements);
// Output: NodeList(2) [[Link], [Link]]
// This shows a NodeList of all div elements with the class "myClass".

// 7. parentElement: Access the parent element of a specific element


const parentElement = [Link]('myId').parentElement;
[Link]('Parent Element of myId:', parentElement);
// Output: <body>...</body>

</script>

</body>
</html>

Async/await" is a modern JavaScript feature that makes it easier to write asynchronous


code that looks and behaves more like synchronous code. It's built on top of Promises.
Here's a breakdown with examples:
Why Async/Await?
Before async/await, handling asynchronous operations often involved:
* Callbacks: Nested callbacks could lead to "callback hell" (pyramid of doom), making
code hard to read and maintain.
* Promises (.then().catch()): A big improvement, but still involved chaining .then() calls,
which could get long for multiple sequential operations.
Async/await provides a more linear and readable way to write asynchronous code.
Key Concepts:
* async Keyword:
* You use the async keyword before a function declaration to make it an asynchronous
function.
* An async function always returns a Promise. If the function returns a non-Promise
value, JavaScript automatically wraps it in a resolved Promise.
* await Keyword:
* You can only use the await keyword inside an async function.
* await pauses the execution of the async function until the Promise it's waiting for
resolves.
* Once the Promise resolves, await returns the resolved value of the Promise.
* If the Promise rejects, await will throw an error, which you can catch using a
try...catch block.
Simple Example: Simulating a Fetch Request
Let's imagine we're fetching data from an API.
// Function that simulates an asynchronous operation (e.g., fetching data)
function fetchData() {
return new Promise(resolve => {
setTimeout(() => {
resolve("Data fetched successfully!");
}, 2000); // Simulate a 2-second delay
});
}

// --- Without async/await (using Promises) ---


function getDataWithPromises() {
[Link]("Fetching data with Promises...");
fetchData()
.then(data => {
[Link]("Promise result:", data);
})
.catch(error => {
[Link]("Promise error:", error);
});
}

// --- With async/await ---


async function getDataWithAsyncAwait() {
[Link]("Fetching data with async/await...");
try {
const data = await fetchData(); // Pause execution until fetchData() resolves
[Link]("Async/Await result:", data);
} catch (error) {
[Link]("Async/Await error:", error);
}
}

// Call the functions


getDataWithPromises();
getDataWithAsyncAwait();

[Link]("This message appears before the data is fetched because operations are
asynchronous.");

Explanation:
* fetchData(): This function returns a Promise that resolves after 2 seconds.
* getDataWithPromises(): This uses the traditional .then() syntax. The
[Link]("Promise result:", data); line only executes after the fetchData Promise
resolves.
* getDataWithAsyncAwait():
* The async keyword makes this function an asynchronous function.
* const data = await fetchData(); is the magic. When fetchData() is called,
getDataWithAsyncAwait() pauses its execution at this line. It won't move to the next line
([Link]("Async/Await result:", data);) until fetchData()'s Promise resolves.
* The try...catch block is crucial for error handling with await. If fetchData()'s Promise
were to reject, the catch block would be executed.
* [Link]("This message appears...");: This line executes immediately because
getDataWithPromises() and getDataWithAsyncAwait() are non-blocking. They initiate
asynchronous operations and then allow the rest of the script to continue.

try...catch और Promises (और async/await जो Promises पर आधारित है ) JavaScript में त्रटि ु यों
(Errors) को हैंडल करने के लिए उपयोग होते हैं, लेकिन वे अलग-अलग तरह की त्रटि ु यों को हैंडल करते हैं और
अलग-अलग संदर्भों में उपयोग किए जाते हैं।
try...catch क्या है ?
try...catch एक सिंक्रोनस एरर हैंडलिंग मैकेनिज्म है । इसका उपयोग उन त्रटिु यों को पकड़ने के लिए किया जाता
है जो आपके कोड के तत्काल निष्पादन (immediate execution) के दौरान होती हैं, यानी जब कोड लाइन बाय
लाइन चल रहा होता है और कोई समस्या आ जाती है ।
ज़रूरत क्यों पड़ी?
बिना try...catch के, यदि आपके सिंक्रोनस कोड में कोई अनहैंडल्ड एरर आती है (जैसे ReferenceError,
TypeError, या आपके द्वारा फेंकी गई Error), तो आपका परू ा प्रोग्राम क्रैश हो जाएगा और चलना बंद कर दे गा।
try...catch हमें उस क्रैश को रोकने और एरर को gracefully (अच्छे से) हैंडल करने की अनम
ु ति दे ता है , ताकि
प्रोग्राम आगे बढ़ सके या उपयोगकर्ता को एक सार्थक संदेश दिखा सके।
उदाहरण:
try {
// वह कोड जो एरर फेंक सकता है
let x = y + 1; // 'y' परिभाषित नहीं है , इसलिए ReferenceError आएगी
[Link]("यह लाइन नहीं चलेगी");
} catch (error) {
// एरर पकड़ी गई, प्रोग्राम क्रैश नहीं होगा
[Link]("एक सिंक्रोनस एरर हुई:", [Link]);
}

[Link]("प्रोग्राम आगे बढ़ रहा है !"); // यह लाइन चलेगी

Promises क्या हैं (त्रटि


ु हैंडलिंग के संदर्भ में )?
Promises का उपयोग असिंक्रोनस ऑपरे शस ं के परिणामों को दर्शाने और हैंडल करने के लिए किया जाता है ।
असिंक्रोनस ऑपरे शन वे होते हैं जो तरु ं त परू े नहीं होते (जैसे नेटवर्क रिक्वेस्ट, टाइमआउट)। Promises में ,
त्रटि
ु यों को .catch() मेथड का उपयोग करके हैंडल किया जाता है ।
ज़रूरत क्यों पड़ी?

A very simple definition of "Callback Hell" is:


Callback Hell (or Pyramid of Doom) is when you have many asynchronous tasks that
depend on each other, and you chain them by putting one callback function inside
another. This creates deeply indented code that becomes very difficult to read,
understand, and maintain.

// Step 1: Do something
function step1(callback) {
[Link]("Starting Step 1...");
setTimeout(() => {
[Link]("Step 1 complete.");
callback(); // Now, let's go to the next step
}, 500); // Takes 0.5 seconds
}

// Step 2: Then do something else


function step2(callback) {
[Link]("Starting Step 2...");
setTimeout(() => {
[Link]("Step 2 complete.");
callback(); // And then the next
}, 300); // Takes 0.3 seconds
}

// Step 3: Finally, do the last thing


function step3(callback) {
[Link]("Starting Step 3...");
setTimeout(() => {
[Link]("Step 3 complete.");
callback(); // We're done!
}, 700); // Takes 0.7 seconds
}

// This is where the "hell" begins


[Link]("--- Executing operations in sequence ---");

step1(() => {
step2(() => {
step3(() => {
[Link]("All steps are finished!");
});
});
});

[Link]("--- Code continues to run while steps are processed ---");

// A closure is a function that "remembers" and can access variables from its
surrounding (outer) scope,
// even after that outer scope has finished executing.

function outer() {
let count = 0; // 2. बाहरी फ़ंक्शन का एक वेरिएबल

return function() {
//it is clouser function
count++;
[Link](count);
};
}
const myCounter = outer(); // 'myCounter' एक क्लोजर है जो 'count' को याद रखता है

myCounter(); // आउटपट
ु : 1
myCounter(); // आउटपट
ु : 2
myCounter(); // आउटपट
ु : 3
myCounter()

Q WHAT ARE STRING METHODS!

charAt(index)
Definition: Returns the character at the specified index in a string. If the index is out of range, it
returns an empty string.

charCodeAt(index)
Definition: Returns the Unicode value of the character at the specified index.

concat(...strings)
Definition: Combines two or more strings and returns a new string. This method does not
change the existing strings.

endsWith(searchString)
Definition: Checks if a string ends with the specified substring, returning true or false.

includes(searchString)
Definition: Determines whether a string contains the specified substring, returning true or false.

indexOf(searchValue)
Definition: Returns the index of the first occurrence of a specified value in a string, or -1 if not
found.

lastIndexOf(searchValue)
Definition: Returns the index of the last occurrence of a specified value in a string, or -1 if not
found.

match(regexp)
Definition: Retrieves the matches when matching a string against a regular expression. Returns
an array of matches or null if no matches are found.

replace(searchValue, newValue)
Definition: Returns a new string with some or all matches of a pattern replaced by a
replacement string.

search(regexp)
Definition: Searches a string for a match against a regular expression and returns the index of
the first match, or -1 if not found.

slice(start, end)
Definition: Extracts a section of a string and returns it as a new string, without modifying the
original string. The end index is not included.

split(separator)
Definition: Splits a string into an array of substrings based on a specified separator string.
Returns an array of substrings.

startsWith(searchString)
Definition: Checks if a string starts with the specified substring, returning true or false.

substring(start, end)
Definition: Returns a subset of a string between two specified indices. If end is omitted, it returns
the substring to the end of the string.

toLowerCase()
Definition: Converts all characters in a string to lowercase and returns the new string.

toUpperCase()
Definition: Converts all characters in a string to uppercase and returns the new string.

trim()
Definition: Removes whitespace from both ends of a string and returns the new string.

valueOf()
Definition: Returns the primitive value of a string object. This method is often used implicitly.

padStart(targetLength, padString)
Definition: Pads the current string with another string (the second argument) until the resulting
string reaches the specified length from the start.

padEnd(targetLength, padString)
Definition: Pads the current string with another string (the second argument) until the resulting
string reaches the specified length from the end.

// Sample string for demonstration


let str = " Hello World, Welcome to JavaScript! ";

// 1. charAt(index)
[Link]([Link](1)); // Output: "H"

// 2. charCodeAt(index)
[Link]([Link](0)); // Output: 32 (space)

// 3. concat(...strings)
let greeting = "Hello";
let name = "John";
[Link]([Link](", ", name)); // Output: "Hello, John"

// 4. endsWith(searchString)
[Link]([Link]("!")); // Output: true

// 5. includes(searchString)
[Link]([Link]("World")); // Output: true

// 6. indexOf(searchValue)
[Link]([Link]("o")); // Output: 4

// 7. lastIndexOf(searchValue)
[Link]([Link]("o")); // Output: 8

// 8. match(regexp)
[Link]([Link](/o/g)); // Output: ["o", "o"]

// 9. replace(searchValue, newValue)
[Link]([Link]("World", "Universe")); // Output: " Hello Universe, Welcome to
JavaScript! "

// 10. search(regexp)
[Link]([Link](/JavaScript/)); // Output: 27

// 11. slice(start, end)


[Link]([Link](3, 8)); // Output: "Hello"

// 12. split(separator)
[Link]([Link](",")); // Output: [" Hello World", " Welcome to JavaScript! "]

// 13. startsWith(searchString)
[Link]([Link](" H")); // Output: true

// 14. substring(start, end)


[Link]([Link](3, 8)); // Output: "Hello"

// 15. toLowerCase()
[Link]([Link]()); // Output: " hello world, welcome to javascript! "

// 16. toUpperCase()
[Link]([Link]()); // Output: " HELLO WORLD, WELCOME TO JAVASCRIPT! "

// 17. trim()
[Link]([Link]()); // Output: "Hello World, Welcome to JavaScript!"

// 19. padStart(targetLength, padString)


let number = "5";
[Link]([Link](2, "0")); // Output: "05"

// 20. padEnd(targetLength, padString)


[Link]([Link](2, "0")); // Output: "50"

-----------------------------------------------------------------------------------------------------------------
Definitions of Each Number Method

[Link](value): Checks if the value is an integer.

[Link](value): Checks if the value is NaN (Not-a-Number).

[Link](value): Checks if the value is a finite number.

[Link](value): Checks if the value is a safe integer (within the range of -2^53 to
2^53).

[Link](string): Parses a string argument and returns a floating-point number.

[Link](string): Parses a string argument and returns an integer.

[Link](digits): Formats a number using fixed-point notation.


[Link](digits): Returns a string representing the number in exponential
notation.

[Link](precision): Formats a number to a specified precision.

[Link](value): Returns the absolute value of a number.

[Link](value): Rounds a number up to the nearest integer.

[Link](value): Rounds a number down to the nearest integer.

[Link](value): Rounds a number to the nearest integer.

[Link](...values): Returns the largest value among the given arguments.

[Link](...values): Returns the smallest value among the given arguments.

[Link](): Returns a pseudo-random number between 0 (inclusive) and 1 (exclusive).

[Link](base, exponent): Returns the base raised to the power of the exponent.

[Link](value): Returns the square root of a number.

[Link](value): Returns the integer part of a number by removing the fractional digits.

// Sample numbers for demonstration


let num1 = 25;
let num2 = 5;

// 1. [Link](value)
[Link](`1. [Link](num1): ${[Link](num1)}`); // Checks if num1 is an
integer

// 2. [Link](value)
[Link](`2. [Link](NaN): ${[Link](NaN)}`); // Checks if the value is NaN

// 3. [Link](value)
[Link](`3. [Link](num1): ${[Link](num1)}`); // Checks if num1 is a finite
number

// 4. [Link](value)
[Link](`4. [Link](num1): ${[Link](num1)}`); // Checks if
num1 is a safe integer
// 5. [Link](string)
[Link](`5. [Link]("3.14"): ${[Link]("3.14")}`); // Parses a string
and returns a floating-point number

// 6. [Link](string)
[Link](`6. [Link]("10.5"): ${[Link]("10.5")}`); // Parses a string and
returns an integer

// 7. [Link](digits)
[Link](`7. (num1).toFixed(2): ${(num1).toFixed(2)}`); // Formats num1 to 2 decimal places

// 8. [Link](digits)
[Link](`8. (num1).toExponential(2): ${(num1).toExponential(2)}`); // Returns num1 in
exponential notation with 2 decimals

// 9. [Link](precision)
[Link](`9. (num1).toPrecision(2): ${(num1).toPrecision(2)}`); // Formats num1 to a specified
precision

// 10. [Link](value)
[Link](`10. [Link](-num1): ${[Link](-num1)}`); // Returns the absolute value of
-num1

// 11. [Link](value)
[Link](`11. [Link](4.2): ${[Link](4.2)}`); // Rounds 4.2 up to the nearest integer

// 12. [Link](value)
[Link](`12. [Link](4.9): ${[Link](4.9)}`); // Rounds 4.9 down to the nearest integer

// 13. [Link](value)
[Link](`13. [Link](4.5): ${[Link](4.5)}`); // Rounds 4.5 to the nearest integer

// 14. [Link](...values)
[Link](`14. [Link](num1, num2): ${[Link](num1, num2)}`); // Returns the largest of
num1 and num2

// 15. [Link](...values)
[Link](`15. [Link](num1, num2): ${[Link](num1, num2)}`); // Returns the smallest of
num1 and num2

// 16. [Link]()
[Link](`16. [Link](): ${[Link]()}`); // Returns a random number between 0
and 1

// 17. [Link](base, exponent)


[Link](`17. [Link](num2, 3): ${[Link](num2, 3)}`); // Returns num2 raised to the
power of 3

// 18. [Link](value)
[Link](`18. [Link](num1): ${[Link](num1)}`); // Returns the square root of num1

// 19. [Link](value)
[Link](`19. [Link](4.9): ${[Link](4.9)}`); // Returns the integer part of 4.9

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////
[Link](value)

Purpose: Checks if a given value is an array.


Returns: true or false.
Original Array: No effect.
[Link](element)

Purpose: Adds one or more elements to the end of the array.


Returns: New length of the array.
Original Array: Modified (adds element(s)).
[Link]()

Purpose: Removes the last element from the array.


Returns: Removed element.
Original Array: Modified (removes last element).
[Link]()

Purpose: Removes the first element from the array.


Returns: Removed element.
Original Array: Modified (removes first element).
[Link](element)

Purpose: Adds one or more elements to the beginning of the array.


Returns: New length of the array.
Original Array: Modified (adds element(s)).
[Link](...arrays)

Purpose: Merges one or more arrays.


Returns: New array containing merged values.
Original Array: No effect.
[Link](value)

Purpose: Checks if a value is in the array.


Returns: true or false.
Original Array: No effect.
[Link](value)

Purpose: Finds the index of a value.


Returns: Index of the value or -1 if not found.
Original Array: No effect.
[Link](value)

Purpose: Finds the last index of a value.


Returns: Index of the value or -1 if not found.
Original Array: No effect.
[Link](start, end)

Purpose: Returns a portion of the array.


Returns: New array with sliced elements.
Original Array: No effect.
[Link](start, deleteCount, ...items)

Purpose: Adds/removes elements at specified indices.


Returns: Array of removed elements.
Original Array: Modified (adds/removes elements).
[Link](callback)

Purpose: Executes a function for each element.


Returns: undefined.
Original Array: No effect.
[Link](callback)

Purpose: Creates a new array by applying a function to each element.


Returns: New array with transformed elements.
Original Array: No effect.
[Link](callback)

Purpose: Filters elements based on a condition.


Returns: New array with filtered elements.
Original Array: No effect.
[Link](callback, initialValue)
Purpose: Reduces array to a single value.
Returns: Resulting value.
Original Array: No effect.
[Link](compareFunction)

Purpose: Sorts elements in place.


Returns: Sorted array (same reference).
Original Array: Modified (sorts elements).
[Link]()

Purpose: Reverses order of elements.


Returns: Reversed array (same reference).
Original Array: Modified (reverses order).
[Link](separator)

Purpose: Joins elements into a string.


Returns: Concatenated string.
Original Array: No effect.
[Link](callback)

Purpose: Checks if all elements pass a condition.


Returns: true or false.
Original Array: No effect.
[Link](callback)

Purpose: Checks if any element passes a condition.


Returns: true or false.
Original Array: No effect.
[Link](callback)

Purpose: Finds the first element that meets a condition.


Returns: First matching element or undefined.
Original Array: No effect.
[Link](callback)

Purpose: Finds the index of the first element that meets a condition.
Returns: Index of first match or -1.
Original Array: No effect.
[Link](value, start, end)

Purpose: Fills elements with a specified value.


Returns: Modified array (same reference).
Original Array: Modified (fills specified range).
[Link](depth)

Purpose: Flattens nested arrays to a specified depth.


Returns: New flattened array.
Original Array: No effect.
[Link](callback)

Purpose: Maps and flattens the array.


Returns: New flattened array.
Original Array: No effect.

---------------------------------
key Differences Between map(), filter(), and reduce()
Purpose:

map():
Transforms each element in the array and returns a new array with the transformed values.

filter():
Selects elements from an array based on a specific condition and returns a new array
containing only those elements.

reduce():
Reduces the array to a single value by applying a function to each element. This can be useful
for tasks like summing numbers, calculating averages, or concatenating strings.

----------------------------------------------------------------------------------
// Sample array for demonstration
let arr = [1, 2, 3, 4, 5];

// 1. [Link](value)
[Link](`1. [Link](arr): ${[Link](arr)}`); // Checks if arr is an array

// 2. [Link](element)
[Link](6);
[Link](`2. [Link](6): ${arr}`); // Adds 6 to the end of arr

// 3. [Link]()
let popped = [Link]();
[Link](`3. [Link](): ${popped}, arr: ${arr}`); // Removes the last element and returns it
// 4. [Link]()
let shifted = [Link]();
[Link](`4. [Link](): ${shifted}, arr: ${arr}`); // Removes the first element and returns it

// 5. [Link](element)
[Link](0);
[Link](`5. [Link](0): ${arr}`); // Adds 0 to the beginning of arr

// 6. [Link](...arrays)
let newArr = [Link]([7, 8]);
[Link](`6. [Link]([7, 8]): ${newArr}`); // Combines arr with another array

// 7. [Link](value)
[Link](`7. [Link](3): ${[Link](3)}`); // Checks if arr contains 3

// 8. [Link](value)
[Link](`8. [Link](2): ${[Link](2)}`); // Returns the index of the first occurrence of 2

// 9. [Link](value)
[Link](2);
[Link](`9. [Link](2): ${[Link](2)}`); // Returns the index of the last
occurrence of 2

// 10. [Link](start, end)


[Link](`10. [Link](1, 4): ${[Link](1, 4)}`); // Returns a shallow copy of a portion of arr

// 11. [Link](start, deleteCount, ...items)


[Link](1, 2, 9, 10);
[Link](`11. [Link](1, 2, 9, 10): ${arr}`); // Adds 9 and 10 at index 1 and removes 2
elements

// 12. [Link](callback)
[Link]((value) => [Link](`12. [Link]: ${value}`)); // Executes a provided function
once for each array element

// 13. [Link](callback)
let squared = [Link]((value) => value ** 2);
[Link](`13. [Link](value => value ** 2): ${squared}`); // Creates a new array with the
results of calling a provided function on every element

// 14. [Link](callback)
let evenNumbers = [Link]((value) => value % 2 === 0);
[Link](`14. [Link](value => value % 2 === 0): ${evenNumbers}`); // Creates a new array
with all elements that pass the test

// 15. [Link](callback, initialValue)


let sum = [Link]((accumulator, currentValue) => accumulator + currentValue, 0);
[Link](`15. [Link]((acc, curr) => acc + curr, 0): ${sum}`); // Executes a reducer function
on each element

// 16. [Link](compareFunction)
let sorted = [Link]((a, b) => b - a);
[Link](`16. [Link]((a, b) => b - a): ${sorted}`); // Sorts the elements of arr in descending
order

// 17. [Link]()
[Link]();
[Link](`17. [Link](): ${arr}`); // Reverses the elements of arr

// 18. [Link](separator)
let joined = [Link](", ");
[Link](`18. [Link](", "): ${joined}`); // Joins all elements into a string

// 19. [Link](callback)
let allGreaterThanZero = [Link]((value) => value > 0);
[Link](`19. [Link](value => value > 0): ${allGreaterThanZero}`); // Checks if all elements
pass the test

// 20. [Link](callback)
let someGreaterThanFive = [Link]((value) => value > 5);
[Link](`20. [Link](value => value > 5): ${someGreaterThanFive}`); // Checks if at least
one element passes the test

// 21. [Link](callback)
let firstEven = [Link]((value) => value % 2 === 0);
[Link](`21. [Link](value => value % 2 === 0): ${firstEven}`); // Returns the value of the
first element that satisfies the testing function

// 22. [Link](callback)
let firstEvenIndex = [Link]((value) => value % 2 === 0);
[Link](`22. [Link](value => value % 2 === 0): ${firstEvenIndex}`); // Returns the
index of the first element that satisfies the testing function

// 23. [Link](value, start, end)


let filledArray = new Array(5).fill(1);
[Link](`23. new Array(5).fill(1): ${filledArray}`); // Fills a new array with 1s

// 24. [Link](depth)
let nestedArray = [1, [2, 3], [4, [5]]];
let flatArray = [Link](1);
[Link](`24. [Link](1): ${flatArray}`); // Flattens the nested arr

Question : what is javascript ?

answer :- javascript is a proggramming language primerly used for creating dynamic or


intaractive content on web pages. . it is the core technologies of developement ,alongside html
and css . while html and css while html provides the structure and css handless the styling
,javascript adds functionaility , making website intractive and responsive

key features of javascript ar :-

1 client side language


2 interactive:- opening closing menu
3. dom menuplation :- javascript can interact with the Dom of a webpage
which , is a tree structure representing the html document . . with javascript
you can
+ acces and modify html element
+ change style dynamically

4 . event handling :- an event is a key concept in web development that allows developers to
make applications interactive. javascript allos developers to respond to user action,like ,clicking
buttons typingin form or hovering other element

5. cross plattform : - javascript works on various platform and devices


6. libraries and framework:- + jquery,lodash
+ react ,angular ,[Link]

7 . Aynchronus proggramming :- javascript supports asynchronus operations , which allows


code excution to continue while waiting for a task (like netwrok or request).this is often doing
using callback ,promiss, or async await syntax

8 server side javascript :-with the advent of nodejs ,javascript can also used to write
server-side-code ,enablling full stack devlopement using a single language

Question what is jason


answer :- JSON (JavaScript Object Notation)

//undrstand

// JSON data
const jsonString = '{"name": "John", "age": 30, "isStudent": false}';

// Parsing JSON string to JavaScript object


const user = [Link](jsonString);
[Link]([Link]); // Output: John

// Converting JavaScript object to JSON string


const userObject = {
name: "Alice",
age: 25,
isStudent: true
};
const userJSON = [Link](userObject);
[Link](userJSON); // Output: '{"name":"Alice","age":25,"isStudent":true}'

/////////////////////////////////////////////////////////////
what is object
In programming, especially in JavaScript, an object is a collection of properties, where each
property is defined as a key-value pair. Objects allow you to group related data and functionality
together.

Q WHAT IS SLICE OR SPLICE METHOD ?

ANS 1. slice()
The slice() method is used to extract a section of an array and return it as a new array. It does
not modify the original array.

[Link](start, end);
----------------------------
const fruits = ['apple', 'banana', 'cherry', 'date', 'fig'];

// Extract from index 1 to index 3


const slicedFruits = [Link](1, 3);
[Link](slicedFruits); // Output: ['banana', 'cherry']

// Extract from index 2 to the end


const slicedFruits2 = [Link](2);
[Link](slicedFruits2); // Output: ['cherry', 'date', 'fig']
-------------------------------------------------------------------------------------------------------------------------------
--------
///////////////////////////////////////////////////////////////////////////////////////////////////
[Link]()
The splice() method is used to add or remove items from an array. It modifies the original array
and can return the removed items.

[Link](start, deleteCount, item1, item2, ...);

const fruits = ['apple', 'banana', 'cherry', 'date'];

// Index 1 se 1 element delete karo aur 'grape' aur 'kiwi' add karo
const removedFruits = [Link](1, 1, 'grape', 'kiwi');

[Link](removedFruits); // Output: ['banana'] (yeh deleted element hai)


[Link](fruits); // Output: ['apple', 'grape', 'kiwi', 'cherry', 'date'] (yeh modified array hai)

-----------------------------------------------------------------------------------
Explanation
splice(start, deleteCount, item1, item2, ...) method mein:

start: Yeh index hai jahan se aap changes shuru karte hain.
deleteCount: Agar yeh 0 hai, toh koi bhi elements delete nahi hote.
item1, item2, ...: Yeh naye elements hain jo aap array mein insert karte hain.

const fruits = ['apple', 'banana', 'cherry'];

// Index 1 par 'grape' aur 'kiwi' add karo


[Link](1, 0, 'grape', 'kiwi');

[Link](fruits); // Output: ['apple', 'grape', 'kiwi', 'banana', 'cherry']

Q WHAT IS BOOTSTRAP ?

ANS :-Bootstrap is a popular open-source front-end framework used to create responsive and
visually appealing websites and web applications quickly and efficiently. Developed by Twitter,
Bootstrap provides a collection of reusable HTML, CSS, and JavaScript components, along with
a grid system that allows developers to structure web content in a mobile-first, responsive
layout.

Key Features of Bootstrap


Responsive Grid System:

Bootstrap’s grid system is based on a 12-column layout, allowing for flexible and responsive
design. You can adjust the number of columns and specify breakpoints to create layouts
optimized for different screen sizes.
Predefined Components:

Bootstrap includes a wide array of UI components, such as buttons, forms, modals, alerts,
carousels, navigation bars, and more. These components are designed to look consistent and
can be easily customized.
Utility Classes:

It offers utility classes to control various CSS properties directly from HTML, such as text
alignment, margins, padding, background colors, and display settings.
JavaScript Plugins:

Bootstrap includes JavaScript plugins to add interactivity, such as modals, dropdowns,


carousels, tooltips, and more. These plugins are built on jQuery, making it easy to create
dynamic, interactive elements.
Customizable:

You can customize Bootstrap by overriding its default styles or by using the Bootstrap Sass
variables to adjust colors, spacing, fonts, and other aspects to match a specific design.
Cross-Browser Compatibility:

Bootstrap ensures compatibility across modern browsers, making it easier to create consistent
experiences for users on different platforms.

------------------------
Bootstrap ki Definition

Bootstrap ek lokpriya open-source front-end framework hai jo websites aur web applications ko
jaldi aur asaani se responsive aur visually appealing banane ke liye istemal hota hai. Iska vikas
Twitter ne kiya tha, aur yeh HTML, CSS, aur JavaScript components ka ek collection provide
karta hai, saath hi ek grid system bhi hai jo developers ko mobile-first, responsive layout mein
web content ko structure karne ki suvidha deta hai.

Bootstrap ke Key Features

1. Responsive Grid System:


Bootstrap ka grid system 12-column layout par aadharit hai, jo flexible aur responsive design ki
suvidha deta hai. Developers columns ki sankhya ko adjust kar sakte hain aur different screen
sizes ke liye layouts ko optimize karne ke liye breakpoints specify kar sakte hain.

2. Predefined Components:

Bootstrap mein UI components ki ek wide array shamil hai, jaise buttons, forms, modals, alerts,
carousels, navigation bars, aur bahut kuch. Yeh components consistent look ke liye design kiye
gaye hain aur aasani se customize kiye ja sakte hain.

3. Utility Classes:

Yeh utility classes pradan karta hai jo various CSS properties ko seedhe HTML se control karne
ki suvidha deti hain, jaise text alignment, margins, padding, background colors, aur display
settings.

4. JavaScript Plugins:

Bootstrap JavaScript plugins ko shamil karta hai jo interactivity add karne ke liye istemal hote
hain, jaise modals, dropdowns, carousels, tooltips, aur bahut kuch. Yeh plugins jQuery par
based hain, jisse dynamic aur interactive elements banana asaan ho jata hai.

5. Customizable:

Developers Bootstrap ko customize kar sakte hain, default styles ko override karke ya Bootstrap
Sass variables ka istemal karke colors, spacing, fonts, aur dusre aspects ko specific design ke
saath match karne ke liye adjust kar sakte hain.

6. Cross-Browser Compatibility:

Bootstrap modern browsers ke beech compatibility ensure karta hai, jisse alag-alag platforms
par users ke liye consistent experiences banana asaan ho jata hai.

Conclusion

Bootstrap ek powerful framework hai jo web development ko tezi se aur asaani se karne mein
madad karta hai. Iske responsive design features, predefined components, aur customizable
options se developers ko aise websites aur web applications banane mein madad milti hai jo
har device par achhe dikhte hain aur achhi functionality pradan karte hain.

Q.1 WHAT IS PROMISS??


ANS:- In JavaScript, a Promise is an object that represents the eventual completion (or failure)
of an asynchronous operation and the resulting value. Promises are used to handle
asynchronous tasks more efficiently and to improve code readability, particularly when handling
multiple async operations that may take time, like data fetching, API calls, or file operations.

Why Use Promises?


[Link] Asynchronous Operations: Promises help manage tasks that don’t complete
immediately, such as network requests or timeouts.

[Link] Callback Hell: Before Promises, asynchronous code relied heavily on callbacks,
leading to nested and hard-to-read code (known as "callback hell"). Promises help prevent this
by allowing a more structured way to chain asynchronous actions.

[Link] Readability and Error Handling: Promises make asynchronous code look cleaner
and easier to handle, especially when dealing with multiple async actions or potential errors.

How Promises Work


A Promise has three states:-

[Link]: The initial state, where the operation hasn’t completed yet.

[Link]: When the operation is successful, the Promise is resolved

----------------------------------------------------------
**** Using async/await******

async function fetchDataAsync() {


try {
const result = await fetchData();
[Link](result);
} catch (error) {
[Link](error);
}
}
fetchDataAsync();

--कैसे काम करता है async/await?


async keyword function के पहले लिखा जाता है , जिससे वह function asynchronous बन जाता है ।
await keyword Promise के साथ use किया जाता है और उस point पर code execution को रोकता है जब
तक कि Promise resolve या reject न हो जाए।

Differences in Practice
Readability: async/await asynchronous code को और भी readable बनाता है , क्योंकि यह traditional
synchronous code जैसा दिखता है ।

Error Handling: async/await के साथ error handling try-catch block में होती है , जो errors को handle
करने का एक cleaner तरीका है ।

तो, async/await और Promise में अंतर नहीं है ; बल्कि, async/await Promises को handle करने का एक
और बेहतर तरीका है , जिससे code लिखना और समझना आसान हो जाता है ।.

-------------------------------------
++++using promiss+++++

** Custom Promises Using new Promise()


जब कोई function पहले से Promise return नहीं करता है , या हमें एक customized asynchronous
operation की जरूरत होती है (जैसे setTimeout के साथ कुछ काम करना), तब हम खद ु एक custom Promise
बनाते हैं। इस स्थिति में हम new Promise() का उपयोग करते हैं।

+++with axios both+++++


import React, { useEffect, useState } from 'react';
import axios from 'axios';

function UserData() {
const [users, setUsers] = useState([]);
const [message, setMessage] = useState('');

useEffect(() => {
// API URL
const apiUrl = "[Link]

// Axios request with if, else if, and else conditions


[Link](apiUrl)
.then((response) => {
if ([Link] === 200) {
// Status 200: Success, data received
setUsers([Link]);
setMessage("Data fetched successfully!");
} else if ([Link] === 404) {
// Status 404: Not Found
setMessage("Data not found!");
} else {
// Other status codes
setMessage("Unexpected status code received.");
}
})
.catch((error) => {
if ([Link]) {
// Server responded with a status code out of 2x+ range
if ([Link] === 500) {
setMessage("Server error! Please try again later.");
} else {
setMessage("An error occurred: " + [Link]);
}
} else if ([Link]) {
// Request made but no response received
setMessage("No response from server.");
} else {
// Other errors
setMessage("Error in setting up request: " + [Link]);
}
});
}, []);

return (
<div>
<h1>User Data</h1>
<p>{message}</p>
<ul>
{[Link]((user) => (
<li key={[Link]}>{[Link]}</li>
))}
</ul>
</div>
);
}

export default UserData;


-------------------------------------------
**direct promiss

import React, { useEffect, useState } from 'react';


import axios from 'axios';

function UserData() {
const [users, setUsers] = useState([]);
const [error, setError] = useState(null);
useEffect(() => {
// API URL
const apiUrl = "[Link]

// Direct Promise-based Axios request


[Link](apiUrl)
.then((response) => {
// Directly setting the users data
setUsers([Link]);
})
.catch((error) => {
// Directly setting the error message
setError("An error occurred: " + [Link]);
});
}, []);

return (
<div>
<h1>User Data</h1>
{error && <p>{error}</p>}
<ul>
{[Link]((user) => (
<li key={[Link]}>{[Link]}</li>
))}
</ul>
</div>
);
}

export default UserData;

================================
Direct Promise Approach: Axios request को useEffect में सीधे call कर सकते हैं, और .then()/.catch()
का उपयोग कर सकते हैं।

Custom Promise: यदि आपको Axios response पर extra control चाहिए, तो आप custom Promise बना
सकते हैं और इसे useEffect में call कर सकते हैं।

//////////////////////////////))///////////////////////////////)////))/////////

JavaScript mein Promise ek object hai jo kisi asynchronous operation ke eventual completion
(ya failure) aur resulting value ko represent karta hai. Promises ka istemal asynchronous tasks
ko zyada effectively handle karne aur code ki readability ko sudharne ke liye kiya jata hai,
khaaskar jab multiple async operations handle karne hote hain, jaise data fetching, API calls, ya
file operations.

Promises Ka Upyog Kyon Karein?

1. Asynchronous Operations Ko Handle Karna: Promises un tasks ko manage karne mein


madad karte hain jo turant complete nahi hote, jaise network requests ya timeouts.

2. Callback Hell Se Bachna: Promises se pehle, asynchronous code callbacks par heavily
depend karta tha, jo nested aur hard-to-read code (jise "callback hell" kaha jata hai) ki taraf le
jata tha. Promises isse prevent karte hain, kyunki ye structured way mein asynchronous actions
ko chain karne ki suvidha dete hain.

3. Readability Aur Error Handling Mein Sudhar: Promises asynchronous code ko clean aur
handle karne mein aasan banate hain, khaaskar jab multiple async actions ya potential errors
ho.

Promises Kaise Kaam Karte Hain

Ek Promise ke teen states hote hain:

1. Pending: Pehli state, jahan operation abhi complete nahi hua hota.

2. Fulfilled: Jab operation successful hota hai, tab Promise resolve hota hai.

Using async/await

async function fetchDataAsync() {


try {
const result = await fetchData();
[Link](result);
} catch (error) {
[Link](error);
}
}
fetchDataAsync();

Kaise Kaam Karta Hai async/await?

async keyword function ke pehle likha jata hai, jisse wo function asynchronous ban jata hai.

await keyword Promise ke sath use kiya jata hai aur code execution ko rokta hai jab tak
Promise resolve ya reject nahi ho jata.
Differences in Practice

Readability: async/await asynchronous code ko aur bhi readable banata hai, kyunki ye
traditional synchronous code jaisa lagta hai.

Error Handling: async/await ke sath error handling try-catch block mein hoti hai, jo errors ko
handle karne ka ek cleaner tarika hai.

Toh, async/await aur Promise mein antar nahi hai; balki, async/await Promises ko handle karne
ka ek aur better tarika hai, jisse code likhna aur samajhna aasan ho jata hai.

Using Promises

Custom Promises Using new Promise() Jab koi function pehle se Promise return nahi karta hai,
ya humein ek customized asynchronous operation ki zaroorat hoti hai (jaise setTimeout ke sath
kuch kaam karna), tab hum khud ek custom Promise banate hain. Is sthiti mein hum new
Promise() ka upyog karte hain.

With Axios

import React, { useEffect, useState } from 'react';


import axios from 'axios';

function UserData() {
const [users, setUsers] = useState([]);
const [message, setMessage] = useState('');

useEffect(() => {
// API URL
const apiUrl = "[Link]

// Axios request with if, else if, and else conditions


[Link](apiUrl)
.then((response) => {
if ([Link] === 200) {
// Status 200: Success, data received
setUsers([Link]);
setMessage("Data fetched successfully!");
} else if ([Link] === 404) {
// Status 404: Not Found
setMessage("Data not found!");
} else {
// Other status codes
setMessage("Unexpected status code received.");
}
})
.catch((error) => {
if ([Link]) {
// Server responded with a status code out of 2xx range
if ([Link] === 500) {
setMessage("Server error! Please try again later.");
} else {
setMessage("An error occurred: " + [Link]);
}
} else if ([Link]) {
// Request made but no response received
setMessage("No response from server.");
} else {
// Other errors
setMessage("Error in setting up request: " + [Link]);
}
});
}, []);

return (
<div>
<h1>User Data</h1>
<p>{message}</p>
<ul>
{[Link]((user) => (
<li key={[Link]}>{[Link]}</li>
))}
</ul>
</div>
);
}

export default UserData;

Direct Promise Approach

import React, { useEffect, useState } from 'react';


import axios from 'axios';

function UserData() {
const [users, setUsers] = useState([]);
const [error, setError] = useState(null);

useEffect(() => {
// API URL
const apiUrl = "[Link]

// Direct Promise-based Axios request


[Link](apiUrl)
.then((response) => {
// Directly setting the users data
setUsers([Link]);
})
.catch((error) => {
// Directly setting the error message
setError("An error occurred: " + [Link]);
});
}, []);

return (
<div>
<h1>User Data</h1>
{error && <p>{error}</p>}
<ul>
{[Link]((user) => (
<li key={[Link]}>{[Link]}</li>
))}
</ul>
</div>
);
}

export default UserData;

Summary

Direct Promise Approach: Axios request ko useEffect mein seedha call kar sakte hain, aur
.then()/.catch() ka upyog kar sakte hain.

Custom Promise: Yadi aapko Axios response par extra control chahiye, to aap custom Promise
bana sakte hain aur ise useEffect mein call kar sakte hain.
q what is let var const difference?

ans :- Here's a table focused on scope, declaration, and assignment differences between var,
let, and const:

Feature var let


const
Scope Function-scoped Block-scoped
Block-scoped
Re-declaration Allowed in the same scop Not allowed in the
same scope Not allowed in the same scope
Re-assignment Allowed Allowed
Not allowed (after initial
assignment)
Declaration Can be declared without assignment Can be declared without
assignment Must be declared with assignment

///
Example of Re-assign:-

let z = 10; // Declaration और Assignment


z = 30; // यह सिर्फ re-assign हो रहा है , क्योंकि हम सिर्फ value बदल रहे हैं, दोबारा declare नहीं कर रहे ।
[Link](z); // Output: 30

///////////
Example var के साथ re-declare
var x = 10; // यह पहली बार declaration और assignment है ।
var x = 20; // यहाँ x को दोबारा declare किया गया है (re-declare), और नई value assign की गई है ।
[Link](x); // Output: 20

●​ Callback Hell tab hoti hai jab aap ek callback ke andar doosra callback daalte hain aur
is tarah code ka structure complex ho jata hai.
●​ Isse bachne ke liye aap Promises ya Async/Await ka use kar sakte hain, jo code ko
more readable aur manageable banate hain.

Promises aur Async/Await modern JavaScript me best practices hain jo asynchronous


operations ko handle karte waqt aapko clean aur structured code likhne me madad karte hain.

// Example of Callback Hell


fetchData(function(error, data) {
if (error) {
[Link]("Error in fetching data!");
} else {
processData(data, function(error, processedData) {
if (error) {
[Link]("Error in processing data!");
} else {
saveData(processedData, function(error, savedData) {
if (error) {
[Link]("Error in saving data!");
} else {
[Link]("Data saved successfully!");
}
});
}
});
}
});

------------------------------------------------------

var, let, aur const ke beech ka antar

Scope:

var: Function-scoped hota hai. Agar ise function ke andar declare kiya gaya hai, to ye sirf usi
function ke andar accessible hota hai.

let: Block-scoped hota hai. Ye sirf us block (jaise ki curly braces ke andar) ke andar accessible
hota hai jahan ise declare kiya gaya hai.

const: Block-scoped hota hai, let ki tarah. Ye bhi sirf us block ke andar accessible hota hai jahan
ise define kiya gaya hai.

Re-declaration:

var: Same scope mein re-declaration allow hai. Aap ek hi variable ko baar baar declare kar
sakte hain.
let: Same scope mein re-declaration allowed nahi hai. Aap same block mein ek hi variable ko
dobara declare nahi kar sakte.

const: Same scope mein re-declaration allowed nahi hai. Aap same block mein ek hi variable ko
dobara declare nahi kar sakte.

Re-assignment:

var: Re-assignment allowed hai. Aap var se declare kiye gaye variable ki value change kar
sakte hain.

let: Re-assignment allowed hai. Aap let se declare kiye gaye variable ki value change kar sakte
hain.

const: Initial assignment ke baad re-assignment allowed nahi hai. Ek baar agar const se kisi
variable ko value assign kar di, to usse badal nahi sakte.

Declaration:

var: Isay bina initialization ke declare kiya ja sakta hai.

let: Isay bina initialization ke declare kiya ja sakta hai.

const: Isay initial assignment ke sath declare karna zaroori hai.

Examples

let ke sath Re-assignment

let z = 10; // Declaration aur Assignment


z = 30; // Ye sirf re-assignment hai; hum sirf value badal rahe hain, dobara declare nahi kar
rahe.
[Link](z); // Output: 30

var ke sath Re-declaration

var x = 10; // Ye pehli baar declaration aur assignment hai.


var x = 20; // Yahan x ko dobara declare kiya gaya hai (re-declare), aur nayi value assign ki
gayi hai.
[Link](x); // Output: 20

Sankshipt
var ka istemal tab karein jab aapko function scope ki zaroorat ho aur re-declaration allow ho.

let ka istemal tab karein jab aapko block scope ki zaroorat ho aur value ko reassign karna ho.

const ka istemal tab karein jab aapko block scope ki zaroorat ho aur initial assignment ke baad
value ko reassign nahi karna ho.

Q WHAT IS RECURSION

Recursion is a programming technique where a function calls itself in order to solve a problem.
The idea is to break down a complex problem into smaller, more manageable sub-problems,
allowing the function to repeat its process until it reaches a base case.

function factorial(n) {
// Base case
if (n === 0) {
return 1; // 0! is 1
}
// Recursive case
return n * factorial(n - 1);
}

[Link](factorial(5)); // Output: 120

__________________________________
Recursion

Recursion ek programming technique hai jismein ek function khud ko call karta hai kisi problem
ko solve karne ke liye. Iska mool mantra hai complex problem ko choti-choti, manageable
sub-problems mein todna, jis se function apne process ko tab tak dohra sakta hai jab tak woh
ek base case tak nahi pahunchta.

Example of Recursion:

function factorial(n) {
// Base case
if (n === 0) {
return 1; // 0! is 1
}
// Recursive case
return n * factorial(n - 1);
}
[Link](factorial(5)); // Output: 120

Is example mein, factorial function apne aap ko call karta hai jab tak n ka value 0 nahi ho jata.
Jab n 0 hota hai, function base case tak pahunchta hai aur 1 return karta hai. Is tarah se
function factorial calculate karta hai.

question what is regex?

answer :_In a sequence of characters, Regex (Regular Expression) specifies the match pattern
in a given text. It works by defining rules or patterns that allow you to search, validate, or
manipulate strings effectively.

let hasNumber = /\d{10}/.test(text);


[Link](hasNumber); // Output: true

// 2. match() - Get all digits in the string


let allDigits = [Link](/\d+/g);
[Link](allDigits); // Output: ['9876543210', '1234']

// 3. replace() - Replace phone number with '**********'


let hiddenNumber = [Link](/\d{10}/, '**********');
[Link](hiddenNumber); // Output: "John's phone number is ********** and his ID is
AB1234"

4.// Create a regular expression


const regex = /hello/;

// Test the string


const result = [Link]("hello world"); // Returns true
[Link](result); // Output: true

const result2 = [Link]("Hi there!"); // Returns false


[Link](result2); // Output: false

--------------------------------------

Regex (Regular Expression)

Ek character sequence mein, Regex (Regular Expression) ek match pattern ko specify karta hai
diye gaye text mein. Yeh rules ya patterns ko define karke kaam karta hai jo aapko strings ko
search, validate, ya manipulate karne mein madad karte hain.
Examples of Regex Usage:

1. Check for a 10-digit number:

let hasNumber = /\d{10}/.test(text);


[Link](hasNumber); // Output: true

2. Extract all digits in the string:

let allDigits = [Link](/\d+/g);


[Link](allDigits); // Output: ['9876543210', '1234']

3. Replace a phone number with '**********':

let hiddenNumber = [Link](/\d{10}/, '**********');


[Link](hiddenNumber); // Output: "John's phone number is ********** and his ID is
AB1234"

4. Create and test a regular expression:

// Create a regular expression


const regex = /hello/;

// Test the string


const result = [Link]("hello world"); // Returns true
[Link](result); // Output: true

const result2 = [Link]("Hi there!"); // Returns false


[Link](result2); // Output: false

Is tarah se, Regex ka istemal karke aap apne text mein pattern matching, extraction, aur
replacement kar sakte hain, jo string manipulation ko asan aur efficient banata hai.

Q WHAT IS CALL APPLY BIND AND THIS METHOD

1. call() Method
The call() method invokes a function with a specific value for this, and any number of arguments
passed individually.

[Link](thisArg, arg1, arg2, ...)


function greet(greeting, punctuation) {
[Link](greeting + ", I am " + [Link] + punctuation);
}

const person = { name: "Alice" };

// 'person' object को `this` के रूप में set किया, और बाकी arguments pass किए
[Link](person, "Hello", "!");
// Output: Hello, I am Alice!

////////////////////
2. apply() Method
The apply() method is similar to call(), but it takes the arguments as an array (or array-like
object) rather than individually.

[Link](thisArg, [arg1, arg2, ...])


function greet(greeting, punctuation) {
[Link](greeting + ", I am " + [Link] + punctuation);
}

const person = { name: "Bob" };

// 'person' object को `this` के रूप में set किया, और arguments को array में pass किया
[Link](person, ["Hi", "."]);
// Output: Hi, I am Bob.

/////////////////////////////

3. bind() Method
The bind() method creates a new function that, when invoked, has its this value set to a specific
value. Unlike call() and apply(), bind() does not immediately execute the function; instead, it
returns a new function that can be called later.

const boundFunction = [Link](thisArg, arg1, arg2, ...)

function greet(greeting, punctuation) {


[Link](greeting + ", I am " + [Link] + punctuation);
}

const person = { name: "Charlie" };

// 'person' object को `this` के रूप में bind किया और arguments bind किए
const greetPerson = [Link](person, "Hey", "!");
greetPerson(); // Output: Hey, I am Charlie!
////////////////////
4. this Keyword
The this keyword refers to the object it belongs to. The value of this is determined based on how
a function is called:
const person = {
name: "John",
greet: function() {
[Link]("Hi, " + [Link]);
}
};

[Link](); // Output: Hi, John

///////////////////////////
1. call() Method
Definition: The call() method calls a function with a given this value and arguments provided
individually.

2. apply() Method
Definition: The apply() method calls a function with a given this value and arguments provided
as an array.

3. bind() Method
Definition: The bind() method creates a new function that, when called, has its this keyword set
to a specific value, with a given sequence of arguments.

4. this
Definition: The this keyword refers to the object that is executing the current function. Its value
can change based on the context in which the function is called.F

---------------------------------------

JavaScript Functions: call(), apply(), bind(), and this Keyword

1. call() Method
Definition: call() method ek function ko ek diye gaye this value aur arguments ko vyaktigat roop
se pass karne ke liye call karta hai.
Example:

function greet(greeting, punctuation) {


[Link](greeting + ", I am " + [Link] + punctuation);
}
const person = { name: "Alice" };

// 'person' object ko `this` ke roop mein set kiya, aur baaki arguments pass kiye
[Link](person, "Hello", "!");
// Output: Hello, I am Alice!

---

2. apply() Method
Definition: apply() method ek function ko ek diye gaye this value aur arguments ko ek array ke
roop mein pass karne ke liye call karta hai.
Example:

function greet(greeting, punctuation) {


[Link](greeting + ", I am " + [Link] + punctuation);
}

const person = { name: "Bob" };

// 'person' object ko `this` ke roop mein set kiya, aur arguments ko array mein pass kiya
[Link](person, ["Hi", "."]);
// Output: Hi, I am Bob.

---

3. bind() Method
Definition: bind() method ek nayi function banata hai jo, jab call kiya jata hai, toh uska this
keyword ek vishesh value par set hota hai, diye gaye arguments ke saath.
Example:

function greet(greeting, punctuation) {


[Link](greeting + ", I am " + [Link] + punctuation);
}

const person = { name: "Charlie" };

// 'person' object ko `this` ke roop mein bind kiya aur arguments bind kiye
const greetPerson = [Link](person, "Hey", "!");
greetPerson(); // Output: Hey, I am Charlie!
---

4. this Keyword
Definition: this keyword us object ko sandarbhit karta hai jo vartaman function ko chala raha hai.
Iska value us sandarbh par nirbhar karta hai jismein function ko call kiya jata hai.
Example:

const person = {
name: "John",
greet: function() {
[Link]("Hi, " + [Link]);
}
};

[Link](); // Output: Hi, John

---

Methods ka Sankshipt Vivaran

1. call() Method

Definition: Ek function ko ek diye gaye this value aur arguments ko vyaktigat roop se call karta
hai.

2. apply() Method

Definition: Ek function ko ek diye gaye this value aur arguments ko ek array ke roop mein call
karta hai.

3. bind() Method

Definition: Ek nayi function banata hai jo, jab call kiya jata hai, toh uska this keyword ek vishesh
value par set hota hai, diye gaye arguments ke saath.

4. this

Definition: Us object ko sandarbhit karta hai jo vartaman function ko chala raha hai, aur iska
value call sandarbh par nirbhar karta hai.
What is a Prototype?
// what is prototype

// The prototype is a special object automatically associated with every function and object in
JavaScript.

// We define a set of properties and methods on this prototype object,

// which are then shared and accessible by all instances (examples) of that function or object.

// when to use

// प्रोटोटाइप का उपयोग तब होता है जब आप चाहते हैं कि कई ऑब्जेक्ट्स (instances) एक ही मेथड या प्रॉपर्टी


को साझा करें ,

// न कि हर ऑब्जेक्ट के पास उसकी अपनी कॉपी हो।

// "...या किसी क्लास में हमें ऑब्जेक्ट को क्रिएट करना हो तब हम प्रोटोटाइप का यज़
ू कर सकते हैं।"

// function Animal(name) { // This is a constructor function for creating 'Animal' objects.

// [Link] = name;

// }

// [Link] = function()

// [Link](`${[Link]} makes a sound.`);

// };

// let dog = new Animal("Dog"); // 'dog' is an instance of 'Animal'. It inherits from


'[Link]'.

// [Link](); // When '[Link]()' is called, JavaScript looks for 'speak' on 'dog'. It doesn't
find it directly, so it looks up the prototype chain to '[Link]' and finds 'it' there.

WHAT DO YOU MEAN BY SELF INVOKING FUNCTION


A self-invoking function (or immediately invoked function expression, IIFE) is a JavaScript
function that is defined and executed immediately after its creation, without being called
elsewhere in the code

(function() {
// Your code here
[Link]("This function runs immediately!");
})();

Self-invoking function: A function that runs as soon as it is defined, usually encapsulated in


parentheses and followed by another set of parentheses to invoke it immediately.

-------------
Self-Invoking Function (IIFE)

Definition: Self-invoking function, jise Immediately Invoked Function Expression (IIFE) bhi kaha
jata hai, JavaScript ka ek khas function hai jo khud se turant execute hota hai. Iska istemal
aksar scope ke management aur variable encapsulation ke liye hota hai. IIFE ko define karne
ke liye function ko parentheses mein wrap kiya jata hai, aur iske baad ek aur set of parentheses
ka istemal karke ise turant invoke kiya jata hai.

Structure:

IIFE ki basic structure kuch is tarah hoti hai:

(function() {
// Aapka code yahan
})();

Yahan pe:

Pehla parentheses ( function definition ko start karta hai.

Doosra parentheses ) function definition ko band karta hai.

Teesra set of parentheses () function ko turant invoke karta hai.

Example:

Yeh ek example hai jisme ek self-invoking function ka istemal kiya gaya hai:

(function() {
let message = "Hello, World!";
[Link](message); // Output: Hello, World!
})();

Use Cases:

1. Variable Encapsulation: IIFE ka istemal karne se hum variables ko encapsulate kar sakte
hain. Yeh global scope ko pollution se bachaata hai, kyunki variables sirf IIFE ke andar hi
accessible hote hain.

(function() {
var privateVar = "I am private!";
[Link](privateVar); // Accessible here
})();
[Link](privateVar); // ReferenceError: privateVar is not defined

2. Initialization: Aksar IIFE ka istemal initialization code likhne ke liye hota hai, jaise DOM
elements ko manipulate karna ya koi initial setup karna.

(function() {
[Link] = "lightblue";
[Link]("Background color changed!");
})();

3. Avoiding Global Scope Pollution: IIFE ka istemal karne se hum apne code ke global scope ko
pollution se bacha sakte hain, jisse global variables ki sankhya kam hoti hai.

4. Creating a Module: IIFE ka istemal modules banane ke liye bhi hota hai, jahan aapko private
functions ya variables ki jarurat hoti hai.

var counterModule = (function() {


let count = 0; // Private variable

return {
increment: function() {
count++;
[Link](count);
},
decrement: function() {
count--;
[Link](count);
}
};
})();
[Link](); // Output: 1
[Link](); // Output: 2
[Link](); // Output: 1

Conclusion:

Self-invoking functions (IIFEs) JavaScript mein ek powerful technique hain jo scope


management aur variable encapsulation ko asaan banate hain. Yeh functions ko turant execute
karne ka tarika pradan karte hain, jisse aap apne code ko zyada modular aur organized bana
sakte hain.

[Link] between == and === operatore

it is used to compare both values and types


5 === '5'; // false
/////////////
nan****
[Link](0 / 0); // NaN (division by zero)
[Link]([Link](-1)); // NaN (square root of a negative number)

[Link](Number("hello")); // NaN (cannot convert to number)


[Link](undefined + 5); // NaN (undefined is not a number)
[Link](null * 2); // 0 (null is treated as 0 in multiplication)

//////////////////
undefined***

let a; // `a` is declared but not initialized


[Link](a); // undefined

function foo() {
return; // If a function doesn't explicitly return a value, it returns `undefined`
}
[Link](foo()); // undefined

let obj = {};


[Link]([Link]); // undefined (because the property `name` doesn't exist)
////////////////////
null******
let b = null; // b is explicitly set to null, meaning "no value"
[Link](b); // null

let obj = { name: null }; // 'name' is explicitly set to null, meaning "no name"
[Link]([Link]); // null
/////////////////
***false
let isAdult = true;
if (isAdult) {
[Link]("You are an adult."); // This will run because isAdult is true
}

/////////////////////////////////////////////////////////
// JavaScript Operators: Clean, Concise & Beautiful Examples

[Link]("--- 1. Arithmetic Operators ---");


let a = 10, b = 3;
[Link](`+ (Add): ${a + b}`); // 13
[Link](`- (Sub): ${a - b}`); // 7
[Link](`* (Mul): ${a * b}`); // 30
[Link](`/ (Div): ${a / b}`); // 3.33...
[Link](`% (Mod): ${a % b}`); // 1
[Link](`** (Exp): ${b ** 2}`); // 9 (3^2)
let inc = 5; [Link](`++ (Inc): ${++inc}`); // 6
let dec = 5; [Link](`-- (Dec): ${--dec}`); // 4

[Link]("\n--- 2. Assignment Operators ---");


let x = 10;
x += 5; // x = 15
[Link](`+= (Add Assign): ${x}`);
x *= 2; // x = 30
[Link](`*= (Mul Assign): ${x}`);

[Link]("\n--- 3. Comparison Operators ---");


let num = 8, strNum = '8';
[Link](`== (Loose Eq): ${num == strNum}`); // true
[Link](`=== (Strict Eq): ${num === strNum}`); // false
[Link](`!= (Not Eq): ${num != 5}`); // true
[Link](`!== (Strict Not Eq): ${num !== strNum}`); // true
[Link](`> (Greater): ${num > 5}`); // true
[Link](`< (Less): ${num < 5}`); // false
[Link](`>= (Gtr/Eq): ${num >= 8}`); // true

[Link]("\n--- 4. Logical Operators ---");


let p = true, q = false;
[Link](`&& (AND): ${p && q}`); // false
[Link](`|| (OR): ${p || q}`); // true
[Link](`! (NOT): ${!p}`); // false

[Link]("\n--- 5. Conditional (Ternary) Operator ---");


let age = 20;
let status = (age >= 18) ? "Adult" : "Minor";
[Link](`Status: ${status}`); // Adult

[Link]("\n--- 6. String Operator ---");


let greeting = "Hello" + " World";
[Link](`Concatenation: ${greeting}`); // Hello World

[Link]("\n--- 7. Type Operators ---");


[Link](`Type of "abc": ${typeof "abc"}`); // string
[Link](`Is [] an Array? ${[] instanceof Array}`); // true

[Link]("\n--- 8. Nullish Coalescing Operator (??) ---");


let user = null;
let name = user ?? "Guest";
[Link](`Name: ${name}`); // Guest

[Link]("\n--- 9. Optional Chaining Operator (?.) ---");


const person = { address: { street: "Main St" } };
[Link](`Street: ${[Link]?.street}`); // Main St
[Link](`City: ${[Link]?.city}`); // undefined (no error)

[Link]("\n--- 10. Spread (...) and Rest (...) Operators ---");


// Spread: Expand elements
const arr = [1, 2];
const newArr = [...arr, 3];
[Link](`Spread Array: ${newArr}`); // [1,2,3]
const obj = { a: 1 };
const newObj = { ...obj, b: 2 };
[Link]('Spread Object:', newObj); // { a: 1, b: 2 }

// Rest: Collect into array/object


function sum(...nums) { // nums collects all arguments
return [Link]((acc, curr) => acc + curr, 0);
}
[Link](`Rest Sum: ${sum(1, 2, 3, 4)}`); // 10

[Link]("\n--- 11. Copying Objects & Arrays: Shallow vs. Deep ---");

// --- Understanding the Difference ---


// Original object with nested data
const originalData = {
id: 1,
info: {
name: "Alice",
age: 30
},
items: ["apple", "banana"]
};

[Link]('Original Data:', originalData);

// --- 11a. Shallow Copy ---


// Creates a new object, but copies references of nested objects/arrays.
// Changing nested parts in the copy WILL affect the original.

const shallowCopyData = { ...originalData }; // Using Spread for shallow copy

[Link]('\n--- Shallow Copy Example ---');


[Link]('Shallow Copy (before change):', shallowCopyData);

// Modify a top-level primitive property:


[Link] = 2; // Changes only in shallowCopy

// Modify a nested object property:


[Link] = 31; // Changes in [Link] TOO!

// Modify a nested array:


[Link]("orange"); // Changes in [Link] TOO!

[Link]('Shallow Copy (after change):', shallowCopyData);


[Link]('Original Data (after shallow copy change):', originalData);
// Notice: id changed only in shallowCopy, but [Link] and items changed in BOTH!

// --- 11b. Deep Copy ---


// Creates a completely new object with new copies of all nested objects/arrays.
// Changing nested parts in the copy will NOT affect the original.

const originalDeepData = {
id: 10,
info: {
name: "Bob",
age: 25
},
items: ["book", "pen"]
};

let deepCopyData;

[Link]('\n--- Deep Copy Example ---');


[Link]('Original Deep Data (before change):', originalDeepData);

// Method for Deep Copy: structuredClone() (Recommended for modern environments)


// Handles most data types including Maps, Sets, Dates, etc. (but not functions or DOM
elements)
if (typeof structuredClone === 'function') {
deepCopyData = structuredClone(originalDeepData);
[Link]('Method: structuredClone()');
} else {
// Fallback for older environments or simple JSON-serializable objects
// WARNING: Does NOT copy functions, Dates, undefined, etc.
deepCopyData = [Link]([Link](originalDeepData));
[Link]('Method: [Link]([Link]()) (Fallback)');
}

[Link]('Deep Copy (before change):', deepCopyData);

// Modify a top-level primitive property:


[Link] = 11; // Changes only in deepCopyData
// Modify a nested object property:
[Link] = 26; // Changes ONLY in [Link]

// Modify a nested array:


[Link]("laptop"); // Changes ONLY in [Link]

[Link]('Deep Copy (after change):', deepCopyData);


[Link]('Original Deep Data (after deep copy change):', originalDeepData);
// Notice: ALL changes (id, [Link], items) only affected the deepCopyData, NOT the
originalDeepData.

// [Link]("\n--- 12. Bitwise Operators (Advanced - Uncomment to see) ---");


// let numA = 5; // 0101
// let numB = 3; // 0011
// [Link](`& (AND): ${numA & numB}`); // 1 (0001)
// [Link](`| (OR): ${numA | numB}`); // 7 (0111)
// [Link](`^ (XOR): ${numA ^ numB}`); // 6 (0110)
रे स्ट ऑपरे टर में आप "और ज़्यादा कुछ add" नहीं कर सकते जो उसे भेजा न गया हो। वह केवल वही "पैक"
करता है जो उसे इंडिविजअ ु ल आइटम्स के रूप में मिलता है ।

quetion what is this keyword

quetion what is this keyword


answer :-
In JavaScript (and React), the this keyword refers to the current instance of an object or class
and is used to access its properties and methods within that context. Here's why and when we
use this:

///////////////
class Car {
constructor(brand) {
[Link] = brand; // 'this' refers to the current instance of Car
}

getBrand() {
return [Link]; // Using 'this' to access the brand property
}
}

const myCar = new Car("Toyota");


[Link]([Link]()); // Output: Toyota
////////////////////
class Button extends [Link] {
handleClick() {
[Link](this); // 'this' refers to the Button component instance
}

render() {
return <button onClick={[Link](this)}>Click me</button>;
}
}
///////////////

question: what is this keyword


answer: JavaScript (aur React) mein this keyword current instance of an object ya class ko refer
karta hai. Ye context-specific hota hai aur isse hum properties aur methods ko access karne ke
liye istemal karte hain. this ka behavior thoda complex ho sakta hai, kyunki ye function call ke
context par depend karta hai. Yahan iske istemal ke kuch mahatvapurn points hain:

1. Object Context

this keyword us object ko refer karta hai jisse function call kiya gaya hai. Agar aap ek method ko
kisi object ke context mein call karte hain, toh this us object ko represent karega.

Example:

const person = {
name: "John",
greet: function() {
[Link]("Hello, my name is " + [Link]); // 'this' refers to the person object
}
};

[Link](); // Output: Hello, my name is John

2. Class Context

Classes mein, this keyword current instance ko refer karta hai. Jab aap class ka object banate
hain, this us object ke properties aur methods ko access karne mein madad karta hai.

Example:

class Car {
constructor(brand) {
[Link] = brand; // 'this' current instance of Car ko refer karta hai
}

getBrand() {
return [Link]; // 'this' ka istemal brand property ko access karne ke liye hota hai
}
}

const myCar = new Car("Toyota");


[Link]([Link]()); // Output: Toyota

3. Event Handling in React

React components mein, this keyword component instance ko refer karta hai. Ye aapko
component ke state aur methods ko access karne ki suvidha deta hai. Lekin, JavaScript ki
function scoping ki wajah se, event handler methods mein this ka context thoda tricky ho sakta
hai.

Example:

class Button extends [Link] {


handleClick() {
[Link](this); // 'this' Button component instance ko refer karta hai
}

render() {
return <button onClick={[Link](this)}>Click me</button>;
}
}

Yahan, bind(this) ka istemal karke hum handleClick method ke liye this ko current instance par
set kar rahe hain. Agar aap bind ka istemal nahi karte, toh this global context ya undefined ko
refer karega, jo aksar desired behavior nahi hota.

4. Arrow Functions

Arrow functions mein this lexical scope ko maintain karte hain, jisse aapko traditional functions
ki tarah bind karne ki zarurat nahi hoti. Ye useful hota hai jab aapko this ka reference maintain
karna hota hai.

Example:
class Button extends [Link] {
handleClick = () => {
[Link](this); // 'this' refers to the Button component instance
}

render() {
return <button onClick={[Link]}>Click me</button>;
}
}

Is example mein, handleClick ko arrow function ke roop mein define kiya gaya hai, jisse this
Button component ko refer karega bina bind ki zarurat ke.

Summary

this keyword JavaScript mein ek powerful feature hai, lekin iska behavior context ke hisaab se
change hota hai. Aapko yeh samajhna zaroori hai ki this kis object ko refer karta hai aur kis
context mein aap use kar rahe hain. Yeh samajhne se aap better code likh sakte hain, jo clear
aur maintainable ho.

what is callback or higher order function

question:- what is callback or higher order function?

A callback in JavaScript is a function that is passed as an argument to another function and is


executed after some operation or event is completed. It allows functions to be executed in a
specific order and is especially useful for handling asynchronous operations like network
requests or timers.

[Link]-order functions: A function that accepts another function as an argument is called a


higher-order function, and the passed-in function is known as a callback.

2Named or Anonymous: Callbacks can be named functions or anonymous (functions defined


directly as an argument).

function greet(name, callback) {


[Link]("Hello, " + name);
callback(); // Calling the callback function
}

function sayGoodbye() {
[Link]("Goodbye!");
}

greet("Alice", sayGoodbye);
// Output:
// Hello, Alice
// Goodbye!

//////////////////////

greet() ek higher-order function hai, kyunki yeh ek function (callback function) ko argument ke
roop mein accept kar raha hai.
sayGoodbye() ek callback function hai, kyunki isko greet() function ke andar se execute kiya ja
raha hai.

-------------------------
question: what is a callback in JavaScript?
answer: JavaScript mein callback ek aisi function hoti hai jo kisi doosri function ko argument ke
roop mein di jati hai aur kuch operation ya event ke complete hone ke baad execute hoti hai. Ye
functions ko ek specific order mein execute karne ki suvidha deti hai aur asynchronous
operations, jaise network requests ya timers, handle karne ke liye bahut upyogi hoti hai.

Key Points:

1. Higher-Order Functions: Ek function jo kisi doosri function ko argument ke roop mein accept
karta hai, use higher-order function kaha jata hai. Ismein pass ki gayi function ko callback
function kaha jata hai.

2. Named or Anonymous: Callbacks ya toh named functions ho sakti hain ya anonymous (wo
functions jo seedha argument ke roop mein define kiye gaye hain).

Example Code:

// Higher-order function that accepts a callback


function greet(name, callback) {
[Link]("Hello, " + name);
callback(); // Calling the callback function
}

// Callback function to be executed


function sayGoodbye() {
[Link]("Goodbye!");
}
// Calling the greet function with a name and the callback
greet("Alice", sayGoodbye);
// Output:
// Hello, Alice
// Goodbye!

Explanation:

Higher-Order Function: greet() function ko higher-order function kaha jata hai, kyunki ye ek
function (callback function) ko argument ke roop mein accept kar raha hai. Ismein callback
parameter ka use kiya gaya hai jo kisi doosri function ko represent karta hai.

Callback Function: sayGoodbye() ek callback function hai. Ye function ko greet() function ke


andar se execute kiya ja raha hai, isliye isse callback kaha jata hai. Jab greet() function call hota
hai, pehle "Hello, Alice" print hota hai aur uske baad sayGoodbye() function call hota hai, jo
"Goodbye!" print karta hai.

Benefits of Callbacks:

1. Asynchronous Operations: Callbacks asynchronous operations ko handle karne mein madad


karte hain. Jaise ki, network request ke complete hone ke baad data process karna.

2. Function Composition: Callbacks se aap functions ko modular aur reusable bana sakte hain.
Aap alag-alag callback functions ko use karke ek hi higher-order function ko different ways mein
utilize kar sakte hain.

3. Event Handling: Callbacks ka istemal event handling mein bhi hota hai, jaise button click
hone par koi action execute karna.

Conclusion:

Callbacks JavaScript mein ek important concept hain jo functions ko flexible aur reusable
banate hain. Ye asynchronous programming ko asan banate hain aur developers ko control
dete hain ki kab aur kaise functions execute honi chahiye. Callback functions ka sahi istemal
karke, aap apne JavaScript applications ko zyada efficient aur responsive bana sakte hain.

what is hosting?

Question what is hosting?


answer :- hosting allows you to a variable and function can be declared after it has been used

/////
In JavaScript, hosting refers to the automatic process by which JavaScript moves declarations
(variables and functions) to the top of their scope (global or local) before the code execution.
This means that variable and function declarations are "hoisted" to the top of their scope,
allowing them to be used before they are actually declared in the code.

/////////
sayHello(); // Output: Hello, world!

function sayHello() {
[Link]("Hello, world!");
}

-------------------------------------------------------

question: what is hosting?


answer: Hosting ka matlab hai ki JavaScript mein aapko ek variable ya function ko declare
karne se pehle bhi use karne ki suvidha milti hai.

Key Points:

1. Automatic Process: Hosting ek automatic process hai jisme JavaScript declarations (variables
aur functions) ko unke scope ke top par le jaya jata hai, chahe aap unhe code ke beech mein
kahin bhi declare karein.

2. Scope: Ye hoisting global scope ya local scope (function ke andar) ke liye hota hai. Iska
matlab hai ki agar aap ek function ko call karte hain ya variable ka use karte hain uske
declaration se pehle, toh JavaScript isse samajh lega ki aapne use declare kiya hai.

Example Code:

sayHello(); // Output: Hello, world!

function sayHello() {
[Link]("Hello, world!");
}

Explanation:

Function Hoisting: Is example mein, sayHello function ko call kiya gaya hai usse pehle, jahan
yeh declare nahi hua hai. Phir bhi, JavaScript isse execute karta hai aur output "Hello, world!"
deta hai. Ye hoisting ki wajah se possible hai, kyunki function declarations ko unke scope ke top
par le jaya jata hai.
Hoisting with Variables:

Variables ke saath bhi hoisting hoti hai, lekin unki behavior thodi alag hoti hai.

[Link](myVar); // Output: undefined


var myVar = 5;
[Link](myVar); // Output: 5

Explanation:

Variable Hoisting: Is example mein, myVar ko pehle console mein log kiya gaya hai, jabki isse
declare nahi kiya gaya hai. Iska output undefined hai, kyunki JavaScript declaration ko hoist
karta hai lekin initialization ko nahi. Isliye, myVar ki value tab tak undefined hoti hai jab tak aap
use explicitly assign nahi karte.

Key Differences:

1. Function Hoisting: Function declarations ko poore scope ke liye hoisted kiya jata hai, toh aap
unhe unke declare hone se pehle call kar sakte hain.

2. Variable Hoisting: Variables ko declare kiya jata hai lekin unki value initialization nahi hoti jab
tak unhe explicitly assign nahi kiya jata.

Conclusion:

Hoisting JavaScript ka ek important feature hai jo aapko variables aur functions ko unki
declaration se pehle istemal karne ki suvidha deta hai. Ye JavaScript ke behavior ko samajhne
mein madad karta hai, lekin aapko iski nuances samajhna bhi zaroori hai, taaki aap unexpected
behavior se bach sakein. Isliye, hamesha variable aur function declarations ko unke istemal se
pehle declare karna behtar hota hai, jisse code readability aur maintenance mein sudhar hota
hai.

what is data types?

Q what is data types?


answer:- Common Primitive Types in JavaScript:-

1. Number: Represents numeric values (e.g., 1, 100, 3.14).


let age = 25; // Number

[Link]: Represents a sequence of characters (e.g., "Hello").


let name = "John"; // String
Boolean: Represents true or false.

3 .let isStudent = true; // Boolean

4 . Undefined: A variable that has been declared but not assigned a value.
let x; // Undefined

5. Null: Represents the intentional absence of any object value.


let y = null; // Null

6. Symbol: A unique and immutable value used to create unique object property keys.

7. let sym = Symbol("id"); // Symbol

8. BigInt: For very large integers (larger than Number can handle).
let bigNumber = BigInt(123456789123456789); // BigInt

////////////////
Common Non-Primitive Types in JavaScript:

[Link] :- Used to store collections of data in key-value pairs.


let person = {
name: "John",
age: 25
}; // Object

[Link]: Used to store a collection of elements (of any type).


let numbers = [1, 2, 3, 4]; // Array

3. Function: A block of code designed to perform a particular task.


function greet() {
[Link]("Hello");
} // Function

what is opps?

question :- what is opps?

answer :-OOPs (Object-Oriented Programming) is a programming paradigm based on the


concept of "objects."

..here concept of oops are as follow !


1. class:- A class is a blueprint or template for creating objects. It defines the properties
(attributes) and behaviors (methods)

For example
class Car {
constructor(brand, color) {
[Link] = brand;\
[Link] = color;
}

drive() {
[Link](`${[Link]} is driving.`);
}
}

[Link]:
An object is an instance of a class. When you create an object, you're creating a specific
version of the class with its own data.

For example, if the Car class is a blueprint, the object could be a specific car like a "red
Toyota."

const myCar = new Car("Toyota", "red");


[Link](); // Output : toyto is driving

3 . Encapsulation:
Encapsulation refers to bundling the data (attributes) and methods (functions) that operate on
the data into a single unit, the object.

class Car {
constructor(brand) {
this._brand = brand; // private property (by convention, using an underscore)
}

getBrand() {
return this._brand; // public method
}
}
const myCar = new Car("Toyota");
[Link]([Link]()); // Toyota

4. Inheritance:
Inheritance allows one class (child or subclass) to inherit the properties and methods of another
class (parent or superclass).

class Vehicle {
constructor(brand) {
[Link] = brand;
}

drive() {
[Link](`${[Link]} is driving.`);
}
}

class Car extends Vehicle {


constructor(brand, color) {
super(brand);
[Link] = color;
}
}

const myCar = new Car("Toyota", "red");


[Link](); // Output: Toyota is driving.

[Link]:
0r... In other words, polymorphism allows one method to be implemented in multiple ways
based on the object that is calling it.

class Animal {
makeSound() {
[Link]("Animal makes a sound");
}
}

class Dog extends Animal {


makeSound() {
[Link]("Dog barks");
}

class Cat extends Animal {


makeSound() {
[Link]("Cat meows");
}
}
const myDog = new Dog();
const myCat = new Cat();

[Link](); // Dog barks


[Link](); // Cat meows

6. Abstraction refers to the concept of hiding the complex implementation details of a system
and showing only the essential features to the user. It allows developers to focus on what an
object does rather than how it does it.

-------------------------------------

Answer: OOPs (Object-Oriented Programming) ek programming paradigm hai jo "objects" ke


concept par adharit hai. Ismein kuch key concepts shamil hain, jo aapko code ko behtar tarike
se organize aur manage karne mein madad karte hain.

Concepts of OOPs:

1. Class:

Definition: Class ek blueprint ya template hoti hai jisse objects banaye jate hain. Yeh properties
(attributes) aur behaviors (methods) ko define karti hai.

Example:

class Car {
constructor(brand, color) {
[Link] = brand;
[Link] = color;
}

drive() {
[Link](`${[Link]} is driving.`);
}
}

2. Object:

Definition: Object ek class ka instance hota hai. Jab aap ek object create karte hain, aap class
ka ek specific version banate hain apne data ke saath.
Example: Agar Car class ek blueprint hai, toh object kisi specific car ka representation ho sakta
hai, jaise "red Toyota".

const myCar = new Car("Toyota", "red");


[Link](); // Output: Toyota is driving.

3. Encapsulation:

Definition: Encapsulation ka matlab hai data (attributes) aur methods (functions) ko ek single
unit (object) mein bundling karna. Yeh data ko private (chhupa hua) aur public (prakat) methods
ke saath secure karta hai.

Example:

class Car {
constructor(brand) {
this._brand = brand; // private property (underscore convention se)
}

getBrand() {
return this._brand; // public method
}
}
const myCar = new Car("Toyota");
[Link]([Link]()); // Output: Toyota

4. Inheritance:

Definition: Inheritance ek class (child ya subclass) ko doosri class (parent ya superclass) ke


properties aur methods inherit karne ki suvidha deta hai. Iska matlab hai ki child class parent
class ki functionalities ko reuse kar sakti hai.

Example:

class Vehicle {
constructor(brand) {
[Link] = brand;
}

drive() {
[Link](`${[Link]} is driving.`);
}
}
class Car extends Vehicle {
constructor(brand, color) {
super(brand); // parent class ka constructor call
[Link] = color;
}
}

const myCar = new Car("Toyota", "red");


[Link](); // Output: Toyota is driving.

5. Polymorphism:

Definition: Polymorphism ka matlab hai ek method ko alag-alag objects par alag tarike se
implement karna. Yeh ek method ko alag-alag objects ke liye alag behavior dene ki suvidha
deta hai.

Example:

class Animal {
makeSound() {
[Link]("Animal makes a sound");
}
}

class Dog extends Animal {


makeSound() {
[Link]("Dog barks");
}
}

class Cat extends Animal {


makeSound() {
[Link]("Cat meows");
}
}

const myDog = new Dog();


const myCat = new Cat();

[Link](); // Output: Dog barks


[Link](); // Output: Cat meows
6. Abstraction:

Definition: Abstraction ka matlab hai kisi system ki complex implementation details ko chhupana
aur sirf essential features ko user ke samne rakhna. Isse developers ko object ke functionality
par focus karne ka mauka milta hai, na ki uski implementation par.

Example: Abstraction ko use karte waqt, aap ek interface ya abstract class define karte hain
jisse concrete classes ko implement karna hota hai, lekin end user ko sirf important methods
dikhte hain.
// This function abstracts the complexity of fetching and parsing data.
function fetchDataAndProcess(url) {
[Link](`Fetching data from: ${url}`); // Abstracted detail
// In a real app, this would involve fetch(), [Link](), error
handling etc.
const rawData = `{"name": "ItemX", "value": 100}`; // Simulate data
fetch
const parsedData = [Link](rawData); // Simulate parsing
[Link]("Data processed:", parsedData);
return parsedData;
}

// Usage: The user only needs to know 'what' it does, not 'how'.
const myData = fetchDataAndProcess("[Link]
// Further operations with myData...

Conclusion:

OOPs ke ye concepts programming ko modular, reusable, aur maintainable banate hain. Isse
aap complex systems ko behtar tarike se model kar sakte hain, jisse development process aur
code quality mein sudhar hota hai. Is paradigm ka istemal karke, aap code ko logical parts mein
divide kar sakte hain, jo ki debugging aur enhancement ko aasaan banata hai.

Common questions

Powered by AI

JavaScript array methods push(), pop(), shift(), and unshift() are essential for manipulating arrays efficiently. The push() method adds one or more elements to the end of an array and returns the new length, allowing for dynamic expansion of arrays . Conversely, pop() removes the last element, which is useful for dynamically reducing arrays . The shift() method removes the first element and returns it, which helps in cases where the initial data point needs to be removed . Unshift() adds elements to the beginning of an array, adjusting all existing indices and offering flexibility in how array data is structured . These methods modify the original array, making them powerful tools for dynamic data management.

In JavaScript, callback functions are critical in event handling by allowing code execution upon specific events, such as clicks or key presses, without blocking the main execution thread . Callbacks execute a function upon completion of another operation, providing flexibility and modularity . However, they may lead to complex and less readable code known as callback hell when handling multiple asynchronous actions. In comparison, Promises and async/await provide more structured approaches to asynchronous programming. Promises utilize .then() and .catch() chains, while async/await allows writing code that looks synchronous, vastly improving readability and error handling . While callbacks are vital for simple asynchronous tasks, Promises and async/await offer enhanced control and clarity for complex operations.

The async/await syntax in JavaScript offers a more straightforward way to handle promises by making asynchronous code appear synchronous, improving readability significantly . With async/await, error handling becomes clearer, as errors can be caught using a try-catch block, similar to synchronous code . This contrasts with Promises, where .then() and .catch() methods are used, often resulting in chain-like structures, which can become less readable in complex scenarios . Thus, while both handle asynchronous operations, async/await provides a syntax that makes code easier to write and debug, aligning more closely with traditional synchronous error handling practices.

Flattening arrays with the flat() method simplifies handling nested arrays by reducing their depth. This process is beneficial in data manipulation where hierarchical data structures need to be converted into a more linear form for ease of access and processing . For instance, let nestedArray = [1, [2, [3, [4]]]] when flattened using flat(2), it becomes [1, 2, 3, [4]], effectively reducing its depth by two levels . Such transformations facilitate operations like aggregations or transformations within datasets, streamlining processes that rely on simpler array structures.

The JavaScript Math object provides several functions for performing mathematical tasks. Key methods include Math.abs(), which returns the absolute value of a number; Math.ceil(), which rounds a number up to the nearest integer; Math.floor(), which rounds a number down; and Math.round(), which rounds to the nearest integer . Math.max() and Math.min() return the largest and smallest of a set of numbers, respectively . Other methods like Math.random() generate a random number between 0 and 1, Math.pow() computes powers of numbers, while Math.sqrt() and Math.trunc() return the square root and integer part of a number, respectively . These methods streamline complex mathematical computations in JavaScript code.

Method chaining is a programming pattern where multiple methods are called on the same object consecutively. In JavaScript, array methods like sort() and reverse() can be chained to manipulate array data efficiently. For example, if you have an array and wish to sort it in ascending order and then reverse it for descending order, you can execute sortedArray = array.sort().reverse(). This combines sorting and reversing in one line, enhancing readability and sophistication of the code without needing intermediate variables . This pattern reduces code verbosity and organizes operations logically, maximizing efficiency while maintaining clarity.

In JavaScript, hoisting is the process whereby function and variable declarations are moved to the top of their respective scopes before execution. This means functions can be called before they are defined in the code because their declarations are hoisted . For example, a function like sayHello() can be invoked before its declaration line but will execute correctly due to hoisting . However, while function declarations are fully hoisted, variable declarations are only partially hoisted. Variables declared with var are initialized as undefined until they are assigned a value later in the code, which can lead to unexpected behaviors if not fully understood . This understanding is crucial when managing scope and ensuring predictable code execution flows.

The Math.random() function in JavaScript is used to generate a pseudo-random floating-point number between 0 (inclusive) and 1 (exclusive). It is commonly used in scenarios requiring randomness, such as creating random IDs, simulating user actions, or providing random choices in games. The function's output can be scaled to any range by multiplying the result and using Math.floor() or Math.ceil() for integer ranges . However, the randomness is pseudo, based on algorithms rather than true randomness, meaning it's suitable for applications where exact randomness isn't crucial.

Promises in JavaScript enhance code readability by providing a structured method for handling asynchronous operations. Unlike callback functions, which can lead to callback hell with nested and difficult-to-read structures, promises allow for chaining asynchronous actions in a more linear fashion . This prevents nested code and improves error handling through a clear '.catch()' method for handling rejections . Promises operate in three states: pending, fulfilled, and rejected, which enable developers to manage operations that may not complete immediately, such as API requests or reading files . These features make promises a robust solution for making asynchronous programming clean and manageable.

The map(), filter(), and reduce() methods serve distinct purposes in JavaScript. The map() method transforms each array element using a provided function, returning a new array with these transformed values . The filter() method extracts elements that meet a specific condition, creating a new array of filtered elements . In contrast, reduce() executes a function on each array element, effectively reducing the array to a single value which can be useful in tasks such as summing numbers or concatenating strings . Each method is suited for specific tasks: map() for transformation, filter() for selection, and reduce() for accumulation, making them integral in functional programming paradigms.

You might also like