├── .gitignore
├── LICENSE
├── Destructuring
├── README.md
├── Array.md
└── Object.md
├── This vs That
├── InnerHTML vs InnerText.md
├── Append vs AppendChild.md
├── QuerySelector vs GetElementById.md
└── QuerySelector vs QuerySelectorAll.md
├── Async Programming
├── Callback.md
├── Async Programming.md
├── README.md
├── AsyncAndAwait.md
└── Promise.Movie.md
├── DOM
├── DOM2.md
└── DOM1.md
├── MRF.md
├── OLD
├── MRF.md
├── CODEKATA JS.md
└── Promise.md
├── Spread and Rest Operator.md
├── Functions.md
├── OOPs in JS.2.md
├── console.md
├── CODEKATA_JS.md
├── README.MD
└── OOPs in JS.md
/.gitignore:
--------------------------------------------------------------------------------
1 | exclude
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | MIT License
2 |
3 | Copyright (c) 2024 Pugazharasan Chandrasekar
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in all
13 | copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 | SOFTWARE.
22 |
--------------------------------------------------------------------------------
/Destructuring/README.md:
--------------------------------------------------------------------------------
1 | # JavaScript Destructuring Symphony 🎵
2 |
3 | Welcome to the JavaScript Destructuring Symphony, where we explore the art of deconstructing arrays and objects with elegance and style. Navigate through the harmony of code and music, and enjoy the organized structure of your JavaScript compositions.
4 |
5 | ## Array Destructuring: A Tamil Symphony 🎶
6 |
7 | In the world of arrays, experience the beauty of extracting values with the finesse of a classic Tamil melody from the 2000s. Each section represents a note in our symphony:
8 |
9 | - [**Basic Syntax**](Array.md#basic-syntax): Unwrapping the melody with effortless extraction.
10 | - [**Swapping Notes**](Array.md#swapping-notes): Dancing between melodies with ease.
11 | - [**Skipping Elements**](Array.md#skipping-elements): Selecting the desired elements like choosing instruments in an ensemble.
12 | - [**Rest Operator**](Array.md#rest-operator-in-array-destructuring): Gathering the remaining elements like a buffet plate.
13 | - [**Default Notes**](Array.md#default-values): Providing fallback maestros when needed.
14 | - [**Nested Level Destructuring**](Array.md#nested-level-array-destructuring): Diving deeper into the musical array.
15 |
16 | Feel the symphony of array destructuring as it unfolds: [Array Destructuring in JavaScript](Array.md)
17 |
18 | ## Object Destructuring: Building a Furnished House 🏡
19 |
20 | Embark on a journey of furnishing your JavaScript code with the art of object destructuring, transforming plain objects into fully furnished spaces:
21 |
22 | - [**Basic Furnishing**](Object.md#basic-furnishing): Setting up rooms with essential items.
23 | - [**Customizing Furnishings**](Object.md#customizing-furnishings): Personalizing your JavaScript space with style.
24 | - [**Nested Rooms**](Object.md#nested-rooms-diving-deeper): Efficiently furnishing nested rooms.
25 | - [**Default Furnishings**](Object.md#default-furnishings): Ensuring default elements for each room.
26 | - [**Rest Operator in Furnishing**](Object.md#rest-operator-in-furnishing): Expanding the house efficiently.
27 | - [**Mixed Data Types**](Object.md#mixed-data-types): Gracefully handling mixed data types within your furnished space.
28 | - [**Dynamic Property Names**](Object.md#dynamic-property-names): Handling dynamic or computed property names with finesse.
29 |
30 | Conclude your journey in the art of object destructuring: [Object Destructuring in JavaScript](Object.md)
31 |
32 | Happy coding and may your JavaScript compositions be as harmonious as a symphony!
33 |
--------------------------------------------------------------------------------
/This vs That/InnerHTML vs InnerText.md:
--------------------------------------------------------------------------------
1 | # innerHTML vs innerText: A Duel of DOM Textual Manipulation ⚔️
2 |
3 | ## Introduction: Unveiling the Powers Within Elements
4 |
5 | Within the mystical Document Object Model (DOM), two siblings, `innerHTML` and `innerText`, possess unique powers in the manipulation of content within elements. In this showdown, let's illuminate the distinctions between these text-wielding sorcerers through a comprehensive table, guiding you in choosing the right incantation for your web enchantments.
6 |
7 | ## The Textual Duel: innerHTML vs innerText
8 |
9 | | Aspect | `innerHTML` | `innerText` |
10 | | ------------------------ | ------------------------------------------------------------------------------- | ------------------------------------------------------------------------------ |
11 | | **Content Manipulation** | Represents the HTML content within an element, including tags. | Represents only the visible text content within an element, excluding tags. |
12 | | **Rendering HTML Tags** | Parses and renders HTML tags as part of the content. | Treats HTML tags as plain text, rendering them as visible characters. |
13 | | **Cross-Site Scripting** | Prone to cross-site scripting (XSS) attacks if user input is directly injected. | Safer against XSS attacks, as it treats input as plain text. |
14 | | **Performance** | Can be less performant when dealing with large chunks of HTML. | Generally performs better, especially with large text content. |
15 | | **Usage** | Ideal for inserting or manipulating complex HTML structures. | Suitable for tasks where only the text content needs manipulation. |
16 | | **Accessibility** | May cause issues with screen readers due to unexpected tags. | Preferred for accessibility as it ensures only text is read by screen readers. |
17 |
18 | ## Practical Examples
19 |
20 | ### Using `innerHTML`:
21 |
22 | ```javascript
23 | // Manipulating content with innerHTML
24 | const container = document.getElementById('content-container');
25 | container.innerHTML = '
Transformed with innerHTML
';
26 | ```
27 |
28 | ### Using `innerText`:
29 |
30 | ```javascript
31 | // Manipulating content with innerText
32 | const paragraph = document.querySelector('.content-paragraph');
33 | paragraph.innerText = 'Only the text within, no tags included!';
34 | ```
35 |
36 | ## Conclusion: Choosing the Right Incantation
37 |
38 | In the mystical realm of the DOM, the choice between `innerHTML` and `innerText` depends on the nature of your task. `innerHTML` is the sorcerer skilled in crafting and manipulating rich HTML structures, while `innerText` is the purist, focusing solely on the text content within an element.
39 |
40 | May you, the master of text manipulation, choose your incantation wisely, weaving enchanting narratives and bringing life to the pixels within your web creations. The duel concludes, and the choice is yours to make. ✨📜
--------------------------------------------------------------------------------
/This vs That/Append vs AppendChild.md:
--------------------------------------------------------------------------------
1 | # Append vs AppendChild: A Table of Elemental Differences ⚖️
2 |
3 | ## Introduction: Unraveling the Symphony of DOM Harmony
4 |
5 | In the grand symphony of web development, two virtuosos, `append` and `appendChild`, step into the spotlight to orchestrate the harmonious arrangement of elements. As we delve into their nuances, we aim to craft a comprehensive table that unveils the differences and similarities between these maestros, shedding light on when to call upon each in the grand composition of web enchantment.
6 |
7 | ## The Elemental Duel: append vs appendChild
8 |
9 | | Aspect | `appendChild` | `append` |
10 | | ---------------------- | --------------------------------------------------------- | -------------------------------------------------------------------------------------- |
11 | | **Functionality** | Appends a single node as the last child of a parent node. | Appends one or more nodes and/or DOMString objects to the end of a parent node. |
12 | | **Multiple Arguments** | Only accepts one node as an argument. | Accepts multiple nodes and/or DOMString objects as arguments. |
13 | | **Chaining** | Does not support chaining. | Supports chaining multiple append operations. |
14 | | **Performance** | Generally considered slightly faster. | Slightly slower due to the flexibility of handling multiple arguments. |
15 | | **Ease of Use** | Simple and straightforward for appending a single node. | Versatile, especially when dealing with multiple elements, providing a concise syntax. |
16 | | **Compatibility** | Widely supported in modern browsers. | Supported in modern browsers, but check for compatibility with legacy systems. |
17 |
18 | ## Practical Examples
19 |
20 | ### Using `appendChild`:
21 |
22 | ```javascript
23 | const parentElement = document.getElementById('container');
24 | const childElement = document.createElement('div');
25 | childElement.textContent = 'Appended with appendChild!';
26 | parentElement.appendChild(childElement);
27 | ```
28 |
29 | ### Using `append`:
30 |
31 | ```javascript
32 | const parentElement = document.getElementById('container');
33 | const childElement1 = document.createElement('p');
34 | childElement1.textContent = 'First element appended with append!';
35 |
36 | const childElement2 = document.createElement('p');
37 | childElement2.textContent = 'Second element appended with append!';
38 |
39 | parentElement.append(childElement1, 'Direct text', childElement2);
40 | ```
41 |
42 | ## Conclusion: A Symphony of Choices
43 |
44 | In the grand orchestra of web development, choosing between `append` and `appendChild` depends on the complexity of your composition. `appendChild` is the soloist, perfect for appending a single element, while `append` leads the ensemble, seamlessly incorporating multiple elements and strings into the symphony.
45 |
46 | May you, the conductor of the DOM, wield these methods with finesse, creating harmonies that resonate across browsers and enchant users in the digital realm. The choice is yours – the symphony awaits. 🎵✨
--------------------------------------------------------------------------------
/Async Programming/Callback.md:
--------------------------------------------------------------------------------
1 |
2 | # Callbacks in JavaScript: A "Vikram Vedha" Tale 🎬
3 |
4 | ## Introduction to Callbacks
5 |
6 | In the dynamic world of JavaScript programming, callbacks play a pivotal role, akin to the intricate plot twists in the Tamil movie "Vikram Vedha" (2017). As we embark on this journey, let's delve deeper into the significance of callbacks and explore real-world scenarios where they become indispensable.
7 |
8 | ## Why Callbacks Are Needed
9 |
10 | Callbacks function as the directors of our code, orchestrating sequences of tasks much like directors Pushkar and Gayathri shaped the gripping narrative in "Vikram Vedha." They are vital for handling asynchronous operations, events, and ensuring that specific tasks are executed only after the completion of others.
11 |
12 | ### Real-world Scenarios: Callbacks in Action
13 |
14 | Consider scenarios where callbacks shine:
15 |
16 | - **Handling HTTP Requests:**
17 | Callbacks are commonly used to manage asynchronous tasks, such as fetching data from an API. The callback ensures that subsequent actions are executed only when the data is successfully retrieved.
18 |
19 | - **User Interactions on a Web Page:**
20 | Callbacks come into play when responding to user interactions, like button clicks. They help manage the flow of actions, ensuring a seamless user experience.
21 |
22 | ## Callback Example: A Detective's Call
23 |
24 | ```javascript
25 | function solveCase(suspect, callback) {
26 | // Detective work happening here
27 |
28 | // Once the case is solved, make the callback
29 | callback(`Case Solved: ${suspect}`);
30 | }
31 |
32 | function celebrateSuccess(result) {
33 | console.log(result);
34 | console.log("Celebrating success!");
35 | }
36 |
37 | // Calling the solveCase function with a callback
38 | solveCase("Vedha", celebrateSuccess);
39 | ```
40 |
41 | **Output:**
42 | ```
43 | Case Solved: Vedha
44 | Celebrating success!
45 | ```
46 |
47 | **Explanation:**
48 | In this example, the `solveCase` function represents a detective solving a case. Once the case is solved, the callback function (`celebrateSuccess`) is invoked to celebrate the success.
49 |
50 | ## Limitations of Callbacks: A Crime Thriller Twist
51 |
52 | Callbacks, while indispensable, can lead to a phenomenon known as the "Callback Hell" or "Pyrrhic Callback," reminiscent of the suspenseful and complex plot twists in "Vikram Vedha." When multiple callbacks are nested within each other, the code structure becomes convoluted and challenging to maintain.
53 |
54 | ### Callback Hell Example: Unraveling the Plot
55 |
56 | ```javascript
57 | detective.solveCase("Vikram", function (result) {
58 | console.log(result);
59 |
60 | crimeBoss.getPunishment("Vedha", function (punishment) {
61 | console.log(punishment);
62 |
63 | detective.reportToSuperior("Vikram", function (report) {
64 | console.log(report);
65 |
66 | // More callbacks nested here...
67 |
68 | });
69 | });
70 | });
71 | ```
72 |
73 | **Explanation:**
74 | In this callback hell scenario, callbacks are nested within each other, leading to a pyramid of indentation and making the code difficult to follow—much like the intricate plot twists in "Vikram Vedha."
75 |
76 | ## The Road Ahead: Teasing Promises and Async/Await
77 |
78 | Understanding callbacks and their challenges is crucial, but fear not! In the subsequent sections, we'll explore solutions to escape the callback hell. Get ready for a code narrative inspired by the suspenseful storytelling of "Vikram Vedha"! 🕵️♂️🎥
79 |
--------------------------------------------------------------------------------
/This vs That/QuerySelector vs GetElementById.md:
--------------------------------------------------------------------------------
1 | # QuerySelector vs getElementById: A Table of DOM Discovery ⚖️
2 |
3 | ## Introduction: Unveiling the Maestros of Element Retrieval
4 |
5 | In the magical realm of the Document Object Model (DOM), two stalwart sorcerers, `querySelector` and `getElementById`, stand ready to unveil the secrets of element retrieval. As we explore their differences and strengths, we will craft a table to guide you in choosing the right sorcerer for your quest in the enchanted land of web development.
6 |
7 | ## The Elemental Duel: querySelector vs getElementById
8 |
9 | | Aspect | `querySelector` | `getElementById` |
10 | | ------------------------- | ----------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------- |
11 | | **Selector Syntax** | Accepts any valid CSS selector. | Requires the exact ID of the element. |
12 | | **Scope** | Searches the entire document for the first matching element. | Scopes the search to the element with the specified ID. |
13 | | **Flexibility** | Offers versatility with complex selectors, allowing for class, attribute, and pseudo-class selectors. | Limited to selecting elements by their unique ID. |
14 | | **Performance** | Generally slightly slower due to the flexibility of handling complex selectors. | Faster, as it targets a specific ID directly. |
15 | | **Return Value** | Returns the first matching element or `null` if none is found. | Returns the element with the specified ID or `null` if not found. |
16 | | **Usage** | Ideal for general-purpose selections and complex queries. | Perfect for quick and direct retrieval of an element by its ID. |
17 | | **Browser Compatibility** | Widely supported in modern browsers. | Supported in all modern browsers; a reliable choice for legacy systems. |
18 |
19 | ## Practical Examples
20 |
21 | ### Using `querySelector`:
22 |
23 | ```javascript
24 | const anyElement = document.querySelector('.example-class'); // Retrieves the first element with class 'example-class'
25 | const complexElement = document.querySelector('div#container > p:first-child'); // Retrieves the first paragraph within a container div
26 | ```
27 |
28 | ### Using `getElementById`:
29 |
30 | ```javascript
31 | const specificElement = document.getElementById('unique-id'); // Retrieves the element with the ID 'unique-id'
32 | ```
33 |
34 | ## Conclusion: Choosing Your Sorcerer
35 |
36 | In the vast expanse of the DOM, the choice between `querySelector` and `getElementById` depends on the nature of your quest. If you seek the flexibility to wield intricate selectors and traverse the entire document, `querySelector` is your versatile companion. Alternatively, for a focused and expedited quest to find an element by its unique ID, the loyal `getElementById` is your steadfast guide.
37 |
38 | May your journey through the enchanted DOM be guided by the wisdom of these sorcerers, ensuring that you wield the right magic for every web incantation. 🧙♂️✨
--------------------------------------------------------------------------------
/Destructuring/Array.md:
--------------------------------------------------------------------------------
1 | # Array Destructuring in JavaScript: A Tamil Symphony 🎵
2 |
3 | ## Introduction
4 |
5 | Array Destructuring in JavaScript is like orchestrating a Tamil melody from the 2000s, where each musical note represents a variable, and together they create a harmonious symphony of coding elegance.
6 |
7 | ### Basic Syntax
8 |
9 | ```javascript
10 | const tamilMusicalNotes = ["Sa", "Re", "Ga", "Ma", "Pa", "Dha", "Ni", "Sa"];
11 |
12 | const [firstNote, secondNote, thirdNote] = tamilMusicalNotes;
13 |
14 | console.log(firstNote); // Output: Sa
15 | console.log(secondNote); // Output: Re
16 | console.log(thirdNote); // Output: Ga
17 | ```
18 |
19 | **Explanation:**
20 |
21 | - **Unveiling the Melody:** Just like the musical notes in a classic Tamil melody, Array Destructuring beautifully assigns each note to a variable, creating a harmonious flow.
22 |
23 |
24 | ### Swapping Notes
25 |
26 | ```javascript
27 | let melody1 = "Deva's Melody";
28 | let melody2 = "Vijay Antony's Rhythm";
29 |
30 | [melody1, melody2] = [melody2, melody1];
31 |
32 | console.log(melody1); // Output: Vijay Antony's Rhythm
33 | console.log(melody2); // Output: Deva's Melody
34 | ```
35 |
36 | **Explanation:**
37 |
38 | - **Swapping Melodies:** Array Destructuring allows you to swap musical melodies effortlessly, creating a delightful dance of Tamil musical transformation.
39 |
40 |
41 | ### Skipping Elements
42 |
43 | ```javascript
44 | const tamilInstruments = ["Veena", "Flute", "Tabla", "Ghatam"];
45 |
46 | const [favoriteInstrument, , , leastFavoriteInstrument] = tamilInstruments;
47 |
48 | console.log(favoriteInstrument); // Output: Veena
49 | console.log(leastFavoriteInstrument); // Output: Ghatam
50 | ```
51 |
52 | **Explanation:**
53 |
54 | - **Skipping Instruments:** Similar to choosing favorite instruments in a Tamil ensemble, Array Destructuring lets you select the elements you desire.
55 |
56 | ### Rest Operator in Array Destructuring
57 |
58 | ```javascript
59 | const musicDirectors = ["Deva", "Vijay Antony", "AR Rahman", "Harris Jayaraj"];
60 |
61 | const [firstDirector, secondDirector, ...restOfDirectors] = musicDirectors;
62 |
63 | console.log(firstDirector); // Output: Deva
64 | console.log(secondDirector); // Output: Vijay Antony
65 | console.log(restOfDirectors); // Output: [AR Rahman, Harris Jayaraj]
66 | ```
67 |
68 | **Explanation:**
69 |
70 | - **A Melodic Ensemble:** The `...` (Rest) operator gathers the remaining directors into a new array, akin to the collaboration of iconic music directors in the Tamil music scene.
71 |
72 | ### Default Notes
73 |
74 | ```javascript
75 | const playbackSingers = ["Hariharan", "Shreya Ghoshal"];
76 |
77 | const [firstSinger, secondSinger, thirdSinger = "SPB"] = playbackSingers;
78 |
79 | console.log(firstSinger); // Output: Hariharan
80 | console.log(secondSinger); // Output: Shreya Ghoshal
81 | console.log(thirdSinger); // Output: SPB
82 | ```
83 |
84 | **Explanation:**
85 |
86 | - **Default Maestro:** Array Destructuring allows you to set a default maestro, ensuring a graceful fallback if the array lacks sufficient elements.
87 |
88 | ### Nested Level Array Destructuring
89 |
90 | ```javascript
91 | const tamilSongs = [
92 | ["Roja", "Vellai Roja"],
93 | ["Kadhalan", "Mukkabla"],
94 | ["Minsara Kanavu", "Vennilave"],
95 | ];
96 |
97 | const [
98 | [firstMovie, firstSong],
99 | [secondMovie, secondSong],
100 | [thirdMovie, thirdSong],
101 | ] = tamilSongs;
102 |
103 | console.log(`In ${firstMovie}, enjoy the song "${firstSong}"`);
104 | console.log(`In ${secondMovie}, groove to the beats of "${secondSong}"`);
105 | console.log(`In ${thirdMovie}, get lost in the melody of "${thirdSong}"`);
106 | ```
107 |
108 | **Explanation:**
109 |
110 | - **Melodic Harmony:** Nested level array destructuring allows you to dive deeper into the musical array, extracting not just movies but also their iconic songs. Each nested level corresponds to a layer of melodic harmony, revealing the beauty of Tamil music composition.
111 |
112 | Now, your array destructuring symphony embraces the depth of nested structures, creating a richer and more nuanced melody in the world of Tamil music.
113 |
114 | # Conclusion
115 |
116 | In the world of JavaScript, Array Destructuring unfolds as a symphony of elegant melodies inspired by Tamil music. Each line of code dances to the rhythm, creating a harmonious ensemble. From unveiling notes to swapping melodies and diving into nested structures, your code now echoes the beauty of Tamil music composition. As you journey through code, may your arrays and melodies resonate with this timeless harmony. 🎶✨
--------------------------------------------------------------------------------
/Async Programming/Async Programming.md:
--------------------------------------------------------------------------------
1 | # Asynchronous Programming in JavaScript: An Epic Code Journey 🌐
2 |
3 | ## Sync Vs Async: Unraveling the Plot
4 |
5 | ### Sync
6 | JavaScript, known for its traditional single-threaded, synchronous nature, resembles the linear progression of classic movie plots (*🎥 Example: "Kaithi" (2019)*). In synchronous programming, code executes sequentially, one statement at a time, crafting a narrative akin to a timeless cinematic experience. The story follows a single timeline, where scenes unfold one after the other in a harmonious sequence.
7 |
8 | **Synchronous Example:**
9 | ```javascript
10 | console.log("Start");
11 | console.log("Middle");
12 | console.log("End");
13 | ```
14 |
15 | **Output:**
16 | ```
17 | Start
18 | Middle
19 | End
20 | ```
21 |
22 | ### Async
23 | JavaScript, in its evolution, has embraced the paradigm of asynchronous programming, breaking away from the linear constraints of traditional synchronous execution. In asynchronous programming, the script doesn't wait for each statement to complete before moving on to the next one. Instead, it initiates tasks and continues with the execution, allowing other operations to run concurrently.
24 |
25 | Imagine the narrative of a modern interactive film (*🎥 Example: "Super Deluxe" (2019)*), where multiple storylines unfold simultaneously, each progressing independently. Similarly, in asynchronous programming, different tasks can be initiated, and the script doesn't stall while waiting for each one to finish. Callbacks or Promises are employed to handle the results of these asynchronous operations once they are completed, contributing to a more dynamic and responsive application.
26 |
27 | This asynchronous approach is particularly beneficial for handling time-consuming operations, such as fetching data from a server or processing large sets of information, without blocking the main thread of execution. It allows JavaScript applications to maintain a level of responsiveness, akin to a cinematic experience where various plotlines unfold concurrently, contributing to a more engaging and efficient code execution.
28 |
29 | **Asynchronous Example:**
30 | ```javascript
31 | console.log("Start");
32 |
33 | setTimeout(() => {
34 | console.log("Inside Timeout");
35 | }, 2000);
36 |
37 | console.log("End");
38 | ```
39 |
40 | **Output:**
41 | ```
42 | Start
43 | End
44 | Inside Timeout
45 | ```
46 |
47 | In the asynchronous example, the code inside `setTimeout` plays a supporting role without blocking the execution of subsequent statements. This flexibility allows the "End" to be logged before the timeout completes, introducing an unexpected twist to the storyline.
48 |
49 | ## How JS Handles Async Processes: Behind the Scenes
50 |
51 | JavaScript orchestrates its asynchronous saga using the Call Stack, Web API, Callback Queue, and Event Loop, akin to the backstage coordination in movie production.
52 |
53 | ### Call Stack: The Script Unfolds
54 |
55 | The Call Stack takes center stage, a data structure tracking function calls in the code. When a function is called, it gracefully enters the stack, and upon completion, exits the stage.
56 |
57 | ### Web API: Supporting Actors
58 |
59 | Web APIs, the supporting actors from the browser environment (DOM, AJAX, Timeout functions), take on asynchronous tasks, allowing the main script to continue its performance.
60 |
61 | ### Callback Queue: Waiting in the Wings
62 |
63 | Once a Web API completes an asynchronous task, it places the corresponding callback function in the Callback Queue, patiently waiting for its cue.
64 |
65 | ### Event Loop: The Director's Vision
66 |
67 | The Event Loop, resembling a vigilant director, constantly scans the Call Stack and Callback Queue. If the Call Stack is vacant, it takes the first callback from the Queue and seamlessly transitions it to the spotlight.
68 |
69 | ## Visual Representation of Asynchronous Execution
70 |
71 | ```mermaid
72 | graph LR
73 | subgraph JS Code
74 | JSCode("JavaScript Code")
75 | end
76 |
77 | subgraph Call Stack
78 | CallStack("Call Stack")
79 | end
80 |
81 | subgraph Web API
82 | WebAPI("Web API")
83 | end
84 |
85 | subgraph Callback Queue
86 | CallbackQueue("Callback Queue")
87 | end
88 |
89 | subgraph Event Loop
90 | EventLoop("Event Loop")
91 | end
92 |
93 | JSCode --> CallStack
94 | CallStack --> WebAPI
95 | WebAPI --> CallbackQueue
96 | CallbackQueue --> EventLoop
97 | EventLoop --> CallStack
98 | ```
99 |
100 | This visual narrative illustrates the flow of asynchronous execution in JavaScript—a well-choreographed dance, from function calls to the Event Loop gracefully handling callbacks.
101 |
102 | Understanding these concepts is akin to navigating the plot twists of a Tamil movie. As we venture forward, we'll delve into specific asynchronous patterns, starting with callbacks, addressing common challenges, much like overcoming hurdles in a thrilling movie plot.
103 |
104 | Get ready for an epic coding saga, unfolding just like your favorite Tamil movies! 🍿🎬🚀
--------------------------------------------------------------------------------
/Destructuring/Object.md:
--------------------------------------------------------------------------------
1 |
2 | # Object Destructuring in JavaScript: Building a Furnished House 🏡
3 |
4 | ## Introduction
5 |
6 | Object Destructuring in JavaScript is akin to the art of furnishing a house. It allows you to efficiently extract and assign values from objects, transforming a plain object into a fully furnished space. Let's explore the basics and then move on to more sophisticated furnishing techniques.
7 |
8 | ### Basic Furnishing
9 |
10 | ```javascript
11 | const livingRoom = {
12 | sofa: "Comfy Couch",
13 | tv: "Smart TV",
14 | coffeeTable: "Wooden Table",
15 | };
16 |
17 | const { sofa, tv, coffeeTable } = livingRoom;
18 |
19 | console.log(sofa); // Output: Comfy Couch
20 | console.log(tv); // Output: Smart TV
21 | console.log(coffeeTable); // Output: Wooden Table
22 | ```
23 |
24 | **Explanation:**
25 |
26 | - **Setting Up the Living Room:** Object Destructuring allows you to furnish your living room with essential items, making it a cozy and functional space.
27 |
28 | ### Customizing Furnishings
29 |
30 | ```javascript
31 | const bedroom = {
32 | bed: "Queen Size Bed",
33 | wardrobe: "Spacious Wardrobe",
34 | dresser: "Elegant Dresser",
35 | };
36 |
37 | const { bed: myBed, wardrobe: myWardrobe, dresser: myDresser } = bedroom;
38 |
39 | console.log(myBed); // Output: Queen Size Bed
40 | console.log(myWardrobe); // Output: Spacious Wardrobe
41 | console.log(myDresser); // Output: Elegant Dresser
42 | ```
43 |
44 | **Explanation:**
45 |
46 | - **Personalizing the Bedroom:** Object Destructuring allows you to customize the names of the furnishings in your bedroom, creating a personalized and stylish space.
47 |
48 | ### Nested Rooms: Diving Deeper
49 |
50 | ```javascript
51 | const house = {
52 | livingRoom: {
53 | sofa: "Comfy Couch",
54 | tv: "Smart TV",
55 | coffeeTable: "Wooden Table",
56 | },
57 | bedroom: {
58 | bed: "Queen Size Bed",
59 | wardrobe: "Spacious Wardrobe",
60 | dresser: "Elegant Dresser",
61 | },
62 | };
63 |
64 | const { livingRoom: { sofa, tv, coffeeTable }, bedroom: { bed, wardrobe, dresser } } = house;
65 |
66 | console.log(sofa); // Output: Comfy Couch
67 | console.log(tv); // Output: Smart TV
68 | console.log(coffeeTable); // Output: Wooden Table
69 | console.log(bed); // Output: Queen Size Bed
70 | console.log(wardrobe); // Output: Spacious Wardrobe
71 | console.log(dresser); // Output: Elegant Dresser
72 | ```
73 |
74 | **Explanation:**
75 |
76 | - **Exploring Nested Rooms:** Object Destructuring allows you to efficiently furnish each room in your house, even if they are nested within each other.
77 |
78 | ### Default Furnishings
79 |
80 | ```javascript
81 | const kitchen = {
82 | stove: "Gas Stove",
83 | fridge: "Double Door Fridge",
84 | };
85 |
86 | const { stove, fridge, sink = "Stainless Steel Sink" } = kitchen;
87 |
88 | console.log(stove); // Output: Gas Stove
89 | console.log(fridge); // Output: Double Door Fridge
90 | console.log(sink); // Output: Stainless Steel Sink
91 | ```
92 |
93 | **Explanation:**
94 |
95 | - **Ensuring Default Elements:** Object Destructuring allows you to ensure that each room has default elements, even if they are not explicitly defined.
96 |
97 | ### Rest Operator in Furnishing
98 |
99 | ```javascript
100 | const entireHouse = {
101 | livingRoom,
102 | bedroom,
103 | kitchen,
104 | garden: {
105 | plants: "Assorted Plants",
106 | bench: "Wooden Bench",
107 | },
108 | };
109 |
110 | const { livingRoom, ...restOfHouse } = entireHouse;
111 |
112 | console.log(livingRoom); // Output: { sofa: "Comfy Couch", tv: "Smart TV", coffeeTable: "Wooden Table" }
113 | console.log(restOfHouse); // Output: { bedroom, kitchen, garden: { plants: "Assorted Plants", bench: "Wooden Bench" } }
114 | ```
115 |
116 | **Explanation:**
117 |
118 | - **Expanding the House:** The `...` (Rest) operator in Object Destructuring allows you to efficiently furnish one room while leaving the rest of the house intact.
119 |
120 | ## Mixed Data Types
121 |
122 | ```javascript
123 | const mixedRoom = {
124 | chair: "Comfortable Chair",
125 | desk: 42,
126 | computer: { brand: "Apple", model: "MacBook Pro" },
127 | };
128 |
129 | const { chair, desk, computer: { brand, model } } = mixedRoom;
130 |
131 | console.log(chair); // Comfortable Chair
132 | console.log(desk); // 42
133 | console.log(brand); // Apple
134 | console.log(model); // MacBook Pro
135 | ```
136 |
137 | **Explanation:** Object Destructuring gracefully handles mixed data types within your furnished space.
138 |
139 | ## Dynamic Property Names
140 |
141 | ```javascript
142 | const dynamicRoom = {
143 | furnitureType: "Chair",
144 | chairDetails: "Comfortable Chair",
145 | };
146 |
147 | const { [`${dynamicRoom.furnitureType}Details`]: chairDetails } = dynamicRoom;
148 |
149 | console.log(chairDetails); // Comfortable Chair
150 | ```
151 |
152 | **Explanation:** Handle dynamic or computed property names with Object Destructuring.
153 |
154 | ## Conclusion
155 |
156 | Object Destructuring transforms the process of furnishing a house into a seamless and elegant experience. Whether you're setting up your living room, customizing your bedroom, or exploring nested rooms, the art of object destructuring lets you furnish your JavaScript code with style and efficiency. Happy furnishing! 🛋️
--------------------------------------------------------------------------------
/This vs That/QuerySelector vs QuerySelectorAll.md:
--------------------------------------------------------------------------------
1 | # QuerySelector vs QuerySelectorAll: Navigating the Web Ensemble 🎭
2 |
3 | ## Introduction: Unveiling the Dynamics of Querying in DOM
4 |
5 | In the enchanting world of the Document Object Model (DOM), two powerful selectors, `querySelector` and `querySelectorAll`, take center stage to unravel the complexities of element retrieval. Let us embark on a journey to construct a table that illuminates the divergent and convergent aspects of these selectors, providing insight into when to summon each in the intricate dance of web sorcery.
6 |
7 | ## The Querying Duet: querySelector vs querySelectorAll
8 |
9 | | Aspect | `querySelector` | `querySelectorAll` |
10 | | --------------------- | ---------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------- |
11 | | **Selection** | Fetches the first element that matches the specified selector. | Retrieves a static NodeList of all elements that match the specified selector. |
12 | | **Returns** | Returns a single Element object. | Returns a NodeList (not an array) of Element objects. |
13 | | **Usage** | Ideal for selecting one element or the first matching element. | Suited for selecting multiple elements with the same selector. |
14 | | **Performance** | Generally faster, especially when used with a more specific selector. | May be slower due to collecting a NodeList, but optimizations have been made in modern browsers. |
15 | | **Flexibility** | Less flexible when selecting multiple elements with the same selector. | Offers versatility in selecting multiple elements, especially with the use of complex selectors. |
16 | | **Iterating** | Not required to iterate, as it returns a single Element. | Requires iteration over the NodeList to access each Element. |
17 | | **Practical Example** | ```javascript const element = document.querySelector('.class-selector'); ``` | ```javascript const elements = document.querySelectorAll('.class-selector'); elements.forEach(element => console.log(element)); ``` |
18 |
19 | ## When to Use Which: A Guided Journey
20 |
21 | ### Use `querySelector` When:
22 |
23 | - You need to select a single element or the first matching element that satisfies a specific selector.
24 | - The goal is to retrieve a quick reference to an individual element without the need for iteration.
25 | - Performance is a crucial consideration, especially when dealing with a more specific selector.
26 |
27 | **Detailed Explanation:**
28 |
29 | `querySelector` shines when simplicity and speed are paramount. If your intention is to grab the first occurrence of an element with a specific class or ID, this method is your go-to. Due to its efficiency, it's an excellent choice when dealing with selectors that uniquely identify an element.
30 |
31 | ### Use `querySelectorAll` When:
32 |
33 | - You aim to select and manipulate multiple elements that share a common selector.
34 | - The requirement is to obtain a NodeList containing all matching elements for further iteration and manipulation.
35 | - A more complex selector or a combination of selectors is necessary to precisely target elements.
36 |
37 | **Detailed Explanation:**
38 |
39 | `querySelectorAll` steps into the limelight when your mission involves orchestrating a group of elements. It returns a NodeList, allowing you to iterate through and manipulate each element individually. It's particularly valuable when dealing with a class that multiple elements share, as it effortlessly gathers them into a NodeList for collective management.
40 |
41 | ## Practical Examples
42 |
43 | ### Using `querySelector`:
44 |
45 | ```javascript
46 | const singleElement = document.querySelector('.class-selector');
47 | console.log(singleElement); // Outputs the first element with the class 'class-selector'
48 | ```
49 |
50 | ### Using `querySelectorAll`:
51 |
52 | ```javascript
53 | const multipleElements = document.querySelectorAll('.class-selector');
54 | multipleElements.forEach(element => console.log(element)); // Outputs all elements with the class 'class-selector'
55 | ```
56 |
57 | ## Conclusion: A Harmonious Interplay
58 |
59 | In the intricate ballet of DOM manipulation, the choice between `querySelector` and `querySelectorAll` hinges on the melody you wish to compose. Use `querySelector` when seeking a soloist, a single element that steals the spotlight. Opt for `querySelectorAll` when conducting an ensemble, summoning multiple elements to perform in unison.
60 |
61 | May your web symphony be enriched with the nuanced understanding of these selectors, as you navigate the vast expanse of the DOM, orchestrating a performance that captivates users and weaves tales in pixels. 🎭✨
--------------------------------------------------------------------------------
/DOM/DOM2.md:
--------------------------------------------------------------------------------
1 | # Windows into the Web: Unveiling Common Utilities and Magical Events ✨
2 |
3 | In the vast and enchanting realm of the web, there exists a magical object known as the Window. Imagine it as a grand theater, and within it, a symphony of utility functions and mesmerizing events orchestrates the dance of pixels and the flow of information. As your guide through this mystical journey, let us uncover the secrets behind the Maestro's Wand, the Sands of Time, Whispers in the Breeze, and the Dance of the Elements.
4 |
5 | ## The Maestro's Wand: Common Utility Functions 🎭
6 |
7 | Our journey begins with the Maestro's Wand, a collection of common utility functions within the Window object. These functions serve as the conductor, directing the harmony of web interactions.
8 |
9 | ```javascript
10 | // Maestro's Wand in action
11 | const screenWidth = window.innerWidth;
12 | const pageHeight = window.innerHeight;
13 |
14 | console.log(`Screen Width: ${screenWidth}, Page Height: ${pageHeight}`);
15 |
16 | // Additional utility functions
17 | const locationURL = window.location.href;
18 | console.log(`Current URL: ${locationURL}`);
19 |
20 | const userAgent = window.navigator.userAgent;
21 | console.log(`User Agent: ${userAgent}`);
22 | ```
23 |
24 | Here, the Maestro's Wand reveals not only dimensions but also the current URL and user agent, providing a richer tapestry for our magical canvas. With functions like `window.alert()`, the Maestro can also send messages to the audience, guiding them through the web spectacle.
25 |
26 | ## The Sands of Time: setTimeout vs setInterval ⏰
27 |
28 | As we step onto the sands of time, we encounter two magical entities: `setTimeout` and `setInterval`. Picture setTimeout as a sorcerer casting a spell, delaying an action for a set period.
29 |
30 | ```javascript
31 | // Casting a spell with setTimeout
32 | setTimeout(() => {
33 | console.log("Delayed enchantment!");
34 | }, 2000);
35 | ```
36 |
37 | In contrast, setInterval is the guardian of repetitive rhythms, casting spells at regular intervals.
38 |
39 | ```javascript
40 | // The rhythmic beats of setInterval
41 | const intervalId = setInterval(() => {
42 | console.log("Repeated enchantment!");
43 | }, 3000);
44 |
45 | // Clearing the enchantment with clearInterval
46 | setTimeout(() => {
47 | clearInterval(intervalId);
48 | console.log("Enchantment ceased!");
49 | }, 15000);
50 | ```
51 |
52 | By understanding these sands of time, we gain the power to control the pacing of our web enchantments and even bring them to an end when needed.
53 |
54 | ## Whispers in the Breeze: prompt, Alert, and confirm 🗣️
55 |
56 | In the mystical land of user communication, three wizards—`prompt`, `alert`, and `confirm`—whisper messages to the user. `alert` is a direct messenger, instantly catching the user's attention.
57 |
58 | ```javascript
59 | // The direct messenger - alert
60 | window.alert("Behold the magic!");
61 | ```
62 |
63 | `prompt` requests an audience response, like a courteous wizard inviting participation.
64 |
65 | ```javascript
66 | // The interactive wizard - prompt
67 | const userResponse = window.prompt("What is your name?");
68 | console.log(`Greetings, ${userResponse}!`);
69 | ```
70 |
71 | And then there is `confirm`, the yes-or-no oracle, seeking the user's decree.
72 |
73 | ```javascript
74 | // The oracle of decisions - confirm
75 | const userDecision = window.confirm("Are you ready for the adventure?");
76 | ```
77 |
78 | These wizards bring the user into the magical narrative, creating an immersive experience.
79 |
80 | ## Dance of the Elements: Working with Events 💃
81 |
82 | As we approach the grand finale, the Dance of the Elements unfolds—a spectacle of events, listeners, and handlers. Picture elements on a webpage as dancers, responding to the music of user interactions.
83 |
84 | ```javascript
85 | // The Dance of the Elements
86 | const button = document.getElementById("magicButton");
87 |
88 | button.addEventListener("click", () => {
89 | console.log("Button clicked! Let the magic begin!");
90 | });
91 |
92 | // Additional events for an interactive ballet
93 | button.addEventListener("mouseover", () => {
94 | console.log("The magic button feels the presence of the cursor!");
95 | });
96 |
97 | button.addEventListener("mouseout", () => {
98 | console.log("The magic button bids farewell to the cursor!");
99 | });
100 |
101 | window.addEventListener("resize", () => {
102 | console.log("The window has resized! The magic adapts!");
103 | });
104 | ```
105 |
106 | Here, the button becomes a dancer, responding not only to clicks but also to the subtle moves of the cursor and the grand gestures of window resizing.
107 |
108 | ## Conclusion: Awe of the Wonders Within the Window Object
109 |
110 | Our journey through the magical realm of the Window object has been nothing short of awe-inspiring. The Maestro's Wand orchestrates the symphony, the Sands of Time control the tempo, Whispers in the Breeze communicate with users, and the Dance of the Elements creates an interactive ballet.
111 |
112 | As you continue to explore the enchanting world of web development, remember the wonders hidden within the Window object—a treasure trove of utilities and events waiting to be discovered. May your web creations continue to captivate and mesmerize, leaving users in awe of the magic you bring to the digital stage. ✨
--------------------------------------------------------------------------------
/MRF.md:
--------------------------------------------------------------------------------
1 | # 🚀 Mastering JavaScript Array Methods: Unveiling the Power 🔍
2 |
3 | JavaScript arrays are like the unsung heroes of coding, and we're about to unleash their superpowers! 🦸♂️ Today, we're diving deep into the secrets of three mighty methods: `map`, `reduce`, and `filter`.
4 |
5 | ## 1. `map` Method: Transforming with Elegance ✨
6 |
7 | ### Purpose:
8 | `map` is your artistic brush, painting a new array by transforming each element.
9 |
10 | ### Code Symphony:
11 |
12 | ```javascript
13 | const originalArray = [1, 2, 3, 4, 5];
14 |
15 | const newArray = originalArray.map((value, index, array) => value * 2);
16 |
17 | console.log(newArray);
18 | ```
19 |
20 | ### Output Magic:
21 | ```javascript
22 | [2, 4, 6, 8, 10]
23 | ```
24 |
25 | ### Elegance Explained:
26 | - The `map` enchantment gracefully dances through each element.
27 | - A symphony of transformations creates a stunning new array.
28 |
29 | ## 2. `reduce` Method: Crafting a Singular Masterpiece 🖌️
30 |
31 | ### Purpose:
32 | `reduce` transforms an array into a majestic singular value, with the power to set a starting point.
33 |
34 | ### Code Alchemy (Empty Cauldron):
35 |
36 | ```javascript
37 | const numbers = [1, 2, 3, 4, 5];
38 |
39 | const resultObject = numbers.reduce((accumulator, number) => {
40 | accumulator[number] = (accumulator[number] || 0) + 1;
41 | return accumulator;
42 | }, {});
43 |
44 | console.log(resultObject);
45 | ```
46 |
47 | ### Output Enchantment:
48 | ```javascript
49 | { '1': 2, '2': 3, '3': 2, '4': 3, '5': 2 }
50 | ```
51 |
52 | ### Alchemy Explained:
53 | - An empty cauldron (`{}`) sets the stage for the alchemical process.
54 | - Each number is stirred into the mix, concocting a magical potion of frequencies.
55 |
56 | ### Code Alchemy (With Initial Potion):
57 |
58 | ```javascript
59 | const numbers = [1, 2, 3, 4, 5];
60 |
61 | const sum = numbers.reduce((accumulator, value) => accumulator + value, 0);
62 |
63 | console.log(sum);
64 | ```
65 |
66 | ### Output Sorcery:
67 | ```javascript
68 | 15
69 | ```
70 |
71 | ### Alchemy Unveiled:
72 | - A starting potion (`0`) initiates the mystical brewing.
73 | - The potion gathers its elements, summing them into a powerful elixir.
74 |
75 | `reduce` is your magic wand, shaping data realms at your command.
76 |
77 | ## 3. `filter` Method: Summoning the Chosen Ones 🧙♂️
78 |
79 | ### Purpose:
80 | `filter` conjures a new array, gathering only elements that pass a mystical test.
81 |
82 | ### Code Spell:
83 |
84 | ```javascript
85 | const numbers = [1, 2, 3, 4, 5];
86 |
87 | const evenNumbers = numbers.filter((value, index, array) => value % 2 === 0);
88 |
89 | console.log(evenNumbers);
90 | ```
91 |
92 | ### Output Enchantment:
93 | ```javascript
94 | [2, 4]
95 | ```
96 |
97 | ### Spell Unveiled:
98 | - The `filter` spell evaluates each element.
99 | - Only the chosen ones (even numbers in this tale) are summoned into the enchanted array.
100 |
101 | ## 🌟 Apprentice Tips:
102 |
103 | - **Immutable Operations:**
104 | - These methods are your coding guardians, creating a new array for experimentation, leaving the original untouched. It's like crafting a clone, keeping the original safe and sound.
105 |
106 | - **Chaining Methods:**
107 | - String these methods together like a united team, weaving complex operations step by step. It makes your code more comprehensible and controlled.
108 |
109 | ```javascript
110 | const transformedArray = originalArray
111 | .map((value) => value * 2) // Double each value
112 | .filter((value) => value > 5) // Keep only values greater than 5
113 | .reduce((sum, value) => sum + value, 0); // Add them up
114 | ```
115 |
116 | Embrace these array methods like a :sparkles: superpower :sparkles:, making your coding journey more enjoyable and efficient.
117 |
118 | ## 🧙♂️ JavaScript Array Methods Almanac 📜
119 |
120 | | Method | Number of Arguments | Arguments | Number of Arguments for Function | Arguments for Function | Return Type | Description |
121 | | :-------: | :-----------------: | :------------------------: | :------------------------------: | :--------------------------------------: | :---------: | :------------------------: |
122 | | `.map` | 1 | `function` | 3 | `value`, `index`, `array` | `Array` | Transforms each element. |
123 | | `.reduce` | 2 | `function`, `initialValue` | 4 | `accumulator`, `value`, `index`, `array` | `any` | Aggregates values. |
124 | | `.filter` | 1 | `function` | 3 | `value`, `index`, `array` | `Array` | Selects specific elements. |
125 |
126 | May your coding adventures be filled with magical arrays!
127 |
128 | 🌟
129 |
130 | ---
131 |
132 | *Thank you for being a part of this coding quest. Your journey is the heartbeat of these words. Whether you found information, inspiration, or just enjoyed the content, your presence is treasured. Writing is a shared adventure, and I'm grateful to have you as a fellow traveler. Cheers to the joy of discovery and exploration! 🚀*
133 |
134 | *If you found the article delightful, consider showering it with more stars!*
135 |
136 | *With appreciation,*
137 |
138 | *Pugazharasan C*
--------------------------------------------------------------------------------
/DOM/DOM1.md:
--------------------------------------------------------------------------------
1 | # Dancing with the DOM: A Symphony of Web Magic ✨
2 |
3 | ## Introduction: Unveiling the Enchantment of DOM
4 |
5 | In the vast expanse of the internet, where pixels burst into life and websites hum with vitality, a mystical force orchestrates the dance of web elements. This enchanting force is the Document Object Model, or DOM – the unseen maestro conducting the symphony of web magic.
6 |
7 | ```html
8 |
9 |
10 |
11 |
12 |
13 |
14 | Web Magic Symphony
15 |
16 |
17 |
18 |
19 |
Welcome to the enchanted world of DOM!
20 |
21 |
22 |
23 |
24 | ```
25 |
26 | ```javascript
27 | // app.js - The enchantment commences
28 | document.addEventListener('DOMContentLoaded', () => {
29 | // DOM orchestrates the magic; elements spring to life!
30 | const magicContainer = document.getElementById('magic-container');
31 | magicContainer.innerHTML += 'Feel the magic!
';
32 | });
33 | ```
34 |
35 | ## The Birth of Elements: createElement and setAttribute 💫
36 |
37 | In this mystical realm, two protagonists, `createElement` and `setAttribute`, take the stage. Picture `createElement` as the sorcerer conjuring elements into existence, while `setAttribute` bestows upon them unique powers and characteristics. Together, they weave the very fabric of the web, turning lines of code into a visual masterpiece.
38 |
39 | ```javascript
40 | // Crafting elements with createElement and setting attributes with setAttribute
41 | const newElement = document.createElement('div'); // crafts an empty div element:
42 | newElement.setAttribute('class', 'magical-box'); // Sets class attribute to 'magical-box':
43 | newElement.textContent = 'I am a magical box!'; // Adds text content: I am a magical box!
44 | document.body.appendChild(newElement);
45 | ```
46 |
47 | ## The Quest for Identity: getElementById and the Mystical QuerySelectors 🌟
48 |
49 | As our saga unfolds, we meet `getElementById` on a quest to find an element by its unique identity, while the dynamic duo, `querySelector` vs `querySelectorAll`, traverse the web cosmos, seeking elements with unparalleled flexibility.
50 |
51 | ```javascript
52 | // Seeking elements by ID and employing querySelectors
53 | const specificElement = document.getElementById('magic-container'); // Retrieves a unique element with the ID 'magic-container'
54 | const anyElement = document.querySelector('.magical-box'); // Retrieves the first element with class 'magical-box'
55 | const allElements = document.querySelectorAll('.magical-box'); // Retrieves all elements with class 'magical-box'
56 | ```
57 |
58 | For more details
59 | + [QuerySelector vs QuerySelectorAll](./This%20vs%20That/QuerySelector%20vs%20QuerySelectorAll.md)
60 | + [QuerySelector vs GetElementById](./This%20vs%20That/QuerySelector%20vs%20GetElementById.md)
61 |
62 |
63 | ## Words Unveiled: innerHTML vs innerText 📜
64 |
65 | As we venture deeper, we encounter two siblings, `innerHTML` and `innerText`, each with distinct powers in content manipulation. `InnerHTML`, the artist, paints content within an element, while `innerText`, the storyteller, unveils raw, unadorned text.
66 |
67 | ```javascript
68 | // Manipulating content within elements using innerHTML and innerText
69 | const magicParagraph = document.querySelector('.magical-box');
70 | magicParagraph.innerText = 'Witness the enchantment!';
71 | magicParagraph.innerHTML += 'Behold the magic!';
72 | console.log(magicParagraph.innerText); // Outputs: Witness the enchantment!Behold the magic!
73 | console.log(magicParagraph.innerHTML); // Outputs: Witness the enchantment!Behold the magic!
74 | ```
75 |
76 | Wanna Explore More [InnerHTML vs InnerText](./This%20vs%20That/InnerHTML%20vs%20InnerText.md)
77 |
78 |
79 | ## Harmony in Unity: appendChild vs append 🎵
80 |
81 | Our odyssey concludes with the rhythmic dance of `appendChild` and `append`. These virtuosos seamlessly unite elements, constructing the web symphony with finesse. Picture them as conductors, arranging elements in a crescendo of unity.
82 |
83 | ```javascript
84 | // Bringing elements together with appendChild and append
85 | const parentElement = document.getElementById('magic-container');
86 | const childElement = document.createElement('p');
87 | childElement.textContent = 'A new element joins the symphony!';
88 | parentElement.appendChild(childElement);
89 | // Alternatively
90 | parentElement.append(childElement, 'Yet another magical paragraph!');
91 | ```
92 | For more details [Append vs AppendChild](../This%20vs%20That/Append%20vs%20AppendChild.md)
93 |
94 | ## Conclusion: The Everlasting Dance of DOM
95 |
96 | In the magical world of the Document Object Model, where elements waltz and scripts sing, the symphony of web magic plays on. The dance of `createElement` and `setAttribute`, the quest of `getElementById` and `querySelector`s, the unveiling of `innerHTML` and `innerText`, and the harmony in the unity of `appendChild` and `append` – all combine to create a mesmerizing spectacle.
97 |
98 | May you, the sorcerer of the web, continue to dance with the DOM, orchestrating a symphony that enchants users and leaves an indelible mark on the digital landscape. For in the realm of web magic, the Document Object Model reigns supreme, bringing to life the pixels and code that shape our digital dreams. ✨
--------------------------------------------------------------------------------
/Async Programming/README.md:
--------------------------------------------------------------------------------
1 | Certainly! Here's an introduction and details added to the combined index:
2 |
3 | # Asynchronous JavaScript Programming: A Cinematic Code Journey 🚀🍿
4 |
5 | Welcome to the thrilling world of asynchronous JavaScript programming, where the scripts unfold like a cinematic adventure! In this epic journey, we explore the dynamic landscape of async programming, callbacks, promises, and the blockbuster duo: `async` and `await`. Join us as we navigate through the intricacies of JavaScript's async realm, encountering suspenseful moments, unexpected twists, and seamless plot continuations.
6 |
7 | ## Table of Contents
8 |
9 | ### [Async Programming in JavaScript](Async%20Programming.md)
10 |
11 | 1. [Sync Vs Async: Unraveling the Plot](Async%20Programming.md#sync-vs-async-unraveling-the-plot)
12 | - [Sync](Async%20Programming.md#sync)
13 | - [Async](Async%20Programming.md#async)
14 |
15 | 2. [How JS Handles Async Processes: Behind the Scenes](Async%20Programming.md#how-js-handles-async-processes-behind-the-scenes)
16 | - [Call Stack: The Script Unfolds](Async%20Programming.md#call-stack-the-script-unfolds)
17 | - [Web API: Supporting Actors](Async%20Programming.md#web-api-supporting-actors)
18 | - [Callback Queue: Waiting in the Wings](Async%20Programming.md#callback-queue-waiting-in-the-wings)
19 | - [Event Loop: The Director's Vision](Async%20Programming.md#event-loop-the-directors-vision)
20 |
21 | 3. [Visual Representation of Asynchronous Execution](Async%20Programming.md#visual-representation-of-asynchronous-execution)
22 |
23 | ### [Callbacks in JavaScript: A "Vikram Vedha" Tale 🎬](Callback.md)
24 |
25 | 1. [Introduction to Callbacks](Callback.md#introduction-to-callbacks)
26 | 2. [Why Callbacks Are Needed](Callback.md#why-callbacks-are-needed)
27 | - [Real-world Scenarios: Callbacks in Action](Callback.md#real-world-scenarios-callbacks-in-action)
28 | 3. [Callback Example: A Detective's Call](Callback.md#callback-example-a-detectives-call)
29 | 4. [Limitations of Callbacks: A Crime Thriller Twist](Callback.md#limitations-of-callbacks-a-crime-thriller-twist)
30 | - [Callback Hell Example: Unraveling the Plot](Callback.md#callback-hell-example-unraveling-the-plot)
31 | 5. [The Road Ahead: Teasing Promises and Async/Await](Callback.md#the-road-ahead-teasing-promises-and-asyncawait)
32 |
33 | ### [Promises in JavaScript: A Cinematic Code Saga 🌟](Promise.Movie.md)
34 |
35 | 1. [Unveiling the Promise](Promise.Movie.md#unveiling-the-promise)
36 | 2. [Promise States: A Visual Masterpiece](Promise.Movie.md#promise-states-a-visual-masterpiece)
37 | - [Crafting a Promise: Behind the Scenes](Promise.Movie.md#crafting-a-promise-behind-the-scenes)
38 | - [Handling Promises: A Director's Cut with `then()`, `catch()`, and `finally()`](Promise.Movie.md#handling-promises-a-directors-cut-with-then-catch-and-finally)
39 | 3. [Chaining Promises: Sequencing Asynchronous Operations – A Script Continuation](Promise.Movie.md#chaining-promises-sequencing-asynchronous-operations--a-script-continuation)
40 | - [Basic Promise Structure: Setting the Stage](Promise.Movie.md#basic-promise-structure-setting-the-stage)
41 | - [Chaining `then` for Sequencing: A Symphonic Composition](Promise.Movie.md#chaining-then-for-sequencing-a-symphonic-composition)
42 | - [Chaining Promises for Sequential Operations: A Script Continuation](Promise.Movie.md#chaining-promises-for-sequential-operations-a-script-continuation)
43 | 4. [Promise Methods: The Arsenal Unleashed](Promise.Movie.md#promise-methods-the-arsenal-unleashed)
44 | - [`Promise.resolve()` and `Promise.reject()`: Static Methods as Plot Enablers](Promise.Movie.md#promiseresolve-and-promisereject-static-methods-as-plot-enablers)
45 | - [Chaining Promises: Sequencing Asynchronous Operations – A Script Continuation](Promise.Movie.md#chaining-promises-sequencing-asynchronous-operations--a-script-continuation)
46 | - [Promise Methods Comparison: A Cinematic Spectrum](Promise.Movie.md#promise-methods-comparison-a-cinematic-spectrum)
47 | 5. [Closing Scene: Understanding Promises](Promise.Movie.md#closing-scene-understanding-promises)
48 |
49 | ### [Async/Await: Scripting the Next Blockbuster 🍿🚀](AsyncAndAwait.md)
50 |
51 | 1. [Keywords Async and Await](AsyncAndAwait.md#keywords-async-and-await)
52 | 2. [Async Function: The Prologue of a Cinematic Code Tale 🎬](AsyncAndAwait.md#async-function-the-prologue-of-a-cinematic-code-tale)
53 | - [The Async Hero: `getMovieTitle`](AsyncAndAwait.md#the-async-hero-getmovietitle)
54 | - [Action Begins: Calling the Async Function](AsyncAndAwait.md#action-begins-calling-the-async-function)
55 | - [The Promise: A Glimpse of the Future](AsyncAndAwait.md#the-promise-a-glimpse-of-the-future)
56 | - [The Climax: Logging the Output](AsyncAndAwait.md#the-climax-logging-the-output)
57 | 3. [Async Function Definition: `playSuspensefulMusic`](AsyncAndAwait.md#async-function-definition-playsuspensefulmusic)
58 | - [The Setup: `playSuspensefulMusic`](AsyncAndAwait.md#the-setup-playsuspensefulmusic)
59 | - [Action Unfolds: `climaxScene`](AsyncAndAwait.md#action-unfolds-climaxscene)
60 | - [The Suspense: Awaiting the Outcome](AsyncAndAwait.md#the-suspense-awaiting-the-outcome)
61 | - [Climax Revealed: Logging the Result](AsyncAndAwait.md#climax-revealed-logging-the-result)
62 | 4. [Navigating the Cinematic Code Tale: Try-Catch Chronicles](AsyncAndAwait.md#navigating-the-cinematic-code-tale-try-catch-chronicles)
63 | - [The Unpredictable Plot: `unexpectedTwist`](AsyncAndAwait.md#the-unpredictable-plot-unexpectedtwist)
64 | - [Dive into the Unknown: `continuePlot`](AsyncAndAwait.md#dive-into-the-unknown-continueplot)
65 | - [The Drama Unfolds: `try` Block](AsyncAndAwait.md#the-drama-unfolds-try-block)
66 | - [Plot Twist Unveiled: `catch` Block](AsyncAndAwait.md#plot-twist-unveiled-catch-block)
67 |
68 | Embark on this cinematic code journey and witness the magic of asynchronous storytelling in JavaScript! 🌟
--------------------------------------------------------------------------------
/OLD/MRF.md:
--------------------------------------------------------------------------------
1 | # :rainbow: Comprehensive Guide to `map`, `reduce`, and `filter` Array Methods in JavaScript :rocket:
2 |
3 | In JavaScript, arrays are a fundamental data structure, and they come with powerful methods to manipulate and transform data efficiently. This guide will cover three essential array methods: `map`, `reduce`, and `filter`.
4 |
5 | ## 1. `map` Method
6 |
7 | ### Purpose:
8 | The `map` method is used to create a new array by applying a provided function to each element of the original array.
9 |
10 | ### Code Sample:
11 |
12 | ```javascript
13 | const originalArray = [1, 2, 3, 4, 5];
14 |
15 | const newArray = originalArray.map((value, index, array) => {
16 | // Transformation logic here
17 | return value * 2;
18 | });
19 |
20 | console.log(newArray);
21 | ```
22 |
23 | ### Output:
24 | ```javascript
25 | [2, 4, 6, 8, 10]
26 | ```
27 |
28 |
29 | ### Explanation:
30 | - The `map` method iterates through each element of the original array.
31 | - The provided function is applied to each element (multiplying each element by 2 in this case).
32 | - The result is a new array with the transformed values.
33 |
34 | ## 2. `reduce` Method
35 |
36 | ### Purpose:
37 | The `reduce` method is used to reduce the array to a single value by applying a provided function. You can also set an initial value for the accumulator.
38 |
39 | ### Code Sample with Default Value (Empty Object):
40 |
41 | ```javascript
42 | const numbers = [1, 2, 3, 4, 5];
43 |
44 | const resultObject = numbers.reduce((accumulator, number) => {
45 | // Increment the frequency count for each number
46 | accumulator[number] = (accumulator[number] || 0) + 1;
47 | return accumulator;
48 | }, {});
49 | console.log(resultObject);
50 | ```
51 |
52 | ### Output:
53 | ```javascript
54 | { '1': 2, '2': 3, '3': 2, '4': 3, '5': 2 }
55 | ```
56 |
57 |
58 | ### Explanation:
59 | - In this example, we use an empty object (`{}`) as the initial value for the accumulator.
60 | - The provided function is applied to each element of the array.
61 | - The accumulator, which starts as an empty object, is updated in each iteration.
62 | - The final result is an object where each key represents a unique number in the array, and values represent their frequencies.
63 |
64 | ### Code Sample with Initial Value:
65 |
66 | ```javascript
67 | const numbers = [1, 2, 3, 4, 5];
68 |
69 | const sum = numbers.reduce((accumulator, value) => {
70 | return accumulator + value;
71 | }, 0);
72 |
73 | console.log(sum);
74 | ```
75 |
76 | ### Output:
77 | ```js
78 | 15
79 | ```
80 |
81 |
82 | ### Explanation:
83 | - In this example, we use `0` as the initial value for the accumulator.
84 | - The provided function is applied to each element of the array.
85 | - The accumulator, starting at `0`, accumulates the sum of all elements.
86 |
87 | The `reduce` method is versatile and powerful. You can customize it based on your needs, whether you're aggregating values, transforming data, or building complex data structures.
88 |
89 | ## 3. `filter` Method
90 |
91 | ### Purpose:
92 | The `filter` method creates a new array with all elements that pass a provided test.
93 |
94 | ### Code Sample:
95 |
96 | ```javascript
97 | const numbers = [1, 2, 3, 4, 5];
98 |
99 | const evenNumbers = numbers.filter((value, index, array) => {
100 | return value % 2 === 0;
101 | });
102 |
103 | console.log(evenNumbers);
104 | ```
105 |
106 | ### Output:
107 | ```javascript
108 | [ 2, 4]
109 | ```
110 |
111 |
112 | ### Explanation:
113 | - The `filter` method applies the provided function to each element of the array.
114 | - Only the elements that pass the test (even numbers in this case) are included in the new array.
115 |
116 | ## :beginner: Additional Tips:
117 |
118 | - **Immutable Operations:**
119 | - Think of these methods as your code's guardians. They won't change the original array; instead, they create a new one with the changes you want. It's like making a copy to play with, leaving the original safe and sound. This helps you keep things organized and prevents unexpected surprises.
120 |
121 | - **Chaining Methods:**
122 | - Imagine these methods as a team working together. You can ask them to do different tasks one after another, and they'll pass the result down the line. It's like a conveyor belt for your data. By combining these methods, you can achieve complex operations step by step, making it easier to understand and control.
123 |
124 | ```javascript
125 | const transformedArray = originalArray
126 | .map((value) => value * 2) // Double each value
127 | .filter((value) => value > 5) // Keep only values greater than 5
128 | .reduce((sum, value) => sum + value, 0); // Add them up
129 | ```
130 |
131 | This way of working with arrays might feel like a :sparkles: superpower :sparkles: once you get used to it. It's like having a set of tools that play well together, making your coding journey more :dizzy: enjoyable and :chart_with_upwards_trend: efficient.
132 |
133 |
134 | Keep exploring :compass:, and you'll become a coding superhero in no time! :seedling:
135 |
136 | # :crystal_ball: JavaScript Array Methods Overview
137 |
138 | | Method | Number of Arguments | Arguments | Number of Arguments for Function | Arguments for Function | Return Type | Description |
139 | | :-------: | :-----------------: | :------------------------: | :------------------------------: | :--------------------------------------: | :---------: | :------------------------: |
140 | | `.map` | 1 | `function` | 3 | `value`, `index`, `array` | `Array` | Transforms each element. |
141 | | `.reduce` | 2 | `function`, `initialValue` | 4 | `accumulator`, `value`, `index`, `array` | `any` | Aggregates values. |
142 | | `.filter` | 1 | `function` | 3 | `value`, `index`, `array` | `Array` | Selects specific elements. |
143 |
144 |
145 | ---
146 |
147 | *Thank you for taking the time to read my article. Your engagement is the driving force behind the words on these pages. Whether you found information, inspiration, or simply enjoyed the content, your presence is deeply appreciated. Writing is a shared journey, and I'm grateful to have you as a reader. Cheers to the joy of exploration and discovery! 🌟*
148 |
149 | *If you enjoyed the article, consider giving it more stars!*
150 |
151 | *With gratitude,*
152 |
153 | *Pugazharasan C*
--------------------------------------------------------------------------------
/Spread and Rest Operator.md:
--------------------------------------------------------------------------------
1 |
2 | # Spread and Rest: A Ponniyin Selvan Code Saga 🌟
3 |
4 | ## Introduction
5 |
6 | Embark on a JavaScript adventure reminiscent of "Ponniyin Selvan," where Spread and Rest operators take center stage, portraying characters in a code-rich saga filled with versatility and consolidation.
7 |
8 | ### Spread Operator: Unleashing Power 💥
9 |
10 | #### Spreading Arrays
11 |
12 | ```javascript
13 | const kingdoms = ["Chola", "Pandya", "Chera"];
14 | const newKingdoms = [...kingdoms, "Pallava", "Hoysala"]; // 🌐 Spread the power!
15 |
16 | console.log(newKingdoms);
17 | // Output: ["Chola", "Pandya", "Chera", "Pallava", "Hoysala"]
18 | ```
19 |
20 | **Explanation:**
21 |
22 | - **Dynamic Integration:** The Spread operator doesn't just merge arrays; it orchestrates a seamless integration of new kingdoms with the existing ones, creating a powerful alliance that echoes the spirit of "Ponniyin Selvan."
23 |
24 | #### Spreading Objects
25 |
26 | ```javascript
27 | const heroes = { protagonist: "Arulmozhivarman", companion: "Vallavarayan Vandhiyathevan" };
28 | const newHeroes = { ...heroes, ally: "Adhithya Karikalan" }; // 🚀 Spread the character dynamics!
29 |
30 | console.log(newHeroes);
31 | // Output: { protagonist: "Arulmozhivarman", companion: "Vallavarayan Vandhiyathevan", ally: "Adhithya Karikalan" }
32 | ```
33 |
34 | **Explanation:**
35 |
36 | - **Character Empowerment:** The Spread operator empowers newHeroes by inheriting the attributes of the original heroes, plus a new ally. It's not just copying; it's enhancing and extending, mirroring the intricate relationships in "Ponniyin Selvan."
37 |
38 | ### Rest Operator: Consolidating Forces 🤝
39 |
40 | #### Consolidating Arrays
41 |
42 | ```javascript
43 | const characters = ["Arulmozhivarman", "Vallavarayan Vandhiyathevan", "Adhithya Karikalan", "Kundhavai", "Parthibendran Pallavan", "Poonguzhali"];
44 | const [hero, companion, ...supportingCharacters] = characters; // 🏰 Consolidate the forces!
45 |
46 | console.log(hero); // Output: Arulmozhivarman
47 | console.log(companion); // Output: Vallavarayan Vandhiyathevan
48 | console.log(supportingCharacters); // Output: ["Adhithya Karikalan", "Kundhavai", "Parthibendran Pallavan", "Poonguzhali"]
49 | ```
50 |
51 | **Explanation:**
52 |
53 | - **Leadership Unveiled:** The Rest operator isn't just collecting array elements; it's unveiling the leadership duo, Arulmozhivarman and Vallavarayan Vandhiyathevan, while efficiently consolidating the supporting characters for a clearer view of the code structure.
54 |
55 | #### Consolidating Objects
56 |
57 | ```javascript
58 | const kingdoms = {
59 | ruler: "Chola",
60 | rival: "Pandya",
61 | friend: "Pallava",
62 | strategist: "Vallavarayan Vandhiyathevan",
63 | };
64 |
65 | const { ruler, rival, ...allies } = kingdoms; // 👑 Consolidate the kingdom hierarchy!
66 |
67 | console.log(ruler); // Output: Chola
68 | console.log(rival); // Output: Pandya
69 | console.log(allies);
70 | // Output: { friend: "Pallava", strategist: "Vallavarayan Vandhiyathevan" }
71 | ```
72 |
73 | **Explanation:**
74 |
75 | - **Dynamic Leadership:** The Rest operator in objects reveals the dynamic leadership structure, leaving rivals to handle the rest. It's not just extracting; it's showcasing a dynamic hierarchy inspired by the political intrigue in "Ponniyin Selvan."
76 |
77 | ### Functions with Spread and Rest
78 |
79 | #### Using Spread in Functions
80 |
81 | ```javascript
82 | function assembleTeam(leader, companion, ...teamMembers) {
83 | console.log(`Leader: ${leader}`);
84 | console.log(`Companion: ${companion}`);
85 | console.log(`Team Members: ${teamMembers.join(", ")}`);
86 | }
87 |
88 | const warriors = ["Arulmozhivarman", "Vallavarayan Vandhiyathevan", "Adhithya Karikalan", "Parthibendran Pallavan"];
89 | assembleTeam("Sundara Chola", "Vanavan Mahadevi", ...warriors); // 🌐 Spread the teamwork spirit!
90 | ```
91 |
92 | **Explanation:**
93 |
94 | - **Dynamic Team Assembly:** Spread in functions isn't just spreading arguments; it's dynamically assembling a warrior team with Sundara Chola and Vanavan Mahadevi leading alongside the heroes. It's not just calling a function; it's orchestrating a dynamic ensemble.
95 |
96 | #### Using Rest in Functions
97 |
98 | ```javascript
99 | function createKingdom(leader, ally, rival, ...restOfKingdom) {
100 | console.log(`Leader: ${leader}`);
101 | console.log(`Rival: ${rival}`);
102 | console.log(`Rest of the Kingdom: ${restOfKingdom.join(", ")}`);
103 | }
104 |
105 | const lands = ["Chera", "Pallava", "Hoysala"];
106 | createKingdom("Raja Raja Chola", "Pandya Brothers", ...lands); // 🏰 Establish the kingdom initiative!
107 | ```
108 |
109 | **Explanation:**
110 |
111 | - **Kingdom Initiative:** Rest in functions isn't just consolidating parameters; it's initiating the Kingdom with Raja Raja Chola at the helm, Pandya Brothers as rivals, and efficiently handling the rest of the lands. It's not just defining a function; it's establishing an initiative inspired by the political landscape in "Ponniyin Selvan."
112 |
113 |
114 | ### Visual Reference: Spread and Rest Operators
115 |
116 | Absolutely! Visual aids can make complex concepts more digestible. Let's try a simplified table and some explanatory notes:
117 |
118 | ### Spread Operator:
119 |
120 | | Use Case | Example | Explanation |
121 | | ------------------ | ------------------------------------------------ | ----------------------------------------------------------- |
122 | | Arrays | `const newArray = [...oldArray]` | Copies elements from an existing array |
123 | | Objects | `const newObj = { ...oldObj, newProp: "value" }` | Copies properties from an existing object and adds new ones |
124 | | Function Arguments | `myFunction(...args)` | Passes array elements as individual function arguments |
125 |
126 | ### Rest Operator:
127 |
128 | | Use Case | Example | Explanation |
129 | | ------------------ | ---------------------------------------------- | -------------------------------------------------- |
130 | | Arrays | `const [first, second, ...rest] = myArray` | Collects remaining elements into a new array |
131 | | Objects | `const { prop1, prop2, ...rest } = myObject` | Collects remaining properties into a new object |
132 | | Function Arguments | `function myFunction(arg1, arg2, ...restArgs)` | Gathers remaining function arguments into an array |
133 |
134 | ## Conclusion
135 |
136 | In this Ponniyin Selvan Code Saga, Spread and Rest operators showcase their prowess in spreading power, consolidating forces, and dynamically orchestrating code structures. Whether it's forming alliances, managing characters, or dynamically creating teams and kingdoms, these operators add a layer of sophistication and flexibility to your JavaScript scripts. Get ready for an epic coding adventure with Spread and Rest in the spirit of "Ponniyin Selvan!" 🌟
137 |
--------------------------------------------------------------------------------
/Async Programming/AsyncAndAwait.md:
--------------------------------------------------------------------------------
1 | # Async/Await: Scripting the Next Blockbuster 🍿🚀
2 |
3 | ## Keywords Async and Await
4 |
5 | In the realm of JavaScript, enter the dynamic duo: `async` and `await`. These keywords team up to revolutionize asynchronous programming, much like the lead pair in your favorite action-packed blockbuster. Let's uncover their roles in our coding saga.
6 |
7 | # Async Function: The Prologue of a Cinematic Code Tale 🎬
8 |
9 | In the vast script of JavaScript, an `async` function emerges as the protagonist—an asynchronous hero ready to unfold a captivating tale. Let's dive into the prologue of our cinematic code journey with an `async` function.
10 |
11 | ```javascript
12 | // Async Function Definition
13 | async function getMovieTitle() {
14 | return "Mankatha";
15 | }
16 |
17 | // Calling the Async Function
18 | const movieTitlePromise = getMovieTitle();
19 |
20 | console.log(movieTitlePromise);
21 | ```
22 |
23 | ## The Async Hero: `getMovieTitle`
24 |
25 | Meet our Async Hero, `getMovieTitle`. This function is marked as `async`, signaling its prowess in handling asynchronous tasks. Its mission: retrieve the title of an epic movie—let's call it "Mankatha."
26 |
27 | ## Action Begins: Calling the Async Function
28 |
29 | The script, eager to reveal the movie title, calls our Async Hero—`getMovieTitle`. But here's the twist: instead of immediately getting the title, it receives a Promise in return. The plot thickens!
30 |
31 | ```javascript
32 | console.log(movieTitlePromise); // Promise {: "Mankatha"}
33 | ```
34 |
35 | **Output :**
36 | ```javascript
37 | Promise {: "Mankatha"}
38 | [[Prototype]]: Promise
39 | [[PromiseState]]: "fulfilled"
40 | [[PromiseResult]]: "Mankatha"
41 | ```
42 |
43 | ## The Promise: A Glimpse of the Future
44 |
45 | `movieTitlePromise` holds a Promise—a commitment from our Async Hero that the movie title will be revealed. The script, undeterred by the asynchronous nature, patiently awaits the outcome.
46 |
47 | ## The Climax: Logging the Output
48 |
49 | Asynchronously, when the movie title is ready, the `then` method steps in to capture the climax. It logs the awaited movie title, giving closure to this part of the code tale.
50 |
51 | ```javascript
52 | movieTitlePromise.then((title) => {
53 | console.log("Movie Title:", title); // Movie Title: Mankatha
54 | });
55 | ```
56 |
57 | The log statement unveils the movie title, bringing the prologue to a satisfying end. In the upcoming acts, we'll delve into more complex plotlines, exploring the full potential of async functions. Get ready for an exciting code narrative reminiscent of your favorite cinematic adventures! 🚀🎥
58 |
59 | ```javascript
60 | // Async Function Definition
61 | async function playSuspensefulMusic(minutes) {
62 | console.log("Enchanting suspenseful music echoes...");
63 | return new Promise((resolve) => {
64 | setTimeout(() => {
65 | console.log("Suspense Revealed");
66 | resolve("Vinayak Mahadev and Prithvi walk away with bags of money");
67 | }, minutes * 60 * 1000);
68 | });
69 | }
70 |
71 | // Async Function Call
72 | async function climaxScene() {
73 | console.log('Vinayak whispers "Action King" over the phone');
74 | const result = await playSuspensefulMusic(3);
75 | console.log("Climax Revealed:", result);
76 | }
77 |
78 | // Initiating the Climax Scene
79 | climaxScene();
80 | ```
81 |
82 | ## The Setup: `playSuspensefulMusic`
83 |
84 | Our script orchestrates the scene with an asynchronous function named `playSuspensefulMusic`. This function simulates enchanting suspenseful music and introduces a promise-based time delay to build anticipation.
85 |
86 | ## Action Unfolds: `climaxScene`
87 |
88 | The protagonist, `climaxScene`, steps in to initiate the suspenseful sequence. It whispers the phrase "Action King" and eagerly awaits the outcome of `playSuspensefulMusic` using the `await` keyword, adding a touch of cinematic tension.
89 |
90 | ## The Suspense: Awaiting the Outcome
91 |
92 | As the suspenseful music echoes, the `await` keyword gracefully pauses the script, allowing it to patiently await the resolution of the asynchronous `playSuspensefulMusic` function. The countdown begins!
93 |
94 | ## Climax Revealed: Logging the Result
95 |
96 | Finally, the suspense is unveiled, and the script continues its execution. The result of the suspenseful theme music is captured in the variable `result` and is then vividly logged.
97 |
98 | **Expected Output:**
99 | ```javascript
100 | Vinayak whispers "Action King" over the phone
101 | Enchanting suspenseful music echoes...
102 | Suspense Revealed
103 | Climax Revealed: Vinayak Mahadev and Prithvi walk away with bags of money
104 | ```
105 |
106 | The script crafts a cinematic experience, complete with suspense, anticipation, and a climactic revelation. As we explore more scenes in the upcoming acts, be prepared for a riveting code tale that mirrors the excitement of your favorite cinematic adventures! 🍿🎬✨
107 |
108 | ## Navigating the Cinematic Code Tale: Try-Catch Chronicles 🍿🎬
109 |
110 | In the ever-evolving script of JavaScript, the plot thickens with the introduction of error handling using `try` and `catch`. Let's embark on the next chapter of our cinematic code journey, exploring the intricacies of these constructs.
111 |
112 | ## The Unpredictable Plot: `unexpectedTwist`
113 |
114 | In the ongoing cinematic code tale, our script introduces an `async` function named `unexpectedTwist`. This function represents a critical plot point, where the storyline could take an unexpected turn—either leading to the hero's success or presenting an unforeseen obstacle.
115 |
116 | ## Dive into the Unknown: `continuePlot`
117 |
118 | The protagonist,
119 |
120 | `continuePlot`, steps in to navigate the uncertain plot. The `try` block encapsulates the asynchronous call to `unexpectedTwist`, aiming to capture the outcome. However, the `catch` block stands ready to handle any plot twists or unexpected challenges that may arise.
121 |
122 | ## The Drama Unfolds: `try` Block
123 |
124 | Within the `try` block, the script awaits the resolution of `unexpectedTwist`. If all goes well, and the hero prevails against the odds, the outcome is captured and vividly logged. This represents the success path of the storyline.
125 |
126 | ## Plot Twist Unveiled: `catch` Block
127 |
128 | In case of an unforeseen obstacle disrupting the plot, the `catch` block gracefully catches the error, preventing it from derailing the entire script. The error is logged, adding depth to the narrative, and the script proceeds with grace.
129 |
130 | Now, let's explore the code that brings these elements to life.
131 |
132 | ```javascript
133 | // Async Function Definition
134 | async function unexpectedTwist() {
135 | return new Promise((resolve, reject) => {
136 | const randomEvent = Math.random();
137 |
138 | // Simulating an unexpected event (error or success)
139 | if (randomEvent < 0.5) {
140 | console.log("The plot takes an unexpected twist!");
141 | resolve("The hero prevails against all odds");
142 | } else {
143 | console.log("An unforeseen obstacle disrupts the storyline!");
144 | reject("The hero faces a sudden challenge");
145 | }
146 | });
147 | }
148 |
149 | // Async Function Call with Try-Catch
150 | async function continuePlot() {
151 | try {
152 | const outcome = await unexpectedTwist();
153 | console.log("Outcome:", outcome);
154 | } catch (error) {
155 | console.error("Plot Twist Error:", error);
156 | }
157 | }
158 |
159 | // Initiating the Next Scene
160 | continuePlot();
161 | ```
162 |
163 | **Expected Output (Example):**
164 | ```javascript
165 | The plot takes an unexpected twist!
166 | Outcome: The hero prevails against all odds
167 | ```
168 |
169 | or
170 |
171 | ```javascript
172 | An unforeseen obstacle disrupts the storyline!
173 | Plot Twist Error: The hero faces a sudden challenge
174 | ```
175 |
176 | The script, equipped with try-catch error handling, ensures that the cinematic code tale continues seamlessly, adapting to unexpected twists and challenges. As we progress through the subsequent scenes, anticipate more plot developments and twists in this thrilling coding saga! 🍿🎬🌟
--------------------------------------------------------------------------------
/Functions.md:
--------------------------------------------------------------------------------
1 | # JavaScript Functions: A Love Story ❤️
2 |
3 | ## The Serenade of Functions 🎶
4 |
5 | In the enchanting world of JavaScript, functions are like magical notes in a serenade, crafting a symphony of logic and passion. Our love story begins with a classic introduction:
6 |
7 | ```javascript
8 | function greet() {
9 | console.log("Sweet melodies of 'Hello,' dear reader!");
10 | }
11 |
12 | greet(); // Ah, the sweet serenade of a greeting!
13 | ```
14 |
15 | ### Output
16 | ```yaml
17 | Sweet melodies of 'Hello,' dear reader!
18 | ```
19 |
20 | ## Love at First Sight: Named Functions 💘
21 |
22 | Our first protagonist, the Named Function, is like a love letter to simplicity and reusability:
23 |
24 | ```javascript
25 | function sayHello(name) {
26 | console.log(`Love whispers: Hello, ${name}!`);
27 | }
28 |
29 | sayHello("Hermione Granger"); // A tender greeting: Hello, Hermione Granger!
30 | ```
31 |
32 | ### Output
33 | ```yaml
34 | Love whispers: Hello, Hermione Granger!
35 | ```
36 |
37 | **Explanation:**
38 |
39 | - **Named Functions:** Think of them as love notes with a name tag. Easy to remember, easy to reuse—expressing your sentiments with clarity.
40 |
41 | ## The Mysterious Affair: Anonymous Functions 🌌
42 |
43 | In the moonlit garden of programming, Anonymous Functions unfold a love affair with the unknown:
44 |
45 | ```javascript
46 | let greet = function () {
47 | console.log("Whispers of affection: Mysterious greetings!");
48 | };
49 |
50 | greet(); // A secret greeting shared with the stars: Mysterious greetings!
51 | ```
52 |
53 | ### Output
54 | ```yaml
55 | Whispers of affection: Mysterious greetings!
56 | ```
57 |
58 | **Explanation:**
59 |
60 | - **Anonymous Functions:** Imagine these as mysterious love notes passed in secret. They exist without a name, adding a touch of intrigue to your code.
61 |
62 | ## Modern Romance: Arrow Functions (ES6) 🏹
63 |
64 | As our love story evolves, Arrow Functions take center stage—a modern waltz of simplicity:
65 |
66 | **Old Way (Traditional):**
67 |
68 | ```javascript
69 | let addOld = function (a, b) {
70 | return a + b;
71 | };
72 | ```
73 |
74 | **New Way (Arrow Function):**
75 |
76 | ```javascript
77 | let addNew = (a, b) => a + b;
78 |
79 | console.log(addOld(3, 4)); // A dance from the past: 7
80 | console.log(addNew(3, 4)); // A waltz in the present: 7
81 | ```
82 |
83 | ### Output
84 | ```yaml
85 | 7
86 | 7
87 | ```
88 |
89 | **Differences:**
90 |
91 | - **Arrow Functions:** Think of them as love notes written in shorthand. Concise, modern, and expressing your feelings with a touch of elegance.
92 |
93 | ## Love at First Sight: IIFE (Immediately Invoked Function Expression) ⚡
94 |
95 | In the blink of an eye, the Immediately Invoked Function Expression (IIFE) declares its love and acts upon it:
96 |
97 | **Example:**
98 |
99 | ```javascript
100 | (function () {
101 | let message = "A love at first sight, I am an IIFE!";
102 | console.log(`Whispers of love: ${message}`);
103 | })();
104 | ```
105 |
106 | ### Output
107 | ```yaml
108 | Whispers of love: A love at first sight, I am an IIFE!
109 | ```
110 |
111 | **Explanation:**
112 |
113 | - **IIFE (Immediately Invoked Function Expression):** Picture this as a love declaration made in a split second. It's like saying "I love you" and giving a warm hug all at once.
114 |
115 | ## The Symphony of Devotion: The `return` Keyword 🎻
116 |
117 | Our love story wouldn't be complete without the devotion expressed through the `return` keyword:
118 |
119 | ```javascript
120 | function multiply(a, b) {
121 | return a * b;
122 | }
123 |
124 | let result = multiply(5, 2);
125 | console.log(`The crescendo of love: ${result}`);
126 | ```
127 |
128 | ### Output
129 | ```yaml
130 | The crescendo of love: 10
131 | ```
132 |
133 | **Explanation:**
134 |
135 | - **The `return` Keyword:** This is akin to a grand gesture of love. Your function does something special, and the `return` keyword delivers the heartfelt result.
136 |
137 | ## Mutual Understanding: Handling Arguments 🤝
138 |
139 | In this partnership of understanding, functions handle arguments with grace:
140 |
141 | ```javascript
142 | function greetPerson(name, greeting = "Hello") {
143 | console.log(`Sweet words exchanged: ${greeting}, ${name}!`);
144 | }
145 |
146 | greetPerson("Harry Potter"); // A warm embrace: Hello, Harry Potter!
147 | greetPerson("Hermione Granger", "Hi"); // A playful exchange: Hi, Hermione Granger!
148 | ```
149 |
150 | ### Output
151 | ```yaml
152 | Sweet words exchanged: Hello, Harry Potter!
153 | Sweet words exchanged: Hi, Hermione Granger!
154 | ```
155 |
156 | **Explanation:**
157 |
158 | - **Handling Arguments:** This is like having a conversation in a language both you and your love understand. You can customize the way you express your feelings based on the context.
159 |
160 | ## Infinite Love: Rest Parameters 💖
161 |
162 | Finally, our tale concludes with infinite love, expressed through the Rest Parameters:
163 |
164 | ```javascript
165 | function sum(...numbers) {
166 | return numbers.reduce((total, num) => total + num, 0);
167 | }
168 |
169 | console.log(`A symphony of infinite love: ${sum(1, 2, 3, 4, 5)}`);
170 | ```
171 |
172 | ### Output
173 | ```yaml
174 | A symphony of infinite love: 15
175 | ```
176 |
177 | **Explanation:**
178 |
179 | - **Rest Parameters:** Picture this as a group hug. You're gathering all the love in one place and enjoying the warmth of togetherness.
180 |
181 | ## Love Table: Comparing Different Wormy Functions 🐛💖
182 |
183 | Let's summarize the love story of each function type in a charming table:
184 |
185 | | Function Type | Personality | Characteristics | Example Code |
186 | | ------------------------------- | ------------------ | ------------------------------------------------------- | ----------------------------------------------------------------------------------------------- |
187 | | Named Functions | Poetic Worm | Declared with a name for readability and reusability. | `function sayHello(name) { console.log("Hello, " + name + "!"); }` |
188 | | Anonymous Functions | Mysterious Worm | Defined without a name, often used as arguments. | `let greet = function () { console.log("Greetings!"); };` |
189 | | Arrow Functions (ES6) | Nimble Dancer | Concise, expressive syntax, inherits `this` gracefully. | `let addNew = (a, b) => a + b;` |
190 | | IIFE (Immediately Invoked) | Energetic Lover | Self-invoking for quick and intimate declarations. | `(function () { let message = "I am an IIFE!"; console.log(message); })();` |
191 | | The `return` Keyword | Melodious Composer | Expresses devotion by returning values to the caller. | `function multiply(a, b) { return a * b; }` |
192 | | Handling Arguments | Wise Communicator | Accepts parameters gracefully, with default values. | `function greetPerson(name, greeting = "Hello") { console.log(greeting + ", " + name + "!"); }` |
193 | | Rest Parameters (Infinite Love) | Infinite Embrace | Gathers an infinite array of love with `...` syntax. | `function sum(...numbers) { return numbers.reduce((total, num) =>total + num, 0); }` |
194 |
195 | In the world of JavaScript functions, each type has its own unique charm. May your code be as enchanting as the most delightful tale ever told by our tiny, loving worms! 🐛💖
196 |
197 | ✨
198 |
199 | ---
200 |
201 | *Thank you for taking the time to read my article. Your engagement is the driving force behind the words on these pages. Whether you found information, inspiration, or simply enjoyed the content, your presence is deeply appreciated. Writing is a shared journey, and I'm grateful to have you as a reader. Cheers to the joy of exploration and discovery! 🌟*
202 |
203 | *If you enjoyed the article, consider giving it more stars!*
204 |
205 | *With gratitude,*
206 |
207 | *Pugazharasan C*
--------------------------------------------------------------------------------
/OOPs in JS.2.md:
--------------------------------------------------------------------------------
1 |
2 |
3 | # 🌌The Four Pillars of JavaScript Magic
4 |
5 | Greetings, fellow sorcerers! 🧙♂️✨
6 |
7 | In our magical journey through the realms of Object-Oriented Programming (OOP) in JavaScript, we've uncovered the secrets of Classes, Prototypes, Constructors, and the art of Getters and Setters. Now, as we venture deeper into the enchanted forest of OOP, let's illuminate the path with the four radiant pillars of JavaScript magic: Abstraction, Encapsulation, Inheritance, and Polymorphism.
8 |
9 | ## :crystal_ball: Abstraction: Painting with Broad Strokes
10 |
11 | In the vast canvas of JavaScript magic, Abstraction is the art of painting with broad strokes, capturing the essence of an object while hiding the intricate details. It allows us to focus on what an object does rather than how it achieves it.
12 |
13 | ### :art: The Art of Abstraction
14 |
15 | - **Essence Over Details:** Abstraction encourages us to think in terms of essential features and behaviors, leaving out the nitty-gritty details.
16 |
17 | - **Hierarchy of Abstraction:** Just like a painting with layers, objects can be abstracted into hierarchies, each layer revealing a different level of detail.
18 |
19 | ### :crystal: Example of Abstraction
20 |
21 | ```javascript
22 | // Abstract class representing a Shape
23 | class Shape {
24 | constructor(color) {
25 | this.color = color;
26 | }
27 |
28 | // Abstract method for calculating area
29 | calculateArea() {
30 | // To be implemented by subclasses
31 | }
32 |
33 | // Concrete method for displaying color
34 | displayColor() {
35 | console.log(`The color of the shape is ${this.color}`);
36 | }
37 | }
38 |
39 | // Concrete subclass - Circle
40 | class Circle extends Shape {
41 | constructor(color, radius) {
42 | super(color);
43 | this.radius = radius;
44 | }
45 |
46 | // Implementing abstract method for Circle
47 | calculateArea() {
48 | return Math.PI * this.radius * this.radius;
49 | }
50 | }
51 |
52 | // Concrete subclass - Rectangle
53 | class Rectangle extends Shape {
54 | constructor(color, length, width) {
55 | super(color);
56 | this.length = length;
57 | this.width = width;
58 | }
59 |
60 | // Implementing abstract method for Rectangle
61 | calculateArea() {
62 | return this.length * this.width;
63 | }
64 | }
65 |
66 | // Creating instances and utilizing abstraction
67 | const redCircle = new Circle("red", 5);
68 | const blueRectangle = new Rectangle("blue", 4, 6);
69 |
70 | console.log(redCircle.calculateArea()); // Output: 78.54
71 | console.log(blueRectangle.calculateArea()); // Output: 24
72 | redCircle.displayColor(); // Output: The color of the shape is red
73 | ```
74 |
75 | ## :closed_lock_with_key: Encapsulation: Safeguarding Mysteries
76 |
77 | Encapsulation is the magical art of safeguarding the mysteries of an object, hiding its internal state and requiring interactions to occur through an enchanted interface. It fosters a realm of controlled access, ensuring the integrity of an object's magical essence.
78 |
79 | ### :mag_right: The Magic of Encapsulation
80 |
81 | - **Data Hiding:** Encapsulation conceals the internal details of an object, allowing only the essential information to be visible.
82 |
83 | - **Controlled Access:** Interaction with an object's properties and methods is regulated, preventing unauthorized manipulation.
84 |
85 | ### :closed_book: Example of Encapsulation
86 |
87 | ```javascript
88 | // EnchantedArtifact with encapsulation
89 | class EnchantedArtifact {
90 | #power; // Private property
91 |
92 | constructor(power) {
93 | this.#power = power;
94 | }
95 |
96 | // Getter for accessing the hidden power
97 | getPower() {
98 | console.log("Accessing the hidden power!");
99 | return this.#power;
100 | }
101 |
102 | // Setter for modifying the hidden power
103 | setPower(newPower) {
104 | console.log("Modifying the hidden power!");
105 | this.#power = newPower;
106 | }
107 | }
108 |
109 | // Creating an enchanted artifact
110 | const magicalStaff = new EnchantedArtifact("Arcane Energy");
111 |
112 | // Accessing and modifying the hidden power using encapsulation
113 | console.log(magicalStaff.getPower()); // Output: Accessing the hidden power!
114 | magicalStaff.setPower("Nature Magic"); // Output: Modifying the hidden power!
115 | console.log(magicalStaff.getPower()); // Output: Accessing the hidden power!
116 | ```
117 |
118 | ## :family: Inheritance: Bloodlines of Magic
119 |
120 | Inheritance is the magical concept of creating a new object by duplicating the qualities of an existing object. It's like the bloodline of magic, where the traits of a magical being are passed down to its descendants.
121 |
122 | ### :crown: The Majesty of Inheritance
123 |
124 | - **Code Reusability:** Inheritance enables the reuse of code from existing objects, promoting a more efficient and organized codebase.
125 |
126 | - **Hierarchy of Objects:** Objects can be organized into hierarchies, with a parent object passing its traits to its magical offspring.
127 |
128 | ### :scroll: Example of Inheritance
129 |
130 | ```javascript
131 | // Parent class - MagicalBeing
132 | class MagicalBeing {
133 | constructor(name, power) {
134 | this.name = name;
135 | this.power = power;
136 | }
137 |
138 | // Magical method
139 | castSpell() {
140 | console.log(`${this.name} casts a mesmerizing spell!`);
141 | }
142 | }
143 |
144 | // Child class - DarkMagician inheriting from MagicalBeing
145 | class DarkMagician extends MagicalBeing {
146 | constructor(name, power, darkPower) {
147 | super(name, power); // Calling the constructor of the parent class
148 | this.darkPower = darkPower;
149 | }
150 |
151 | // Additional method for DarkMagician
152 | useDarkPower() {
153 | console.log(`${this.name} harnesses the power of darkness!`);
154 | }
155 | }
156 |
157 | // Creating instances and utilizing inheritance
158 | const wizard = new MagicalBeing("Merlin", "Arcane Magic");
159 | const darkWizard = new DarkMagician("Morgana", "Dark Sorcery", "Shadow Manipulation");
160 |
161 | wizard.castSpell(); // Output: Merlin casts a mesmerizing spell!
162 | darkWizard.castSpell(); // Output: Morgana casts a mesmerizing spell!
163 | darkWizard.useDarkPower(); // Output: Morgana harnesses the power of darkness!
164 | ```
165 |
166 | ## :crystal_ball: Polymorphism: Many Forms of Magic
167 |
168 | Polymorphism is the magical ability of an object to take on many forms. It allows objects of different types to be treated as objects of a common type, enabling flexibility and adaptability in the magical realm.
169 |
170 | ### :sparkles: The Spell of Polymorphism
171 |
172 | - **Method Overloading:** Objects can have multiple forms of a method, each tailored to its specific nature.
173 |
174 | - **Code Flexibility:** Polymorphism provides a flexible approach to interacting with objects, allowing for variations in behavior.
175 |
176 | ### :crystal_ball: Example of Polymorphism
177 |
178 | ```javascript
179 | // Polymorphic method - castMagicSpell
180 | function castMagicSpell(magicalEntity) {
181 | magicalEntity.castSpell();
182 | }
183 |
184 | // Instances with different forms but common method
185 | const sorcerer = new MagicalBeing("Merlin", "Arcane Magic");
186 | const witch = new DarkMagician("Hermione", "Nature Magic", "Shape-shifting");
187 |
188 | // Utilizing polymorphism in the magical realm
189 | castMagicSpell(sorcerer); // Output: Merlin casts a mesmerizing spell!
190 | castMagicSpell(witch);
191 |
192 | // Output: Hermione casts a mesmerizing spell!
193 | ```
194 |
195 | ## :crystal_ball: Epilogue: Unveiling the Essence of Magic
196 |
197 | As we conclude this chapter on the Four Pillars of JavaScript Magic, remember that Abstraction, Encapsulation, Inheritance, and Polymorphism are the ancient spells that weave the very fabric of the enchanted JavaScript realm. Mastering these spells will empower you to create spells of your own, crafting code that resonates with the harmonies of elegant and powerful sorcery.
198 |
199 | May your code be enchanting and your spells be bug-free! Until our paths cross again in the magical realms of JavaScript, farewell, noble sorcerers! 🌟🔮
--------------------------------------------------------------------------------
/console.md:
--------------------------------------------------------------------------------
1 | # 🕵️♂️ CodeDetective Agency Chronicles
2 |
3 | Greetings, esteemed detectives, and welcome to the enthralling world of the CodeDetective Agency! 🕵️♂️🔍 Join our brilliant investigators, Sherlock Holmes and Hercule Poirot, as they navigate the intricate realm of digital mysteries and unveil the secrets behind the Console Object Methods.
4 |
5 | ## 🖥️ Case File: The Mysterious Bug
6 |
7 | Our astute detectives, Sherlock Holmes and Hercule Poirot, are on the trail of a perplexing bug that has infiltrated the code of a critical software system. The interface is behaving strangely, and the culprit seems elusive. Armed with the Console Object Methods, our detectives embark on the investigation.
8 |
9 | ### 📋 Console.log() - Shedding Light on Clues
10 |
11 | ```javascript
12 | // Gathering evidence
13 | console.log("Initializing investigation...");
14 |
15 | // Examining variables
16 | let suspect = "Undefined";
17 | console.log("Suspect:", suspect);
18 |
19 | // Uncovering the bug's tracks
20 | console.log("Bug identified: Unexpected behavior in user interface.");
21 | ```
22 |
23 | The `console.log()` method becomes our detectives' flashlight, illuminating the dark corners of the code and revealing crucial information about variables and unexpected behaviors.
24 |
25 | **Output:**
26 | ```
27 | Initializing investigation...
28 | Suspect: Undefined
29 | Bug identified: Unexpected behavior in user interface.
30 | ```
31 |
32 | ## ⚠️ Case File: The Warning Signs
33 |
34 | As Sherlock Holmes and Hercule Poirot dig deeper, they encounter warning signs that lead them to believe the bug might be more than meets the eye.
35 |
36 | ### ⚠️ console.warn() - Caution in the Code
37 |
38 | ```javascript
39 | // Investigating anomalies
40 | console.warn("Warning: Unusual pattern detected in user interactions.");
41 |
42 | // Verifying suspect's involvement
43 | console.warn("Caution: Possible connection to suspect 'Undefined'.");
44 | ```
45 |
46 | The `console.warn()` method serves as a cautionary beacon, signaling potential issues and guiding our detectives to areas of concern.
47 |
48 | **Output:**
49 | ```
50 | Warning: Unusual pattern detected in user interactions.
51 | Caution: Possible connection to suspect 'Undefined'.
52 | ```
53 |
54 | ## 🚨 Case File: Error Unleashed
55 |
56 | In a twist of events, our detectives stumble upon a cascade of errors, each more cryptic than the last.
57 |
58 | ### 🚨 console.error() - Unmasking the Error
59 |
60 | ```javascript
61 | // Tracing the error trail
62 | console.error("Error: Critical flaw in authentication module.");
63 |
64 | // Examining error details
65 | console.error("Details:", {
66 | type: "Runtime Error",
67 | location: "Authenticator.js",
68 | message: "Unexpected token 'null'."
69 | });
70 | ```
71 |
72 | The `console.error()` method acts as a mask remover, exposing the true face of errors and providing detailed insights into their origins.
73 |
74 | **Output:**
75 | ```
76 | Error: Critical flaw in authentication module.
77 | Details: { type: 'Runtime Error', location: 'Authenticator.js', message: "Unexpected token 'null'." }
78 | ```
79 |
80 | ## 📊 Case File: Tabular Investigation
81 |
82 | As the investigation progresses, Sherlock Holmes and Hercule Poirot need a structured view of the data to connect the dots.
83 |
84 | ### 📊 console.table() - Organizing Clues
85 |
86 | ```javascript
87 | // Compiling data for analysis
88 | const userLogs = [
89 | { username: "Watson", activity: "Login", timestamp: "2024-03-15 08:30:00" },
90 | { username: "Hastings", activity: "Logout", timestamp: "2024-03-15 09:15:00" },
91 | // ...more entries
92 | ];
93 |
94 | // Displaying data in a table
95 | console.table(userLogs);
96 | ```
97 |
98 | The `console.table()` method transforms raw data into a neatly organized table, aiding our detectives in spotting patterns and correlations.
99 |
100 | **Output:**
101 | ```
102 | ┌───────────────┬─────────────┬─────────────────────┬─────────────────────┐
103 | │ (index) │ username │ activity │ timestamp │
104 | ├───────────────┼─────────────┼─────────────────────┼─────────────────────┤
105 | │ 0 │ 'Watson' │ 'Login' │'2024-03-15 08:30:00'│
106 | │ 1 │ 'Hastings' │ 'Logout' │'2024-03-15 09:15:00'│
107 | └───────────────┴─────────────┴─────────────────────┴─────────────────────┘
108 | ```
109 |
110 |
111 | ## ⏰ Case File: Timing Is Everything
112 |
113 | In a race against time, Sherlock Holmes and Hercule Poirot need to measure the execution time of critical functions.
114 |
115 | ### ⏰ console.time() - Racing Against the Clock
116 |
117 | ```javascript
118 | // Starting the timer
119 | console.time("Function Execution Time");
120 |
121 | // Performing critical function
122 | criticalFunction();
123 |
124 | // Stopping the timer
125 | console.timeEnd("Function Execution Time");
126 | ```
127 |
128 | The `console.time()` and `console.timeEnd()` duo allows our detectives to track the elapsed time for crucial operations, ensuring optimal performance.
129 |
130 | **Output:**
131 | ```
132 | Function Execution Time: 354.235ms
133 | ```
134 |
135 | ## ℹ️ Case File: Information Unveiled
136 |
137 | Amidst the complexity, Sherlock Holmes and Hercule Poirot uncover valuable information that could crack the case wide open.
138 |
139 | ### ℹ️ console.info() - Nuggets of Wisdom
140 |
141 | ```javascript
142 | // Revealing key information
143 | console.info("Important: Code refactor in progress.");
144 |
145 | // Sharing insights
146 | console.info("Insight: Bug related to recent changes in authentication flow.");
147 | ```
148 |
149 | The `console.info()` method becomes the conduit for sharing essential information and insights, fostering collaboration among the investigative team.
150 |
151 | **Output:**
152 | ```
153 | Important: Code refactor in progress.
154 | Insight: Bug related to recent changes in authentication flow.
155 | ```
156 |
157 | ## ✔️ Case File: Assertion in Action
158 |
159 | In a quest for certainty, Sherlock Holmes and Hercule Poirot employ assertions to validate critical assumptions.
160 |
161 | ### ✔️ console.assert() - Asserting Truths
162 |
163 | ```javascript
164 | // Asserting critical assumption
165 | console.assert(suspect !== "Undefined", "Assertion failed: Suspect cannot be 'Undefined'.");
166 |
167 | // Continuing the investigation
168 | if (suspect !== "Undefined") {
169 | // Further analysis
170 | }
171 | ```
172 |
173 | The `console.assert()` method acts as a digital oath, ensuring that critical assumptions hold true and guiding the investigation in the right direction.
174 |
175 | **Output:**
176 | ```
177 | Assertion failed: Suspect cannot be 'Undefined'.
178 | ```
179 |
180 | ## 📚 Case File: Grouping Evidence
181 |
182 | As the pieces of the puzzle come together, our detectives organize evidence into logical groups.
183 |
184 | ### 📚 console.group() - Unity in Evidence
185 |
186 | ```javascript
187 | // Initiating evidence grouping
188 | console.group("Authentication Module Analysis");
189 |
190 | // Logging related evidence
191 | console.log("User logs:", userLogs);
192 | console.warn("Warning: Anomaly detected.");
193 |
194 | // Concluding the analysis
195 | console.groupEnd();
196 | ```
197 |
198 | The `console.group()` method allows our detectives to maintain order and unity in the midst of complex investigations.
199 |
200 | **Output:**
201 | ```
202 | Authentication Module Analysis
203 | User logs: [ { username: 'Watson', activity: 'Login', timestamp: '2024-03-15 08:30:00' },
204 | { username: 'Hastings', activity: 'Logout', timestamp: '2024-03-15 09:15:00' } ]
205 | Warning: Anomaly detected.
206 | ```
207 |
208 | ## 🔢 Case File: Counting Clues
209 |
210 | In the final stretch, Sherlock Holmes and Herc
211 |
212 | ule Poirot tally up the occurrences of a key event.
213 |
214 | ### 🔢 console.count() - Tallying Events
215 |
216 | ```javascript
217 | // Counting occurrences
218 | for (let i = 0; i < userLogs.length; i++) {
219 | // Analyzing each log entry
220 | console.count("Log entry analyzed");
221 | // ...additional analysis
222 | }
223 | ```
224 |
225 | The `console.count()` method becomes the digital tally counter, keeping track of the occurrences of crucial events in the investigation.
226 |
227 | **Output:**
228 | ```
229 | Log entry analyzed: 1
230 | Log entry analyzed: 2
231 | ```
232 |
233 | ## 🧹 Case File: Clearing the Path
234 |
235 | With the investigation complete, Sherlock Holmes and Hercule Poirot clear the console, leaving behind a clean slate for the next challenge.
236 |
237 | ### 🧹 console.clear() - A Fresh Start
238 |
239 | ```javascript
240 | // Clearing the console for a fresh start
241 | console.clear();
242 | ```
243 |
244 | The `console.clear()` method becomes the virtual broom, sweeping away the remnants of the investigation and preparing the console for new mysteries.
245 |
246 | ## 📜 Epilogue: The Chronicles Continue
247 |
248 | As we conclude this chapter in the CodeDetective Agency Chronicles, remember that the Console Object Methods are not just tools; they are the essence of clarity in the world of programming investigations. May your code be bug-free, and your consoles clear, dear detectives!
249 |
250 | Until our paths cross again in the digital realm, farewell, noble tech sleuths! 🕵️♂️🚀
--------------------------------------------------------------------------------
/CODEKATA_JS.md:
--------------------------------------------------------------------------------
1 | # :sparkles: CODEKATA JS
2 |
3 | ## :rocket: Elevate Your Coding Skills with CodeKata
4 |
5 | Embark on a journey of coding excellence with CodeKata, a curated series of challenges designed by industry veterans from companies like Microsoft, Walmart, Samsung, and more.
6 |
7 | Practice on CodeKata to enhance your coding proficiency, level up your skills, and boost your chances of acing coding interviews.
8 |
9 | ## :diamonds: Diverse Challenges Await
10 |
11 | Explore a range of coding challenges across categories like :beginner: Absolute Beginner, :1234: Mathematics, :file_folder: Arrays, :abc: Strings, and more. CodeKata caters to all skill levels, making it ideal for both novice and experienced coders.
12 |
13 | ## :mage: Master JavaScript Problem Solving
14 |
15 | Building on the basics covered in [our introductory guide](README.md), dive into real-world problem-solving with JavaScript on CodeKata. Hone your skills, tackle challenges across domains, and elevate your coding prowess through practical exercises.
16 |
17 | Now, let's dive into problem-solving on CodeKata. To get started, visit [CodeKata on GUVI](https://www.guvi.in/code-kata) and explore a curated series of challenges across different categories. Whether you're an absolute :beginner: beginner or an experienced :man_technologist: coder, CodeKata provides a range of tiles to suit every skill level and interest.
18 |
19 | # :computer: User Input in JavaScript
20 |
21 | JavaScript is a language that is not inherently designed for obtaining basic user input. However, with the help of Node.js packages, we can facilitate the process of receiving user input.
22 |
23 | ## :gear: Default Input Code
24 |
25 | To gather user input in JavaScript, you can use the following default code:
26 |
27 | ```javascript
28 | // Getting input via STDIN
29 | const readline = require("readline");
30 |
31 | const inp = readline.createInterface({
32 | input: process.stdin
33 | });
34 |
35 | const userInput = [];
36 |
37 | inp.on("line", (data) => {
38 | userInput.push(data);
39 | });
40 |
41 | inp.on("close", () => {
42 | // start-here
43 | // Your code goes here … replace the below line with your code logic
44 |
45 | console.log(userInput);
46 |
47 | // end-here
48 | });
49 | ```
50 |
51 | ## :bulb: Explanation
52 |
53 | :beginner: **Note for Beginners:**
54 | Understanding the intricacies of this basic snippet may not be crucial at the start. Instead, focus on utilizing the data in the `userInput` array to solve problems in your CodeKata challenges. As you progress, you'll become more familiar with handling user input and can delve deeper into the code details.
55 |
56 | 1. `const readline = require("readline");`
57 | - Import the `readline` module, a utility for reading data from a readable stream, using the `require` function.
58 |
59 | 2. `const inp = readline.createInterface({
60 | input: process.stdin
61 | });`
62 | - Create an interface (`inp`) for reading input. Specify that the input should come from the standard input (`stdin`) stream.
63 |
64 | 3. `const userInput = [];`
65 | - Initialize an empty array called `userInput` to store the user's input.
66 |
67 | 4. `inp.on("line", (data) => {
68 | userInput.push(data);
69 | });`
70 | - Set up an event listener on the `line` event of the `inp` interface. When a line of input is received, the provided callback function is executed, pushing the input data into the `userInput` array.
71 |
72 | 5. `inp.on("close", () => {
73 | console.log(userInput);
74 | });`
75 | - Set up another event listener on the `close` event of the `inp` interface. When the input stream is closed (no more data to read), the provided callback function is executed. This is where you can place your code logic. In the example, it prints the collected `userInput` array to the console.
76 |
77 | # :sparkle: Let's Solve a Problem
78 |
79 | ## :question: Odd or Even Checker
80 |
81 | ### :book: Problem Description
82 | You are tasked with creating a program that determines whether a given number is odd or even.
83 |
84 | ### :page_with_curl: Input Format
85 | There will be only one line of input, which contains a single integer.
86 |
87 | ### :scroll: Output Format
88 | Print "Even" if the number is even, and "Odd" if the number is odd.
89 |
90 | ### :pencil2: Sample Input
91 | ```
92 | 4
93 | ```
94 |
95 | ### :pencil2: Sample Output
96 | ```
97 | Even
98 | ```
99 |
100 | ## :bulb: Let's understand the problem a bit better.
101 |
102 | ### :grey_question: What is an integer?
103 | An integer is a number that can be represented as a whole number. In other words, it is a number without any fractional part. For example, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
104 |
105 | ### :grey_question: What is an odd number?
106 | An odd number is a number that is not divisible by 2. For example, 1, 3, 5, 7, 9, 11, 13, 15
107 |
108 | ### :grey_question: What is an even number?
109 | An even number is a number that is divisible by 2. For example, 2, 4, 6, 8, 10
110 |
111 | ### :grey_question: How do we determine if a number is odd or even?
112 | We can use the modulo operator (`%`) to determine if a number is odd or even. If the remainder of the number after division by 2 is 0, it is even. Otherwise, it is odd.
113 |
114 | ### :grey_question: How do we check if a number is odd or even?
115 |
116 | ```javascript
117 | // Assuming the first element in userInput is the number to check
118 | const numberToCheck = parseInt(userInput[0]);
119 |
120 | // Check if the number is odd or even
121 | if (numberToCheck % 2 === 0) {
122 | console.log("Even");
123 | }
124 | else {
125 | console.log("Odd");
126 | }
127 | ```
128 |
129 | ## :white_check_mark: Final Solution
130 | ```javascript
131 | // Getting input via STDIN
132 | const readline = require("readline");
133 |
134 | const inp = readline.createInterface({
135 | input: process.stdin
136 | });
137 |
138 | const userInput = [];
139 |
140 | inp.on("line", (data) => {
141 | userInput.push(data);
142 | });
143 |
144 | inp.on("close", () => {
145 | // start-here
146 | // Your code goes here … replace the below line with your code logic
147 |
148 | // Assuming the first element in userInput is the number to check
149 | const numberToCheck = parseInt(userInput[0]);
150 |
151 | // Check if the number is odd or even
152 | if (numberToCheck % 2 === 0) {
153 | console.log("Even");
154 | } else {
155 | console.log("Odd");
156 | }
157 |
158 | // end-here
159 | });
160 | ```
161 | ## :bulb: Explanation
162 |
163 | 1. `const numberToCheck = parseInt(userInput[0]);`
164 | - This line assumes that the first element in the `userInput` array contains the number you want to check (as per the problem statement). It uses `parseInt()` to convert the string representation of the number into an actual integer. This step is necessary because user input is initially collected as strings, and we want to perform numerical operations.
165 |
166 | 2. `if (numberToCheck % 2 === 0) {`
167 | - This line checks if `numberToCheck` is divisible evenly by 2. The `%` operator gives the remainder after division. So, `numberToCheck % 2 === 0` checks if the remainder is 0, indicating that the number is even.
168 |
169 | 3. `console.log("Even");`
170 | - If the condition in the previous line is true (i.e., the number is even), this line prints "Even" to the console.
171 |
172 | 4. `} else {`
173 | - If the condition in the `if` statement is false (i.e., the number is not even), the code inside the `else` block will be executed.
174 |
175 | 5. `console.log("Odd");`
176 | - This line prints "Odd" to the console, indicating that the number is not even.
177 |
178 | So, in summary, the code takes user input, extracts the number to check, determines if it's even or odd using the modulo operator, and prints the result to the console. It's a simple and effective way to solve the Odd or Even Checker problem.
179 |
180 | ## :arrow_forward: What's Next?
181 |
182 | Let's solve more problems.
183 |
184 | ### :white_check_mark: Problem-Solving Checklist
185 |
186 | - [x] **Print the `userInput` array:**
187 | - This step helps in understanding the input format and allows us to visualize the data we're working with.
188 |
189 | - [x] **Spread values into variables:**
190 | - Assign meaningful variable names to different elements in the `userInput` array. For example, `numberToCheck` and `numberToPrint` are good choices.
191 |
192 | - [x] **Convert input values to the desired data type:**
193 | - Since the input values are initially collected as strings, use appropriate conversion functions (`parseInt`, `parseFloat`, etc.) to convert them to the desired data type.
194 |
195 | - [x] **Proceed to solve the problem:**
196 | - Apply the necessary logic to solve the specific problem using the variables created. Break down the problem into smaller steps if needed.
197 |
198 | Now that you've learned how to solve a problem, let's move on to the next problem in the series.
199 |
200 | ## :mortar_board: Beginner-Friendly Problem Categories
201 |
202 | Welcome, coding enthusiast! 🚀 If you're just starting your coding journey, consider following these problem categories to enhance your skills and build a solid foundation:
203 |
204 | - Input/Output
205 | - Absolute Beginner
206 | - Basics
207 | - Maths
208 | - Array
209 | - String
210 | - Looping
211 | - Patterns
212 |
213 | ---
214 |
215 | *Thank you for taking the time to read my article. Your engagement is the driving force behind the words on these pages. Whether you found information, inspiration, or simply enjoyed the content, your presence is deeply appreciated. Writing is a shared journey, and I'm grateful to have you as a reader. Cheers to the joy of exploration and discovery! 🌟*
216 |
217 | *If you enjoyed the article, consider giving it more stars!*
218 |
219 | *With gratitude,*
220 |
221 | *Pugazharasan C*
--------------------------------------------------------------------------------
/OLD/CODEKATA JS.md:
--------------------------------------------------------------------------------
1 | # CODEKATA JS
2 |
3 | ## Elevate Your Coding Skills with CodeKata
4 |
5 | Embark on a journey of coding excellence with CodeKata, a curated series of challenges designed by industry veterans from companies like Microsoft, Walmart, Samsung, and more.
6 |
7 | Practice on CodeKata to enhance your coding proficiency, level up your skills, and boost your chances of acing coding interviews.
8 |
9 | ## Diverse Challenges Await
10 |
11 | Explore a range of coding challenges across categories like Absolute Beginner, Mathematics, Arrays, Strings, and more. CodeKata caters to all skill levels, making it ideal for both novice and experienced coders.
12 |
13 | ## Master JavaScript Problem Solving
14 |
15 | Building on the basics covered in [our introductory guide](README.md), dive into real-world problem-solving with JavaScript on CodeKata. Hone your skills, tackle challenges across domains, and elevate your coding prowess through practical exercises.
16 |
17 | Now, let's dive into problem-solving on CodeKata. To get started, visit [CodeKata on GUVI](https://www.guvi.in/code-kata) and explore a curated series of challenges across different categories. Whether you're an absolute beginner or an experienced coder, CodeKata provides a range of tiles to suit every skill level and interest.
18 |
19 |
20 | # User Input in JavaScript
21 |
22 | JavaScript is a language that is not inherently designed for obtaining basic user input. However, with the help of Node.js packages, we can facilitate the process of receiving user input.
23 |
24 | ## Default Input Code
25 |
26 | To gather user input in JavaScript, you can use the following default code:
27 |
28 | ```javascript
29 | // Getting input via STDIN
30 | const readline = require("readline");
31 |
32 | const inp = readline.createInterface({
33 | input: process.stdin
34 | });
35 |
36 | const userInput = [];
37 |
38 | inp.on("line", (data) => {
39 | userInput.push(data);
40 | });
41 |
42 | inp.on("close", () => {
43 | // start-here
44 | // Your code goes here … replace the below line with your code logic
45 |
46 | console.log(userInput);
47 |
48 | // end-here
49 | });
50 | ```
51 |
52 | Replace the `console.log(userInput);` line with your actual code logic for processing the user input.
53 |
54 | ## Explanation
55 |
56 | :beginner: **Note for Beginners:**
57 | Understanding the intricacies of this basic snippet may not be crucial at the start. Instead, focus on utilizing the data in the `userInput` array to solve problems in your CodeKata challenges. As you progress, you'll become more familiar with handling user input and can delve deeper into the code details.
58 |
59 | 1. `const readline = require("readline");`
60 | - Import the `readline` module, a utility for reading data from a readable stream, using the `require` function.
61 |
62 | 2. `const inp = readline.createInterface({
63 | input: process.stdin
64 | });`
65 | - Create an interface (`inp`) for reading input. Specify that the input should come from the standard input (`stdin`) stream.
66 |
67 | 3. `const userInput = [];`
68 | - Initialize an empty array called `userInput` to store the user's input.
69 |
70 | 4. `inp.on("line", (data) => {
71 | userInput.push(data);
72 | });`
73 | - Set up an event listener on the `line` event of the `inp` interface. When a line of input is received, the provided callback function is executed, pushing the input data into the `userInput` array.
74 |
75 | 5. `inp.on("close", () => {
76 | console.log(userInput);
77 | });`
78 | - Set up another event listener on the `close` event of the `inp` interface. When the input stream is closed (no more data to read), the provided callback function is executed. This is where you can place your code logic. In the example, it prints the collected `userInput` array to the console.
79 |
80 | # Let's Solve a Problem
81 |
82 | ## Odd or Even Checker
83 |
84 | ### Problem Description
85 | You are tasked with creating a program that determines whether a given number is odd or even.
86 | > This section provides an explanation of the problem you are required to solve. It outlines the task or challenge you need to address through your program.
87 | ### Input Format
88 | There will be ony line of input, which contains a single integer.
89 | > This section provides the format of the input data you are required to process. It also explains the data type of the input data.
90 | ### Output Format
91 | Print "Even" if the number is even, and "Odd" if the number is odd.
92 | > This section provides the format of the output data you are required to generate. It also explains the data type of the output data.
93 | ### Sample Input
94 | ```
95 | 4
96 | ```
97 |
98 | ### Sample Output
99 | ```
100 | Even
101 | ```
102 | ## Let's understand the problem a bit better.
103 |
104 | ### What is an integer?
105 | An integer is a number that can be represented as a whole number. In other words, it is a number without any fractional part. For example, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
106 |
107 | ### What is an odd number?
108 | An odd number is a number that is not divisible by 2. For example, 1, 3, 5, 7, 9, 11, 13, 15
109 |
110 | ### What is an even number?
111 | An even number is a number that is divisible by 2. For example, 2, 4, 6, 8, 10
112 |
113 | ### How do we determine if a number is odd or even?
114 | We can use the modulo operator (`%`) to determine if a number is odd or even. If the remainder of the number after division by 2 is 0, it is even. Otherwise, it is odd.
115 |
116 | ### How do we check if a number is odd or even?
117 |
118 | ```javascript
119 | // Assuming the first element in userInput is the number to check
120 | const numberToCheck = parseInt(userInput[0]);
121 |
122 | // Check if the number is odd or even
123 | if (numberToCheck % 2 === 0) {
124 | console.log("Even");
125 | }
126 | else {
127 | console.log("Odd");
128 | }
129 | ```
130 |
131 | ## Final Solution
132 | ```javascript
133 | // Getting input via STDIN
134 | const readline = require("readline");
135 |
136 | const inp = readline.createInterface({
137 | input: process.stdin
138 | });
139 |
140 | const userInput = [];
141 |
142 | inp.on("line", (data) => {
143 | userInput.push(data);
144 | });
145 |
146 | inp.on("close", () => {
147 | // start-here
148 | // Your code goes here … replace the below line with your code logic
149 |
150 | // Assuming the first element in userInput is the number to check
151 | const numberToCheck = parseInt(userInput[0]);
152 |
153 | // Check if the number is odd or even
154 | if (numberToCheck % 2 === 0) {
155 | console.log("Even");
156 | } else {
157 | console.log("Odd");
158 | }
159 |
160 | // end-here
161 | });
162 | ```
163 |
164 | ## Explanation
165 |
166 | 1. `const numberToCheck = parseInt(userInput[0]);`
167 | - This line assumes that the first element in the `userInput` array contains the number you want to check (as per the problem statement). It uses `parseInt()` to convert the string representation of the number into an actual integer. This step is necessary because user input is initially collected as strings, and we want to perform numerical operations.
168 |
169 | 2. `if (numberToCheck % 2 === 0) {`
170 | - This line checks if `numberToCheck` is divisible evenly by 2. The `%` operator gives the remainder after division. So, `numberToCheck % 2 === 0` checks if the remainder is 0, indicating that the number is even.
171 |
172 | 3. `console.log("Even");`
173 | - If the condition in the previous line is true (i.e., the number is even), this line prints "Even" to the console.
174 |
175 | 4. `} else {`
176 | - If the condition in the `if` statement is false (i.e., the number is not even), the code inside the `else` block will be executed.
177 |
178 | 5. `console.log("Odd");`
179 | - This line prints "Odd" to the console, indicating that the number is not even.
180 |
181 | So, in summary, the code takes user input, extracts the number to check, determines if it's even or odd using the modulo operator, and prints the result to the console. It's a simple and effective way to solve the Odd or Even Checker problem.
182 |
183 | ## What's Next?
184 |
185 | Let's solve more problems.
186 | ### Problem-Solving Checklist
187 |
188 | - [x] **Print the `userInput` array:**
189 | - This step helps in understanding the input format and allows us to visualize the data we're working with.
190 |
191 | - [x] **Spread values into variables:**
192 | - Assign meaningful variable names to different elements in the `userInput` array. For example, `numberToCheck` and `numberToPrint` are good choices.
193 |
194 | - [x] **Convert input values to the desired data type:**
195 | - Since the input values are initially collected as strings, use appropriate conversion functions (`parseInt`, `parseFloat`, etc.) to convert them to the desired data type.
196 |
197 | - [x] **Proceed to solve the problem:**
198 | - Apply the necessary logic to solve the specific problem using the variables created. Break down the problem into smaller steps if needed.
199 |
200 | Now that you've learned how to solve a problem, let's move on to the next problem in the series.
201 |
202 | ## Beginner-Friendly Problem Categories
203 |
204 | Welcome, coding enthusiast! 🚀 If you're just starting your coding journey, consider following these problem categories to enhance your skills and build a solid foundation:
205 |
206 | - Input/Output
207 | - Absolute Beginner
208 | - Basics
209 | - Maths
210 | - Array
211 | - String
212 | - Looping
213 | - Patterns
214 |
215 | ---
216 |
217 | *Thank you for taking the time to read my article. Your engagement is the driving force behind the words on these pages. Whether you found information, inspiration, or simply enjoyed the content, your presence is deeply appreciated. Writing is a shared journey, and I'm grateful to have you as a reader. Cheers to the joy of exploration and discovery! 🌟*
218 |
219 | *If you enjoyed the article, consider giving it more stars!*
220 |
221 | *With gratitude,*
222 |
223 | *Pugazharasan C*
224 |
--------------------------------------------------------------------------------
/README.MD:
--------------------------------------------------------------------------------
1 | # JavaScript Learning Repository
2 |
3 | Welcome to the JavaScript Learning Repository, your ultimate guide to mastering the intricacies of JavaScript programming! 🚀
4 |
5 | ## 🔍 Overview
6 |
7 | This repository serves as a comprehensive learning path, covering essential topics in JavaScript to equip both beginners and experienced developers. From fundamental JS basics to advanced concepts like functions, array methods (MRF), spread and rest operators, and array and object destructuring, this repository is your one-stop destination for honing your JavaScript skills.
8 |
9 | ## 🧭 What's Inside?
10 |
11 | 1. **JS Basics:** Delve into the core of JavaScript with detailed explanations and practical examples covering variables, data types, coding procedures, and more.
12 |
13 | 2. **Functions:** Explore the world of functions, from traditional named ones to modern arrow functions, and learn about IIFE (Immediately Invoked Function Expression) and handling arguments.
14 |
15 | 3. **Mastering JavaScript Array Methods (MRF):** Unlock the full potential of array methods such as `map`, `reduce`, and `filter` with real-world examples and tips for beginners.
16 |
17 | 4. **Spread and Rest Operator:** Understand the power of spreading and consolidating arrays and objects using these operators, enhancing your coding experience.
18 |
19 | 5. **Array and Object Destructuring:** Experience the elegance of simplifying your code with array and object destructuring, making it more concise and readable.
20 |
21 | ## 🚀 Getting Started
22 |
23 | Clone or fork this repository to embark on your JavaScript learning journey. Each section provides in-depth explanations, code examples, and practical exercises to solidify your understanding. Feel free to explore, experiment, and contribute, making this repository a dynamic, community-driven resource for JavaScript enthusiasts.
24 |
25 | Happy coding! 🌈✨
26 |
27 | # JavaScript Learning Index
28 |
29 | ## 📚 Table of Contents
30 | 1. [JS Basics](JS%20Basics.md)
31 | - [JavaScript Cheat Sheet](JS%20Basics.md#1-javascript-cheat-sheet)
32 | - [Introduction](JS%20Basics.md#11-introduction)
33 | - [Variable: The Cornerstone of Data Management 🧱](JS%20Basics.md#12-variable-the-cornerstone-of-data-management-)
34 | - [Hoisting: Elevating Declarations 🚀](JS%20Basics.md#13-hoisting-elevating-declarations-)
35 | - [Number: Measuring the Dimensions 📏](JS%20Basics.md#21-number-measuring-the-dimensions-)
36 | - [String: Weaving the Textual Threads 🧵](JS%20Basics.md#22-string-weaving-the-textual-threads-)
37 | - [Object: Architectural Blueprint 📐](JS%20Basics.md#23-object-architectural-blueprint-)
38 | - [Boolean: Construction Conditions 🚦](JS%20Basics.md#24-boolean-construction-conditions-)
39 | - [Undefined: Uncharted Territory 🗺️](JS%20Basics.md#25-undefined-uncharted-territory-️)
40 | - [Symbol: Unique Building ID 🔍](JS%20Basics.md#26-symbol-unique-building-id-)
41 | - [BigInt: Precision Engineering 🔧](JS%20Basics.md#27-bigint-precision-engineering-)
42 | - [Coding Procedure: Architectural Blueprint 📝](JS%20Basics.md#3-coding-procedure-architectural-blueprint-)
43 | - [Typecasting in JavaScript: Shaping the Material 🔄](JS%20Basics.md#4-typecasting-in-javascript-shaping-the-material-)
44 | - [String to Number: Forging Numeric Foundations 🔢](JS%20Basics.md#41-string-to-number-forging-numeric-foundations-)
45 | - [Array of Strings to Array of Numbers: Crafting Numeric Arrays 🛠️](JS%20Basics.md#42-array-of-strings-to-array-of-numbers-crafting-numeric-arrays-️)
46 | - [Number to String: Molding Textual Structures 🖌️](JS%20Basics.md#43-number-to-string-molding-textual-structures-️)
47 | - [JavaScript Operators: Navigating the Blueprint 🚀](JS%20Basics.md#5-javascript-operators-navigating-the-blueprint-)
48 | - [Arithmetic Operators: Crafting Mathematical Foundations 📐](JS%20Basics.md#51-arithmetic-operators-crafting-mathematical-foundations-)
49 | - [Relational Operators: Comparing Blueprints 🔄](JS%20Basics.md#52-relational-operators-comparing-blueprints-)
50 | - [Logical Operators: Navigating Expressive Pathways 🛤️](JS%20Basics.md#53-logical-operators-navigating-expressive-pathways-️)
51 | - [Assignment Operators: Crafting Variable Destinies 🎨](JS%20Basics.md#54-assignment-operators-crafting-variable-destinies-)
52 | - [Conditional Operator: Navigating Decision Crossroads 🛤️](JS%20Basics.md#55-conditional-operator-navigating-decision-crossroads-️)
53 | - [Bitwise Operators: Weaving Binary Narratives 🧵](JS%20Basics.md#56-bitwise-operators-weaving-binary-narratives-)
54 | - [Conditional Statements: Guiding Code Through Decision Crossroads 🚦](JS%20Basics.md#57-conditional-statements-guiding-code-through-decision-crossroads-)
55 | - [Looping Statements: Constructing Repetitive Structures 🏗️](JS%20Basics.md#6-looping-statements-constructing-repetitive-structures-️)
56 | - [While loop: Laying the Bricks 🧱](JS%20Basics.md#61-while-loop-laying-the-bricks-)
57 | - [For loop: Blueprinting the Iterations 🏗️](JS%20Basics.md#62-for-loop-blueprinting-the-iterations-️)
58 | - [do...while loop: Building with Perseverance 🏢](JS%20Basics.md#63-dowhile-loop-building-with-perseverance-)
59 | - [Branching Statement: Choosing Paths Wisely 🛣️](JS%20Basics.md#7-branching-statement-choosing-paths-wisely-️)
60 | - [Switch Statement: Navigating the Options 🔄](JS%20Basics.md#71-switch-statement-navigating-the-options-)
61 | - [Break and Continue: Controlling the Flow 🚦](JS%20Basics.md#8-break-and-continue-controlling-the-flow-)
62 | - [Break: Halting Execution 🛑](JS%20Basics.md#81-break-halting-execution-)
63 | - [Continue: Skipping Ahead ⏩](JS%20Basics.md#82-continue-skipping-ahead-)
64 | - [Other Loops: Exploring Diversity 🔄](JS%20Basics.md#9-other-loops-exploring-diversity-)
65 | - [For...in Loop: Mapping the Terrain 🗺️](JS%20Basics.md#91-forin-loop-mapping-the-terrain-️)
66 | - [For...of Loop: Embracing the Values 🔄](JS%20Basics.md#92-forof-loop-embracing-the-values-)
67 | 2. [All About Console](console.md)
68 | - [🖥️ Case File: The Mysterious Bug (aka) console.log()](console.md#️-case-file-the-mysterious-bug)
69 | - [⚠️ Case File: The Warning Signs (aka) console.warn()](console.md#️-case-file-the-warning-signs)
70 | - [🚨 Case File: Error Unleashed (aka) console.error()](console.md#-case-file-error-unleashed)
71 | - [📊 Case File: Tabular Investigation (aka) console.table()](console.md#-case-file-tabular-investigation)
72 | - [⏰ Case File: Timing Is Everything (aka) console.time()](console.md#-case-file-timing-is-everything)
73 | - [ℹ️ Case File: Information Unveiled (aka) console.info()](console.md#ℹ️-case-file-information-unveiled)
74 | - [✔️ Case File: Assertion in Action (aka) console.assert()](console.md#️-case-file-assertion-in-action)
75 | - [📚 Case File: Grouping Evidence (aka) console.group()](console.md#-case-file-grouping-evidence)
76 | - [🔢 Case File: Counting Clues (aka) console.count()](console.md#-case-file-counting-clues)
77 | - [🧹 Case File: Clearing the Path (aka) console.clear()](console.md#-case-file-clearing-the-path)
78 |
79 | 3. [Functions](Functions.md)
80 | - [JavaScript Functions: A Love Story ❤️](Functions.md#javascript-functions-a-love-story-️)
81 | - [The Serenade of Functions 🎶](Functions.md#the-serenade-of-functions-)
82 | - [Love at First Sight: Named Functions 💘](Functions.md#love-at-first-sight-named-functions-)
83 | - [The Mysterious Affair: Anonymous Functions 🌌](Functions.md#the-mysterious-affair-anonymous-functions-)
84 | - [Modern Romance: Arrow Functions (ES6) 🏹](Functions.md#modern-romance-arrow-functions-es6-)
85 | - [Love at First Sight: IIFE (Immediately Invoked Function Expression) ⚡](Functions.md#love-at-first-sight-iife-immediately-invoked-function-expression-)
86 | - [The Symphony of Devotion: The `return` Keyword 🎻](Functions.md#the-symphony-of-devotion-the-return-keyword-)
87 | - [Mutual Understanding: Handling Arguments 🤝](Functions.md#mutual-understanding-handling-arguments-)
88 | - [Infinite Love: Rest Parameters 💖](Functions.md#infinite-love-rest-parameters-)
89 | - [Love Table: Comparing Different Wormy Functions 🐛💖](Functions.md#love-table-comparing-different-wormy-functions-)
90 |
91 |
92 |
93 | 3. [MRF](MRF.md)
94 | - [Mastering JavaScript Array Methods: Unveiling the Power 🔍](MRF.md#-mastering-javascript-array-methods-unveiling-the-power-)
95 | - [1. `map` Method: Transforming with Elegance ✨](MRF.md#1-map-method-transforming-with-elegance-)
96 | - [2. `reduce` Method: Crafting a Singular Masterpiece 🖌️](MRF.md#2-reduce-method-crafting-a-singular-masterpiece-)
97 | - [3. `filter` Method: Summoning the Chosen Ones 🧙♂️](MRF.md#3-filter-method-summoning-the-chosen-ones-)
98 | - [🌟 Apprentice Tips](MRF.md#-apprentice-tips)
99 | - [🧙♂️ JavaScript Array Methods Almanac 📜](MRF.md#-javascript-array-methods-almanac-)
100 |
101 |
102 | 4. [Spread and Rest Operator](Spread%20and%20Rest%20Operator.md)
103 | - [Introduction](Spread%20and%20Rest%20Operator.md#spread-and-rest-a-ponniyin-selvan-code-saga)
104 | - [Spread Operator: Unleashing Power 💥](Spread%20and%20Rest%20Operator.md#spread-operator-unleashing-power)
105 | - [Rest Operator: Consolidating Forces 🤝](Spread%20and%20Rest%20Operator.md#rest-operator-consolidating-forces)
106 | - [Functions with Spread and Rest](Spread%20and%20Rest%20Operator.md#functions-with-spread-and-rest)
107 | - [Visual Reference: Spread and Rest Operators](Spread%20and%20Rest%20Operator.md#visual-reference-spread-and-rest-operators)
108 |
109 | 5. [Array and Object Destructuring](Destructuring/README.md)
110 | - [Array Destructuring: A Tamil Symphony 🎶](Destructuring/README.md#array-destructuring-a-tamil-symphony)
111 | - [Object Destructuring: Building a Furnished House 🏡](Destructuring/README.md#object-destructuring-building-a-furnished-house)
112 | 6. [🚀 OOP in JavaScript - Unveiling the Magic!](OOPs%20in%20JS.md)
113 | - [🌈 Chapter 1: What is Object-Oriented Programming (OOP)?](OOPs%20in%20JS.md#-chapter-1-what-is-object-oriented-programming-oop)
114 | - [🌈 Chapter 2: Understanding the Basics of Prototype](OOPs%20in%20JS.md#-chapter-2-understanding-the-basics-of-prototype)
115 | - [:european\_castle: Unveiling the Castle of Classes](OOPs%20in%20JS.md#european_castle-unveiling-the-castle-of-classes)
116 | - [:construction\_worker: Constructors at Work](OOPs%20in%20JS.md#construction_worker-constructors-at-work)
117 | - [:key: Unveiling the Mysteries of Properties](OOPs%20in%20JS.md#key-unveiling-the-mysteries-of-properties)
118 | - [:sparkles: Enchanting Methods: The Magic Within](OOPs%20in%20JS.md#sparkles-enchanting-methods-the-magic-within)
119 | - [:crystal\_ball: Unveiling the Magic of Getters and Setters](OOPs%20in%20JS.md#crystal_ball-unveiling-the-magic-of-getters-and-setters)
120 | 1. [🌌The Four Pillars of JavaScript Magic](OOPs%20in%20JS.2.md)
121 | - [:crystal\_ball: Abstraction: Painting with Broad Strokes](OOPs%20in%20JS.2.md#crystal_ball-abstraction-painting-with-broad-strokes)
122 | - [:closed\_lock\_with\_key: Encapsulation: Safeguarding Mysteries](OOPs%20in%20JS.2.md#closed_lock_with_key-encapsulation-safeguarding-mysteries)
123 | - [:family: Inheritance: Bloodlines of Magic](OOPs%20in%20JS.2.md#family-inheritance-bloodlines-of-magic)
124 | - [:crystal\_ball: Polymorphism: Many Forms of Magic](OOPs%20in%20JS.2.md#crystal_ball-polymorphism-many-forms-of-magic)
125 | 2. [Dancing with the DOM: A Symphony of Web Magic ✨](DOM/DOM1.md#dancing-with-the-dom-a-symphony-of-web-magic-)
126 | - [Introduction: Unveiling the Enchantment of DOM](DOM/DOM1.md#introduction-unveiling-the-enchantment-of-dom)
127 | - [The Birth of Elements: createElement and setAttribute 💫](DOM/DOM1.md#the-birth-of-elements-createelement-and-setattribute-)
128 | - [The Quest for Identity: getElementById and the Mystical QuerySelectors 🌟](DOM/DOM1.md#the-quest-for-identity-getelementbyid-and-the-mystical-queryselectors-)
129 | - [Words Unveiled: innerHTML vs innerText 📜](DOM/DOM1.md#words-unveiled-innerhtml-vs-innertext-)
130 | - [Harmony in Unity: appendChild vs append 🎵](DOM/DOM1.md#harmony-in-unity-appendchild-vs-append-)
131 | - [Conclusion: The Everlasting Dance of DOM](#conclusion-the-everlasting-dance-of-dom)
132 | 3. [Windows into the Web: Unveiling Common Utilities and Magical Events ✨](DOM/DOM2.md#windows-into-the-web-unveiling-common-utilities-and-magical-events-)
133 | - [The Maestro's Wand: Common Utility Functions 🎭](DOM/DOM2.md#the-maestros-wand-common-utility-functions-)
134 | - [The Sands of Time: setTimeout vs setInterval ⏰](DOM/DOM2.md#the-sands-of-time-settimeout-vs-setinterval-)
135 | - [Whispers in the Breeze: prompt, Alert, and confirm 🗣️](DOM/DOM2.md#whispers-in-the-breeze-prompt-alert-and-confirm-️)
136 | - [Dance of the Elements: Working with Events 💃](DOM/DOM2.md#dance-of-the-elements-working-with-events-)
137 | - [Conclusion: Awe of the Wonders Within the Window Object](#conclusion-awe-of-the-wonders-within-the-window-object)
138 | 1. [Async Programming in JavaScript](Async%20Programming/Async%20Programming.md)
139 |
140 | - [Sync Vs Async: Unraveling the Plot](Async%20Programming/Async%20Programming.md#sync-vs-async-unraveling-the-plot)
141 | - [How JS Handles Async Processes: Behind the Scenes](Async%20Programming/Async%20Programming.md#how-js-handles-async-processes-behind-the-scenes)
142 | - [Callbacks in JavaScript: A "Vikram Vedha" Tale 🎬](Async%20Programming/Callback.md)
143 |
144 | - [Promises in JavaScript: A Cinematic Code Saga 🌟](Async%20Programming/Promise.Movie.md)
145 | - [Async/Await: Scripting the Next Blockbuster 🍿🚀](Async%20Programming/AsyncAndAwait.md)
146 |
147 | - [Navigating the Cinematic Code Tale: Try-Catch Chronicles](Async%20Programming/AsyncAndAwait.md#navigating-the-cinematic-code-tale-try-catch-chronicles)
148 |
149 |
150 | ## 🌟 Conclusion
151 |
152 | Congratulations on reaching the end of this JavaScript Learning Repository! 🎉 Whether you are a beginner taking your first steps or an experienced developer refining your skills, I hope this journey has been both informative and enjoyable.
153 |
154 | Remember, the world of JavaScript is vast and ever-evolving. Keep exploring, practicing, and embracing the joy of coding. Feel free to contribute to this repository, share your insights, and engage with the vibrant JavaScript community.
155 |
156 | Happy coding, and may your JavaScript adventures be filled with creativity and success! 🚀💻✨
157 |
158 | ---
159 |
160 | *Thank you for being a part of this learning experience. Your enthusiasm and dedication make the coding community vibrant and inspiring. If you found this repository helpful, consider sharing it with others and spreading the love for JavaScript!*
161 |
162 | *With gratitude,*
163 |
164 | *Pugazharasan C*
165 |
--------------------------------------------------------------------------------
/Async Programming/Promise.Movie.md:
--------------------------------------------------------------------------------
1 | Certainly! Let's infuse the movie theme throughout the document for a more cinematic experience:
2 |
3 | ---
4 |
5 | # Promises in JavaScript: A Cinematic Code Saga 🌟
6 |
7 | ## Unveiling the Promise
8 |
9 | In the realm of JavaScript, a Promise unfolds its narrative much like an unexpected plot twist in a suspenseful movie – a potent mechanism for managing asynchronous operations. It represents the eventual completion or failure of an asynchronous task, offering a structured way to handle outcomes.
10 |
11 | ## Promise States: A Visual Masterpiece
12 |
13 | A Promise, like a movie in production, can exist in one of three states:
14 |
15 | - **Pending:** The opening scene; the promise is awaiting either fulfillment or rejection.
16 | - **Fulfilled:** The climax; the operation completed successfully, and the promise holds a resulting value.
17 | - **Rejected:** The plot twist; an error occurred during the operation, and the promise contains a reason for the failure.
18 |
19 | *Visual Representation:*
20 |
21 | 🎬 Async Operation (Pending) ➡️ Error (Rejected)
22 |
23 | ➡️ Fulfilled (Settled)
24 | |----------- Settled -----------| |----------- Unsettled -----------|
25 |
26 | This visual guide paints the canvas of Promise states, unfolding like scenes in a captivating movie.
27 |
28 | ## Crafting a Promise: Behind the Scenes
29 |
30 | In the grand production of JavaScript, a Promise is an object representing the eventual completion or failure of an asynchronous operation. Promises are the actors that bring order to the chaos, making it easier to write asynchronous code in a well-organized and readable manner.
31 |
32 | *Script Excerpt:*
33 |
34 | ```javascript
35 | const myPromise = new Promise((resolve, reject) => {
36 | // Simulating an asynchronous operation (e.g., fetching data from an API)
37 | setTimeout(() => {
38 | const success = true; // Simulating a successful operation, set to false for failure
39 |
40 | if (success) {
41 | // If the operation is successful, resolve the Promise
42 | resolve('Data successfully fetched');
43 | } else {
44 | // If there's an error, reject the Promise
45 | reject('Error fetching data');
46 | }
47 | }, 2000); // Simulating a delay of 2 seconds
48 | });
49 | ```
50 |
51 | *Behind the Scenes Commentary:*
52 |
53 | In this scene, inside the Promise constructor, there's a simulated asynchronous operation using `setTimeout`. If the operation is successful, the Promise is resolved with a message; otherwise, it is rejected with an error message. The suspense builds as the audience wonders about the fate of the asynchronous operation.
54 |
55 | ## Handling Promises: A Director's Cut with `then()`, `catch()`, and `finally()`
56 |
57 | In the script of JavaScript Promises, the `then()`, `catch()`, and `finally()` methods are the director's tools, managing the highs and lows of the plot. Here's a glimpse of their usage:
58 |
59 | ### `then()` method:
60 |
61 | It is used to handle the fulfillment (success) of a Promise.
62 | It takes one or two optional callback functions as arguments.
63 | The first callback is called when the Promise is resolved.
64 | The second callback (optional) is called when the Promise is rejected.
65 |
66 | *Script Excerpt:*
67 |
68 | ```javascript
69 | // Using then for handling fulfillment
70 | promiseObject.then(
71 | (result) => {
72 | // Handle success
73 | console.log(result);
74 | },
75 | (error) => {
76 | // Handle rejection (optional)
77 | console.error(error);
78 | }
79 | );
80 | ```
81 |
82 | *Behind the Scenes Commentary:*
83 |
84 | In this riveting scene, the `then` method orchestrates the success and failure of the Promise, much like a director guiding actors through crucial moments in the storyline.
85 |
86 | ### Chaining then methods: A Sequel in the Making
87 |
88 | You can chain multiple `then` methods to handle a sequence of asynchronous operations. Each `then` in the chain receives the result of the previous `then`'s callback.
89 |
90 | *Script Excerpt:*
91 |
92 | ```javascript
93 | promiseObject
94 | .then((result1) => {
95 | // Handle result1
96 | return result1 + 1;
97 | })
98 | .then((result2) => {
99 | // Handle result2 (which is result1 + 1)
100 | console.log(result2);
101 | })
102 | ```
103 |
104 | *Behind the Scenes Commentary:*
105 |
106 | The plot thickens as `then` methods are chained together, forming a sequel of asynchronous operations. Each `then` builds upon the result of the previous one, creating a storyline filled with twists and turns.
107 |
108 | ### `catch()` method: Navigating Through Plot Twists
109 |
110 | It is used to handle the rejection (failure) of a Promise.
111 | It takes a callback function that is called when the Promise is rejected.
112 | It is an alternative to providing the rejection callback in the `then` method.
113 |
114 | *Script Excerpt:*
115 |
116 | ```javascript
117 | promiseObject.catch((error) => {
118 | // Handle rejection
119 | console.error(error);
120 | });
121 | ```
122 |
123 | *Behind the Scenes Commentary:*
124 |
125 | As the plot takes an unexpected turn, the `catch` method swoops in to handle the rejection, much like a skilled director navigating through plot twists.
126 |
127 | ### `finally()` method: The Grand Finale
128 |
129 | The `finally` method is used to specify a callback function to be executed regardless of whether the Promise is fulfilled or rejected. It's often used for cleanup operations.
130 |
131 | *Script Excerpt:*
132 |
133 | ```javascript
134 | promiseObject
135 | .then((result) => {
136 | // Handle success
137 | console.log(result);
138 | })
139 | .catch((error) => {
140 | // Handle rejection
141 | console.error(error);
142 | })
143 | .finally(() => {
144 | // This block will be executed regardless of the Promise's state
145 | console.log('Finally block executed');
146 | });
147 | ```
148 |
149 | *Behind the Scenes Commentary:*
150 |
151 | As the grand finale approaches, the `finally` method takes center stage, ensuring that the designated block of code is executed regardless of how the Promise concludes. It's the concluding scene, leaving a lasting impression on the audience.
152 |
153 |
154 |
155 | ## `Resolve()` and `Reject()`: Static Methods as Plot Enablers
156 |
157 | Certainly! In the world of JavaScript Promises, the `resolve()` and `reject()` methods are the unseen scriptwriters, crafting the plot by creating and handling resolved or rejected Promise instances.
158 |
159 | ### `Promise.resolve()` method: Writing the Resolution Scene
160 |
161 | *Script Excerpt:*
162 |
163 | ```javascript
164 | const resolvedPromise = Promise.resolve('Resolved value');
165 |
166 | resolvedPromise.then((result) => {
167 | console.log(result); // Output: Resolved value
168 | });
169 | ```
170 |
171 | *Behind the Scenes Commentary:*
172 |
173 | In this empowering scene, `Promise.resolve()` takes the lead, creating a Promise that is immediately resolved with the value 'Resolved value'. The audience witnesses the power of resolution in action.
174 |
175 | ```javascript
176 | const anotherPromise = new Promise((resolve, reject) => {
177 | // Some asynchronous operation
178 | resolve('Async operation resolved');
179 | });
180 |
181 | const resolvedWithPromise = Promise.resolve(anotherPromise);
182 |
183 | resolvedWithPromise.then((result) => {
184 | console.log(result); // Output: Async operation resolved
185 | });
186 | ```
187 |
188 | Here, `Promise.resolve()` is used to create a Promise that is resolved with the result of the asynchronous operation represented by `anotherPromise`. The plot thickens as the resolution unfolds.
189 |
190 | ### `Promise.reject()` method: The Dramatic Turn
191 |
192 | *Script Excerpt:*
193 |
194 | ```javascript
195 | const rejectedPromise = Promise.reject('Error reason');
196 |
197 | rejectedPromise.catch((error) => {
198 | console.error(error); // Output: Error reason
199 | });
200 | ```
201 |
202 | *Behind the Scenes Commentary:*
203 |
204 | In a dramatic turn of events, `Promise.reject()` sets the stage for conflict, creating a Promise that is immediately rejected with the reason 'Error reason'. The audience braces for impact as rejection takes center stage.
205 |
206 | ```javascript
207 | const anotherPromise = new Promise((resolve, reject) => {
208 | // Some asynchronous operation that fails
209 | reject('Async operation failed');
210 | });
211 |
212 | const rejectedWithPromise = Promise.reject(anotherPromise);
213 |
214 | rejectedWithPromise.catch((error) => {
215 | console.error(error); // Output: Async operation failed
216 | });
217 | ```
218 |
219 | In this scenario, `Promise.reject()` is used to craft a plot where a Promise is rejected with the reason from the failed asynchronous operation represented by `anotherPromise`. The plot thickens with unexpected turns.
220 |
221 | These static methods are the unseen architects of the storyline, shaping the plot with resolutions and rejections, much like behind-the-scenes scriptwriters crafting the twists and turns.
222 |
223 | ## Chaining Promises: Sequencing Asynchronous Operations – A Script Continuation
224 |
225 | Chaining promises in JavaScript is a technique where each scene builds upon the previous, creating a sequence of asynchronous operations. The code becomes a screenplay, with each `then` and `catch` block contributing to the unfolding drama.
226 |
227 | ### Basic Promise Structure: Setting the Stage
228 |
229 | *Script Excerpt:*
230 |
231 | ```javascript
232 | // Basic Promise Structure
233 | const myPromise = new Promise((resolve, reject) => {
234 | // Asynchronous operation
235 | // If successful, call resolve with a result
236 | // If there's an error, call reject with an error
237 | });
238 | ```
239 |
240 | *Behind the Scenes Commentary:*
241 |
242 | The stage is set with the basic promise structure, where a promise represents the eventual completion or failure of an asynchronous operation. The suspense builds as the audience wonders about the upcoming scenes.
243 |
244 | ### Chaining `then` for Sequencing: A Symphonic Composition
245 |
246 | *Script Excerpt:*
247 |
248 | ```javascript
249 | myPromise
250 | .then((result1) => {
251 | // Handle result1
252 | return result1 + 1; // Can return a value or a new promise
253 | })
254 | .then((result2) => {
255 | // Handle the result of the second asynchronous operation
256 | console.log(result2);
257 | });
258 | ```
259 |
260 | *Behind the Scenes Commentary:*
261 |
262 | The symphony begins as `then` methods are chained together, creating a harmonious composition. Each `then` block receives the result of the previous one, contributing to the seamless flow of the narrative.
263 |
264 | ### Chaining Promises for Sequential Operations: A Script Continuation
265 |
266 | *Script Excerpt:*
267 |
268 | ```javascript
269 | asyncOperation1()
270 | .then((result1) => {
271 | // Handle result1
272 | return asyncOperation2(result1);
273 | })
274 | .then((result2) => {
275 | // Handle result2 (which is the result of asyncOperation2)
276 | return asyncOperation3(result2);
277 | })
278 | .then((result3) => {
279 | // Handle result3 (which is the result of asyncOperation3)
280 | console.log(result3);
281 | })
282 | .catch((error) => {
283 | // Handle errors in any stage of the sequence
284 | console.error(error);
285 | });
286 | ```
287 |
288 | *Behind the Scenes Commentary:*
289 |
290 | The plot thickens as promises are chained for sequential operations. Each `then` block builds upon the previous one, and the audience is taken on a journey through the interconnected scenes of asynchronous operations.
291 |
292 | Chaining promises transforms the code into a compelling script, making it more readable and avoiding the chaos of callback hell. It ensures a clear and captivating flow of execution, much like a well-orchestrated movie screenplay.
293 |
294 | ## Promise Methods: The Arsenal Unleashed
295 |
296 | Certainly! Let's dive deeper into the arsenal of Promise methods, each playing a unique role in our cinematic code saga.
297 |
298 | ### 1. `Promise.all()`: Harmony in Completion
299 |
300 | *Script Excerpt:*
301 |
302 | ```javascript
303 | const promises = [promise1, promise2, promise3];
304 |
305 | Promise.all(promises)
306 | .then((results) => {
307 | console.log("All promises fulfilled:", results);
308 | })
309 | .catch((error) => {
310 | console.error("At least one promise rejected:", error);
311 | });
312 | ```
313 |
314 | *Behind the Scenes Commentary:*
315 |
316 | In this powerful scene, `Promise.all()` takes the stage, orchestrating harmony in completion. All promises must fulfill their roles for the show to go on. If any promise falters, an unforeseen event takes place, echoing through the narrative.
317 |
318 | ### 2. `Promise.allSettled()`: Every Outcome Matters
319 |
320 | *Script Excerpt:*
321 |
322 | ```javascript
323 | Promise.allSettled([promise1, promise2, promise3])
324 | .then((results) => {
325 | console.log("All promises settled:", results);
326 | });
327 | ```
328 |
329 | *Behind the Scenes Commentary:*
330 |
331 | `Promise.allSettled()` emerges as the silent observer, waiting for every outcome to unfold. Regardless of success or failure, it captures the essence of each promise's journey, providing a comprehensive look behind the scenes.
332 |
333 | ### 3. `Promise.any()`: The Race to Success
334 |
335 | *Script Excerpt:*
336 |
337 | ```javascript
338 | Promise.any([promise1, promise2, promise3])
339 | .then((result) => {
340 | console.log("At least one promise fulfilled:", result);
341 | });
342 | ```
343 |
344 | *Behind the Scenes Commentary:*
345 |
346 | In a race against time, `Promise.any()` mirrors the thrilling pursuit of the first fulfilled promise. The narrative intensifies as promises compete for the spotlight, and the first one to succeed takes center stage.
347 |
348 | ### 4. `Promise.race()`: The Swift Revelation
349 |
350 | *Script Excerpt:*
351 |
352 | ```javascript
353 | Promise.race([promise1, promise2, promise3])
354 | .then((result) => {
355 | console.log("The first promise to settle:", result);
356 | });
357 | ```
358 |
359 | *Behind the Scenes Commentary:*
360 |
361 | `Promise.race()` unfolds as the swift revelation, showcasing the result of the first promise to settle. The narrative takes an unexpected turn, aligning with the first promise to either triumph or face a rapid downfall.
362 |
363 | ### Promise Methods Comparison: A Cinematic Spectrum
364 |
365 | *Comparison Scene:*
366 |
367 |
368 | | Method | Purpose | Resolves When | Rejects When |
369 | | -------------------- | -------------------------------------------------- | ------------------------------------------- | ------------------------------------------------------------- |
370 | | `Promise.all()` | Waits for all promises to fulfill | All promises fulfill | Any promise rejects |
371 | | `Promise.allSettled()` | Waits for all promises to settle | All promises settle (fulfilled or rejected) | N/A (Doesn't short-circuit on rejections) |
372 | | `Promise.any()` | Resolves with the first fulfilled promise | The first promise fulfills | All promises reject except the first one |
373 | | `Promise.race()` | Resolves or rejects with the first settled promise | The first promise settles | The first promise rejects or fulfills (whichever comes first) |
374 |
375 | *Scene Transition:*
376 |
377 | In this cinematic spectrum, each method plays a distinct role, offering flexibility in handling multiple promises. The scriptwriter can choose the method that best fits the desired narrative, creating a dynamic and engaging plot.
378 |
379 | ## Closing Scene: Understanding Promises
380 |
381 | Understanding Promises and their methods is a pivotal step in mastering the art of asynchronous JavaScript. The characters - `resolve()` and `reject()`, the chained promises, and the ensemble cast of `Promise.all()`, `Promise.allSettled()`, `Promise.any()`, and `Promise.race()` - contribute to a script filled with promise-induced excitement!
382 |
383 | In the upcoming sections, we'll embark on more advanced concepts, exploring the intricate plot twists of JavaScript's asynchronous landscape. Brace yourselves for a code narrative that rivals the most thrilling cinematic experiences! 🚀🍿🎬
384 |
--------------------------------------------------------------------------------
/OLD/Promise.md:
--------------------------------------------------------------------------------
1 | # Promises in JavaScript: A Promising Script 🌟
2 |
3 | ## Unveiling the Promise
4 |
5 | In the world of JavaScript, a Promise unfolds like a plot twist in a suspenseful movie – a powerful mechanism for managing asynchronous operations. It represents the eventual completion or failure of an asynchronous task, offering a structured way to handle outcomes.
6 |
7 | ## Promise States
8 |
9 | A Promise can exist in one of three states:
10 |
11 | - **Pending:** The initial state; the promise is awaiting either fulfillment or rejection.
12 | - **Fulfilled:** The operation completed successfully, and the promise holds a resulting value.
13 | - **Rejected:** An error occurred during the operation, and the promise contains a reason for the failure.
14 |
15 | ## Navigating Promise States: A Visual Guide
16 |
17 | ```mermaid
18 | graph LR
19 | P((Pending))
20 | F((Fulfilled))
21 | R((Rejected))
22 | S[Settled]
23 | U[Unsettled] -.- P
24 | P ==>|Async Operation| F
25 | P ==>|Error| R
26 | F -.- S
27 | R -.- S
28 | ```
29 |
30 | This visual representation illustrates the flow of Promise states from Pending to Fulfilled or Rejected based on the outcome of an asynchronous operation.
31 |
32 | ## Crafting a Promise
33 | In JavaScript, a Promise is an object representing the eventual completion or failure of an asynchronous operation. Promises are used to handle asynchronous operations, making it easier to write asynchronous code in a more organized and readable manner.
34 |
35 | Here's an example of how you can craft a Promise:
36 |
37 | ```javascript
38 | const myPromise = new Promise((resolve, reject) => {
39 | // Simulating an asynchronous operation (e.g., fetching data from an API)
40 | setTimeout(() => {
41 | const success = true; // Simulating a successful operation, set to false for failure
42 |
43 | if (success) {
44 | // If the operation is successful, resolve the Promise
45 | resolve('Data successfully fetched');
46 | } else {
47 | // If there's an error, reject the Promise
48 | reject('Error fetching data');
49 | }
50 | }, 2000); // Simulating a delay of 2 seconds
51 | });
52 | ```
53 | In this example:
54 |
55 | 1. Inside the Promise constructor, there's a simulated asynchronous operation using `setTimeout`.
56 | 2. If the operation is successful, the Promise is resolved with a message; otherwise, it is rejected with an error message.
57 |
58 | You can customize the constructor function to perform any asynchronous operation, such as making an API request, reading a file, or querying a database. The key is to ensure that the Promise is appropriately resolved or rejected based on the outcome of the asynchronous operation.
59 |
60 | ## Handling Promises: then(), catch() and finally()
61 | In JavaScript Promises, the `then` and `catch` methods are used to handle the resolution and rejection of a Promise, respectively. Here's a breakdown of their usage:
62 |
63 | 1. **`then` method:**
64 | - It is used to handle the fulfillment (success) of a Promise.
65 | - It takes one or two optional callback functions as arguments.
66 | - The first callback is called when the Promise is resolved.
67 | - The second callback (optional) is called when the Promise is rejected.
68 | - The `then` method returns a new Promise, allowing for chaining.
69 |
70 | ```javascript
71 | // Using then for handling fulfillment
72 | promiseObject.then(
73 | (result) => {
74 | // Handle success
75 | console.log(result);
76 | },
77 | (error) => {
78 | // Handle rejection (optional)
79 | console.error(error);
80 | }
81 | );
82 | ```
83 |
84 | 2. **Chaining `then` methods:**
85 | - You can chain multiple `then` methods to handle a sequence of asynchronous operations.
86 | - Each `then` in the chain receives the result of the previous `then`'s callback.
87 |
88 | ```javascript
89 | promiseObject
90 | .then((result1) => {
91 | // Handle result1
92 | return result1 + 1;
93 | })
94 | .then((result2) => {
95 | // Handle result2 (which is result1 + 1)
96 | console.log(result2);
97 | })
98 | ```
99 |
100 | 3. **`catch` method:**
101 | - It is used to handle the rejection (failure) of a Promise.
102 | - It takes a callback function that is called when the Promise is rejected.
103 | - It is an alternative to providing the rejection callback in the `then` method.
104 |
105 | ```javascript
106 | promiseObject.catch((error) => {
107 | // Handle rejection
108 | console.error(error);
109 | });
110 | ```
111 | Certainly! Let's add the `finally` method and modify the example to remove chaining:
112 |
113 |
114 | 1. **`finally` method:**
115 | - The `finally` method is used to specify a callback function to be executed regardless of whether the Promise is fulfilled or rejected.
116 | - It's often used for cleanup operations.
117 |
118 | ```javascript
119 | promiseObject
120 | .then((result) => {
121 | // Handle success
122 | console.log(result);
123 | })
124 | .catch((error) => {
125 | // Handle rejection
126 | console.error(error);
127 | })
128 | .finally(() => {
129 | // This block will be executed regardless of the Promise's state
130 | console.log('Finally block executed');
131 | });
132 | ```
133 |
134 | With the addition of the `finally` method, the provided callback will be executed after the Promise is settled, whether it's fulfilled or rejected. This is useful for performing cleanup or finalization steps.
135 |
136 | If you want to avoid chaining, you can structure your code like this:
137 |
138 | ```javascript
139 | promiseObject
140 | .then((result) => {
141 | // Handle success
142 | console.log(result);
143 | // Return a new Promise for the next step
144 | return someOtherPromise();
145 | })
146 | .catch((error) => {
147 | // Handle rejection
148 | console.error(error);
149 | })
150 | .finally(() => {
151 | // This block will be executed regardless of the Promise's state
152 | console.log('Finally block executed');
153 | });
154 | ```
155 |
156 | In this structure, each `then` block returns a new Promise for the next step, allowing you to handle asynchronous operations sequentially without chaining.
157 |
158 | 4. **Combining `then`, `catch` and `finally`:**
159 | - You can use both `then` and `catch` for more fine-grained control.
160 | - The `catch` method will catch any rejection that occurs in the preceding `then` methods in the chain.
161 |
162 | ```javascript
163 | promiseObject
164 | .then((result) => {
165 | // Handle success
166 | console.log(result);
167 | })
168 | .catch((error) => {
169 | // Handle rejection
170 | console.error(error);
171 | });
172 | .finally(() => {
173 | // This block will be executed regardless of the Promise's state
174 | console.log('Finally block executed');
175 | });
176 | ```
177 |
178 | Here, `then()` manages fulfilled promises, `catch()` handles rejections and `finally()` ensures a block of code is executed regardless of fulfillment or rejection.
179 |
180 | These methods provide a powerful way to structure and handle asynchronous code in a readable and organized manner.
181 |
182 |
183 | ## resolve() and reject(): Static Methods
184 | Certainly! In JavaScript Promises, the `Promise` object provides two static methods: `resolve()` and `reject()`. These methods are used to create and return resolved or rejected Promise instances, respectively.
185 |
186 | 1. **`Promise.resolve()` method:**
187 | - It returns a Promise object that is resolved with a given value or the result of another Promise.
188 | - If the provided value is a Promise, it is returned as is.
189 |
190 | ```javascript
191 | const resolvedPromise = Promise.resolve('Resolved value');
192 |
193 | resolvedPromise.then((result) => {
194 | console.log(result); // Output: Resolved value
195 | });
196 | ```
197 |
198 | In this example, `Promise.resolve()` creates a Promise that is immediately resolved with the value `'Resolved value'`.
199 |
200 | ```javascript
201 | const anotherPromise = new Promise((resolve, reject) => {
202 | // Some asynchronous operation
203 | resolve('Async operation resolved');
204 | });
205 |
206 | const resolvedWithPromise = Promise.resolve(anotherPromise);
207 |
208 | resolvedWithPromise.then((result) => {
209 | console.log(result); // Output: Async operation resolved
210 | });
211 | ```
212 |
213 | Here, `Promise.resolve()` is used to create a Promise that is resolved with the result of the asynchronous operation represented by `anotherPromise`.
214 |
215 | 2. **`Promise.reject()` method:**
216 | - It returns a Promise object that is rejected with a given reason (error).
217 | - Similar to `Promise.resolve()`, if the provided value is a Promise, it is returned as is.
218 |
219 | ```javascript
220 | const rejectedPromise = Promise.reject('Error reason');
221 |
222 | rejectedPromise.catch((error) => {
223 | console.error(error); // Output: Error reason
224 | });
225 | ```
226 |
227 | In this example, `Promise.reject()` creates a Promise that is immediately rejected with the reason `'Error reason'`.
228 |
229 | ```javascript
230 | const anotherPromise = new Promise((resolve, reject) => {
231 | // Some asynchronous operation that fails
232 | reject('Async operation failed');
233 | });
234 |
235 | const rejectedWithPromise = Promise.reject(anotherPromise);
236 |
237 | rejectedWithPromise.catch((error) => {
238 | console.error(error); // Output: Async operation failed
239 | });
240 | ```
241 |
242 | Here, `Promise.reject()` is used to create a Promise that is rejected with the reason from the failed asynchronous operation represented by `anotherPromise`.
243 |
244 | These static methods are handy for creating and handling Promises in scenarios where you want to immediately resolve or reject a Promise, or when dealing with asynchronous operations that return Promises.
245 |
246 | ## Chaining Promises: Sequencing Asynchronous Operations
247 |
248 | Chaining promises in JavaScript is a way to sequence asynchronous operations, making code more readable and avoiding callback hell. Here's a simple and easy-to-understand explanation:
249 |
250 | 1. **Basic Promise Structure:**
251 | - A promise represents the eventual completion or failure of an asynchronous operation.
252 | - It has two states: `fulfilled` (resolved) or `rejected` (failed).
253 | - You can create a promise using the `new Promise` constructor.
254 |
255 | ```javascript
256 | const myPromise = new Promise((resolve, reject) => {
257 | // Asynchronous operation
258 | // If successful, call resolve with a result
259 | // If there's an error, call reject with an error
260 | });
261 | ```
262 |
263 | 2. **Chaining `then` for Sequencing:**
264 | - The `then` method is used to handle the result of a successful promise.
265 |
266 | ```javascript
267 | myPromise
268 | .then((result) => {
269 | // Handle the result of the first asynchronous operation
270 | return result + 1; // Can return a value or a new promise
271 | })
272 | .then((newResult) => {
273 | // Handle the result of the second asynchronous operation
274 | console.log(newResult);
275 | })
276 | ```
277 |
278 | 3. **Chaining Promises for Sequential Operations:**
279 | - Each `then` block in the chain receives the result of the previous one.
280 | - This allows you to sequence asynchronous operations easily.
281 | - The `catch` method is used to handle errors at any point in the chain.
282 |
283 | ```javascript
284 | asyncOperation1()
285 | .then((result1) => {
286 | // Handle result1
287 | return asyncOperation2(result1);
288 | })
289 | .then((result2) => {
290 | // Handle result2 (which is the result of asyncOperation2)
291 | return asyncOperation3(result2);
292 | })
293 | .then((result3) => {
294 | // Handle result3 (which is the result of asyncOperation3)
295 | console.log(result3);
296 | })
297 | .catch((error) => {
298 | // Handle errors in any stage of the sequence
299 | console.error(error);
300 | });
301 | ```
302 |
303 |
304 | Chaining promises simplifies the structure of asynchronous code, making it easier to understand and maintain. It ensures a clear flow of execution and provides a centralized place for error handling.
305 |
306 | ## Promise Methods: Exploring the Arsenal
307 |
308 | Certainly! Let's explore the arsenal of Promise methods:
309 |
310 | ### 1. **Promise.all()**
311 | - **Purpose:** Resolves when all promises in the iterable are fulfilled or rejects if any promise is rejected.
312 | - **Usage:**
313 |
314 | ```javascript
315 | const promises = [promise1, promise2, promise3];
316 | Promise.all(promises)
317 | .then((results) => {
318 | console.log("All promises fulfilled:", results);
319 | })
320 | .catch((error) => {
321 | console.error("At least one promise rejected:", error);
322 | });
323 | ```
324 |
325 | - This is useful when you want to wait for multiple asynchronous operations to complete before proceeding.
326 |
327 | ### 2. **Promise.allSettled()**
328 | - **Purpose:** Resolves when all promises in the iterable are settled (fulfilled or rejected).
329 | - **Usage:**
330 |
331 | ```javascript
332 | Promise.allSettled([promise1, promise2, promise3])
333 | .then((results) => {
334 | console.log("All promises settled:", results);
335 | });
336 | ```
337 |
338 | - Unlike `Promise.all()`, this method doesn't short-circuit on the first rejection. It waits for all promises to settle, providing information on each.
339 |
340 | ### 3. **Promise.any()**
341 | - **Purpose:** Resolves with the value of the first fulfilled promise in the iterable.
342 | - **Usage:**
343 |
344 | ```javascript
345 | Promise.any([promise1, promise2, promise3])
346 | .then((result) => {
347 | console.log("At least one promise fulfilled:", result);
348 | });
349 | ```
350 |
351 | - Useful when you are interested in the result of the first successfully resolved promise.
352 |
353 | ### 4. **Promise.race()**
354 | - **Purpose:** Resolves or rejects as soon as one of the promises in the iterable resolves or rejects.
355 | - **Usage:**
356 |
357 | ```javascript
358 | Promise.race([promise1, promise2, promise3])
359 | .then((result) => {
360 | console.log("The first promise to settle:", result);
361 | });
362 | ```
363 |
364 | - Useful when you want the result of the first completed promise, regardless of fulfillment or rejection.
365 |
366 | These methods provide flexibility in handling multiple promises, allowing you to tailor your approach based on specific requirements.
367 |
368 |
369 | ## **Promise Methods Comparison**
370 | Certainly! Here's a comparison table for `Promise.all()`, `Promise.allSettled()`, `Promise.any()`, and `Promise.race()`:
371 |
372 | | Method | Purpose | Resolves When | Rejects When |
373 | | ---------------------- | -------------------------------------------------- | ----------------------------------------------- | ------------------------------------------------------------- |
374 | | `Promise.all()` | Waits for all promises to fulfill | All promises fulfill | Any promise rejects |
375 | | `Promise.allSettled()` | Waits for all promises to settle | All promises settle (fulfilled or rejected) | N/A (Doesn't short-circuit on rejections) |
376 | | `Promise.any()` | Resolves with the first fulfilled promise | The first promise fulfills | All promises reject except the first one |
377 | | `Promise.race()` | Resolves or rejects with the first settled promise | The first promise settles (fulfills or rejects) | The first promise rejects or fulfills (whichever comes first) |
378 |
379 | ### **Comparison Notes:**
380 | - `Promise.all()` waits for all promises to fulfill or rejects if any promise is rejected.
381 | - `Promise.allSettled()` waits for all promises to settle, providing information on each.
382 | - `Promise.any()` resolves with the value of the first fulfilled promise and rejects only if all promises are rejected.
383 | - `Promise.race()` resolves or rejects as soon as the first promise settles, whether fulfilled or rejected.
384 |
385 | ### **Useful Scenarios:**
386 | - Use `Promise.all()` when you need all promises to succeed before proceeding.
387 | - Use `Promise.allSettled()` when you want to know the outcome of all promises, regardless of fulfillment or rejection.
388 | - Use `Promise.any()` when you are interested in the result of the first successfully resolved promise.
389 | - Use `Promise.race()` when you want the result of the first completed promise, regardless of fulfillment or rejection.
390 |
391 | Understanding Promises and their methods is a pivotal step in mastering asynchronous JavaScript. In the upcoming sections, we'll build upon this foundation, exploring more advanced concepts. Get ready for a script filled with promise-induced excitement! 🚀
392 |
--------------------------------------------------------------------------------
/OOPs in JS.md:
--------------------------------------------------------------------------------
1 | # 🚀 OOP in JavaScript - Unveiling the Magic!
2 |
3 | Hey there, aspiring wizards of code! 🧙♂️✨
4 |
5 | Welcome to the enchanting world of Object-Oriented Programming (OOP) in JavaScript! 🌟 Today, we're diving deep into the mystical realm of classes, prototypes, and the powerful 'this' keyword.
6 |
7 | ## 🌈 Why This Document?
8 |
9 | You might be wondering, "Why are we delving into the magical arts of OOP in JavaScript?" Well, fear not, for there's a grand purpose behind this journey:
10 |
11 | ### :bulb: Unravel the Magic of Classes and Prototypes
12 |
13 | In JavaScript, understanding OOP is like unlocking a treasure trove of possibilities. It empowers you to create reusable, organized, and enchanting code structures.
14 |
15 | ### :sparkles: Harness the Power of 'this' Keyword
16 |
17 | The 'this' keyword, often mysterious to many, holds immense power. By the end of this document, you'll wield it with confidence, using it as your trusty magical wand to cast spells on your code.
18 |
19 | ### :crystal_ball: Discover the Art of Constructors, Setters, and Getters
20 |
21 | Ever wanted to craft objects with specific properties and behaviors? Constructors, setters, and getters are your potions for brewing objects with precision and control.
22 |
23 | Now, let's embark on this magical journey and unravel the secrets of OOP in JavaScript! 🌌✨
24 |
25 |
26 | # 🌈 Chapter 1: What is Object-Oriented Programming (OOP)?
27 |
28 | Greetings, magical apprentices! 🧙♀️✨
29 |
30 | ## :bulb: Understanding the Essence
31 |
32 | In the vast realm of coding, Object-Oriented Programming (OOP) is a paradigm that brings order and magic to the chaotic world of code. But what does it mean?
33 |
34 | At its core, OOP revolves around the concept of **objects**. An object is like a magical entity that encapsulates data and behaviors. These objects interact with each other, casting spells and collaborating to create a harmonious code symphony.
35 |
36 | ## :sparkles: Key Components
37 |
38 | ### 1. **Objects**
39 | - Objects are the building blocks of OOP. They encapsulate data (attributes) and actions (methods), making them powerful entities in the code kingdom.
40 |
41 | ### 2. **Classes**
42 | - Think of classes as blueprints or molds for creating objects. They define the structure and behavior that objects belonging to them will exhibit.
43 |
44 | ### 3. **`this` Keyword**
45 | - Brace yourselves for the magic of the 'this' keyword! It's your trusty wand, allowing objects to refer to themselves and access their own properties and methods.
46 |
47 | ### 4. **Getter and Setter Methods**
48 | - Unveil the secrets of accessing and modifying object properties with getter and setter methods. These enchanting methods provide controlled access to the magical attributes within an object.
49 |
50 | ### 5. **Constructor**
51 | - The constructor is like the magical birthplace of objects. It's a special method within a class that is invoked when a new object is created. Here, you can set up the initial state and enchantments of the object.
52 |
53 | ### 6. **Abstraction, Encapsulation, Inheritance, Polymorphism**
54 | - While these magical concepts exist in the realm of OOP, our focus in this article will be on Objects and Classes. The intricacies of Abstraction, Encapsulation, Inheritance, and Polymorphism shall be explored in future enchanting chapters.
55 |
56 |
57 | ## :crystal_ball: Why OOP Matters
58 |
59 | In the magical world of coding, OOP serves as a guiding light. Here's why it matters:
60 |
61 | - **Organization:** OOP provides a structured approach, making code more organized and manageable.
62 | - **Reusability:** With classes and objects, you can reuse code, saving time and effort.
63 | - **Flexibility:** OOP offers flexibility through concepts like inheritance and polymorphism, adapting to changing requirements.
64 |
65 | So, fellow enchanters, that's a glimpse into the enchanting world of OOP! Ready yourselves, for we shall delve deeper into each magical component in the chapters to come. 🚀📜
66 |
67 | # 🌈 Chapter 2: Understanding the Basics of Prototype
68 |
69 | Ahoy, aspiring wizards! 🧙♂️✨
70 |
71 | ## :bulb: Embarking on the Journey of Prototypes
72 |
73 | In the enchanting land of JavaScript, understanding prototypes is like discovering a magical scroll that unlocks the true power of objects. Let's unravel the mystery!
74 |
75 | ## :scroll: What is a Prototype?
76 |
77 | In JavaScript, every object is linked to a prototype object. A prototype is like a magical ancestor, passing down properties and methods to its descendants (objects). This linkage forms a chain known as the prototype chain.
78 |
79 | ## :sparkles: Key Concepts
80 |
81 | ### 1. **`prototype` Property**
82 | - Each function in JavaScript has a special property called `prototype`. It's like a spellbook containing methods that objects created from the function will inherit.
83 |
84 | ### 2. **`__proto__` Property**
85 | - The `__proto__` property is a direct connection to an object's prototype. It's like a magical mirror reflecting the prototype from which an object inherits.
86 |
87 | ### 3. **Prototypal Inheritance**
88 | - Prototypal inheritance is the magical process where an object inherits properties and methods from its prototype. It's the essence of the enchanting connection between objects and their prototypes.
89 |
90 | ## :mage: Why Prototypes Matter
91 |
92 | Understanding prototypes is akin to wielding a powerful wand in the world of JavaScript. Here's why it matters:
93 |
94 | - **Code Efficiency:** Prototypes enable objects to share methods, reducing memory consumption and promoting efficient code.
95 |
96 | - **Dynamic Updates:** Changes to the prototype reflect in all objects linked to it, providing a dynamic and centralized way to update behaviors.
97 |
98 | - **Code Reusability:** Prototypal inheritance fosters code reuse, allowing multiple objects to inherit from a common prototype.
99 |
100 | ## :sparkle: Example for Better Understanding
101 |
102 | ```javascript
103 | // Creating a simple function (constructor)
104 | function Wizard(name) {
105 | this.name = name;
106 | }
107 |
108 | // Adding a method to the prototype
109 | Wizard.prototype.castSpell = function () {
110 | console.log(`${this.name} casts a magical spell!`);
111 | };
112 |
113 | // Creating wizard objects
114 | const merlin = new Wizard("Merlin");
115 | const gandalf = new Wizard("Gandalf");
116 |
117 | // Wizards inheriting and using the prototype method
118 | merlin.castSpell(); // Output: Merlin casts a magical spell!
119 | gandalf.castSpell(); // Output: Gandalf casts a magical spell!
120 | ```
121 |
122 | ## :book: Delving Deeper
123 |
124 | To truly master the art of prototypes, one must explore the depths of the prototype chain, experiment with custom prototypes, and harness the full potential of prototypal inheritance.
125 |
126 | ### :chains: The Prototype Chain
127 |
128 | The prototype chain is a mystical connection between objects, forming a lineage of inheritance. Objects inherit properties not only from their direct prototype but also from the entire chain of prototypes.
129 |
130 | ```javascript
131 | // Example of a prototype chain
132 | function Elf(name, power) {
133 | this.name = name;
134 | this.power = power;
135 | }
136 |
137 | // Adding a method to Elf's prototype
138 | Elf.prototype.castMagic = function () {
139 | console.log(`${this.name} casts a powerful spell!`);
140 | };
141 |
142 | // Creating a DarkElf constructor that inherits from Elf
143 | function DarkElf(name, power, darkPower) {
144 | // Call Elf constructor to initialize shared properties
145 | Elf.call(this, name, power);
146 | this.darkPower = darkPower;
147 | }
148 |
149 | // Inheriting Elf's prototype to enable shared methods
150 | DarkElf.prototype = Object.create(Elf.prototype);
151 |
152 | // Adding a method specific to DarkElf
153 | DarkElf.prototype.darkCast = function () {
154 | console.log(`${this.name} unleashes dark power!`);
155 | };
156 |
157 | // Creating DarkElf objects
158 | const legolas = new Elf("Legolas", "Bow and Arrow");
159 | const malfoy = new DarkElf("Malfoy", "Slytherin", "Dark Arts");
160 |
161 | // Utilizing inherited methods
162 | legolas.castMagic(); // Output: Legolas casts a powerful spell!
163 | malfoy.castMagic(); // Output: Malfoy casts a powerful spell!
164 | malfoy.darkCast(); // Output: Malfoy unleashes dark power!
165 | ```
166 |
167 | ## :crystal_ball: Custom Prototypes
168 |
169 | Masters of the arcane arts can forge their own prototypes, imbuing objects with unique powers. Let's craft a custom prototype to empower our objects with additional abilities.
170 |
171 | ```javascript
172 | // Creating a custom prototype
173 | const magicalBeingPrototype = {
174 | teleport: function (destination) {
175 | console.log(`${this.name} teleports to ${destination} effortlessly.`);
176 | },
177 | invisibility: function () {
178 | console.log(`${this.name} fades into the shadows, becoming invisible.`);
179 | },
180 | };
181 |
182 | // Creating beings with magical powers
183 | const wizard = Object.create(magicalBeingPrototype);
184 | wizard.name = "Gandalf";
185 |
186 | const witch = Object.create(magicalBeingPrototype);
187 | witch.name = "Hermione";
188 |
189 | // Utilizing custom prototype methods
190 | wizard.teleport("Rivendell"); // Output: Gandalf teleports to Rivendell effortlessly.
191 | witch.invisibility(); // Output: Hermione fades into the shadows, becoming invisible.
192 | ```
193 |
194 | ## :scroll: Closing the Tome of Prototypes
195 |
196 | As we close the tome on prototypes, let's reflect on the magic woven into the fabric of JavaScript. Prototypes, the silent architects of objects, and the intricate dance of the prototype chain have unfolded their mysteries.
197 |
198 | ### :star2: Lessons Learned
199 |
200 | - **Prototypes:** Blueprints guiding object creation.
201 | - **Prototype Chain:** A cosmic dance of inheritance.
202 |
203 | ### :crystal_ball: Beyond Prototypes
204 |
205 | The journey continues to classes, constructors, and the dance of `this`. The adventure unfolds, beckoning us to explore further.
206 |
207 | ## :european_castle: Unveiling the Castle of Classes
208 |
209 | In the magical kingdom of JavaScript, classes stand tall as majestic castles where objects are born. They provide a blueprint for creating objects with shared properties and methods. Behold the wonders of this castle!
210 |
211 | ```javascript
212 | // Creating a magical class
213 | class SpellCaster {
214 | // Constructor to enchant new objects
215 | constructor(name, power) {
216 | this.name = name;
217 | this.power = power;
218 | }
219 |
220 | // Magical method within the class
221 | castSpell() {
222 | console.log(`${this.name} casts a mesmerizing spell!`);
223 | }
224 | }
225 |
226 | // Creating enchanted beings from the SpellCaster class
227 | const sorcerer = new SpellCaster("Merlin", "Arcane Magic");
228 | const enchantress = new SpellCaster("Morgana", "Dark Sorcery");
229 |
230 | // Utilizing the magical powers of the class
231 | sorcerer.castSpell(); // Output: Merlin casts a mesmerizing spell!
232 | enchantress.castSpell(); // Output: Morgana casts a mesmerizing spell!
233 | ```
234 | ## :construction_worker: Constructors at Work
235 |
236 | In the magical kingdom of JavaScript, constructors are the skilled artisans within the castle, crafting new objects and enchanting them with initial properties. Witness their craftsmanship in the magical realm.
237 |
238 | ```javascript
239 | // Creating a constructor function
240 | function MagicalCreature(name, type) {
241 | this.name = name;
242 | this.type = type;
243 | }
244 |
245 | // Enchanting beings with the constructor
246 | const phoenix = new MagicalCreature("Fawkes", "Phoenix");
247 | const dragon = new MagicalCreature("Smaug", "Dragon");
248 |
249 | // Behold the enchanted creatures!
250 | console.log(phoenix); // Output: { name: 'Fawkes', type: 'Phoenix' }
251 | console.log(dragon); // Output: { name: 'Smaug', type: 'Dragon' }
252 | ```
253 |
254 | ### :zap: Constructors in Action
255 |
256 | - **Creation:** Constructors, like skilled artisans, create new instances of objects. In the example, `MagicalCreature` crafts phoenixes and dragons.
257 |
258 | - **Enchantment:** The `this` keyword within the constructor bestows magical properties upon the created beings. Each instance carries a unique name and type.
259 |
260 | - **Invocation:** The magical invocation of `new` brings forth new entities. The enchanted creatures, Fawkes and Smaug, come to life.
261 |
262 | ### :mage: The Craft of Constructors
263 |
264 | - **Craftsmanship:** Constructors encapsulate the art of crafting objects with initial properties.
265 |
266 | - **Flexibility:** While classes offer a modern approach, constructors showcase the traditional craftsmanship still widely employed.
267 |
268 | ### :bulb: Wisdom for Apprentices
269 |
270 | - **Understanding `this`:** The `this` keyword within constructors dynamically adapts, pointing to the newly created object. It's the magical force that binds properties to the object.
271 |
272 | - **Invocation Ritual:** The sacred invocation using `new` breathes life into the constructor, transforming it into an object-enchanting spell.
273 |
274 | ## :key: Unveiling the Mysteries of Properties
275 |
276 | In the enchanting world of JavaScript, properties play a pivotal role in shaping the characteristics of objects. Let's embark on a journey to uncover the secrets of properties.
277 |
278 | ### :mag_right: What is a Property?
279 |
280 | A property is a magical attribute of an object, defining its characteristics or features. These attributes can be accessed and manipulated, allowing us to interact with the enchanted beings within the realm.
281 |
282 | ### :house_with_garden: Property
283 |
284 | In the mystical realm of JavaScript, open properties are like gardens accessible to all. They are visible and open for admiration and interaction by anyone in the enchanted kingdom.
285 |
286 | ```javascript
287 | class EnchantedBeing {
288 | power; // Property
289 |
290 | constructor(power) {
291 | this.power = power;
292 | }
293 |
294 | revealPower() {
295 | console.log(`The revealed power: ${this.power}`);
296 | }
297 | }
298 |
299 | const fairy = new EnchantedBeing("Nature Magic");
300 | fairy.revealPower(); // Output: The revealed power: Nature Magic
301 | console.log(fairy.power); // Output: Nature Magic
302 | ```
303 |
304 |
305 | ### :closed_lock_with_key: Private Property
306 |
307 | Amidst the enchanting gardens of open properties, there exist hidden treasures—private properties. Marked by the # symbol, these properties are concealed within the enchanted class or constructor, shielded from external eyes.
308 |
309 | ```javascript
310 | // Only on NodeJS
311 |
312 | class EnchantedBeing {
313 | #privatePower; // Private property
314 |
315 | constructor(power) {
316 | this.#privatePower = power;
317 | }
318 |
319 | revealPower() {
320 | console.log(`The hidden power: ${this.#privatePower}`);
321 | }
322 | }
323 |
324 | const sorcerer = new EnchantedBeing("Arcane Magic");
325 | sorcerer.revealPower(); // Output: The hidden power: Arcane Magic
326 | console.log(sorcerer.#privatePower); // Error: Private field '#privatePower' must be declared in an enclosing class
327 | ```
328 |
329 | ### :closed_book: Wisdom from the Tome
330 |
331 | - **Open Wonders:** Properties without the # symbol are open for all to see and interact with, adding transparency to the enchanted realm.
332 |
333 | - **Private Mysteries:** Private properties, marked by the # symbol, offer secrecy within the enchanted class or constructor.
334 |
335 | ## :sparkles: Enchanting Methods: The Magic Within
336 |
337 | In the enchanted realms of JavaScript, methods are the mystical incantations that bring objects to life, empowering them with the ability to perform magical actions. Let's embark on a magical journey to explore the secrets of methods.
338 |
339 | ### :mage: The Art of Methodology
340 |
341 | Methods in JavaScript are functions that are associated with an object. They encapsulate logic and allow objects to perform actions or provide information about themselves. Here's a glimpse of the enchanting syntax:
342 |
343 | ```javascript
344 | class EnchantedArtifact {
345 | // An enchanting method to cast a spell
346 | castSpell() {
347 | console.log('Abracadabra! A spell is cast.');
348 | }
349 |
350 | // A magical method to reveal the enchanted properties
351 | revealProperties() {
352 | console.log('Enchanted Properties:', this);
353 | }
354 | }
355 |
356 | // Creating an enchanted artifact
357 | const magicWand = new EnchantedArtifact();
358 |
359 | // Casting a spell using the method
360 | magicWand.castSpell();
361 | // Output: Abracadabra! A spell is cast.
362 |
363 | // Revealing the enchanted properties
364 | magicWand.revealProperties();
365 | // Output: Enchanted Properties: EnchantedArtifact {}
366 | ```
367 |
368 | ### :crystal_ball: The Wisdom of Methods
369 |
370 | - **Function Enchantment:** Methods are essentially functions that are part of an object, adding a magical touch to the object's abilities.
371 |
372 | - **Object Interaction:** Methods allow objects to interact with their surroundings, casting spells, revealing secrets, and performing other enchanting tasks.
373 |
374 | - **`this` in Action:** Within methods, the `this` keyword is a magical reference to the object itself, providing a way for objects to refer to their own properties and methods.
375 |
376 | ## :crystal_ball: Unveiling the Magic of Getters and Setters
377 |
378 | In the enchanting world of JavaScript, getters and setters are magical constructs that bestow objects with the power of controlled access to their properties. Let's uncover the secrets of these mystical guardians.
379 |
380 | ### :key: Enchanting Access with Getters
381 |
382 | Getters are magical methods that allow us to retrieve the value of a property with finesse. They act as guardians, controlling the access to the inner treasures of an object.
383 |
384 | ```javascript
385 | class EnchantedArtifact {
386 | _innerTreasure = 'Secret Knowledge';
387 |
388 | // A mystical guardian (getter) revealing the inner treasure
389 | get treasure() {
390 | console.log('Accessing the inner treasure!');
391 | return this._innerTreasure;
392 | }
393 | }
394 |
395 | // Creating an enchanted artifact
396 | const ancientScroll = new EnchantedArtifact();
397 |
398 | // Accessing the inner treasure using the getter
399 | console.log(ancientScroll.treasure);
400 | // Output: Accessing the inner treasure!
401 | // Output: Secret Knowledge
402 | ```
403 |
404 | ### :lock_with_ink_pen: Guarding Secrets with Setters
405 |
406 | Setters are enchanting spells that provide a controlled mechanism for setting the value of a property. They ensure that only worthy changes are made to the magical essence of an object.
407 |
408 |
409 | ```javascript
410 | class EnchantedArtifact {
411 | _innerTreasure = 'Secret Knowledge';
412 |
413 | // A bewitching spell (setter) to safeguard the inner treasure
414 | set treasure(newTreasure) {
415 | if (newTreasure === 'New Wisdom') {
416 | console.log('Changing the inner treasure!');
417 | this._innerTreasure = newTreasure;
418 | } else {
419 | console.error('Invalid attempt to change the inner treasure!');
420 | }
421 | }
422 | }
423 |
424 | // Creating an enchanted artifact
425 | const ancientScroll = new EnchantedArtifact();
426 |
427 | // Attempting to change the inner treasure using the setter
428 | ancientScroll.treasure = 'Ancient Secrets';
429 | // Output: Invalid attempt to change the inner treasure!
430 | console.log(ancientScroll.treasure);
431 | // Output: Secret Knowledge
432 |
433 | ancientScroll.treasure = 'New Wisdom';
434 | // Output: Changing the inner treasure!
435 | console.log(ancientScroll.treasure);
436 | // Output: New Wisdom
437 | ```
438 |
439 | ### :closed_book: Wisdom from the Tome
440 |
441 | - **Getters' Magic:** Getters provide a way to enchantingly retrieve the value of a property, controlling the access to inner secrets.
442 |
443 | - **Setters' Spell:** Setters act as protective spells, guarding against unworthy changes and ensuring the integrity of an object's magical essence.
444 |
445 | - **Guardians of Access:** Getters and setters together form the guardians of access, bringing harmony to the magical world of JavaScript.
446 |
447 |
448 | ## :thinking: The Quest for Setters and Getters: A Journey into Necessity
449 |
450 | In the vast realms of JavaScript, the need for setters and getters arises from the desire to create objects with controlled access to their inner properties. This quest leads us to explore the essential reasons behind embracing these enchanting constructs.
451 |
452 | ### :key: The Key to Controlled Access
453 |
454 | 1. **Encapsulation of Secrets:** Setters and getters enable the encapsulation of an object's internal state. They act as guardians, controlling access to crucial data and preventing unauthorized manipulation.
455 |
456 | ```javascript
457 | class MagicalArtifact {
458 | #innerSecret = 'Hidden Wisdom';
459 |
460 | get secret() {
461 | return this.#innerSecret;
462 | }
463 |
464 | set secret(newSecret) {
465 | if (newSecret === 'New Wisdom') {
466 | this.#innerSecret = newSecret;
467 | } else {
468 | console.error('Invalid attempt to change the inner secret!');
469 | }
470 | }
471 | }
472 |
473 | const ancientScroll = new MagicalArtifact();
474 | console.log(ancientScroll.secret); // Output: Hidden Wisdom
475 | ```
476 |
477 | 2. **Validation and Constraints:** Setters empower developers to impose validation checks and constraints when assigning values to properties. This ensures that only valid and acceptable values become part of an object's essence.
478 |
479 | ```javascript
480 | class Wizard {
481 | #magicLevel = 0;
482 |
483 | get magicLevel() {
484 | return this.#magicLevel;
485 | }
486 |
487 | set magicLevel(newLevel) {
488 | if (newLevel >= 0 && newLevel <= 100) {
489 | this.#magicLevel = newLevel;
490 | } else {
491 | console.error('Invalid magic level!');
492 | }
493 | }
494 | }
495 |
496 | const merlin = new Wizard();
497 | merlin.magicLevel = 75;
498 | console.log(merlin.magicLevel); // Output: 75
499 | ```
500 |
501 | ### :shield: Safeguarding the Magical Essence
502 |
503 | 3. **Data Integrity:** With setters, the integrity of an object's magical essence is preserved. Unworthy attempts to alter the internal state are thwarted, maintaining the sanctity of the object.
504 |
505 | 4. **Adaptability and Evolution:** Setters provide a flexible mechanism to adapt an object's behavior over time. As the requirements evolve, setters allow for seamless adjustments without compromising the object's integrity.
506 |
507 | ### :bulb: Illuminating Wisdom
508 |
509 | In the enchanting world of JavaScript, setters and getters emerge as indispensable tools for crafting robust and secure objects. They bring forth a balance between accessibility and protection, allowing developers to wield the power of controlled access with finesse.
510 |
511 | ## :zap: The Battle of Titans: Methods vs Getters/Setters
512 |
513 | In the grand arena of JavaScript, two formidable contenders—methods and getters/setters—vie for supremacy. Let's explore the strengths and characteristics of these mighty titans to understand when to summon each in the quest for code excellence.
514 |
515 | ### :hammer_and_wrench: The Mighty Methods
516 |
517 | 1. **Versatility and Power:** Methods wield a broad spectrum of capabilities, ranging from executing complex logic to performing a series of actions. They are the swiss army knives of functionality, adaptable to diverse scenarios.
518 |
519 | ```javascript
520 | class SpellCaster {
521 | #spellPower = 0;
522 |
523 | castSpell() {
524 | // Perform spellcasting logic
525 | this.#spellPower += 10;
526 | console.log('Spell cast!');
527 | }
528 |
529 | getSpellPower() {
530 | return this.#spellPower;
531 | }
532 | }
533 |
534 | const sorcerer = new SpellCaster();
535 | sorcerer.castSpell();
536 | console.log(sorcerer.getSpellPower()); // Output: 10
537 | ```
538 |
539 | 2. **Action-Packed:** Methods thrive in an action-packed environment. They execute a sequence of steps, making them ideal for scenarios where multiple actions need to be orchestrated.
540 |
541 | ### :arrows_counterclockwise: The Graceful Getters and Setters
542 |
543 | 3. **Controlled Access:** Getters and setters serve as the gatekeepers of an object's properties, controlling access and modification. They allow for a fine-tuned approach, ensuring that interactions adhere to defined rules.
544 |
545 | ```javascript
546 | class EnchantedArmor {
547 | #defenseRating = 0;
548 |
549 | get defenseRating() {
550 | return this.#defenseRating;
551 | }
552 |
553 | set defenseRating(newRating) {
554 | if (newRating >= 0) {
555 | this.#defenseRating = newRating;
556 | } else {
557 | console.error('Invalid defense rating!');
558 | }
559 | }
560 | }
561 |
562 | const mysticalArmor = new EnchantedArmor();
563 | mysticalArmor.defenseRating = 20;
564 | console.log(mysticalArmor.defenseRating); // Output: 20
565 | ```
566 |
567 | 4. **Property Guardians:** Getters and setters act as diligent guardians, ensuring that external forces abide by the rules when interacting with an object's properties.
568 |
569 | ### :boom: Choosing the Right Champion
570 |
571 | 5. **Scenario-driven Selection:** The choice between methods and getters/setters depends on the scenario at hand. Methods excel in scenarios where dynamic actions and logic are paramount, while getters/setters shine in scenarios demanding controlled property access.
572 |
573 | 6. **Harmonious Coexistence:** In many cases, methods and getters/setters can coexist harmoniously, each contributing its unique strengths to the overall design of the magical artifact.
574 |
575 | # :trophy: Code Sorcery Unleashed!
576 |
577 | Congratulations, brave JavaScript sorcerer, for embarking on this enchanting journey through the mystical realms of Object-Oriented Programming in JavaScript. Together, we've explored the arcane arts of prototypes, delved into the secrets of classes, harnessed the power of constructors, and witnessed the dance of getters and setters.
578 |
579 | ## :sparkles: Your Journey Continues
580 |
581 | As you emerge victorious from this quest, remember that the world of JavaScript magic is vast and ever-expanding. This is but the beginning of your adventures. The enchanted lands of abstraction, encapsulation, inheritance, and polymorphism await your exploration.
582 |
583 | ## :book: The Tome of Knowledge
584 |
585 | Feel free to revisit this magical tome whenever you seek guidance or desire to deepen your understanding of the mystical arts. Each chapter holds the key to unlocking new levels of JavaScript mastery.
586 |
587 | ## :mage: Keep Casting Spells
588 |
589 | Armed with the knowledge bestowed upon you, continue casting spells in the form of code. Solve puzzles, tackle challenges, and let your creativity flow. The more you code, the more potent your spells become.
590 |
591 | ## :crystal_ball: The Future Awaits
592 |
593 | As you traverse the ever-shifting landscape of JavaScript, anticipate new discoveries, challenges, and revelations. The future holds untold possibilities, and with each incantation of code, you shape the destiny of your coding journey.
594 |
595 | May your code be elegant, your bugs few, and your algorithms swift. Until we meet again in the realms of code, farewell, fellow sorcerer. May your programming adventures be magical! 🚀✨
596 |
597 | ---
598 |
599 | *Thank you for taking the time to read my article. Your engagement is the driving force behind the words on these pages. Whether you found information, inspiration, or simply enjoyed the content, your presence is deeply appreciated. Writing is a shared journey, and I'm grateful to have you as a reader. Cheers to the joy of exploration and discovery! 🌟*
600 |
601 | *If you enjoyed the article, consider giving it more stars!*
602 |
603 | *With gratitude,*
604 |
605 | *Pugazharasan C*
--------------------------------------------------------------------------------