├── README.md └── javascript.js /README.md: -------------------------------------------------------------------------------- 1 | In JS we trust - The best way to learn is by building/coding and teaching. I create the challenges to help my friends learn JavaScript and in return it helps me embrace the language in much deeper level. Feel free to clone, fork and pull. 2 | 3 | --- 4 | 5 | ###### 1. What's the output? 6 | 7 | ```javascript 8 | function a(x) { 9 | x++; 10 | return function () { 11 | console.log(++x); 12 | }; 13 | } 14 | 15 | a(1)(); 16 | a(1)(); 17 | a(1)(); 18 | 19 | let x = a(1); 20 | x(); 21 | x(); 22 | x(); 23 | ``` 24 | 25 | - A: `1, 2, 3` and `1, 2, 3` 26 | - B: `3, 3, 3` and `3, 4, 5` 27 | - C: `3, 3, 3` and `1, 2, 3` 28 | - D: `1, 2, 3` and `3, 3, 3` 29 | 30 |
Answer 31 |

32 | 33 | #### Answer: B 34 | 35 | This question revisits closure - one of the most confusing concepts in JavaScript. Closure allows us to create a `stateful function` and such a function can access to the variable outside of its scope. In a nutshell, a closure can have access to the `global` variable (scope), `father function` scope and `its` own scope. 36 | 37 | We have here, the only one correct answer, 3, 3, 3 and 3, 4, 5 because first we simply call the function `a()`. It works like a normal function and we have not seen anything so-called `stateful` yet. In the following code, we declare a variable `x` and it stores the value of function `a(1)`, that is why we get 3. 4. 5 rather than 3, 3, 3. 38 | 39 | This kind of gotcha gives me the feeling of `static` variable in PHP world. 40 | 41 |

42 |
43 | 44 | --- 45 | 46 | ###### 2. What's the output? 47 | 48 | ```javascript 49 | function Name(a, b) { 50 | this.a = a; 51 | this.b = b; 52 | } 53 | 54 | const me = Name("Vuong", "Nguyen"); 55 | 56 | console.log(!(a.length - window.a.length)); 57 | ``` 58 | 59 | - A: `undefined` 60 | - B: `NaN` 61 | - C: `true` 62 | - D: `false` 63 | 64 |
Answer 65 |

66 | 67 | #### Answer: C 68 | 69 | We get true in the console. The tricky part is when we create an object from the constructor function Name but we DO NOT USE `new` keywork. That makes the variable `a` global one and get the value "Vuong". Remember that it is actually a property of the global object `window` (in the browser) or `global` in the nodejs. 70 | 71 | We then get `a.length` ~ 5 and `window.a.length` ~ 5 which return 0. !0 returns true. 72 | 73 | Imagine what would happen when we create the instance `me` with the `new` keywork. That is an interesting inquire! 74 | 75 |

76 |
77 | 78 | --- 79 | 80 | ###### 3. What's the output? 81 | 82 | ```javascript 83 | const x = function (...x) { 84 | let k = (typeof x).length; 85 | let y = () => "freetut".length; 86 | let z = { y: y }; 87 | 88 | return k - z.y(); 89 | }; 90 | 91 | console.log(Boolean(x())); 92 | ``` 93 | 94 | - A: `true` 95 | - B: 1 96 | - C: -1 97 | - D: `false` 98 | 99 |
Answer 100 |

101 | 102 | #### Answer: A 103 | 104 | The spread operator `...x` might help us obtain the parameter in the function in the form of array. Yet, in Javascript the typeof array return "object" rather than "array". It is totally odd if you are coming from PHP. 105 | 106 | That is said, we now have the length of the string `object` which returns 6. z.y() simply returns the length of the string 'freetut' (7). 107 | 108 | Be aware that the function x() (in the form of `function express` or `anonymous function` (if you are coming from PHP) return -1 when being called and when converted to bool with `Boolean(-1)` return true instead of false. Noted that `Boolean(0)` return false. 109 | 110 |

111 |
112 | 113 | --- 114 | 115 | ###### 4. What's the output? 116 | 117 | ```javascript 118 | (function js(x) { 119 | const y = (j) => j * x; 120 | 121 | console.log(y(s())); 122 | 123 | function s() { 124 | return j(); 125 | } 126 | 127 | function j() { 128 | return x ** x; 129 | } 130 | })(3); 131 | ``` 132 | 133 | - A: `undefined` 134 | - B: 18 135 | - C: 81 136 | - D: 12 137 | 138 |
Answer 139 |

140 | 141 | #### Answer: C 142 | 143 | The function `js()` can be automatically executed without calling it and known as IIFE (Immediately Invoked Function Expression). Noted the parameter `x` of the function `js` is actuallly passed with the value 3. 144 | 145 | The value return of the function is y(s())), meaning calling three other functions `y()`, `s()` and `j()` because the function `s()` returns `j()`. 146 | 147 | j() returns 3^3 = 27 so that s() returns 27. 148 | 149 | y(s()) means y(27) which returns 27\*3 = 81. 150 | 151 | Note that we can call `declare function` BEFORE the function is actually declared but not with `expression function`. 152 | 153 |

154 |
155 | 156 | --- 157 | 158 | ###### 5. What's the output? 159 | 160 | ```javascript 161 | var tip = 100; 162 | 163 | (function () { 164 | console.log("I have $" + husband()); 165 | 166 | function wife() { 167 | return tip * 2; 168 | } 169 | 170 | function husband() { 171 | return wife() / 2; 172 | } 173 | 174 | var tip = 10; 175 | })(); 176 | ``` 177 | 178 | - A: "I have \$10"; 179 | - B: "I have \$100"; 180 | - C: "I have \$50"; 181 | - D: "I have \$NaN"; 182 | 183 |
Answer 184 |

185 | 186 | #### Answer: D 187 | 188 | We have here an IIFE (Immediately Invoked Function Expression). It means we do not have to call it but it will be excuted automatically when declared. The flow is as: husband() returns wife()/2 and wife() returns tip\*2. 189 | 190 | We might think that tip = 100 because it is a global variable when declaring with `var` keyword. However, it is actually `undefined` because we also have `var tip = 10` INSIDE the function. As the variable `tip` is hoisted with default value `undefined`, the final result would be D. We know that `undefined` returns NaN when we try to divide to 2 or multiple with 2. 191 | 192 | If we do not re-declare `var tip = 10;` at the end of the function, we will definately get B. 193 | 194 | JS is fun, right? 195 | 196 |

197 |
198 | 199 | --- 200 | 201 | ###### 6. What's the output? 202 | 203 | ```javascript 204 | const js = { language: "loosely type", label: "difficult" }; 205 | 206 | const edu = { ...js, level: "PhD" }; 207 | 208 | const newbie = edu; 209 | 210 | delete edu.language; 211 | 212 | console.log(Object.keys(newbie).length); 213 | ``` 214 | 215 | - A: 2; 216 | - B: 3; 217 | - C: 4; 218 | - D: 5; 219 | 220 |
Answer 221 |

222 | 223 | #### Answer: A 224 | 225 | This challenge revises the ES6's feature regarding `spread operator ...` Spread operator is quite useful for retrieving parameter in function, to `unite` or `combine` object and array in JavaScript. PHP also has this feature. 226 | 227 | In the variable `edu`, we use `...js` (spread operator here) to combine both objects into one. It works in the same way with array. 228 | 229 | Then we declare another variable named `newbie`. IMPORTANT note: By declaring the variable like that, both variables point to the SAME POSITION in the memory. We may have known something like `$a = &$b` in PHP, which let both varibles work in the same way. We might have known about `pass by reference` in the case. 230 | 231 | Then we have 2 as `edu.language` is deleted. Both objects now have only two elements. 232 | 233 | Now is time to think about coping an object in JS either shallow or deep one. 234 | 235 |

236 |
237 | 238 | --- 239 | 240 | ###### 7. What's the output? 241 | 242 | ```javascript 243 | var candidate = { 244 | name: "Vuong", 245 | age: 30, 246 | }; 247 | 248 | var job = { 249 | frontend: "Vuejs or Reactjs", 250 | backend: "PHP and Laravel", 251 | city: "Auckland", 252 | }; 253 | 254 | class Combine { 255 | static get() { 256 | return Object.assign(candidate, job); 257 | } 258 | 259 | static count() { 260 | return Object.keys(this.get()).length; 261 | } 262 | } 263 | 264 | console.log(Combine.count()); 265 | ``` 266 | 267 | - A: 5; 268 | - B: 6; 269 | - C: 7; 270 | - D: 8; 271 | 272 |
Answer 273 |

274 | 275 | #### Answer: A 276 | 277 | The buit-in method `Object.assign(candidate, job)` merges the two objects `candidate` and `job` into one object. Then the method `Object.keys` counts the number of `key` in the object. 278 | 279 | Note that two methods `get()` and `count()` are defined as `static`, so they need to be called statically using `Class.staticmethod()` syntax. Then the final object get 5 elements. 280 | 281 |

282 |
283 | 284 | --- 285 | 286 | ###### 8. What's the output? 287 | 288 | ```javascript 289 | var x = 1; 290 | 291 | (() => { 292 | x += 1; 293 | ++x; 294 | })(); 295 | ((y) => { 296 | x += y; 297 | x = x % y; 298 | })(2); 299 | (() => (x += x))(); 300 | (() => (x *= x))(); 301 | 302 | console.log(x); 303 | ``` 304 | 305 | - A: 4; 306 | - B: 50; 307 | - C: 2; 308 | - D: 10; 309 | 310 |
Answer 311 |

312 | 313 | #### Answer: A 314 | 315 | Initially `x` is declared with the value 1. In the first IIFE function, there are two operations. First `x` becomes 2 and then 3. 316 | 317 | In the second IIFE function, `x = x + y` then the current value is 5. In the second operation, it returns only 1 as it undergoes `5%2`. 318 | 319 | In the third and fouth IIFE functions, we get 2 `x = x + x` and then 4 `x = x * x`. It is more than simple. 320 | 321 |

322 |
323 | 324 | --- 325 | 326 | ###### 9. What's the output? 327 | 328 | ```php 329 | $var = 10; 330 | 331 | $f = function($let) use ($var) { 332 | return ++$let + $var; 333 | }; 334 | 335 | $var = 15; 336 | echo $f(10); 337 | ``` 338 | 339 | ```javascript 340 | var x = 10; 341 | 342 | const f = (l) => ++l + x; 343 | 344 | x = 15; 345 | console.log(f(10)); 346 | ``` 347 | 348 | - A: 26 and 26; 349 | - B: 21 and 21; 350 | - C: 21 and 26; 351 | - D: 26 and 21; 352 | 353 |
Answer 354 |

355 | 356 | #### Answer: C 357 | 358 | This question illustrates the diffences between PHP and JavaScript when handling closure. In the first snippet, we declare a closure with the keyword `use`. Closure in PHP is simply an anonymous function and the data is passed to the function using the keyword `use`. Otherwise, it is called as `lambda` when we do not use the keyword `use`. You can check the result of the snippet here https://3v4l.org/PSeMY. PHP `closure` only accepts the value of the variable BEFORE the closure is defined, no matter where it is called. As such, `$var` is 10 rather than 15. 359 | 360 | On the contrary, JavaScript treats the variable a bit different when it is passed to anonymous function. We do not have to use the keyword `use` here to pass variable to the closure. The variable `x` in the second snippet is updated before the closure is called, then we get 26. 361 | 362 | Note that in PHP 7.4, we have arrow function and we then do not have to use the keyword `use` to pass the variable to function. Another way to call a `global` ariable inside a function in PHP is to use the keyword `global` or employ the built-in GLOBAL variable \$GLOBALS. 363 | 364 |

365 |
366 | 367 | --- 368 | 369 | ###### 10. What's the output? 370 | 371 | ```javascript 372 | let x = {}; 373 | let y = {}; 374 | let z = x; 375 | 376 | console.log(x == y); 377 | console.log(x === y); 378 | console.log(x == z); 379 | console.log(x === z); 380 | ``` 381 | 382 | - A: true true true true; 383 | - B: false false false false; 384 | - C: true true false false; 385 | - D: false false true true; 386 | 387 |
Answer 388 |

389 | 390 | #### Answer: D 391 | 392 | Technically, `x` and `y` have the same value. Both are empty objects. However, we do not use the value to compare objects. 393 | 394 | `z` is `x` are two objects referring to the same memory position. In JavaScript, array and object are passed by `reference`. `x` and `z` therefore return true when being compared. 395 | 396 |

397 |
398 | 399 | --- 400 | 401 | ###### 11. What's the output? 402 | 403 | ```javascript 404 | console.log("hello"); 405 | 406 | setTimeout(() => console.log("world"), 0); 407 | 408 | console.log("hi"); 409 | ``` 410 | 411 | - A: "hello" -> "world" -> "hi" 412 | - B: "hello" -> "hi" -> "world" 413 | - C: "hi" -> "world" -> "hello" 414 | - D: "hi" -> "hello" -> "world" 415 | 416 |
Answer 417 |

418 | 419 | #### Answer: B 420 | 421 | Given that the function setTimeout() will be kept in the `task queue` before jumping back to `stack,` "hello" and "hi" will be printed first, then A is incorrect. That is also the case of the answers C and D. 422 | 423 | No matter how many seconds you set to the `setTimeout()` function, it will run after synchronous code. So we will get "hello" first as it is put into the call stack first. Though the `setTimeout()` is then being put into the call stack, it will subsequently offload to web API (or Node API) and then being called when other synchronous codes are cleared. It means we then get "hi" and finally "world". 424 | 425 | So B is the correct answer. 426 | 427 | Credit: @kaitoubg (voz) for your suggestion regarding the ` timeout throttled` by which I have decided to alter the question slightly. It will ensure that readers will not get confused as the previous code might bring out different results when tested on other browsers or environments. The main point of the question is about the discrepancy between the synchronous code and asynchronous code when using `setTimeout.`. 428 | 429 |

430 |
431 | 432 | --- 433 | 434 | ###### 12. What's the output? 435 | 436 | ```javascript 437 | String.prototype.lengthy = () => { 438 | console.log("hello"); 439 | }; 440 | 441 | let x = { name: "Vuong" }; 442 | 443 | delete x; 444 | 445 | x.name.lengthy(); 446 | ``` 447 | 448 | - A: "Vuong"; 449 | - B: "hello"; 450 | - C: "undefined" 451 | - D: "ReferenceError" 452 | 453 |
Answer 454 |

455 | 456 | #### Answer: B 457 | 458 | `String.prototype.someThing = function () {}` is the common way to define a new built-in method for `String`. We can do the same thing with `Array`, `Object` or `FunctionName` where FunctionName is the function designed by ourself. 459 | 460 | That is not challenging to realise that `"string".lengthy()` always returns `hello`. Yet, the tricky part lies in the `delete object` where we might think that this expression will entirely delete the object. That is not the case as `delete` is used to delete the property of the object only. It does not delete the object. Then we get `hello` rather than `ReferenceError`. 461 | 462 | Note that if we declare object without `let, const` or `var`, we then have a global object. `delete objectName` then return `true`. Otherwise, it always returns `false`. 463 | 464 |

465 |
466 | 467 | --- 468 | 469 | ###### 13. What's the output? 470 | 471 | ```javascript 472 | let x = {}; 473 | 474 | x.__proto__.hi = 10; 475 | 476 | Object.prototype.hi = ++x.hi; 477 | 478 | console.log(x.hi + Object.keys(x).length); 479 | ``` 480 | 481 | - A: 10 482 | - B: 11 483 | - C: 12 484 | - D: NaN 485 | 486 |
Answer 487 |

488 | 489 | #### Answer: C 490 | 491 | First we have an empty object `x`, then we add another property `hi` for x with `x.__proto__.hi`. Note this is equivalent to `Object.prototype.hi = 10` and we are adding to the `father` object `Object` the property `hi`. It means every single object will inherit this propety. The property `hi` becomes a shared one. Say now we declare a new object such as `let y = {}`, `y` now has a propery `hi` inherited from the `father` `Object`. Put it simply `x.__proto__ === Object.prototype` returns `true`. 492 | 493 | Then we overwrite the property `hi` with a new value 11. Last we have 11 + 1 = 12. `x` has one property and `x.hi` returns 11. 494 | 495 | Updated (July 27th 2021). If you write `Object.prototype.hi = 11;` instead of `Object.prototype.hi = ++x.hi;` as written in the code above, then `Object.keys(x)` will return an empty array as `Object.keys(object)` only returns the property of the object itself, not the inherited ones. It means the final result will be 11 rather than 12. For some reason, the code ``Object.prototype.hi = ++x.hi;` will create a property for the object `x` itself and then `Object.keys(x)` gives us the array `["hi"]`. 496 | 497 | Yet, if you run `console.log(x.hasOwnProperty("hi"))` it still returns `false`. By the way, when you deliberately add a property for x such as `x.test = "testing"`, then `console.log(x.hasOwnProperty("test"))` returns `true`. 498 | 499 |

500 |
501 | 502 | --- 503 | 504 | ###### 14. What's the output? 505 | 506 | ```javascript 507 | const array = (a) => { 508 | let length = a.length; 509 | delete a[length - 1]; 510 | return a.length; 511 | }; 512 | 513 | console.log(array([1, 2, 3, 4])); 514 | 515 | const object = (obj) => { 516 | let key = Object.keys(obj); 517 | let length = key.length; 518 | delete obj[key[length - 1]]; 519 | 520 | return Object.keys(obj).length; 521 | }; 522 | 523 | console.log(object({ 1: 2, 2: 3, 3: 4, 4: 5 })); 524 | 525 | const setPropNull = (obj) => { 526 | let key = Object.keys(obj); 527 | let length = key.length; 528 | obj[key[length - 1]] = null; 529 | 530 | return Object.keys(obj).length; 531 | }; 532 | 533 | console.log(setPropNull({ 1: 2, 2: 3, 3: 4, 4: 5 })); 534 | ``` 535 | 536 | - A: 333 537 | - B: 444 538 | - C: 434 539 | - D: 343 540 | 541 |
Answer 542 |

543 | 544 | #### Answer: C 545 | 546 | This question examines how the `delete` operator works in JavaScript. In short, it does nothing when we write `delete someObject` or `delete someArray`. It nonetheless completely deletes and removes a property of an object when writing something like `delete someObject.someProperty`. In the case of array, when we write `delete someArray[keyNumber]`, it only removes the `value` of the `index`, keep the `index` intact and the new `value` is now set to `undefined`. For that reason, in the code first snippet, we get (the length) 4 elements as in the original array but only 3 properties left in the object passed when the function object() is called, as in the second snippet. 547 | 548 | The third snippet gives us 4 as declaring an object's propery to either `null` or `undefined` does not completely remove the property. The key is intact. So the length of the object is immutable. 549 | 550 | For those who are familiar with PHP, we have `unset($someArray[index])` that remove the array element, both key and value. When `print_r` the array, we might not see the key and value that have been unset. However, when we push (using `array_push($someArray, $someValue)`) a new element in that array, we might see that the previous key is still kept, but no value and not being displayed. That is something you should be aware of. Have a look at https://3v4l.org/7C3Nf 551 | 552 |

553 |
554 | 555 | --- 556 | 557 | ###### 15. What's the output? 558 | 559 | ```javascript 560 | var a = [1, 2, 3]; 561 | var b = [1, 2, 3]; 562 | 563 | var c = [1, 2, 3]; 564 | var d = c; 565 | 566 | var e = [1, 2, 3]; 567 | var f = e.slice(); 568 | 569 | console.log(a === b); 570 | console.log(c === d); 571 | console.log(e === f); 572 | ``` 573 | 574 | - A: true true true 575 | - B: false false true 576 | - C: true true false 577 | - D: false true false 578 | 579 |
Answer 580 |

581 | 582 | #### Answer: D 583 | 584 | `a` and `b` returns false because they point to different memory location even though the values are the same. If you are coming from PHP world, then it will return true obviously when we compare either value or value + type. Check it out: https://3v4l.org/IjaOs. 585 | 586 | In JavaScript, value is passed by reference in case of `array` and `object`. Hence in the second case, `d` is the copy of `c` but they both point to the same memory position. Everything changes in `c` will result in the change in `d`. In PHP, we might have `$a = &$b;`, working in the similar way. 587 | 588 | The third one gives us a hint to copy an array in JavaScript using `slice()` method. Now we have `f`, which is the copy of `e` but they point to different memory locations, thus they have different "life". We get `false` accordingly when they are being compared. 589 | 590 |

591 |
592 | 593 | --- 594 | 595 | ###### 16. What's the output? 596 | 597 | ```javascript 598 | var languages = { 599 | name: ["elixir", "golang", "js", "php", { name: "feature" }], 600 | feature: "awesome", 601 | }; 602 | 603 | let flag = languages.hasOwnProperty(Object.values(languages)[0][4].name); 604 | 605 | (() => { 606 | if (flag !== false) { 607 | console.log( 608 | Object.getOwnPropertyNames(languages)[0].length << 609 | Object.keys(languages)[0].length 610 | ); 611 | } else { 612 | console.log( 613 | Object.getOwnPropertyNames(languages)[1].length << 614 | Object.keys(languages)[1].length 615 | ); 616 | } 617 | })(); 618 | ``` 619 | 620 | - A: 8 621 | - B: NaN 622 | - C: 64 623 | - D: 12 624 | 625 |
Answer 626 |

627 | 628 | #### Answer: 64 629 | 630 | The code snippet is quite tricky as it has a couple of different built-in methods handling object in `JavaScript`. For example, both `Object.keys` and `Object.getOwnPropertyNames` are used even thought they are quite similar except that the latter can return non-enumerable properties. You might want to have a look at this thoroughly written reference https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/getOwnPropertyNames 631 | 632 | `Object.values` and `Object.keys` return the property value and property name of the object, respectively. That is nothing new. `object.hasOwnProperty('propertyName')` returns a `boolean` confirming whether a property exists or not. 633 | 634 | We have `flag` true because `Object.values(languages)[0][4].name` returns `feature`, which is also the name of the property. 635 | 636 | Then we have 4 << 4 in the `if-else` flow that returns the bitwise value, equivalent to `4*2^4` ~ `4*16` ~ 64. 637 | 638 |

639 |
640 | 641 | --- 642 | 643 | ###### 17. What's the output? 644 | 645 | ```javascript 646 | var player = { 647 | name: "Ronaldo", 648 | age: 34, 649 | getAge: function () { 650 | return ++this.age - this.name.length; 651 | }, 652 | }; 653 | 654 | function score(greeting, year) { 655 | console.log( 656 | greeting + " " + this.name + `! You were born in ${year - this.getAge()}` 657 | ); 658 | } 659 | 660 | window.window.window.score.call(window.window.window.player, "Kiora", 2019); 661 | 662 | score.apply(player, ["Kiora", 2009]); 663 | 664 | const helloRonaldo = window.score.bind(window.player, "Kiora", 2029); 665 | 666 | helloRonaldo(); 667 | ``` 668 | 669 | - A: "Kiora Ronaldo! You were born in 1985", "Kiora Ronaldo! You were born in 1985", "Kiora Ronaldo! You were born in 1985" 670 | - B: "Kiora Ronaldo! You were born in 1991", "Kiora Ronaldo! You were born in 1991", "Kiora Ronaldo! You were born in 1999" 671 | - C: "Kiora Ronaldo! You were born in 1991", NaN, "Kiora Ronaldo! You were born in 1980" 672 | - D: "Kiora Ronaldo! You were born in 1991", "Kiora Ronaldo! You were born in 1980", "Kiora Ronaldo! You were born in 1999" 673 | 674 |
Answer 675 |

676 | 677 | #### Answer: D 678 | 679 | We can use `call()`, `apply()` and `bind()` to apply a function to any object. At first sight, it seems that three functions do the same thing. Yet there are some situations where they are differently employed to handle respective contexts or solve particular problems. 680 | 681 | Of the three, only `bind()` can be executed after binding. We can create a variable to store the result as `helloRonaldo()` in the code snippet above. `apply()` and `call()` will bind and execute the function at the same time. `apply()` hints us `a` ~ array where we need to pass an array as parameter. `call()` hints us `c` or comma where we pass parameters with a comma. You might want to have a look at this post https://stackoverflow.com/questions/15455009/javascript-call-apply-vs-bind 682 | 683 | Note that `window.window.window.score` or `window.score` or simply `score` do the same thing. It points to the `score()` function in the global scope. 684 | 685 | The correct anwser is D. The `score()` and `getAge()` functions are nothing special. The only tricky part is that `this.age` is incremented each time you call the funtion `getAge()`; 686 | 687 |

688 |
689 | 690 | --- 691 | 692 | ###### 18. What's the output? 693 | 694 | ```javascript 695 | var ronaldo = { age: 34 }; 696 | 697 | var messi = { age: 32 }; 698 | 699 | function score(year, tr, t) { 700 | if (typeof tr === "function" && typeof t === "function") { 701 | console.log(`You score ${tr(year, t(this.age))} times`); 702 | } 703 | } 704 | 705 | const transform = (x, y) => x - y; 706 | 707 | const title = (x) => ++x + x++; 708 | 709 | const helloRonaldo = score.bind(ronaldo, 2029, transform, title); 710 | 711 | helloRonaldo(); 712 | 713 | const helloMessi = score.bind(messi, 2029, transform, title); 714 | 715 | helloMessi(); 716 | ``` 717 | 718 | - A: "You score 1989 times" and "You score 1963 times" 719 | - B: "You score 1959 times" and "You score 1989 times" 720 | - C: "You score 1989 times" and "You score 1953 times" 721 | - D: "You score 1959 times" and "You score 1963 times" 722 | 723 |
Answer 724 |

725 | 726 | #### Answer: D 727 | 728 | `bind()` allows us to bind a function declared with any object. Here we bind `score()` and both `ronaldo` and `messi`. 729 | 730 | In `score()` we pass three parameters `year`, `tr` and `t` in which both `tr` and `t` are function. They handle simple things as defined afterwards. 731 | 732 | When we bind `score()` with `ronaldo` and `messi`, we pass three parameters as declared in the `score()` function wherein `transform` and `title` are functions. 733 | 734 |

735 |
736 | 737 | --- 738 | 739 | ###### 19. What's the output? 740 | 741 | ```javascript 742 | var person = {}; 743 | 744 | Object.defineProperties(person, { 745 | name: { 746 | value: "Vuong", 747 | enumerable: true, 748 | }, 749 | job: { 750 | value: "developer", 751 | enumerable: true, 752 | }, 753 | studying: { 754 | value: "PhD", 755 | enumerable: true, 756 | }, 757 | money: { 758 | value: "NZD", 759 | enumerable: false, 760 | }, 761 | }); 762 | 763 | class Evaluate { 764 | static checkFlag(obj) { 765 | return Object.getOwnPropertyNames(obj) > Object.keys(obj) 766 | ? Object.getOwnPropertyNames(obj) 767 | : Object.keys(obj); 768 | } 769 | } 770 | 771 | const flag = Evaluate.checkFlag(person); 772 | 773 | console.log(flag.length); 774 | ``` 775 | 776 | - A: 1 777 | - B: 2 778 | - C: 3 779 | - D: 4 780 | 781 |
Answer 782 |

783 | 784 | #### Answer: D 785 | 786 | `Object.keys(obj)` is almost identical to `Object.getOwnPropertyNames(obj)` except the fact that the latter returns any type of object's property regardless of `enumerable`. By default `enumerable` is true when creating object. Using `Object.defineProperties` or `Object.defineProperty` we can manually set this option to `false`. 787 | 788 | As such the object `person` will get 3 using`Object.keys(obj)`but 4 with `Object.getOwnPropertyNames(obj)`. `In short Object.keys(obj)` only returns the property setting the enumerable as `true`. 789 | 790 |

791 |
792 | 793 | --- 794 | 795 | ###### 20. What's the output? 796 | 797 | ```javascript 798 | const id = 10; 799 | 800 | const getID = (...id) => { 801 | id(id); 802 | 803 | function id(id) { 804 | console.log(typeof id); 805 | } 806 | }; 807 | 808 | getID(id); 809 | ``` 810 | 811 | - A: ReferenceError 812 | - B: 10 813 | - C: undefined 814 | - D: 'function' 815 | 816 |
Answer 817 |

818 | 819 | #### Answer: D 820 | 821 | When declaring a function inside another function, we are working with Closure in JavaScript. Note that if a function is declared as normal (rather than function expression), it is hoisted. We might see several `id` in the code snippet above but in fact, some of them does nothing. 822 | 823 | The result of the code depending on the operator `typeof id`, which is `function`. So `id` in this operation is the `id()` function. 824 | 825 |

826 |
827 | 828 | --- 829 | 830 | ###### 21. What's the output? 831 | 832 | ```javascript 833 | var book1 = { 834 | name: "Name of the rose", 835 | getName: function () { 836 | console.log(this.name); 837 | }, 838 | }; 839 | 840 | var book2 = { 841 | name: { value: "Harry Potter" }, 842 | }; 843 | 844 | var bookCollection = Object.create(book1, book2); 845 | 846 | bookCollection.getName(); 847 | ``` 848 | 849 | - A: 'Harry Potter' 850 | - B: 'Name of the rose' 851 | - C: ReferenceError 852 | - D: Object object 853 | 854 |
Answer 855 |

856 | 857 | #### Answer: A 858 | 859 | `Object.create` allows us to create an object which is based on another object. If we do not pass the second parameter - `book2` in this case - the `name` property of the object `bookCollection` will be `Name of the rose` inherited from the `book1`. It means we can provide additional properties when declaring object with `Object.create`. 860 | 861 | `bookCollection` has its own property `name` and another one inherited from `book1`. In this case its own property `name` will show up as it has higher priority. That is why we get 'Harry Potter'. 862 | 863 |

864 |
865 | 866 | --- 867 | 868 | ###### 22. What's the output? 869 | 870 | ```javascript 871 | (() => { 872 | const a = Object.create({}); 873 | 874 | const b = Object.create(null); 875 | 876 | let f1 = a.hasOwnProperty("toString"); 877 | 878 | let f2 = "toString" in b; 879 | 880 | let result = 881 | f1 === false && f2 === false 882 | ? console.log((typeof a.toString()).length) 883 | : console.log(b.toString()); 884 | })(); 885 | ``` 886 | 887 | - A: ReferenceError 888 | - B: undefined 889 | - C: 0 890 | - D: 6 891 | 892 |
Answer 893 |

894 | 895 | #### Answer: D 896 | 897 | The two objects `a` and `b` are created using `Object.create()` operator. There is a bit of difference between them as `a` inherits from Object prototype but `b` is totally empty when we pass the `null` paramater. Yet `hasOwnProperty('toString')` always returns `false` neither `a` nor `b` given that `toString()` is not defined inside these objects. The method however is still available as it is inherited from Object prototype. 898 | 899 | Both `f1` and `f2` return `false`. Note that we use `object.hasOwnProperty('key')` and `('key' in object)` to check the availability of a key in an object. There is a bit difference between the two as the latter also returns the key inherited. You might want to have a look here: https://stackoverflow.com/questions/455338/how-do-i-check-if-an-object-has-a-key-in-javascript 900 | 901 | Then `typeof a.toString()` returns `string`, which gives us 6 with the `.length` property. 902 | 903 | If the syntax is odd to you, you might look for 'self-invoking function' and 'arrow function' in JavaScript. 904 | 905 |

906 |
907 | 908 | --- 909 | 910 | ###### 23. What's the output? 911 | 912 | ```javascript 913 | let promise = new Promise((rs, rj) => { 914 | setTimeout(() => rs(4), 0); 915 | 916 | Promise.resolve(console.log(3)); 917 | 918 | console.log(2); 919 | }); 920 | 921 | promise 922 | .then((rs) => { 923 | console.log(rs ? rs ** rs : rs); 924 | return rs; 925 | }) 926 | .then((rs) => console.log(rs == 256 ? rs : rs * rs)); 927 | ``` 928 | 929 | - A: 3, 2, 256, 256 930 | - B: 3, 2, 256, 16 931 | - C: 256, 16, 3, 2 932 | - D: 16, 256, 3, 2 933 | 934 |
Answer 935 |

936 | 937 | #### Answer: B 938 | 939 | We first declare a promise-based code with `let` and then call it. Given that `setTimeout()` is an asynchronous action, it will run last even the time is set to 0 in `setTimeout(() => rs(4), 0);`. Although `Promise.resolve(console.log(3))` also returns a promise but it is a Microtasks, then it has a higher priority than Tasks as set by `setTimeout()`. You might want to have a look at this post https://jakearchibald.com/2015/tasks-microtasks-queues-and-schedules/. 940 | 941 | In `.then()` we chain the result so that we have `4^4` in the first then() and `4*4` in the second `then()`. Note that `return rs` returns the original value. 942 | 943 |

944 |
945 | 946 | --- 947 | 948 | ###### 24. What's the output? 949 | 950 | ```javascript 951 | async function f() { 952 | let promise = new Promise((resolve, reject) => { 953 | setTimeout(() => resolve("done!"), 0); 954 | }); 955 | 956 | setTimeout(() => console.log("world"), 0); 957 | 958 | console.log(await promise); 959 | 960 | console.log("hello"); 961 | } 962 | 963 | f(setTimeout(() => console.log("kiora"), 0)); 964 | ``` 965 | 966 | - A: ReferenceError 967 | - B: done, hello, world 968 | - C: hello, done, world 969 | - D: kiora, done, hello, world 970 | 971 |
Answer 972 |

973 | 974 | #### Answer: D 975 | 976 | Though we do not declare any paramater for the function `f()`, we pass `setTimeout(()=>console.log("kiora"),0)` when call it. We therefore get 'kiora' first. 977 | 978 | Given that the variable `promise` returns a solved promise and it is called with the keyword `await`, JavaScript will 'pause' at this line `console.log(await promise);` till the result is resolved. That is why we get "done" at the next result. 979 | 980 | Why we do not get "world" or "hello" at the second ? As JavaScript "pauses" at the line with `await` keyword, we cannot get "hello" as usual (note that whenever we call setTimeout(), this function will run last because it is an asynchronous task operator), whereas `setTimeout(()=> console.log("world"), 0);` should always run last. 981 | 982 | Here we might see a bit of difference when employing `await` keyword before asynchronous operator (in this case, we use `setTimeout()` as an example) or when call the function/operator without it. 983 | 984 |

985 |
986 | 987 | --- 988 | 989 | ###### 25. What's the output? 990 | 991 | ```javascript 992 | function name() { 993 | return new Promise((resolve) => { 994 | setTimeout(() => { 995 | resolve("New Zealand"); 996 | }, 10); 997 | }); 998 | } 999 | 1000 | function fruit() { 1001 | return new Promise((resolve) => { 1002 | setTimeout(() => { 1003 | resolve("Kiwi"); 1004 | }, 20); 1005 | }); 1006 | } 1007 | 1008 | (async function countryandfruit() { 1009 | const getName = await name(); 1010 | const getFruit = await fruit(); 1011 | 1012 | console.log(`Kiora: ${getName} ${getFruit}`); 1013 | })(); 1014 | 1015 | (async function fruitandcountry() { 1016 | const [getName, getFruit] = await Promise.all([name(), fruit()]); 1017 | 1018 | console.log(`Hello: ${getName} ${getFruit}`); 1019 | })(); 1020 | ``` 1021 | 1022 | - A: Null 1023 | - B: Kiora 1024 | - C: "Hello: New Zealand Kiwi" -> "Kiora: New Zealand Kiwi" 1025 | - D: "Kiora: New Zealand Kiwi" -> "Hello: New Zealand Kiwi" 1026 | 1027 |
Answer 1028 |

1029 | 1030 | #### Answer: C 1031 | 1032 | Both `countryandfruit` and `fruitandcountry` are self invoking functions. Both are declared with the keyword `async`, it means the code inside will run step by step. It helps us control the flow of data much more concise as compared to Promise-based operator or callback way. 1033 | 1034 | The first function returns `"Kiora: New Zealand Kiwi"` and the second one ouputs `"Hello: New Zealand Kiwi"`. We might think that the order will be the same but actually the order of the result is reversed because the function with `await` keyword will run step by step rather than in in parallel as Promise.all. It means `fruitandcountry` will run faster than `countryandfruit`. 1035 | 1036 | You might want to have a look at the difference between the two at https://alligator.io/js/async-functions/ 1037 | 1038 |

1039 |
1040 | 1041 | --- 1042 | 1043 | ###### 26. What's the output? 1044 | 1045 | ```javascript 1046 | class MySort { 1047 | constructor(object) { 1048 | this.object = object; 1049 | } 1050 | 1051 | getSort() { 1052 | return Object.entries(this.object)[0][1].sort()[ 1053 | Object.values(this.object).length 1054 | ]; 1055 | } 1056 | } 1057 | 1058 | const object = { 1059 | month: ["July", "September", "January", "December"], 1060 | }; 1061 | 1062 | const sortMe = new MySort(object); 1063 | 1064 | console.log(sortMe.getSort()); 1065 | ``` 1066 | 1067 | - A: July 1068 | - B: September 1069 | - C: January 1070 | - D: December 1071 | 1072 |
Answer 1073 |

1074 | 1075 | #### Answer: C 1076 | 1077 | `Object.entries` returns an array consisting of both key and value from an object while `Object.values` retuns an array of the values of object and `Object.keys` gives us an array of keys of the object. As such, `Object.entries(object)` in the code snippet above gives us a nested array with just one element in which the values are put in another nested array like that `[["month", ["July", "September", "January", "December"]]]`. 1078 | 1079 | For that reason, `Object.entries(this.object)[0][1].sort()` will actually sort the value array and return a new order as "December" -> "January" -> "July" -> "September". Hence, when we get the element with the index given by `[Object.values(this.object).length]` we get `January` because `[Object.values(this.object).length]` give us 1 (the length of the array given by Object.values); 1080 | 1081 |

1082 |
1083 | 1084 | --- 1085 | 1086 | ###### 27. What's the output? 1087 | 1088 | ```javascript 1089 | const flag = [] !== !!!!![]; 1090 | 1091 | let f = () => {}; 1092 | 1093 | console.log((typeof f()).length + flag.toString().length); 1094 | ``` 1095 | 1096 | - A: NaN 1097 | - B: 12 1098 | - C: 13 1099 | - D: 14 1100 | 1101 |
Answer 1102 |

1103 | 1104 | #### Answer: C 1105 | 1106 | Comparing two arrays or two objects in JavaScript always return `false` because both are passed by reference, unlike primitive types such as string, number or boolean. That is why comparing [] and [] using either == or === returns `false`. The weird part is the `!==!!!!!` which is equivalent to `!==`, nothing special. So the `flag` is `true`. 1107 | 1108 | In the expression function `f()`, we use arrow function here but and `{}` is a part of the function rather than an object. In case you want to return an object, you have to write as `let f = () => ({})` or simply using normal way to define function. With the keyword `return`, we can easily catch the content of the function when using normal way to define function. 1109 | 1110 | Thus, the `typeof f()` returns `undefined` rathern `object`. We then get the length 9 and the flag (true) becomes 'true' (a string, by using toString() function), which returns 3 with the property `length`. We finally get 13. 1111 | 1112 |

1113 |
1114 | 1115 | --- 1116 | 1117 | ###### 28. What's the output? 1118 | 1119 | ```javascript 1120 | (function (a, b, c) { 1121 | arguments[2] = (typeof arguments).length; 1122 | c > 10 ? console.log(c) : console.log(++c); 1123 | })(1, 2, 3); 1124 | ``` 1125 | 1126 | - A: 4 1127 | - B: 5 1128 | - C: 6 1129 | - D: 7 1130 | 1131 |
Answer 1132 |

1133 | 1134 | #### Answer: D 1135 | 1136 | We have a self-invoking function with three parameters declared. Note that `arguments` inside a function returns an object consisting of the parameters of the function. 1137 | 1138 | The key part here is that when we assign a value to that array (it is array-like, as mentioned above) (or any element), the function will use that value rather than the value from the parameter we pass to it when calling the function. Hence, `c` will be `(typeof arguments).length;` (6) rather than 3. 1139 | 1140 | As `c` has a new value of 6, it is definitely less than 10, so we get the final result `console.log(++c)`, which returns 7. 1141 | 1142 | Note that `arguments` is not available on arrow functions. See more detailed here https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/arguments 1143 | 1144 | From ES6 onwards, it is recommended to use ...restParameter given that it is a true array. It means you can manipulate the parameter with native JavaScript functions such as map, reduce or filter. 1145 | 1146 | For PHP developer, we have `func_get_args()` in PHP that does the same thing, but it will not override the value passed. Check it by yourself at https://3v4l.org/dMfhW 1147 | 1148 |

1149 |
1150 | 1151 | --- 1152 | 1153 | ###### 29. What's the output? 1154 | 1155 | ```javascript 1156 | class Calculator { 1157 | constructor(a, b) { 1158 | this.a = a; 1159 | this.b = b; 1160 | } 1161 | static getFlag() { 1162 | return new Array(this.a).length == new Array(this.b).toString().length; 1163 | } 1164 | 1165 | getValue() { 1166 | return Calculator.getFlag() ? typeof this.a : typeof new Number(this.b); 1167 | } 1168 | } 1169 | 1170 | const me = new Calculator(5, 5); 1171 | 1172 | console.log(me.getValue()); 1173 | ``` 1174 | 1175 | - A: NaN 1176 | - B: "string" 1177 | - C: "object" 1178 | - D: "number" 1179 | 1180 |
Answer 1181 |

1182 | 1183 | #### Answer: C 1184 | 1185 | We have a class named Calculator. When declaring a new instance of the object, we pass two parameters `a` and `b`. These two parameters have the same value but `new Array(this.a).length` is totally different from `new Array(this.b).toString().length` because the latter returns a string `",,,,"` meaning the length 4 while the former returns the length of an array and we therefore get 5. 1186 | 1187 | For that reason `getFlag()` returns `false`. In `getValue()` we get `typeof new Number(this.b);` which returns `object`. That is a bit different from `typeof b`, which returns `number`. 1188 | 1189 |

1190 |
1191 | 1192 | --- 1193 | 1194 | ###### 30. What's the output? 1195 | 1196 | ```javascript 1197 | var name = "Auckland"; 1198 | 1199 | const nz = { 1200 | name: "Kiwi", 1201 | 1202 | callMe: function () { 1203 | return this.name; 1204 | }, 1205 | }; 1206 | 1207 | let me = nz.callMe; 1208 | 1209 | let she = nz.callMe.bind(nz); 1210 | 1211 | let result = me() === nz.callMe() ? she() : `${me()} ${she()}`; 1212 | 1213 | console.log(result); 1214 | ``` 1215 | 1216 | - A: undefined 1217 | - B: "Auckland" 1218 | - C: "Kiwi" 1219 | - D: "Auckland Kiwi" 1220 | 1221 |
Answer 1222 |

1223 | 1224 | #### Answer: D 1225 | 1226 | The key point in this question involves the keyword `this` in JavaScript. We have a simple object that contains one method and one string property `name`. 1227 | 1228 | First, it is important to write down is that `let me = nz.callMe;` and then call `me()` is totally different from directly calling `nz.callMe()`. If we assign a variable to a method delared inside an object, `this` in that method will behave differently (when we call the variable as a method and when dirrectly call that method). In particular, in the first case, `this` is the `window` object while in the second one, `this` inside the function still points to property `name` in the object `nz`. It means `me()` returns "Auckland" while `nz.callMe` returns "Kiwi". 1229 | 1230 | Then `result` will return `false` and we get the final output value `${me()} ${she()}`. Why `she()` is different from `me()`? You might easily guess that `she` still `bind` to the object `nz` rather than `window` object as in `me()`. 1231 | 1232 |

1233 |
1234 | 1235 | --- 1236 | 1237 | ###### 31. What's the output? 1238 | 1239 | ```javascript 1240 | const club = { 1241 | name: "Juventus", 1242 | player: ["Ronaldo"], 1243 | showMePlayer: function () { 1244 | this.player.map(function (thename) { 1245 | console.log(this.name.length); 1246 | }, this); 1247 | }, 1248 | showMe: function () { 1249 | this.player.forEach( 1250 | function (thename) { 1251 | console.log(this.name.length); 1252 | }.bind(this) 1253 | ); 1254 | }, 1255 | show: function () { 1256 | const self = this; 1257 | this.player.map(function (thename) { 1258 | console.log(self.name.length); 1259 | }); 1260 | }, 1261 | Me: function () { 1262 | this.player.map(function (thename) { 1263 | console.log(this.name.length); 1264 | }); 1265 | }, 1266 | }; 1267 | 1268 | club.showMePlayer(); 1269 | club.showMe(); 1270 | club.show(); 1271 | club.Me(); 1272 | ``` 1273 | 1274 | - A: 8 - 8 - 8 - 8 1275 | - B: "Juventus" - "Juventus" - "Juventus" - "Juventus" 1276 | - C: "Ronaldo" - "Ronaldo" - "Ronaldo" - "Ronaldo" 1277 | - D: 8 - 8 - 8 - 0 1278 | 1279 |
Answer 1280 |

1281 | 1282 | #### Answer: D 1283 | 1284 | The code snippet above is not a big challenge for you I guess. It simply gives you an example of `this` in different contexts when we declare an anonymous function inside a method of an object. The three first methods are common ways to handle `this` using `this` as second parameter in `map()`, by using `bind(this)` in `forEach` (or map()) or by `that = this`technique (you might see people use `self = this` rather than `that= this`). 1285 | 1286 | The last method `Me()` will cause unexpected result because `this.name` does not bind to the object `club`. Note that you might get another result when testing the code on jsbin.com. On Chrome and Firefox, we get 0. 1287 | 1288 | For further information, kindly have a look at http://speakingjs.com/es5/ch17.html#_pitfall_losing_this_when_extracting_a_method 1289 | 1290 |

1291 |
1292 | 1293 | --- 1294 | 1295 | ###### 32. What's the output? 1296 | 1297 | ```javascript 1298 | ((...a) => { 1299 | const b = ["javascript", "new zealand"]; 1300 | 1301 | const c = [...a, typeof a, ...b, "kiwi"]; 1302 | 1303 | console.log(c.length + c[0].length); 1304 | })(new Array(10)); 1305 | ``` 1306 | 1307 | - A: 5 1308 | - B: 10 1309 | - C: 15 1310 | - D: 20 1311 | 1312 |
Answer 1313 |

1314 | 1315 | #### Answer: C 1316 | 1317 | `...` can be used in two ways in JavaScript (and PHP) as either `spread operator` or `rest parameter`. You might have to check the following article about the two. They are the same as three dots, but the way they are employed vary considerably between the two. https://javascript.info/rest-parameters-spread-operator 1318 | 1319 | We see both `spread operator` and `rest parameter` in the code snippet above. First the parameter `(...a)` in the self-invoking function is of course a `rest parameter` while the constant `c` we see the `spread operator`. In the former case, it simply means that you can pass to the function as many parameter as you want. Note that the `typeof a` in this case is `object` even though it is a native array in JavaScript. (I means native array because you might think about array-like if we use arguments. Please have a look at the question 28 or this link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/arguments). 1320 | 1321 | `Spread operator` as in the constant `c` allows us to combine array. So `...a` in the code above is `rest parameter` when it is used as function parameter but in this case it is the syntax of `spread operator`. 1322 | 1323 | Finally, we get `c` with 5 elements (`...a` is a nested array, so the `length` is 1) but the first element has 10 child elements (when we pass to the function `new Array(10)`). The length of both then returns 15. 1324 | 1325 |

1326 |
1327 | 1328 | --- 1329 | 1330 | ###### 33. What's the output? 1331 | 1332 | ```javascript 1333 | function Kiora(name, ...career) { 1334 | this.name = name; 1335 | 1336 | return Array.isArray(career) === true && typeof career === "object" ? {} : ""; 1337 | } 1338 | 1339 | var student = new Kiora("Vuong"); 1340 | 1341 | console.log(student.name); 1342 | ``` 1343 | 1344 | - A: "Vuong" 1345 | - B: undefined 1346 | - C: ErrorReference 1347 | - D: false 1348 | 1349 |
Answer 1350 |

1351 | 1352 | #### Answer: B 1353 | 1354 | We have a function constructor `Kiora` (written with a capital letter, but that is optional) that can be used to create object, as the `student` object in the code above. In the function, we have two parameters with the second one is actually a `rest parameter`. The typeof operator is `object` but if we check with `Array.isArray(array)` it also returns true. 1355 | 1356 | For that reason, `Array.isArray(career) === true && typeof career === "object"` returns true. Hence the `return` operator finally returns an object `{}`. 1357 | 1358 | You might be surprised when `console.log(student.name);` outputs `undefined` given that the constructor function `Kiora` returns an object. Otherwise, we might simply get the value `name`. 1359 | 1360 |

1361 |
1362 | 1363 | --- 1364 | 1365 | ###### 34. What's the output? 1366 | 1367 | ```javascript 1368 | class Filter { 1369 | constructor(element) { 1370 | this.element = element; 1371 | } 1372 | filter() { 1373 | return this.type() === "object" ? this.element[0].name : "hello"; 1374 | } 1375 | 1376 | type() { 1377 | return typeof this.element; 1378 | } 1379 | } 1380 | 1381 | let countries = [ 1382 | { name: "New Zealand", isdeveloped: true }, 1383 | { name: "Vietnam", isdeveloped: false }, 1384 | ]; 1385 | 1386 | let x = new Filter(countries); 1387 | 1388 | const filter = countries.filter((item) => { 1389 | return !item.isdeveloped; 1390 | }); 1391 | 1392 | console.log(x.filter().length + filter[0].name.length); 1393 | ``` 1394 | 1395 | - A: 15 1396 | - B: 16 1397 | - C: 17 1398 | - D: 18 1399 | 1400 |
Answer 1401 |

1402 | 1403 | #### Answer: D 1404 | 1405 | Apologize that the code snippet is a bit longer than usual. But actually it is not really challenging as you might think. You can easily get the correct result after spending a little of time to debug. 1406 | 1407 | First we declare a class that has two methods. The first method `filter()` will returns the first element of the array (of the propterty `element`) or simply returns `hello` depending on the `type()` method. We know that `typeof of array` will return `object` so the `filter()` method return `this.element[0].name`. 1408 | 1409 | Try to make you feel confused, we then call the built-in `filter()` method. This native method returns a new array depending on the condition we pass to the call-back function. Note that `!item.isdeveloped` means `false`. It means we get `Vietnam`. 1410 | 1411 | Finally we get `New Zealand`.length and `Vietnam`.length, which in total returns 18. 1412 | 1413 |

1414 |
1415 | 1416 | --- 1417 | 1418 | ###### 35. What's the output? 1419 | 1420 | ```javascript 1421 | async function abc() { 1422 | console.log(8); 1423 | 1424 | await Promise.resolve(2).then(console.log); 1425 | 1426 | console.log(3); 1427 | } 1428 | 1429 | setTimeout(() => { 1430 | console.log(1); 1431 | }, 0); 1432 | 1433 | abc(); 1434 | 1435 | queueMicrotask(() => { 1436 | console.log(0); 1437 | }); 1438 | 1439 | Promise.resolve(4).then(console.log); 1440 | 1441 | console.log(6); 1442 | ``` 1443 | 1444 | - A: 6 - 8 - 3 - 0 - 4 - 2 - 1 1445 | - B: 8 - 2 - 3 - 0 - 4 - 6 - 1 1446 | - C: 6 - 8 - 2 - 0 - 4 - 3 - 1 1447 | - D: 8 - 6 - 2 - 0 - 4 - 3 - 1 1448 | 1449 |
Answer 1450 |

1451 | 1452 | #### Answer: D 1453 | 1454 | D is correct anwser. The order of the asynchronous code's output depends on the MicroTask or MacroTask. MicroTask has a higher priority. Note that the synchronous code always be executed before asynchronous code. So in essense, we have the order as follows: 1455 | 1456 | 1) synchronous code 1457 | 2) microtask code (promise, queueMicrotask) 1458 | 3) macrotask code (setTimeout, setInterval) 1459 | 1460 | Be awared that in Nodejs environment, we also have `process.nextTick(callback)` which has the highest priority but we dont have it in this code. 1461 | 1462 | So, first callback in the `setTimeout()` will be executed last given that this is a MacroTask. That is why we got 1 last. 1463 | 1464 | Second, the function `abc()` is called next. Then we have 8 printed out in the console first. As the next line of code inside that function is an asynchrnous code with the keyword "await", we then `console.log(6)` as `Promise.resolve(4).then(console.log)` is an asynchrnous code. That is why we got 6. 1465 | 1466 | Now is the time for `Promise.resolve(2)`, so we get 2. At this point, you might have some sort of confusion. What will happend if we do not pass the keyword "await" before `Promise.resolve(2)` ? 1467 | 1468 | As we have `await`, the code will be blocked here. Then what? We get 0 and 4 not 3. `Promise` and `queueMicrotask` are both microtask and they are already to run before `console.log(3)`. The reason is that microtask queue need to be emptied before any other codes can be called in the callstack. 1469 | 1470 | In the next step, we get 3 and the last one is 1. 1471 | 1472 | What would happend if we do not have the `await` keyword? Then the order of the output will be 8 - 3 - 6 - 2 - 0 - 4 -1. 1473 | 1474 |

1475 |
1476 | 1477 | ###### 36. What's the output? 1478 | 1479 | ```javascript 1480 | function myAccount(money) { 1481 | let myMoney = money; 1482 | 1483 | return { 1484 | status: function () { 1485 | return `You have $ ${myMoney} in your account`; 1486 | }, 1487 | dePoSit: function (amount) { 1488 | myMoney = myMoney + amount; 1489 | }, 1490 | withDraw: function (amount) { 1491 | if (amount > myMoney) { 1492 | return `You cannot withdraw money now`; 1493 | } 1494 | myMoney = myMoney - amount; 1495 | }, 1496 | }; 1497 | } 1498 | 1499 | const vuong = myAccount(1000); 1500 | 1501 | vuong.withDraw(500); 1502 | 1503 | vuong.withDraw(200); 1504 | 1505 | vuong.dePoSit(100); 1506 | 1507 | vuong.withDraw(50); 1508 | 1509 | console.log(vuong.status()); 1510 | ``` 1511 | 1512 | - A: "You have \$ 950 in your account" 1513 | - B: "You have \$ 1000 in your account" 1514 | - C: "You have \$ 550 in your account" 1515 | - D: "You have \$ 350 in your account" 1516 | 1517 |
Answer 1518 |

1519 | 1520 | #### Answer: D 1521 | 1522 | As the "state" of the data is preserved each time we call `dePoSit()` or `withDraw()`, hence we get \$350 after all. 1523 | 1524 | Noted that that is a kind of "factory" function with "preload" data. You might think about another object when pass to `myAccount(somedata);` some other data. That is a really helpful way to create multiple objects from a factory function. 1525 | 1526 |

1527 |
1528 | 1529 | ###### 37. What's the output? 1530 | 1531 | ```javascript 1532 | const hoccoban = { 1533 | x: "youtube.com/hoccoban".length, 1534 | getMe() { 1535 | const inner = function () { 1536 | console.log(++this.x); 1537 | }; 1538 | inner.bind(this)(); 1539 | }, 1540 | }; 1541 | 1542 | hoccoban.getMe(); 1543 | ``` 1544 | 1545 | - A: 20 1546 | - B: 21 1547 | - C: 22 1548 | - D: 23 1549 | 1550 |
Answer 1551 |

1552 | 1553 | #### Answer: B 1554 | 1555 | We get 21. First "youtube.com/hoccoban" returns 20 as we are using the property length of the string. Then it is being added one more value in `++this.x`. The question here seems trivial but it is actually not. There is a crucial note we should keep in mind is that `console.log(++this.x)` will not work as `x` is undefined when it is called outside of the object. 1556 | 1557 | We can solve the problem with `this` in this case by using arrow function in the inner so that is can become something like `const inner = () => {}` as the arrow function does not actually have `this`. It will automatically look around and call the available object when the function is executed. 1558 | 1559 | The second solution is that we can somehow "bypass" the tricky `this` by using that/this solution. We just need to declare a new variable `const that = this` inside getMe() and before declaring inner function. That is a quite common practice. 1560 | 1561 | The third solution is to take advantage of call(), bind() and apply() which are native methods of function (yes, function is also an object in JavaScript). In this case, we implement `bind(this)` to "bind" the function and the object so that `this` can actually point to the object when the function is executed. Note that bind() cannot be instantlly executed so that we need to add () after we bridge the function and the object. If we replace bind() with call(), then we do not need to pass () as in the above example. So `inner.bind(this)();` will become `inner.call(this);`. They are technically equal. In practice, we tend to create a new variable to get the result from the binding of the function and the object. 1562 | 1563 |

1564 |
1565 | 1566 | ###### 38. What's the output? 1567 | 1568 | ```javascript 1569 | function* hocCoBan() { 1570 | yield "js.edu.vn"; 1571 | yield "youtube.com/hoccoban"; 1572 | yield "Vuong Nguyen"; 1573 | } 1574 | 1575 | let data = hocCoBan(); 1576 | 1577 | console.log((typeof data).length + data.next().value.length); 1578 | ``` 1579 | 1580 | - A: NaN 1581 | - B: 10 1582 | - C: Error 1583 | - D: 15 1584 | 1585 |
Answer 1586 |

1587 | 1588 | #### Answer: D 1589 | 1590 | First, take a closer look at the function. It has a asterisk (\*) next to the keyword "function". We do not have `return` keyword inside the function itself. What is going on here? 1591 | 1592 | It you have already known about generator, then this code snippet is not a big deal at all. We do not use generator very often, but this native JavaScript feature is the basis for async/await function, which is supported in ES7 that allows us to handle the flow of asynchronous code much easily. 1593 | 1594 | The operator `typeof data` will return `object` rather than `function`, which is the same case with `typeof hocCoBan()`. Of course, `typeof hocCoBan` still returns `function`. But it is actually a normal function. Basically, we get 6 in the operator `(typeof data).length`. 1595 | 1596 | Then `data.next()` calls the the built-in method `next()` which will output the value in the first `yield`, which is declared in the function. Then we get the length 9 with the string `js.edu.vn`. 1597 | 1598 | After all, we get 15. Not that understanding generator is quite important if you really want to understand `async/await` function. 1599 | 1600 |

1601 |
1602 | 1603 | ###### 39. What's the output? 1604 | 1605 | ```javascript 1606 | const a = [1, 2, "chó", 3, 1, "chó", "mèo", 3]; 1607 | 1608 | const b = [...new Set(a)]; 1609 | 1610 | b.length = "chó".length; 1611 | 1612 | console.log(b); 1613 | ``` 1614 | 1615 | - A: 4 1616 | - B: [1, 2, "chó", 3, "mèo"] 1617 | - C: [1, 2, "chó", "mèo"] 1618 | - D: [1, 2, "chó"] 1619 | 1620 |
Answer 1621 |

1622 | 1623 | #### Answer: D 1624 | 1625 | When using ... in array, it is called spread operator in JavaScript which, technically, is similar to rest parameter (using in the context of function). It provides a more elegant way to concat (combine) or copy array. In the code above, b is a copy of a. However, as we pass a in to a `Set`, it will return the unique value only in a. It means, now we have `[1, 2, "chó", 3, "mèo"] in b. 1626 | 1627 | However, we then set the length for b as 3. Note that "chó".length returns 3 but in PHP, strlen("chó") returns 4, just in case you are coming from PHP world. 1628 | 1629 | As we set the length for the array b, we also cut down the array itselt. That is the reason why we get [1, 2, "chó"] printing out in the console. 1630 | 1631 |

1632 |
1633 | 1634 | ###### 40. What's the output? 1635 | 1636 | ```javascript 1637 | const mot = function (m) { 1638 | return arguments[0]; 1639 | }; 1640 | 1641 | const hai = function (...m) { 1642 | return arguments[arguments[0]]; 1643 | }; 1644 | 1645 | const a = [mot(123), hai(1, 2, 3)]; 1646 | 1647 | console.log(typeof a !== "object" ? a[0] : a[1]); 1648 | ``` 1649 | 1650 | - A: 1 1651 | - B: 2 1652 | - C: 3 1653 | - D: 123 1654 | 1655 |
Answer 1656 |

1657 | 1658 | #### Answer: B 1659 | 1660 | First, it should be noted that `arguments` cannot be used in an arrow function, so in order to take advantage of this feature, we have to write the function in the casual form. `arguments` returns an array-like object that contains any parameter we pass into the function when executing it. 1661 | 1662 | `...` is a `rest operator`. We use this feature in function and array. Noted that in the context of array, it is called `spread operator` and it behaves differently. When declaring a function with ..., we can pass as many parameters into the function itselt when executing it as we want. 1663 | 1664 | Note that in the function `hai`, we return `arguments[arguments[0]]` which means `hai(1, 2, 3)` will return 2 rathern than 1 because `arguments[0]` return 1 and then `arguments[1]` returns 2. 1665 | 1666 | The last thing we have to take note is that the typeof operator of an array will return `object`, here the trick seems more daunting. The final anwser is 2 as we got it in `a[1]`, or `hai(1, 2, 3)`. 1667 | 1668 |

1669 |
1670 | 1671 | ###### 41. What's the output? 1672 | 1673 | ```javascript 1674 | class Component { 1675 | constructor(age) { 1676 | this.age = age + `${typeof Coder}`.length; 1677 | } 1678 | 1679 | getAge() { 1680 | return ++this.age; 1681 | } 1682 | } 1683 | 1684 | class Coder extends Component { 1685 | constructor(age) { 1686 | super(age); 1687 | this.age = age - `${typeof Coder}`.length; 1688 | } 1689 | } 1690 | 1691 | const a = new Coder(16); 1692 | 1693 | console.log(a.getAge()); 1694 | ``` 1695 | 1696 | - A: 7 1697 | - B: 8 1698 | - C: 9 1699 | - D: 10 1700 | 1701 |
Answer 1702 |

1703 | 1704 | #### Answer: C 1705 | 1706 | We have two simple classes in which Coder extends Component. Nothing fancy. As `typeof ClassName` returns `function` rather than `class`, we then get 8 in the operator `"function".length`. 1707 | 1708 | Though we implement `super(age)` in the Coder class, we actually overwrite the contructor of the parent class Component in the child class Coder. Therefore, when initiating the object `a`, the following code is automatically triggered `this.age = age -`\${typeof Coder}`.length;`. The difference between the child and parent 's constructor is minus (-) and plus (+) in the above code. 1709 | 1710 | As such, we have 16 - 8 rather than 16 + 8, which returns 8. The function `getAge()` returns 9, so the corrent answer is C. 1711 | 1712 | Bear in mind that JavaSCript is not a "real" OOP programming language even though we can now implement `class` and `object` as in other languages. 1713 | 1714 |

1715 |
1716 | 1717 | ###### 42. What's the output? 1718 | 1719 | ```javascript 1720 | class RemoveFalse { 1721 | constructor(element) { 1722 | this.element = element; 1723 | 1724 | this.length = this.removeFalse().length; 1725 | } 1726 | 1727 | removeFalse() { 1728 | this.element = this.element.filter(Boolean); 1729 | 1730 | return this.element; 1731 | } 1732 | } 1733 | 1734 | const theArray = [true, false, 1, 0, NaN, undefined, "", null, "js.edu.vn"]; 1735 | 1736 | const a = new RemoveFalse(theArray); 1737 | 1738 | console.log(a.length); 1739 | ``` 1740 | 1741 | - A: false 1742 | - B: true 1743 | - C: 2 1744 | - D: 3 1745 | 1746 |
Answer 1747 |

1748 | 1749 | #### Answer: D 1750 | 1751 | The key message that can be taken away in the code snippet above is `filer(Boolean)` which can be taken into consideration in case you want to eliminate `falsy values` in an array. We can use `filter(callback)` or `filter(Boolean)` in particular in this case to do that. Note that we have to pass into the filter function a callback and in this case Boolean is actually a function. You can check `typeof Boolean` to see it. 1752 | 1753 | Similar to `map` or `reduce` function, `filter` always returns a new array from the exisiting one. `[true, false, 1, 0, NaN, undefined, "", null, "js.edu.vn"].filter(Boolean);` will return `[true, 1, "js.edu.vn"];`, hence calling the function `removeFalse()` gives us 3. So the correct answer is 3. 1754 | 1755 |

1756 |
1757 | 1758 | ###### 43. What's the output? 1759 | 1760 | ```javascript 1761 | const coderfarm = [1, [], {}, [], 2, 3]; 1762 | 1763 | const converted = Number(coderfarm instanceof Array); 1764 | 1765 | const result = coderfarm.indexOf(converted + true); 1766 | 1767 | console.log(result); 1768 | ``` 1769 | 1770 | - A: [] 1771 | - B: {} 1772 | - C: 2 1773 | - D: 4 1774 | 1775 |
Answer 1776 |

1777 | 1778 | #### Answer: D 1779 | 1780 | We have a simple array in the code snippet above that includes some digits, two other arrays and one object. Using the built-in function `Number`, we can convert any value passing to the function into `digit`. As `coderfarm instanceof Array` returns `true`, then `converted` get 1. Noted that you can use another way to check the type of an array is `Array.isArrray(arrayToBeChecked)` which return a `boolean` value. Suprisingly, the operator `typeof []` returns `object` rather than `array`. 1781 | 1782 | The built-in function `indexOf` will return the index of the element that is being checked. So as `converted + true` return 2, we are going to check the index of the element with the value 2 in the array `coderfarm`. 1783 | 1784 | We get 4 in the `console.log` and the correct answer is D. 1785 | 1786 |

1787 |
1788 | 1789 | ###### 44. What's the output? 1790 | 1791 | ```javascript 1792 | const converter = (arrayInput) => { 1793 | return { ...arrayInput }; 1794 | }; 1795 | 1796 | const content = ["function", "object", "decorator"]; 1797 | 1798 | const checking = content[Number(false)]; 1799 | 1800 | const result = typeof converter(content) === content[1]; 1801 | 1802 | console.log(checking ? (result ? (typeof converter).length : false) : false); 1803 | ``` 1804 | 1805 | - A: 6 1806 | - B: NaN 1807 | - C: true 1808 | - D: 8 1809 | 1810 |
Answer 1811 |

1812 | 1813 | #### Answer: D 1814 | 1815 | The operator `...` in JavaScript is very handy. The function `converter` is quite trivial, it takes advantege of `...` (rest operator || spread operator) to turn an array into an object. 1816 | 1817 | First we have the constant `checking` with the value `function` given that `Number(false)` gives us 0 and that is the first index in the array `content`. 1818 | 1819 | Second, the constant `result` gives us the value `true` as the `typeof converter(content)` is `function`, which is also the value of `content[1]`. 1820 | 1821 | Then in the final code, we have `checking = true`, and then `result = true` as well, so the final result is `(typeof converter).length` which is equivalent to `"function".length` because the `typeof of converter` is simply `function`. We get 8 after all and the correct answer is D. 1822 | 1823 | So the key message here is that we can take advantate of the `spread operator` (or `...`) to turn an array to an object. For example: `const a = ["hello", 2]`, then we can have a go with `const b = {...a}` and b is now an object with the following value: `{0: "hello", 1: 2}`. The key of the object is actually the index of the original array. 1824 | 1825 |

1826 |
1827 | 1828 | ###### 45. What's the output? 1829 | 1830 | ```javascript 1831 | function* js(length) { 1832 | for (let i = length.length; i > 0; --i) { 1833 | yield i; 1834 | } 1835 | } 1836 | 1837 | let getJS = js(typeof js); 1838 | 1839 | let result = getJS.next().value; 1840 | 1841 | console.log(result + getJS.next().value); 1842 | ``` 1843 | 1844 | - A: 10 1845 | - B: 14 1846 | - C: 15 1847 | - D: 16 1848 | 1849 |
Answer 1850 |

1851 | 1852 | #### Answer: C 1853 | 1854 | We have a generator function in the code snippet above, which is defined with the \*. Noted that we can "store" as many result as we want in a generator thanks to the keyword `yield`. 1855 | 1856 | As the `typeof js` is `function`, so the length of the string `function` is 8. So when calling `getJS.next().value;`, we get 8. However, in the next calling, it returns 7, and in the following calling after that, we get 6. That is why generator can "store" and "release" (or return) as many value as we want. 1857 | 1858 | So the answer is C, which is 8 (first execution of the generator) + 7 (second execution of the generator). 1859 | 1860 |

1861 |
1862 | 1863 | ###### 46. What's the output? 1864 | 1865 | ```javascript 1866 | var ages = [10, 15, 20, 25]; 1867 | 1868 | let response = []; 1869 | 1870 | ages.some(function (currentValue, index, ages) { 1871 | if (currentValue > ages[ages.length - index]) 1872 | response.push(currentValue + ages.length); 1873 | }); 1874 | 1875 | console.log(response); 1876 | ``` 1877 | 1878 | - A: [20] 1879 | - B: [20, 25] 1880 | - C: [25, 29] 1881 | - D: [29] 1882 | 1883 |
Answer 1884 |

1885 | 1886 | #### Answer: D 1887 | 1888 | `Array.prototype.some()` is a built-in function facilitating us to iterate the array using a callback. As in the code snippet above, there are three parameters in the callback, namely `currentValue` (the value of the current element that is being checked), `index` (the index of the element in the array that is being checked/evaluated) and `ages` (the array itself). 1889 | 1890 | The function `some()` returns a `boolean` value. The code `currentValue > ages[ages.length - index]` returns `true` only one time, which is the last element. Let 's examine the code when it runs through each element: 1891 | 1892 | 1. 10 > ages[4 - 0]. As ages[4] returns `undefined`, and `10 > undefined` returns `false`, it stops. 1893 | 1894 | 2. 15 > ages[4 - 1]. As ages[3] returns 25, it breaks as the operator returns `false`. 1895 | 1896 | 3. 20 > ages[4 - 2]. As ages[2] returns 20, it breaks as the operator returns `false`. 1897 | 1898 | 4. 25 > ages[4 - 3]. As ages[1] returns 10, it returns `true`. Only this value is being pushed to the array `response`. 1899 | 1900 | So `response.push(currentValue + ages.length)` will add the value 25 + 4 to the array `response`, D is the correct answer. 1901 | 1902 |

1903 |
1904 | 1905 | ###### 47. What's the output? 1906 | 1907 | ```javascript 1908 | const getSTring = (string, method = false) => { 1909 | if (method === true) { 1910 | return string.slice(1, 4).length; 1911 | } 1912 | 1913 | return string.substr(1, 4).length; 1914 | }; 1915 | 1916 | console.log(getSTring("hello", true) + getSTring("hello")); 1917 | ``` 1918 | 1919 | - A: 6 1920 | - B: 7 1921 | - C: 8 1922 | - D: 9 1923 | 1924 |
Answer 1925 |

1926 | 1927 | #### Answer: B 1928 | 1929 | `getString()` is an arrow function with two parameters. As you can see that the parameter `method` has the default value `false`, then if you do not pass any value to it when executing the function, the default value will be used. 1930 | 1931 | The key thing to take note from the code above is the difference betweet `slice(1, 4)` (which returns 3 characters) and `substr(1, 4)` (which returns 4 ones). 1932 | 1933 | Finally `console.log(getSTring("hello", true) + getSTring("hello"))` returns 7 because `slice` and `substr` are both used. 1934 | 1935 |

1936 |
1937 | 1938 | ###### 48. What's the output? 1939 | 1940 | ```javascript 1941 | (function (a, b, c) { 1942 | console.log(Boolean([...arguments].slice(2, 3)[0].slice(3, 4))); 1943 | })("hello", "world", "new zealand"); 1944 | ``` 1945 | 1946 | - A: "new" 1947 | - B: true 1948 | - C: "land" 1949 | - D: false 1950 | 1951 |
Answer 1952 |

1953 | 1954 | #### Answer: B 1955 | 1956 | The code above is a self-executing function. It runs when it is being declared. We have three parameters and three arguments passed are `"hello", "world"` and `"new zealand"`. 1957 | 1958 | First, `arguments` returns an object consisting of arguments passed to the function when executing it. However, using spread operator `...`, we then convert the object to an array. We can also do it by using `Array.from(object)`. 1959 | 1960 | Second, `slice(2, 3)` extracts the element from the index 2 to the index 3, which returns `"new zealand"`. It is still an array. We then extract the element with the index `[0]` and we get the string `"new zealand"` rather than an array. 1961 | 1962 | Third, `"new zealand".slice(3, 4)` gives us an empty string (with a space between) `" "`. The `Boolean(" ")` gives us `true`. Noted that if there is no space in the empty string, we get `false` instead. 1963 | 1964 | So the correct answer is B. 1965 | 1966 |

1967 |
1968 | 1969 | ###### 49. What's the output? 1970 | 1971 | ```javascript 1972 | class HocCoBan { 1973 | name = "hello world"; 1974 | 1975 | getSlice(slice) { 1976 | return this.getName(slice).slice(true, this.name.length); 1977 | } 1978 | 1979 | getName(space) { 1980 | return this.name.split(space); 1981 | } 1982 | } 1983 | 1984 | HocCoBan.prototype.split = function (argument) { 1985 | return this.getSlice(argument); 1986 | }; 1987 | 1988 | const a = new HocCoBan(); 1989 | 1990 | console.log(a.split("").length); 1991 | ``` 1992 | 1993 | - A: NaN 1994 | - B: true 1995 | - C: 10 1996 | - D: 11 1997 | 1998 |
Answer 1999 |

2000 | 2001 | #### Answer: C 2002 | 2003 | The code above is nothing much special. However it is written in a complicated way on purpose. First, we have a class named "HocCoBan" with two methods and one property. Then we add another method `split` using the tradional way (via `prototype`). Note that `class` in JavaScript is simply a syntactic sugar of `function` given that `typeof ClassName` return `function`. 2004 | 2005 | When we call the method `split`, we pass the an empty string to it. This method then call other methods. The flow is as follows: 2006 | 2007 | `split("")` ==> `this.getSlice("")` ==> `this.getName("")` ==> `this.name.split("")`. Here `split` is a built-in function that convert a string to an array. 2008 | 2009 | Noted that in `getSlice()`, we also use `.slice(true, this.name.length)` to `slice` (cut) the array from the index 1 to 11. So the length is 10. 2010 | 2011 | So the final answer is C. 2012 | 2013 | This code might help us master the concept function `prototype` in JavaScript and the understand the difference between the built in function `String.prototype.split` and the function we declare by ourself `HocCoBan.prototype.split`. 2014 | 2015 |

2016 |
2017 | 2018 | ###### 50. What's the output? 2019 | 2020 | ```javascript 2021 | function javaScript(node) { 2022 | let mot = node.includes("I") ? "love" : "you"; 2023 | 2024 | return function (deno = mot) { 2025 | let hai = node.replace(deno, "done"); 2026 | 2027 | return function (done = hai) { 2028 | return (node + deno + done).length; 2029 | }; 2030 | }; 2031 | } 2032 | 2033 | console.log(javaScript("I love you")()()); 2034 | ``` 2035 | 2036 | - A: 18 2037 | - B: 24 2038 | - C: 20 2039 | - D: 25 2040 | 2041 |
Answer 2042 |

2043 | 2044 | #### Answer: B 2045 | 2046 | Apart from learning some built-in functions to handle string such as `replace` and `inclues`, we are reviving the concept of `currying function` in JavaScript. Say you want to declare a function with three parameters, you may consider refactoring the code by declaring 3 nested functions, each with one parameter you wish to pass to. Basically, both of them work in the same way. However, noted that only the outerest (the main) function has the name as `javaScript` in the code above. Both nested (inner) functions are declared without the name. We also use three `return` keywords in the code. 2047 | 2048 | When executing the function, you then have three `()` as in the `javaScript("I love you")()()`. We do not pass any argument into the second and third functions (both are inner/nested functions without the name) and these functions will take the default value we have alreaded declared when being executing. 2049 | 2050 | All in all, we have the final operator `return (node + deno + done).length;` in which `node` is "I love you", `deno` is "love" and `done` is "I done you". The length of these strings is 24, which you can calculate by yourself the concatenated string `I love youyou I done you`. Be aware of the `empty space`, which is also taken into account. 2051 | 2052 |

2053 |
2054 | 2055 | ###### 51. What's the output? 2056 | 2057 | ```javascript 2058 | const www = ["hello", "coranovirus", "kiora", "world", "new zealand"]; 2059 | 2060 | const found = www.find(function (world) { 2061 | return world > "victory"; 2062 | }); 2063 | 2064 | const result = found[1] < www[0][0] ? www[false ? 1 : 0] : www[true ? 0 : 1]; 2065 | 2066 | console.log(result); 2067 | ``` 2068 | 2069 | - A: "hello" 2070 | - B: "world" 2071 | - C: "victory" 2072 | - D: "w" 2073 | 2074 |
Answer 2075 |

2076 | 2077 | #### Answer: A 2078 | 2079 | The key information in the question above is about the method `Array.prototype.find()`. It returns the first element in the array that meets the condition declared in the callback function, which is passed to the function. The array is being iterated to check every single element. In the code above, we might easily see that the element `world` is the first element in the array that has a larger value than `victory`. Remember that "w" > "v" return trues if the two letters are compared. When two words are being compared, only the first letter in each word is being utilised to compare. 2080 | 2081 | As the result, `found` is now `world` and thus `found[1]` returns the letter `w` whereas `www[0][0]` gives us the letter `h` in the element `hello`. It means `found[1] < www[0][0]` returns `false`. 2082 | 2083 | So the final result is `www[true ? 0: 1]` or `www[0]`, which is `hello`. And the correct answer is A. 2084 | 2085 |

2086 |
2087 | 2088 | ###### 52. What's the output? 2089 | 2090 | ```javascript 2091 | (function (flag) { 2092 | let age = Boolean(NaN === NaN ? false : flag); 2093 | 2094 | console.log(age.toString()[Number(flag)]); 2095 | })([]); 2096 | ``` 2097 | 2098 | - A: "f" 2099 | - B: "t" 2100 | - C: true 2101 | - D: false 2102 | 2103 |
Answer 2104 |

2105 | 2106 | #### Answer: B 2107 | 2108 | We have a self-executing function with the parameter/argument is an empty array. Noted that `NaN === NaN` returns `false`, then `age` gets the value `flag`, which is an empty array. However, the boolean value is `true` when we call `Boolean([])`. 2109 | 2110 | The function `toString()` returns the string `true` and the `Number([])` returns `0`. Then we get "t" in the console.log. The correct answer is B. 2111 | 2112 | Keep in mind that `Boolean([])` ==> `true` but `Number([])` ==> `0`. And sadly `NaN === NaN` returns `false`. 2113 | 2114 |

2115 |
2116 | 2117 | ###### 53. What's the output? 2118 | 2119 | ```javascript 2120 | 2121 | 1) console.log(Boolean([])); 2122 | 2) console.log(Number([])); 2123 | 3) console.log(Number(Boolean([]))); 2124 | 4) console.log(Boolean(Number([]))); 2125 | 2126 | 5) console.log(Boolean({})); 2127 | 6) console.log(Number({})); 2128 | 7) console.log(Number(Boolean({}))); 2129 | 8) console.log(Boolean(Number({}))); 2130 | 2131 | 9) console.log(Boolean(new Boolean(false))); 2132 | 2133 | ``` 2134 | 2135 | - A: true - 0 - 1 - false - true - 1 - 1 - false - false 2136 | - B: true - 0 - 1 - false - false - NaN - 1 - false - true 2137 | - C: true - 0 - 1 - false - false - false - 1 - false - false 2138 | - D: true - 0 - 1 - false - true - NaN - 1 - false - true 2139 | 2140 |
Answer 2141 |

2142 | 2143 | #### Answer: D 2144 | 2145 | JavaScript is sometimes tedious to deal with given that it is a loosely type language. The data type of a variable can be changed depending on the value. An unexpected behaviour might unfortunately occur when you change/convert the original value to another one. 2146 | 2147 | For example, the code 2 `Number([])` returns `0` and 6 `(Number({}))` returns `NaN`, although both `(Boolean([]))` and `(Boolean({}))` return `true`. 2148 | 2149 | In the code 9 `Boolean(new Boolean(false))`, we get `true` even though we pass into the function constructor `Boolean()` a `false` (as the) parameter. However, if we do not use the keyword `new`, then `false` will return. It seems that in `Boolean(new Boolean(false))`, we have a valid opreration, so it is `true`. However, in the `Boolean(Boolean(false)))` where we do not use the keyword `new`, we then get `false` because now a `false` value is being evaluated rather than an operation. 2150 | 2151 | So, the correct answer is D. 2152 | 2153 | Credit: @tiepphan, Vietnamese Angular Facebook group. 2154 | 2155 |

2156 |
2157 | 2158 | ###### 54. What's the output? 2159 | 2160 | ```javascript 2161 | const myYoutube = { 2162 | name: "hoccoban", 2163 | address: "youtube.com/hoccoban", 2164 | getInfo() { 2165 | return this; 2166 | }, 2167 | content: () => (this === window ? myYoutube.getInfo() : this), 2168 | }; 2169 | 2170 | console.log(myYoutube.content().name); 2171 | ``` 2172 | 2173 | - A: "hoccoban" 2174 | - B: window (object) 2175 | - C: NaN 2176 | - D: undefined 2177 | 2178 |
Answer 2179 |

2180 | 2181 | #### Answer: A 2182 | 2183 | To answer the tricky question above, you might want to have a look at the concept of `this` in JavaScript (on browser environment). By default, `this` refers to `window` object. Note that `Window` (written in capital) is the Function constructor of the `window` object. In this regard, `console.log(this === window)` return true but `console.log(this === Window)` returns false. 2184 | 2185 | As `content()` is an arrow function, `this` declared inside this function points to `window`, so `myYoutube.content()` returns `myYoutube.getInfo()`. Noted that we have to explicitly write `myYoutube.getInfo()` to make sure the code will run correctly as `this` in this case does not work as it does not refer to the currect object. In the function `getInfo()`, however, `this` actually refers to the currect object instead of `window` object because we use a normal function here. 2186 | 2187 | Then we have the property `name` with the value "hoccoban". So the correct answer is A. 2188 | 2189 | Credit: Thanks https://github.com/phanvigiaii for fixing the typo. Please make a pull request when you have time bro. Cheer. 2190 | 2191 |

2192 |
2193 | 2194 | ###### 55. What's the output? 2195 | 2196 | ```javascript 2197 | const myArray = [1, 2, 3]; 2198 | 2199 | myArray.someProperty = this; 2200 | 2201 | Array.prototype.someOtherProperty = "hello"; 2202 | 2203 | let result = []; 2204 | 2205 | for (let key in myArray) { 2206 | result.push(key); 2207 | } 2208 | 2209 | for (let key in myArray) { 2210 | if (myArray.hasOwnProperty(key)) { 2211 | result.push(key); 2212 | } 2213 | } 2214 | 2215 | console.log(result.length); 2216 | ``` 2217 | 2218 | - A: 10 2219 | - B: NaN 2220 | - C: 9 2221 | - D: 7 2222 | 2223 |
Answer 2224 |

2225 | 2226 | #### Answer: C 2227 | 2228 | We have a simple array that consists of 3 elements. If checking the type of the array with the operator `typeof`, we will have `object`. (Hint, you can make use of `Array.isArray(array))` or `array instanceof Array` to check its type). 2229 | 2230 | When declaring `myArray.someProperty`, we now add a new property to that array and when declaring `Array.prototype.someOtherProperty = "hello"`, we add a new property to every single array. 2231 | 2232 | As a result, the `for... in` loop will iterate through the array in question and return its key/property and the inherited property as well. However, in the second iteration, we take advantage of the method `hasOwnProperty(key)` to check whether a particular key/property actually belongs to the array in question rather than the inherited one. 2233 | 2234 | In short, in the first iteration, we get 5 (3 original ones, 1 property that is directly added to the array, 1 inherited from the Array.prototype. In the second one, we only get 4 as the inherited property is not taken into consideration. 2235 | 2236 | Keep in mind that, we use `for... of` to loop through an array or the traditional `for` loop. It is not a good practice to use `for ... in` to loop through an array. It is often used to loop through an object. 2237 | 2238 |

2239 |
2240 | 2241 | ###### 56. What's the output? 2242 | 2243 | ```javascript 2244 | const coderfarm = [1, 2, 3, 4, 5]; 2245 | 2246 | const [top, ...bottom] = (function (a) { 2247 | let result = a; 2248 | 2249 | a.unshift(new Array(3)); 2250 | 2251 | return result; 2252 | })(coderfarm); 2253 | 2254 | console.log(top.length + bottom.length); 2255 | ``` 2256 | 2257 | - A: 8 2258 | - B: 9 2259 | - C: 10 2260 | - D: 11 2261 | 2262 |
Answer 2263 |

2264 | 2265 | #### Answer: A 2266 | 2267 | We are using destructure array (or object) technique to extract element of an array (or object). We also take advantage of `...` (spread parameter) here. 2268 | 2269 | The array we are destructuring is returned from a self-executing function. First we pass the parameter `coderfarm`, which is the parameter `a` when declaring the function. Then we update this array with some additional value (an array with three `undefined` elements using `new Array(3)`) on the top of the array (using `unshift`). The array is updated now as `[[undefined, undefined, undefined], 1, 2, 3, 4, 5]`. 2270 | 2271 | So `top` is the first element of the array or `[undefined, undefined, undefined]`, which returns 3 when we check the length. 2272 | 2273 | The `bottom` returns the rest of the array in question, which is 5 when using `length` property. 2274 | 2275 | The final number is 8 and thus the correct answer is A. 2276 | 2277 |

2278 |
2279 | 2280 | ###### 57. What's the output? 2281 | 2282 | ```javascript 2283 | let age = { number: 10 }; 2284 | 2285 | const getAge = (flag) => { 2286 | flag ? delete age.number : delete age; 2287 | return age.number++; 2288 | }; 2289 | 2290 | console.log(getAge(false)); 2291 | 2292 | console.log(age.number); 2293 | 2294 | console.log(getAge(true)); 2295 | 2296 | console.log(age.number); 2297 | ``` 2298 | 2299 | - A: 10 - 10 - NaN - NaN 2300 | - B: 10 - 10 - undefined - undefined 2301 | - C: 10 - 11 - undefined - undefined 2302 | - D: 10 - 11 - NaN - NaN 2303 | 2304 |
Answer 2305 |

2306 | 2307 | #### Answer: D 2308 | 2309 | The operator `delete` only works on the property of an object, not the object itself. In the code snippet above, we have a simple function `getAge` with the parameter `flag`. When the `flag` is `true`, we trigger `delete age.number` and if it is `false`, we will use the operator `delete` upon the whole object. 2310 | 2311 | As this operator does not work on an object, if we can say that, it turns out that `delete age` actually does nothing. As such, `console.log(getAge(false))` returns 10 and simultanously increases the value of `age.number` to 11. The value is now being kept in the memory. As such, `console.log(age.number)` will return 11. 2312 | 2313 | When we pass the argument `flag` as `true` in the `console.log(getAge(true))`, we will trigger `delete age.number` which removes the value and the property `age.number` itself. It means `age.number` is now `undefined`. However, because we also attempt to increase the value of this `undefined` property using `++` operator, it returns `NaN`. 2314 | 2315 | `console.log(age.number)` also returns `NaN` as well. So the correct answer is D. 2316 | 2317 |

2318 |
2319 | 2320 | ###### 58. What's the output? 2321 | 2322 | ```javascript 2323 | const youtube = { name: "hoccoban" }; 2324 | 2325 | const copy = Object.create(youtube); 2326 | 2327 | const cloneA = Object.assign({}, copy); 2328 | 2329 | const cloneB = Object.assign({}, youtube); 2330 | 2331 | console.log(cloneA.name); 2332 | 2333 | console.log(cloneB.name); 2334 | 2335 | console.log(copy.name); 2336 | ``` 2337 | 2338 | - A: undefined - "hoccoban" - "hoccoban" 2339 | - B: "hoccoban" - "hoccoban" - "hoccoban" 2340 | - C: "hoccoban" - "hoccoban" - "undefined" 2341 | - D: undefined - "undefined" - "hoccoban" 2342 | 2343 |
Answer 2344 |

2345 | 2346 | #### Answer: A 2347 | 2348 | We have three outputs in the code snippet above. 2349 | 2350 | First `console.log(cloneA.name);` will return `undefined` but why? We use `Object.assign` to clone a new object from an empty and from the object `copy`. The object `copy` itself is actually created from the original object `youtube` using `Object.create`. Noted that because we use `Object.create`, `copy` will inherit the data from the original one but it is still an empty object itself. 2351 | 2352 | Second, both `console.log(cloneB.name)` and `console.log(copy.name)` return "hoccoban" because `cloneB.name` will have the actual property `name`. On the contrary, `copy.name` outputs the property `name` inherited from the `youtube`. 2353 | 2354 | So the correct answer is A. 2355 | 2356 |

2357 |
2358 | 2359 | ###### 59. What's the output? 2360 | 2361 | ```javascript 2362 | ((x) => { 2363 | const data = !Array.isArray(x) ? x : x.entries(); 2364 | 2365 | console.log(data.next().value[1]); 2366 | })(["hello", "world", "vuong"]); 2367 | ``` 2368 | 2369 | - A: NaN 2370 | - B: "hello" 2371 | - C: "world" 2372 | - D: "vuong" 2373 | 2374 |
Answer 2375 |

2376 | 2377 | #### Answer: B 2378 | 2379 | We have a self-invoking function here and we pass an array to it when the function is executed. Note that `Array.isArray(x)` return `true` but actually we use `!` before `Array.isArray(x)`. It means `data` will return `x.entries()`. 2380 | 2381 | The method `array.entries()`, as you might have already known, returns a `gererator`. Here we will call `next()` to iterate through each element. Note that if you only call `next()` once, it will only return the first element instead of the whole iterator. 2382 | 2383 | Then when we call `value`, it returns an array with the index and the value of the iterator. So what will we get if we call ` console.log(data.next().value[0])`. Sure, it returns `0` as `0` is the index. 2384 | 2385 | So the correct answer is B. 2386 | 2387 |

2388 |
2389 | 2390 | ###### 60. What's the output? 2391 | 2392 | ```javascript 2393 | let x = Symbol(); 2394 | 2395 | let y = Symbol(); 2396 | 2397 | console.log(x === y ? `${typeof x}`[1] : `${typeof x}`[2]); 2398 | ``` 2399 | 2400 | - A: NaN 2401 | - B: "object" 2402 | - C: "y" 2403 | - D: "m" 2404 | 2405 |
Answer 2406 |

2407 | 2408 | #### Answer: D 2409 | 2410 | As `x` and `y` are both instances of `symbol`, they are unique in our codebase; therefore, the `===` comparison will return `false` as expected. In the simple code snippet above, we get the `else` operation. 2411 | 2412 | It should be noted that the `typeof x` operation gives us `symbol`, and since a string in JavaScript is iterable, we get `m` as we pass in the index 2. 2413 | 2414 | So the correct answer is D. 2415 | 2416 |

2417 |
2418 | 2419 | ###### 61. What's the output? 2420 | 2421 | ```javascript 2422 | const frameworks = ["react", "angular", "vue"]; 2423 | 2424 | const iterator = frameworks[Symbol.iterator](); 2425 | const i = frameworks.entries(); 2426 | 2427 | iterator.next(); 2428 | i.next(); 2429 | 2430 | console.log(iterator.next().value[1]); 2431 | console.log(i.next().value[1]); 2432 | ``` 2433 | 2434 | - A: "react" - "angular" 2435 | - B: "react" - "react" 2436 | - C: "angular" - "angular" 2437 | - D: "n" - "angular" 2438 | 2439 |
Answer 2440 |

2441 | 2442 | #### Answer: D 2443 | 2444 | As `frameworks` is an array, it has a built-in method named `Symbol.iterator`. You can hence iterate through the whole array using commonly used methods such as `for... of`, normal `for loop`, `forEach` or `map`, among others. That is relatively trivial, I suppose. 2445 | 2446 | This code challenge above is written to help us understand the concept of iteration better. First, we use the built-in method called `entries()` to create a new iteration. So does [Symbol.iterator](). Both seem to do the same thing. 2447 | 2448 | Each time we call `next()` method, the iteration will output one element. We then can call `value()` to get the value. The difference between `iterator` and `i` is that the former shows the value itself while the latter outputs an array consisting of the index and the value. It means that in the code above, `iterator.next().value` returns `angular` and `i.next().value` gives us `[1, angular]`. 2449 | 2450 | So the correct answer is D. 2451 | 2452 |

2453 |
2454 | 2455 | ###### 62. What's the output? 2456 | 2457 | ```javascript 2458 | class React { 2459 | theName = "Not React"; 2460 | } 2461 | 2462 | class Author extends React { 2463 | static theName = "Real React"; 2464 | 2465 | render() { 2466 | return this.theName; 2467 | } 2468 | 2469 | static render() { 2470 | return this.theName; 2471 | } 2472 | } 2473 | 2474 | const me = new Author(); 2475 | 2476 | console.log(me.render()); 2477 | 2478 | console.log(Author.render()); 2479 | ``` 2480 | 2481 | - A: "Not React" - "Real React" 2482 | - B: "Not React" - Error 2483 | - C: Error - Error 2484 | - D: Error - "Real React" 2485 | 2486 |
Answer 2487 |

2488 | 2489 | #### Answer: A 2490 | 2491 | We have two classes in the code snippet above. It sounds we are imitating React. The `React` class has only one property named `theName,` and no method is declared here. Providing that `Author` extends the `React` class, it inherits that property, surely. However, we have also declared another property with the same name in the `Author` classs. The difference is that the property declared in the child class is given the keyword `static.` 2492 | 2493 | The `Author` class also has two methods with the same name `render()`, one as regular methods and another with `static` keyword. Will that work in JavaScript? 2494 | 2495 | It turns out that JavaScript is quite flexible. It supports both property and method if they are declared with the same name as long as they are either regular property (or method) or static property (or method). 2496 | 2497 | The last thing you should be aware of is that the method `static render()` only calls the static property, here is `static theName = "Real React";` So does the regular method `render().` As such, the code does not run into any issues. 2498 | 2499 | So the correct answer is A. 2500 | 2501 |

2502 |
2503 | 2504 | ###### 63. What's the output? 2505 | 2506 | ```javascript 2507 | class js { 2508 | say = "hello"; 2509 | } 2510 | 2511 | js.prototype.say = "goodbye"; 2512 | console.log(new js().say); 2513 | 2514 | js.prototype.thename = "google"; 2515 | console.log(new js().thename); 2516 | ``` 2517 | 2518 | - A: Error - Error 2519 | - B: "hello" - "google" 2520 | - C: "goodbye" - "google" 2521 | - D: Error - "google" 2522 | 2523 |
Answer 2524 |

2525 | 2526 | #### Answer: B 2527 | 2528 | `js` is a standard class declared in the code snippet above that has only one property with the name `say.` Then we again declare another property with the same name `say` for it. You might think that the property `say` has been overwritten with a new value `goodbye.` 2529 | 2530 | That is not the case as we will get `hello` when we run `console.log(new js().say);`. It is clear that the JavaScript engine prioritizes the property declared inside the class more than the property declared later using the prototype mechanism. 2531 | 2532 | If the property has not been declared inside the class itself, we can then add a new one with the help of `prototype` as in `thename`. Without the doubt, the code `console.log(new js().thename);` gives us `google` as expected. 2533 | 2534 | So the correct answer is B. 2535 | 2536 |

2537 |
2538 | 2539 | ###### 64. What's the output? 2540 | 2541 | ```javascript 2542 | const App = ([y, x, z]) => { 2543 | return () => { 2544 | ++x; 2545 | return () => { 2546 | return x++; 2547 | }; 2548 | }; 2549 | }; 2550 | 2551 | console.log(App([10, 20, 30, 40])()()); 2552 | ``` 2553 | 2554 | - A: 10 2555 | - B: 32 2556 | - C: 21 2557 | - D: 22 2558 | 2559 |
Answer 2560 |

2561 | 2562 | #### Answer: C 2563 | 2564 | To answer the question raised on the above code snippet, you might want to revisit two concepts, `currying function` and `destructing array or object.` 2565 | 2566 | First, `currying function` means we convert a function with multiple parameters into multiple functions with a SINGLE parameter. Then you can easily manipulate the flow of the data. Noted that `currying function` is relevant to `higher-order function`, you might want to have a look. 2567 | 2568 | `destructing array or object` means we attempt to extract a complex array or object more conveniently. For example, `[y, x, z] = [10, 20, 30, 40]` will extract y, x and z with the value 10, 20 and 30 respectively. 2569 | 2570 | The last thing is incremental operator here `++x` returns 21 but `x++` does not as it still returns 21. 2571 | 2572 | So the correct answer is C. 2573 | 2574 |

2575 |
2576 | 2577 | ###### 65. What's the output? 2578 | 2579 | ```javascript 2580 | const numbers = [5, 6, 7]; 2581 | 2582 | function callback(accumulator, currentValue) { 2583 | return accumulator + currentValue; 2584 | } 2585 | 2586 | const theCallBack = (accumulator, currentValue) => accumulator + currentValue; 2587 | 2588 | const sum = numbers.reduce( 2589 | callback, 2590 | numbers.reduce(theCallBack, numbers.reduce(theCallBack, 7)) 2591 | ); 2592 | 2593 | console.log(sum); 2594 | ``` 2595 | 2596 | - A: 54 2597 | - B: 55 2598 | - C: 60 2599 | - D: 61 2600 | 2601 |
Answer 2602 |

2603 | 2604 | #### Answer: D 2605 | 2606 | `Array.prototype.reduce()` is a bit perplexed built-in method that allows you to manipulate data in an array. It returns a single value from the array predefined as in the case with `map` or `filter`. The syntaxt of the function is `arr.reduce(callback( accumulator, currentValue, [, index[, array]] )[, initialValue])`, so it accepts a callback function with four arguments including `accumulator`, `currentValue`, `currentIndex` (optional) and `array` (optional). 2607 | 2608 | The second argument of the `reduce` method, which is optional, is called `initialValue` that will be counted as the first element with the index 0 when `reduce` is executing. If `initialValue` is not provided, then `reduce` will run with the index 1 instead. `reduce()` sounds complicated, but truly it is not. In case you want to revise the function, kindly take a look at MDN here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce 2609 | 2610 | The above code has two callback functions named `callback` and `thecallback`, which do the same thing. The seemingly creepy code is the variable `sum`, which is returned by a couple of nested `reduce` functions. It turns out that there is only one "real" `reduce` function and the other ones give us `initialValue` only. 2611 | 2612 | - The first `initialValue` is 7; 2613 | - The first nested `reduce` function gives us 7 (initialValue) + 5 + 6 + 7 = 25. 2614 | - The second nested `reduce` has 25 as the initialValue, which we get from the above. Then it returns 25 + 5 + 6 + 7 = 43; 2615 | - The "real" `reduce` function now has 43 as the initialValue, the we get the final result: 43 + 5+ 6 + 7 = 61. 2616 | 2617 | So the correct answer is D. 2618 | 2619 |

2620 |
2621 | 2622 | ###### 66. What's the output? 2623 | 2624 | ```javascript 2625 | const a = { name: "hoccoban.com" }; 2626 | const b = { name: "youtube.com/hoccoban" }; 2627 | 2628 | const first = { ...a }.name.length; 2629 | const second = { ...a, ...b }.name.length; 2630 | const third = { ...a, ...b, name: "hello" }.name.length; 2631 | 2632 | console.log(first + second + third); 2633 | ``` 2634 | 2635 | - A: 12 2636 | - B: 37 2637 | - C: 5 2638 | - D: 20 2639 | 2640 |
Answer 2641 |

2642 | 2643 | #### Answer: B 2644 | 2645 | The code snippet above is relatively trivial. What we can learn from it is all about the `spread operator` (three-dot ...). Sometimes it is also used as a `rest operator` to extract data from an object or array. 2646 | 2647 | We have two simple objects which both have the same key `name` but different values. The constant `first` gives us the length of the string value of the keyword `name` that is copied from `a`. So, `first` is now 12. 2648 | 2649 | The constant `second` merges `a` and `b` into one object. However, as `b` has the same key `name` with `a`, the object created by merging two objects will have the value of `b`. It means the constant `second` gives us the length of `youtube.com/hoccoban`, which is 20. 2650 | 2651 | `third` does the same thing with `first` and `second` as it merges two objects into one. However, it also adds another key-value to the object. Coincidently, the key now is `name`, which is the same with the key attained from `a` and `b`. Hence, this key and value will take over the merged object. That means `third` is the length of the string `hello`, which is 5. 2652 | 2653 | In total, we have 12 + 20 + 5, and the final result is 37. 2654 | 2655 | So the correct answer is B. 2656 | 2657 |

2658 |
2659 | 2660 | ###### 67. What's the output? 2661 | 2662 | ```javascript 2663 | const hocCoBan = {}; 2664 | 2665 | Object.defineProperty(hocCoBan, "domain", { 2666 | value: "hoccoban.com", 2667 | }); 2668 | 2669 | async function App({ year, age }) { 2670 | return year - age + hocCoBan.domain.length; 2671 | } 2672 | 2673 | App({ year: 2021, age: 30 }).then((r) => console.log(r)); 2674 | ``` 2675 | 2676 | - A: 2051 2677 | - B: 2001 2678 | - C: 30 2679 | - D: 2003 2680 | 2681 |
Answer 2682 |

2683 | 2684 | #### Answer: D 2685 | 2686 | The code snippet above seems complicated regarding how we take advantage of `Object.defineProperty` to add key and value to the object `hocCoBan`. In fact, `Object.defineProperty` has a couple of handy features that allow us to control the behavior of the object in some situations where we want to make sure that the object created is mutable or not, whether it is iterable (using `for..in`) and so for. For example, if we set `configurable: false` when we declare an object with `Object.defineProperty`, we cannot use `delete` operator to delete the object's property. We cannot change the value of that property as well. 2687 | 2688 | The second "take away" message when reading the code above is the unpacking object technique, or a more frequent term is the destructing object. Say you have an object with two keys called `year` and `age`, then you can get them by using the destructing object technique as follows: `{year, age} = theOBject;`. In the code above, when declaring the function `App`, we also use destructing object technique to get the key from the object and use them as the parameters. 2689 | 2690 | If you are familiar with asynchronous code in JavaScript when using the keyword `async,` it is not a big deal to understand why we need to use `then` to get the function `App` being called. It fact, `async` always returns a promise, so we need to use `then` method to get the data we want. 2691 | 2692 | The flow of the code is: 2021 - 30 + `"hoccoban.com".length` (which is 12). 2693 | 2694 | The final result is 2003. So the correct answer is D. 2695 | 2696 |

2697 |
2698 | 2699 | ###### 68. What's the output? 2700 | 2701 | ```javascript 2702 | class hoccoban { 2703 | #thisyear = 2021; 2704 | constructor(covidTheFirstYear) { 2705 | this.covidTheFirstYear = covidTheFirstYear; 2706 | } 2707 | 2708 | getThisYear() { 2709 | return this.#thisyear; 2710 | } 2711 | 2712 | getCovidFirstYear() { 2713 | return this.covidTheFirstYear; 2714 | } 2715 | } 2716 | 2717 | const message = new hoccoban(2019); 2718 | 2719 | const result = 2720 | hoccoban.hello ?? message.getThisYear() - message.getCovidFirstYear(); 2721 | 2722 | console.log(result); 2723 | ``` 2724 | 2725 | - A: NaN 2726 | - B: 2019 2727 | - C: undefined 2728 | - D: 2 2729 | 2730 |
Answer 2731 |

2732 | 2733 | #### Answer: D 2734 | 2735 | This challenge partly illustrates the newest features of JavaScript detailed in ECMAScript 2020 or ES11. 2736 | 2737 | Now you can declare a private property in a class thanks to the symbol `#`. Like other languages, a private property in JavaScript can only be accessed from inside the class. It will trigger an error when you attempt to call it outside the class, surely. 2738 | 2739 | The second feature you might see on the code snippet above is the `nullish coalescing operator` or `??`. When declaring some variable such as `let myVariable = number ?? 7`, if the variable `number` is either `undefined` or `null`, the variable `myVariable` will be assigned the value `7`. 2740 | 2741 | So `hoccoban.hello` means `undefined` because we have not added any value yet. Then by using `nullish coalescing operator` with `??` the variable `result` simply returns 2 as `message.getThisYear()` gives us 2020 and `message.getCovidFirstYear()` gives us 2019. Note that we can access the private property outside of the class via a method, as in the method `getThisYear()`. 2742 | 2743 | So the correct answer is D. 2744 | 2745 |

2746 |
2747 | 2748 | ###### 69. What's the output? 2749 | 2750 | ```javascript 2751 | const keyWords = "hello world"; 2752 | 2753 | const entries = keyWords.split(" "); 2754 | 2755 | const collections = []; 2756 | 2757 | entries.forEach((entry, index) => { 2758 | collections.push([entry, index]); 2759 | }); 2760 | 2761 | const objectResult = Object.fromEntries(collections); 2762 | 2763 | const { world } = objectResult; 2764 | 2765 | console.log(world); 2766 | ``` 2767 | 2768 | - A: 0 2769 | - B: true 2770 | - C: 1 2771 | - D: "hello" 2772 | 2773 |
Answer 2774 |

2775 | 2776 | #### Answer: C 2777 | 2778 | The code snippet above is not challenging for those who have had decent experience working with ES6 I suppose. First we turn `keywords` into an array using `split()` function. Then we create a variable named `collection`, which initially is an empty array. 2779 | 2780 | Take a closer look at the `forEach` function, which allows us to run a for loop through the whole array `entries`, you might realize that `push([entry, index]);` add an array to `collections` rather than an element. 2781 | 2782 | The next step is by taking advantage of `Object.fromEntries()` that converts an array with at least two elements (the form of key-value) to an object. This built-in method is the reversing version of `Object.entries()`, which extracts key and value from an object to an array. 2783 | 2784 | `const { world } = objectResult;` is nothing special as we unpack the object using destructing object technique supported since ES6. As the object `objectResult` has `hello` and `world` with two respective values 0 and 1, we get 1 when printing out `world`, so the correct answer is C. 2785 | 2786 |

2787 |
2788 | 2789 | ###### 70. What's the output? 2790 | 2791 | ```javascript 2792 | const target = { 2793 | domainname: "hoccoban.com", 2794 | author: "vuong", 2795 | }; 2796 | 2797 | const handler = { 2798 | get: function (thetarget, prop, receiver) { 2799 | if (prop === "domainname") { 2800 | return thetarget.author.length; 2801 | } else { 2802 | return thetarget.domainname.length; 2803 | } 2804 | }, 2805 | }; 2806 | 2807 | const proxyObject = new Proxy(target, handler); 2808 | 2809 | console.log(proxyObject.domainname > proxyObject.author); 2810 | ``` 2811 | 2812 | - A: true 2813 | - B: false 2814 | - C: 12 2815 | - D: 5 2816 | 2817 |
Answer 2818 |

2819 | 2820 | #### Answer: B 2821 | 2822 | We have implemented a basic use case of `Proxy` in the code snippet above. Each `proxyObject` object has two parameters (`target` and `handler`). `handler` is also an object. 2823 | 2824 | Apart from `get()` as you might see, `handler` also has a handful of other methods such as `set`, `defineProperty()`, `has()` and so forth. Sometimes, people may say a `method is a trap` of a proxy object. 2825 | 2826 | Back to the code above, the `get` method allows us to modify how the proxy object will display the value of the original object. `thetarget` is the original object, and `prop` is the property of that object as you might guess. You might choose another name in the `get` function if you want when creating your handler. 2827 | 2828 | The `handler` above calculates the length of the string value of the two properties. Based on the flow of `if - else` code, it swaps the returned value. 2829 | 2830 | So `proxyObject.domainname` now should be understood as `target.author.length` which means 5 and `proxyObject.author` means `target.domainname.length` which gives us 12. So the output is `false`. The correct answer is B. 2831 | 2832 | If you do the same thing with the original, it should be something like `console.log(target.domainname.length > target.author.length)` which returns `true`. 2833 | 2834 | I believe that `Proxy` is worth to have a closer look. If that is the case, no place is better than MDN. So have a go at: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy 2835 | 2836 |

2837 |
2838 | 2839 | ###### 71. What's the output? 2840 | 2841 | ```javascript 2842 | const promise1 = new Promise((resolve, reject) => { 2843 | setTimeout(() => resolve("hello"), 5000); 2844 | }); 2845 | 2846 | const promise2 = new Promise((resolve, reject) => { 2847 | setTimeout(() => resolve("world"), 4000); 2848 | }); 2849 | 2850 | (async () => { 2851 | console.time("timeleap"); 2852 | 2853 | const p1 = await promise1; 2854 | 2855 | const p2 = await promise2; 2856 | 2857 | console.log(`${p1} ${p2}`); 2858 | 2859 | console.timeEnd("timeleap"); 2860 | })(); 2861 | ``` 2862 | 2863 | - A: Promise { } - "hello world" - timeleap: ~ 5000 ms 2864 | - B: Promise { } - "hello world" - timeleap: ~ 9000 ms 2865 | - C: Promise { } - "hello world" - timeleap: ~ 4000 ms 2866 | - D: Promise { } - "hello world" - timeleap: ~ 1000 ms 2867 | 2868 |
Answer 2869 |

2870 | 2871 | #### Answer: A 2872 | 2873 | We have already had a couple of questions regarding asynchronous code in general and handling the data flow with promise in particular. If you understand how JS works, I am sure that the code challenge above is not difficult. 2874 | 2875 | We have two promises; each takes 5 or 4 seconds to complete the code and returns "hello" (in `promise1`) and "world" (in `promise2`) in the `resolve` methods, respectively. 2876 | 2877 | Then we take advantage of the `async` function to chain the two promises to get the result we want. As `async` function returns a `promise` so to get the returned value from `async` function, we have to use `then()` method. As we do not do that here, then we get `Promise { }`. 2878 | 2879 | The question is, does `p2` have to wait and only run after `p1` complete? It turns out that it does not. Both `p1` and `p2` run simultaneously in the task queue thanks to web API or nodejs API (the environments by which JavaScript engine runs). So it will not take 9 seconds to finish the code but solely around 5. It means `promise1` takes 5 seconds to complete and at the same time, `promise2` reaches the bottom within only 4 seconds. 2880 | 2881 | That is why A is the correct answer. 2882 | 2883 | Updated: What happens if `promise2` takes 6 seconds instead of 4 ? Well, as `promise2` runs almost at the same time with `promise1`, it will only take 1 second after the `promise1` completes. So in total, it takes approximately 6 seconds. 2884 | 2885 |

2886 |
2887 | 2888 | ###### 72. What's the output? 2889 | 2890 | ```javascript 2891 | const promise1 = () => { 2892 | return new Promise((resolve, reject) => { 2893 | setTimeout(() => resolve("hello"), 5000); 2894 | }); 2895 | }; 2896 | 2897 | const promise2 = () => { 2898 | return new Promise((resolve, reject) => { 2899 | setTimeout(() => resolve("world"), 4000); 2900 | }); 2901 | }; 2902 | 2903 | (async () => { 2904 | console.time("timeleap"); 2905 | 2906 | const p1 = await promise1(); 2907 | 2908 | const p2 = await promise2(); 2909 | 2910 | console.log(`${p1} ${p2}`); 2911 | 2912 | console.timeEnd("timeleap"); 2913 | })(); 2914 | ``` 2915 | 2916 | - A: Promise { } - "hello world" - timeleap: ~ 5000 ms 2917 | - B: Promise { } - "hello world" - timeleap: ~ 9000 ms 2918 | - C: Promise { } - "hello world" - timeleap: ~ 4000 ms 2919 | - D: Promise { } - "hello world" - timeleap: ~ 1000 ms 2920 | 2921 |
Answer 2922 |

2923 | 2924 | #### Answer: B 2925 | 2926 | The 72nd challenge is almost identical to the 71st. Please take a closer look. 2927 | 2928 | The difference lies in the way we declare a promise. In question 71st, we use two constants, and both return promise, but in question 72, we declare functions and each returns a promise. 2929 | 2930 | If you run the code, you might be surprised with the result as it takes around 9 seconds to complete the code in place of 5 seconds as in the previous question. 2931 | 2932 | It means that `const p1 = await promise1;` and `const p1 = await promise1();` are different as the latter (a function) might block the callstack and `const p2 = await promise2();` can only be called after the `p1` completes. The two do not run in parallel as the two promises in the previous question. 2933 | 2934 | As it takes 9 seconds to finish, B is the correct answer. 2935 | 2936 |

2937 |
2938 | 2939 | ###### 73. What's the output? 2940 | 2941 | ```javascript 2942 | let history = { 2943 | year: 2021, 2944 | getYear: function () { 2945 | console.log(this.year); 2946 | }, 2947 | }; 2948 | 2949 | setTimeout(history.getYear, 0); 2950 | setTimeout(history.getYear.bind(history), 10); 2951 | 2952 | const { year, getYear } = history; 2953 | getYear(); 2954 | ``` 2955 | 2956 | - A: undefined - undefined - 2021 2957 | - B: undefined - 2021 - 2021 2958 | - C: 2021 - undefined - 2021 2959 | - D: 2021 - 2021 - 2021 2960 | 2961 |
Answer 2962 |

2963 | 2964 | #### Answer: A 2965 | 2966 | We have three outputs on the code above. First, we have a simple object with one property and one method. Noted that the method point to the property `year` using `this` keyword. The problem now happens when we attempt to extract data from the object. 2967 | 2968 | Be aware of the `setTimeout` method, which will create a separated context that is different from the original object's context. Even though in `setTimeout(history.getYear, 0);` we have explicitly called the object `history`, setTimeout will still execute the function `history.getYear` with`this` pointing to the global object. So it returns `undefined.` 2969 | 2970 | `getYear();` is extracted from the object we have defined in the beginning. But as `this` is out of the original context when executing the function, it returns `undefined`. This code is called last, but the output is displayed first on the console window as it is a synchronous code. 2971 | 2972 | `setTimeout(history.getYear.bind(history), 10);` runs last and will give us 2021 as it is bound to the object `history`. Finally, we get `undefined - undefined - 2021,` and A is the correct answer. 2973 | 2974 |

2975 |
2976 | 2977 | ###### 74. What's the output? 2978 | 2979 | ```javascript 2980 | class handleCovid { 2981 | constructor(start) { 2982 | this.start = start; 2983 | } 2984 | 2985 | calculate(someValue) { 2986 | this.start = this.start + someValue; 2987 | return this.start; 2988 | } 2989 | 2990 | vaccine() { 2991 | ++this.start; 2992 | return this; 2993 | } 2994 | 2995 | delaying() { 2996 | ++this.start; 2997 | return this; 2998 | } 2999 | 3000 | static getFinal(result) { 3001 | return result * 2; 3002 | } 3003 | } 3004 | 3005 | const now = new handleCovid(2019); 3006 | 3007 | console.log(handleCovid.getFinal(now.vaccine().delaying().calculate(2020))); 3008 | ``` 3009 | 3010 | - A: 2019 3011 | - B: 8082 3012 | - C: 8080 3013 | - D: 8084 3014 | 3015 |
Answer 3016 |

3017 | 3018 | #### Answer: B 3019 | 3020 | The code snippet above is ugly and sounds complicated at first. Yet, you might encounter a situation when some good "take away" messages might be given. The flow of the code is not hard to understand, I suppose. 3021 | 3022 | First, a function in JavaScript can accept another function as its parameter. With regard to the `static` keyword, it means we can directly call a static method in the form of `className.staticmethod` without invoking the object created by the normal way `new ClassName`. 3023 | 3024 | Besides, you might want to have a look at how we chain more than one method together. That is possible if these methods `return this`. 3025 | 3026 | Now let break it down: 3027 | 3028 | - `calculate(2020)` --> 2019 + 2020 = 4039; 3029 | - `delaying().calculate(2020)` --> 4040; 3030 | - `now.vaccine().delaying().calculate(2020)` --> 4041; 3031 | - `handleCovid.getFinal(now.vaccine().delaying().calculate(2020)` --> 4041 \* 2 = 8082; 3032 | 3033 | So the correct answer is B. 3034 | 3035 |

3036 |
3037 | 3038 | ###### 75. What's the output? 3039 | 3040 | ```javascript 3041 | function HappyNewYear() { 3042 | return "hello"; 3043 | } 3044 | 3045 | const year2021 = new HappyNewYear(); 3046 | year2021.__proto__.greeting = "happy"; 3047 | HappyNewYear.prototype.say = "new year"; 3048 | 3049 | console.log(year2021.__proto__ === HappyNewYear.prototype); 3050 | console.log(Object.getPrototypeOf(year2021) === HappyNewYear.prototype); 3051 | console.log(Reflect.getPrototypeOf(year2021) === HappyNewYear.prototype); 3052 | 3053 | console.log(year2021.__proto__ === Object.prototype); 3054 | console.log(year2021 instanceof HappyNewYear); 3055 | console.log(year2021 instanceof Object); 3056 | 3057 | const thisyear = new HappyNewYear(); 3058 | console.log(`${thisyear.greeting} ${thisyear.say}`); 3059 | ``` 3060 | 3061 | - A: true - true - true - false - true - false - "happy new year" 3062 | - B: true - true - true - false - false - true - "happy new year" 3063 | - C: true - true - true - true - true - true - "happy new year" 3064 | - D: true - true - true - false - true - true - "happy new year" 3065 | 3066 |
Answer 3067 |

3068 | 3069 | #### Answer: D 3070 | 3071 | The code snippet above helps us revise the concept of `prototype` in JavaScript with two essential keywords: `__proto__` and `FunctionName.prototype`. I believe that the code `console.log(year2021.__proto__ === HappyNewYear.prototype);` is the key to understand the difference between the two. So, in short, every single object in JavaScript has a built-in property `__proto__` that gives us an overview of the built-in (internal) [[Prototype]]. They are the things (property and method) the object inherits from the "parent" function constructor or class). 3072 | 3073 | For example, if you declare a literal object such as `const a = {}` then `a.__proto__ === Object.prototype` returns `true` because `a` inherits the prototype from the "parent" `Object`. However, if an object is created using function constructor then the "parent" prototype is function constructor itself instead of the `Object`. So while `console.log(year2021.__proto__ === HappyNewYear.prototype);` returns `true`, `console.log(year2021.__proto__ === Object.prototype);` gives us `false`. 3074 | 3075 | Be aware of `Object.getPrototypeOf (object)` and `Reflect.getPrototypeOf(object)`. The two are recommended to use as `__proto__` is being deprecated. 3076 | 3077 | You might want to read more about `__proto__` at MDN https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/proto 3078 | 3079 | The correct answer is D, and btw "happy new year"! 3080 | 3081 |

3082 |
3083 | 3084 | ###### 76. What's the output? 3085 | 3086 | ```javascript 3087 | const address = { 3088 | name: "hoccoban.com", 3089 | author: "Vuong Nguyen", 3090 | }; 3091 | 3092 | const key = Reflect.has(address, "author") 3093 | ? Reflect.ownKeys(address)[0] 3094 | : "hello"; 3095 | 3096 | Reflect.set(address, "language", "JavaScript"); 3097 | 3098 | const totalKeys = Reflect.ownKeys(address).length; 3099 | 3100 | const name = Reflect.get(address, key).length; 3101 | 3102 | const language = Reflect.get(address, "language").length; 3103 | 3104 | console.log(totalKeys + name + language); 3105 | ``` 3106 | 3107 | - A: 22 3108 | - B: 10 3109 | - C: 20 3110 | - D: 25 3111 | 3112 |
Answer 3113 |

3114 | 3115 | The correct answer is D. Why? Now let break it down: 3116 | 3117 | - `Reflect.has(address, 'author')` gives us `true` given that the object `address` has the key `author`. Simple as it is. So the value of the variable `key` is now `Reflect.ownKeys(address)[0]`, which in fact is the key `name`. 3118 | 3119 | - `Reflect.set(address, 'language', 'JavaScript');` set another key-value to the object `address`. 3120 | 3121 | - `Reflect.ownKeys(address).length;` gives us 3 because now it has three keys, so `totalKeys` is now 3. 3122 | 3123 | - `Reflect.get(address, key).length;` gives us the length of the string `hoccoban.com` which is 12. 3124 | 3125 | - `Reflect.get(address, 'language').length` is the length of the string `JavaScript`, which is 10. 3126 | 3127 | - The final answer is 3 + 12 + 10 = 25. 3128 | 3129 | #### Answer: D 3130 | 3131 |

3132 |
3133 | 3134 | ###### 77. What's the output? 3135 | 3136 | ```javascript 3137 | const myModule = (function () { 3138 | const covidYear = 2019; 3139 | 3140 | const year = 2021; 3141 | 3142 | function getYear() { 3143 | return year; 3144 | } 3145 | 3146 | function getCovidYear() { 3147 | return covidYear; 3148 | } 3149 | 3150 | function exposeYear() { 3151 | return getYear(); 3152 | } 3153 | 3154 | function exposeCovidYear() { 3155 | return getCovidYear(); 3156 | } 3157 | 3158 | return { 3159 | nothing: undefined ?? null ?? null ?? undefined, 3160 | exposeYear, 3161 | exposeCovidYear, 3162 | }; 3163 | })(); 3164 | 3165 | const result = 3166 | myModule.nothing ?? myModule.exposeYear() + myModule.exposeCovidYear(); 3167 | 3168 | console.log(result); 3169 | ``` 3170 | 3171 | - A: 2021 3172 | - B: 2019 3173 | - C: 4040 3174 | - D: undefined 3175 | 3176 |
Answer 3177 |

3178 | 3179 | The challenge above will help you revise the `revealing pattern` and thanks to it you can declare a private variable in JavaScript. Note that we can now declare a `private` property in a class in modern JavaScript, so the above way of writing a private variable seems old-fashioned. 3180 | 3181 | First, we have an IIFE function - immediately invoked function expressions. There are two variables and two functions as well. However, in the `return`, there are three key-values. We can not directly access the two variables `covidYear` and `year` except for using some already-built functions inside the IIFE. 3182 | 3183 | If you feel the keyword `??` is odd, then you might want to have a look at the latest syntax supported in modern JavaScript called "Nullish Coalescing Operator". It means, if the left element is either `undefined` or `null`, the value of the right element will be assigned. 3184 | 3185 | In short, we have `myModule.exposeYear()` (2021) and `myModule.exposeCovidYear()` (2019). In total, the final result is 4040. So the correct answer is C. 3186 | 3187 | #### Answer: C 3188 | 3189 |

3190 |
3191 | 3192 | ###### 78. What's the output? 3193 | 3194 | ```javascript 3195 | class HocCoban { 3196 | constructor(address) { 3197 | this.address = address; 3198 | this.youtube = ""; 3199 | } 3200 | get getAddress() { 3201 | return this.address; 3202 | } 3203 | 3204 | set setYoutube(channel) { 3205 | this.youtube = channel; 3206 | } 3207 | 3208 | getYoutube() { 3209 | return this.youtube.length; 3210 | } 3211 | } 3212 | 3213 | const web = new HocCoban("hoccoban.com"); 3214 | 3215 | web.setYoutube = "youtube.com/hoccoban"; 3216 | 3217 | console.log(web.getAddress); 3218 | 3219 | console.log(web.youtube); 3220 | 3221 | console.log(web.getYoutube()); 3222 | ``` 3223 | 3224 | - A: "hoccoban.com" - "youtube.com/hoccoban" - 20 3225 | - B: "hoccoban.com" - function() - 20 3226 | - C: function() - "youtube.com/hoccoban" - 20 3227 | - D: function() - function() - 20 3228 | 3229 |
Answer 3230 |

3231 | 3232 | `set` and `get` are commonly called setter and getter. When declaring a method in a class and putting the keyword `set` or `get` before it, you can then call them without using `parenthesis - ()`. Put another way, when using `get` and `set`, you can directly get or set the value of/for the properties. Somehow it might be convenient in some cases. 3233 | 3234 | Be aware of the methods declared with a `getter` as we just need to call the method as we call a property (without using parenthesis). 3235 | 3236 | If you know how a traditional method works in JavaScript, then the code challenge above is not difficult, I suppose. The answer is A. 3237 | 3238 | #### Answer: A 3239 | 3240 |

3241 |
3242 | 3243 | ###### 79. What's the output? 3244 | 3245 | ```javascript 3246 | const result = ["ronaldo", "messi", "neymar", "Ronaldo", "LuKaKUUUU"].sort(); 3247 | 3248 | console.log(result); 3249 | ``` 3250 | 3251 | - A: ["LuKaKUUUU", "Ronaldo", "messi", "neymar", "ronaldo"] 3252 | - B: ["LuKaKUUUU", "messi", "neymar", "Ronaldo","ronaldo"] 3253 | - C: ["LuKaKUUUU", "messi", "neymar", "ronaldo", "Ronaldo"] 3254 | - D: ["messi", "neymar", "ronaldo", "Ronaldo", "LuKaKUUUU"] 3255 | 3256 |
Answer 3257 |

3258 | 3259 | In JavaScript, the built-in `sort()` method sorts the elements of an array. It returns a sorted array in ascending order. Note that each element will be converted to strings and then compared according to the sequences of UTF-16 code unit values. What does it mean? 3260 | 3261 | It means, "banana" < "cherry" or 80 < 9 (because "80" < "9" in the Unicode order). 3262 | 3263 | If you run the following code `const result = [9, 11, 89].sort();`, the constant `result` will be sorted as `[11, 8, 9]` rather than `[9, 11, 89]` because the engine will convert the number value to string. 3264 | 3265 | The following codes might give you a hint about the relationship between character and number. Ultimately, as the computer can only understand 0 and 1, all characters and even decimal numbers are then converted to 1 and 0. `charCodeAt()` gives us the decimal value of any string evaluated. 3266 | 3267 | `console.log("LuKaKUUUU".charCodeAt(0))` or `console.log("LuKaKUUUU".charCodeAt())` ==> 76 3268 | `console.log("Ronaldo".charCodeAt(0))` or `console.log("Ronaldo".charCodeAt())` ==> 82 3269 | `console.log("messi".charCodeAt(0))` or `console.log("messi".charCodeAt())` ==> 109 3270 | `console.log("neymar".charCodeAt(0))` or `console.log("neymar".charCodeAt())` ==> 110 3271 | `console.log("ronaldo".charCodeAt(0))` or `console.log("ronaldo".charCodeAt())` ==> 114 3272 | `console.log("9".charCodeAt())` or `console.log("99".charCodeAt())` ==> 57 3273 | `console.log("80".charCodeAt())` or `console.log("8".charCodeAt())` ==> 56 3274 | 3275 | Noted that if index is not a number, it defaults to 0. The answer is A. 3276 | 3277 | #### Answer: A 3278 | 3279 |

3280 |
3281 | 3282 | ###### 80. What's the output? 3283 | 3284 | ```javascript 3285 | const anArray = typeof []; 3286 | const aTypeOfNull = typeof null; 3287 | 3288 | const weirdFirst = null instanceof Object; 3289 | const weirdSecond = [] instanceof Object; 3290 | const weirdThird = [] instanceof Array; 3291 | 3292 | console.log(anArray); 3293 | console.log(aTypeOfNull); 3294 | 3295 | console.log(weirdFirst); 3296 | console.log(weirdSecond); 3297 | console.log(weirdThird); 3298 | ``` 3299 | 3300 | - A: "array" - "null" - false - true - true 3301 | - B: "array" - "object" - false - true - true 3302 | - C: "object" - "object" - false - false - true 3303 | - D: "object" - "object" - false - true - true 3304 | 3305 |
Answer 3306 |

3307 | 3308 | In the 80th challenge question, we will review some fundamental "issue" or "weird" features in JavaScript relating to the `typeof` and `instance` operators. Given that the original version of the JavaScript language was designed in just 10 days, there are a bundle of inconsistent behaviors that cannot be fixed. They are permanent features existing in the modern language. If we fix it, a lot of websites might crash. 3309 | 3310 | The above code shows us some of the weird features in JavaScript. For example, `[]` is an array but the `typeof []` gives us `object`. Note that you might take advantage of `Array.isArray([])` rather than `typeof` to examine whether a variable is an array or not. 3311 | 3312 | `typeof null;` is another weird operator as it returns `object`. However `null instanceof Object;` returns `false`. ~WhatTheHell~!!! 3313 | 3314 | Man, `[] instanceof Object;` and `[] instanceof Array;` both return `true`. How inconsistent it is. 3315 | 3316 | The answer is D. 3317 | 3318 | #### Answer: D 3319 | 3320 |

3321 |
3322 | 3323 | ###### 81. What's the output? 3324 | 3325 | ```javascript 3326 | class Dog { 3327 | speak() { 3328 | return this.say(); 3329 | } 3330 | 3331 | say() { 3332 | console.log("hello world"); 3333 | } 3334 | } 3335 | 3336 | class Cat { 3337 | speak() { 3338 | return this.say(); 3339 | } 3340 | 3341 | say() { 3342 | console.log("kia ora"); 3343 | } 3344 | } 3345 | 3346 | const animal = new Dog(); 3347 | animal.speak(); 3348 | Object.setPrototypeOf(animal, Cat.prototype); 3349 | animal.speak(); 3350 | ``` 3351 | 3352 | - A: "hello world" - undefined 3353 | - B: "kia ora" - "kia ora" 3354 | - C: "hello world" - "kia ora" 3355 | - D: "hello world" - "hello world" 3356 | 3357 |
Answer 3358 |

3359 | 3360 | The central issue/concept mentioned in the code above is the method `Object.setPrototypeOf(object, prototype)`. It is one of the features in ES6, or ECMAScript 2015. Another way to set the prototype of an object is `Object.prototype.__proto__` but the latter is controversial. 3361 | 3362 | At first, `animal.speak();` gives us "hello world" which is no surprise. Yet, in the second call, we get "kia ora" instead of "hello world". When checking the prototype with `Object.getPrototypeOf(animal)`, you might see that `Cat` is the prototype of the object `animal` rather than `Dog`. 3363 | 3364 | The answer is C. 3365 | 3366 | By the way, `kia ora` means `hello` in the Māori language. 3367 | 3368 | #### Answer: C 3369 | 3370 |

3371 |
3372 | 3373 | ###### 82. What's the output? 3374 | 3375 | ```javascript 3376 | const js = [9, 10]; 3377 | 3378 | function mutate(a, b) { 3379 | a.push(b); 3380 | } 3381 | 3382 | mutate(js, 1); 3383 | console.log(js); 3384 | ``` 3385 | 3386 | - A: [9, 10] 3387 | - B: [9, 10, 1] 3388 | - C: [1, 9, 10] 3389 | - D: ReferenceError 3390 | 3391 |
Answer 3392 |

3393 | 3394 | The code snippet might be pretty trivial if you have already obtained a solid understanding of the two different concepts: `reference` and `value.` In JavaScript, non-primitive type such as array and object does not store the value but the reference. 3395 | 3396 | Also, as the arguments in function are passed by the reference, the function `mutate` will push another element into the array `js`. Finally, the initial variable 'js' is updated with the new value `[9, 10, 1]`. 3397 | 3398 | If the variable `js` is assigned a primitive value such as string or number, no matter how the function `mutate`, it will not mutate the initial variable 'js'. However, if the variable is an object, then it will also be mutated, as in the case of an array in the code above. 3399 | 3400 | B is the correct answer. 3401 | 3402 | #### Answer: B 3403 | 3404 |

3405 |
3406 | 3407 | ###### 83. What's the output when running the code on a browser? 3408 | 3409 | ```javascript 3410 | console.log(this === window); 3411 | console.log(this === frames); 3412 | console.log(this === globalThis); 3413 | console.log(this === self); 3414 | console.log(this === global); 3415 | ``` 3416 | 3417 | - A: true - true - true - true - "ReferenceError" 3418 | - B: true - false - true - true - "ReferenceError" 3419 | - C: true - true - true - true - true 3420 | - D: true - true - "ReferenceError" - true - "ReferenceError" 3421 | 3422 |
Answer 3423 |

3424 | 3425 | The code snippet above might output different results if running on other environments than the browser. For example, there is no `self`, `window`, or `frames` on Nodejs. 3426 | 3427 | `global` plays the role of the global object in Nodejs, but that is not the case in the browser environment. In contrast, `globalThis` is available in both browser and Nodejs environments. 3428 | 3429 | The first takeaway message is that Nodejs does have `this`, `global`, and `globalThis`. Browser environment has 5 ones including `this`, `globalThis`, `window`, `frames`, and `self`. 3430 | 3431 | The second takeaway message is that Web Worker only has `self` as the global object. 3432 | 3433 | Ultimately, A is the correct answer. 3434 | 3435 | #### Answer: A 3436 | 3437 |

3438 |
3439 | 3440 | ###### 84. What's the output ? 3441 | 3442 | ```javascript 3443 | class StackHocCoBan { 3444 | constructor() { 3445 | this.stack = []; 3446 | } 3447 | 3448 | push(thing) { 3449 | return this.stack.push(thing); 3450 | } 3451 | 3452 | pop() { 3453 | return this.stack.pop(); 3454 | } 3455 | 3456 | peek() { 3457 | return this.stack[this.length - 1]; 3458 | } 3459 | 3460 | get length() { 3461 | return this.stack.length; 3462 | } 3463 | 3464 | isEmpty() { 3465 | return this.length === 0; 3466 | } 3467 | } 3468 | 3469 | const firstThing = new StackHocCoBan(); 3470 | 3471 | firstThing.push(firstThing.length); 3472 | firstThing.push(firstThing.length); 3473 | !firstThing.isEmpty() ? firstThing.push(firstThing.length) : firstThing.length; 3474 | firstThing.pop(); 3475 | 3476 | console.log(firstThing.peek() + firstThing.length + firstThing.pop()); 3477 | ``` 3478 | 3479 | - A: 3 3480 | - B: 4 3481 | - C: 5 3482 | - D: 6 3483 | 3484 |
Answer 3485 |

3486 | 3487 | The code challenge above is a bit lengthy, frankly. But it might practically help you to revise the concept of `stack` implemented in JavaScript. Such a concept is quite crucial when it comes to the algorithm, so to say. It appears that `stack` and `queue` are blood brothers, and as a developer, you are always advised to master these concepts along with array, linked list, tree, graphs, and so on. 3488 | 3489 | In my opinion, both `stack` and `queue` are simply arrays, but they are exclusively built to serve some particular jobs with strict requirements. You might see `pop()` or `push()` in the code above are standard native methods we often use when working with the array. 3490 | 3491 | So now `firstThing` is an object initiated by the class `StackHocCoBan`. As the class's construct initially triggers an empty array ` this.stack = [];`, first the code `firstThing.push(firstThing.length);` will actually push the number 0 into the array given that `firstThing.length` returns 0 as the stack, at the beginning` is empty. 3492 | 3493 | Then `firstThing.push(firstThing.length);` (the second one) pushes number 1 to the stack as we have already had one item (the number 0). 3494 | 3495 | `firstThing.isEmpty()` returns `false` because we have two things in the stack. Yet, be causious with "!" before it. As we write `!firstThing.isEmpty()`, the code with call `firstThing.push(firstThing.length)` rather than `firstThing.length;`. It is a simply short-hand of `if-else`. 3496 | 3497 | So, the stack is pushed the number 2 because `firstThing.length` returns 2. So now the stack is as [0, 1, 2], beautiful, right? 3498 | 3499 | `firstThing.pop()` will eliminate the number 2 and the stack is now [0, 1]. 3500 | 3501 | The last line of the code above is `firstThing.peek()` (1) + `firstThing.length` (2) + `firstThing.pop()` (1). 3502 | 3503 | So B is the correct answer. 3504 | 3505 | #### Answer: B 3506 | 3507 |

3508 |
3509 | 3510 | ###### 85. What's the output ? 3511 | 3512 | ```javascript 3513 | class QueueHocCoBan { 3514 | constructor() { 3515 | this.queue = []; 3516 | } 3517 | 3518 | enqueue(item) { 3519 | return this.queue.unshift(item); 3520 | } 3521 | 3522 | dequeue() { 3523 | return this.queue.pop(); 3524 | } 3525 | 3526 | peek() { 3527 | return this.queue[this.length - 1]; 3528 | } 3529 | 3530 | get length() { 3531 | return this.queue.length; 3532 | } 3533 | 3534 | isEmpty() { 3535 | return this.queue.length === 0; 3536 | } 3537 | } 3538 | 3539 | const items = new QueueHocCoBan(); 3540 | 3541 | items.enqueue("constructor"); 3542 | items.enqueue("QueueHocCoBan"); 3543 | items.enqueue("hoccoban.com"); 3544 | 3545 | const item = items.peek().length - items.length; 3546 | 3547 | console.log(item); 3548 | ``` 3549 | 3550 | - A: 6 3551 | - B: 7 3552 | - C: 8 3553 | - D: 9 3554 | 3555 |
Answer 3556 |

3557 | 3558 | Following up the question 85th, we now pay the attention to another important concepts - `queue` - which is a bit different from `stack`. While `stack` leverages two native array methods `push()` (for adding new item) and `pop()`(for extracting new item), `queue` utilises `unshift()` (for adding new item) and `pop()` (for extracting new item). In essense, both `stack` and `queue` are array and thus the difference between them, IMO, lays in the way `push()` and `unshift()` are implemented for adding new item. While `push()` adds a new item/element at the end/tail of the array, `unshift()` adds the new one to the top/head of the array itself. 3559 | 3560 | First, the object `items` will add three new elements into the array (initiated by the constructor) at the top one by one, thanks to the method `enqueue`. The array will look like this ["hoccoban.com", "QueueHocCoBan", "constructor"]; 3561 | 3562 | Now `items.peek()` gives us "constructor" and thus `items.peek().length` returns 11. `items.length` simply returns 3 and so the final result will be 8. 3563 | 3564 | So C is the correct answer. 3565 | 3566 | By way of summarisation, using `queue`, we can only take out the first element (also the tail of the array) with the method `dequeue().` You might need to find another way to extract other elements of the queue. 3567 | 3568 | #### Answer: C 3569 | 3570 |

3571 |
3572 | 3573 | ###### 86. What's the output ? 3574 | 3575 | ```javascript 3576 | const domains = new Map(); 3577 | 3578 | domains.set("site", "hoccoban.com"); 3579 | domains.set("youtube", "youtube.com/hoccoban"); 3580 | 3581 | const keys = domains.keys(); 3582 | const values = domains.values(); 3583 | 3584 | let result = domains.has("hoccoban.com") 3585 | ? values.next().value 3586 | : keys.next().value; 3587 | 3588 | console.log(result); 3589 | ``` 3590 | 3591 | - A: "site" 3592 | - B: "hoccoban.com" 3593 | - C: "youtube" 3594 | - D: "youtube.com/hoccoban" 3595 | 3596 |
Answer 3597 |

3598 | 3599 | There are two ways hash tables are implemented in JavaScript: object and Map(). Hash tables are data structures created to store information in the form of key-value. 3600 | 3601 | While the native object defined as {} is trivial for a JavaScript developer, a new way to design a hash table has been recently added into the language. When writing `const domains = new Map();`, we have declared an object with a couple of different features as opposed to the veteran one declared in the form of `{}` or `new Object` we all know. 3602 | 3603 | You are advised to take advantage of the built-in methods such as `set()`, `get()`, `has()` or `delete()` among others to manipulate the map object. 3604 | 3605 | Note that a map object can be iterated using `for of`. You might need to use `next().value` to extract the raw information written. At this point, you might want to revisit `function generator` to see why we need to do that. 3606 | 3607 | Both `keys()` and `values()` are native methods of the class `Map`. You might see that they works on a map object as in a normal object. Back to the code snippet above, `let result = domains.has("hoccoban.com") ? values.next().value: keys.next().value` returns `keys.next().value` given that `domains.has("hoccoban.com")` returns `false`. 3608 | 3609 | So `console.log(result)` gives us "site", so A is the correct answer. 3610 | 3611 | Note that if you want to extract "youtube", you must run `keys.next().value` twice. 3612 | 3613 | #### Answer: A 3614 | 3615 |

3616 |
3617 | 3618 | ###### 87. What's the output ? 3619 | 3620 | ```javascript 3621 | function inner(flag) { 3622 | hello = 10; 3623 | if (flag) { 3624 | return ++hello; 3625 | } 3626 | return --hello; 3627 | } 3628 | 3629 | var hello = 12; 3630 | inner(hello > 11 ? false : true); 3631 | console.log(hello); 3632 | ``` 3633 | 3634 | - A: 9 3635 | - B: 10 3636 | - C: 11 3637 | - D: 12 3638 | 3639 |
Answer 3640 |

3641 | 3642 | As a variable in JavaScript can be declared without any functional keyword such as var, let, or const standing before the variable name, as seen on the code above, this challenge sounds a bit odd as now developers tend to use `const` or `let` everywhere. What happened when we do that? The variable will have a global scope no matter where it has been written initially. So first, the variable `hello` will be accessed anywhere outside of the function scope whenever (after to be exact) the function inner has been executed. 3643 | 3644 | Then we redeclare the `hello` variable with a different value. 3645 | 3646 | The code `inner(hello>11? false: true)` is translated to `inner(false)`, so the variable `hello` declared inside this function is mutated to 9. 3647 | 3648 | As `hello` is now 9 instead of 12, A is the correct answer. 3649 | 3650 | #### Answer: A 3651 | 3652 |

3653 |
3654 | 3655 | ###### 88. What's the output ? 3656 | 3657 | ```javascript 3658 | const collections = ["a", [123], true, "c", { abc: "hello world" }]; 3659 | const iterator = collections.values(); 3660 | 3661 | const a = iterator.next().value.length; 3662 | const b = iterator.next().value.length; 3663 | const c = iterator.next().value.toString().length; 3664 | const d = iterator.next().value.length; 3665 | const e = Object.values(iterator.next().value)[Number(a > b)].length; 3666 | 3667 | console.log(a + b + c + d + e); 3668 | ``` 3669 | 3670 | - A: 12 3671 | - B: 14 3672 | - C: 16 3673 | - D: 18 3674 | 3675 |
Answer 3676 |

3677 | 3678 | The code snippet above is frankly tedious as it does not solve any big problem but is still written in a very cryptic manner, honestly. I want you to pay a bit more attention to the native function to manipulate array `values()`. For your information, I also use `Object.values()` so that you can somehow make a comparison between the two by yourself. 3679 | 3680 | In the beginning, we have a very simple array packed with different types of data such as boolean, string, array and object. The code `collections.values();` returns an iterator, so you can not simply access to each element as an usual array. You might run a `for of` loop here to render all of the elements in this iterator. By doing that, the way iterator works is likely a typical array. 3681 | 3682 | So how do we access a single element in this iterator? We need to use `next().value`. Each time we call it, the iterator will render the value, one by one, starting with the first element. 3683 | 3684 | It means `const a = iterator.next().value.length;` returns 1. So a is 1. So does b. C is a bit different and we have 4 here as `true`, a boolean, is converted to a string. d is 1. So 3685 | 3686 | The code in e is not fascinating, I suppose. `Object.values` gives us an array of value defined in the object `{ abc: "hello world" }`. `[Number(a > b)]` give us [0]. So e is simply the length of the string "hello world", which is 11. 3687 | 3688 | Finally, in the console we have 1 + 1 + 4 + 1 + 11 = 18. So D is the correct answer. 3689 | 3690 | #### Answer: D 3691 | 3692 |

3693 |
3694 | 3695 | ###### 89. What's the output ? 3696 | 3697 | ```javascript 3698 | const matrix = [ 3699 | [1, 2, 3], 3700 | [4, 5, 6], 3701 | [7, 8, 9], 3702 | ]; 3703 | 3704 | function matrixHandle(m) { 3705 | let total = arguments[0][0][0]; 3706 | let length = m.length; 3707 | for (let i = 0; i < length; i++) { 3708 | for (let j = 0; j < m[i].length; j++) { 3709 | total += m[i][j]; 3710 | } 3711 | } 3712 | return total; 3713 | } 3714 | 3715 | console.log(matrixHandle(matrix)); 3716 | ``` 3717 | 3718 | - A: 44 3719 | - B: 45 3720 | - C: 46 3721 | - D: 47 3722 | 3723 |
Answer 3724 |

3725 | You can easily create a two-dimensional array by nesting an array inside the parent one as the variable `matrix` above. To render all of the elements in the matrix, we implement a simple code with two for-loop functions which are nested. 3726 | 3727 | `arguments[0][0][0];` gives us 1 because `arguments` has wrapped the variable `matrix` in an array. Note that `arguments` is a Array-like. 3728 | 3729 | So the variable `total` at first is 1, and then the final value cumulated by looping through the matrix is 46. 3730 | 3731 | In short, we have 1 + 1 + 2 + 3 + 4 + 5 + 6 + 7+ 8 + 9 = 46. So C is the correct answer. 3732 | 3733 | #### Answer: C 3734 | 3735 |

3736 |
3737 | 3738 | ###### 90. What's the output ? 3739 | 3740 | ```javascript 3741 | const container1 = { 3742 | stack: "Docker", 3743 | getStack: function () { 3744 | return this.stack; 3745 | }, 3746 | }; 3747 | const a = container1.getStack(); 3748 | 3749 | const container2 = { 3750 | stack: "Kubernetes", 3751 | getStack: () => this.stack, 3752 | }; 3753 | const b = container2.getStack(); 3754 | 3755 | const container3 = { 3756 | architect: "microservice", 3757 | getStack: function () { 3758 | const stack = ["K8s"]; 3759 | return stack.map(function (element) { 3760 | return `${element} - ${this.architect}`; 3761 | }); 3762 | }, 3763 | }; 3764 | const c = container3.getStack(); 3765 | 3766 | const container4 = { 3767 | architect: "microservice", 3768 | getStack: function () { 3769 | const stack = ["K8s"]; 3770 | return stack.map((element) => `${element} - ${this.architect}`); 3771 | }, 3772 | }; 3773 | const d = container4.getStack(); 3774 | 3775 | console.log(`${a} -> ${b} -> ${c} -> ${d}`); 3776 | ``` 3777 | 3778 | - A: "Docker -> Kubernetes -> K8s - undefined -> K8s - microservice" 3779 | - B: "Docker -> Kubernetes -> K8s - microservice -> K8s - microservice" 3780 | - C: "Docker -> undefined -> K8s - microservice -> K8s - undefined" 3781 | - D: "Docker -> undefined -> K8s - undefined -> K8s - microservice" 3782 | 3783 |
Answer 3784 |

3785 | The code above might help you revise how the arrow function works in different contexts, especially when dealing with the keyword `this` in JavaScript. There are two crucial takeaway messages you might need to keep in mind when using a function, as follows: 3786 | 3787 | - First: The arrow function does not create a new `this` binding when you use them. It inherits from the parent one(environment) when it is defined. 3788 | 3789 | - Second: The keyword `this` could be problematic when it is called in a callback function. For example when implementing `setTimeout`, `setInterval` or `map`, `filter`, `reduce` or `some`, `every` among others, you will need to pass a callback function. Given that the callback function changes the context, `this` might therefore change to `global` object and no longer point to the parent object. 3790 | 3791 | We have 4 objects in the snippet above. Each has a simple property and a trivial method. `a` returns `docker` because `this.stack` exactly points to the object declared `container1`. However, `b` returns `undefined` because `this` in the arrow function points to the global one rather than `container2`. Why? As we mentioned above, the arrow function does not create a context for itself, so `container2.getStack()` is still bound to the global object. `this.stack` becomes `undefined` as a result. 3792 | 3793 | Next `c` gives us `K8s - undefined` because `this` is called in the callback function when we use `map`. A new context is now created by the function `map`, so `this` will not point to the object `container3`. The callback function implemented with `map` or `filter` always creates a new context so that `this` changes. 3794 | 3795 | We get `K8s - microservice"` in `d` because the arrow function helps us fix the problem caused by switching context as in the object `container3`. Here are some lessons learned when dealing with context, nested functions (or implementing callback function): 3796 | 3797 | - Use normal function rather than arrow function when you write a method inside an object in which the method does not have a nested function(method) or callback one. Arrow function is not recommended when creating object prototypes, classes along with object literals as well. 3798 | 3799 | - Use the arrow function when you want to access to `this`, especially in the case of nested method (function) or when using callback function. Otherwise, `this` will no longer point to the object in these cases (nested method or using callback function with map, filter). There are two other techniques (old-fashion ones) to fix that. 3800 | 3801 | - There are 3 ways to fix `this` issue relating to the nested method or callback function: using arrow function as mentioned above, use `self = this` technique or explicitly binding with `call`, `bind` or `apply` method. 3802 | 3803 | #### Answer: D 3804 | 3805 |

3806 |
3807 | 3808 | ###### 91. What's the output ? 3809 | 3810 | ```javascript 3811 | class Angular { 3812 | vendor = "Google"; 3813 | lang = "TypeScript"; 3814 | overview() { 3815 | let report = []; 3816 | report.push(this.lang); 3817 | report = report.map(function (e) { 3818 | return e.length + this.vendor.length; 3819 | }); 3820 | 3821 | return report; 3822 | } 3823 | } 3824 | 3825 | const me = new Angular(); 3826 | 3827 | console.log(me.overview()); 3828 | ``` 3829 | 3830 | - A: 16 3831 | - B: 106 3832 | - C: NaN 3833 | - D: TypeError 3834 | 3835 |
Answer 3836 |

3837 | 3838 | The code snippet above might help you revise the concept of context in conjunction with the way `this` is treated in JavaScript. In short, if you implement a callback function for the `map` method (or in another case: nested function), then you might need to pay attention to `this` binding. 3839 | 3840 | While `report.push(this.lang);` works pretty well as `this` points to the property declared within the class `Angular`, the line `return e.length + this.vendor.length;` does not work as `this` no longer points to `vendor` we have already declared as a property in the class. The `map` function creates a new context here. As `vendor` is undefined inside the callback of the `map` function, we get `TypeError` in the console. So D is the correct answer. 3841 | 3842 | How to fix that? We can quickly fix this one with one of three techniques: (1) use arrow function for the callback passing to `map`, (2) temporarily create an alternative `this` such as `let self = this` before we call map and use `self` instead of `this`. (3) explicitly bind the callback for `map` using bind, call or apply. We can also pass `this` as the second parameter for the map function. It also works. 3843 | 3844 | #### Answer: D 3845 | 3846 |

3847 |
3848 | 3849 | ###### 92. What's the output ? 3850 | 3851 | ```javascript 3852 | class FrameWork { 3853 | constructor(options) { 3854 | this.options = options ?? ["Angular", "React", "Vue"]; 3855 | } 3856 | 3857 | total() { 3858 | return this.options.length; 3859 | } 3860 | 3861 | filter() { 3862 | const selected = this.options.filter(function (element) { 3863 | return element[0] === "A"; 3864 | }); 3865 | return selected[0].length + this.total(); 3866 | } 3867 | } 3868 | 3869 | const app = new FrameWork(); 3870 | 3871 | console.log(app.filter()); 3872 | ``` 3873 | 3874 | - A: 8 3875 | - B: 2 3876 | - C: 10 3877 | - D: 1 3878 | 3879 |
Answer 3880 |

3881 | 3882 | The code challenge above implements a simple class with two methods. There is only one point in the syntax that you might need to pay a bit more attention to is `??` (nullish coalescing operator ) which is quite similar to `||` (OR). 3883 | 3884 | `??` returns the right-hand side value if the left-hand side is either `null` or `undefined` while `||` does the same thing for `falsy` value (false, null, undefined, 0, -0, 0n, NaN, "").length 3885 | 3886 | So as we do not pass anything into the constructor when we initiate the object `app`, `this.options` takes the default value `["Angular", "React", "Vue"]`, then the method `total()` evaluates the length of the array, which is 3. 3887 | 3888 | `filter()` gives us the length of "Angular", which is 8. So the final value is 10. The correct answer is C. 3889 | 3890 | #### Answer: C 3891 | 3892 |

3893 |
3894 | 3895 | ###### 93. What's the output ? 3896 | 3897 | ```javascript 3898 | const origin = [[[123], 321], 213]; 3899 | const manipulated = origin.flat(origin.length); 3900 | console.log(manipulated.length + origin.length); 3901 | ``` 3902 | 3903 | - A: 2 3904 | - B: 3 3905 | - C: 4 3906 | - D: 5 3907 | 3908 |
Answer 3909 |

3910 | 3911 | The challenge might hopefully help you have a grip on the native array method `flat()`, which is quite handy to flatten a nested array. `flat()` accepts a parameter that defines the level of the nested array you are going to manipulate. By default, this parameter is 1. 3912 | 3913 | The method returns a manipulated array. So on the code about `origin.length` returns 2 given that the array `origin` has two elements. When flattening the original array named `origin` with `flat(2)`, we then have a new array `[123, 321, 213]`. 3914 | 3915 | Finally, we have 5 in the console, and D is the correct answer. 3916 | 3917 | #### Answer: D 3918 | 3919 |

3920 |
3921 | 3922 | ###### 94. What's the output ? 3923 | 3924 | ```javascript 3925 | const pipe = 3926 | (...funs) => 3927 | (v) => { 3928 | funs.reduce((res, func) => { 3929 | return func(res); 3930 | }, v); 3931 | }; 3932 | 3933 | const plusFour = (v) => v + 4; 3934 | const multiplyBySix = (v) => v * 6; 3935 | const divideByTwo = (v) => v / 2; 3936 | 3937 | pipe(plusFour, multiplyBySix, divideByTwo, multiplyBySix, console.log)(1); 3938 | ``` 3939 | 3940 | - A: 80 3941 | - B: 90 3942 | - C: 100 3943 | - D: 110 3944 | 3945 |
Answer 3946 |

3947 | 3948 | The `pipe` function can receive an unlimited number of arguments/parameters thanks to rest parameter `...funcs`. These arguments/parameters turn out are function as we call the parent function `pipe`. In JavaScript, it is quite common to pass a function as a parameter of another function. 3949 | 3950 | Please call these functions, which are passed to `pipe`, are child functions. They are then looped and executed one by one with `reduce` method, no matter how many functions you attempt to pass to `pipe`. `v` in the code is simply the argument defined in each child function. 3951 | 3952 | So first we have 1, then by executing `plusFour` it becomes 5. When `multiplyBySix` is called, the output turns to 30. It becomes 15 when we call `divideByTwo`. Finally, it becomes 90 as we multiply 15 \* 6 when the function `multiplyBySix` is called again. 3953 | 3954 | So B is the correct answer. 3955 | 3956 | 3957 | 3958 | #### Answer: B 3959 | 3960 |

3961 |
3962 | 3963 | ###### 95. What's the output ? 3964 | 3965 | ```javascript 3966 | const quickSortRecursive = function (arrayInput) { 3967 | if (!Array.isArray(arrayInput)) { 3968 | console.log("The input data is not an array"); 3969 | return arrayInput; 3970 | } 3971 | const pivotIndex = arrayInput.length - 1; 3972 | const pivot = arrayInput[pivotIndex]; 3973 | const left = []; 3974 | const right = []; 3975 | let currentItem; 3976 | for (let i = 0; i < pivotIndex; i++) { 3977 | currentItem = arrayInput[i]; 3978 | if (currentItem < pivot) { 3979 | left.push(currentItem); 3980 | } else { 3981 | right.push(currentItem); 3982 | } 3983 | } 3984 | 3985 | return [...quickSortRecursive(left), pivot, ...quickSortRecursive(right)]; 3986 | }; 3987 | 3988 | console.log(quickSortRecursive([1, 100, 8, 19, 8, 6])); 3989 | ``` 3990 | 3991 | - A: [1, 100, 8, 19, 8, 6] 3992 | - B: [1, 6, 8, 8, 19, 100] 3993 | - C: [100, 19, 8, 8, 6, 1] 3994 | - D: 6 3995 | 3996 |
Answer 3997 |

3998 | 3999 | You might see a commonly used algorithm here in the code challenge called "quicksort" in which we apply the strategy "divide and conquer". We also use the "recursive" method when we want to recall the function until it meets our expectations. You might also need to know about the "rest parameter" in JavaScript, as shown by the three dots (...) above. 4000 | 4001 | The code above helps us to arrange an array in such a way that the value will increase from left to right. Using the quicksort method, we need to create a pivot (likely the first item from right to left or the first item from left to right). First, we divide the original array into two parts: left and right, depending on the value compared to the pivot. 4002 | 4003 | Next, by calling the function recursively, we keep creating new pivots for the right and left arrays created above for the purpose of sorting value. 4004 | 4005 | Finally, the original array is sorted from left to right depending on the value. 4006 | 4007 | So B is the correct answer. 4008 | 4009 | 4010 | 4011 | #### Answer: B 4012 | 4013 |

4014 |
4015 | 4016 | ###### 96. What's the output ? 4017 | 4018 | ```javascript 4019 | const hasOwn = (a) => { 4020 | return function (o = { a: 10 }) { 4021 | o.property = a[1]; 4022 | return (b) => { 4023 | return o.a + o.property + b; 4024 | }; 4025 | }; 4026 | }; 4027 | 4028 | console.log(hasOwn([10, 20])()(10)); 4029 | ``` 4030 | 4031 | - A: 10 4032 | - B: 20 4033 | - C: 30 4034 | - D: 40 4035 | 4036 |
Answer 4037 |

4038 | 4039 | We have quite trivial nested functions. If you are familiar with the concept of `closure` in JavaScript, then it is not a big deal to read the code above. The final function, named hasOwn, has three parameters, and when we execute it, we only pass two arguments because we have already defined the default value for the second nested function. 4040 | 4041 | The final result is as `o.a + o.property + b`, meaning 10 + 20 + 10. So D is the correct answer. 4042 | 4043 | #### Answer: D 4044 | 4045 |

4046 |
4047 | 4048 | 4049 | 4050 | ###### 97. What's the output ? 4051 | 4052 | ```javascript 4053 | function craft(text){ 4054 | const p = document.createElement("p"); 4055 | p.innerHTML = text; 4056 | document.body.append(p) 4057 | } 4058 | craft("1 - sync A") 4059 | const fetchItem = new Promise((resolve) => { 4060 | craft("2 - eager sync B") 4061 | setTimeout(function(){ 4062 | craft("3 - eager async C") 4063 | resolve("4 - async - D"); 4064 | }, 2000) 4065 | }); 4066 | craft("5 - sync E") 4067 | 4068 | fetchItem.then(data => craft(data)) 4069 | ``` 4070 | 4071 | - A: 1 - 2 - 3 - 4 - 5 4072 | - B: 1 - 2 - 5 - 3 - 4 4073 | - C: 1 - 2 - 5 - 4 - 3 4074 | - D: 1 - 2 - 3 - 5 - 4 4075 | 4076 |
Answer 4077 |

4078 | 4079 | The order will be: sync --> async. Given that Promise is eager, then we have 1 - 2 - 5 - 3 - 4. Note that if we do not call then(), the data handled by promise will not be casted out. 4080 | 4081 | #### Answer: B 4082 | 4083 |

4084 |
4085 | 4086 | 4087 | 4088 | 4089 | 4090 | 4091 | 4092 | 4093 | 4094 | 4095 | 4096 | -------------------------------------------------------------------------------- /javascript.js: -------------------------------------------------------------------------------- 1 | console.log("Hello world") --------------------------------------------------------------------------------