ECMAScript Features and JavaScript Basics
ECMAScript Features and JavaScript Basics
Key Updates:
// 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
}
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
Copy code
const promise1 = [Link](3);
const promise2 = [Link](4);
const promise3 = new Promise((resolve, reject) => setTimeout(resolve,
100, 'foo'));
[Link]():
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.
////////////////////////////////////////////////////////////////////////////////
JavaScript में Map एक बिल्ट-इन ऑब्जेक्ट है जो की-वैल्यू पेयर्स (key-value pairs) का एक कलेक्शन होता
है , ठीक वैसे ही जैसे एक ऑब्जेक्ट होता है । हालांकि, Map में कुछ महत्वपर्ण
ू अंतर और फायदे हैं जो इसे विशिष्ट
उपयोग के मामलों के लिए अधिक बेहतर बनाते हैं।
मख्
ु य विशेषताएँ:
1. कीज़ का प्रकार (Any Key Type): Map की सबसे बड़ी विशेषता यह है कि इसकी कीज़ किसी भी डेटा
ू यंस, फंक्शन्स, ऑब्जेक्ट्स (यहाँ तक कि null और
टाइप की हो सकती हैं – स्ट्रिं ग्स, नंबर्स, बलि
undefined भी) भी की के रूप में उपयोग किए जा सकते हैं। पारं परिक ऑब्जेक्ट में , कीज़ हमेशा
स्ट्रिं ग्स (या Symbols) होती हैं।
// A. Set के साथ has() का उदाहरण
const fruits = new Set(['apple', 'banana', 'orange']);
////////////////////////////////////////////////////////////
BigInt: A JavaScript data type that allows you to represent and manipulate integers larger than
2 power53− 1(9007199254740991) with arbitrary precision.
// जोड़ना
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>
<script>
// Accessing elements using different DOM methods
</script>
</body>
</html>
[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]);
}
// 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
}
step1(() => {
step2(() => {
step3(() => {
[Link]("All steps are finished!");
});
});
});
// 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()
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.
// 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
// 12. split(separator)
[Link]([Link](",")); // Output: [" Hello World", " Welcome to JavaScript! "]
// 13. startsWith(searchString)
[Link]([Link](" H")); // Output: true
// 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!"
-----------------------------------------------------------------------------------------------------------------
Definitions of Each Number Method
[Link](value): Checks if the value is a safe integer (within the range of -2^53 to
2^53).
[Link](base, exponent): Returns the base raised to the power of the exponent.
[Link](value): Returns the integer part of a number by removing the fractional digits.
// 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
// 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: 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)
---------------------------------
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
// 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
// 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
// 24. [Link](depth)
let nestedArray = [1, [2, 3], [4, [5]]];
let flatArray = [Link](1);
[Link](`24. [Link](1): ${flatArray}`); // Flattens the nested arr
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
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
//undrstand
// JSON data
const jsonString = '{"name": "John", "age": 30, "isStudent": false}';
/////////////////////////////////////////////////////////////
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.
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'];
// Index 1 se 1 element delete karo aur 'grape' aur 'kiwi' add karo
const removedFruits = [Link](1, 1, 'grape', 'kiwi');
-----------------------------------------------------------------------------------
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.
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.
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:
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.
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.
[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.
[Link]: The initial state, where the operation hasn’t completed yet.
----------------------------------------------------------
**** Using async/await******
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+++++
function UserData() {
const [users, setUsers] = useState([]);
const [message, setMessage] = useState('');
useEffect(() => {
// API URL
const apiUrl = "[Link]
return (
<div>
<h1>User Data</h1>
<p>{message}</p>
<ul>
{[Link]((user) => (
<li key={[Link]}>{[Link]}</li>
))}
</ul>
</div>
);
}
function UserData() {
const [users, setUsers] = useState([]);
const [error, setError] = useState(null);
useEffect(() => {
// API URL
const apiUrl = "[Link]
return (
<div>
<h1>User Data</h1>
{error && <p>{error}</p>}
<ul>
{[Link]((user) => (
<li key={[Link]}>{[Link]}</li>
))}
</ul>
</div>
);
}
================================
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.
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.
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 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
function UserData() {
const [users, setUsers] = useState([]);
const [message, setMessage] = useState('');
useEffect(() => {
// API URL
const apiUrl = "[Link]
return (
<div>
<h1>User Data</h1>
<p>{message}</p>
<ul>
{[Link]((user) => (
<li key={[Link]}>{[Link]}</li>
))}
</ul>
</div>
);
}
function UserData() {
const [users, setUsers] = useState([]);
const [error, setError] = useState(null);
useEffect(() => {
// API URL
const apiUrl = "[Link]
return (
<div>
<h1>User Data</h1>
{error && <p>{error}</p>}
<ul>
{[Link]((user) => (
<li key={[Link]}>{[Link]}</li>
))}
</ul>
</div>
);
}
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:
///
Example of Re-assign:-
///////////
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.
------------------------------------------------------
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:
Examples
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);
}
__________________________________
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.
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.
--------------------------------------
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:
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.
1. call() Method
The call() method invokes a function with a specific value for this, and any number of arguments
passed individually.
// '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.
// '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.
// '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]);
}
};
///////////////////////////
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
---------------------------------------
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:
// '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:
// '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:
// '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]);
}
};
---
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.
// which are then shared and accessible by all instances (examples) of that function or object.
// when to use
// "...या किसी क्लास में हमें ऑब्जेक्ट को क्रिएट करना हो तब हम प्रोटोटाइप का यज़
ू कर सकते हैं।"
// [Link] = name;
// }
// [Link] = function()
// };
// [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.
(function() {
// Your code here
[Link]("This function runs 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:
(function() {
// Aapka code yahan
})();
Yahan pe:
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.
return {
increment: function() {
count++;
[Link](count);
},
decrement: function() {
count--;
[Link](count);
}
};
})();
[Link](); // Output: 1
[Link](); // Output: 2
[Link](); // Output: 1
Conclusion:
//////////////////
undefined***
function foo() {
return; // If a function doesn't explicitly return a value, it returns `undefined`
}
[Link](foo()); // undefined
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]("\n--- 11. Copying Objects & Arrays: Shallow vs. Deep ---");
const originalDeepData = {
id: 10,
info: {
name: "Bob",
age: 25
},
items: ["book", "pen"]
};
let deepCopyData;
///////////////
class Car {
constructor(brand) {
[Link] = brand; // 'this' refers to the current instance of Car
}
getBrand() {
return [Link]; // Using 'this' to access the brand property
}
}
render() {
return <button onClick={[Link](this)}>Click me</button>;
}
}
///////////////
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
}
};
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
}
}
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:
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.
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:
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.
Benefits of Callbacks:
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?
/////
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!");
}
-------------------------------------------------------
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:
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.
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.
4 . Undefined: A variable that has been declared but not assigned a value.
let x; // Undefined
6. Symbol: A unique and immutable value used to create unique object property keys.
8. BigInt: For very large integers (larger than Number can handle).
let bigNumber = BigInt(123456789123456789); // BigInt
////////////////
Common Non-Primitive Types in JavaScript:
what is opps?
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."
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.`);
}
}
[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");
}
}
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.
-------------------------------------
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".
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:
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;
}
}
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");
}
}
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.
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.