├── .DS_Store ├── readme.md └── resources ├── Array └── readme.md ├── Arrow_Functions └── readme.md ├── Browser_API └── readme.md ├── Closure └── readme.md ├── Conditionals └── readme.md ├── Constructor_Function └── readme.md ├── Currying └── readme.md ├── DOM └── readme.md ├── Date └── readme.md ├── Destructuring └── readme.md ├── Error_Handling └── readme.md ├── Events └── readme.md ├── Fetch_Api └── readme.md ├── Loops └── readme.md ├── Maps └── readme.md ├── Math └── readme.md ├── Numbers └── readme.md ├── Objects └── readme.md ├── Operators └── readme.md ├── Promise └── readme.md ├── Prototype └── readme.md ├── Recursive_Functions └── readme.md ├── RegEx └── readme.md ├── Regular_Function └── readme.md ├── Rest_Parameter └── readme.md ├── Sets └── readme.md ├── Spread └── readme.md ├── String └── readme.md ├── Ternary └── readme.md ├── Timer_Function └── readme.md ├── Type_Conversion └── readme.md └── jsToMarkdown ├── jsToMarkdown.js └── readme.md /.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/beTop1PercentTechie/JS-Coding-Challenges/df3008c17ef07cc75905bac9fe8e006849e44e7b/.DS_Store -------------------------------------------------------------------------------- /readme.md: -------------------------------------------------------------------------------- 1 | # Welcome to our JavaScript Coding Challenge Sheet! 🎉 2 | 3 | This thoughtfully curated collection is designed to help you strengthen your JavaScript skills, one question at a time. 4 | 5 | We've organized the challenges by topics, making it easy for you to focus on areas that matter most to you. Each category includes multiple questions, and every question comes with a title, description, example, topics covered, helpful hints, and finally, a detailed solution to guide you. 6 | 7 | 8 | ## Pre-Read Before You Begin: 9 | Please take a moment to carefully go through each question and fully understand the requirements. If you can figure it out, start building the solution confidently. No need to submit your solutions anywhere! 10 | 11 | If you're unable to solve the challenge initially: 12 | 13 | - Check out the topics covered for a hint or an idea of the approach. 14 | - Explore the helpful resources in the hints section to deepen your understanding. 15 | 16 | Make sure to give every challenge at least one try before looking at the solution. 17 | 18 | Once you're done, review the solution and give yourself a well-deserved treat—whether for getting the right answer or simply showing up! `Remember, consistent practice will eventually help you crack even the toughest problems.` 19 | 20 | 21 | Simply click on the link below to get started, and dive into a world of learning and growth. 22 | 23 | --- 24 | 25 | ### 1. [Numbers](/resources/Numbers/) 26 | ### 2. [String](/resources/String/) 27 | ### 3. [Operators](/resources/Operators/) 28 | ### 4. [Type Conversion](/resources/Type_Conversion/) 29 | ### 5. [Maps](/resources/Maps/) 30 | ### 6. [Sets](/resources/Sets/) 31 | ### 7. [Arrays](/resources/Array/) 32 | ### 8. [Objects](/resources/Objects/) 33 | ### 9. [Conditionals](/resources/Conditionals/) 34 | ### 10. [Ternary](/resources/Ternary/) 35 | ### 11. [Loops](/resources/Loops/) 36 | ### 12. [Regular Functions](/resources/Regular_Function/) 37 | ### 13. [Arrow Functions](/resources/Arrow_Functions/) 38 | ### 14. [Recursive Functions](/resources/Recursive_Functions/) 39 | ### 15. [Closure](/resources/Closure/) 40 | ### 16. [Currying](/resources/Currying/) 41 | ### 17. [Math](/resources/Math/) 42 | ### 18. [Date](/resources/Date/) 43 | ### 19. [Regex](/resources/RegEx/) 44 | ### 20. [Spread](/resources/Spread/) 45 | ### 21. [Rest](/resources/Rest_Parameter/) 46 | ### 22. [Destructuring](/resources/Destructuring/) 47 | ### 23. [Constructor Function](/resources/Constructor_Function/) 48 | ### 24. [Prototype](/resources/Prototype/) 49 | ### 25. [Error Handling](/resources/Error_Handling/) 50 | ### 26. [Promises](/resources/Promise/) 51 | ### 27. [Fetch API](/resources/Fetch_Api/) 52 | ### 28. [Browser APIs](/resources/Browser_API/) 53 | ### 29. [Timer Functions](/resources/Timer_Function/) 54 | ### 30. [DOM - CRUD Elements](/resources/DOM/) 55 | ### 31. [Events](/resources/Events/) 56 | 57 | --- 58 | 59 | #### We believe in you—best of luck as you tackle these challenges! 🌟 60 | 61 | `PS: Star the reporsitory if you found it useful` 62 | 63 | _Curated with ❤️ from Aimerz_ -------------------------------------------------------------------------------- /resources/Arrow_Functions/readme.md: -------------------------------------------------------------------------------- 1 | # Arrow Functions 2 | ##### `Question 1. Sum of Two Numbers` 3 | 4 | Write a program using an arrow function to calculate the sum of two numbers. 5 | 6 | `Example:` 7 | 8 | ```javascript 9 | 10 | const add = (a, b) => { 11 | 12 | // Your code here 13 | 14 | }; 15 | console.log(add(5, 3)); // Output: 8 16 | 17 | ``` 18 | 19 | `Topics Covered:` 20 | Arrow Function 21 | 22 | **Hints:** 23 | - [Arrow Function Syntax](https://www.programiz.com/javascript/arrow-function) 24 | 25 |
26 | Solution 27 | 28 | ### Let's look at the solution: 29 | 30 | ```javascript 31 | 32 | const add = (a, b) => a + b; 33 | console.log(add(5, 3)); // Output: 8 34 | 35 | ``` 36 | 37 | **Explanation:** 38 | 39 | 40 | - const add = (a, b) => a + b;: This is an arrow function that adds the values of a and b together. 41 | - console.log(add(5, 3));: This calls the add function with arguments 5 and 3, which returns 8, and console.log prints the result. 42 | 43 |
44 | 45 | ---- 46 | ###### ` Question 2. Find the Square of a Number` 47 | 48 | Write a program using an arrow function to calculate the square of a given number. 49 | 50 | `Example:` 51 | 52 | ```javascript 53 | 54 | const square = (a) => { 55 | 56 | // Your code here 57 | 58 | }; 59 | console.log(square(5)); // Output: 25 60 | 61 | ``` 62 | 63 | `Topics Covered:` 64 | Arrow Function 65 | 66 | **Hints:** 67 | - [Arrow Function](https://www.programiz.com/javascript/arrow-function) 68 | 69 |
70 | Solution 71 | 72 | ### Let's look at the solution: 73 | 74 | ```javascript 75 | 76 | const square = (a) => { 77 | a*a; 78 | }; 79 | console.log(square(5)); // Output: 25 80 | 81 | ``` 82 | 83 | **Explanation:** 84 | 85 | 86 | - The original function lacks a return statement, so it doesn't return any value, resulting in undefined when called. 87 | - Adding the return keyword ensures the function returns the result of a * a, so console.log(square(5)) outputs 25. 88 | 89 |
90 | 91 | ---- 92 | ###### ` Question 3. Check if a Number is Even` 93 | 94 | Write a program using an arrow function to check if a given number is even. Return true if even, otherwise false. 95 | 96 | `Example:` 97 | 98 | ```javascript 99 | 100 | const isEven = (n) =>{ 101 | 102 | // Your Code here 103 | 104 | } 105 | console.log(isEven(7)); // Output: false 106 | 107 | ``` 108 | 109 | `Topics Covered:` 110 | Arrow Function 111 | 112 | **Hints:** 113 | - [Arrow Function](https://www.programiz.com/javascript/arrow-function) 114 | 115 |
116 | Solution 117 | 118 | ### Let's look at the solution: 119 | 120 | ```javascript 121 | 122 | const isEven = (n) => n % 2 === 0; 123 | console.log(isEven(7)); // Output: false 124 | 125 | ``` 126 | 127 | **Explanation:** 128 | 129 | 130 | - The isEven function takes a parameter n and checks if it is even by using the modulus operator (%). 131 | - The expression n % 2 === 0 checks if the remainder when dividing n by 2 is 0, which means the number is even. 132 | 133 |
134 | 135 | ---- 136 | ###### ` Question 4. Filter Odd Numbers from an Array` 137 | 138 | Write a program using an arrow function to filter odd numbers from an array. 139 | 140 | `Example:` 141 | 142 | ```javascript 143 | 144 | const filterOdds = (arr) => { 145 | 146 | // Your Code here 147 | 148 | } 149 | console.log(filterOdds([1, 2, 3, 4, 5])); // Output: [1, 3, 5] 150 | 151 | ``` 152 | 153 | `Topics Covered:` 154 | Arrow Function 155 | 156 | **Hints:** 157 | - [Arrow Function](https://www.programiz.com/javascript/arrow-function) 158 | 159 |
160 | Solution 161 | 162 | ### Let's look at the solution: 163 | 164 | ```javascript 165 | 166 | const filterOdds = (arr) => arr.filter(num => num % 2 !== 0); 167 | console.log(filterOdds([1, 2, 3, 4, 5])); // Output: [1, 3, 5] 168 | 169 | ``` 170 | 171 | **Explanation:** 172 | 173 | 174 | - The filterOdds uses the filter() method to iterate over the array arr. 175 | - For each number (num), it checks if num % 2 !== 0, which returns true for odd numbers. 176 | 177 |
178 | 179 | ---- 180 | ###### ` Question 5. Convert Celsius to Fahrenheit` 181 | 182 | Write a program using an arrow function to convert a given temperature in Celsius to Fahrenheit. 183 | 184 | `Example:` 185 | 186 | ```javascript 187 | 188 | const celsiusToFahrenheit = (celsius) => 189 | { 190 | 191 | // your code here 192 | 193 | } 194 | console.log(celsiusToFahrenheit(25)); // Output: 195 | 196 | ``` 197 | 198 | `Topics Covered:` 199 | Arrow Function 200 | 201 | **Hints:** 202 | - [Arrow Function](https://www.programiz.com/javascript/arrow-function) 203 | 204 |
205 | Solution 206 | 207 | ### Let's look at the solution: 208 | 209 | ```javascript 210 | 211 | const celsiusToFahrenheit = (celsius) => (celsius * 9/5) + 32; 212 | console.log(celsiusToFahrenheit(25)); // Output: 77 213 | 214 | ``` 215 | 216 | **Explanation:** 217 | 218 | 219 | - The (celsius * 9/5) + 32 converts the Celsius temperature (celsius) to Fahrenheit. 220 | - (celsius * 9/5) + 32 converts the Celsius temperature (celsius) to Fahrenheit. 221 | 222 |
223 | 224 | ---- 225 | ###### ` Question 6. Enumerate a Map` 226 | 227 | Write a program using an arrow function to enumerate (loop through) a Map and print each key-value pair. 228 | 229 | `Example:` 230 | 231 | ```javascript 232 | 233 | const enumerateMap = (map) => { 234 | 235 | // Your Code here 236 | 237 | }; 238 | 239 | const myMap = new Map([["a", 1], ["b", 2], ["c", 3]]); 240 | enumerateMap(myMap); 241 | 242 | 243 | 244 | 245 | ``` 246 | 247 | `Topics Covered:` 248 | Arrow Function 249 | 250 | **Hints:** 251 | - [Arrow Function](https://www.programiz.com/javascript/arrow-function) 252 | 253 |
254 | Solution 255 | 256 | ### Let's look at the solution: 257 | 258 | ```javascript 259 | 260 | const enumerateMap = (map) => { 261 | map.forEach((value, key) => console.log("Key: " + key + ", Value: " + value)); 262 | }; 263 | 264 | const myMap = new Map([["a", 1], ["b", 2], ["c", 3]]); 265 | enumerateMap(myMap); 266 | 267 | 268 | ``` 269 | 270 | **Explanation:** 271 | 272 | 273 | - The arrow function enumerateMap takes a Map and uses the forEach() method to iterate through each key-value pair. It logs the key and value in each iteration. 274 | - The Map is passed to the enumerateMap function. 275 | 276 |
277 | 278 | ---- 279 | -------------------------------------------------------------------------------- /resources/Constructor_Function/readme.md: -------------------------------------------------------------------------------- 1 | # Constructor Function 2 | 3 | ###### ` Question 1: ChatMessage Constructor` 4 | 5 | Write a ChatMessage constructor function to represent messages in a chat app. Each message should have text, sender, and timestamp. Add a method formatMessage() to return a formatted string. 6 | 7 | `Example:` 8 | 9 | ```javascript 10 | 11 | function ChatMessage(text, sender, timestamp) { 12 | //Your code here 13 | } 14 | 15 | // Example Usage: 16 | const message = new ChatMessage("Hello!", "Deepak", new Date()); 17 | console.log(message.formatMessage()); // Output: Deepak [10:30 AM]: Hello! 18 | 19 | 20 | 21 | ``` 22 | 23 | `Topics Covered:` 24 | Constructor function, Date & time 25 | 26 | **Hints:** 27 | - [Constructor function](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/Function), - [Date & time](https://www.w3schools.com/js/js_dates.asp) 28 | 29 |
30 | Solution 31 | 32 | ### Let's look at the solution: 33 | 34 | ```javascript 35 | 36 | function ChatMessage(text, sender, timestamp) { 37 | this.text = text; 38 | this.sender = sender; 39 | this.timestamp = timestamp; 40 | 41 | this.formatMessage = function () { 42 | const formattedTime = this.timestamp.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' }); 43 | return `${this.sender} [${formattedTime}]: ${this.text}`; 44 | }; 45 | } 46 | 47 | // Example Usage: 48 | const message = new ChatMessage("Hello!", "Deepak", new Date()); 49 | console.log(message.formatMessage()); // Output: Deepak [10:30 AM]: Hello! 50 | 51 | 52 | ``` 53 | 54 | **Explanation:** 55 | 56 | ### Purpose 57 | Represents a chat message with text, sender, and timestamp. 58 | 59 | ### Steps 60 | 61 | 1. **ChatMessage Constructor Initializes:** 62 | - text: Message content. 63 | - sender: Message sender. 64 | - timestamp: Time of the message. 65 | 66 | 2. **formatMessage() Formats the Message as:** 67 | - Sender [Time]: Message. 68 | 69 | ### Example 70 | 71 | Creates a message object and logs the formatted message. 72 | 73 | **Output:** 74 | Deepak [10:30 AM]: Hello! 75 | 76 | 77 |
78 | 79 | ---- 80 | ###### ` Question 2: Real-Time Voting System` 81 | 82 | Create a Poll constructor function for a voting system. Each poll has a question, an array of options, and an object votes to track votes for each option. Add methods vote(option) to increment votes and getResults() to return the voting results. 83 | 84 | `Example:` 85 | 86 | ```javascript 87 | 88 | function Poll(question, options) { 89 | //Your code here 90 | } 91 | 92 | // Example Usage: 93 | const poll = new Poll("What's your favorite language?", ["JavaScript", "Python", "Java"]); 94 | poll.vote("JavaScript"); 95 | poll.vote("JavaScript"); 96 | poll.vote("Python"); 97 | console.log(poll.getResults()); // Output: { JavaScript: 2, Python: 1, Java: 0 } 98 | 99 | 100 | 101 | ``` 102 | 103 | `Topics Covered:` 104 | Constructor function 105 | 106 | **Hints:** 107 | - [Constructor function](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/Function) 108 | 109 |
110 | Solution 111 | 112 | ### Let's look at the solution: 113 | 114 | ```javascript 115 | 116 | function Poll(question, options) { 117 | this.question = question; 118 | this.options = options; 119 | this.votes = {}; 120 | 121 | // Initialize vote counts for each option 122 | options.forEach(option => { 123 | this.votes[option] = 0; 124 | }); 125 | 126 | this.vote = function (option) { 127 | if (this.votes.hasOwnProperty(option)) { 128 | this.votes[option]++; 129 | } 130 | }; 131 | 132 | this.getResults = function () { 133 | return this.votes; 134 | }; 135 | } 136 | 137 | // Example Usage: 138 | const poll = new Poll("What's your favorite language?", ["JavaScript", "Python", "Java"]); 139 | poll.vote("JavaScript"); 140 | poll.vote("JavaScript"); 141 | poll.vote("Python"); 142 | console.log(poll.getResults()); // Output: { JavaScript: 2, Python: 1, Java: 0 } 143 | 144 | 145 | ``` 146 | 147 | **Explanation:** 148 | 149 | 150 | ### Purpose: 151 | Represents a poll with a question, options, and votes. 152 | 153 | ### Steps: 154 | 155 | ### Poll Constructor Initializes: 156 | - question: The poll's question. 157 | - options: Array of answer options. 158 | - votes: An object to track votes for each option, initialized to 0. 159 | 160 | ### vote(option): 161 | - Increments the vote count for the specified option if it exists. 162 | 163 | ### getResults(): 164 | - Returns the current vote counts for all options. 165 | 166 | 167 |
168 | 169 | ---- 170 | ###### ` Question 3: Multi-Language Translator` 171 | 172 | Write a Translator constructor function that takes an object translations (key-value pairs of language codes and messages). Add a method translate(languageCode) that returns the message in the requested language. 173 | 174 | `Example:` 175 | 176 | ```javascript 177 | 178 | function Translator(translations) { 179 | //Your code here 180 | } 181 | 182 | // Example Usage: 183 | const translator = new Translator({ en: "Hello", es: "Hola", fr: "Bonjour" }); 184 | console.log(translator.translate("es")); // Output: Hola 185 | console.log(translator.translate("de")); // Output: Translation not available 186 | 187 | 188 | ``` 189 | 190 | `Topics Covered:` 191 | Constructor function 192 | 193 | **Hints:** 194 | - [Constructor function](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/Function) 195 | 196 |
197 | Solution 198 | 199 | ### Let's look at the solution: 200 | 201 | ```javascript 202 | 203 | function Translator(translations) { 204 | this.translations = translations; 205 | 206 | this.translate = function (languageCode) { 207 | return this.translations[languageCode] || "Translation not available"; 208 | }; 209 | } 210 | 211 | // Example Usage: 212 | const translator = new Translator({ en: "Hello", es: "Hola", fr: "Bonjour" }); 213 | console.log(translator.translate("es")); // Output: Hola 214 | console.log(translator.translate("de")); // Output: Translation not available 215 | 216 | 217 | ``` 218 | 219 | **Explanation:** 220 | 221 | 222 | ### Purpose 223 | Represents a translator that provides translations for different languages. 224 | 225 | ### Constructor 226 | Initializes with a translations object containing language codes and their corresponding translations. 227 | 228 | ### Parameters: 229 | - translations: An object where the keys are language codes (e.g., "en" for English, "es" for Spanish) and the values are their respective translations. 230 | 231 | ### Methods 232 | 233 | ### translate(languageCode) 234 | - **Purpose**: Returns the translation for the specified languageCode. 235 | - **Parameters**: 236 | - languageCode: The language code for which the translation is needed (e.g., "en" for English, "es" for Spanish). 237 | - **Returns**: 238 | - The translation for the given languageCode. 239 | - If the language code is not available, it returns "Translation not available.". 240 | 241 | 242 |
243 | 244 | ---- 245 | ###### ` Question 4: Notification Constructor with Priority` 246 | 247 | Write a Notification constructor function for a messaging system. Each notification has message, timestamp, and priority (e.g., "low", "high"). Add a method isHighPriority() to return true if the priority is "high". 248 | 249 | `Example:` 250 | 251 | ```javascript 252 | 253 | function Notification(message, timestamp, priority) { 254 | //Your code here 255 | } 256 | 257 | // Example Usage: 258 | const notification = new Notification("New comment received!", new Date(), "high"); 259 | console.log(notification.isHighPriority()); // Output: true 260 | 261 | 262 | ``` 263 | 264 | `Topics Covered:` 265 | Constructor function 266 | 267 | **Hints:** 268 | - [Constructor function](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/Function) 269 | 270 |
271 | Solution 272 | 273 | ### Let's look at the solution: 274 | 275 | ```javascript 276 | 277 | function Notification(message, timestamp, priority) { 278 | this.message = message; 279 | this.timestamp = timestamp; 280 | this.priority = priority; 281 | 282 | this.isHighPriority = function () { 283 | return this.priority === "high"; 284 | }; 285 | } 286 | 287 | // Example Usage: 288 | const notification = new Notification("New comment received!", new Date(), "high"); 289 | console.log(notification.isHighPriority()); // Output: true 290 | 291 | 292 | ``` 293 | 294 | **Explanation:** 295 | 296 | 297 | ### Purpose 298 | Defines a Notification object with a message, timestamp, and priority level. 299 | 300 | ### Constructor 301 | 302 | - message: The notification message (e.g., "New comment received!"). 303 | - timestamp: The time when the notification was created. 304 | - priority: The priority level of the notification (e.g., "high", "low"). 305 | 306 | ### Methods 307 | 308 | ### isHighPriority() 309 | - **Purpose**: Checks if the notification has a high priority. 310 | - **Returns**: true if the priority is "high", otherwise false. 311 | 312 |
313 | 314 | ---- 315 | ###### ` Question 5: Multi-Level Dropdown Menu` 316 | 317 | Create a Dropdown constructor function for multi-level dropdown menus. Each menu has label, items (array of submenus or options), and isOpen. Add methods toggle() to open/close the dropdown and render() to display the menu structure. 318 | 319 | `Example:` 320 | 321 | ```javascript 322 | 323 | function Dropdown(label, items) { 324 | //Your code here 325 | } 326 | 327 | // Example Usage: 328 | const dropdown = new Dropdown("File", ["New", { label: "Open", items: ["Recent", "Browse"] }]); 329 | dropdown.toggle(); 330 | dropdown.render(); 331 | // Output: 332 | // File (Open) 333 | // - New 334 | // - Open 335 | // - Recent 336 | // - Browse 337 | 338 | 339 | ``` 340 | 341 | `Topics Covered:` 342 | Constructor function, Array methods i.e forEach() 343 | 344 | **Hints:** 345 | - [Constructor function](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/Function), - [Array methods i.e forEach()](https://www.w3schools.com/js/js_array_iteration.asp) 346 | 347 |
348 | Solution 349 | 350 | ### Let's look at the solution: 351 | 352 | ```javascript 353 | 354 | function Dropdown(label, items) { 355 | this.label = label; 356 | this.items = items; 357 | this.isOpen = false; 358 | 359 | this.toggle = function () { 360 | this.isOpen = !this.isOpen; 361 | }; 362 | 363 | this.render = function () { 364 | console.log(`${this.label} (${this.isOpen ? "Open" : "Closed"})`);; 365 | if (this.isOpen) { 366 | this.items.forEach(item => { 367 | if (typeof item === "string") { 368 | console.log(`- ${item}`); 369 | } else { 370 | console.log(`- ${item.label}`); 371 | if (item.items) { 372 | item.items.forEach(subItem => console.log(` - ${subItem}`)); 373 | } 374 | } 375 | }); 376 | } 377 | }; 378 | } 379 | 380 | // Example Usage: 381 | const dropdown = new Dropdown("File", ["New", { label: "Open", items: ["Recent", "Browse"] }]); 382 | dropdown.toggle(); 383 | dropdown.render(); 384 | 385 | ``` 386 | 387 | **Explanation:** 388 | 389 | 390 | ### Purpose 391 | Defines a Dropdown object with a label, a list of items, and an open/closed state. 392 | 393 | ### Constructor 394 | 395 | - label: The label displayed for the dropdown (e.g., "File"). 396 | - items: The list of items in the dropdown, which can be strings or objects (with sub-items). 397 | - isOpen: A boolean that tracks whether the dropdown is open or closed (initially set to false). 398 | 399 | ### Methods 400 | 401 | ### toggle() 402 | - **Purpose**: Toggles the dropdown's open/closed state. 403 | 404 | ### render() 405 | - **Purpose**: Displays the dropdown's label and items, showing sub-items if the dropdown is open. 406 | 407 | 408 |
409 | 410 | ---- 411 | -------------------------------------------------------------------------------- /resources/Currying/readme.md: -------------------------------------------------------------------------------- 1 | # Currying 2 | 3 | ###### ` Question 1. Add Two Numbers` 4 | 5 | Write a curried function that accepts two numbers as arguments and returns their sum. The first argument is passed to the curried function, and the second argument is passed to the returned function. 6 | 7 | `Example:` 8 | 9 | ```javascript 10 | 11 | const add = function(a) { 12 | return function(b) { 13 | 14 | // Your Code here 15 | 16 | }; 17 | }; 18 | 19 | console.log(add(5)(3)); // Output: 8 20 | 21 | ``` 22 | 23 | `Topics Covered:` 24 | Function Currying 25 | 26 | **Hints:** 27 | - [Function Currying](https://www.geeksforgeeks.org/what-is-currying-function-in-javascript/) 28 | - [Currying]( https://javascript.info/currying-partials/) 29 | 30 |
31 | Solution 32 | 33 | ### Let's look at the solution: 34 | 35 | ```javascript 36 | 37 | const add = function(a) { 38 | return function(b) { 39 | return a + b; 40 | }; 41 | }; 42 | 43 | console.log(add(5)(3)); // Output: 8 44 | 45 | ``` 46 | 47 | **Explanation:** 48 | 49 | 50 | - The add function is an anonymous function that returns another function, which takes b and adds it to a. 51 | - When called as add(5)(3), it returns 5 + 3, resulting in 8. 52 | 53 |
54 | 55 | ---- 56 | ###### ` Question 2. Multiply Three Numbers with currying` 57 | 58 | Write a curried function that takes three numbers and returns their product. The curried function should handle each number step by step, with the first function accepting the first number, and the second and third functions handling the remaining numbers. 59 | 60 | `Example:` 61 | 62 | ```javascript 63 | 64 | function multiply(a) { 65 | 66 | // Write your code here 67 | 68 | } 69 | 70 | console.log(multiply(2)(3)(4)); // Output: 24 71 | 72 | ``` 73 | 74 | `Topics Covered:` 75 | Function Currying 76 | 77 | **Hints:** 78 | - [Function Currying](https://www.geeksforgeeks.org/what-is-currying-function-in-javascript/), - [Currying]( https://javascript.info/currying-partials/) 79 | 80 |
81 | Solution 82 | 83 | ### Let's look at the solution: 84 | 85 | ```javascript 86 | 87 | function multiply(a) { 88 | return function(b) { 89 | return function(c) { 90 | return a * b * c; 91 | }; 92 | }; 93 | } 94 | 95 | console.log(multiply(2)(3)(4)); // Output: 24 96 | 97 | ``` 98 | 99 | **Explanation:** 100 | 101 | 102 | - The multiply function returns another function for each parameter, b and c. 103 | - When called as multiply(2)(3)(4), it multiplies 2 * 3 * 4, resulting in 24. 104 | 105 |
106 | 107 | ---- 108 | ###### ` Question 3. Calculate Power` 109 | 110 | Write a curried function that calculates the power of a number, where the first argument is the base, and the second is the exponent. This function should return the result of raising the base to the power of the exponent. 111 | 112 | `Example:` 113 | 114 | ```javascript 115 | 116 | function power(a) { 117 | 118 | // Your code here 119 | 120 | } 121 | 122 | console.log(power(2)(3)); // Output: 8 123 | 124 | 125 | ``` 126 | 127 | `Topics Covered:` 128 | Function Currying 129 | 130 | **Hints:** 131 | - [Function Currying](https://www.geeksforgeeks.org/what-is-currying-function-in-javascript/), - [Currying]( https://javascript.info/currying-partials/) 132 | 133 |
134 | Solution 135 | 136 | ### Let's look at the solution: 137 | 138 | ```javascript 139 | 140 | function power(a) { 141 | return function(b) { 142 | return Math.pow(a, b); 143 | }; 144 | } 145 | 146 | console.log(power(2)(3)); // Output: 8 147 | 148 | 149 | ``` 150 | 151 | **Explanation:** 152 | 153 | 154 | - The power function returns another function that calculates a raised to the power of b using Math.pow(a, b). 155 | 156 |
157 | 158 | ---- 159 | ###### ` Question 4. String Concatenation` 160 | 161 | Write a curried function to concatenate two strings. The first function should accept the first string, and the second function should accept the second string. It should return the concatenated result of both strings. 162 | 163 | `Example:` 164 | 165 | ```javascript 166 | 167 | function concatStrings(str1) { 168 | 169 | // Your Code here 170 | 171 | } 172 | 173 | console.log(concatStrings("Hello")("World")); // Output: "HelloWorld" 174 | 175 | 176 | ``` 177 | 178 | `Topics Covered:` 179 | Function Currying 180 | 181 | **Hints:** 182 | - [Function Currying](https://www.geeksforgeeks.org/what-is-currying-function-in-javascript/), - [Currying]( https://javascript.info/currying-partials/) 183 | 184 |
185 | Solution 186 | 187 | ### Let's look at the solution: 188 | 189 | ```javascript 190 | 191 | function concatStrings(str1) { 192 | return function(str2) { 193 | return str1 + str2; 194 | }; 195 | } 196 | 197 | console.log(concatStrings("Hello")("World")); // Output: "HelloWorld" 198 | 199 | ``` 200 | 201 | **Explanation:** 202 | 203 | 204 | - The concatStrings function takes str1 and returns another function that takes str2 and concatenates both strings. 205 | - When called as concatStrings("Hello")("World"), it concatenates "Hello" and "World", resulting in "HelloWorld". 206 | 207 |
208 | 209 | ---- 210 | ###### ` Question 5. Subtract Two Numbers` 211 | 212 | Write a curried function that takes two numbers and returns their difference. The curried function will first accept one number, and then the second function will accept the second number to subtract from the first. 213 | 214 | `Example:` 215 | 216 | ```javascript 217 | 218 | function subtract(a) { 219 | 220 | // Your code here 221 | 222 | } 223 | 224 | console.log(subtract(10)(5)); // Output: 5 225 | 226 | ``` 227 | 228 | `Topics Covered:` 229 | Function Currying 230 | 231 | **Hints:** 232 | - [Function Currying](https://www.geeksforgeeks.org/what-is-currying-function-in-javascript/), - [Currying]( https://javascript.info/currying-partials/) 233 | 234 |
235 | Solution 236 | 237 | ### Let's look at the solution: 238 | 239 | ```javascript 240 | 241 | function subtract(a) { 242 | return function(b) { 243 | return a - b; 244 | }; 245 | } 246 | 247 | console.log(subtract(10)(5)); // Output: 5 248 | 249 | ``` 250 | 251 | **Explanation:** 252 | 253 | 254 | - The subtract function takes a and returns another function that subtracts b from a. 255 | - When called as subtract(10)(5), it performs 10 - 5, resulting in 5. 256 | 257 |
258 | 259 | ---- 260 | ###### ` Question 6. Calculate Final Price After Discount and Tax` 261 | 262 | Write a curried function that calculates the final price of a product after applying a discount and then adding tax. The first function will accept the original price of the product, the second function will accept the discount rate, and the third function will accept the tax rate. The function should return the final price after applying the discount and tax. 263 | 264 | `Example:` 265 | 266 | ```javascript 267 | 268 | function calculateFinalPrice(price) { 269 | 270 | // Your code here 271 | 272 | } 273 | 274 | console.log(calculateFinalPrice(1000)(20)(15)); // Output: 920 275 | 276 | 277 | 278 | ``` 279 | 280 | `Topics Covered:` 281 | Function Currying 282 | 283 | **Hints:** 284 | - [Function Currying](https://www.geeksforgeeks.org/what-is-currying-function-in-javascript/), - [Currying]( https://javascript.info/currying-partials/) 285 | 286 |
287 | Solution 288 | 289 | ### Let's look at the solution: 290 | 291 | ```javascript 292 | 293 | function calculateFinalPrice(price) { 294 | return function(discountRate) { 295 | return function(taxRate) { 296 | const discount = price * (discountRate / 100); 297 | const priceAfterDiscount = price - discount; 298 | const finalPrice = priceAfterDiscount * (1 + taxRate / 100); 299 | return finalPrice; 300 | }; 301 | }; 302 | } 303 | 304 | console.log(calculateFinalPrice(1000)(20)(15)); // Output: 920 305 | 306 | ``` 307 | 308 | **Explanation:** 309 | 310 | 311 | - The discount is subtracted from the original price, and then tax is added to the discounted price to calculate the final price. 312 | - For an original price of 1000, a 20% discount, and a 15% tax, the final price is 920. 313 | 314 |
315 | 316 | ---- 317 | -------------------------------------------------------------------------------- /resources/Date/readme.md: -------------------------------------------------------------------------------- 1 | # Date 2 | ###### ` Question 1:Get Current Date and Time` 3 | 4 | Description:Write a javascript program where print the current date and time using Date object. 5 | `Example:` 6 | 7 | ```javascript 8 | 9 | function logCurrentDate() { 10 | //code here 11 | } 12 | 13 | // Calling the function 14 | logCurrentDate(); 15 | 16 | ``` 17 | `Topics Covered:` 18 | Date Object 19 | 20 | **Hints:** 21 | - [Date Object](https://www.w3schools.com/js/js_dates.asp) 22 |
23 | Solution 24 | 25 | ### Let's look at the solution: 26 | 27 | ```javascript 28 | function logCurrentDate() { 29 | console.log(new Date()); // Creates and logs the current date and time 30 | } 31 | 32 | logCurrentDate(); 33 | 34 | ``` 35 | **Explanation:** 36 | -The function logCurrentDate creates a new Date object representing the current date and time. 37 | 38 | -It directly logs this object to the console without storing it in a variable. 39 |
40 | 41 | ---- 42 | ###### ` Question 2:Get Specific Date and Time` 43 | 44 | Description::Write a javascript program where print the specific date and time using Date object 45 | 46 | `Example:` 47 | 48 | ```javascript 49 | 50 | function logSpecificDate() { 51 | //code here 52 | } 53 | 54 | logSpecificDate(); // Calling the function 55 | 56 | ``` 57 | `Topics Covered:` 58 | Date Object 59 | 60 | **Hints:** 61 | - [Date Object](https://www.w3schools.com/js/js_dates.asp) 62 |
63 | Solution 64 | 65 | ### Let's look at the solution: 66 | 67 | ```javascript 68 | function logSpecificDate() { 69 | let specificDate = new Date('2024-12-25T00:00:00'); 70 | console.log(specificDate); // Logs: Thu Dec 25 2024 00:00:00 GMT+0000 (UTC) 71 | } 72 | 73 | logSpecificDate(); // Calling the function 74 | 75 | 76 | ``` 77 | **Explanation:** 78 | -The function logSpecificDate creates a Date object for the specific date '2024-12-25T00:00:00' and logs it. 79 | 80 | -When calling logSpecificDate(), it logs the date in the console in the default format. 81 |
82 | 83 | ---- 84 | ###### ` Question 3:Get Current Year, Month, Date` 85 | 86 | Description:Write a javascript program where print the year date and month using the different function of date object. 87 | 88 | `Example:` 89 | 90 | ```javascript 91 | 92 | function logCurrentDateInfo() { 93 | //code here 94 | } 95 | 96 | logCurrentDateInfo(); // Calling the function 97 | 98 | 99 | ``` 100 | `Topics Covered:` 101 | Date Object getFullYear getDate getMonth. 102 | 103 | **Hints:** 104 | - [Date Object,getFullYear, getDate, getMonth](https://www.geeksforgeeks.org/how-to-get-day-month-and-year-from-date-object-in-javascript/#:~:text=The%20getMonth()%20method%20to,year%20from%20the%20Date%20object.) 105 |
106 | Solution 107 | 108 | ### Let's look at the solution: 109 | 110 | ```javascript 111 | function logCurrentDateInfo() { 112 | let currentDate = new Date(); 113 | console.log('Year:', currentDate.getFullYear()); // Logs current year 114 | console.log('Month:', currentDate.getMonth() + 1); // Logs current month (0-indexed) 115 | console.log('Date:', currentDate.getDate()); // Logs current date 116 | } 117 | 118 | logCurrentDateInfo(); // Calling the function 119 | 120 | 121 | ``` 122 | **Explanation:** 123 | -The function logCurrentDateInfo creates a new Date object, and then logs the current year, month (adding 1 to adjust for the zero-based index), and date to the console. 124 | 125 | -Calling logCurrentDateInfo() triggers the function and prints the current date details. 126 |
127 | 128 | ---- 129 | ###### ` Question 4:Format Date as a String` 130 | 131 | Description:Write a javascript program where print the current date and formate the date in the readable formate. 132 | `Example:` 133 | 134 | ```javascript 135 | 136 | function logFormattedDate() { 137 | //code here 138 | } 139 | 140 | logFormattedDate(); // Calling the function 141 | 142 | ``` 143 | `Topics Covered:` 144 | Date Object,toDateString(). 145 | 146 | **Hints:** 147 | - [Date Object,toDateString().](https://www.w3schools.com/js/js_dates.asp) 148 |
149 | Solution 150 | 151 | ### Let's look at the solution: 152 | 153 | ```javascript 154 | function logFormattedDate() { 155 | let currentDate = new Date(); 156 | let formattedDate = currentDate.toDateString(); // Formats the date as a string 157 | console.log(formattedDate); // Logs the formatted date, e.g., "Tue Dec 21 2024" 158 | } 159 | 160 | logFormattedDate(); // Calling the function 161 | 162 | 163 | ``` 164 | **Explanation:** 165 | -The function logFormattedDate creates a Date object for the current date and formats it using toDateString() to display the date in a readable format (e.g., "Tue Dec 21 2024"). 166 | 167 | -When the function is called, it logs the formatted date to the console. 168 |
169 | 170 | ---- 171 | ###### ` Question 5:Get Day of the Week` 172 | 173 | Description:Write a javascript program where print the day of week according to date.For this firstly find the day then return the day of week from that. 174 | `Example:` 175 | 176 | ```javascript 177 | 178 | function logDayOfWeek() { 179 | //code here 180 | } 181 | 182 | logDayOfWeek(); // Calling the function 183 | 184 | 185 | ``` 186 | `Topics Covered:` 187 | Date Object getDay() 188 | 189 | **Hints:** 190 | - [Date Object, getDay()](https://www.w3schools.com/js/js_dates.asp) 191 |
192 | Solution 193 | 194 | ### Let's look at the solution: 195 | 196 | ```javascript 197 | function logDayOfWeek() { 198 | let currentDate = new Date(); 199 | let dayOfWeek = currentDate.getDay(); // Gets the day of the week (0 = Sunday, 1 = Monday, etc.) 200 | console.log('Day of the week:', dayOfWeek); // Logs the day (0 = Sunday, 1 = Monday, etc.) 201 | } 202 | 203 | logDayOfWeek(); // Calling the function 204 | 205 | 206 | ``` 207 | **Explanation:** 208 | -The function logDayOfWeek creates a Date object for the current date and uses getDay() to retrieve the day of the week (0 for Sunday, 1 for Monday, etc.). 209 | 210 | -The function then logs this day to the console when called. 211 |
212 | 213 | ---- 214 | ###### ` Question 6:Add Days to a Date` 215 | 216 | Description:Write a javascript program where manipulate the current date by adding some extra date and return the updated date from it. 217 | `Example:` 218 | 219 | ```javascript 220 | 221 | function getFutureDate(daysToAdd) { 222 | //code here 223 | } 224 | 225 | console.log(getFutureDate(5)); // Logs the date 5 days from today 226 | 227 | 228 | ``` 229 | `Topics Covered:` 230 | Date Object, getDate() 231 | 232 | **Hints:** 233 | - [Date Object, getDate()](https://www.w3schools.com/js/js_dates.asp) 234 |
235 | Solution 236 | 237 | ### Let's look at the solution: 238 | 239 | ```javascript 240 | function getFutureDate(daysToAdd) { 241 | let currentDate = new Date(); 242 | currentDate.setDate(currentDate.getDate() + daysToAdd); 243 | return currentDate; 244 | } 245 | 246 | console.log(getFutureDate(5)); // Logs the date 5 days from today 247 | 248 | ``` 249 | **Explanation:** 250 | -getFutureDate(daysToAdd) accepts a number (daysToAdd) and adds that many days to the current date. 251 | 252 | -The function then returns the updated date. 253 |
254 | 255 | ---- 256 | ###### ` Question 7:Subtract Days from a Date` 257 | 258 | Description:Write a javascript program where manipulate the current date by subtracting some date and return the updated date from it. 259 | `Example:` 260 | 261 | ```javascript 262 | function subtractDaysFromCurrentDate(daysToSubtract) { 263 | //code here 264 | } 265 | 266 | // Example usage: 267 | let updatedDate = subtractDaysFromCurrentDate(10); // Subtract 10 days from the current date 268 | console.log(updatedDate); // Logs the updated date 269 | 270 | 271 | ``` 272 | `Topics Covered:` 273 | Date Object, getDate() 274 | 275 | **Hints:** 276 | - [Date Object, getDate()](https://www.w3schools.com/js/js_dates.asp) 277 |
278 | Solution 279 | 280 | ### Let's look at the solution: 281 | 282 | ```javascript 283 | function subtractDaysFromCurrentDate(daysToSubtract) { 284 | let currentDate = new Date(); // Get the current date 285 | currentDate.setDate(currentDate.getDate() - daysToSubtract); // Subtract the specified number of days 286 | return currentDate; // Return the updated date 287 | } 288 | 289 | // Example usage: 290 | let updatedDate = subtractDaysFromCurrentDate(10); // Subtract 10 days from the current date 291 | console.log(updatedDate); // Logs the updated date 292 | 293 | 294 | ``` 295 | **Explanation:** 296 | -subtractDaysFromCurrentDate(daysToSubtract): This function takes an argument daysToSubtract and subtracts that many days from the current date. 297 | 298 | -setDate(currentDate.getDate() - daysToSubtract): This modifies the current date by subtracting the specified number of days. 299 |
300 | 301 | ---- 302 | ###### ` Question 8:Compare Dates` 303 | 304 | Description:Write a javascript program where create a two variable date1 date2 and took a two date and then compare it on the basis of comparison print that date1 is earlier to date2 of later to date2 or same to date2. 305 | `Example:` 306 | 307 | ```javascript 308 | 309 | function compareDates(date1, date2) { 310 | //code here 311 | } 312 | 313 | // Example usage: 314 | let date1 = new Date('2024-12-25'); 315 | let date2 = new Date('2024-12-31'); 316 | 317 | compareDates(date1, date2); // Compare the two dates 318 | 319 | 320 | ``` 321 | `Topics Covered:` 322 | Date Object, getDate() 323 | 324 | **Hints:** 325 | - [Date Object, getDate()](https://www.w3schools.com/js/js_dates.asp) 326 |
327 | Solution 328 | 329 | ### Let's look at the solution: 330 | 331 | ```javascript 332 | function compareDates(date1, date2) { 333 | if (date1 < date2) { 334 | console.log('date1 is earlier than date2'); 335 | } else if (date1 > date2) { 336 | console.log('date1 is later than date2'); 337 | } else { 338 | console.log('Both dates are the same'); 339 | } 340 | } 341 | 342 | // Example usage: 343 | let date1 = new Date('2024-12-25'); 344 | let date2 = new Date('2024-12-31'); 345 | 346 | compareDates(date1, date2); // Compare the two dates 347 | 348 | ``` 349 | **Explanation:** 350 | -compareDates(date1, date2): This function takes two Date objects as parameters (date1 and date2) and compares them. 351 | 352 | -Inside the function, the comparison logic is similar to your original code: 353 | 354 | If date1 is earlier than date2, it logs 'date1 is earlier than date2'. 355 | If date1 is later than date2, it logs 'date1 is later than date2'. 356 | If the dates are the same, it logs 'Both dates are the same'. 357 |
358 | 359 | ---- 360 | ###### ` Question 9: Convert Date to Timestamp (Unix Time)` 361 | 362 | Description:Write a javascript program where convert a Date object to a Unix timestamp (milliseconds since January 1, 1970). 363 | `Example:` 364 | 365 | ```javascript 366 | 367 | function getCurrentTimestamp() { 368 | //code here 369 | } 370 | 371 | // Example usage: 372 | let timestamp = getCurrentTimestamp(); 373 | console.log('Timestamp:', timestamp); // Logs the timestamp 374 | 375 | 376 | 377 | ``` 378 | `Topics Covered:` 379 | Date Object,getTime() 380 | 381 | **Hints:** 382 | - [Date Object,getTime()](https://www.w3schools.com/js/js_dates.asp) 383 |
384 | Solution 385 | 386 | ### Let's look at the solution: 387 | 388 | ```javascript 389 | function getCurrentTimestamp() { 390 | let currentDate = new Date(); // Get the current date 391 | let timestamp = currentDate.getTime(); // Get the timestamp (milliseconds since January 1, 1970) 392 | return timestamp; // Return the timestamp 393 | } 394 | 395 | // Example usage: 396 | let timestamp = getCurrentTimestamp(); 397 | console.log('Timestamp:', timestamp); // Logs the timestamp 398 | 399 | 400 | ``` 401 | **Explanation:** 402 | -getCurrentTimestamp(): This function creates a new Date object for the current date and time, then calls .getTime() on it to get the timestamp. 403 | 404 | -.getTime(): This method returns the number of milliseconds since the Unix epoch (January 1, 1970, 00:00:00 UTC). 405 |
406 | 407 | ---- 408 | ###### ` Question 10:Get Time Difference Between Two Dates` 409 | 410 | Description:Write a program in javascript where take two variable startDate endDate and store the two date then find dateDiffrence after that find the daysDiffrence and return the difference. 411 | `Example:` 412 | 413 | ```javascript 414 | 415 | function getDaysDifference(startDate, endDate) { 416 | //code here 417 | } 418 | 419 | // Example usage: 420 | let startDate = new Date('2024-01-01'); 421 | let endDate = new Date('2024-12-31'); 422 | 423 | let daysDifference = getDaysDifference(startDate, endDate); 424 | console.log('Days difference:', daysDifference); // Logs the difference in days 425 | 426 | 427 | 428 | ``` 429 | `Topics Covered:` 430 | Date Object 431 | 432 | **Hints:** 433 | - [Date Object](https://www.w3schools.com/js/js_dates.asp) 434 |
435 | Solution 436 | 437 | ### Let's look at the solution: 438 | 439 | ```javascript 440 | function getDaysDifference(startDate, endDate) { 441 | let timeDifference = endDate - startDate; // Difference in milliseconds 442 | let daysDifference = timeDifference / (1000 * 3600 * 24); // Convert to days 443 | return daysDifference; // Return the difference in days 444 | } 445 | 446 | // Example usage: 447 | let startDate = new Date('2024-01-01'); 448 | let endDate = new Date('2024-12-31'); 449 | 450 | let daysDifference = getDaysDifference(startDate, endDate); 451 | console.log('Days difference:', daysDifference); // Logs the difference in days 452 | 453 | 454 | ``` 455 | **Explanation:** 456 | -getDaysDifference(startDate, endDate): This function takes two Date objects as parameters — startDate and endDate. 457 | 458 | -endDate - startDate: Subtracting the two dates gives the difference in milliseconds. 459 | 460 | -timeDifference / (1000 * 3600 * 24): This converts the time difference from milliseconds to days. 461 | 462 | -The denominator represents the number of milliseconds in a day (1000 milliseconds in a second, 3600 seconds in an hour, and 24 hours in a day). 463 |
464 | 465 | ---- 466 | 467 | 468 | -------------------------------------------------------------------------------- /resources/Destructuring/readme.md: -------------------------------------------------------------------------------- 1 | # Destructuring 2 | ###### ` Question 1. Extract Values from an Array` 3 | 4 | Write a program to extract specific values from an array using destructuring. For a given array, extract the first and third elements into separate variables. 5 | 6 | `Example:` 7 | 8 | ```javascript 9 | 10 | function getElements(arr) { 11 | 12 | // YOur code here 13 | 14 | } 15 | 16 | const arr = [10, 20, 30, 40, 50]; 17 | const { first, third } = getElements(arr); 18 | 19 | console.log(first); // Output: 10 20 | console.log(third); // Output: 30 21 | 22 | 23 | ``` 24 | 25 | `Topics Covered:` 26 | Destructuring in JS 27 | 28 | **Hints:** 29 | - [Destructuring](https://www.geeksforgeeks.org/destructuring-assignment-in-javascript/) 30 | - [Array and Object destructuring](https://www.honeybadger.io/blog/javascript-destructuring/) 31 | 32 |
33 | Solution 34 | 35 | ### Let's look at the solution: 36 | 37 | ```javascript 38 | 39 | function getElements(arr) { 40 | const [first, , third] = arr; 41 | return { first, third }; 42 | } 43 | 44 | const arr = [10, 20, 30, 40, 50]; 45 | const { first, third } = getElements(arr); 46 | 47 | console.log(first); // Output: 10 48 | console.log(third); // Output: 30 49 | 50 | ``` 51 | 52 | **Explanation:** 53 | 54 | 55 | - The getElements function extracts specific elements (first and third) from the array using destructuring. 56 | - Destructuring is applied to assign first and third while skipping the second element using a comma. 57 | 58 | 59 |
60 | 61 | ---- 62 | ###### ` Question 2. Swap Two Variables` 63 | 64 | Write a program to swap the values of two variables using array destructuring. The program should not use a temporary variable for swapping. 65 | 66 | `Example:` 67 | 68 | ```javascript 69 | 70 | function swapValues(a, b) { 71 | 72 | // Your code here 73 | 74 | } 75 | 76 | let a = 5, b = 10; 77 | [a, b] = swapValues(a, b); 78 | 79 | console.log(a); // Output: 10 80 | console.log(b); // Output: 5 81 | 82 | ``` 83 | 84 | `Topics Covered:` 85 | Destructuring in JS 86 | 87 | **Hints:** 88 | - [Destructuring](https://www.geeksforgeeks.org/destructuring-assignment-in-javascript/) 89 | 90 |
91 | Solution 92 | 93 | ### Let's look at the solution: 94 | 95 | ```javascript 96 | 97 | function swapValues(a, b) { 98 | return [b, a]; 99 | } 100 | 101 | let a = 5, b = 10; 102 | [a, b] = swapValues(a, b); 103 | 104 | console.log(a); // Output: 10 105 | console.log(b); // Output: 5 106 | 107 | ``` 108 | 109 | **Explanation:** 110 | 111 | 112 | - The swapValues function takes two parameters a and b and returns them in reversed order. 113 | - The function returns an array [b, a] to swap the values of a and b. 114 | 115 | 116 |
117 | 118 | ---- 119 | ###### ` Question 3. Extract Properties from an Object` 120 | 121 | Write a program to extract specific properties from an object using destructuring. Given an object, extract the name and age properties into variables. 122 | 123 | `Example:` 124 | 125 | ```javascript 126 | 127 | function getPersonDetails(person) { 128 | 129 | // Your code here 130 | 131 | } 132 | 133 | const person = { name: "Alice", age: 25, city: "New York" }; 134 | const { name, age } = getPersonDetails(person); 135 | 136 | console.log(name); // Output: Alice 137 | console.log(age); // Output: 25 138 | 139 | 140 | ``` 141 | 142 | `Topics Covered:` 143 | Destructuring in JS 144 | 145 | **Hints:** 146 | - [Destructuring](https://www.geeksforgeeks.org/destructuring-assignment-in-javascript/), - [Object Destructuring](https://www.javascripttutorial.net/javascript-object-destructuring/) 147 | 148 |
149 | Solution 150 | 151 | ### Let's look at the solution: 152 | 153 | ```javascript 154 | 155 | function getPersonDetails(person) { 156 | const { name, age } = person; 157 | return { name, age }; 158 | } 159 | 160 | const person = { name: "Alice", age: 25, city: "New York" }; 161 | const { name, age } = getPersonDetails(person); 162 | 163 | console.log(name); // Output: Alice 164 | console.log(age); // Output: 25 165 | 166 | ``` 167 | 168 | **Explanation:** 169 | 170 | 171 | - The getPersonDetails function extracts the name and age properties from the person object using destructuring. 172 | - Destructuring is applied inside the function to extract the required properties. 173 | 174 | 175 |
176 | 177 | ---- 178 | ###### ` Question 4. Default Values in Destructuring` 179 | 180 | Write a program to use default values in destructuring. If the property or element does not exist, assign a default value. Extract a name and gender from the object, with gender defaulting to "Unknown". 181 | 182 | `Example:` 183 | 184 | ```javascript 185 | 186 | function getPersonDetails(person) { 187 | 188 | // Your code here 189 | 190 | } 191 | 192 | const person = { name: "Bob", age: 30 }; 193 | const { name, gender } = getPersonDetails(person); 194 | 195 | console.log(name); // Output: Bob 196 | console.log(gender); // Output: Unknown 197 | 198 | 199 | ``` 200 | 201 | `Topics Covered:` 202 | Destructuring in JS 203 | 204 | **Hints:** 205 | - [Destructuring](https://www.geeksforgeeks.org/destructuring-assignment-in-javascript/), - [Object Destructuring](https://www.javascripttutorial.net/javascript-object-destructuring/) 206 | 207 |
208 | Solution 209 | 210 | ### Let's look at the solution: 211 | 212 | ```javascript 213 | 214 | function getPersonDetails(person) { 215 | const { name, gender = "Unknown" } = person; 216 | return { name, gender }; 217 | } 218 | 219 | const person = { name: "Bob", age: 30 }; 220 | const { name, gender } = getPersonDetails(person); 221 | 222 | console.log(name); // Output: Bob 223 | console.log(gender); // Output: Unknown 224 | 225 | ``` 226 | 227 | **Explanation:** 228 | 229 | 230 | - The getPersonDetails function extracts name and gender from the person object, providing a default value for gender if it's not present. 231 | - Destructuring is used to extract name and provide a default value "Unknown" for gender. 232 | 233 | 234 |
235 | 236 | ---- 237 | ###### ` Question 5. Nested Object Destructuring` 238 | 239 | Write a program to extract values from a nested object using destructuring. For a given object, extract the city property of the address. 240 | 241 | `Example:` 242 | 243 | ```javascript 244 | 245 | function getPersonDetails(person) { 246 | 247 | // Your code here 248 | 249 | } 250 | 251 | const person = { name: "Bob", age: 30 }; 252 | const { name, gender } = getPersonDetails(person); 253 | 254 | console.log(name); // Output: Bob 255 | console.log(gender); // Output: Unknown 256 | 257 | 258 | 259 | ``` 260 | 261 | `Topics Covered:` 262 | Destructuring in JS 263 | 264 | **Hints:** 265 | - [Destructuring](https://www.geeksforgeeks.org/destructuring-assignment-in-javascript/), - [Object Destructuring](https://www.javascripttutorial.net/javascript-object-destructuring/) 266 | 267 |
268 | Solution 269 | 270 | ### Let's look at the solution: 271 | 272 | ```javascript 273 | 274 | function getPersonDetails(person) { 275 | const { name, gender = "Unknown" } = person; 276 | return { name, gender }; 277 | } 278 | 279 | const person = { name: "Bob", age: 30 }; 280 | const { name, gender } = getPersonDetails(person); 281 | 282 | console.log(name); // Output: Bob 283 | console.log(gender); // Output: Unknown 284 | 285 | ``` 286 | 287 | **Explanation:** 288 | 289 | 290 | - The getPersonDetails function extracts name and gender from the person object, providing a default value for gender if it's not present. 291 | - Destructuring is used to extract name and provide a default value "Unknown" for gender. 292 | 293 | 294 |
295 | 296 | ---- 297 | ###### ` Question 6. Rest Operator in Array Destructuring` 298 | 299 | Write a program to extract values from a nested object using destructuring. For a given object, extract the city property of the address. 300 | 301 | `Example:` 302 | 303 | ```javascript 304 | 305 | function splitArray(arr) { 306 | 307 | // Your code here 308 | 309 | } 310 | 311 | const arr = [1, 2, 3, 4, 5]; 312 | const { first, second, rest } = splitArray(arr); 313 | 314 | console.log(first, second); // Output: 1 2 315 | console.log(rest); // Output: [3, 4, 5] 316 | 317 | 318 | 319 | 320 | ``` 321 | 322 | `Topics Covered:` 323 | Destructuring in JS, Rest 324 | 325 | **Hints:** 326 | - [Rest](https://www.geeksforgeeks.org/javascript-rest-operator/), - [Destructuring](https://www.geeksforgeeks.org/destructuring-assignment-in-javascript/) 327 | 328 |
329 | Solution 330 | 331 | ### Let's look at the solution: 332 | 333 | ```javascript 334 | 335 | function splitArray(arr) { 336 | const [first, second, ...rest] = arr; 337 | return { first, second, rest }; 338 | } 339 | 340 | const arr = [1, 2, 3, 4, 5]; 341 | const { first, second, rest } = splitArray(arr); 342 | 343 | console.log(first, second); // Output: 1 2 344 | console.log(rest); // Output: [3, 4, 5] 345 | 346 | ``` 347 | 348 | **Explanation:** 349 | 350 | 351 | - The splitArray function uses destructuring to extract first and second elements from the array, and gathers the remaining elements into rest. 352 | - The function splits the array into specific elements (first, second) and collects the rest into a new array (rest). 353 | 354 | 355 |
356 | 357 | ---- 358 | ###### ` Question 7. Function Parameter Destructuring` 359 | 360 | Write a program to destructure an object directly in a function’s parameters. Create a function that takes an object and extracts its name and age properties for use within the function. 361 | 362 | `Example:` 363 | 364 | ```javascript 365 | 366 | function displayInfo(person) { 367 | 368 | // Your code here 369 | 370 | } 371 | 372 | displayInfo({ name: "Charlie", age: 35, city: "London" }); 373 | // Output: Name: Charlie, Age: 35 374 | 375 | 376 | ``` 377 | 378 | `Topics Covered:` 379 | Destructuring in JS, Rest 380 | 381 | **Hints:** 382 | - [Rest](https://www.geeksforgeeks.org/javascript-rest-operator/), - [Destructuring](https://www.geeksforgeeks.org/destructuring-assignment-in-javascript/) 383 | 384 |
385 | Solution 386 | 387 | ### Let's look at the solution: 388 | 389 | ```javascript 390 | 391 | function displayInfo(person) { 392 | console.log("Name: " + person.name + ", Age: " + person.age); 393 | } 394 | 395 | displayInfo({ name: "Charlie", age: 35, city: "London" }); 396 | // Output: Name: Charlie, Age: 35 397 | 398 | 399 | ``` 400 | 401 | **Explanation:** 402 | 403 | 404 | - The displayInfo function takes an object person and accesses name and age properties to log them. 405 | - The + operator is used to concatenate the string and variables. 406 | 407 |
408 | 409 | ---- 410 | -------------------------------------------------------------------------------- /resources/Fetch_Api/readme.md: -------------------------------------------------------------------------------- 1 | # Fetch Api 2 | 3 | ###### ` Question 1: Fetch Data from API` 4 | 5 | Write a function fetchData that fetches data from the following URL and returns the JSON response. 6 | 7 | `Example:` 8 | 9 | ```javascript 10 | 11 | async function fetchData() { 12 | const url = "https://jsonplaceholder.typicode.com/posts"; 13 | //Your code here 14 | } 15 | 16 | // Example usage 17 | fetchData().then(data => console.log(data)); 18 | 19 | 20 | ``` 21 | 22 | `Topics Covered:` 23 | Error handling, Async/Await, fetch api 24 | 25 | **Hints:** 26 | - [Error handling](https://www.w3schools.com/js/js_errors.asp), - [Async/Await](https://www.w3schools.com/js/js_async.asp), - [fetch api](https://www.w3schools.com/jsref/api_fetch.asp) 27 | 28 |
29 | Solution 30 | 31 | ### Let's look at the solution: 32 | 33 | ```javascript 34 | 35 | async function fetchData() { 36 | const url = "https://jsonplaceholder.typicode.com/posts"; 37 | 38 | try { 39 | const response = await fetch(url); // Fetch data from the API 40 | const data = await response.json(); // Parse JSON response 41 | return data; // Return the array of objects 42 | } catch (error) { 43 | console.error("Error fetching data:", error); 44 | } 45 | } 46 | 47 | // Example usage 48 | fetchData().then(data => console.log(data)); 49 | 50 | 51 | ``` 52 | 53 | **Explanation:** 54 | 55 | 56 | ### Function: fetchData() 57 | 58 | **Purpose**: Fetches data from the API (https://jsonplaceholder.typicode.com/posts). 59 | 60 | #### Steps: 61 | 1. Sends a request to the specified URL using fetch(). 62 | 2. Waits for the response and parses it as JSON using response.json(). 63 | 3. Returns the parsed data (array of objects). 64 | 65 | #### Error Handling: 66 | - If there's an error during the fetch operation, it logs the error message to the console. 67 | 68 | ### Usage: 69 | - The fetchData() function is called and the resulting data is logged to the console using .then(data => console.log(data)). 70 | 71 | 72 |
73 | 74 | ---- 75 | ###### ` Question 2: Fetch with Query Parameters` 76 | 77 | Write a function fetchPostsByUser that fetches posts by a specific user ID from the following URL: 78 | API URL:https://jsonplaceholder.typicode.com/posts?userId=USER_ID 79 | 80 | `Example:` 81 | 82 | ```javascript 83 | 84 | async function fetchPostsByUser(userId) { 85 | const url = `https://jsonplaceholder.typicode.com/posts?userId=${userId}`; // Add query parameter 86 | //Your code here 87 | } 88 | 89 | // Example usage 90 | fetchPostsByUser(1).then(posts => console.log(posts)); 91 | 92 | 93 | 94 | ``` 95 | 96 | `Topics Covered:` 97 | Error handling, Async/Await, fetch api 98 | 99 | **Hints:** 100 | - [Error handling](https://www.w3schools.com/js/js_errors.asp), - [Async/Await](https://www.w3schools.com/js/js_async.asp), - [fetch api](https://www.w3schools.com/jsref/api_fetch.asp) 101 | 102 |
103 | Solution 104 | 105 | ### Let's look at the solution: 106 | 107 | ```javascript 108 | 109 | async function fetchPostsByUser(userId) { 110 | const url = `https://jsonplaceholder.typicode.com/posts?userId=${userId}`; // Add query parameter 111 | 112 | try { 113 | const response = await fetch(url); // Fetch posts for the specific user 114 | const posts = await response.json(); // Parse JSON response 115 | return posts; // Return the array of posts 116 | } catch (error) { 117 | console.error("Error fetching posts:", error); 118 | } 119 | } 120 | 121 | // Example usage 122 | fetchPostsByUser(1).then(posts => console.log(posts)); 123 | 124 | 125 | 126 | ``` 127 | 128 | **Explanation:** 129 | 130 | 131 | ## Function: fetchPostsByUser(userId) 132 | 133 | ## Purpose: 134 | Fetches posts for a specific user from the API [https://jsonplaceholder.typicode.com/posts](https://jsonplaceholder.typicode.com/posts). 135 | 136 | ## Steps: 137 | 1. Constructs the API URL with the provided userId as a query parameter: 138 | `https://jsonplaceholder.typicode.com/posts?userId=${userId}`; 139 | 2. Sends a request to the URL using fetch(). 140 | 3. Waits for the response and parses it as JSON using response.json(). 141 | 4. Returns the parsed data (an array of posts). 142 | 143 | ## Error Handling: 144 | - If there's an error during the fetch operation, it logs the error message to the console. 145 | 146 | ## Usage: 147 | - The fetchPostsByUser(1) function is called with userId = 1, and the resulting posts are logged to the console using .then(posts => console.log(posts)). 148 | 149 | 150 |
151 | 152 | ---- 153 | ###### ` Question 3: Cancel Fetch Request` 154 | 155 | Write a function cancelRequest that uses the Fetch API and AbortController to cancel a request to this URL after 3 seconds if it doesn't complete. 156 | API URL:https://jsonplaceholder.typicode.com/posts 157 | 158 | `Example:` 159 | 160 | ```javascript 161 | 162 | async function cancelRequest() { 163 | //Your code here 164 | } 165 | 166 | // Example usage: 167 | cancelRequest().then(console.log).catch(console.error); 168 | 169 | 170 | ``` 171 | 172 | `Topics Covered:` 173 | Error handling, Async/Await, fetch api 174 | 175 | **Hints:** 176 | - [Error handling](https://www.w3schools.com/js/js_errors.asp), - [Async/Await](https://www.w3schools.com/js/js_async.asp), - [fetch api](https://www.w3schools.com/jsref/api_fetch.asp) 177 | 178 |
179 | Solution 180 | 181 | ### Let's look at the solution: 182 | 183 | ```javascript 184 | 185 | async function cancelRequest() { 186 | const controller = new AbortController(); // Create AbortController 187 | const signal = controller.signal; 188 | 189 | setTimeout(() => { 190 | controller.abort(); // Cancel the request after 3 seconds 191 | }, 3000); 192 | 193 | try { 194 | const response = await fetch('https://jsonplaceholder.typicode.com/posts', { signal }); 195 | const data = await response.json(); 196 | return data; 197 | } catch (error) { 198 | if (error.name === 'AbortError') { 199 | return 'Request canceled'; // Handle request cancellation 200 | } 201 | throw error; 202 | } 203 | } 204 | 205 | // Example usage: 206 | cancelRequest().then(console.log).catch(console.error); 207 | 208 | 209 | ``` 210 | 211 | **Explanation:** 212 | 213 | 214 | ## Function: cancelRequest() 215 | 216 | ## Purpose: 217 | Cancels an API request after 3 seconds using AbortController. 218 | 219 | ## Steps: 220 | 1. Creates an AbortController and sets a 3-second timeout to abort the request. 221 | 2. Sends a fetch request to the API with the signal from the controller. 222 | 3. Handles responses: 223 | - If completed, parses and returns the data. 224 | - If aborted, returns "Request canceled." 225 | 4. Logs or handles other errors if they occur. 226 | 227 | ## Usage: 228 | 1. Calls cancelRequest(). 229 | 2. Logs either the API data or "Request canceled" to the console. 230 | 231 |
232 | 233 | ---- 234 | ###### ` Question 4: Fetch and Update DOM` 235 | 236 | Write a function fetchAndUpdateDOM that fetches a list of users and dynamically creates a