├── LICENSE └── README.md /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2022 Vasu Awasthi 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 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: "Tricky Javascript Code Snippets Questions Asked in the Interview (es6/es7/es8/es9)" 3 | description: "Prepare for your next 2025 Javascript Coding Interview Questions with these tricky code snippets. Covering ES6/ES7/ES8/ES9 syntax and features, this article provides examples and explanations to help you ace your interview." 4 | githubPath: "https://github.com/Vasu7389/JavaScript-Interview-Questions" 5 | --- 6 | 7 | Updated Jan 11, 2025 8 | 9 | In this article, we will cover a range of JavaScript interview questions, including those related to the latest versions of the language (ES6, ES7, ES8, and ES9). 10 | 11 | We'll also compare the differences between ES5 and the newer versions of the language and provide examples of ES6 code snippets. 12 | 13 | Additionally, we'll include multiple choice questions (MCQs) on ES6 and explore some of the trickiest code snippets that are commonly asked in JavaScript interviews. 14 | 15 | Whether you're preparing for a job interview or simply want to brush up on your knowledge of the language, this article has something for you. 16 | 17 | ## Javascript Coding Interview Questions ES6 ES7 ES8 18 | 19 | ECMAScript (ES) is a standardized version of JavaScript, a programming language that is widely used to create interactive web pages and applications. ECMAScript is a formal specification developed and maintained by the Ecma International organization. 20 | 21 | JavaScript is a programming language that is commonly used to create interactive web pages and applications. It is based on the ECMAScript specification and is an implementation of it. JavaScript is a client-side scripting language, meaning it is executed by the user's web browser rather than a server. It is used to create dynamic and interactive elements on web pages, such as form validation, image sliders, and modal windows. 22 | 23 | ECMAScript and JavaScript are closely related, and the terms are often used interchangeably. However, ECMAScript is the formal specification, and JavaScript is the implementation of that specification. 24 | 25 | \*Discover the answers by clicking on the questions. 26 | 27 |
28 | 29 |

1. Guess the output of this code? Beginner 🚂 30 | 31 | ```js 32 | let a = {}; 33 | let b = { key: "b" }; 34 | let c = { key: "c" }; 35 | 36 | a[b] = 123; 37 | a[c] = 456; 38 | 39 | console.log(a[b]); 40 | ``` 41 | 42 |

43 |
44 | 45 | The output of this code will be `456`. 46 | 47 | In this code, a is an empty object that is being assigned properties using the square bracket notation. The values of the properties are being set to the numbers `123` and `456`. The keys of the properties are the objects b and c. 48 | 49 | When the `console.log` statement is executed, it logs the value of the property of a whose `key` is the object `b`. In this case, the value of this property is 456, because the value of the property was last set to 456 when the object c was used as the key. 50 | 51 | This behavior occurs because when objects are used as keys in an object, the object's default behavior is to convert the object to a string representation. In this case, both b and c are converted to the string `[object Object]`, which means that they both end up being used as the same key in the a object. As a result, the value of the property that is set using the object c as the key overwrites the value of the property that was set using the object b as the key. 52 | 53 | So the object `a` looks like - 54 | 55 | ```js 56 | { 57 | "[object Object]": 456 58 | } 59 | ``` 60 | 61 |
62 | 63 |
64 | 65 |

2. Guess the output of this code? Beginner 🚂 66 | 67 | ```js 68 | let obj1 = { key: "value" }; 69 | let obj2 = obj1; 70 | let obj3 = obj2; 71 | 72 | obj1.key = "new value"; 73 | obj2 = { key: "another value" }; 74 | 75 | console.log(obj1.key, obj2.key, obj3.key); 76 | ``` 77 | 78 |

79 |
80 | The output of this code will be `new value` `another value` `new value`. 81 | 82 | In this code, we are declaring three variables obj1, obj2, and obj3, and assigning an object to each of them. Then, we are reassigning a new object to obj2 and modifying a property of obj1. 83 | 84 | When the console.log statement is executed, it logs the values of the key property for each object. The value of the key property for obj1 is "new value", the value of the key property for obj2 is "another value", and the value of the key property for obj3 is "new value". 85 | 86 | This is because when an object is assigned to a variable, the variable stores a reference to the object in memory rather than the object itself. Changing the value of a property of the object using one variable will affect the value of that property when accessed using a different variable that references the same object. However, reassigning a new object to a variable will change the reference stored in that variable, so the original object is no longer accessible using that variable. 87 | 88 | In this case, the value of the key property for obj1 was changed to "new value" using the obj1 variable, which affected the value of the key property when accessed using the obj3 variable, because both variables reference the same object. However, the value of the key property for obj2 was not affected, because the obj2 variable was reassigned to reference a new object. 89 | 90 |
91 | 92 |
93 | 94 |

3. Guess the output of this JavaScript code? Intermediate 🚁 95 | 96 | ```js 97 | const obj = { 98 | a: "foo", 99 | b: function () { 100 | console.log(this.a); 101 | }, 102 | }; 103 | 104 | const c = obj.b; 105 | 106 | obj.b(); 107 | c(); 108 | ``` 109 | 110 |

111 |
112 | 113 | Answer - foo, undefined 114 | 115 | When the method obj.b is called directly on obj, the output will be "foo". This is because this refers to the object that the method is called on, and obj.a is equal to "foo". 116 | 117 | When the variable c is assigned the value of obj.b, it is a reference to the function itself and not the object obj. When c is called, it is not called on an object, so this will not refer to obj and the value of this.a is undefined. As a result, the output when calling c() will be undefined. 118 | 119 |
120 | 121 |
122 | 123 |

4. Guess the output of this code? Beginner 🚂 124 | 125 | ```js 126 | const x = { foo: 1 }; 127 | const y = { foo: 2 }; 128 | 129 | function addFoo(obj) { 130 | return obj.foo + 1; 131 | } 132 | 133 | console.log(addFoo(x)); 134 | console.log(addFoo(y)); 135 | ``` 136 | 137 |

138 |
139 | Answer - 2, 3 140 | 141 | The addFoo function takes an object as an argument and returns the value of obj.foo + 1. When addFoo is called with x as the argument, the output will be 2, because x.foo is equal to 1. When addFoo is called with y as the argument, the output will be 3, because y.foo is equal to 2. 142 | 143 |
144 |
145 | 146 |

5. Guess the output of below JavaScript code? Beginner 🚂 147 | 148 | ```js 149 | const arr = [1, 2, 3, 4, 5]; 150 | 151 | for (var i = 0; i < arr.length; i++) { 152 | setTimeout(function () { 153 | console.log(i); 154 | }, 1000); 155 | } 156 | ``` 157 | 158 |

159 |
160 | Answer - 5, 5, 5, 5, 5 161 | 162 | The setTimeout function is called inside of a loop that iterates through the elements in the arr array. The setTimeout function will execute its callback function after a delay of 1000 milliseconds. However, by the time the delay has elapsed and the callback function is called, the loop will have already completed and the value of i will be 5. As a result, the output will be 5 printed five times. 163 | 164 |
165 |
166 | 167 |

6. Guess the output of this JavaScript code? Beginner 🚂 168 | 169 | ```js 170 | const arr = [1, 2, 3, 4, 5]; 171 | 172 | arr.forEach(function (element) { 173 | console.log(element); 174 | }); 175 | ``` 176 | 177 |

178 |
179 | Answer - 1, 2, 3, 4, 5 180 | 181 | The forEach method is called on the arr array and a callback function is passed as an argument. The callback function will be executed for each element in the array, with the element passed as an argument to the callback. As a result, the output will be the elements of the array, 1, 2, 3, 4, and 5, printed on separate lines. 182 | 183 |
184 | 185 |
186 | 187 |

7. Guess the output of this code?
Expert 🚀
188 | 189 | ```js 190 | let x = 1; 191 | 192 | if (function f() {}) { 193 | x += typeof f; 194 | } 195 | 196 | console.log(x); 197 | ``` 198 | 199 |

200 |
201 | Answer - 1undefined 202 | 203 | The if statement is evaluating the function f as a boolean value. In JavaScript, functions are truthy values, so the condition will evaluate to true and the code block inside the if statement will be executed. The value of x is then incremented by the string "undefined", which is the result of calling typeof f. 204 | 205 |
206 | 207 |
208 | 209 |

8. Guess the output of this code? Beginner 🚂 210 | 211 | ```js 212 | let a = { 213 | x: 1, 214 | y: 2, 215 | }; 216 | let b = a; 217 | a.x = 5; 218 | console.log(a); 219 | console.log(b); 220 | ``` 221 | 222 |

223 |
224 | 225 | Answer - {x:5, y:2} {x:5, y:2} 226 | 227 | JavaScript objects are passed by reference. So when we assigned a object to b. b also pointing to the same object in memory. When we change the value of a.x it also affects b.x 228 | 229 |
230 | 231 |
232 | 233 |

9. Guess the output of this code? Intermediate 🚁 234 | 235 | ```js 236 | let x = [1, 2, 3]; 237 | let y = [1, 2, 3]; 238 | let z = y; 239 | 240 | console.log(x == y); 241 | console.log(x === y); 242 | console.log(z == y); 243 | console.log(z == x); 244 | ``` 245 | 246 |

247 |
248 | Answer - 249 | 250 | false 251 | false 252 | true 253 | false 254 | 255 | When comparing two objects with the == operator, it compares their references, not their values. In this case, x and y are different objects with the same values. z is assigned the value of y, so they refer to the same object. As a result, the first comparison returns false, the second comparison also returns false and the third comparison returns true. and the last comparison also returns false. 256 | 257 |
258 | 259 |
260 | 261 |

10. Guess the output of the below JavaScript code? Beginner 🚂 262 | 263 | ```js 264 | var x = 0; 265 | for (let i = 0; i < 5; i++) { 266 | setTimeout(() => { 267 | x++; 268 | console.log(x); 269 | }, 1000); 270 | } 271 | ``` 272 | 273 |

274 |
275 | 276 | Answer: 277 | 278 | 1 279 | 2 280 | 3 281 | 4 282 | 5 283 | 284 | The for loop is iterating 5 times, and in each iteration, it is scheduling a function to be invoked after 1000 milliseconds (1 second) using setTimeout. 285 | This function increments the value of `x` and logs it. 286 | 287 | But all the 5 functions invoked after 1000 milliseconds. 288 | 289 | Since, javascript is single threaded and event loop queue all the functions in the event loop and execute them one by one. 290 | 291 | But inside each `setTimeout` callback execution, `x++` increments `x` value by 1. 292 | 293 | _It makes difference when position of `x++` code changes wrt the setTimout callback._ 294 | 295 | So all the 5 `callbacks` logs the values in `incremental` way, which is `1 2 3 4 5`. 296 | 297 |
298 | 299 |
300 | 301 |

11. Guess the output of this JavaScript code? Beginner 🚂 302 | 303 | ```js 304 | let a = { x: 1 }; 305 | let b = { x: 2 }; 306 | let c = { x: 3 }; 307 | let d = { x: 4 }; 308 | let e = { x: 5 }; 309 | let arr = [a, b, c, d, e]; 310 | 311 | arr.forEach((obj) => (obj.x = obj.x * 2)); 312 | 313 | console.log(a.x, b.x, c.x, d.x, e.x); 314 | ``` 315 | 316 |

317 |
318 | Answer: 319 | 320 | 2 4 6 8 10 321 | 322 | The code is using the `forEach` method to iterate over an array of objects, and it is modifying the `x` property of each object by multiplying it by 2. 323 | 324 | It's updating the original objects with `x*2` values. 325 | 326 | So, the output of the code is 2 4 6 8 10. 327 | 328 |
329 | 330 |
331 | 332 |

12. Guess the output of the JavaScript code? Beginner 🚂 333 | 334 | ```js 335 | let num = 0; 336 | 337 | function test() { 338 | var num = 1; 339 | return num; 340 | } 341 | 342 | console.log(test()); 343 | console.log(num); 344 | ``` 345 | 346 |

347 |
348 | Answer: 349 | 1 350 | 0 351 | 352 | The code defines a global variable num with the value of 0 and then a function test which declares a local variable num with the value of 1 and returns it. 353 | 354 | When test() is called, it first declares a local variable num with the value of 1. 355 | 356 | Then the function return statement logs 1 on the console. 357 | 358 | After that, it logs the value of global variable num which is 0. 359 | 360 | Because the global and local variables have different scope and different memory allocation. 361 | 362 |
363 | 364 |
365 | 366 |

13. Guess the output of the below JavaScript code? Beginner 🚂 367 | 368 | ```js 369 | let obj = { name: "John", age: 25 }; 370 | let newObj = { ...obj, age: 30 }; 371 | 372 | console.log(obj.age); 373 | console.log(newObj.age); 374 | ``` 375 | 376 |

377 |
378 | Answer: 379 | 25 380 | 30 381 | 382 | The code creates an object obj with properties name and age. Then it creates a new object newObj using the spread operator to copy the properties of obj and then it updates the age property to 30. 383 | 384 | The spread operator `...` creates a new object with properties copied from the original object. 385 | 386 | So, the first console.log statement logs the value of age property of obj which is `25`. 387 | 388 | And, the second console.log statement logs the value of age property of newObj which is `30`. 389 | 390 | It doesn't affect the original object `obj`. 391 | 392 |
393 | 394 |
395 | 396 |

14. Guess the output of the below JavaScript code? Intermediate 🚁 397 | 398 | ```js 399 | const add = (a = 1, b = 2) => a + b; 400 | console.log(add()); 401 | console.log(add(5)); 402 | console.log(add(undefined, 10)); 403 | ``` 404 | 405 |

406 |
407 | 408 | Answer: 409 | 410 | ```bash 411 | 3 412 | 7 413 | 11 414 | ``` 415 | 416 | The code defines a function add which takes two parameters a and b and returns the sum of both. It uses default parameters to assign default values 1 to a and 2 to b if they are not provided. 417 | 418 | So, the first console.log statement logs the result of add() which is 1 + 2 = 3 as both the parameters are not provided and default values are used. 419 | 420 | The second console.log statement logs the result of add(5) which is 5 + 2 = 7 as only the first parameter is provided and the default value of b is used. 421 | 422 | The third console.log statement logs the result of add(undefined, 10) which is 1 + 10 = 11 as the first parameter is provided as undefined and it takes the default value 1 and the second parameter is provided as 10. 423 | 424 |
425 | 426 |
427 | 428 |

15. Guess the output of the below JavaScript code? Beginner 🚂 429 | 430 | ```js 431 | const name = "John"; 432 | const age = 25; 433 | 434 | const user = { name, age }; 435 | console.log(user); 436 | ``` 437 | 438 |

439 |
440 | 441 | Answer: 442 | 443 | ```js 444 | { name: "John", age: 25 } 445 | ``` 446 | 447 | The code defines two variables name and age with values "John" and 25 respectively. 448 | 449 | Then, it uses `object literal` notation to create an object user with properties `name` and `age` and the values are assigned from the variables name and age respectively. 450 | 451 | So, the `console.log` statement logs the user object which is `{ name: "John", age: 25 }`. 452 | 453 | In `ES6+`, you can use object literal notation to create objects with properties using the same name as the variables with the values assigned to them. 454 | 455 |
456 | 457 |
458 | 459 |

16. Guess the output of the below JavaScript code? Intermediate 🚁 460 | 461 | ```js 462 | const arr = [1, 2, 3]; 463 | const [a, b, c] = arr; 464 | 465 | console.log(a); 466 | console.log(b); 467 | console.log(c); 468 | ``` 469 | 470 |

471 |
472 | 473 | Answer: 474 | 475 | ```bash 476 | 1 477 | 2 478 | 3 479 | ``` 480 | 481 | The code defines an array arr with values [1, 2, 3]. 482 | 483 | Then, it uses `destructuring assignment` to extract the values from the array `arr` and assign them to variables `a`, `b`, and `c` respectively. 484 | 485 | So, the first console.log statement logs the value of a which is `1`. 486 | 487 | The second console.log statement logs the value of b which is `2`. 488 | 489 | The third console.log statement logs the value of c which is `3`. 490 | 491 | In ES6+, you can use destructuring assignment to extract values from arrays and objects and assign them to variables in a concise way. 492 | 493 |
494 | 495 |
496 | 497 |

17. What is the output of the below JavaScript code and why? Beginner 🚂 498 | 499 | ```js 500 | console.log(typeof null); 501 | console.log(typeof undefined); 502 | console.log(null === undefined); 503 | console.log(null == undefined); 504 | ``` 505 | 506 |

507 |
508 | Answer: 509 | 510 | ```bash 511 | object 512 | undefined 513 | false 514 | true 515 | ``` 516 | 517 | `typeof null` returns object which is an error in JavaScript. This is a historical bug in the language that cannot be fixed without breaking existing code. So, to check for `null`, you should use `===` null instead of `typeof` operator. 518 | 519 | typeof undefined returns undefined. 520 | 521 | null === undefined is false because `null` and `undefined` are two distinct types in JavaScript. 522 | 523 | null == undefined is true because `==` is the loose equality operator in JavaScript, which performs type coercion before comparison. In this case, both null and undefined are coerced to undefined before comparison, and since they both have the same value, the comparison returns true. However, it is generally recommended to use `===` instead of `==` to avoid unexpected behavior due to type coercion. 524 | 525 |
526 | 527 | ## Javascript Programming Questions 528 | 529 |
530 | 531 |

18. Write a function in JavaScript that takes an array of numbers and returns the sum of all positive numbers in the array. Beginner 🚂 532 | 533 |

534 |
535 | Answer: 536 | 537 | ```js 538 | function sumOfPositiveNumbers(numbers) { 539 | let sum = 0; 540 | for (let i = 0; i < numbers.length; i++) { 541 | if (numbers[i] > 0) { 542 | sum += numbers[i]; 543 | } 544 | } 545 | return sum; 546 | } 547 | 548 | // Example usage: 549 | const arr = [1, -2, 3, 4, -5, 6]; 550 | console.log(sumOfPositiveNumbers(arr)); // Output: 14 551 | ``` 552 | 553 | The `sumOfPositiveNumbers` function takes an array of numbers as its parameter and initializes a variable sum to `0`. It then loops through each element of the array and checks if the number is greater than 0. If the number is positive, it adds the number to the sum. Finally, it returns the sum of all positive numbers in the array. 554 | 555 | In the example usage, we pass an array `[1, -2, 3, 4, -5, 6]` to the sumOfPositiveNumbers function. The function returns the sum of all positive numbers in the array, which is `14`. 556 | 557 |
558 | 559 |
560 | 561 |

19. Write a function in JavaScript that takes a string as input and returns a new string with all the vowels removed. Intermediate 🚁 562 | 563 |

564 |
565 | Answer: 566 | 567 | ```js 568 | function removeVowels(str) { 569 | const vowels = ["a", "e", "i", "o", "u", "A", "E", "I", "O", "U"]; 570 | let newStr = ""; 571 | for (let i = 0; i < str.length; i++) { 572 | if (!vowels.includes(str[i])) { 573 | newStr += str[i]; 574 | } 575 | } 576 | return newStr; 577 | } 578 | 579 | // Example usage: 580 | const str = "This is a test string with vowels"; 581 | console.log(removeVowels(str)); // Output: Ths s tst strng wth vwls 582 | ``` 583 | 584 | The `removeVowels` function takes a string as its parameter and initializes an array vowels containing all the vowels. It then loops through each character of the input string and checks if the character is not present in the vowels array. If the character is not a vowel, it adds the character to the `newStr` string. Finally, it returns the newStr string with all the vowels removed. 585 | 586 | In the example usage, we pass a string 'This is a test string with vowels' to the removeVowels function. The function returns a new string with all the vowels removed, which is 'Ths s tst strng wth vwls'. 587 | 588 |
589 | 590 |
591 | 592 |

20. Write a function in JavaScript that takes an array of strings as input and returns a new array with the strings sorted in alphabetical order. Beginner 🚂 593 | 594 |

595 |
596 | Answer: 597 | 598 | ```js 599 | function sortStrings(arr) { 600 | return arr.sort(); 601 | } 602 | 603 | // Example usage: 604 | const strings = ["apple", "banana", "cherry", "date", "elderberry"]; 605 | console.log(sortStrings(strings)); // Output: ['apple', 'banana', 'cherry', 'date', 'elderberry'] 606 | ``` 607 | 608 | The `sortStrings` function takes an array of strings as its parameter and uses the `sort()` method to sort the array in alphabetical order. The sort() method sorts the elements of an array in place and returns the sorted array. By default, the sort() method sorts the array elements in ascending order based on the `Unicode` values of the characters. Therefore, for strings, it sorts them in alphabetical order. 609 | 610 | In the example usage, we pass an array of strings `['apple', 'banana', 'cherry', 'date', 'elderberry']` to the sortStrings function. The function returns a new array with the strings sorted in alphabetical order, which is `['apple', 'banana', 'cherry', 'date', 'elderberry']`. 611 | 612 |
613 | 614 |
615 | 616 |

21. Write a function in JavaScript that checks if a string is a palindrome. Beginner 🚂 617 | 618 |

619 |
620 | Answer: 621 | 622 | ```js 623 | function isPalindrome(str) { 624 | const reversedStr = str.split("").reverse().join(""); 625 | return str === reversedStr; 626 | } 627 | 628 | // Example usage: 629 | console.log(isPalindrome("racecar")); // Output: true 630 | console.log(isPalindrome("hello")); // Output: false 631 | ``` 632 | 633 | The `isPalindrome` function takes a string as its parameter and first reverses the string using the `split()`, `reverse()`, and `join()` methods. It then checks if the reversed string is equal to the original string and returns true if they are equal and false otherwise. 634 | 635 | In the example usage, we pass the strings `racecar` and `hello` to the isPalindrome function. The function returns true for the first string because it is a palindrome (i.e., the reversed string is equal to the original string), and false for the second string. 636 | 637 |
638 | 639 |
640 | 641 |

22. Write a function in JavaScript that finds the second highest number in an array of numbers. Beginner 🚂 642 | 643 |

644 |
645 | Answer: 646 | 647 | ```js 648 | function findSecondHighest(arr) { 649 | const sortedArr = arr.sort((a, b) => b - a); 650 | return sortedArr[1]; 651 | } 652 | 653 | // Example usage: 654 | const numbers = [10, 5, 20, 15, 8]; 655 | console.log(findSecondHighest(numbers)); // Output: 15 656 | ``` 657 | 658 | The `findSecondHighest` function takes an array of numbers as its parameter and first sorts the array in descending order using the `sort()` method and a comparison function. It then returns the second element in the sorted array, which is the second highest number. 659 | 660 | In the example usage, we pass the array `[10, 5, 20, 15, 8]` to the findSecondHighest function. The function returns `15`, which is the second highest number in the array. 661 | 662 |
663 | 664 |
665 | 666 |

23. Write a function in JavaScript that removes duplicates from an array. Beginner 🚂 667 | 668 |

669 |
670 | Answer: 671 | 672 | ```js 673 | function removeDuplicates(arr) { 674 | return [...new Set(arr)]; 675 | } 676 | 677 | // Example usage: 678 | const numbers = [1, 2, 3, 2, 1, 4, 5, 4]; 679 | console.log(removeDuplicates(numbers)); // Output: [1, 2, 3, 4, 5] 680 | ``` 681 | 682 | The `removeDuplicates` function takes an array as its parameter and first creates a Set object from the array using the `Set()` constructor. A Set is a collection of unique values, so all duplicates are automatically removed. We then use the spread syntax `(...)` to convert the Set back to an array. 683 | 684 | In the example usage, we pass the array `[1, 2, 3, 2, 1, 4, 5, 4]` to the removeDuplicates function. The function returns a new array with duplicates removed, which is `[1, 2, 3, 4, 5]`. 685 | 686 |
687 | 688 |
689 | 690 |

24. Write a function in JavaScript that returns the sum of two numbers without using the + operator.

691 |
692 | Answer: 693 | 694 | ```jsx 695 | function add(a, b) { 696 | while (b !== 0) { 697 | let carry = a & b; 698 | a = a ^ b; 699 | b = carry << 1; 700 | } 701 | return a; 702 | } 703 | 704 | // Example usage: 705 | console.log(add(5, 7)); // Output: 12 706 | ``` 707 | 708 | The add function takes two numbers a and b as its parameters and uses a bitwise approach to add them. It repeatedly performs a bitwise AND operation between a and b to get the carry bits and performs a bitwise XOR operation between a and b to get the sum bits. It then shifts the carry bits one position to the left and assigns the result to b. This process continues until b is equal to 0. The final value of a is the sum of the two numbers. 709 | 710 | In the example usage, we pass the numbers 5 and 7 to the add function. The function returns 12, which is the sum of the two numbers. 711 | 712 |
713 | 714 |
715 | 716 |

25. Write a function in JavaScript that checks if a given string is a valid IPv4 address.

Intermediate 🚁 717 | 718 |
719 | Answer: 720 | 721 | ```jsx 722 | function isValidIPv4(str) { 723 | const octets = str.split("."); 724 | if (octets.length !== 4) return false; 725 | for (let i = 0; i < octets.length; i++) { 726 | const octet = octets[i]; 727 | if (isNaN(octet) || octet < 0 || octet > 255) return false; 728 | if (octet.length > 1 && octet[0] === "0") return false; 729 | } 730 | return true; 731 | } 732 | 733 | // Example usage: 734 | console.log(isValidIPv4("192.168.0.1")); // Output: true 735 | console.log(isValidIPv4("256.0.0.0")); // Output: false 736 | ``` 737 | 738 | The `isValidIPv4` function takes a string as its parameter and checks if it is a valid `IPv4` address. 739 | 740 | An IPv4 address consists of four octets separated by periods, with each octet being a number between 0 and 255. 741 | 742 | The function first splits the string into an array of octets using the split() method. 743 | 744 | It then checks if the array has exactly four elements and if each element is a number between 0 and 255. 745 | 746 | It also checks if each octet does not start with a 0 unless it is a single-digit octet. 747 | 748 | If any of these conditions are not met, the function returns false. Otherwise, it returns true. 749 | 750 | In the example usage, we pass the strings '192.168.0.1' and '256.0.0.0' to the isValidIPv4 function. The function returns true for the first string because it is a valid IPv4 address and false for the second string because it is not a valid IPv4 address. 751 | 752 |
753 | 754 |
755 | 756 |

26. Write a function in JavaScript that converts a given string to title case. Expert 🚀 757 |

758 |
759 | Answer: 760 | 761 | ```jsx 762 | function toTitleCase(str) { 763 | return str.replace(/\b\w+/g, function (word) { 764 | return word.charAt(0).toUpperCase() + word.slice(1).toLowerCase(); 765 | }); 766 | } 767 | 768 | // Example usage: 769 | console.log(toTitleCase("the quick brown fox")); // Output: 'The Quick Brown Fox' 770 | ``` 771 | 772 | The `toTitleCase` function takes a string as its parameter and converts it to title case. Title case is a style of capitalization where the first letter of each word is capitalized, and the rest of the letters are in lowercase. 773 | 774 | The function uses a regular expression to match the first letter of each word in the string and then uses the `charAt()` and `slice()` methods to capitalize the first letter and convert the rest of the letters to lowercase. It returns the modified string. 775 | 776 | In the example usage, we pass the string 'the quick brown fox' to the toTitleCase function. The function returns 'The Quick Brown Fox', which is the string converted to title case. 777 | 778 |
779 | 780 |
781 | 782 |

27. Write a function in JavaScript that generates a random hexadecimal color code. Expert 🚀 783 |

784 |
785 | Answer: 786 | 787 | ```jsx 788 | function getRandomColor() { 789 | const hexChars = "0123456789ABCDEF"; 790 | let color = "#"; 791 | for (let i = 0; i < 6; i++) { 792 | color += hexChars[Math.floor(Math.random() * 16)]; 793 | } 794 | return color; 795 | } 796 | 797 | // Example usage: 798 | console.log(getRandomColor()); // Output: e.g. '#3D5A89' 799 | ``` 800 | 801 | The `getRandomColor` function generates a random hexadecimal color code. A hexadecimal color code is a six-digit code that represents a color by specifying the amount of red, green, and blue in it. 802 | 803 | Each digit of the code can be any of the sixteen hexadecimal characters (0 to 9 and A to F). 804 | 805 | The function generates a random color code by selecting six random hexadecimal characters from the hexChars string using the Math.random() function and concatenating them together with a # symbol. 806 | 807 | It then returns the generated color code. 808 | 809 | In the example usage, we call the getRandomColor function, which returns a randomly generated color code. The output can vary each time the function is called, but it should be a valid hexadecimal color code. 810 | 811 |
812 | 813 |
814 | 815 |

28. Guess the output of the following code:

Beginner 🚂 816 | 817 | ```jsx 818 | let x = 5; 819 | { 820 | let x = 10; 821 | console.log(x); 822 | } 823 | console.log(x); 824 | ``` 825 | 826 |
827 | 828 | The output of the code above is: 829 | 830 | Answer: 831 | 832 | ```bash 833 | 10 834 | 5 835 | ``` 836 | 837 | This is because of the block scoping behavior of the let keyword in ES6. 838 | 839 | When we declare a variable with `let` inside a block (in this case, the block is defined by the curly braces), the variable is only accessible inside that block and its sub-blocks. 840 | 841 | In the code above, we define a variable `x` outside the block with the value of `5`. Then we define another variable x inside the block with the value of 10. 842 | 843 | The first `console.log()` statement inside the block will print 10, because x refers to the variable defined inside the block. The second console.log() statement outside the block will print 5, because it refers to the variable defined outside the block. 844 | 845 |
846 | 847 |
848 | 849 |

29. Guess the output of the following code:

Beginner 🚂 850 | 851 | ```jsx 852 | const obj = { a: 1, b: 2, c: 3 }; 853 | const { a, b } = obj; 854 | console.log(a, b); 855 | ``` 856 | 857 |
858 | 859 | The output of the code above is: 860 | 861 | Answer: 862 | 863 | ```bash 864 | 1 2 865 | ``` 866 | 867 | This is because of the object destructuring syntax introduced in ES6. 868 | 869 | We declare a constant variable obj with an object containing three properties. Then we use object destructuring to extract the properties a and b from the object and assign them to separate variables with the same names. 870 | 871 | The console.log() statement then prints the values of the a and b variables, which are 1 and 2 respectively. 872 | 873 |
874 | 875 |
876 | 877 |

30. Guess the output of the following code:

Beginner 🚂 878 | 879 | ```jsx 880 | const arr1 = [1, 2, 3]; 881 | const arr2 = [4, 5, 6]; 882 | const arr3 = [...arr1, ...arr2]; 883 | console.log(arr3); 884 | ``` 885 | 886 |
887 | 888 | The output of the code above is: 889 | 890 | Answer: 891 | 892 | ```bash 893 | [1, 2, 3, 4, 5, 6] 894 | ``` 895 | 896 | This is because of the spread syntax `(...)` introduced in ES6. 897 | 898 | The `...` operator can be used to spread the elements of an array or the properties of an object into a new array or object. 899 | 900 | In the code above, we define two arrays arr1 and arr2. Then we create a new array arr3 by spreading the elements of arr1 and arr2 into it using the spread syntax. 901 | 902 | The console.log() statement then prints the contents of arr3, which are the elements of arr1 followed by the elements of arr2. 903 | 904 |
905 | 906 |
907 | 908 |

31. What is the output of the following code?

Beginner 🚂 909 | 910 | ```jsx 911 | const arr1 = [1, 2, 3]; 912 | const arr2 = [...arr1]; 913 | 914 | arr2.push(4); 915 | 916 | console.log(arr1); 917 | console.log(arr2); 918 | ``` 919 | 920 |
921 | 922 | The output of the code will be: 923 | 924 | Answer: 925 | 926 | ```bash 927 | [1, 2, 3] 928 | [1, 2, 3, 4] 929 | ``` 930 | 931 | The code creates an array arr1 with the values [1, 2, 3]. It then creates a new array arr2 using the spread syntax (...) to spread the values of arr1 into a new array. 932 | 933 | arr2.push(4) adds the value 4 to the end of arr2. 934 | 935 | However, arr1 remains unchanged because arr2 is a new array with its own reference to the values of arr1. This is known as creating a shallow copy of the array. 936 | 937 | Therefore, the first console.log(arr1) prints [1, 2, 3] and the second console.log(arr2) prints [1, 2, 3, 4]. 938 | 939 |
940 | 941 |
942 | 943 |

32. What is the output of the following code?

Beginner 🚂 944 | 945 | ```jsx 946 | const x = 10; 947 | 948 | function foo() { 949 | console.log(x); 950 | const x = 20; 951 | } 952 | 953 | foo(); 954 | ``` 955 | 956 |
957 | 958 | The output of the code will be: 959 | 960 | Answer: 961 | 962 | ```bash 963 | ReferenceError: Cannot access 'x' before initialization 964 | ``` 965 | 966 | The foo function attempts to log the value of x before it is initialized. This causes a ReferenceError to be thrown, as x is not yet defined in the function scope. 967 | 968 | This happens because of variable hoisting in JavaScript. When a variable is declared with const or let, it is not hoisted to the top of the scope like variables declared with var are. Instead, they are only accessible after they are declared. 969 | 970 | Therefore, when console.log(x) is called in the foo function, the local variable x has not yet been initialized, resulting in a ReferenceError. 971 | 972 |
973 | 974 |
975 | 976 |

33. What is the output of the following code?

Beginner 🚂 977 | 978 | ```jsx 979 | const a = [1, 2, 3]; 980 | const b = a; 981 | 982 | b.push(4); 983 | 984 | console.log(a); 985 | console.log(b); 986 | ``` 987 | 988 |
989 | 990 | The output of the code will be: 991 | 992 | Answer: 993 | 994 | ```bash 995 | [1, 2, 3, 4] 996 | [1, 2, 3, 4] 997 | ``` 998 | 999 | The code creates an array a with the values [1, 2, 3]. It then creates a new variable b and assigns it to a, creating a reference to the same array. 1000 | 1001 | b.push(4) adds the value 4 to the end of the array. 1002 | 1003 | Since a and b reference the same array, both console.log(a) and console.log(b) will print [1, 2, 3, 4]. 1004 | 1005 | This is different from the previous example where ... spread operator was used, which created a new array with the same values as the original array instead of referencing the same array. 1006 | 1007 |
1008 | 1009 |
1010 | 1011 |

34. What is the output of the following code?

Intermediate 🚁 1012 | 1013 | ```jsx 1014 | const companies = [ 1015 | { id: "1", name: "Facebook" }, 1016 | { id: "2", name: "Apple" }, 1017 | { id: "3", name: "Google" }, 1018 | ]; 1019 | 1020 | companies.sort((a, b) => (a.name > b.name ? -1 : 1)); 1021 | console.log(companies); 1022 | ``` 1023 | 1024 |
1025 | 1026 | The output of the code will be: 1027 | 1028 | Answer: 1029 | 1030 | ```bash 1031 | [ 1032 | {id: "3", name:"Google"}, 1033 | {id: "1", name:"Facebook"}, 1034 | {id: "2", name:"Apple"} 1035 | ] 1036 | ``` 1037 | 1038 | The comparison function takes two parameters, "a" and "b", which represent two elements being compared in the array. 1039 | 1040 | If the "name" property of "a" comes before the "name" property of "b" in alphabetical order, then the function returns -1, which means "a" should come before "b" in the sorted array. 1041 | 1042 | Otherwise, if the "name" property of "a" comes after the "name" property of "b" in alphabetical order, then the function returns 1, which means "b" should come before "a" in the sorted array. 1043 | 1044 |
1045 | 1046 |
1047 | 1048 |

35. Guess the output of the following code that uses the typeof operator.

Beginner 🚂 1049 | 1050 | ```js 1051 | console.log(typeof 42); 1052 | console.log(typeof "Hello"); 1053 | console.log(typeof true); 1054 | console.log(typeof [1, 2, 3]); 1055 | console.log(typeof { name: "John", age: 25 }); 1056 | console.log(typeof null); 1057 | console.log(typeof undefined); 1058 | console.log(typeof function () {}); 1059 | ``` 1060 | 1061 |
1062 | Answer: 1063 | 1064 | ``` 1065 | number 1066 | string 1067 | boolean 1068 | object 1069 | object 1070 | object 1071 | undefined 1072 | function 1073 | ``` 1074 | 1075 | The typeof operator in JavaScript is used to determine the type of a value or expression. Here's the breakdown of the output: 1076 | 1077 | - typeof 42 returns "number" because 42 is a numeric value. 1078 | - typeof "Hello" returns "string" because "Hello" is a string. 1079 | - typeof true returns "boolean" because true is a boolean value. 1080 | - typeof [1, 2, 3] returns "object" because arrays are considered objects in JavaScript. 1081 | - typeof { name: "John", age: 25 } returns "object" because objects are considered objects in JavaScript. 1082 | - typeof null returns "object", which is a known quirk in JavaScript. null is considered an object type. 1083 | - typeof undefined returns "undefined" because it is a special value in JavaScript representing an uninitialized variable. 1084 | - typeof function() {} returns "function" because it is a function object. 1085 | 1086 |
1087 | 1088 |
1089 | 1090 |

36. Write a function in JavaScript to determine the type of a value.

Expert 🚀 1091 | 1092 | ```javascript 1093 | console.log(getType(42)); 1094 | console.log(getType("Hello")); 1095 | console.log(getType(true)); 1096 | console.log(getType([1, 2, 3])); 1097 | console.log(getType({ name: "John", age: 25 })); 1098 | console.log(getType(null)); 1099 | console.log(getType(undefined)); 1100 | console.log(getType(function () {})); 1101 | 1102 | //The function should print "array" for "[]" and "null" for "null" types. 1103 | ``` 1104 | 1105 |
1106 | Answer: 1107 | 1108 | ```js 1109 | const getType = (val) => (val === null ? null : val?.constructor.name); 1110 | ``` 1111 | 1112 | The output of the code will be: 1113 | 1114 | ```bash 1115 | number 1116 | string 1117 | boolean 1118 | Array 1119 | Object 1120 | null 1121 | undefined 1122 | Function 1123 | ``` 1124 | 1125 | The function getType takes a value as an argument and returns its type. If the value is null, it returns null. Otherwise, it uses the constructor.name property to determine the type of the value. 1126 | 1127 | - getType(42) returns "number" because 42 is a numeric value. 1128 | - getType("Hello") returns "string" because "Hello" is a string. 1129 | - getType(true) returns "boolean" because true is a boolean value. 1130 | - getType([1, 2, 3]) returns "Array" because arrays are considered objects in JavaScript, and the constructor name for an array is "Array". 1131 | - getType({ name: "John", age: 25 }) returns "Object" because objects are considered objects in JavaScript, and the constructor name for an object is "Object". 1132 | - getType(null) returns null because null is a special value in JavaScript. 1133 | - getType(undefined) returns "undefined" because it is a special value in JavaScript representing an uninitialized variable. 1134 | - getType(function() {}) returns "Function" because it is a function object, and the constructor name for a function is "Function". 1135 | - The getType function can be used to dynamically determine the type of values in JavaScript. 1136 | 1137 |
1138 | 1139 |
1140 | 1141 |

37. Which of the following options accurately describes the output or error thrown by the code above?

Beginner 🚂 1142 | 1143 | ```js 1144 | function calculateSum() { 1145 | console.log(result); 1146 | var num1 = 5; 1147 | let num2 = 10; 1148 | const num3 = 15; 1149 | var result = num1 + num2 + num3; 1150 | } 1151 | 1152 | calculateSum(); 1153 | ``` 1154 | 1155 | - A: 30 1156 | - B: undefined 1157 | - C: ReferenceError 1158 | - D: TypeError 1159 | 1160 |
1161 | 1162 | Answer - 1163 | B: undefined 1164 | 1165 | In the code, the variable result is declared using the var keyword, but it is assigned a value after the console.log statement. 1166 | 1167 | When JavaScript executes the function calculateSum(), it hoists the variable declaration of result to the top of the function scope. However, since the assignment of the value num1 + num2 + num3 comes after the console.log statement, the variable is undefined at the point of the console.log. 1168 | 1169 | So, the code is effectively interpreted like this: 1170 | 1171 | ```js 1172 | function calculateSum() { 1173 | var result; // Variable declaration is hoisted to the top 1174 | 1175 | console.log(result); // undefined 1176 | 1177 | var num1 = 5; 1178 | let num2 = 10; 1179 | const num3 = 15; 1180 | result = num1 + num2 + num3; // Assignment is performed here 1181 | } 1182 | 1183 | calculateSum(); 1184 | ``` 1185 | 1186 | Since the variable result is hoisted, it exists in the function scope but does not have any assigned value until after the console.log statement. Therefore, when console.log(result) is executed, the variable result exists but is undefined. 1187 | 1188 |
1189 | 1190 |
1191 | 1192 |

38. What will be the output of the following code snippet?

Beginner 🚂 1193 | 1194 | ```javascript 1195 | let x = 10; 1196 | 1197 | function updateX() { 1198 | if (true) { 1199 | let x = 20; 1200 | console.log(x); 1201 | } 1202 | console.log(x); 1203 | } 1204 | 1205 | updateX(); 1206 | ``` 1207 | 1208 | - A: 20, 10 1209 | - B: 20, 20 1210 | - C: 10, 10 1211 | - D: 10, 20 1212 | 1213 |
1214 | 1215 | Answer - 1216 | B: 20, 10 1217 | 1218 | In this code, the variable `x` is declared and assigned a value of `10` outside the `updateX` function. 1219 | 1220 | Inside the function, a new block is created using an `if` statement. Within that block, a new variable `x` is declared and assigned a value of `20` using `let`. This creates a separate scope for the inner `x`, which is only accessible within the `if` block. 1221 | 1222 | When the `console.log` statements are executed, the first one inside the `if` block will output `20`, as it refers to the inner `x` variable. The second `console.log` statement outside the `if` block will output `10`, as it refers to the outer `x` variable. 1223 | 1224 | Therefore, the output will be `20, 10`. 1225 | 1226 |
1227 | 1228 |
1229 | 1230 |

39. What will be the output of the following code snippet?

Intermediate 🚁 1231 | 1232 | ```javascript 1233 | const person = { 1234 | name: "John", 1235 | age: 30, 1236 | }; 1237 | 1238 | Object.freeze(person); 1239 | person.age = 40; 1240 | 1241 | console.log(person.age); 1242 | ``` 1243 | 1244 | - A: 30 1245 | - B: 40 1246 | - C: TypeError 1247 | - D: ReferenceError 1248 | 1249 |
1250 | 1251 | Answer - 1252 | A: 30 1253 | 1254 | In this code, the `Object.freeze()` method is used to make 1255 | 1256 | the `person` object immutable. This means that the properties of the object cannot be modified. 1257 | 1258 | When attempting to assign a new value to `person.age` after freezing the object, it does not throw an error or modify the object. Instead, it silently fails in non-strict mode and throws a TypeError in strict mode. 1259 | 1260 | Since the code is not running in strict mode, the assignment `person.age = 40` does not have any effect. Therefore, when `console.log(person.age)` is executed, it will output the original value of `30`. 1261 | 1262 | Hence, the output will be `30`. 1263 | 1264 |
1265 | 1266 |
1267 | 1268 |

40. What will be the output of the following code snippet?

Beginner 🚂 1269 | 1270 | ```javascript 1271 | function foo() { 1272 | let x = 1; 1273 | 1274 | function bar() { 1275 | let y = 2; 1276 | console.log(x + y); 1277 | } 1278 | 1279 | bar(); 1280 | } 1281 | 1282 | foo(); 1283 | ``` 1284 | 1285 | - A: 1 1286 | - B: 2 1287 | - C: 3 1288 | - D: ReferenceError 1289 | 1290 |
1291 | 1292 | Answer - 1293 | C: 3 1294 | 1295 | In this code, there are two nested functions: `foo` and `bar`. The variable `x` is declared and assigned a value of `1` within the `foo` function, while the variable `y` is declared and assigned a value of `2` within the `bar` function. 1296 | 1297 | When the `foo` function is called, it invokes the `bar` function. Inside the `bar` function, the values of `x` and `y` are accessed and summed together using `console.log(x + y)`. 1298 | 1299 | Since `x` is accessible within the `bar` function due to lexical scoping, the value of `x` is `1`. Similarly, the value of `y` is `2`. Therefore, the output of `console.log(x + y)` will be `3`. 1300 | 1301 | Hence, the correct answer is C: 3. 1302 | 1303 |
1304 | 1305 |
1306 | 1307 |

41. What will be the output of the following code snippet?

Beginner 🚂 1308 | 1309 | ```javascript 1310 | let x = 10; 1311 | 1312 | function outer() { 1313 | console.log(x); 1314 | 1315 | if (false) { 1316 | var x = 20; 1317 | } 1318 | } 1319 | 1320 | outer(); 1321 | ``` 1322 | 1323 | - A: 10 1324 | - B: 20 1325 | - C: undefined 1326 | - D: ReferenceError 1327 | 1328 |
1329 | 1330 | Answer: 1331 | C: undefined 1332 | 1333 | In this code snippet, there's a variable hoisting issue with the var declaration inside the outer function. The variable x is declared using var within the outer function scope. 1334 | 1335 | When the function outer() is called, the console.log(x) statement is executed. At this point, the variable x is hoisted to the top of the function scope and is initialized with undefined. This means that the local variable x inside the function is different from the global x. 1336 | 1337 | The if (false) block will not be executed, so the assignment var x = 20; will not take place. 1338 | 1339 | Thus, the console.log(x) statement inside the outer function will log the value of the locally hoisted variable x, which is undefined. 1340 | 1341 | Hence, the correct answer is C: undefined. 1342 | 1343 |
1344 | 1345 |
1346 | 1347 |

42. What will be the output of the following code snippet?

Intermediate 🚁 1348 | 1349 | ```javascript 1350 | const obj = { 1351 | a: 1, 1352 | b: 2, 1353 | c: { 1354 | a: 3, 1355 | b: 4, 1356 | }, 1357 | }; 1358 | 1359 | const { 1360 | a, 1361 | b, 1362 | c: { a: nestedA }, 1363 | } = obj; 1364 | 1365 | console.log(a, b, nestedA); 1366 | ``` 1367 | 1368 | - A: 1 2 3 1369 | - B: 1 2 4 1370 | - C: 3 2 1 1371 | - D: SyntaxError 1372 | 1373 |
1374 | 1375 | Answer: 1376 | A: 1 2 3 1377 | 1378 | This code snippet uses destructuring assignment to extract values from the `obj` object. It extracts the properties `a`, `b`, and the nested property `a` from the `c` object and assigns them to the corresponding variables `a`, `b`, and `nestedA`, respectively. 1379 | 1380 | After destructuring, the variables will hold the following values: 1381 | 1382 | - `a`: 1 (value of `obj.a`) 1383 | - `b`: 2 (value of `obj.b`) 1384 | - `nestedA`: 3 (value of `obj.c.a`) 1385 | 1386 | When `console.log(a, b, nestedA)` is executed, it will print `1 2 3`, as the values of the variables match the above assignments. 1387 | 1388 | Hence, the correct answer is A: 1 2 3. 1389 | 1390 |
1391 | 1392 |
1393 | 1394 |

43. What will be the output of the following code snippet?

Expert 🚀 1395 | 1396 | ```javascript 1397 | function* generatorFunction() { 1398 | yield 1; 1399 | yield 2; 1400 | return 3; 1401 | } 1402 | 1403 | const generator = generatorFunction(); 1404 | 1405 | console.log(generator.next()); 1406 | console.log(generator.next()); 1407 | console.log(generator.next()); 1408 | ``` 1409 | 1410 | - A: { value: 1, done: false }, { value: 2, done: false }, { value: 3, done: true } 1411 | - B: { value: 1, done: false }, { value: 2, done: false }, { value: undefined, done: true } 1412 | - C: { value: 1, done: true }, { value: 2, done: true }, { value: 3, done: true } 1413 | - D: SyntaxError 1414 | 1415 |
1416 | 1417 | Answer: 1418 | A: { value: 1, done: false }, { value: 2, done: false }, { value: 3, done: true } 1419 | 1420 | This code snippet demonstrates the use of a generator function. When a generator function is called, it returns an iterator object, which can be used to control the execution of the generator function. 1421 | 1422 | The `generatorFunction` is a generator function that yields three values: `1`, `2`, and `3`. The `yield` keyword pauses the execution and returns the yielded value. When the generator is finished, it returns the value using the `return` statement. 1423 | 1424 | When the generator is executed step by step using `generator.next()`, it proceeds through the generator function's code, stopping at each `yield` statement. 1425 | 1426 | - The first call to `generator.next()` will return `{ value: 1, done: false }`, indicating that the first value yielded is `1`, and the generator is not yet done. 1427 | - The second call to `generator.next()` will return `{ value: 2, done: false }`, indicating that the second value yielded is `2`, and the generator is not yet done. 1428 | - The third call to `generator.next()` will return `{ value: 3, done: true }`, indicating that the third value yielded is `3`, and the generator is done (`done` is `true`). 1429 | 1430 | After the generator is done, any further calls to `generator.next()` will keep returning `{ value: undefined, done: true }`. 1431 | 1432 | Hence, the correct answer is A: { value: 1, done: false }, { value: 2, done: false }, { value: 3, done: true }. 1433 | 1434 |
1435 | 1436 |
1437 | 1438 |

44. Write a function to make the following code snippet work?

Expert 🚀 1439 | 1440 | ```js 1441 | console.log(sum(4, 6, 8, 10).value); //output - 28 1442 | console.log(sum(4)(6)(8)(10).value); //output - 28 1443 | ``` 1444 | 1445 |
1446 | 1447 | Answer 1448 | 1449 | ```js 1450 | function sum(...args) { 1451 | const ans = args.reduce((a, b) => a + b, 0); //just to get sum of all the array elements 1452 | 1453 | const myFunc = (num) => { 1454 | return sum(num, ...args); 1455 | }; 1456 | 1457 | myFunc.value = ans; 1458 | 1459 | return myFunc; 1460 | } 1461 | 1462 | console.log(sum(4, 6, 8, 10).value); //output - 28 1463 | console.log(sum(4)(6)(8)(10).value); //output - 28 1464 | ``` 1465 | 1466 | The sum function takes any number of arguments using the rest parameter ...args and calculates the sum of those arguments. 1467 | 1468 | It defines a nested function called myFunc, which takes a new number num and returns a new instance of the sum function with the accumulated sum and the new number. 1469 | 1470 | The current sum value is assigned to a property named value on myFunc. 1471 | 1472 | The myFunc function is then returned, allowing you to chain multiple function calls together. 1473 | 1474 | As a result, you can use this sum function to either pass all numbers at once or chain multiple function calls to add numbers incrementally, and it will provide the correct sum when you access the value property. 1475 | 1476 |
1477 | 1478 |
1479 | 1480 |

45. Understanding the `.sort()` Method Variations

Beginner 🚂 1481 | 1482 | ```js 1483 | const fruits = ["banana", "apple", "orange", "grape", "kiwi"]; 1484 | 1485 | // Task 1: Sort the array of fruits in alphabetical order (default behavior) 1486 | // Task 2: Sort the array of fruits in descending alphabetical order 1487 | // Task 3: Sort the array of fruits based on the length of the fruit names in ascending order 1488 | // Task 4: Sort the array of fruits in ascending order by the second character of each fruit name 1489 | ``` 1490 | 1491 |
1492 | 1493 | Answer 1494 | 1495 | Task 1: Sort in alphabetical order (default behavior) 1496 | 1497 | ```js 1498 | const alphabeticalOrder = [...fruits].sort(); 1499 | console.log(alphabeticalOrder); // Output: ['apple', 'banana', 'grape', 'kiwi', 'orange'] 1500 | ``` 1501 | 1502 | Task 2: Sort in descending alphabetical order 1503 | 1504 | ```js 1505 | const descendingOrder = [...fruits].sort((a, b) => b.localeCompare(a)); 1506 | console.log(descendingOrder); // Output: ['orange', 'kiwi', 'grape', 'banana', 'apple'] 1507 | ``` 1508 | 1509 | Task 3: Sort based on the length of the fruit names in ascending order 1510 | 1511 | ```js 1512 | const sortByLength = [...fruits].sort((a, b) => a.length - b.length); 1513 | console.log(sortByLength); // Output: ['kiwi', 'apple', 'grape', 'banana', 'orange'] 1514 | ``` 1515 | 1516 | Task 4: Sort in ascending order by the second character of each fruit name 1517 | 1518 | ```js 1519 | const sortBySecondChar = [...fruits].sort((a, b) => a[1].localeCompare(b[1])); 1520 | console.log(sortBySecondChar); // Output: ['banana', 'kiwi', 'apple', 'orange', 'grape'] 1521 | ``` 1522 | 1523 | Explanation: 1524 | 1525 | - Task 1 utilizes the default behavior of `.sort()` to arrange elements alphabetically. 1526 | - Task 2 reverses the order by using `localeCompare()` with the reverse comparison. 1527 | - Task 3 sorts the array by the length of the elements, ensuring ascending order. 1528 | - Task 4 specifically compares the second character of each element for sorting. 1529 | 1530 | These variations demonstrate different uses of the `.sort()` method by customizing the sorting logic through comparator functions, enabling diverse sorting patterns for arrays. 1531 | 1532 |
1533 | 1534 |
1535 | 1536 |

46. Explain the output of the following code and correct any errors.

Beginner 🚂 1537 | 1538 | ```javascript 1539 | let numbers = [1, 2, 3, 4, 5]; 1540 | numbers = numbers.map((number) => number * 2); 1541 | console.log(numbers.reduce((total, num) => total + num)); 1542 | ``` 1543 | 1544 |
1545 | 1546 | **Answer:** 1547 | 1548 | ```javascript 1549 | // Output: 30 (No errors in the code) 1550 | ``` 1551 | 1552 | **Explanation:** 1553 | 1554 | 1. **Array Creation:** The code starts by creating an array named `numbers` containing the values `[1, 2, 3, 4, 5]`. 1555 | 1556 | 2. **Array Mapping:** The `map()` method is used to create a new array by applying a function to each element of the original array. In this case, the function `number => number * 2` doubles each number in the array. The new array becomes `[2, 4, 6, 8, 10]`. 1557 | 1558 | 3. **Array Reduction:** The `reduce()` method is used to reduce the array to a single value by applying a function against an accumulator and each element in the array (from left to right). The function `(total, num) => total + num` adds each number in the array to the `total`, starting with an initial `total` of 0. 1559 | 1560 | 4. **Output:** The final `console.log()` statement outputs the result of the `reduce()` operation, which is 30 (the sum of all the doubled numbers in the array). 1561 | 1562 |
1563 | 1564 |
1565 | 1566 |

47. Write a JavaScript function that takes an array of numbers as input and returns a new array containing only the even numbers.

Beginner 🚂 1567 | 1568 | _\*You can't use built-in methods like filter or forEach._ 1569 | 1570 |
1571 | 1572 | **Answer:** 1573 | 1574 | Approach 1: Using a loop and conditional statement 1575 | 1576 | ```js 1577 | function findEvenNumbers(numberArray) { 1578 | const evenNumbers = []; 1579 | for (let i = 0; i < numberArray.length; i++) { 1580 | if (numberArray[i] % 2 === 0) { 1581 | evenNumbers.push(numberArray[i]); 1582 | } 1583 | } 1584 | return evenNumbers; 1585 | } 1586 | ``` 1587 | 1588 | Approach 2: Using recursion and conditional statement 1589 | 1590 | ```js 1591 | function findEvenNumbersRecursive(numberArray) { 1592 | if (numberArray.length === 0) { 1593 | return []; 1594 | } 1595 | 1596 | const firstNumber = numberArray[0]; 1597 | const remainingNumbers = numberArray.slice(1); 1598 | 1599 | if (firstNumber % 2 === 0) { 1600 | return [firstNumber].concat(findEvenNumbersRecursive(remainingNumbers)); 1601 | } else { 1602 | return findEvenNumbersRecursive(remainingNumbers); 1603 | } 1604 | } 1605 | ``` 1606 | 1607 |
1608 | --------------------------------------------------------------------------------