From 817694aaa3e67c3c05c263d1e64c1ef872120365 Mon Sep 17 00:00:00 2001 From: Glen Padua Date: Thu, 10 Dec 2020 05:53:50 +0530 Subject: [PATCH 001/193] Fix typo --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 4b7ea9a3..d56004e4 100644 --- a/README.md +++ b/README.md @@ -4621,7 +4621,7 @@ First, we invoke the `addHobby` function, and pass `"running"` as the value for Then, we invoke the `addHobby` function, and pass `"dancing"` as the value for `hobby`. We didn't pass a value for `hobbies`, so it gets the default value, the `hobbies` property on the `person` object. We push the hobby `dancing` to the `person.hobbies` array. -Last, we invoke the `addHobby` function, and pass `"bdaking"` as the value for `hobby`, and the `person.hobbies` array as the value for `hobbies`. We push the hobby `baking` to the `person.hobbies` array. +Last, we invoke the `addHobby` function, and pass `"baking"` as the value for `hobby`, and the `person.hobbies` array as the value for `hobbies`. We push the hobby `baking` to the `person.hobbies` array. After pushing `dancing` and `baking`, the value of `person.hobbies` is `["coding", "dancing", "baking"]` From b916959d7e971e018e8354d1fe994ec8f922835d Mon Sep 17 00:00:00 2001 From: Misha Ovsepyan Date: Wed, 16 Dec 2020 21:48:37 +0300 Subject: [PATCH 002/193] 63 typo fix --- ru-RU/README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/ru-RU/README.md b/ru-RU/README.md index e901a1dd..0c37cff1 100644 --- a/ru-RU/README.md +++ b/ru-RU/README.md @@ -1962,9 +1962,9 @@ console.log(num2); #### Ответ: A -Унарный оператор `++` _first возвращает_ значение операнда, _then приращивает_ значение операнда. Значение `num1` равно `10`, так как функция увеличений вначале возвращает значение `num`, которое равно `10`, и только затем увеличивает значение `num`. +Унарный оператор `++` _сначала возвращает_ значение операнда, _затем приращивает_ значение операнда. Значение `num1` равно `10`, так как функция увеличений вначале возвращает значение `num`, которое равно `10`, и только затем увеличивает значение `num`. -`num2` - это `10`, так как мы передали `num1` в `incpasePassedNumber`. `number` равно `10` (значение `num1`. Опять же, унарный оператор `++` _first возвращает_ значение операнда, _then увеличивает значение операнда. Значение `number` равно `10`, поэтому `num2` равно `10`. +`num2` - это `10`, так как мы передали `num1` в `incpasePassedNumber`. `number` равно `10` (значение `num1`. Опять же, унарный оператор `++` _сначала возвращает_ значение операнда, _затем увеличивает_ значение операнда. Значение `number` равно `10`, поэтому `num2` равно `10`.

From 0e2adadc2900fc7b5c92144a79867277618ff0f9 Mon Sep 17 00:00:00 2001 From: Nazir Bahrul Ulum <39704763+devnazir@users.noreply.github.com> Date: Thu, 17 Dec 2020 09:08:55 +0700 Subject: [PATCH 003/193] memperbaiki kata-kata yang kurang dapat dipahami --- id-ID/README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/id-ID/README.md b/id-ID/README.md index 00a06524..787698d6 100644 --- a/id-ID/README.md +++ b/id-ID/README.md @@ -63,9 +63,9 @@ sayHi(); #### Jawaban: D -Di dalam function, kita buat variabel `name` dan variabel declaration-nya menggunakan `var`. Artinya variable tersebut hoisted (dalam fase pembuatan ini menggunakan memory penyimpanan) dengan isi standar-nya `undefined`, hingga kita benar berada di baris code pembuatan variabel-nya. Kita belum membuat variabel tersebut saat kita memanggil variabel `name`, jadi isi dari varabel tersebut masih `undefined` +Di dalam function, kita membuat sebuah variabel `name` dan variabel tersebut di deklarasikan menggunakan `var`. Artinya variable tersebut di hoisting (dalam fase pembuatan ini menggunakan memory penyimpanan) dengan isi standar-nya `undefined`, saat javascript mengeksekusi baris code pembuatan variabel-nya. variabel `name` isinya masih undefined, jadi isi dari variabel tersebut `undefined` -Variabel declaration yang menggunakan `let` (dan `const`) juga hoisted, tapi tidak seperti `var`, variabel declaration `let` dan `const` tidak ditentukan isi standar-nya. `let` dan `const` tidak bisa diakses sebelum di tentukan dulu isi-nya. Kejadian ini disebut "temporal dead zone". Saat kita mencoba memanggil variabel yang belum ditentukan isi-nya, Javascript mengeluarkan error `ReferenceError`. +Mendeklarasikan varibel menggunakan `let` (dan `const`) juga terkena hoisting, tidak seperti `var`, variabel declaration `let` dan `const` tidak ditentukan isi standar-nya. `let` dan `const` tidak bisa diakses sebelum di tentukan dulu isi-nya. Kejadian ini disebut "temporal dead zone". Saat kita mencoba memanggil variabel yang belum ditentukan isi-nya, Javascript mengeluarkan error `ReferenceError`.

From b033d19bc30c75538306f5b2bf468fb5d62cf0b3 Mon Sep 17 00:00:00 2001 From: unknown Date: Sat, 19 Dec 2020 20:22:24 +0100 Subject: [PATCH 004/193] Added typo fix for question 141 --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 4b7ea9a3..d56004e4 100644 --- a/README.md +++ b/README.md @@ -4621,7 +4621,7 @@ First, we invoke the `addHobby` function, and pass `"running"` as the value for Then, we invoke the `addHobby` function, and pass `"dancing"` as the value for `hobby`. We didn't pass a value for `hobbies`, so it gets the default value, the `hobbies` property on the `person` object. We push the hobby `dancing` to the `person.hobbies` array. -Last, we invoke the `addHobby` function, and pass `"bdaking"` as the value for `hobby`, and the `person.hobbies` array as the value for `hobbies`. We push the hobby `baking` to the `person.hobbies` array. +Last, we invoke the `addHobby` function, and pass `"baking"` as the value for `hobby`, and the `person.hobbies` array as the value for `hobbies`. We push the hobby `baking` to the `person.hobbies` array. After pushing `dancing` and `baking`, the value of `person.hobbies` is `["coding", "dancing", "baking"]` From 669675982b5b1c0eb41fcd898c6549b909fff90e Mon Sep 17 00:00:00 2001 From: Alireza Sheikholmolouki Date: Tue, 22 Dec 2020 00:45:07 +0330 Subject: [PATCH 005/193] Fix question 134 --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index d56004e4..1d686609 100644 --- a/README.md +++ b/README.md @@ -4317,7 +4317,7 @@ We get to the last line of `funcTwo`, which logs `Last line!` to the console. No --- -###### 134. How can we invoke `sum` in `index.js` from `sum.js?` +###### 134. How can we invoke `sum` in `sum.js` from `index.js?` ```javascript // sum.js From 57bca2170da4e588e371157d41055749939db3be Mon Sep 17 00:00:00 2001 From: Piotr Wawrzynkiewicz Date: Tue, 19 Jan 2021 15:40:47 +0100 Subject: [PATCH 006/193] Little fix to the answer explanation of question 119 --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 1d686609..a7c97136 100644 --- a/README.md +++ b/README.md @@ -3856,7 +3856,7 @@ With the optional chaining operator `?.`, we no longer have to explicitly check `person.pet?.name`: `person` has a property named `pet`: `person.pet` is not nullish. It has a property called `name`, and returns `Mara`. `person.pet?.family?.name`: `person` has a property named `pet`: `person.pet` is not nullish. `pet` does _not_ have a property called `family`, `person.pet.family` is nullish. The expression returns `undefined`. `person.getFullName?.()`: `person` has a property named `getFullName`: `person.getFullName()` is not nullish and can get invoked, which returns `Lydia Hallie`. -`member.getLastName?.()`: `member` is not defined: `member.getLastName()` is nullish. The expression returns `undefined`. +`member.getLastName?.()`: variable `member` is non existent therefore a `ReferenceError` gets thrown!

From e70807334355fceb50e11fa144df4ee52b8f18ef Mon Sep 17 00:00:00 2001 From: Piotr Wawrzynkiewicz Date: Thu, 21 Jan 2021 11:37:01 +0100 Subject: [PATCH 007/193] Fixes to question 98 --- README.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index 1d686609..12610f93 100644 --- a/README.md +++ b/README.md @@ -3123,7 +3123,7 @@ console.log(getList(list)) console.log(getUser(user)) ``` -- A: `[1, [2, 3, 4]]` and `undefined` +- A: `[1, [2, 3, 4]]` and `SyntaxError` - B: `[1, [2, 3, 4]]` and `{ name: "Lydia", age: 21 }` - C: `[1, 2, 3, 4]` and `{ name: "Lydia", age: 21 }` - D: `Error` and `{ name: "Lydia", age: 21 }` @@ -3139,11 +3139,11 @@ The `getList` function receives an array as its argument. Between the parenthese With the rest parameter `...y`, we put all "remaining" arguments in an array. The remaining arguments are `2`, `3` and `4` in this case. The value of `y` is an array, containing all the rest parameters. The value of `x` is equal to `1` in this case, so when we log `[x, y]`, `[1, [2, 3, 4]]` gets logged. -The `getUser` function receives an object. With arrow functions, we don't _have_ to write curly brackets if we just return one value. However, if you want to return an _object_ from an arrow function, you have to write it between parentheses, otherwise no value gets returned! The following function would have returned an object: +The `getUser` function receives an object. With arrow functions, we don't _have_ to write curly brackets if we just return one value. However, if you want to instantly return an _object_ from an arrow function, you have to write it between parentheses, otherwise everything between the two braces will be interpreted as a block statement. In this case the code between the braces is not a valid JavaScript code, so a `SyntaxError` gets thrown. -`const getUser = user => ({ name: user.name, age: user.age })` +The following function would have returned an object: -Since no value gets returned in this case, the function returns `undefined`. +`const getUser = user => ({ name: user.name, age: user.age })`

From 1ac33f434874063028faf050e4accc1e3fa533a6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=AF=AB=E8=A9=A9=E7=BE=8A?= Date: Tue, 26 Jan 2021 00:55:40 +0800 Subject: [PATCH 008/193] Translation zh-TW answer 66 --- zh-TW/README_zh-TW.md | 54 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 54 insertions(+) diff --git a/zh-TW/README_zh-TW.md b/zh-TW/README_zh-TW.md index e230b5c5..5bf81296 100644 --- a/zh-TW/README_zh-TW.md +++ b/zh-TW/README_zh-TW.md @@ -2047,3 +2047,57 @@ multiply(value); --- + +###### 66. 使用哪個建構式可以成功繼承 Dog 類別? + +```javascript +class Dog { + constructor(name) { + this.name = name; + } +}; + +class Labrador extends Dog { + // 1 + constructor(name, size) { + this.size = size; + } + // 2 + constructor(name, size) { + super(name); + this.size = size; + } + // 3 + constructor(size) { + super(name); + this.size = size; + } + // 4 + constructor(name, size) { + this.name = name; + this.size = size; + } + +}; +``` + +- A: 1 +- B: 2 +- C: 3 +- D: 4 + +
Answer +

+ +#### Answer: B + +在子類別中,在呼叫 `super` 前不能存取 `this` 關鍵字,如果你這麼做,它將拋出一個 `ReferenceError`,建構式1與4會引發這個錯誤。 + +使用 `super` 關鍵字時,我們要提供參數給父類別呼叫其建構式。父類別需要接受一個 `name` 參數,所以我們需要把 `name` 傳給 `super`。 + +`Labrador` 類別接收兩個參數, `name` 參數是由於它繼承了 `Dog` , `size` 作為`Labrador` 類的額外屬性,它們都需要傳遞給 `Labrador` 的建構式,因此使用建構式2是正確答案。 + +

+
+ +--- From 819dcf36bb4f887834ec3725cf78584cdfadbeee Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=AF=AB=E8=A9=A9=E7=BE=8A?= Date: Tue, 26 Jan 2021 01:08:11 +0800 Subject: [PATCH 009/193] Translation zh-TW answer 67 --- zh-TW/README_zh-TW.md | 36 ++++++++++++++++++++++++++++++++++-- 1 file changed, 34 insertions(+), 2 deletions(-) diff --git a/zh-TW/README_zh-TW.md b/zh-TW/README_zh-TW.md index 5bf81296..c31b390c 100644 --- a/zh-TW/README_zh-TW.md +++ b/zh-TW/README_zh-TW.md @@ -2086,10 +2086,10 @@ class Labrador extends Dog { - C: 3 - D: 4 -
Answer +
答案

-#### Answer: B +#### 答案: B 在子類別中,在呼叫 `super` 前不能存取 `this` 關鍵字,如果你這麼做,它將拋出一個 `ReferenceError`,建構式1與4會引發這個錯誤。 @@ -2101,3 +2101,35 @@ class Labrador extends Dog {

--- + +###### 67. 將會輸出什麽內容? + +```javascript +// index.js +console.log('running index.js'); +import { sum } from './sum.js'; +console.log(sum(1, 2)); + +// sum.js +console.log('running sum.js'); +export const sum = (a, b) => a + b; +``` + +- A: `running index.js`, `running sum.js`, `3` +- B: `running sum.js`, `running index.js`, `3` +- C: `running sum.js`, `3`, `running index.js` +- D: `running index.js`, `undefined`, `running sum.js` + +
答案 +

+ +#### 答案: B + +`import` 命令是 _編譯階段_ 執行的。這代表被引入的模組會優先執行,而引入模組的檔案會 _之後執行_。 + +這是 `CommonJS` 中 `require()` 和 `import` 之間的區別!使用 `require()`,您可以在執行程式時根據需要戴入依賴的項目。如果我們使用 `require` 而不是 `import` 來執行此題, 結果將會依 `running index.js`,`running sum.js`,`3` 的順序輸出。 + +

+
+ +--- From c7ff57c08eb53b53979fcac39720a9380a4d97bc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=AF=AB=E8=A9=A9=E7=BE=8A?= Date: Tue, 26 Jan 2021 01:15:39 +0800 Subject: [PATCH 010/193] Translation zh-TW answer 68 --- zh-TW/README_zh-TW.md | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/zh-TW/README_zh-TW.md b/zh-TW/README_zh-TW.md index c31b390c..c0ae6ce4 100644 --- a/zh-TW/README_zh-TW.md +++ b/zh-TW/README_zh-TW.md @@ -2133,3 +2133,27 @@ export const sum = (a, b) => a + b;
--- +###### 68. 將會輸出什麽內容? + +```javascript +console.log(Number(2) === Number(2)); +console.log(Boolean(false) === Boolean(false)); +console.log(Symbol('foo') === Symbol('foo')); +``` + +- A: `true`, `true`, `false` +- B: `false`, `true`, `false` +- C: `true`, `false`, `true` +- D: `true`, `true`, `true` + +
答案 +

+ +#### 答案: A + +每個 Symbol 都是完全唯一的。傳遞給 Symbol 的參數只是給 Symbol 的一個描述。 Symbol 的值不依賴於傳遞的參數。當我們建立兩個全新的 Symbol 去比較時:第一個`Symbol('foo')`,第二個`Symbol('foo')`, 因這兩個值是唯一的,彼此不相等,因此 `Symbol('foo') === Symbol('foo')` 會得到 `false`。 + +

+
+ +--- \ No newline at end of file From 151e3090e238dc7234315b1fbd69f7af1fd727f6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=AF=AB=E8=A9=A9=E7=BE=8A?= Date: Tue, 26 Jan 2021 01:23:00 +0800 Subject: [PATCH 011/193] Translation zh-TW answer 69 --- zh-TW/README_zh-TW.md | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git a/zh-TW/README_zh-TW.md b/zh-TW/README_zh-TW.md index c0ae6ce4..26c89b4c 100644 --- a/zh-TW/README_zh-TW.md +++ b/zh-TW/README_zh-TW.md @@ -2156,4 +2156,31 @@ console.log(Symbol('foo') === Symbol('foo'));

+--- + +###### 69. 將會輸出什麽內容? + +```javascript +const name = 'Lydia Hallie'; +console.log(name.padStart(13)); +console.log(name.padStart(2)); +``` + +- A: `"Lydia Hallie"`, `"Lydia Hallie"` +- B: `" Lydia Hallie"`, `" Lydia Hallie"` (`"[13x whitespace]Lydia Hallie"`, `"[2x whitespace]Lydia Hallie"`) +- C: `" Lydia Hallie"`, `"Lydia Hallie"` (`"[1x whitespace]Lydia Hallie"`, `"Lydia Hallie"`) +- D: `"Lydia Hallie"`, `"Lyd"`, + +
答案 +

+ +#### 答案: C + +使用 `padStart` 函數,我們可以在字串的前面加上填充字串。傳遞給此函數的參數是字串的總長度(包含填充字串)。字串 Lydia Hallie 的長度為 `12` , 因此 `name.padStart(13)` 在字串的開頭只會插入1個空格,因為 12 + 1 等於 13。 + +如果傳給 `padStart` 函數的參數小於字串的長度,則不會加上填充字串。 + +

+
+ --- \ No newline at end of file From 482d1760fd6c107907d87d000b4571d6891038ec Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=AF=AB=E8=A9=A9=E7=BE=8A?= Date: Tue, 26 Jan 2021 01:28:00 +0800 Subject: [PATCH 012/193] Translation zh-TW answer 70 --- zh-TW/README_zh-TW.md | 23 ++++++++++++++++++++++- 1 file changed, 22 insertions(+), 1 deletion(-) diff --git a/zh-TW/README_zh-TW.md b/zh-TW/README_zh-TW.md index 26c89b4c..00d50435 100644 --- a/zh-TW/README_zh-TW.md +++ b/zh-TW/README_zh-TW.md @@ -2183,4 +2183,25 @@ console.log(name.padStart(2));

---- \ No newline at end of file +--- + +###### 70. 將會輸出什麽內容? + +```javascript +console.log('🥑' + '💻'); +``` + +- A: `"🥑💻"` +- B: `257548` +- C: 一個包含碼位(code point)的字串 +- D: 錯誤 + +
答案 +

+ +#### 答案: A + +使用 `+` 運算元,你可以連接字串。在此例,我們將字串“🥑”與字串”💻“連接起來,產生”🥑💻“。 + +

+
From f8a321508323c14591680ca9ce285cc25a10cdc5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=AF=AB=E8=A9=A9=E7=BE=8A?= Date: Tue, 26 Jan 2021 01:49:31 +0800 Subject: [PATCH 013/193] update the intro --- zh-TW/README_zh-TW.md | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/zh-TW/README_zh-TW.md b/zh-TW/README_zh-TW.md index 00d50435..bde3449c 100644 --- a/zh-TW/README_zh-TW.md +++ b/zh-TW/README_zh-TW.md @@ -1,10 +1,9 @@

JavaScript 進階題目列表

- --- -我會在我的 [Instagram](https://www.instagram.com/theavocoder) 上發布關於 JavaScript 的複選題,同時也會更新到這個 Repo 當中。更新日期: 2019 年 12 月 24 日 +我會在我的 [Instagram](https://www.instagram.com/theavocoder) 上發布關於 JavaScript 的複選題,同時也會更新到這個 Repo 當中。更新日期: 2020 年 06 月 12 日 從基礎到進階程度,測試你有多了解 JavaScript,不僅更新你的知識,更能幫助你的 coding 面試! :muscle: :rocket: 我每週都會在這個 Repo 中更新新的題目。 @@ -16,6 +15,9 @@
+--- + +歡迎在項目中使用它們 😃 我 _真的_ 很感激這個repo的參考,我創造了問題和解釋(是的,我很傷心lol),社區幫助我如此之多地維護和改進它!我很喜歡這個repo。 💪🏼 謝謝你,祝你玩得開心! --- From 2297a2c03f061c85c6a6a160c6acd2cbc360d7a5 Mon Sep 17 00:00:00 2001 From: Mario Ruiz Date: Mon, 25 Jan 2021 14:37:51 -0600 Subject: [PATCH 014/193] Update README.md --- README.md | 24 ++++++++++++------------ 1 file changed, 12 insertions(+), 12 deletions(-) diff --git a/README.md b/README.md index 1d686609..3c197c5d 100644 --- a/README.md +++ b/README.md @@ -387,7 +387,7 @@ console.log(member.getFullName()); #### Answer: A -In JavaScript, functions are objects, and therefore, the method `getFullName` gets added to the constructor function object itself. For that reason, we can call `Person.getFullName()`, but `member.getFullName` throws a `TypeError`. +In JavaScript, functions are objects, and therefore, the method `getFullName` gets added to the constructor function object itself. For that reason, we can call `Person.getFullName()`, but `member.getFullName` throws a `TypeError`. If you want a method to be available to all object instances, you have to add it to the prototype property: @@ -2052,7 +2052,7 @@ On the fourth call, we again don't return from the callback function. The accumu

- + --- ###### 66. With which constructor can we successfully extend the `Dog` class? @@ -2402,13 +2402,13 @@ console.log(name);
Answer

-#### Answer: D +#### Answer: A When we unpack the property `name` from the object on the right-hand side, we assign its value `"Lydia"` to a variable with the name `myName`. With `{ name: myName }`, we tell JavaScript that we want to create a new variable called `myName` with the value of the `name` property on the right-hand side. -Since we try to log `name`, a variable that is not defined, a ReferenceError gets thrown. +Since we try to log `name`, a variable that is not defined, `undefined` is returned on the left side assignment. Later, the value of `Lydia` is stored through the destructuring assignment.

@@ -4774,11 +4774,11 @@ getFruit([['🍍'], ['🍊', '🍌']]) #### Answer: D -The `?` allows us to optionally access deeper nested properties within objects. We're trying to log the item on index `1` within the subarray that's on index `1` of the `fruits` array. If the subarray on index `1` in the `fruits` array doesn't exist, it'll simply return `undefined`. If the subarray on index `1` in the `fruits` array exists, but this subarray doesn't have an item on its `1` index, it'll also return `undefined`. +The `?` allows us to optionally access deeper nested properties within objects. We're trying to log the item on index `1` within the subarray that's on index `1` of the `fruits` array. If the subarray on index `1` in the `fruits` array doesn't exist, it'll simply return `undefined`. If the subarray on index `1` in the `fruits` array exists, but this subarray doesn't have an item on its `1` index, it'll also return `undefined`. First, we're trying to log the second item in the `['🍍']` subarray of `[['🍊', '🍌'], ['🍍']]`. This subarray only contains one item, which means there is no item on index `1`, and returns `undefined`. -Then, we're invoking the `getFruits` function without passing a value as an argument, which means that `fruits` has a value of `undefined` by default. Since we're conditionally chaining the item on index `1` of`fruits`, it returns `undefined` since this item on index `1` does not exist. +Then, we're invoking the `getFruits` function without passing a value as an argument, which means that `fruits` has a value of `undefined` by default. Since we're conditionally chaining the item on index `1` of`fruits`, it returns `undefined` since this item on index `1` does not exist. Lastly, we're trying to log the second item in the `['🍊', '🍌']` subarray of `['🍍'], ['🍊', '🍌']`. The item on index `1` within this subarray is `🍌`, which gets logged. @@ -4792,7 +4792,7 @@ Lastly, we're trying to log the second item in the `['🍊', '🍌']` subarray o ```javascript class Calc { constructor() { - this.count = 0 + this.count = 0 } increase() { @@ -4919,11 +4919,11 @@ console.log(animals[dog]) #### Answer: B -Object keys are converted to strings. +Object keys are converted to strings. Since the value of `dog` is an object, `animals[dog]` actually means that we’re creating a new property called `"object Object"` equal to the new object. `animals["object Object"]` is now equal to `{ emoji: "🐶", name: "Mara"}`. -`cat` is also an object, which means that `animals[cat]` actually means that we’re overwriting the value of `animals[``"``object Object``"``]` with the new cat properties. +`cat` is also an object, which means that `animals[cat]` actually means that we’re overwriting the value of `animals[``"``object Object``"``]` with the new cat properties. Logging `animals[dog]`, or actually `animals["object Object"]` since converting the `dog` object to a string results `"object Object"`, returns the `{ emoji: "🐈", name: "Sara" }`. @@ -4956,7 +4956,7 @@ console.log(user.email) #### Answer: A -The `updateEmail` function is an arrow function, and is not bound to the `user` object. This means that the `this` keyword is not referring to the `user` object, but refers to the global scope in this case. The value of `email` within the `user` object does not get updated. When logging the value of `user.email`, the original value of `my@email.com` gets returned. +The `updateEmail` function is an arrow function, and is not bound to the `user` object. This means that the `this` keyword is not referring to the `user` object, but refers to the global scope in this case. The value of `email` within the `user` object does not get updated. When logging the value of `user.email`, the original value of `my@email.com` gets returned.

@@ -4999,7 +4999,7 @@ The `Promise.all` method runs the passed promises in parallel. If one promise fa --- -###### 153. What should the value of `method` be to log `{ name: "Lydia", age: 22 }`? +###### 153. What should the value of `method` be to log `{ name: "Lydia", age: 22 }`? ```javascript const keys = ["name", "age"] @@ -5021,7 +5021,7 @@ Object[method](keys.map((_, i) => { #### Answer: C -The `fromEntries` method turns a 2d array into an object. The first element in each subarray will be the key, and the second element in each subarray will be the value. In this case, we’re mapping over the `keys` array, which returns an array which first element is the item on the key array on the current index, and the second element is the item of the values array on the current index. +The `fromEntries` method turns a 2d array into an object. The first element in each subarray will be the key, and the second element in each subarray will be the value. In this case, we’re mapping over the `keys` array, which returns an array which first element is the item on the key array on the current index, and the second element is the item of the values array on the current index. This creates an array of subarrays containing the correct keys and values, which results in `{ name: "Lydia", age: 22 }` From 21731e98a3b4cfb97780b01e9360fff000ca24c1 Mon Sep 17 00:00:00 2001 From: Mario Ruiz Date: Mon, 25 Jan 2021 14:50:52 -0600 Subject: [PATCH 015/193] Revert "Update README.md" This reverts commit 2297a2c03f061c85c6a6a160c6acd2cbc360d7a5. --- README.md | 24 ++++++++++++------------ 1 file changed, 12 insertions(+), 12 deletions(-) diff --git a/README.md b/README.md index 3c197c5d..1d686609 100644 --- a/README.md +++ b/README.md @@ -387,7 +387,7 @@ console.log(member.getFullName()); #### Answer: A -In JavaScript, functions are objects, and therefore, the method `getFullName` gets added to the constructor function object itself. For that reason, we can call `Person.getFullName()`, but `member.getFullName` throws a `TypeError`. +In JavaScript, functions are objects, and therefore, the method `getFullName` gets added to the constructor function object itself. For that reason, we can call `Person.getFullName()`, but `member.getFullName` throws a `TypeError`. If you want a method to be available to all object instances, you have to add it to the prototype property: @@ -2052,7 +2052,7 @@ On the fourth call, we again don't return from the callback function. The accumu

- + --- ###### 66. With which constructor can we successfully extend the `Dog` class? @@ -2402,13 +2402,13 @@ console.log(name);
Answer

-#### Answer: A +#### Answer: D When we unpack the property `name` from the object on the right-hand side, we assign its value `"Lydia"` to a variable with the name `myName`. With `{ name: myName }`, we tell JavaScript that we want to create a new variable called `myName` with the value of the `name` property on the right-hand side. -Since we try to log `name`, a variable that is not defined, `undefined` is returned on the left side assignment. Later, the value of `Lydia` is stored through the destructuring assignment. +Since we try to log `name`, a variable that is not defined, a ReferenceError gets thrown.

@@ -4774,11 +4774,11 @@ getFruit([['🍍'], ['🍊', '🍌']]) #### Answer: D -The `?` allows us to optionally access deeper nested properties within objects. We're trying to log the item on index `1` within the subarray that's on index `1` of the `fruits` array. If the subarray on index `1` in the `fruits` array doesn't exist, it'll simply return `undefined`. If the subarray on index `1` in the `fruits` array exists, but this subarray doesn't have an item on its `1` index, it'll also return `undefined`. +The `?` allows us to optionally access deeper nested properties within objects. We're trying to log the item on index `1` within the subarray that's on index `1` of the `fruits` array. If the subarray on index `1` in the `fruits` array doesn't exist, it'll simply return `undefined`. If the subarray on index `1` in the `fruits` array exists, but this subarray doesn't have an item on its `1` index, it'll also return `undefined`. First, we're trying to log the second item in the `['🍍']` subarray of `[['🍊', '🍌'], ['🍍']]`. This subarray only contains one item, which means there is no item on index `1`, and returns `undefined`. -Then, we're invoking the `getFruits` function without passing a value as an argument, which means that `fruits` has a value of `undefined` by default. Since we're conditionally chaining the item on index `1` of`fruits`, it returns `undefined` since this item on index `1` does not exist. +Then, we're invoking the `getFruits` function without passing a value as an argument, which means that `fruits` has a value of `undefined` by default. Since we're conditionally chaining the item on index `1` of`fruits`, it returns `undefined` since this item on index `1` does not exist. Lastly, we're trying to log the second item in the `['🍊', '🍌']` subarray of `['🍍'], ['🍊', '🍌']`. The item on index `1` within this subarray is `🍌`, which gets logged. @@ -4792,7 +4792,7 @@ Lastly, we're trying to log the second item in the `['🍊', '🍌']` subarray o ```javascript class Calc { constructor() { - this.count = 0 + this.count = 0 } increase() { @@ -4919,11 +4919,11 @@ console.log(animals[dog]) #### Answer: B -Object keys are converted to strings. +Object keys are converted to strings. Since the value of `dog` is an object, `animals[dog]` actually means that we’re creating a new property called `"object Object"` equal to the new object. `animals["object Object"]` is now equal to `{ emoji: "🐶", name: "Mara"}`. -`cat` is also an object, which means that `animals[cat]` actually means that we’re overwriting the value of `animals[``"``object Object``"``]` with the new cat properties. +`cat` is also an object, which means that `animals[cat]` actually means that we’re overwriting the value of `animals[``"``object Object``"``]` with the new cat properties. Logging `animals[dog]`, or actually `animals["object Object"]` since converting the `dog` object to a string results `"object Object"`, returns the `{ emoji: "🐈", name: "Sara" }`. @@ -4956,7 +4956,7 @@ console.log(user.email) #### Answer: A -The `updateEmail` function is an arrow function, and is not bound to the `user` object. This means that the `this` keyword is not referring to the `user` object, but refers to the global scope in this case. The value of `email` within the `user` object does not get updated. When logging the value of `user.email`, the original value of `my@email.com` gets returned. +The `updateEmail` function is an arrow function, and is not bound to the `user` object. This means that the `this` keyword is not referring to the `user` object, but refers to the global scope in this case. The value of `email` within the `user` object does not get updated. When logging the value of `user.email`, the original value of `my@email.com` gets returned.

@@ -4999,7 +4999,7 @@ The `Promise.all` method runs the passed promises in parallel. If one promise fa --- -###### 153. What should the value of `method` be to log `{ name: "Lydia", age: 22 }`? +###### 153. What should the value of `method` be to log `{ name: "Lydia", age: 22 }`? ```javascript const keys = ["name", "age"] @@ -5021,7 +5021,7 @@ Object[method](keys.map((_, i) => { #### Answer: C -The `fromEntries` method turns a 2d array into an object. The first element in each subarray will be the key, and the second element in each subarray will be the value. In this case, we’re mapping over the `keys` array, which returns an array which first element is the item on the key array on the current index, and the second element is the item of the values array on the current index. +The `fromEntries` method turns a 2d array into an object. The first element in each subarray will be the key, and the second element in each subarray will be the value. In this case, we’re mapping over the `keys` array, which returns an array which first element is the item on the key array on the current index, and the second element is the item of the values array on the current index. This creates an array of subarrays containing the correct keys and values, which results in `{ name: "Lydia", age: 22 }` From da723b35f4bbe600c8763953a7d427bbd91f1ba7 Mon Sep 17 00:00:00 2001 From: Mario Ruiz Date: Mon, 25 Jan 2021 14:52:39 -0600 Subject: [PATCH 016/193] Update README.md Question 76 fixed as today the browser accepts the left side of the expression to be started as undefined --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 1d686609..da836bd5 100644 --- a/README.md +++ b/README.md @@ -2402,13 +2402,13 @@ console.log(name);
Answer

-#### Answer: D +#### Answer: A When we unpack the property `name` from the object on the right-hand side, we assign its value `"Lydia"` to a variable with the name `myName`. With `{ name: myName }`, we tell JavaScript that we want to create a new variable called `myName` with the value of the `name` property on the right-hand side. -Since we try to log `name`, a variable that is not defined, a ReferenceError gets thrown. +Since we try to log `name`, a variable that is not defined, `undefined` is returned on the left side assignment. Later, the value of `Lydia` is stored through the destructuring assignment.

From e0899bbd681e9a94d61e23bcb7a9b4ee92b0512d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=AF=AB=E8=A9=A9=E7=BE=8A?= Date: Wed, 27 Jan 2021 00:26:02 +0800 Subject: [PATCH 017/193] Translation zh-TW answer 71 --- zh-TW/README_zh-TW.md | 39 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) diff --git a/zh-TW/README_zh-TW.md b/zh-TW/README_zh-TW.md index bde3449c..90ed42a9 100644 --- a/zh-TW/README_zh-TW.md +++ b/zh-TW/README_zh-TW.md @@ -2207,3 +2207,42 @@ console.log('🥑' + '💻');

+ +--- + +###### 71. /* 1 */ 與 /* 2 */ 該填入什麼才能輸出 console.log 之後的值? + +```javascript +function* startGame() { + const answer = yield '你喜歡 JavaScript 嗎?'; + if (answer !== 'Yes') { + return "哦,我想我們該走了"; + } + return 'JavaScript 也愛你 ❤️'; +} + +const game = startGame(); +console.log(/* 1 */); // 你喜歡 JavaScript 嗎? +console.log(/* 2 */); // JavaScript 也愛你 ❤️ +``` + +- A: `game.next("Yes").value` and `game.next().value` +- B: `game.next.value("Yes")` and `game.next.value()` +- C: `game.next().value` and `game.next("Yes").value` +- D: `game.next.value()` and `game.next.value("Yes")` + +
答案 +

+ +#### 答案: C + +`generator` 函數在遇到 yield 關鍵字時會 “暫停” 執行。首先,我們需要讓函數產生字串 "你喜歡 JavaScript 嗎?",這可以透過呼叫 `game.next().value` 來完成。 + +`startGame()` 函數會一行一行執行直到遇到 `yield` 關鍵字,在函數裡第一個就有一個 `yield` 關鍵字:所以執行到第一行就停止了! _此時answer變數還尚未定義_ + +當我們呼叫 `game.next("Yes").value`,前一個 `yield` 被傳遞給 `next()` 的參數值所取代。此例我們使用 `Yes`。變數 `answer` 的值現在等於 `Yes`。 if 語句的條件返回 `false`,並且會返回 `JavaScript 也愛你 ❤️` 。 + +

+
+ +--- \ No newline at end of file From 5c3e9ac19174d564f06e8a6b834e679c1a701b0c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=AF=AB=E8=A9=A9=E7=BE=8A?= Date: Wed, 27 Jan 2021 00:38:16 +0800 Subject: [PATCH 018/193] Translation zh-TW answer 72 --- zh-TW/README_zh-TW.md | 35 +++++++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) diff --git a/zh-TW/README_zh-TW.md b/zh-TW/README_zh-TW.md index 90ed42a9..2055c32a 100644 --- a/zh-TW/README_zh-TW.md +++ b/zh-TW/README_zh-TW.md @@ -2245,4 +2245,39 @@ console.log(/* 2 */); // JavaScript 也愛你 ❤️

+--- + +###### 72. 將會輸出什麽內容? + +```javascript +console.log(String.raw`Hello\nworld`); +``` + +- A: `Hello world!` +- B: `Hello`
     `world` +- C: `Hello\nworld` +- D: `Hello\n`
     `world` + +
答案 +

+ +#### 答案: C + +`String.raw`會回傳一個字串,其中轉義符(`/n`, `/v`, `/t`等)被忽略! 反斜線可能是一個問題,因為你可能會有這樣的結果。 + +`const path = "C:\Documents\Projects\table.html"`。 + +將會得到: + +`C:DocumentsProjects able.html` + +如果使用`String.raw`,它將直接忽略轉譯並輸出。 + +`C:\Documents\Projects\table.html`。 + +在這種情況下,字串會以 "Hello\nworld",被記錄下來。 + +

+
+ --- \ No newline at end of file From 7900c4391aba3af0cb995d597e8c21ae0a85dc33 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=AF=AB=E8=A9=A9=E7=BE=8A?= Date: Wed, 27 Jan 2021 00:45:23 +0800 Subject: [PATCH 019/193] Translation zh-TW answer 73 --- zh-TW/README_zh-TW.md | 36 +++++++++++++++++++++++++++++++++++- 1 file changed, 35 insertions(+), 1 deletion(-) diff --git a/zh-TW/README_zh-TW.md b/zh-TW/README_zh-TW.md index 2055c32a..5358bdc9 100644 --- a/zh-TW/README_zh-TW.md +++ b/zh-TW/README_zh-TW.md @@ -2280,4 +2280,38 @@ console.log(String.raw`Hello\nworld`);

---- \ No newline at end of file +--- + +###### 73. 將會輸出什麽內容? + +```javascript +async function getData() { + return await Promise.resolve('I made it!'); +} + +const data = getData(); +console.log(data); +``` + +- A: `"I made it!"` +- B: `Promise {: "I made it!"}` +- C: `Promise {}` +- D: `undefined` + +
答案 +

+ +#### 答案: C + +一個異步函數總是返回一個 promise 。 `await` 仍然要等待 promise 的 resolve:當我們呼叫 `getData()` 等於 `data` 時,會得到一個等待的 promise。 + +如果我們想獲取 resolve 後的值`"I made it"`,我們可以在`data`上使用`.then()`函數: + +`data.then(res => console.log(res))`。 + +這樣就會出現 `"I made it!"` 的記錄。 + +

+
+ +--- From 64a813c6c4d58d91aeacfeac61048703e950415d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=AF=AB=E8=A9=A9=E7=BE=8A?= Date: Wed, 27 Jan 2021 09:08:24 +0800 Subject: [PATCH 020/193] Translation zh-TW answer 74 --- zh-TW/README_zh-TW.md | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) diff --git a/zh-TW/README_zh-TW.md b/zh-TW/README_zh-TW.md index 5358bdc9..3c322b24 100644 --- a/zh-TW/README_zh-TW.md +++ b/zh-TW/README_zh-TW.md @@ -2315,3 +2315,33 @@ console.log(data); --- + +###### 74. 將會輸出什麽內容? + +```javascript +function addToList(item, list) { + return list.push(item); +} + +const result = addToList('apple', ['banana']); +console.log(result); +``` + +- A: `['apple', 'banana']` +- B: `2` +- C: `true` +- D: `undefined` + +
答案 +

+ +#### 答案: B + +`.push()`函數回傳的是陣列的長度!原本陣列包含一個元素(字串`"香蕉"`),長度為`1`。後來將字串 `"apple"` 加到陣列中後,陣列包含兩個元素。所以會從`addToList`函數中得到,長度為 `"2"`。 + +`push`函數修改了原來的陣列。如果你想從函數中返回 _陣列_ 而不是 _陳列的長度_ ,你應該在加完`item`到陣列後,回傳`list`。 + +

+
+ +--- \ No newline at end of file From 8820d5f6835d9a9c105f14953b03736a29578e8e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=AF=AB=E8=A9=A9=E7=BE=8A?= Date: Wed, 27 Jan 2021 09:19:20 +0800 Subject: [PATCH 021/193] Translation zh-TW answer 75 --- zh-TW/README_zh-TW.md | 34 ++++++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) diff --git a/zh-TW/README_zh-TW.md b/zh-TW/README_zh-TW.md index 3c322b24..e24f0a88 100644 --- a/zh-TW/README_zh-TW.md +++ b/zh-TW/README_zh-TW.md @@ -2344,4 +2344,38 @@ console.log(result);

+--- + +###### 75. 將會輸出什麽內容? + +```javascript +const box = { x: 10, y: 20 }; + +Object.freeze(box); + +const shape = box; +shape.x = 100; + +console.log(shape); +``` + +- A: `{ x: 100, y: 20 }` +- B: `{ x: 10, y: 20 }` +- C: `{ x: 100 }` +- D: `ReferenceError` + +
答案 +

+ +#### 答案: B + +`Object.freeze` 使我們無法增加、刪除或修改Object的屬性(除非該屬性的值是另一個Object)。 + +當我們建立變數`shape`並等同被凍結的Object`box`時,`shape`也是指一個被凍結的Object。你可以透過使用`Object.isFrozen`檢查一個Object是否被凍結。在這種情況下,`Object.isFrozen(shape)`回傳true,因為變數`shape`也指向一個凍結Object。 + +由於`shape`是被凍結的,而且`x`的值不是一個Object,所以我們不能修改`x`的屬性。 `x`仍然等於`10`,於是`{ x: 10, y: 20 }`被記錄下來。 + +

+
+ --- \ No newline at end of file From 5bcb8105c04d94004f962d77a0e6cb1d893ba5b6 Mon Sep 17 00:00:00 2001 From: Uyen Nguyen Date: Wed, 27 Jan 2021 01:01:58 -0800 Subject: [PATCH 022/193] translate to Vietnamese #145 --- vi-VI/README-vi.md | 32 ++++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) diff --git a/vi-VI/README-vi.md b/vi-VI/README-vi.md index 47be74d6..fb70d131 100644 --- a/vi-VI/README-vi.md +++ b/vi-VI/README-vi.md @@ -4706,3 +4706,35 @@ Mặc định ta không thể duyệt qua được object. Trừ phi nó đượ

+ +###### 145. Output là gì? + +```javascript +let count = 0; +const nums = [0, 1, 2, 3]; + +nums.forEach(num => { + if (num) count += 1 +}) + +console.log(count) +``` + +- A: 1 +- B: 2 +- C: 3 +- D: 4 + +
Đáp án +

+ +#### Answer: C + +The `if` condition within the `forEach` loop checks whether the value of `num` is truthy or falsy. Since the first number in the `nums` array is `0`, a falsy value, the `if` statement's code block won't be executed. `count` only gets incremented for the other 3 numbers in the `nums` array, `1`, `2` and `3`. Since `count` gets incremented by `1` 3 times, the value of `count` is `3`. + +Câu lệnh `if` trong vòng lập `forEach` kiểm tra giá trị của `num` là truthy hay falsy. Vì số đầu tiên trong mảng `nums` là `0`, giá trị falsy, code trong câu lệnh `if` sẽ không chạy. `count` chỉ tăng giá trị đối với 3 số còn lại trong mảng `nums`, `1`, `2` và `3`. Vì giá trị của `count` tăng thêm `1` trong 3 lần, giá trị của `count` sẽ là `3`. + +

+
+ +--- From 4f84ab5251f3edd501a2760161466a5456cad8d4 Mon Sep 17 00:00:00 2001 From: Uyen Nguyen Date: Wed, 27 Jan 2021 01:03:18 -0800 Subject: [PATCH 023/193] delete the english portion in #145 --- vi-VI/README-vi.md | 2 -- 1 file changed, 2 deletions(-) diff --git a/vi-VI/README-vi.md b/vi-VI/README-vi.md index fb70d131..4ab59b06 100644 --- a/vi-VI/README-vi.md +++ b/vi-VI/README-vi.md @@ -4730,8 +4730,6 @@ console.log(count) #### Answer: C -The `if` condition within the `forEach` loop checks whether the value of `num` is truthy or falsy. Since the first number in the `nums` array is `0`, a falsy value, the `if` statement's code block won't be executed. `count` only gets incremented for the other 3 numbers in the `nums` array, `1`, `2` and `3`. Since `count` gets incremented by `1` 3 times, the value of `count` is `3`. - Câu lệnh `if` trong vòng lập `forEach` kiểm tra giá trị của `num` là truthy hay falsy. Vì số đầu tiên trong mảng `nums` là `0`, giá trị falsy, code trong câu lệnh `if` sẽ không chạy. `count` chỉ tăng giá trị đối với 3 số còn lại trong mảng `nums`, `1`, `2` và `3`. Vì giá trị của `count` tăng thêm `1` trong 3 lần, giá trị của `count` sẽ là `3`.

From 63378a29cc1b634dce3a15fb993ef79bc03c75aa Mon Sep 17 00:00:00 2001 From: Uyen Nguyen Date: Wed, 27 Jan 2021 01:50:05 -0800 Subject: [PATCH 024/193] translate #146 to Vietnamese --- vi-VI/README-vi.md | 37 ++++++++++++++++++++++++++++++++++++- 1 file changed, 36 insertions(+), 1 deletion(-) diff --git a/vi-VI/README-vi.md b/vi-VI/README-vi.md index 4ab59b06..a371a4ea 100644 --- a/vi-VI/README-vi.md +++ b/vi-VI/README-vi.md @@ -4728,7 +4728,7 @@ console.log(count)
Đáp án

-#### Answer: C +#### Đáp án: C Câu lệnh `if` trong vòng lập `forEach` kiểm tra giá trị của `num` là truthy hay falsy. Vì số đầu tiên trong mảng `nums` là `0`, giá trị falsy, code trong câu lệnh `if` sẽ không chạy. `count` chỉ tăng giá trị đối với 3 số còn lại trong mảng `nums`, `1`, `2` và `3`. Vì giá trị của `count` tăng thêm `1` trong 3 lần, giá trị của `count` sẽ là `3`. @@ -4736,3 +4736,38 @@ Câu lệnh `if` trong vòng lập `forEach` kiểm tra giá trị của `num` l

--- + +###### 146. Output là gì? + +```javascript +function getFruit(fruits) { + console.log(fruits?.[1]?.[1]) +} + +getFruit([['🍊', '🍌'], ['🍍']]) +getFruit() +getFruit([['🍍'], ['🍊', '🍌']]) +``` + +- A: `null`, `undefined`, 🍌 +- B: `[]`, `null`, 🍌 +- C: `[]`, `[]`, 🍌 +- D: `undefined`, `undefined`, 🍌 + +
Answer +

+ +#### Đáp án: D + +Phép toán `?` cho phép ta truy cập giá trị bên trong của object. Chúng ta thử in ra phần tử có thứ tự là `1` trong mảng con với thứ tự là `1` trong mảng `fruits`. Nếu mảng con với thứ tự là `1` trong mảng `fruits` không tồn tại, nó sẽ trả về `undefined`. Nếu mảng con với thứ tự là `1` trong mảng `fruits` tồn tại, nhưng mảng con này không có phần tử nào mang thứ tự `1`, nó cũng sẽ trả về `undefined`. + +Trước tiên, chúng ta thử in ra phần tử thứ hai trong mảng con `['🍍']` của `[['🍊', '🍌'], ['🍍']]`. Mảng con này chỉ chứa một phần tử, nghĩa là không có phần tử nào với thứ tự là `1`, và trả về `undefined`. + +Sau đó, ta gọi hàm `getFruits` khi không truyền vào một đối số nào, nghĩa là `fruits` có giá trị mặc định là `undefined`. Vì ta truyền phần tử mang thứ tự `1` của `fruits`, nó trả về `undefined` do phần tử này không tồn tại. + +Cuối cùng, ta thử in ra phần tử thứ hai trong mảng con `['🍊', '🍌']` của mảng `['🍍'], ['🍊', '🍌']`. Phần tử mang thứ tự `1` bên trong mảng con này là `🍌` sẽ được in ra. + +

+
+ +--- From e906dd762f6c51e97ef3803949e1576dfee869bf Mon Sep 17 00:00:00 2001 From: WhiteMind Date: Fri, 29 Jan 2021 10:57:04 +0800 Subject: [PATCH 025/193] Fixes to question 77 --- zh-CN/README-zh_CN.md | 18 ++++++------------ 1 file changed, 6 insertions(+), 12 deletions(-) diff --git a/zh-CN/README-zh_CN.md b/zh-CN/README-zh_CN.md index af29ca7d..a9287a22 100644 --- a/zh-CN/README-zh_CN.md +++ b/zh-CN/README-zh_CN.md @@ -2401,19 +2401,13 @@ function sum(a, b) {
答案

-#### 答案: B - -纯函数一种若输入参数相同,则永远会得到相同输出的函数。 - -在特定情况下,即使输入相同参数,也不能得到相同的返回值: +#### 答案: A -

-var a = b = {}
-a[Symbol.toPrimitive] = b[Symbol.toPrimitive] = () => Math.random()
-sum(a, b) // Uncertain
-
+纯函数在相同的输入值时,需产生相同的输出,其输出的结果,与输入值以外的其他隐藏信息或状态无关,也和由I/O设备产生的外部输出无关。 +纯函数不会产生副作用。 -所以它不是一个纯函数。 +纯函数与副作用的定义可参考: +https://zh.wikipedia.org/wiki/%E5%89%AF%E4%BD%9C%E7%94%A8_(%E8%AE%A1%E7%AE%97%E6%9C%BA%E7%A7%91%E5%AD%A6)

@@ -5085,4 +5079,4 @@ if (!typeof randomValue === "string") { `!typeof randomValue === "string"` 总是返回false,因为我们实际上是在执行 `false === "string"`。因为条件返回的是 `false`,所以 `else` 语句中的代码块会被运行,因此打印 `Yay it's a string!` 。

- \ No newline at end of file + From cccf279cfd2b1184bef70b425f6745543fce6a95 Mon Sep 17 00:00:00 2001 From: Vlad Date: Mon, 1 Feb 2021 13:01:05 +0300 Subject: [PATCH 026/193] Add RU translation for 133 number of questions --- ru-RU/README.md | 46 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 46 insertions(+) diff --git a/ru-RU/README.md b/ru-RU/README.md index 0c37cff1..06f520bd 100644 --- a/ru-RU/README.md +++ b/ru-RU/README.md @@ -4255,3 +4255,49 @@ console.log(counterOne.count);

+--- + +###### 133. Что будет на выходе? + +```javascript +const myPromise = Promise.resolve(Promise.resolve('Promise!')); + +function funcOne() { + myPromise.then(res => res).then(res => console.log(res)); + setTimeout(() => console.log('Timeout!', 0)); + console.log('Last line!'); +} + +async function funcTwo() { + const res = await myPromise; + console.log(await res); + setTimeout(() => console.log('Timeout!', 0)); + console.log('Last line!'); +} + +funcOne(); +funcTwo(); +``` + +- A: `Promise! Last line! Promise! Last line! Last line! Promise!` +- B: `Last line! Timeout! Promise! Last line! Timeout! Promise!` +- C: `Promise! Last line! Last line! Promise! Timeout! Timeout!` +- D: `Last line! Promise! Promise! Last line! Timeout! Timeout!` + +
Ответ +

+ +#### Ответ: D + +Сначала мы вызываем функцию `funcOne`. В первой строке `funcOne` происходит вызов обещания `myPromise`, которое является _асинхронной_ операцией. Пока движок занят обработкой обещания, он продолжает выполнение функции `funcOne`. Следующая строка является _асинхронной_ функцией `setTimeout`, поэтому её обратный вызов будет отправлен в Web API. (см. мою статью о цикле событий [здесь](https://dev.to/lydiahallie/javascript-visualized-event-loop-3dif).) + +Обещание, как и таймер, является асинхронной операцией, поэтому функция продолжит выполняться несмотря на обработку обещания и обратного вызова `setTimeout`. Выходит так, что `Last line!` попадет в консоль первой, т.к. не является асинхронной операцией. Далее, в следующей строке `funcOne`, обещание будет выполнено и `Promise!` выводится в консоль. Однако, т.к. далее мы вызываем `funcTwo()`, стэк вызывов не будет пустым, из-за чего обратный вызов функции `setTimeout` _пока_ не будет добавлен в стэк вызовов. + +В первой строке `funcTwo` мы _ожидаем_ выполнения обещания myPromise. С помощью ключевого слова `await` мы приостанавливаем выполнение функции пока обещание не будет выполнено (или отклонено). Затем выводим в консоль _ожидаемое_ значение `res` (т.к. предыдущее обещание вернуло обещание). После чего в консоль попадает `Promise!`. + +Следующая строка является _асинхронной_ функцией `setTimeout`, которая отправляет обратный вызов в Web API. + +Мы перешли к следующей строке функции `funcTwo` которая выводит в консоль `Last line!`. Теперь, когда стэк вызовов извлечен из `funcTwo`, он становится пустым. Обратные вызовы, которые ожидали очереди (`() => console.log("Timeout!")` из `funcOne`, и `() => console.log("Timeout!")` из `funcTwo`) добавлены в стэк вызовов один за другим. Первый вызов выведет в консоль `Timeout!` и будет извлечен из стэка. Следующий вызов также выведет `Timeout!` и тоже будет извлечен из стэка вызовов. Лог будет равен `Last line! Promise! Promise! Last line! Timeout! Timeout!` + +

+
From 80d39167b77154c67785f1b0ab29fb15193ebd5a Mon Sep 17 00:00:00 2001 From: Satwik Gupta Date: Tue, 2 Feb 2021 01:11:50 +0530 Subject: [PATCH 027/193] Fix question 133 --- README.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 1d686609..15777dbc 100644 --- a/README.md +++ b/README.md @@ -4277,14 +4277,14 @@ const myPromise = Promise.resolve(Promise.resolve('Promise!')); function funcOne() { myPromise.then(res => res).then(res => console.log(res)); - setTimeout(() => console.log('Timeout!', 0)); + setTimeout(() => console.log('Timeout!'), 0); console.log('Last line!'); } async function funcTwo() { const res = await myPromise; console.log(await res); - setTimeout(() => console.log('Timeout!', 0)); + setTimeout(() => console.log('Timeout!'), 0); console.log('Last line!'); } @@ -4302,7 +4302,7 @@ funcTwo(); #### Answer: D -First, we invoke `funcOne`. On the first line of `funcOne`, we call the `myPromise` promise, which is an _asynchronous_ operation. While the engine is busy completing the promise, it keeps on running the function `funcOne`. The next line is the _asynchronous_ `setTimeout` function, from which the callback is sent to the Web API. (see my article on the event loop here.) +First, we invoke `funcOne`. On the first line of `funcOne`, we call the `myPromise` promise, which is an _asynchronous_ operation. While the engine is busy completing the promise, it keeps on running the function `funcOne`. The next line is the _asynchronous_ `setTimeout` function, from which the callback is sent to the Web API. (see my article on the event loop here.) Both the promise and the timeout are asynchronous operations, the function keeps on running while it's busy completing the promise and handling the `setTimeout` callback. This means that `Last line!` gets logged first, since this is not an asynchonous operation. This is the last line of `funcOne`, the promise resolved, and `Promise!` gets logged. However, since we're invoking `funcTwo()`, the call stack isn't empty, and the callback of the `setTimeout` function cannot get added to the callstack yet. From 8026084d11bcac9a1bcbafdc0fe593a57e3d14bc Mon Sep 17 00:00:00 2001 From: Vlad Date: Tue, 2 Feb 2021 10:44:13 +0300 Subject: [PATCH 028/193] Add RU translation for 134 question --- ru-RU/README.md | 58 +++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 58 insertions(+) diff --git a/ru-RU/README.md b/ru-RU/README.md index 06f520bd..2188c363 100644 --- a/ru-RU/README.md +++ b/ru-RU/README.md @@ -4301,3 +4301,61 @@ funcTwo();

+ +--- + +###### 134. Как мы можем вызвать функцию `sum` в `sum.js` из `index.js?` + +```javascript +// sum.js +export default function sum(x) { + return x + x; +} + +// index.js +import * as sum from './sum'; +``` + +- A: `sum(4)` +- B: `sum.sum(4)` +- C: `sum.default(4)` +- D: Нельзя импортировать значения по умолчанию используя `*`, только именованные экспорты + +
Ответ +

+ +#### Ответ: C + +Используя звездочку `*` мы импортируем все экспортируемые значения из этого файла, как по умолчанию, так и именованные. Если бы у нас был следующий файл: + +```javascript +// info.js +export const name = 'Lydia'; +export const age = 21; +export default 'I love JavaScript'; + +// index.js +import * as info from './info'; +console.log(info); +``` + +В лог попадёт следующее: + +```javascript +{ + default: "I love JavaScript", + name: "Lydia", + age: 21 +} +``` + +Для примера `sum` это означает, что импортированное значение `sum` выглядит так: + +```javascript +{ default: function sum(x) { return x + x } } +``` + +Мы можем вызвать эту функцию с помощью `sum.default` + +

+
From 5b6a9e73d8a608a8cef8f2c5ca08b9d2d4723bd3 Mon Sep 17 00:00:00 2001 From: Vlad Date: Tue, 2 Feb 2021 10:57:50 +0300 Subject: [PATCH 029/193] Prettify text --- ru-RU/README.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/ru-RU/README.md b/ru-RU/README.md index 2188c363..f10ecebb 100644 --- a/ru-RU/README.md +++ b/ru-RU/README.md @@ -4326,7 +4326,7 @@ import * as sum from './sum'; #### Ответ: C -Используя звездочку `*` мы импортируем все экспортируемые значения из этого файла, как по умолчанию, так и именованные. Если бы у нас был следующий файл: +Используя звездочку `*`, мы импортируем все экспортируемые значения из файла, включая именнованные экспорты и экспорты по умолчанию. Если бы у нас был следующий файл: ```javascript // info.js @@ -4349,13 +4349,13 @@ console.log(info); } ``` -Для примера `sum` это означает, что импортированное значение `sum` выглядит так: +Для примера `sum` это означает, что импортированное значение `sum` будет таким: ```javascript { default: function sum(x) { return x + x } } ``` -Мы можем вызвать эту функцию с помощью `sum.default` +Следовательно, мы можем вызвать эту функцию используя `sum.default`

From dd9a8422c28885f4d5cf1bbe31988c8a77390b20 Mon Sep 17 00:00:00 2001 From: Vlad Date: Thu, 4 Feb 2021 11:57:35 +0300 Subject: [PATCH 030/193] Add RU translation for 135 question number --- ru-RU/README.md | 37 +++++++++++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) diff --git a/ru-RU/README.md b/ru-RU/README.md index f10ecebb..80511895 100644 --- a/ru-RU/README.md +++ b/ru-RU/README.md @@ -4359,3 +4359,40 @@ console.log(info);

+ +--- + +###### 135. Что будет на выходе? + +```javascript +const handler = { + set: () => console.log('Added a new property!'), + get: () => console.log('Accessed a property!'), +}; + +const person = new Proxy({}, handler); + +person.name = 'Lydia'; +person.name; +``` + +- A: `Added a new property!` +- B: `Accessed a property!` +- C: `Added a new property!` `Accessed a property!` +- D: В лог ничего не попадёт + +
Ответ +

+ +#### Ответ: C + +C помощью Proxy мы можем добавить собственное поведению объекту, которое мы передаем вторым аргументом. В нашем случае мы передаем объект `handler` который содержит свойства: `set` и `get`. `set` вызывается каждый раз когда мы _устанавливаем_ значения свойств, `get` же вызывается всякий раз когда мы _получаем_ значения свойств. + +Первый аргумент — пустой объект `{}`, который является значением `person`. Для него будет добавлено собственное поведение, описанное в объекте `handler`. При добавлении значения для объекта `person` будет вызвано свойство `set`. При запросе к значению `person` вызовется свойство `get`. + +Сначала мы устанавливаем новое свойство `name` для объекта Proxy (`person.name = "Lydia"`). Вызывается `set` и в лог попадает `"Added a new property!"`. + +Затем мы обращаемся к значению Proxy-объекта. Вызывается свойство `get` объекта `handler`. `"Accessed a property!"` попадает в лог. + +

+
From 1f8a31fda458ef6d03825cb4b1833fffc4b6a251 Mon Sep 17 00:00:00 2001 From: Vlad Date: Thu, 4 Feb 2021 12:09:32 +0300 Subject: [PATCH 031/193] Add RU translation for 136 question number --- ru-RU/README.md | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git a/ru-RU/README.md b/ru-RU/README.md index 80511895..6bef9746 100644 --- a/ru-RU/README.md +++ b/ru-RU/README.md @@ -4396,3 +4396,30 @@ C помощью Proxy мы можем добавить собственное

+ +--- + +###### 136. Какое из перечисленных действий может модифицировать объект `person`? + +```javascript +const person = { name: 'Lydia Hallie' }; + +Object.seal(person); +``` + +- A: `person.name = "Evan Bacon"` +- B: `person.age = 21` +- C: `delete person.name` +- D: `Object.assign(person, { age: 21 })` + +
Ответ +

+ +#### Ответ: A + +С помощью `Object.seal` мы можем предотвращать как _добавление_ новых свойств, так и _удаление_ существующих. + +Однако, изменение существующих свойств остаётся доступным. + +

+
From 713afa9a996be93814661b7be462a54382011b32 Mon Sep 17 00:00:00 2001 From: Lenmor Larroza Dimanalata Date: Sun, 7 Feb 2021 09:31:49 -0500 Subject: [PATCH 032/193] Clarify that `clearInterval` is needed Clearing an interval, other than reloading the browser/process, is the only way to garbage-collect a set interval, so it would stop running. --- README.md | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 15777dbc..b093d0e0 100644 --- a/README.md +++ b/README.md @@ -3685,7 +3685,11 @@ config = null; #### Answer: C -Normally when we set objects equal to `null`, those objects get _garbage collected_ as there is no reference anymore to that object. However, since the callback function within `setInterval` is an arrow function (thus bound to the `config` object), the callback function still holds a reference to the `config` object. As long as there is a reference, the object won't get garbage collected. Since it's not garbage collected, the `setInterval` callback function will still get invoked every 1000ms (1s). +Normally when we set objects equal to `null`, those objects get _garbage collected_ as there is no reference anymore to that object. However, since the callback function within `setInterval` is an arrow function (thus bound to the `config` object), the callback function still holds a reference to the `config` object. +As long as there is a reference, the object won't get garbage collected. +Since this is an interval, setting `config` to `null` or `delete`-ing `config.alert` won't garbage-collect the interval, so the interval will still be called. +It should be cleared with `clearInterval(config.alert)` to remove it from memory. +Since it was not cleared, the `setInterval` callback function will still get invoked every 1000ms (1s).

From 42a44fa252a4f82bff2d46cac78c005f21d28b29 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=9A=D0=B8=D1=80=D0=B8=D0=BB=D0=BB?= Date: Thu, 11 Feb 2021 20:56:33 +0700 Subject: [PATCH 033/193] Add translation of question 137 --- ru-RU/README.md | 32 ++++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) diff --git a/ru-RU/README.md b/ru-RU/README.md index 6bef9746..2047ab59 100644 --- a/ru-RU/README.md +++ b/ru-RU/README.md @@ -4423,3 +4423,35 @@ Object.seal(person);

+ +--- + +###### 137. Какое из перечисленных действий может модифицировать объект `person`? + +```javascript +const person = { + name: 'Lydia Hallie', + address: { + street: '100 Main St', + }, +}; + +Object.freeze(person); +``` + +- A: `person.name = "Evan Bacon"` +- B: `delete person.address` +- C: `person.address.street = "101 Main St"` +- D: `person.pet = { name: "Mara" }` + +
Ответ +

+ +#### Ответ: C + +С помощью метода `Object.freeze` мы можем _заморозить_ объект. Свойства не могут быть добавлены, изменены или удалены. + +Однако, это _неглубоко_ замораживает объект. Замораживаются только _непосредственные_ свойства объекта. Если свойством является другой объект(в нашем примере `address`), свойства этого объекта не замораживаются и могут быть изменены. + +

+
From 07944beabbe4c852bd3108b976b3895ca919454b Mon Sep 17 00:00:00 2001 From: Uyen Nguyen Date: Thu, 18 Feb 2021 00:30:12 -0800 Subject: [PATCH 034/193] translate to Vietnamese 147 - 155 --- vi-VI/README-vi.md | 307 ++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 306 insertions(+), 1 deletion(-) diff --git a/vi-VI/README-vi.md b/vi-VI/README-vi.md index a371a4ea..8ad8854f 100644 --- a/vi-VI/README-vi.md +++ b/vi-VI/README-vi.md @@ -4754,7 +4754,7 @@ getFruit([['🍍'], ['🍊', '🍌']]) - C: `[]`, `[]`, 🍌 - D: `undefined`, `undefined`, 🍌 -
Answer +
Đáp án

#### Đáp án: D @@ -4771,3 +4771,308 @@ Cuối cùng, ta thử in ra phần tử thứ hai trong mảng con `['🍊', '

--- + +###### 147. Output là gì? + +```javascript +class Calc { + constructor() { + this.count = 0 + } + + increase() { + this.count ++ + } +} + +const calc = new Calc() +new Calc().increase() + +console.log(calc.count) +``` + +- A: `0` +- B: `1` +- C: `undefined` +- D: `ReferenceError` + +
Đáp án +

+ +#### Đáp án: A + +Ta set biến `calc` bằng một instance mới của `Calc` class. Sau đó ta tạo ra instance mới của `Calc` và gọi `increase` hàm trên instance đó. Vì thuộc tính count nằm trong constructor của `Calc` class, thuộc tính count không được sử dụng trên prototype của `Calc`. Điều này nghĩa là giá trị của count chưa được thay đổi cho instance mà calc trỏ vào, giá trị của count vẫn là `0`. + +

+
+ +--- + +###### 148. Output là gi? + +```javascript +const user = { + email: "e@mail.com", + password: "12345" +} + +const updateUser = ({ email, password }) => { + if (email) { + Object.assign(user, { email }) + } + + if (password) { + user.password = password + } + + return user +} + +const updatedUser = updateUser({ email: "new@email.com" }) + +console.log(updatedUser === user) +``` + +- A: `false` +- B: `true` +- C: `TypeError` +- D: `ReferenceError` + +
Đáp án +

+ +#### Đáp án: B + +Hàm `updateUser` thay đổi các giá trị của thuộc tính `email` và `password` của user, nếu các giá trị của chúng được truyền vào hàm sau và sau đó hàm trả về `user` object. Giá trị trả về của hàm `updateUser` là `user` object, tức là giá trị của updateUser là trỏ đến cùng một `user` object mà `user` trỏ vào. `updatedUser === user` bằng `true`. + +

+
+ +--- + +###### 149. Output là gi? + +```javascript +const fruit = ['🍌', '🍊', '🍎'] + +fruit.slice(0, 1) +fruit.splice(0, 1) +fruit.unshift('🍇') + +console.log(fruit) +``` + +- A: `['🍌', '🍊', '🍎']` +- B: `['🍊', '🍎']` +- C: `['🍇', '🍊', '🍎']` +- D: `['🍇', '🍌', '🍊', '🍎']` + +
Đáp án +

+ +#### Đáp án: C + +Trước tiên, ta gọi hàm `slice` trên mảng fruit. Hàm slice không thay đổi mảng ban đầu nhưng sẽ trả về giá trị mà nó cắt từ mảng đó: banana emoji. Sau đó ta gọi hàm `splice` trên mảng fruit. Hàm splice sẽ thay đổi mảng ban đầu, nghĩa là mảng fruit bây giờ sẽ bao gồm `['🍊', '🍎']`. Cuối cùng, ta gọi mảng `unshift` trên mảng `fruit` để thay đổi mảng ban đầu bằng cách cộng thêm giá trị được đưa ra, trong trường hợp này là ‘🍇’, phần tử đầu tiên của mảng. Mảng fruit bây giờ bao gồm ['🍇', '🍊', '🍎']`. + +

+
+ +--- + +###### 150. Output là gì? + +```javascript +const animals = {}; +let dog = { emoji: '🐶' } +let cat = { emoji: '🐈' } + +animals[dog] = { ...dog, name: "Mara" } +animals[cat] = { ...cat, name: "Sara" } + +console.log(animals[dog]) +``` + +- A: `{ emoji: "🐶", name: "Mara" }` +- B: `{ emoji: "🐈", name: "Sara" }` +- C: `undefined` +- D: `ReferenceError` + +
Đáp án +

+ +#### Đáp án: B + +Các keys của object được chuyển thành các chuỗi. + +Do giá trị của `dog` là một object, `animals[dog]` thực sự nghĩa là ta tạo ra một thuộc tính mới gọi là `"object Object"` bằng với object mới. `animals["object Object"]` lúc này bằng với `{ emoji: "🐶", name: "Mara"}`. + +`cat` cũng là một object, nên `animals[cat]` thực sự nghĩa là ta thay đổi giá trị của `animals[``"``object Object``"``]` bằng thuộc tính cat mới. + +Khi in ra `animals[dog]`, hoặc thực chất là `animals["object Object"]` vì thay `dog` object bằng một chuỗi thì nó trả về `"object Object"`, ta nhận được `{ emoji: "🐈", name: "Sara" }`. + +

+
+ +--- + +###### 151. Output là gì? + +```javascript +const user = { + email: "my@email.com", + updateEmail: email => { + this.email = email + } +} + +user.updateEmail("new@email.com") +console.log(user.email) +``` + +- A: `my@email.com` +- B: `new@email.com` +- C: `undefined` +- D: `ReferenceError` + +
Đáp án +

+ +#### Đáp án: A + +Hàm `updateEmail` là một cú pháp arrow function và nó không gắn với `user` object. Điều này cho thấy từ khoá `this` không trỏ tới `user` object mà trỏ tới global scope. Giá trị của `email` trong `user` object không thay đổi. Khi ta in ra giá trị của `user.email`, nó trả về giá trị ban đầu của `my@email.com`. + +

+
+ +--- + +###### 152. Output là gì? + +```javascript +const promise1 = Promise.resolve('First') +const promise2 = Promise.resolve('Second') +const promise3 = Promise.reject('Third') +const promise4 = Promise.resolve('Fourth') + +const runPromises = async () => { + const res1 = await Promise.all([promise1, promise2]) + const res2 = await Promise.all([promise3, promise4]) + return [res1, res2] +} + +runPromises() + .then(res => console.log(res)) + .catch(err => console.log(err)) +``` + +- A: `[['First', 'Second'], ['Fourth']]` +- B: `[['First', 'Second'], ['Third', 'Fourth']]` +- C: `[['First', 'Second']]` +- D: `'Third'` + +
Đáp án +

+ +#### Đáp án: D + +Hàm `Promise.all` trả về những promise truyền vào song song nhau. Nếu một promise thất bại, hàm `Promise.all` _rejects_ với giá trị của promise đó. Trong trường hợp này, `promise3` bị reject với giá trị `"Third"`. Ta đang kiểm tra giá trị bị reject trong chuỗi hàm `catch` khi goi hàm `runPromises` để tìm ra lỗi trong hàm `runPromises`. Chỉ có `"Third"` được trả về vì `promise3` reject giá trị này. + +

+
+ +--- + +###### 153. Giá trị nào của `method` sẽ được trả về với log `{ name: "Lydia", age: 22 }`? + +```javascript +const keys = ["name", "age"] +const values = ["Lydia", 22] + +const method = /* ?? */ +Object[method](keys.map((_, i) => { + return [keys[i], values[i]] +})) // { name: "Lydia", age: 22 } +``` + +- A: `entries` +- B: `values` +- C: `fromEntries` +- D: `forEach` + +
Đáp án +

+ +#### Đáp án: C + +Hàm `fromEntries` trả về một mảng 2d trong một object. Phần tử đầu tiên trong từng mảng con sẽ là từ khoá và phần tử thứ hai trong từng mảng con sẽ là giá trị. Trong trường hợp này, ta tiến hành map qua mảng `keys`, nó sẽ trả về một mảng mà phần tử đầu tiên của mảng đó là phần tử trên thứ tự hiện tại của mảng key, và phần tử thứ hai của mảng đó là phần tử trên thứ tự hiện tại của mảng values. + +Theo như trên thì ta tạo ra một mảng gồm những mảng con chứa đựng những từ khoá và giá trị đúng, và nó trả về `{ name: "Lydia", age: 22 }`. + +

+
+ +--- + +###### 154. Output là gì? + +```javascript +const createMember = ({ email, address = {}}) => { + const validEmail = /.+\@.+\..+/.test(email) + if (!validEmail) throw new Error("Valid email pls") + + return { + email, + address: address ? address : null + } +} + +const member = createMember({ email: "my@email.com" }) +console.log(member) +``` + +- A: `{ email: "my@email.com", address: null }` +- B: `{ email: "my@email.com" }` +- C: `{ email: "my@email.com", address: {} }` +- D: `{ email: "my@email.com", address: undefined }` + +
Đáp án +

+ +#### Đáp án: C + +Giá trị mặc định của `address` là một object rỗng `{}`. Khi ta cho biến `member` bằng với object được trả về bởi hàm `createMember`, ta đã không truyền vào một giá trị của address, nghĩa là giá trị của address là object rỗng `{}` được mặc định. Object rỗng mang giá trị truthy, tức là điều kiện `address ? address : null` trả về `true`. Giá trị của address là một object rỗng `{}`. + +

+
+ +--- + +###### 155. Output là gì? + +```javascript +let randomValue = { name: "Lydia" } +randomValue = 23 + +if (!typeof randomValue === "string") { + console.log("It's not a string!") +} else { + console.log("Yay it's a string!") +} +``` + +- A: `It's not a string!` +- B: `Yay it's a string!` +- C: `TypeError` +- D: `undefined` + +
Đáp án +

+ +#### Đáp án: B + +Điều kiện trong mệnh đề `if` kiểm tra xem giá trị của `!typeof randomValue` bằng với `"string"` hay không. Phép toán `!` chuyển giá trị đó thành giá trị boolean. Nếu giá trị là truthy, giá trị trả về sẽ là `false`, nếu giá trị là falsy, giá trị trả về sẽ là `true`. Trong trường hợp này, giá trị trả về của `typeof randomValue` là giá trị truthy `"number"`, nghĩa là giá trị của `!typeof randomValue` là một giá trị boolean `false`. + +`!typeof randomValue === "string"` luôn trả về false, vì ta thực sự đang kiểm tra `false === "string"`. Vì điều kiện đã trả về `false`, code của mệnh đề `else` sẽ chạy và `Yay it's a string!` được in ra. + +

+
From e657367fca1d8aca861c4c3d900bfc8a4d63e5fb Mon Sep 17 00:00:00 2001 From: Sestowner Date: Thu, 18 Feb 2021 10:32:05 +0200 Subject: [PATCH 035/193] Update Ukrainian translation * fix language code * rename README-ua_UA.md -> README.md --- README.md | 2 +- ar-AR/README_AR.md | 2 +- bs-BS/README-bs_BS.md | 2 +- de-DE/README.md | 2 +- es-ES/README-ES.md | 2 +- fr-FR/README_fr-FR.md | 2 +- id-ID/README.md | 2 +- ja-JA/README-ja_JA.md | 2 +- ko-KR/README-ko_KR.md | 2 +- nl-NL/README.md | 2 +- pt-BR/README_pt_BR.md | 2 +- ru-RU/README.md | 2 +- th-TH/README.md | 2 +- tr-TR/README-tr_TR.md | 2 +- ua-UA/README-ua_UA.md => uk-UA/README.md | 0 vi-VI/README-vi.md | 2 +- 16 files changed, 15 insertions(+), 15 deletions(-) rename ua-UA/README-ua_UA.md => uk-UA/README.md (100%) diff --git a/README.md b/README.md index b093d0e0..8459a13d 100644 --- a/README.md +++ b/README.md @@ -34,7 +34,7 @@ Feel free to reach out to me! 😊
- [🇷🇺 Русский](./ru-RU/README.md) - [🇹🇭 ไทย](./th-TH/README-th_TH.md) - [🇹🇷 Türkçe](./tr-TR/README-tr_TR.md) -- [🇺🇦 Українська мова](./ua-UA/README-ua_UA.md) +- [🇺🇦 Українська мова](./uk-UA/README.md) - [🇻🇳 Tiếng Việt](./vi-VI/README-vi.md) - [🇨🇳 简体中文](./zh-CN/README-zh_CN.md) - [🇹🇼 繁體中文](./zh-TW/README_zh-TW.md) diff --git a/ar-AR/README_AR.md b/ar-AR/README_AR.md index 49d410c4..c5380e02 100644 --- a/ar-AR/README_AR.md +++ b/ar-AR/README_AR.md @@ -28,7 +28,7 @@ - [🇷🇺 Русский](./ru-RU/README.md) - [🇹🇭 ไทย](./th-TH/README-th_TH.md) - [🇹🇷 Türkçe](./tr-TR/README-tr_TR.md) -- [🇺🇦 Українська мова](./ua-UA/README-ua_UA.md) +- [🇺🇦 Українська мова](./uk-UA/README.md) - [🇻🇳 Tiếng Việt](./vi-VI/README-vi.md) - [🇨🇳 简体中文](./zh-CN/README-zh_CN.md) - [🇹🇼 繁體中文](./zh-TW/README_zh-TW.md) diff --git a/bs-BS/README-bs_BS.md b/bs-BS/README-bs_BS.md index 28ebdfd1..b2e89de5 100644 --- a/bs-BS/README-bs_BS.md +++ b/bs-BS/README-bs_BS.md @@ -26,7 +26,7 @@ kliknite na njih da biste ih proširili. Sretno :heart: - [🇷🇺 Русский](./ru-RU/README.md) - [🇹🇭 ไทย](./th-TH/README-th_TH.md) - [🇹🇷 Türkçe](./tr-TR/README-tr_TR.md) -- [🇺🇦 Українська мова](./ua-UA/README-ua_UA.md) +- [🇺🇦 Українська мова](./uk-UA/README.md) - [🇻🇳 Tiếng Việt](./vi-VI/README-vi.md) - [🇨🇳 简体中文](./zh-CN/README-zh_CN.md) - [🇹🇼 繁體中文](./zh-TW/README_zh-TW.md) diff --git a/de-DE/README.md b/de-DE/README.md index 47ddf131..9242e097 100644 --- a/de-DE/README.md +++ b/de-DE/README.md @@ -36,7 +36,7 @@ Kontaktiert mich, wenn ihr möchtet! 😊
- [🇷🇺 Русский](./ru-RU/README.md) - [🇹🇭 ไทย](./th-TH/README-th_TH.md) - [🇹🇷 Türkçe](./tr-TR/README-tr_TR.md) -- [🇺🇦 Українська мова](./ua-UA/README-ua_UA.md) +- [🇺🇦 Українська мова](./uk-UA/README.md) - [🇻🇳 Tiếng Việt](./vi-VI/README-vi.md) - [🇨🇳 简体中文](./zh-CN/README-zh_CN.md) - [🇹🇼 繁體中文](./zh-TW/README_zh-TW.md) diff --git a/es-ES/README-ES.md b/es-ES/README-ES.md index 95413ae1..8569da2e 100644 --- a/es-ES/README-ES.md +++ b/es-ES/README-ES.md @@ -26,7 +26,7 @@ Lista de lenguajes disponibles: - [🇷🇺 Русский](./ru-RU/README.md) - [🇹🇭 ไทย](./th-TH/README-th_TH.md) - [🇹🇷 Türkçe](./tr-TR/README-tr_TR.md) -- [🇺🇦 Українська мова](./ua-UA/README-ua_UA.md) +- [🇺🇦 Українська мова](./uk-UA/README.md) - [🇻🇳 Tiếng Việt](./vi-VI/README-vi.md) - [🇨🇳 简体中文](./zh-CN/README-zh_CN.md) - [🇹🇼 繁體中文](./zh-TW/README_zh-TW.md) diff --git a/fr-FR/README_fr-FR.md b/fr-FR/README_fr-FR.md index 3b64662a..cda358f1 100644 --- a/fr-FR/README_fr-FR.md +++ b/fr-FR/README_fr-FR.md @@ -20,7 +20,7 @@ Les réponses se trouvent dans les sections repliées en dessous des questions, - [🇷🇺 Русский](./ru-RU/README.md) - [🇹🇭 ไทย](./th-TH/README-th_TH.md) - [🇹🇷 Türkçe](./tr-TR/README-tr_TR.md) -- [🇺🇦 Українська мова](./ua-UA/README-ua_UA.md) +- [🇺🇦 Українська мова](./uk-UA/README.md) - [🇻🇳 Tiếng Việt](./vi-VI/README-vi.md) - [🇨🇳 简体中文](./zh-CN/README-zh_CN.md) - [🇹🇼 繁體中文](./zh-TW/README_zh-TW.md) diff --git a/id-ID/README.md b/id-ID/README.md index 787698d6..91c00382 100644 --- a/id-ID/README.md +++ b/id-ID/README.md @@ -30,7 +30,7 @@ Jangan sungkan untuk terhubung dengan saya! 😊
- [🇷🇺 Русский](./ru-RU/README.md) - [🇹🇭 ไทย](./th-TH/README-th_TH.md) - [🇹🇷 Türkçe](./tr-TR/README-tr_TR.md) -- [🇺🇦 Українська мова](./ua-UA/README-ua_UA.md) +- [🇺🇦 Українська мова](./uk-UA/README.md) - [🇻🇳 Tiếng Việt](./vi-VI/README-vi.md) - [🇨🇳 简体中文](./zh-CN/README-zh_CN.md) - [🇹🇼 繁體中文](./zh-TW/README_zh-TW.md) diff --git a/ja-JA/README-ja_JA.md b/ja-JA/README-ja_JA.md index 0695cfea..19a11ca6 100644 --- a/ja-JA/README-ja_JA.md +++ b/ja-JA/README-ja_JA.md @@ -22,7 +22,7 @@ - [🇷🇺 Русский](./ru-RU/README.md) - [🇹🇭 ไทย](./th-TH/README-th_TH.md) - [🇹🇷 Türkçe](./tr-TR/README-tr_TR.md) -- [🇺🇦 Українська мова](./ua-UA/README-ua_UA.md) +- [🇺🇦 Українська мова](./uk-UA/README.md) - [🇻🇳 Tiếng Việt](./vi-VI/README-vi.md) - [🇨🇳 简体中文](./zh-CN/README-zh_CN.md) - [🇹🇼 繁體中文](./zh-TW/README_zh-TW.md) diff --git a/ko-KR/README-ko_KR.md b/ko-KR/README-ko_KR.md index a75981ee..a5e85cab 100644 --- a/ko-KR/README-ko_KR.md +++ b/ko-KR/README-ko_KR.md @@ -24,7 +24,7 @@ JavaScript 에 관한 객관식 문제를 [Instagram](https://www.instagram.com/ - [🇷🇺 Русский](./ru-RU/README.md) - [🇹🇭 ไทย](./th-TH/README-th_TH.md) - [🇹🇷 Türkçe](./tr-TR/README-tr_TR.md) -- [🇺🇦 Українська мова](./ua-UA/README-ua_UA.md) +- [🇺🇦 Українська мова](./uk-UA/README.md) - [🇻🇳 Tiếng Việt](./vi-VI/README-vi.md) - [🇨🇳 简体中文](./zh-CN/README-zh_CN.md) - [🇹🇼 繁體中文](./zh-TW/README_zh-TW.md) diff --git a/nl-NL/README.md b/nl-NL/README.md index e093b94d..68f1527f 100644 --- a/nl-NL/README.md +++ b/nl-NL/README.md @@ -31,7 +31,7 @@ - [🇷🇺 Русский](./ru-RU/README.md) - [🇹🇭 ไทย](./th-TH/README-th_TH.md) - [🇹🇷 Türkçe](./tr-TR/README-tr_TR.md) -- [🇺🇦 Українська мова](./ua-UA/README-ua_UA.md) +- [🇺🇦 Українська мова](./uk-UA/README.md) - [🇻🇳 Tiếng Việt](./vi-VI/README-vi.md) - [🇨🇳 简体中文](./zh-CN/README-zh_CN.md) - [🇹🇼 繁體中文](./zh-TW/README_zh-TW.md) diff --git a/pt-BR/README_pt_BR.md b/pt-BR/README_pt_BR.md index c6c8d716..b23c927e 100644 --- a/pt-BR/README_pt_BR.md +++ b/pt-BR/README_pt_BR.md @@ -20,7 +20,7 @@ As respostas estão em seções recolhidas abaixo das questões, basta clicar ne - [🇷🇺 Русский](./ru-RU/README.md) - [🇹🇭 ไทย](./th-TH/README-th_TH.md) - [🇹🇷 Türkçe](./tr-TR/README-tr_TR.md) -- [🇺🇦 Українська мова](./ua-UA/README-ua_UA.md) +- [🇺🇦 Українська мова](./uk-UA/README.md) - [🇻🇳 Tiếng Việt](./vi-VI/README-vi.md) - [🇨🇳 简体中文](./zh-CN/README-zh_CN.md) - [🇹🇼 繁體中文](./zh-TW/README_zh-TW.md) diff --git a/ru-RU/README.md b/ru-RU/README.md index 6bef9746..f41bb2e5 100644 --- a/ru-RU/README.md +++ b/ru-RU/README.md @@ -25,7 +25,7 @@ - [🇧🇷 Português Brasil](./pt-BR/README_pt_BR.md) - [🇹🇭 ไทย](./th-TH/README-th_TH.md) - [🇹🇷 Türkçe](./tr-TR/README-tr_TR.md) -- [🇺🇦 Українська мова](./ua-UA/README-ua_UA.md) +- [🇺🇦 Українська мова](./uk-UA/README.md) - [🇻🇳 Tiếng Việt](./vi-VI/README-vi.md) - [🇨🇳 简体中文](./zh-CN/README-zh_CN.md) - [🇹🇼 繁體中文](./zh-TW/README_zh-TW.md) diff --git a/th-TH/README.md b/th-TH/README.md index 82d75bd6..8b9adea3 100644 --- a/th-TH/README.md +++ b/th-TH/README.md @@ -32,7 +32,7 @@ - [🇧🇷 Português Brasil](./pt-BR/README_pt_BR.md) - [🇷🇺 Русский](./ru-RU/README.md) - [🇹🇷 Türkçe](./tr-TR/README-tr_TR.md) -- [🇺🇦 Українська мова](./ua-UA/README-ua_UA.md) +- [🇺🇦 Українська мова](./uk-UA/README.md) - [🇻🇳 Tiếng Việt](./vi-VI/README-vi.md) - [🇨🇳 简体中文](./zh-CN/README-zh_CN.md) - [🇹🇼 繁體中文](./zh-TW/README_zh-TW.md) diff --git a/tr-TR/README-tr_TR.md b/tr-TR/README-tr_TR.md index 716038cb..3d1edba8 100644 --- a/tr-TR/README-tr_TR.md +++ b/tr-TR/README-tr_TR.md @@ -26,7 +26,7 @@ Mevcut dillerin listesi: - [🇧🇷 Português Brasil](./pt-BR/README_pt_BR.md) - [🇷🇺 Русский](./ru-RU/README.md) - [🇹🇭 ไทย](./th-TH/README-th_TH.md) -- [🇺🇦 Українська мова](./ua-UA/README-ua_UA.md) +- [🇺🇦 Українська мова](./uk-UA/README.md) - [🇻🇳 Tiếng Việt](./vi-VI/README-vi.md) - [🇨🇳 简体中文](./zh-CN/README-zh_CN.md) - [🇹🇼 繁體中文](./zh-TW/README_zh-TW.md) diff --git a/ua-UA/README-ua_UA.md b/uk-UA/README.md similarity index 100% rename from ua-UA/README-ua_UA.md rename to uk-UA/README.md diff --git a/vi-VI/README-vi.md b/vi-VI/README-vi.md index a371a4ea..00831114 100644 --- a/vi-VI/README-vi.md +++ b/vi-VI/README-vi.md @@ -22,7 +22,7 @@ Danh sách các ngôn ngữ khác: - [🇷🇺 Русский](./ru-RU/README.md) - [🇹🇭 ไทย](./th-TH/README-th_TH.md) - [🇹🇷 Türkçe](./tr-TR/README-tr_TR.md) -- [🇺🇦 Українська мова](./ua-UA/README-ua_UA.md) +- [🇺🇦 Українська мова](./uk-UA/README.md) - [🇨🇳 简体中文](./zh-CN/README-zh_CN.md) - [🇹🇼 繁體中文](./zh-TW/README_zh-TW.md) From 901942971015d0e70297c0a70b2a4290459b67f2 Mon Sep 17 00:00:00 2001 From: FrankKai Date: Fri, 16 Apr 2021 14:41:02 +0800 Subject: [PATCH 036/193] fix 133 setTimeout --- zh-CN/README-zh_CN.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/zh-CN/README-zh_CN.md b/zh-CN/README-zh_CN.md index af29ca7d..bdfd7e36 100644 --- a/zh-CN/README-zh_CN.md +++ b/zh-CN/README-zh_CN.md @@ -4272,14 +4272,14 @@ const myPromise = Promise.resolve(Promise.resolve("Promise!")); function funcOne() { myPromise.then(res => res).then(res => console.log(res)); - setTimeout(() => console.log("Timeout!", 0)); + setTimeout(() => console.log("Timeout!"), 0); console.log("Last line!"); } async function funcTwo() { const res = await myPromise; console.log(await res); - setTimeout(() => console.log("Timeout!", 0)); + setTimeout(() => console.log("Timeout!"), 0); console.log("Last line!"); } From 320852216eb5c5d34ea20a2a8abf07e9bebbda4a Mon Sep 17 00:00:00 2001 From: Tom Newton Date: Wed, 21 Apr 2021 21:41:23 +0100 Subject: [PATCH 037/193] Fix typo --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 8459a13d..18c3ccdc 100644 --- a/README.md +++ b/README.md @@ -4009,7 +4009,7 @@ async function* range(start, end) { #### Answer: C -The generator function `range` returns an async object with promises for each item in the range we pass: `Promise{1}`, `Promise{2}`, `Promise{3}`. We set the variable `gen` equal to the async object, after which we loop over it using a `for await ... of` loop. We set the variable `item` equal to the returned Promise values: first `Promise{1}`, then `Promise{2}`, then `Promise{3}`. Since we're _awaiting_ the value of `item`, the resolved promsie, the resolved _values_ of the promises get returned: `1`, `2`, then `3`. +The generator function `range` returns an async object with promises for each item in the range we pass: `Promise{1}`, `Promise{2}`, `Promise{3}`. We set the variable `gen` equal to the async object, after which we loop over it using a `for await ... of` loop. We set the variable `item` equal to the returned Promise values: first `Promise{1}`, then `Promise{2}`, then `Promise{3}`. Since we're _awaiting_ the value of `item`, the resolved promise, the resolved _values_ of the promises get returned: `1`, `2`, then `3`.

From 63f696049641ecfd0a9574db4d35b5fd195d0bbe Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?justin=28=EC=A0=95=EC=9C=A4=EA=B8=B0=29?= Date: Fri, 23 Apr 2021 15:23:15 +0900 Subject: [PATCH 038/193] =?UTF-8?q?=E2=9C=8F=EF=B8=8F=20Fix=20typo=20in=20?= =?UTF-8?q?q12=20answer?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ko-KR/README-ko_KR.md | 1706 ++++++++++++++++++++++++++--------------- 1 file changed, 1077 insertions(+), 629 deletions(-) diff --git a/ko-KR/README-ko_KR.md b/ko-KR/README-ko_KR.md index a5e85cab..8c3b416c 100644 --- a/ko-KR/README-ko_KR.md +++ b/ko-KR/README-ko_KR.md @@ -1,15 +1,23 @@ # (고급) JavaScript 질문 목록 -JavaScript 에 관한 객관식 문제를 [Instagram](https://www.instagram.com/theavocoder)에 매일 게시하고 있어요, 물론 여기에도 게시할 거예요! +JavaScript 에 관한 객관식 문제를 +[Instagram](https://www.instagram.com/theavocoder)에 매일 게시하고 있어요, 물론 +여기에도 게시할 거예요! -초급부터 고급까지: JavaScript를 얼마나 잘 알고 있는지 테스트하거나, 지식을 조금 더 새롭게 하거나, 코딩 면접을 준비하세요! :muscle: :rocket: 이 기록을 매주 새로운 질문으로 업데이트해요. 마지막 업데이트: 10월 09일 +초급부터 고급까지: JavaScript를 얼마나 잘 알고 있는지 테스트하거나, 지식을 조금 +더 새롭게 하거나, 코딩 면접을 준비하세요! :muscle: :rocket: 이 기록을 매주 새로 +운 질문으로 업데이트해요. 마지막 업데이트: 10월 09 +일 -정답은 질문 아래 접힌 부분에 있고, 간단히 클릭하면 펼칠 수 있어요. 행운을 빌어요 :heart: +정답은 질문 아래 접힌 부분에 있고, 간단히 클릭하면 펼칠 수 있어요. 행운을 빌어요 +:heart: 질문이 더 추가될 때마다 이메일을 받고 싶나요?
-✨✉이메일 업데이트 구독 ✉✨ +✨✉이메일 업 +데이트 구독 ✉✨ 사용 가능한 언어 목록: + - [🇸🇦 العربية](./ar-AR/README_AR.md) - [🇪🇬 اللغة العامية](./ar-EG/README_ar-EG.md) - [🇧🇦 Bosanski](./bs-BS/README-bs_BS.md) @@ -29,20 +37,19 @@ JavaScript 에 관한 객관식 문제를 [Instagram](https://www.instagram.com/ - [🇨🇳 简体中文](./zh-CN/README-zh_CN.md) - [🇹🇼 繁體中文](./zh-TW/README_zh-TW.md) - --- ###### 1. 무엇이 출력 될까요? ```javascript function sayHi() { - console.log(name); - console.log(age); - var name = "Lydia"; - let age = 21; + console.log(name) + console.log(age) + var name = 'Lydia' + let age = 21 } -sayHi(); +sayHi() ``` - A: `Lydia` 그리고 `undefined` @@ -55,9 +62,15 @@ sayHi(); #### 정답: D -함수 내에서, 우선 `var` 키워드를 사용해 `name` 변수를 선언해요. 이것은 변수가 정의된 행에 실제로 도달할 때까지, `undefined`의 기본값으로 호이스팅 되(생성단계에 메모리 공간이 설정)는 것을 의미해요. `name` 변수를 출력하려는 줄에서 아직 변수를 정의하고 있지 않기 때문에, `undefined` 값을 유지하고 있어요. +함수 내에서, 우선 `var` 키워드를 사용해 `name` 변수를 선언해요. 이것은 변수가 정 +의된 행에 실제로 도달할 때까지, `undefined`의 기본값으로 호이스팅 되(생성단계에 +메모리 공간이 설정)는 것을 의미해요. `name` 변수를 출력하려는 줄에서 아직 변수를 +정의하고 있지 않기 때문에, `undefined` 값을 유지하고 있어요. -`let` 키워드(그리고 `const`)를 가지는 변수들은, `var`와는 달리, 호이스팅 되지만 초기화 되지 않아요. 그것들을 선언(초기화)하는 줄 전에는 접근할 수 없어요. 이것은 "일시적 사각지대"라고 불려요. 선언되기 전 변수에 접근하려고 하면, JavaScript는 `ReferenceError`를 던져요. +`let` 키워드(그리고 `const`)를 가지는 변수들은, `var`와는 달리, 호이스팅 되지만 +초기화 되지 않아요. 그것들을 선언(초기화)하는 줄 전에는 접근할 수 없어요. +이것은 "일시적 사각지대"라고 불려요. 선언되기 전 변수에 접근하려고 하면, +JavaScript는 `ReferenceError`를 던져요.

@@ -68,11 +81,11 @@ sayHi(); ```javascript for (var i = 0; i < 3; i++) { - setTimeout(() => console.log(i), 1); + setTimeout(() => console.log(i), 1) } for (let i = 0; i < 3; i++) { - setTimeout(() => console.log(i), 1); + setTimeout(() => console.log(i), 1) } ``` @@ -85,9 +98,15 @@ for (let i = 0; i < 3; i++) { #### 정답: C -JavaScript의 이벤트 큐 때문에, `setTimeout`의 콜백 함수는 루프가 실행된 _후에_ 호출돼요. 첫 번째의 루프 변수 `i`는 `var` 키워드를 사용해 선언되어 있기 때문에, 이 값은 전역 변수가 돼요. 루프 동안, 단항 연산자 `++`를 사용하여, 매번 `i`의 값을 `1`씩 증가했어요. `setTimeout`콜백 함수가 호출되기까지, 첫 번째 예에서 `i`는 `3`이에요. +JavaScript의 이벤트 큐 때문에, `setTimeout`의 콜백 함수는 루프가 실행된 _후에_ +호출돼요. 첫 번째의 루프 변수 `i`는 `var` 키워드를 사용해 선언되어 있기 때문에, +이 값은 전역 변수가 돼요. 루프 동안, 단항 연산자 `++`를 사용하여, 매번 `i`의 값 +을 `1`씩 증가했어요. `setTimeout`콜백 함수가 호출되기까지, 첫 번째 예에서 `i`는 +`3`이에요. -두 번째 루프에서, 변수 `i`는 `let` 키워드를 사용해 선언되었어요: `let`(그리고 `const`) 키워드로 선언된 변수는 블록 범위예요(블록은 `{ }` 사이의 모든 것). 각각의 반복 동안, `i`는 새로운 값을 가지고, 각각의 값은 루프 안쪽 범위에 있어요. +두 번째 루프에서, 변수 `i`는 `let` 키워드를 사용해 선언되었어요: `let`(그리고 +`const`) 키워드로 선언된 변수는 블록 범위예요(블록은 `{ }` 사이의 모든 것). 각각 +의 반복 동안, `i`는 새로운 값을 가지고, 각각의 값은 루프 안쪽 범위에 있어요.

@@ -100,13 +119,13 @@ JavaScript의 이벤트 큐 때문에, `setTimeout`의 콜백 함수는 루프 const shape = { radius: 10, diameter() { - return this.radius * 2; + return this.radius * 2 }, - perimeter: () => 2 * Math.PI * this.radius -}; + perimeter: () => 2 * Math.PI * this.radius, +} -console.log(shape.diameter()); -console.log(shape.perimeter()); +console.log(shape.diameter()) +console.log(shape.perimeter()) ``` - A: `20` 그리고 `62.83185307179586` @@ -119,9 +138,12 @@ console.log(shape.perimeter()); #### 정답: B -`diameter`의 값은 정규 함수지만, `perimeter`의 값은 화살표 함수라는 점을 유의하세요. +`diameter`의 값은 정규 함수지만, `perimeter`의 값은 화살표 함수라는 점을 유의하 +세요. -화살표 함수에서, `this` 키워드는 통상적인 함수와는 다르게 현재 주위의 범위를 참조해요! 이것은 `perimeter`를 부르면, shape 객체가 아닌 그 주위의 범위(예를 들면 window)를 참조하는 것을 의미해요. +화살표 함수에서, `this` 키워드는 통상적인 함수와는 다르게 현재 주위의 범위를 참 +조해요! 이것은 `perimeter`를 부르면, shape 객체가 아닌 그 주위의 범위(예를 들면 +window)를 참조하는 것을 의미해요. 그 객체에는 `radius`라는 값은 없기 때문에 `undefined`를 리턴해요. @@ -133,8 +155,8 @@ console.log(shape.perimeter()); ###### 4. 무엇이 출력 될까요? ```javascript -+true; -!"Lydia"; +;+true +!'Lydia' ``` - A: `1` 그리고 `false` @@ -146,9 +168,11 @@ console.log(shape.perimeter()); #### 정답: A -단항 더하기는 피연산자를 숫자로 변환하려 시도해요. `true`는 `1`이고, `false`는 `0`이에요. +단항 더하기는 피연산자를 숫자로 변환하려 시도해요. `true`는 `1`이고, `false`는 +`0`이에요. -문자열 `'Lydia'`는 참 같은 값이에요. 실제로는, "이 참 같은 값이 거짓 같은 값인가?"를 물어보고 있어요. 이것은 `false`를 리턴해요. +문자열 `'Lydia'`는 참 같은 값이에요. 실제로는, "이 참 같은 값이 거짓 같은 값인가 +?"를 물어보고 있어요. 이것은 `false`를 리턴해요.

@@ -159,13 +183,13 @@ console.log(shape.perimeter()); ```javascript const bird = { - size: "small" -}; + size: 'small', +} const mouse = { - name: "Mickey", - small: true -}; + name: 'Mickey', + small: true, +} ``` - A: `mouse.bird.size` 는 유효하지 않아요 @@ -178,13 +202,21 @@ const mouse = { #### 정답: A -JavaScript에서, 모든 객체 키는 문자열이에요 (심볼이 아닌 한). 비록 그것을 문자열 _형_ 으로 입력하지 않아도, 항상 내부적으로 문자열로 변환돼요. +JavaScript에서, 모든 객체 키는 문자열이에요 (심볼이 아닌 한). 비록 그것을 문자열 +_형_ 으로 입력하지 않아도, 항상 내부적으로 문자열로 변환돼요. -JavaScript는 문장을 해석(또는 박스 해제)해요. 대괄호 표기를 사용하면, 첫 번째 열린 대괄호 `[`를 보고 닫힌 대괄호 `]`를 찾을 때까지 진행해요. 그때에만, 그 문장을 평가할 거예요. +JavaScript는 문장을 해석(또는 박스 해제)해요. 대괄호 표기를 사용하면, 첫 번째 열 +린 대괄호 `[`를 보고 닫힌 대괄호 `]`를 찾을 때까지 진행해요. 그때에만, 그 문장을 +평가할 거예요. -`mouse[bird.size]`: 먼저 `"small"`인 `bird.size`를 평가해요. `mouse["small"]` 은 `true`를 리턴해요. +`mouse[bird.size]`: 먼저 `"small"`인 `bird.size`를 평가해요. `mouse["small"]` 은 +`true`를 리턴해요. -그러나, 닷 표기법에서, 이것은 발생하지 않아요, `mouse`는 `bird`라고 불리는 키를 가지고 있지 않아요. 즉, `mouse.bird`는 `undefined`를 의미해요. 그 후, 닷 표기법을 사용해 `size`를 물어봐요. `mouse.bird.size`. `mouse.bird`는 `undefined`로, 실제로는 `undefined.size`를 물어보고 있어요. 이것은 유효하지 않기 때문에, `Cannot read property "size" of undefined`와 비슷한 에러를 던질 거예요. +그러나, 닷 표기법에서, 이것은 발생하지 않아요, `mouse`는 `bird`라고 불리는 키를 +가지고 있지 않아요. 즉, `mouse.bird`는 `undefined`를 의미해요. 그 후, 닷 표기법 +을 사용해 `size`를 물어봐요. `mouse.bird.size`. `mouse.bird`는 `undefined`로, 실 +제로는 `undefined.size`를 물어보고 있어요. 이것은 유효하지 않기 때문에, +`Cannot read property "size" of undefined`와 비슷한 에러를 던질 거예요.

@@ -194,12 +226,12 @@ JavaScript는 문장을 해석(또는 박스 해제)해요. 대괄호 표기를 ###### 6. 무엇이 출력 될까요? ```javascript -let c = { greeting: "Hey!" }; -let d; +let c = { greeting: 'Hey!' } +let d -d = c; -c.greeting = "Hello"; -console.log(d.greeting); +d = c +c.greeting = 'Hello' +console.log(d.greeting) ``` - A: `Hello` @@ -215,7 +247,8 @@ console.log(d.greeting); JavaScript에서, 모든 객체는 서로 동일하게 설정하면 _참조_ 에 따라 상호작용해요. -우선 변수 `c`는 객체에 대한 값을 유지해요. 그 후, `c`와 동일한 객체 참조를 `d`에 할당해요. +우선 변수 `c`는 객체에 대한 값을 유지해요. 그 후, `c`와 동일한 객체 참조를 `d`에 +할당해요. @@ -229,13 +262,13 @@ JavaScript에서, 모든 객체는 서로 동일하게 설정하면 _참조_ 에 ###### 7. 무엇이 출력 될까요? ```javascript -let a = 3; -let b = new Number(3); -let c = 3; +let a = 3 +let b = new Number(3) +let c = 3 -console.log(a == b); -console.log(a === b); -console.log(b === c); +console.log(a == b) +console.log(a === b) +console.log(b === c) ``` - A: `true` `false` `true` @@ -248,11 +281,14 @@ console.log(b === c); #### 정답: C -`new Number()`는, 내장 함수 생성자예요. 숫자처럼 보이지만, 실제로는 숫자가 아니에요: 많은 추가 특성이 있고 그것은 객체예요. +`new Number()`는, 내장 함수 생성자예요. 숫자처럼 보이지만, 실제로는 숫자가 아니 +에요: 많은 추가 특성이 있고 그것은 객체예요. -`==`연산자를 사용할 때, 그건 같은 _값_ 을 가졌는지 여부만 확인해요. 그것들은 모두`3`의 값을 가지고 있으므로, `true`를 리턴해요. +`==`연산자를 사용할 때, 그건 같은 _값_ 을 가졌는지 여부만 확인해요. 그것들은 모 +두`3`의 값을 가지고 있으므로, `true`를 리턴해요. -그러나, `===`연산자를 사용할 때, 값 _과_ 형 둘 다 같아야 해요. 이건 아니에요: `new Number()`는 숫자가 아니에요. **객체**에요. 그래서 둘 다 `false`를 리턴해요. +그러나, `===`연산자를 사용할 때, 값 _과_ 형 둘 다 같아야 해요. 이건 아니에요: +`new Number()`는 숫자가 아니에요. **객체**에요. 그래서 둘 다 `false`를 리턴해요.

@@ -264,17 +300,17 @@ console.log(b === c); ```javascript class Chameleon { static colorChange(newColor) { - this.newColor = newColor; - return this.newColor; + this.newColor = newColor + return this.newColor } - constructor({ newColor = "green" } = {}) { - this.newColor = newColor; + constructor({ newColor = 'green' } = {}) { + this.newColor = newColor } } -const freddie = new Chameleon({ newColor: "purple" }); -console.log(freddie.colorChange("orange")); +const freddie = new Chameleon({ newColor: 'purple' }) +console.log(freddie.colorChange('orange')) ``` - A: `orange` @@ -287,7 +323,10 @@ console.log(freddie.colorChange("orange")); #### 정답: D -`colorChange`함수는 정적이에요. 정적 메소드는 그것들이 만들어지는 생성자 상에서만 살아있도록 설계되어 있어, 어떤 자식들도 상속받을 수 없어요. `freddie`는 자식이기 때문에, 이 함수는 상속되지 않고, `freddie`인스턴스에서는 이용할 수 없어요: `TypeError`가 던져져요. +`colorChange`함수는 정적이에요. 정적 메소드는 그것들이 만들어지는 생성자 상에서 +만 살아있도록 설계되어 있어, 어떤 자식들도 상속받을 수 없어요. `freddie`는 자식 +이기 때문에, 이 함수는 상속되지 않고, `freddie`인스턴스에서는 이용할 수 없어요: +`TypeError`가 던져져요.

@@ -297,9 +336,9 @@ console.log(freddie.colorChange("orange")); ###### 9. 무엇이 출력 될까요? ```javascript -let greeting; // Typo! -greetign = {}; -console.log(greetign); +let greeting // Typo! +greetign = {} +console.log(greetign) ``` - A: `{}` @@ -311,9 +350,12 @@ console.log(greetign); #### 정답: A -역 객체에 빈 객체를 방금 만들었기 때문에, 객체는 출력돼요. `greeting`을 `greettign`으로 잘못 입력했을 경우, JS 인터프리터는 실제로 이것을 `global.greettign = {}` (또는 브라우저의 `window.greetign = {}`) 라고 간주해요. +역 객체에 빈 객체를 방금 만들었기 때문에, 객체는 출력돼요. `greeting`을 +`greettign`으로 잘못 입력했을 경우, JS 인터프리터는 실제로 이것을 +`global.greettign = {}` (또는 브라우저의 `window.greetign = {}`) 라고 간주해요. -이것을 피하기 위해서, `"use strict"`를 사용할 수 있어요. 이렇게 하면 변수를 어떤 것과 동일하게 설정하기 전에 변수를 선언했는지 확인할 수 있어요. +이것을 피하기 위해서, `"use strict"`를 사용할 수 있어요. 이렇게 하면 변수를 어떤 +것과 동일하게 설정하기 전에 변수를 선언했는지 확인할 수 있어요.

@@ -324,10 +366,10 @@ console.log(greetign); ```javascript function bark() { - console.log("Woof!"); + console.log('Woof!') } -bark.animal = "dog"; +bark.animal = 'dog' ``` - A: 별일 없어요, 이건 완전히 괜찮아요! @@ -340,9 +382,11 @@ bark.animal = "dog"; #### 정답: A -함수는 객체이기 때문에, 이건 JavaScript에서는 가능해요! (윈시형 이외는 모두 객체) +함수는 객체이기 때문에, 이건 JavaScript에서는 가능해요! (윈시형 이외는 모두 객체 +) -함수는 특별한 종류의 객체예요. 당신이 쓴 코드는 실제 함수가 아니에요. 함수는 속성을 가진 객체예요. 이 속성은 호출이 가능해요. +함수는 특별한 종류의 객체예요. 당신이 쓴 코드는 실제 함수가 아니에요. 함수는 속 +성을 가진 객체예요. 이 속성은 호출이 가능해요.

@@ -353,16 +397,16 @@ bark.animal = "dog"; ```javascript function Person(firstName, lastName) { - this.firstName = firstName; - this.lastName = lastName; + this.firstName = firstName + this.lastName = lastName } -const member = new Person("Lydia", "Hallie"); -Person.getFullName = function() { - return `${this.firstName} ${this.lastName}`; -}; +const member = new Person('Lydia', 'Hallie') +Person.getFullName = function () { + return `${this.firstName} ${this.lastName}` +} -console.log(member.getFullName()); +console.log(member.getFullName()) ``` - A: `TypeError` @@ -375,15 +419,21 @@ console.log(member.getFullName()); #### 정답: A -생성자에는 보통의 객체처럼 속성을 추가할 수 없어요. 한 번에 모든 객체에 기능을 추가하고 싶다면, 프로토타입을 사용해야 해요. 그래서 이 경우에, +생성자에는 보통의 객체처럼 속성을 추가할 수 없어요. 한 번에 모든 객체에 기능을 +추가하고 싶다면, 프로토타입을 사용해야 해요. 그래서 이 경우에, ```js -Person.prototype.getFullName = function() { - return `${this.firstName} ${this.lastName}`; -}; +Person.prototype.getFullName = function () { + return `${this.firstName} ${this.lastName}` +} ``` -`member.getFullName()`은 작동해요. 이것은 왜 유익할까요? 이 메소드를 생성자 자체에 추가했다고 할게요. 아마도 모든 `Person` 인스턴스는 이 메소드가 필요하지 않을 수도 있어요. 그 경우 그들은 계속해서 속성을 갖고 있기 때문에, 각각의 인스턴스를 위한 메모리 공간을 소비하게 되어, 많은 메모리 공간을 낭비하게 될 거예요. 대신에, 프로토타입을 추가하는 것만으로, 메모리의 한 지점을 가지지만, 모든 것들은 그것에 접근할 수 있어요. +`member.getFullName()`은 작동해요. 이것은 왜 유익할까요? 이 메소드를 생성자 자체 +에 추가했다고 할게요. 아마도 모든 `Person` 인스턴스는 이 메소드가 필요하지 않을 +수도 있어요. 그 경우 그들은 계속해서 속성을 갖고 있기 때문에, 각각의 인스턴스를 +위한 메모리 공간을 소비하게 되어, 많은 메모리 공간을 낭비하게 될 거예요. 대신에, +프로토타입을 추가하는 것만으로, 메모리의 한 지점을 가지지만, 모든 것들은 그것에 +접근할 수 있어요.

@@ -394,19 +444,20 @@ Person.prototype.getFullName = function() { ```javascript function Person(firstName, lastName) { - this.firstName = firstName; - this.lastName = lastName; + this.firstName = firstName + this.lastName = lastName } -const lydia = new Person("Lydia", "Hallie"); -const sarah = Person("Sarah", "Smith"); +const lydia = new Person('Lydia', 'Hallie') +const sarah = Person('Sarah', 'Smith') -console.log(lydia); -console.log(sarah); +console.log(lydia) +console.log(sarah) ``` - A: `Person {firstName: "Lydia", lastName: "Hallie"}` 그리고 `undefined` -- B: `Person {firstName: "Lydia", lastName: "Hallie"}` 그리고 `Person {firstName: "Sarah", lastName: "Smith"}` +- B: `Person {firstName: "Lydia", lastName: "Hallie"}` 그리고 + `Person {firstName: "Sarah", lastName: "Smith"}` - C: `Person {firstName: "Lydia", lastName: "Hallie"}` 그리고 `{}` - D:`Person {firstName: "Lydia", lastName: "Hallie"}` 그리고 `ReferenceError` @@ -415,9 +466,14 @@ console.log(sarah); #### 정답: A -`sarah`에게 `new` 키워드를 사용하지 않았어요. `new`를 사용한 경우, 이것은 우리가 만든 새로운 빈 객체를 참조해요. 그러나, `new`를 추가하지 않으면 **전역변수**를 참조해요! +`sarah`에게 `new` 키워드를 사용하지 않았어요. `new`를 사용한 경우, 이것은 우리가 +만든 새로운 빈 객체를 참조해요. 그러나, `new`를 추가하지 않으면 **전역변수**를 +참조해요! -`this.firstName`은 `"Sarah"`이고, `this.lastName`은 `"Smith"`이리고 말했었어요. (그렇지만) 우리는 실제로 한 일은 `global.firstName = 'Sarah'` 그리고 `global.lastName = 'Smith'`를 정의하는 것이에요. `sarah` 자체는 `undefined`로 남아있어요. 따라서 `Person`함수의 값을 리턴하지 않아요. +`this.firstName`은 `"Sarah"`이고, `this.lastName`은 `"Smith"`이라고 말했었어요. +(그렇지만) 우리가 실제로 한 일은 `global.firstName = 'Sarah'` 그리고 +`global.lastName = 'Smith'`를 정의하는 것이에요. `sarah` 자체는 `undefined`로 남 +아있어요. 따라서 `Person`함수의 값을 리턴하지 않아요.

@@ -436,7 +492,8 @@ console.log(sarah); #### 정답: D -**capturing** 단계 동안에, 이벤트는 조상 요소를 거쳐 목표 요소까지 내려가요. 그런 다음 **target** 요소에 도달하고, **bubbling**이 시작돼요. +**capturing** 단계 동안에, 이벤트는 조상 요소를 거쳐 목표 요소까지 내려가요. 그 +런 다음 **target** 요소에 도달하고, **bubbling**이 시작돼요. @@ -455,7 +512,12 @@ console.log(sarah); #### 정답: B -**기본 객체**를 제외한, 모든 객체는 프로토타입을 가져요. 기본 객체는 사용자에 의해 만들어지거나 `new` 키워드를 사용하여 만들어져요. 기본 객체는 `.toString`과 같은 몇 개의 메소드와 속성에 접근할 수 있어요. 이것이 내장 JavaScript 메소드를 사용할 수 있는 이유죠! 이러한 모든 메소드는 프로토타입에서 이용할 수 있어요. JavaScript가 당신의 객체를 직접 찾을 수 없더라도, 당신이 접근할 수 있도록 프로토타입 체인으로 내려가서 찾을 거에요. +**기본 객체**를 제외한, 모든 객체는 프로토타입을 가져요. 기본 객체는 사용자에 의 +해 만들어지거나 `new` 키워드를 사용하여 만들어져요. 기본 객체는 `.toString`과 같 +은 몇 개의 메소드와 속성에 접근할 수 있어요. 이것이 내장 JavaScript 메소드를 사 +용할 수 있는 이유죠! 이러한 모든 메소드는 프로토타입에서 이용할 수 있어요. +JavaScript가 당신의 객체를 직접 찾을 수 없더라도, 당신이 접근할 수 있도록 프로토 +타입 체인으로 내려가서 찾을 거에요.

@@ -466,10 +528,10 @@ console.log(sarah); ```javascript function sum(a, b) { - return a + b; + return a + b } -sum(1, "2"); +sum(1, '2') ``` - A: `NaN` @@ -482,9 +544,14 @@ sum(1, "2"); #### 정답: C -JavaScript는 **동적으로 만들어진 언어**에요: 특정 변수가 어떤 형인지 지정하지 않아요. 변수는 당신이 모르는 사이에 자동으로 다른 형으로 변환될 수 있는데, 이걸 _암묵적 형 변환_ 이라고 불러요. **Coercion**은 하나의 형을 다른 형으로 변환해요. +JavaScript는 **동적으로 만들어진 언어**에요: 특정 변수가 어떤 형인지 지정하지 않 +아요. 변수는 당신이 모르는 사이에 자동으로 다른 형으로 변환될 수 있는데, 이걸 +_암묵적 형 변환_ 이라고 불러요. **Coercion**은 하나의 형을 다른 형으로 변환해요. -이 예제에서, 함수가 이해하고 값을 리턴하도록, JavaScript는 숫자 `1`을 문자열로 변환해요. 수형 (`1`)와 문자열형 (`'2'`)의 추가 중에는, 숫자는 문자열로 취급해요. `"Hello" + "World"`처럼 문자열을 연결할 수 있어요, 따라서 여기 `"1" + "2"`는 `"12"`을 리턴하는 일이 발생해요. +이 예제에서, 함수가 이해하고 값을 리턴하도록, JavaScript는 숫자 `1`을 문자열로 +변환해요. 수형 (`1`)와 문자열형 (`'2'`)의 추가 중에는, 숫자는 문자열로 취급해요. +`"Hello" + "World"`처럼 문자열을 연결할 수 있어요, 따라서 여기 `"1" + "2"`는 +`"12"`을 리턴하는 일이 발생해요.

@@ -494,10 +561,10 @@ JavaScript는 **동적으로 만들어진 언어**에요: 특정 변수가 어 ###### 16. 무엇이 출력 될까요? ```javascript -let number = 0; -console.log(number++); -console.log(++number); -console.log(number); +let number = 0 +console.log(number++) +console.log(++number) +console.log(number) ``` - A: `1` `1` `2` @@ -531,15 +598,15 @@ console.log(number); ```javascript function getPersonInfo(one, two, three) { - console.log(one); - console.log(two); - console.log(three); + console.log(one) + console.log(two) + console.log(three) } -const person = "Lydia"; -const age = 21; +const person = 'Lydia' +const age = 21 -getPersonInfo`${person} is ${age} years old`; +getPersonInfo`${person} is ${age} years old` ``` - A: `"Lydia"` `21` `["", " is ", " years old"]` @@ -551,7 +618,8 @@ getPersonInfo`${person} is ${age} years old`; #### 정답: B -태그드 템플릿 리터럴을 사용하는 경우, 첫 번째 인수의 값은 항상 문자열 값의 배열이에요. 나머지 인수는 식을 통과한 값을 얻어요. +태그드 템플릿 리터럴을 사용하는 경우, 첫 번째 인수의 값은 항상 문자열 값의 배열 +이에요. 나머지 인수는 식을 통과한 값을 얻어요.

@@ -563,15 +631,15 @@ getPersonInfo`${person} is ${age} years old`; ```javascript function checkAge(data) { if (data === { age: 18 }) { - console.log("You are an adult!"); + console.log('You are an adult!') } else if (data == { age: 18 }) { - console.log("You are still an adult."); + console.log('You are still an adult.') } else { - console.log(`Hmm.. You don't have an age I guess`); + console.log(`Hmm.. You don't have an age I guess`) } } -checkAge({ age: 18 }); +checkAge({ age: 18 }) ``` - A: `You are an adult!` @@ -583,11 +651,15 @@ checkAge({ age: 18 }); #### 정답: C -동등성을 테스트할 때, 원시형은 그 _값_ 에 따라 비교되며, 객체는 그들의 _참조_ 에 따라 비교돼요. JavaScript 객체가 메모리 내의 같은 장소를 참조하고 있는지를 확인해요. +동등성을 테스트할 때, 원시형은 그 _값_ 에 따라 비교되며, 객체는 그들의 _참조_ 에 +따라 비교돼요. JavaScript 객체가 메모리 내의 같은 장소를 참조하고 있는지를 확인 +해요. -비교하고 있는 두 개의 객체는 그것이 없어요: 파라미터로 전달된 객체와 동등성을 확인하기 위해 사용한 객체는 메모리 내의 다른 장소를 참조해요. +비교하고 있는 두 개의 객체는 그것이 없어요: 파라미터로 전달된 객체와 동등성을 확 +인하기 위해 사용한 객체는 메모리 내의 다른 장소를 참조해요. -이것이 `{ age: 18 } === { age: 18 }` 그리고 `{ age: 18 } == { age: 18 }` 두 개 다 `false`를 리턴하는 이유죠. +이것이 `{ age: 18 } === { age: 18 }` 그리고 `{ age: 18 } == { age: 18 }` 두 개 +다 `false`를 리턴하는 이유죠.

@@ -598,10 +670,10 @@ checkAge({ age: 18 }); ```javascript function getAge(...args) { - console.log(typeof args); + console.log(typeof args) } -getAge(21); +getAge(21) ``` - A: `"number"` @@ -614,7 +686,8 @@ getAge(21); #### 정답: C -rest 파라미터 (`...args`.)는 모든 남아있는 인수들을 하나의 배열로 "집합" 해요. 배열은 객체이므로, `typeof args`는 `"object"`를 리턴해요. +rest 파라미터 (`...args`.)는 모든 남아있는 인수들을 하나의 배열로 "집합" 해요. +배열은 객체이므로, `typeof args`는 `"object"`를 리턴해요.

@@ -625,12 +698,12 @@ rest 파라미터 (`...args`.)는 모든 남아있는 인수들을 하나의 배 ```javascript function getAge() { - "use strict"; - age = 21; - console.log(age); + 'use strict' + age = 21 + console.log(age) } -getAge(); +getAge() ``` - A: `21` @@ -643,7 +716,10 @@ getAge(); #### 정답: C -`"use strict"`을 사용하면, 실수로 전역 변수를 선언하지 않게 할 수 있어요. `age`라는 변수를 선언한 적이 전혀 없고, `"use strict"`을 사용하고 있으므로, 참조 에러를 던지게 될 거예요. 만약 `"use strict"`을 사용하지 않았다면, 이건 작동할 거예요, `age` 속성이 전역 객체에 추가된 것이기 때문이죠. +`"use strict"`을 사용하면, 실수로 전역 변수를 선언하지 않게 할 수 있어요. +`age`라는 변수를 선언한 적이 전혀 없고, `"use strict"`을 사용하고 있으므로, 참조 +에러를 던지게 될 거예요. 만약 `"use strict"`을 사용하지 않았다면, 이건 작동할 거 +예요, `age` 속성이 전역 객체에 추가된 것이기 때문이죠.

@@ -653,7 +729,7 @@ getAge(); ###### 21. `sum`의 값은 무엇일까요? ```javascript -const sum = eval("10*10+5"); +const sum = eval('10*10+5') ``` - A: `105` @@ -666,7 +742,9 @@ const sum = eval("10*10+5"); #### 정답: A -`eval` 문자열로서 통과된 코드를 평가해요. 이 경우와 같이 만약 그것이 표현식이라면, 표현 식을 평가해요. 표현 식은 `10 * 10 + 5`이에요. 이것은 숫자 `105`를 리턴해요. +`eval` 문자열로서 통과된 코드를 평가해요. 이 경우와 같이 만약 그것이 표현식이라 +면, 표현 식을 평가해요. 표현 식은 `10 * 10 + 5`이에요. 이것은 숫자 `105`를 리턴 +해요.

@@ -676,7 +754,7 @@ const sum = eval("10*10+5"); ###### 22. cool_secret에 몇 시간이나 접근이 가능할까요? ```javascript -sessionStorage.setItem("cool_secret", 123); +sessionStorage.setItem('cool_secret', 123) ``` - A: 영원히, 데이터는 사라지지 않아요. @@ -691,7 +769,8 @@ sessionStorage.setItem("cool_secret", 123); `sessionStorage`에 저장된 데이터는 _탭_ 을 닫은 후에 삭제돼요. -만약 `localStorage`를 사용했다면, 예를 들어 `localStorage.clear()`를 호출하지 않는 한, 데이터는 영원할 거예요. +만약 `localStorage`를 사용했다면, 예를 들어 `localStorage.clear()`를 호출하지 않 +는 한, 데이터는 영원할 거예요.

@@ -701,10 +780,10 @@ sessionStorage.setItem("cool_secret", 123); ###### 23. 무엇이 출력 될까요? ```javascript -var num = 8; -var num = 10; +var num = 8 +var num = 10 -console.log(num); +console.log(num) ``` - A: `8` @@ -717,7 +796,8 @@ console.log(num); #### 정답: B -`var` 키워드를 사용하면, 같은 이름으로 복수의 변수를 선언할 수 있어요. 변수는 최신의 값을 유지해요. +`var` 키워드를 사용하면, 같은 이름으로 복수의 변수를 선언할 수 있어요. 변수는 최 +신의 값을 유지해요. 블록 스코프의 `let` 또는 `const`에서는 할 수 없어요. @@ -729,13 +809,13 @@ console.log(num); ###### 24. 무엇이 출력 될까요? ```javascript -const obj = { 1: "a", 2: "b", 3: "c" }; -const set = new Set([1, 2, 3, 4, 5]); +const obj = { 1: 'a', 2: 'b', 3: 'c' } +const set = new Set([1, 2, 3, 4, 5]) -obj.hasOwnProperty("1"); -obj.hasOwnProperty(1); -set.has("1"); -set.has(1); +obj.hasOwnProperty('1') +obj.hasOwnProperty(1) +set.has('1') +set.has(1) ``` - A: `false` `true` `false` `true` @@ -748,9 +828,11 @@ set.has(1); #### 정답: C -모든 객체 키는(심볼 제외) 문자열로 직접 입력하지 않아도, 내부적으로는 문자열이에요. 이것이 `obj.hasOwnProperty('1')`도 true를 리턴하는 이유죠. +모든 객체 키는(심볼 제외) 문자열로 직접 입력하지 않아도, 내부적으로는 문자열이에 +요. 이것이 `obj.hasOwnProperty('1')`도 true를 리턴하는 이유죠. -set에서는 작동하지 않아요. set에는 `'1'`이 없어요: `set.has('1')`는 `false`를 리턴해요. 그것은 수형인 `1`을 가지고 있어, `set.has(1)`는 `true`를 리턴해요. +set에서는 작동하지 않아요. set에는 `'1'`이 없어요: `set.has('1')`는 `false`를 리 +턴해요. 그것은 수형인 `1`을 가지고 있어, `set.has(1)`는 `true`를 리턴해요.

@@ -760,8 +842,8 @@ set에서는 작동하지 않아요. set에는 `'1'`이 없어요: `set.has('1') ###### 25. 무엇이 출력 될까요? ```javascript -const obj = { a: "one", b: "two", a: "three" }; -console.log(obj); +const obj = { a: 'one', b: 'two', a: 'three' } +console.log(obj) ``` - A: `{ a: "one", b: "two" }` @@ -774,7 +856,8 @@ console.log(obj); #### 정답: C -같은 이름의 키를 두 개 가지고 있다면, 여전히 첫 번째 위치에 있지만, 마지막에 지정된 값으로 대체될 거예요. +같은 이름의 키를 두 개 가지고 있다면, 여전히 첫 번째 위치에 있지만, 마지막에 지 +정된 값으로 대체될 거예요.

@@ -792,7 +875,8 @@ console.log(obj); #### 정답: A -기본적인 실행 콘텍스트는 전역 실행 문장이에요: 당신의 코드 모든 곳에서 접근할 수 있어요. +기본적인 실행 콘텍스트는 전역 실행 문장이에요: 당신의 코드 모든 곳에서 접근할 수 +있어요.

@@ -803,8 +887,8 @@ console.log(obj); ```javascript for (let i = 1; i < 5; i++) { - if (i === 3) continue; - console.log(i); + if (i === 3) continue + console.log(i) } ``` @@ -829,12 +913,12 @@ for (let i = 1; i < 5; i++) { ```javascript String.prototype.giveLydiaPizza = () => { - return "Just give Lydia pizza already!"; -}; + return 'Just give Lydia pizza already!' +} -const name = "Lydia"; +const name = 'Lydia' -name.giveLydiaPizza(); +name.giveLydiaPizza() ``` - A: `"Just give Lydia pizza already!"` @@ -847,7 +931,9 @@ name.giveLydiaPizza(); #### 정답: A -`String`은 내장 생성자로 속성을 추가할 수 있어요. 단지 프로토타입이라는 메소드를 추가했어요. 원시형 문자열은 문자열 프로토타입 함수에 의해 생성된 문자열 객체로 자동 변환돼요. 그래서, 모든 문자열(문자열 객체)은 그 메소드에 접근할 수 있어요! +`String`은 내장 생성자로 속성을 추가할 수 있어요. 단지 프로토타입이라는 메소드를 +추가했어요. 원시형 문자열은 문자열 프로토타입 함수에 의해 생성된 문자열 객체로 +자동 변환돼요. 그래서, 모든 문자열(문자열 객체)은 그 메소드에 접근할 수 있어요!

@@ -857,14 +943,14 @@ name.giveLydiaPizza(); ###### 29. 무엇이 출력 될까요? ```javascript -const a = {}; -const b = { key: "b" }; -const c = { key: "c" }; +const a = {} +const b = { key: 'b' } +const c = { key: 'c' } -a[b] = 123; -a[c] = 456; +a[b] = 123 +a[c] = 456 -console.log(a[b]); +console.log(a[b]) ``` - A: `123` @@ -877,11 +963,16 @@ console.log(a[b]); #### 정답: B -객체 키는 자동으로 문자열로 변환돼요. 객체 `a`의 키 값으로 `123`을 세팅하려고 해요. +객체 키는 자동으로 문자열로 변환돼요. 객체 `a`의 키 값으로 `123`을 세팅하려고 해 +요. -그러나, 객체를 문자열화 하면 `"[object Object]"`가 돼요. 그래서 여기서 말하고자 하는 건 `a["object Object"] = 123`이라는 거예요. 그 후, 같은 일을 다시 시도해요. `c`는 암묵적으로 문자열화 한 다른 객체에요. 그래서 `a["object Object"] = 456`이 돼요. +그러나, 객체를 문자열화 하면 `"[object Object]"`가 돼요. 그래서 여기서 말하고자 +하는 건 `a["object Object"] = 123`이라는 거예요. 그 후, 같은 일을 다시 시도해요. +`c`는 암묵적으로 문자열화 한 다른 객체에요. 그래서 `a["object Object"] = 456`이 +돼요. -그 후, `a[b]`는 출력하면 실제로는 `a["object Object"]`에요. 단지 `456`을 설정했기 때문에, `456`을 리턴해요. +그 후, `a[b]`는 출력하면 실제로는 `a["object Object"]`에요. 단지 `456`을 설정했 +기 때문에, `456`을 리턴해요.

@@ -891,13 +982,13 @@ console.log(a[b]); ###### 30. 무엇이 출력 될까요? ```javascript -const foo = () => console.log("First"); -const bar = () => setTimeout(() => console.log("Second")); -const baz = () => console.log("Third"); +const foo = () => console.log('First') +const bar = () => setTimeout(() => console.log('Second')) +const baz = () => console.log('Third') -bar(); -foo(); -baz(); +bar() +foo() +baz() ``` - A: `First` `Second` `Third` @@ -912,9 +1003,11 @@ baz(); 처음에 `setTimeout`함수를 호출했어요. 그러나 그것은 마지막에 출력돼요. -브라우저에는 런타임 엔진뿐만 아니라 `WebAPI`라고 불리는 것도 있기 때문이에요. `WebAPI`는 `setTimeout`함수를 최초에 부여하는데, DOM을 예로 들 수 있어요. +브라우저에는 런타임 엔진뿐만 아니라 `WebAPI`라고 불리는 것도 있기 때문이에요. +`WebAPI`는 `setTimeout`함수를 최초에 부여하는데, DOM을 예로 들 수 있어요. -_callback_ 이 WebAPI에 푸시된 후, `setTimeout`함수 자체(callback이 아니에요!)는 stack에 사라졌어요. +_callback_ 이 WebAPI에 푸시된 후, `setTimeout`함수 자체(callback이 아니에요!)는 +stack에 사라졌어요. @@ -926,11 +1019,13 @@ _callback_ 이 WebAPI에 푸시된 후, `setTimeout`함수 자체(callback이 -WebAPI는 준비가 될 때마다 stack에 항목을 추가할 수 없어요. 대신에, _queue_ 라고 불리는 것에 callback 함수를 푸시해요. +WebAPI는 준비가 될 때마다 stack에 항목을 추가할 수 없어요. 대신에, _queue_ 라고 +불리는 것에 callback 함수를 푸시해요. -여기서 event loop가 작동하기 시작해요. **event loop**는 stack과 task queue를 봐요. stack이 비어있다면, queue에 첫 번째의 것을 가져다가 stack 위로 푸시해요. +여기서 event loop가 작동하기 시작해요. **event loop**는 stack과 task queue를 봐 +요. stack이 비어있다면, queue에 첫 번째의 것을 가져다가 stack 위로 푸시해요. @@ -946,9 +1041,7 @@ WebAPI는 준비가 될 때마다 stack에 항목을 추가할 수 없어요. ```html
- +
``` @@ -963,7 +1056,8 @@ WebAPI는 준비가 될 때마다 stack에 항목을 추가할 수 없어요. #### 정답: C -가장 깊이 중첩된 요소가 이벤트를 발생시킬 이벤트 대상이에요. `event.stopPropagation`을 통해서 버블링을 중단할 수 있어요. +가장 깊이 중첩된 요소가 이벤트를 발생시킬 이벤트 대상이에요. +`event.stopPropagation`을 통해서 버블링을 중단할 수 있어요.

@@ -974,9 +1068,7 @@ WebAPI는 준비가 될 때마다 stack에 항목을 추가할 수 없어요. ```html
-

- Click here! -

+

Click here!

``` @@ -990,7 +1082,10 @@ WebAPI는 준비가 될 때마다 stack에 항목을 추가할 수 없어요. #### 정답: A -`p`를 클릭하면, 2개의 로그를 볼 수 있어요: `p` 그리고 `div`. 이벤트의 전파 중에는 3단계가 있어요: 캡처링, 타겟, 버블링. 기본적으로, 이벤트 핸들러는 버블링 단계에서 시작돼요. (`useCapture`를 `true`로 설정하지 않는 한). 가장 깊게 중첩된 요소로부터 바깥쪽으로 나가요. +`p`를 클릭하면, 2개의 로그를 볼 수 있어요: `p` 그리고 `div`. 이벤트의 전파 중에 +는 3단계가 있어요: 캡처링, 타겟, 버블링. 기본적으로, 이벤트 핸들러는 버블링 단계 +에서 시작돼요. (`useCapture`를 `true`로 설정하지 않는 한). 가장 깊게 중첩된 요소 +로부터 바깥쪽으로 나가요.

@@ -1000,14 +1095,14 @@ WebAPI는 준비가 될 때마다 stack에 항목을 추가할 수 없어요. ###### 33. 무엇이 출력 될까요? ```javascript -const person = { name: "Lydia" }; +const person = { name: 'Lydia' } function sayHi(age) { - console.log(`${this.name} is ${age}`); + console.log(`${this.name} is ${age}`) } -sayHi.call(person, 21); -sayHi.bind(person, 21); +sayHi.call(person, 21) +sayHi.bind(person, 21) ``` - A: `undefined is 21` `Lydia is 21` @@ -1020,9 +1115,11 @@ sayHi.bind(person, 21); #### 정답: D -두 개 모두, `this` 키워드를 참조하고자 하는 객체로 보낼 수 있어요. 그러나, `.call`은 _즉시 실행돼요_! +두 개 모두, `this` 키워드를 참조하고자 하는 객체로 보낼 수 있어요. 그러나, +`.call`은 _즉시 실행돼요_! -`.bind.`는 함수의 _복사본_ 을 리턴하지만, 바인딩 콘텍스트죠! 이건 즉시 실행되지 않아요. +`.bind.`는 함수의 _복사본_ 을 리턴하지만, 바인딩 콘텍스트죠! 이건 즉시 실행되지 +않아요.

@@ -1033,10 +1130,10 @@ sayHi.bind(person, 21); ```javascript function sayHi() { - return (() => 0)(); + return (() => 0)() } -console.log(typeof sayHi()); +console.log(typeof sayHi()) ``` - A: `"object"` @@ -1049,9 +1146,12 @@ console.log(typeof sayHi()); #### 정답: B -`sayHi`함수는 즉시 호출 함수(IIFE)로서 리턴된 값을 리턴해요. 이 함수는 `0`을 리턴하고, 형은 `"number"`이에요. +`sayHi`함수는 즉시 호출 함수(IIFE)로서 리턴된 값을 리턴해요. 이 함수는 `0`을 리 +턴하고, 형은 `"number"`이에요. -참고: 단 7개의 내장형이 있어요: `null`, `undefined`, `boolean`, `number`, `string`, `object`, `symbol` 그리고 `bigint`. `"function"`은 객체이기 때문에 형이 아니라 `"object"`형이에요. +참고: 단 7개의 내장형이 있어요: `null`, `undefined`, `boolean`, `number`, +`string`, `object`, `symbol` 그리고 `bigint`. `"function"`은 객체이기 때문에 형 +이 아니라 `"object"`형이에요.

@@ -1061,12 +1161,12 @@ console.log(typeof sayHi()); ###### 35. 이 값들 중 어느 것이 거짓 같은 값 일까요? ```javascript -0; -new Number(0); -(""); -(" "); -new Boolean(false); -undefined; +0 +new Number(0) +;('') +;(' ') +new Boolean(false) +undefined ``` - A: `0`, `''`, `undefined` @@ -1098,7 +1198,7 @@ undefined; ###### 36. 무엇이 출력 될까요? ```javascript -console.log(typeof typeof 1); +console.log(typeof typeof 1) ``` - A: `"number"` @@ -1111,8 +1211,7 @@ console.log(typeof typeof 1); #### 정답: B -`typeof 1` 은 `"number"`를 리턴해요. -`typeof "number"`은 `"string"`을 리턴해요. +`typeof 1` 은 `"number"`를 리턴해요. `typeof "number"`은 `"string"`을 리턴해요.

@@ -1122,9 +1221,9 @@ console.log(typeof typeof 1); ###### 37. 무엇이 출력 될까요? ```javascript -const numbers = [1, 2, 3]; -numbers[10] = 11; -console.log(numbers); +const numbers = [1, 2, 3] +numbers[10] = 11 +console.log(numbers) ``` - A: `[1, 2, 3, 7 x null, 11]` @@ -1137,12 +1236,14 @@ console.log(numbers); #### 정답: C -배열의 길이를 초과한 값을 배열의 요소로 설정하고자 할 때, JavaScript는 "empty slots"라고 불리는 것을 생성해요. 이것은 실제로 `undefined`의 값을 가지고 있지만, 다음과 같은 것을 보게 될 거예요: +배열의 길이를 초과한 값을 배열의 요소로 설정하고자 할 때, JavaScript는 "empty +slots"라고 불리는 것을 생성해요. 이것은 실제로 `undefined`의 값을 가지고 있지만, +다음과 같은 것을 보게 될 거예요: `[1, 2, 3, 7 x empty, 11]` -depending on where you run it (it's different for every browser, node, etc.) -실행 위치에 따라 달라요 (브라우저, node 등마다 달라요.) +depending on where you run it (it's different for every browser, node, etc.) 실 +행 위치에 따라 달라요 (브라우저, node 등마다 달라요.)

@@ -1152,17 +1253,17 @@ depending on where you run it (it's different for every browser, node, etc.) ###### 38. 무엇이 출력 될까요? ```javascript -(() => { - let x, y; +;(() => { + let x, y try { - throw new Error(); + throw new Error() } catch (x) { - (x = 1), (y = 2); - console.log(x); + ;(x = 1), (y = 2) + console.log(x) } - console.log(x); - console.log(y); -})(); + console.log(x) + console.log(y) +})() ``` - A: `1` `undefined` `2` @@ -1175,11 +1276,15 @@ depending on where you run it (it's different for every browser, node, etc.) #### 정답: A -`catch`블록은 `x`의 인수를 받아요. 이것은 인수를 전달할 때 변수로서의 `x`와는 달라요. 이 `x` 변수는 블록-스코프예요. +`catch`블록은 `x`의 인수를 받아요. 이것은 인수를 전달할 때 변수로서의 `x`와는 달 +라요. 이 `x` 변수는 블록-스코프예요. -후에, 블록-스코프 변수는 `1`로 설정하고, 변수 `y`의 값을 설정해요. 여기서, 블록-스코프의 변수 `x`를 출력하는데, 이것은 `1`이에요. +후에, 블록-스코프 변수는 `1`로 설정하고, 변수 `y`의 값을 설정해요. 여기서, 블록- +스코프의 변수 `x`를 출력하는데, 이것은 `1`이에요. -`catch` 블록 밖에서, `x`는 여전히 `undefined`이고 `y`는 `2`이에요. `catch` 블록 밖에서 `console.log(x)`를 출력하면, `undefined`를 리턴하고. 그리고 `y`는 `2`를 리턴해요. +`catch` 블록 밖에서, `x`는 여전히 `undefined`이고 `y`는 `2`이에요. `catch` 블록 +밖에서 `console.log(x)`를 출력하면, `undefined`를 리턴하고. 그리고 `y`는 `2`를 +리턴해요.

@@ -1200,9 +1305,15 @@ depending on where you run it (it's different for every browser, node, etc.) JavaScript는 원시형과 객체만 가지고 있어요. -원시형은 `boolean`, `null`, `undefined`, `bigint`, `number`, `string` 그리고 `symbol`이 있어요. +원시형은 `boolean`, `null`, `undefined`, `bigint`, `number`, `string` 그리고 +`symbol`이 있어요. -원시형과 객체를 구별하는 법은 원시형에는 속성이나 메소드가 없어요. 그러나 `'foo'.toUpperCase()`는 `'FOO'`로 평가되어, `TypeError`의 결과가 되지 않아요. 문자열과 같은 원시형이 속성 또는 메소드에 접근하려고 할 때, JavaScript는 래퍼 클래스 중 하나인 `String`을 사용하여 암묵적으로 감싸고, 표현 식이 평가된 후 즉시 래퍼를 폐기하기 때문이에요. `null` 그리고 `undefined`를 제외한 모든 원시형은 이러한 행동을 합니다. +원시형과 객체를 구별하는 법은 원시형에는 속성이나 메소드가 없어요. 그러나 +`'foo'.toUpperCase()`는 `'FOO'`로 평가되어, `TypeError`의 결과가 되지 않아요. 문 +자열과 같은 원시형이 속성 또는 메소드에 접근하려고 할 때, JavaScript는 래퍼 클래 +스 중 하나인 `String`을 사용하여 암묵적으로 감싸고, 표현 식이 평가된 후 즉시 래 +퍼를 폐기하기 때문이에요. `null` 그리고 `undefined`를 제외한 모든 원시형은 이러 +한 행동을 합니다.

@@ -1212,12 +1323,15 @@ JavaScript는 원시형과 객체만 가지고 있어요. ###### 40. 무엇이 출력 될까요? ```javascript -[[0, 1], [2, 3]].reduce( +;[ + [0, 1], + [2, 3], +].reduce( (acc, cur) => { - return acc.concat(cur); + return acc.concat(cur) }, - [1, 2] -); + [1, 2], +) ``` - A: `[0, 1, 2, 3, 1, 2]` @@ -1230,9 +1344,12 @@ JavaScript는 원시형과 객체만 가지고 있어요. #### 정답: C -`[1, 2]`은 초깃값이에요. 이것이 최초의 값으로, 제일 처음의 `acc`의 값이에요. 처음 라운드 동안에 `acc`는 `[1,2]`이며, `cur`은 `[0, 1]`이에요. 그것들을 연결하면 결과적으로 `[1, 2, 0, 1]`이 돼요. +`[1, 2]`은 초깃값이에요. 이것이 최초의 값으로, 제일 처음의 `acc`의 값이에요. 처 +음 라운드 동안에 `acc`는 `[1,2]`이며, `cur`은 `[0, 1]`이에요. 그것들을 연결하면 +결과적으로 `[1, 2, 0, 1]`이 돼요. -그 후, `[1, 2, 0, 1]`은 `acc`이고, `[2, 3]`은 `cur`이 에요. 그것들을 연결하면 `[1, 2, 0, 1, 2, 3]`을 얻게 돼요. +그 후, `[1, 2, 0, 1]`은 `acc`이고, `[2, 3]`은 `cur`이 에요. 그것들을 연결하면 +`[1, 2, 0, 1, 2, 3]`을 얻게 돼요.

@@ -1242,9 +1359,9 @@ JavaScript는 원시형과 객체만 가지고 있어요. ###### 41. 무엇이 출력 될까요? ```javascript -!!null; -!!""; -!!1; +!!null +!!'' +!!1 ``` - A: `false` `true` `false` @@ -1257,9 +1374,11 @@ JavaScript는 원시형과 객체만 가지고 있어요. #### 정답: B -`null`은 거짓 같은 값이에요. `!null`은 `true`를 리턴해요. `!true`는 `false`를 리턴해요. +`null`은 거짓 같은 값이에요. `!null`은 `true`를 리턴해요. `!true`는 `false`를 리 +턴해요. -`""` 은 거짓 같은 값이에요. `!""`은 `true`를 리턴해요. `!true`는 `false`를 리턴해요. +`""` 은 거짓 같은 값이에요. `!""`은 `true`를 리턴해요. `!true`는 `false`를 리턴 +해요. `1`은 참 같은 값이에요. `!1`은 `false`를 리턴해요. `!false`는`true`를 리턴해요. @@ -1271,7 +1390,7 @@ JavaScript는 원시형과 객체만 가지고 있어요. ###### 42. `setInterval` 메소드는 브라우저에게 무엇을 리턴 할까요? ```javascript -setInterval(() => console.log("Hi"), 1000); +setInterval(() => console.log('Hi'), 1000) ``` - A: 유니크한 id @@ -1284,7 +1403,8 @@ setInterval(() => console.log("Hi"), 1000); #### 정답: A -이것은 유니크한 id를 리턴해요. 이 id는 `clearInterval()` 함수로 간격을 없애기 위해 사용될 수 있어요. +이것은 유니크한 id를 리턴해요. 이 id는 `clearInterval()` 함수로 간격을 없애기 위 +해 사용될 수 있어요.

@@ -1294,7 +1414,7 @@ setInterval(() => console.log("Hi"), 1000); ###### 43. 이것은 무엇을 리턴할까요? ```javascript -[..."Lydia"]; +;[...'Lydia'] ``` - A: `["L", "y", "d", "i", "a"]` @@ -1307,7 +1427,8 @@ setInterval(() => console.log("Hi"), 1000); #### 정답: A -문자열은 반복 가능한 객체예요. 스프레드 연산자는 반복 가능한 객체의 모든 문자를 1개의 요소로 매핑해요. +문자열은 반복 가능한 객체예요. 스프레드 연산자는 반복 가능한 객체의 모든 문자를 +1개의 요소로 매핑해요.

@@ -1318,14 +1439,14 @@ setInterval(() => console.log("Hi"), 1000); ```javascript function* generator(i) { - yield i; - yield i * 2; + yield i + yield i * 2 } -const gen = generator(10); +const gen = generator(10) -console.log(gen.next().value); -console.log(gen.next().value); +console.log(gen.next().value) +console.log(gen.next().value) ``` - A: `[0, 10], [10, 20]` @@ -1338,11 +1459,19 @@ console.log(gen.next().value); #### 정답: C -보통의 함수는 호출 후에 중단할 수 없어요. 하지만, 제너레이터 함수는 중간에 "멈췄다가", 나중에 중단된 부분부터 계속할 수 있어요. 제너레이터 함수는 `yield` 키워드를 만날 때마다, yield 뒤에 지정된 값을 넘겨줘요. 제너레이터 함수에서는 값을 _리턴_ 하지 않고, _넘겨준다_ 는 것을 유의하세요. +보통의 함수는 호출 후에 중단할 수 없어요. 하지만, 제너레이터 함수는 중간에 "멈췄 +다가", 나중에 중단된 부분부터 계속할 수 있어요. 제너레이터 함수는 `yield` 키워드 +를 만날 때마다, yield 뒤에 지정된 값을 넘겨줘요. 제너레이터 함수에서는 값을 _리 +턴_ 하지 않고, _넘겨준다_ 는 것을 유의하세요. -우선, 제너레이터 함수에서 `i`를 `10`으로 초기화해요. `next()` 메소드를 사용해 제너레이터 함수를 호출해요. 처음에 제너레이터 함수를 호출하면, `i`은 `10`이에요. 첫 번째 `yield` 키워드를 만났어요: 그것은 `i`의 값을 넘겨줘요. 이제 제너레이터는 "멈추고", `10`을 출력해요. +우선, 제너레이터 함수에서 `i`를 `10`으로 초기화해요. `next()` 메소드를 사용해 제 +너레이터 함수를 호출해요. 처음에 제너레이터 함수를 호출하면, `i`은 `10`이에요. +첫 번째 `yield` 키워드를 만났어요: 그것은 `i`의 값을 넘겨줘요. 이제 제너레이터는 +"멈추고", `10`을 출력해요. -그 후, `next()` 메소드를 사용해 다시 한번 함수를 호출해요. `i`는 여전히 `10`이에요. 이제, 다음 `yield` 키워드를 만나 `i * 2`를 넘겨줘요. `i`는 `10`이므로, `10 * 2`, 즉 `20`을 리턴해요. 결과는 `10, 20`이에요. +그 후, `next()` 메소드를 사용해 다시 한번 함수를 호출해요. `i`는 여전히 `10`이에 +요. 이제, 다음 `yield` 키워드를 만나 `i * 2`를 넘겨줘요. `i`는 `10`이므로, +`10 * 2`, 즉 `20`을 리턴해요. 결과는 `10, 20`이에요.

@@ -1353,14 +1482,14 @@ console.log(gen.next().value); ```javascript const firstPromise = new Promise((res, rej) => { - setTimeout(res, 500, "one"); -}); + setTimeout(res, 500, 'one') +}) const secondPromise = new Promise((res, rej) => { - setTimeout(res, 100, "two"); -}); + setTimeout(res, 100, 'two') +}) -Promise.race([firstPromise, secondPromise]).then(res => console.log(res)); +Promise.race([firstPromise, secondPromise]).then(res => console.log(res)) ``` - A: `"one"` @@ -1373,7 +1502,11 @@ Promise.race([firstPromise, secondPromise]).then(res => console.log(res)); #### 정답: B -복수의 프로미스를 `Promise.race` 메소드에 넘겨주면, _최초_ 의 프로미스를 해결/거부해요. `setTimeout` 메소드에 타이머를 전달해요: 첫 번째 프로미스(`firstPromise`)에는 500ms, 두 번째 프로미스(`secondPromise`)에는 100ms. 이것은 `'two'`의 값을 가진 `secondPromise`가 최초로 해결한다는 것을 의미해요. 이제 `res`는 `'two'`의 값을 유지하고 출력돼요. +복수의 프로미스를 `Promise.race` 메소드에 넘겨주면, _최초_ 의 프로미스를 해결/거 +부해요. `setTimeout` 메소드에 타이머를 전달해요: 첫 번째 프로미스 +(`firstPromise`)에는 500ms, 두 번째 프로미스(`secondPromise`)에는 100ms. 이것은 +`'two'`의 값을 가진 `secondPromise`가 최초로 해결한다는 것을 의미해요. 이제 +`res`는 `'two'`의 값을 유지하고 출력돼요.

@@ -1383,11 +1516,11 @@ Promise.race([firstPromise, secondPromise]).then(res => console.log(res)); ###### 46. 무엇이 출력 될까요? ```javascript -let person = { name: "Lydia" }; -const members = [person]; -person = null; +let person = { name: 'Lydia' } +const members = [person] +person = null -console.log(members); +console.log(members) ``` - A: `null` @@ -1404,7 +1537,10 @@ console.log(members); -그 후, `members`라는 변수를 선언해요. 배열의 첫 번째 요소에 `person` 변수의 값을 대입해요. 서로를 같게 설정하면 _참조_ 에 의해 상호작용해요. 어떤 변수에서 다른 변수로 참조를 할당하면, 그 참조의 _복사본_ 을 만들어요. (그들은 _같은_ 참조를 가지고 있지 않다는 것을 유의하세요!) +그 후, `members`라는 변수를 선언해요. 배열의 첫 번째 요소에 `person` 변수의 값을 +대입해요. 서로를 같게 설정하면 _참조_ 에 의해 상호작용해요. 어떤 변수에서 다른 +변수로 참조를 할당하면, 그 참조의 _복사본_ 을 만들어요. (그들은 _같은_ 참조를 가 +지고 있지 않다는 것을 유의하세요!) @@ -1412,7 +1548,11 @@ console.log(members); -배열의 첫 번째 요소는 객체에 대한 다른 (복사된) 참조를 가지고 있기 때문에, `person` 변수의 값만 변경하고, 배열의 첫 번째 요소는 변경할 수 없어요. `members`의 첫 번째 요소는 여전히 원본 객체에 대한 참조를 유지하고 있어요. `members` 배열을 출력할 때, 첫 번째 요소는 여전히 객체의 값을 유지하고 있어 로그가 출력돼요. +배열의 첫 번째 요소는 객체에 대한 다른 (복사된) 참조를 가지고 있기 때문에, +`person` 변수의 값만 변경하고, 배열의 첫 번째 요소는 변경할 수 없어요. +`members`의 첫 번째 요소는 여전히 원본 객체에 대한 참조를 유지하고 있어요. +`members` 배열을 출력할 때, 첫 번째 요소는 여전히 객체의 값을 유지하고 있어 로그 +가 출력돼요.

@@ -1423,12 +1563,12 @@ console.log(members); ```javascript const person = { - name: "Lydia", - age: 21 -}; + name: 'Lydia', + age: 21, +} for (const item in person) { - console.log(item); + console.log(item) } ``` @@ -1442,7 +1582,10 @@ for (const item in person) { #### 정답: B -`for-in` 루프를 사용하면, 객체 키를 통해서 반복할 수 있는데, 이 경우에서는 `name` 그리고 `age`에요. 내부적으로, 객체 키는 문자열이에요 (심볼이 아니라면 말이죠). 모든 루프에서, `item`의 값은 반복된 현재의 키 값으로 설정해요. 우선, `item`은 `name`으로 출력돼요. 그 후, `item`은 `age`로 출력돼요. +`for-in` 루프를 사용하면, 객체 키를 통해서 반복할 수 있는데, 이 경우에서는 +`name` 그리고 `age`에요. 내부적으로, 객체 키는 문자열이에요 (심볼이 아니라면 말 +이죠). 모든 루프에서, `item`의 값은 반복된 현재의 키 값으로 설정해요. 우선, +`item`은 `name`으로 출력돼요. 그 후, `item`은 `age`로 출력돼요.

@@ -1452,7 +1595,7 @@ for (const item in person) { ###### 48. 무엇이 출력 될까요? ```javascript -console.log(3 + 4 + "5"); +console.log(3 + 4 + '5') ``` - A: `"345"` @@ -1465,11 +1608,15 @@ console.log(3 + 4 + "5"); #### 정답: B -연산자 결합성은 왼쪽에서 오른쪽 또는 오른쪽에서 왼쪽으로 컴파일러가 표현 식을 평가하는 순서가 돼요. 이것은 연산자가 _같은_ 우선순위를 가진 경우에만 해당돼요. 연산자의 종류는 한 개뿐이에요: `+`. 게다가, 결합성은 왼쪽에서 오른쪽이에요. +연산자 결합성은 왼쪽에서 오른쪽 또는 오른쪽에서 왼쪽으로 컴파일러가 표현 식을 평 +가하는 순서가 돼요. 이것은 연산자가 _같은_ 우선순위를 가진 경우에만 해당돼요. 연 +산자의 종류는 한 개뿐이에요: `+`. 게다가, 결합성은 왼쪽에서 오른쪽이에요. 처음으로 `3 + 4`가 평가돼요. 결과는 숫자 `7`이에요. -`7 + '5'`의 결과는 강제성 때문에 `"75"`가 돼요. JavaScript는 숫자 `7`을 문자열로 변환하고, (자세한 내용은) 질문 15를 보세요. `+` 연산자를 사용해서 두 개의 문자열을 연결할 수 있어요. `"7" + "5"`의 결과는 `"75"`이에요. +`7 + '5'`의 결과는 강제성 때문에 `"75"`가 돼요. JavaScript는 숫자 `7`을 문자열로 +변환하고, (자세한 내용은) 질문 15를 보세요. `+` 연산자를 사용해서 두 개의 문자열 +을 연결할 수 있어요. `"7" + "5"`의 결과는 `"75"`이에요.

@@ -1479,7 +1626,7 @@ console.log(3 + 4 + "5"); ###### 49. `num`의 값은 무엇일까요? ```javascript -const num = parseInt("7*6", 10); +const num = parseInt('7*6', 10) ``` - A: `42` @@ -1492,9 +1639,13 @@ const num = parseInt("7*6", 10); #### 정답: C -문자열의 첫 번째 숫자만 리턴돼요. _진법_ 에 근거하여 (파싱하고자 하는 숫자의 기준을 명시하기 위한 두 번째 인수: 기본적인 10진수, 6진수, 8진수, 2진수 등), `parseInt`는 문자열 내의 문자가 타당한지 여부를 확인해요. 진수에 유효한 숫자가 아닌 문자를 만나면, 파싱을 멈추고, 다음 문자를 무시해요. +문자열의 첫 번째 숫자만 리턴돼요. _진법_ 에 근거하여 (파싱하고자 하는 숫자의 기 +준을 명시하기 위한 두 번째 인수: 기본적인 10진수, 6진수, 8진수, 2진수 등), +`parseInt`는 문자열 내의 문자가 타당한지 여부를 확인해요. 진수에 유효한 숫자가 +아닌 문자를 만나면, 파싱을 멈추고, 다음 문자를 무시해요. -`*`은 유효한 숫자가 아니에요. `"7"`만 십진수의 `7`로 파싱 돼요. 이제 `num`은 `7`의 값을 유지해요. +`*`은 유효한 숫자가 아니에요. `"7"`만 십진수의 `7`로 파싱 돼요. 이제 `num`은 +`7`의 값을 유지해요.

@@ -1504,10 +1655,10 @@ const num = parseInt("7*6", 10); ###### 50. 무엇이 출력 될까요? ```javascript -[1, 2, 3].map(num => { - if (typeof num === "number") return; - return num * 2; - }); +;[1, 2, 3].map(num => { + if (typeof num === 'number') return + return num * 2 +}) ``` - A: `[]` @@ -1520,9 +1671,13 @@ const num = parseInt("7*6", 10); #### 정답: C -배열을 매핑할 때, `num`의 값은 헌재 순환하고 있는 요소예요. 이 경우, 요소는 숫자이기 때문에, if 문의 조건 `typeof num === "number"`는 `true`를 리턴해요. map 합수는 새로운 배열을 만들고 함수에서 리턴된 값을 삽입해요. +배열을 매핑할 때, `num`의 값은 헌재 순환하고 있는 요소예요. 이 경우, 요소는 숫자 +이기 때문에, if 문의 조건 `typeof num === "number"`는 `true`를 리턴해요. map 합 +수는 새로운 배열을 만들고 함수에서 리턴된 값을 삽입해요. -그러나, 값을 리턴하지 않아요. 함수는 값을 리턴하지 않을 때, `undefined`를 리턴해요. 배열에서의 모든 요소에 대해 블록 함수가 호출되기 때문에, 각 요소에 대해 `undefined`를 리턴해요. +그러나, 값을 리턴하지 않아요. 함수는 값을 리턴하지 않을 때, `undefined`를 리턴해 +요. 배열에서의 모든 요소에 대해 블록 함수가 호출되기 때문에, 각 요소에 대해 +`undefined`를 리턴해요.

@@ -1533,16 +1688,16 @@ const num = parseInt("7*6", 10); ```javascript function getInfo(member, year) { - member.name = "Lydia"; - year = "1998"; + member.name = 'Lydia' + year = '1998' } -const person = { name: "Sarah" }; -const birthYear = "1997"; +const person = { name: 'Sarah' } +const birthYear = '1997' -getInfo(person, birthYear); +getInfo(person, birthYear) -console.log(person, birthYear); +console.log(person, birthYear) ``` - A: `{ name: "Lydia" }, "1997"` @@ -1555,11 +1710,19 @@ console.log(person, birthYear); #### 정답: A -인수들의 값이 객체가 아닌 한 _값_ 에 의해 전달돼요. 그 후 _참조_ 에 의해 전달돼요. `birthYear`는 객체가 아니라 문자열이기 때문에 값에 의해 전달돼요. 값으로 전달하면 값의 _복사본_ 이 만들어져요(질문 46을 보세요). +인수들의 값이 객체가 아닌 한 _값_ 에 의해 전달돼요. 그 후 _참조_ 에 의해 전달돼 +요. `birthYear`는 객체가 아니라 문자열이기 때문에 값에 의해 전달돼요. 값으로 전 +달하면 값의 _복사본_ 이 만들어져요(질문 46을 보세요). -변수 `birthYear`는 `"1997"`값에 대한 참조를 가져요. 인수 `year` 또한 `"1997"`에 대한 참조를 가지지만, `birthYear`가 가진 참조 값과는 달라요. `year`에 `"1998"`을 대입하여 `year`의 값을 업데이트할 때, `year`의 값만 업데이트해요. `birthYear`는 여전히 `"1997"`이에요. +변수 `birthYear`는 `"1997"`값에 대한 참조를 가져요. 인수 `year` 또한 `"1997"`에 +대한 참조를 가지지만, `birthYear`가 가진 참조 값과는 달라요. `year`에 `"1998"`을 +대입하여 `year`의 값을 업데이트할 때, `year`의 값만 업데이트해요. `birthYear`는 +여전히 `"1997"`이에요. -`person`의 값은 객체예요. 인수 `member`는 _같은_ 객체의 (복사된) 참조 값을 가져요. `member`객체의 속성이 갖는 참조를 변경하면, 두 개 모두 같은 객체를 참조 값을 가지고 있기 때문에, `person`의 값 또한 변경돼요. 이제 `person`'의 `name` 속성은값 `"Lydia"`에요. +`person`의 값은 객체예요. 인수 `member`는 _같은_ 객체의 (복사된) 참조 값을 가져 +요. `member`객체의 속성이 갖는 참조를 변경하면, 두 개 모두 같은 객체를 참조 값을 +가지고 있기 때문에, `person`의 값 또한 변경돼요. 이제 `person`'의 `name` 속성은 +값 `"Lydia"`에요.

@@ -1570,19 +1733,19 @@ console.log(person, birthYear); ```javascript function greeting() { - throw "Hello world!"; + throw 'Hello world!' } function sayHi() { try { - const data = greeting(); - console.log("It worked!", data); + const data = greeting() + console.log('It worked!', data) } catch (e) { - console.log("Oh no an error:", e); + console.log('Oh no an error:', e) } } -sayHi(); +sayHi() ``` - A: `"It worked! Hello world!"` @@ -1595,9 +1758,13 @@ sayHi(); #### 정답: D -`throw`문을 사용해, 커스텀 에러를 만들 수 있어요. 이 표현 식을 사용해, 예외를 던질 수 있어요. 예외는 string, a number, a boolean or an object이 될 수 있어요. 이 경우, 예외는 `'Hello world'` 문자열이에요. +`throw`문을 사용해, 커스텀 에러를 만들 수 있어요. 이 표현 식을 사용해, 예외를 던 +질 수 있어요. 예외는 string, a number, a boolean or an +object이 될 수 있어요. 이 경우, 예외는 `'Hello world'` 문자열이에요. -`catch` 문을 사용해, `try` 블록에서 예외가 던져졌을 경우에 무엇을 할지 명시할 수 있어요. 예외가 던져졌어요: 문자열 `'Hello world'`. `e`는 이제 문자열이고, 그것을 출력해요. 결과는 `'Oh an error: Hello world'`예요. +`catch` 문을 사용해, `try` 블록에서 예외가 던져졌을 경우에 무엇을 할지 명시할 수 +있어요. 예외가 던져졌어요: 문자열 `'Hello world'`. `e`는 이제 문자열이고, 그것을 +출력해요. 결과는 `'Oh an error: Hello world'`예요.

@@ -1608,12 +1775,12 @@ sayHi(); ```javascript function Car() { - this.make = "Lamborghini"; - return { make: "Maserati" }; + this.make = 'Lamborghini' + return { make: 'Maserati' } } -const myCar = new Car(); -console.log(myCar.make); +const myCar = new Car() +console.log(myCar.make) ``` - A: `"Lamborghini"` @@ -1626,7 +1793,8 @@ console.log(myCar.make); #### 정답: B -속성을 리턴할 때, 속성값은 생성자에 설정한 값이 아닌, _리턴된_ 값과 같아요. `"Maserati"` 문자열을 리턴하기 때문에, `myCar.make`는 `"Maserati"`에요. +속성을 리턴할 때, 속성값은 생성자에 설정한 값이 아닌, _리턴된_ 값과 같아요. +`"Maserati"` 문자열을 리턴하기 때문에, `myCar.make`는 `"Maserati"`에요.

@@ -1636,12 +1804,12 @@ console.log(myCar.make); ###### 54. 무엇이 출력 될까요? ```javascript -(() => { - let x = (y = 10); -})(); +;(() => { + let x = (y = 10) +})() -console.log(typeof x); -console.log(typeof y); +console.log(typeof x) +console.log(typeof y) ``` - A: `"undefined", "number"` @@ -1657,15 +1825,23 @@ console.log(typeof y); `let x = y = 10;`은 다음의 단축형이에요: ```javascript -y = 10; -let x = y; +y = 10 +let x = y ``` -`y`에 `10`을 대입하면, 실제로는 전역 객체에 속성 `y`를 추가해요(브라우저에서는 `window`, Node에서는 `global`). 브라우저에서, `window.y`는 이제 `10`이에요. +`y`에 `10`을 대입하면, 실제로는 전역 객체에 속성 `y`를 추가해요(브라우저에서는 +`window`, Node에서는 `global`). 브라우저에서, `window.y`는 이제 `10`이에요. -그 후, 변수 `x`를 `10`인 `y`를 값으로 선언해요. `let`키워드로 선언된 변수는 _블록 스코프_ 로, 선언된 블록 내에서만 정의돼요: 이 경우 즉시 호출 함수예요(IIFE). `typeof`연산자를 사용할 때, 피연산자 `x`는 정의되지 않았어요: 선언된 블록 밖에서 접근하려 했어요. 이것은 `x`가 선언되지 않음을 의미해요. 값을 할당하거나 선언하지 않은 변수는 `"undefined"` 형이에요. `console.log(typeof x)`는 `"undefined"`를 리턴해요. +그 후, 변수 `x`를 `10`인 `y`를 값으로 선언해요. `let`키워드로 선언된 변수는 _블 +록 스코프_ 로, 선언된 블록 내에서만 정의돼요: 이 경우 즉시 호출 함수예요(IIFE). +`typeof`연산자를 사용할 때, 피연산자 `x`는 정의되지 않았어요: 선언된 블록 밖에서 +접근하려 했어요. 이것은 `x`가 선언되지 않음을 의미해요. 값을 할당하거나 선언하지 +않은 변수는 `"undefined"` 형이에요. `console.log(typeof x)`는 `"undefined"`를 리 +턴해요. -그러나, `y`를 `10`으로 설정할 때 전역 변수 `y`를 만들었어요. 이 값은 코드 내 어디에서나 접근할 수 있어요. `y`는 정의되었고, `"number"`형의 값을 유지해요. `console.log(typeof y)`는 `"number"`을 리턴해요. +그러나, `y`를 `10`으로 설정할 때 전역 변수 `y`를 만들었어요. 이 값은 코드 내 어 +디에서나 접근할 수 있어요. `y`는 정의되었고, `"number"`형의 값을 유지해요. +`console.log(typeof y)`는 `"number"`을 리턴해요.

@@ -1677,21 +1853,21 @@ let x = y; ```javascript class Dog { constructor(name) { - this.name = name; + this.name = name } } -Dog.prototype.bark = function() { - console.log(`Woof I am ${this.name}`); -}; +Dog.prototype.bark = function () { + console.log(`Woof I am ${this.name}`) +} -const pet = new Dog("Mara"); +const pet = new Dog('Mara') -pet.bark(); +pet.bark() -delete Dog.prototype.bark; +delete Dog.prototype.bark -pet.bark(); +pet.bark() ``` - A: `"Woof I am Mara"`, `TypeError` @@ -1704,9 +1880,13 @@ pet.bark(); #### 정답: A -프로토타입에서도 `delete`키워드를 사용해, 객체로부터 속성을 삭제할 수 있어요. 프로토타입에서 속성을 삭제하면, 프로토타입 체인에서 더는 사용할 수 없게 돼요. 이 경우, `bark` 함수는 `delete Dog.prototype.bark` 후에 프로토타입에서 더는 사용할 수 없게 되지만, 그래도 여전히 그것에 접근하려고 해요. +프로토타입에서도 `delete`키워드를 사용해, 객체로부터 속성을 삭제할 수 있어요. 프 +로토타입에서 속성을 삭제하면, 프로토타입 체인에서 더는 사용할 수 없게 돼요. 이 +경우, `bark` 함수는 `delete Dog.prototype.bark` 후에 프로토타입에서 더는 사용할 +수 없게 되지만, 그래도 여전히 그것에 접근하려고 해요. -함수가 아닌 것을 호출하려고 할 때, `TypeError`가 던져져요. 이 경우 `pet.bark`는 `undefined`이기 때문에, `TypeError: pet.bark is not a function`예요. +함수가 아닌 것을 호출하려고 할 때, `TypeError`가 던져져요. 이 경우 `pet.bark`는 +`undefined`이기 때문에, `TypeError: pet.bark is not a function`예요.

@@ -1716,9 +1896,9 @@ pet.bark(); ###### 56. 무엇이 출력 될까요? ```javascript -const set = new Set([1, 1, 2, 3, 4]); +const set = new Set([1, 1, 2, 3, 4]) -console.log(set); +console.log(set) ``` - A: `[1, 1, 2, 3, 4]` @@ -1733,7 +1913,8 @@ console.log(set); `Set`은 _unique_ 값의 집합 객체예요: 값은 set 내에서 단 한 번만 발생해요. -중복 값 `1`을 가진 반복 가능한 `[1, 1, 2, 3, 4]`을 전달하기 때문에, 그들 중 하나는 삭제돼요. 이것은 결과적으로 `{1, 2, 3, 4}`돼요. +중복 값 `1`을 가진 반복 가능한 `[1, 1, 2, 3, 4]`을 전달하기 때문에, 그들 중 하나 +는 삭제돼요. 이것은 결과적으로 `{1, 2, 3, 4}`돼요.

@@ -1744,17 +1925,17 @@ console.log(set); ```javascript // counter.js -let counter = 10; -export default counter; +let counter = 10 +export default counter ``` ```javascript // index.js -import myCounter from "./counter"; +import myCounter from './counter' -myCounter += 1; +myCounter += 1 -console.log(myCounter); +console.log(myCounter) ``` - A: `10` @@ -1767,9 +1948,11 @@ console.log(myCounter); #### 정답: C -import 된 모듈은 _read-only_ 예요 : import 된 모듈은 수정할 수 없어요. export 한 모듈만 값을 변경할 수 있어요. +import 된 모듈은 _read-only_ 예요 : import 된 모듈은 수정할 수 없어요. export 한 +모듈만 값을 변경할 수 있어요. -`myCounter`의 값을 증가시키려고 할 때, 에러를 던져요: `myCounter`는 read-only이고 수정할 수 없어요. +`myCounter`의 값을 증가시키려고 할 때, 에러를 던져요: `myCounter`는 read-only이 +고 수정할 수 없어요.

@@ -1779,11 +1962,11 @@ import 된 모듈은 _read-only_ 예요 : import 된 모듈은 수정할 수 없 ###### 58. 무엇이 출력 될까요? ```javascript -const name = "Lydia"; -age = 21; +const name = 'Lydia' +age = 21 -console.log(delete name); -console.log(delete age); +console.log(delete name) +console.log(delete age) ``` - A: `false`, `true` @@ -1796,9 +1979,14 @@ console.log(delete age); #### 정답: A -`delete`연산자는 불린 값을 리턴해요: 성공적으로 삭제를 한 경우 `true`를, 그렇지 않다면 `false`를 리턴해요. 그러나, `var`, `const` 또는 `let` 키워드로 선언된 변수들은 `delete`연산자를 사용해서 삭제될 수 없어요. +`delete`연산자는 불린 값을 리턴해요: 성공적으로 삭제를 한 경우 `true`를, 그렇지 +않다면 `false`를 리턴해요. 그러나, `var`, `const` 또는 `let` 키워드로 선언된 변 +수들은 `delete`연산자를 사용해서 삭제될 수 없어요. -`name` 변수는 `const`키워드로 선언되었기 때문에, 삭제에 실패해요. `age`를 `21`로 설정할 때, 실제로는 `age`라는 속성을 전역 객체에 추가한 거죠. 이 방법으로 객체, 전역 객체의 속성들을 성공적으로 삭제할 수 있어요. `delete age`는 `true`를 리턴해요. +`name` 변수는 `const`키워드로 선언되었기 때문에, 삭제에 실패해요. `age`를 `21`로 +설정할 때, 실제로는 `age`라는 속성을 전역 객체에 추가한 거죠. 이 방법으로 객체, +전역 객체의 속성들을 성공적으로 삭제할 수 있어요. `delete age`는 `true`를 리턴해 +요.

@@ -1808,10 +1996,10 @@ console.log(delete age); ###### 59. 무엇이 출력 될까요? ```javascript -const numbers = [1, 2, 3, 4, 5]; -const [y] = numbers; +const numbers = [1, 2, 3, 4, 5] +const [y] = numbers -console.log(y); +console.log(y) ``` - A: `[[1, 2, 3, 4, 5]]` @@ -1824,10 +2012,11 @@ console.log(y); #### 정답: C -구조 분해 할당을 통해 객체의 배열 또는 속성들로부터 변수를 해체할 수 있어요. 예를 들어: +구조 분해 할당을 통해 객체의 배열 또는 속성들로부터 변수를 해체할 수 있어요. 예 +를 들어: ```javascript -[a, b] = [1, 2]; +;[a, b] = [1, 2] ``` @@ -1835,12 +2024,13 @@ console.log(y); `a`는 이제 `1`이고, `b`는 이제 `2`예요. 질문에서 실제로 한 건 다음과 같아요: ```javascript -[y] = [1, 2, 3, 4, 5]; +;[y] = [1, 2, 3, 4, 5] ``` -이것은 `y`의 값은 숫자 `1`인 배열의 첫 번째 값과 같다는 것을 의미하죠. `y`를 출력하면 `1`이 리턴돼요. +이것은 `y`의 값은 숫자 `1`인 배열의 첫 번째 값과 같다는 것을 의미하죠. `y`를 출 +력하면 `1`이 리턴돼요.

@@ -1850,10 +2040,10 @@ console.log(y); ###### 60. 무엇이 출력 될까요? ```javascript -const user = { name: "Lydia", age: 21 }; -const admin = { admin: true, ...user }; +const user = { name: 'Lydia', age: 21 } +const admin = { admin: true, ...user } -console.log(admin); +console.log(admin) ``` - A: `{ admin: true, user: { name: "Lydia", age: 21 } }` @@ -1866,7 +2056,10 @@ console.log(admin); #### 정답: B -스프레드 연산자 `...` 를 사용해 객체를 결합할 수 있어요. 이것은 하나의 객체의 키/값의 쌍들을 복사본들로 만들어, 다른 객체에 추가해요. 이 경우, `user` 객체의 복사본들을 만들어, `admin` 객체에 추가해요. `admin` 객체는 이제 복사된 키/값의 쌍들이 들어있고, 결과는 `{ admin: true, name: "Lydia", age: 21 }` 예요. +스프레드 연산자 `...` 를 사용해 객체를 결합할 수 있어요. 이것은 하나의 객체의 키 +/값의 쌍들을 복사본들로 만들어, 다른 객체에 추가해요. 이 경우, `user` 객체의 복 +사본들을 만들어, `admin` 객체에 추가해요. `admin` 객체는 이제 복사된 키/값의 쌍 +들이 들어있고, 결과는 `{ admin: true, name: "Lydia", age: 21 }` 예요.

@@ -1876,12 +2069,12 @@ console.log(admin); ###### 61. 무엇이 출력 될까요? ```javascript -const person = { name: "Lydia" }; +const person = { name: 'Lydia' } -Object.defineProperty(person, "age", { value: 21 }); +Object.defineProperty(person, 'age', { value: 21 }) -console.log(person); -console.log(Object.keys(person)); +console.log(person) +console.log(Object.keys(person)) ``` - A: `{ name: "Lydia", age: 21 }`, `["name", "age"]` @@ -1894,9 +2087,15 @@ console.log(Object.keys(person)); #### 정답: B -`defineProperty`메소드로, 객체에 새로운 속성들을 추가하거나, 기존 것을 수정할 수 있어요. `defineProperty` 메소드를 사용해 객체의 속성을 추가할 때, 기본적으로 객체의 속성들은 _비 열거자_ 예요. `Object.keys`메소드는 모든 _열거자_ 객체의 속성 이름들을 리턴하는데, 이 경우는 `"name"` 뿐이에요. +`defineProperty`메소드로, 객체에 새로운 속성들을 추가하거나, 기존 것을 수정할 수 +있어요. `defineProperty` 메소드를 사용해 객체의 속성을 추가할 때, 기본적으로 객 +체의 속성들은 _비 열거자_ 예요. `Object.keys`메소드는 모든 _열거자_ 객체의 속성 +이름들을 리턴하는데, 이 경우는 `"name"` 뿐이에요. -`defineProperty`를 사용해 추가된 속성들은 기본적으로 변경할 수 없어요. `writable`, `configurable` 그리고 `enumerable` 속성들을 사용해 덮어쓰기 할 수 있어요. `defineProperty`메소드의 방법은 객체에 추가할 속성들을 훨씬 더 정교하게 제어하도록 해줘요. +`defineProperty`를 사용해 추가된 속성들은 기본적으로 변경할 수 없어요. +`writable`, `configurable` 그리고 `enumerable` 속성들을 사용해 덮어쓰기 할 수 있 +어요. `defineProperty`메소드의 방법은 객체에 추가할 속성들을 훨씬 더 정교하게 제 +어하도록 해줘요.

@@ -1907,13 +2106,13 @@ console.log(Object.keys(person)); ```javascript const settings = { - username: "lydiahallie", + username: 'lydiahallie', level: 19, - health: 90 -}; + health: 90, +} -const data = JSON.stringify(settings, ["level", "health"]); -console.log(data); +const data = JSON.stringify(settings, ['level', 'health']) +console.log(data) ``` - A: `"{"level":19, "health":90}"` @@ -1926,11 +2125,16 @@ console.log(data); #### 정답: A -`JSON.stringify` 두 번째 인수는 _replacer_ 예요. replacer는 함수 또는 배열 둘 중 하나가 될 수 있고, stringify 할 대상과 방법을 제어할 수 있게 해줘요. +`JSON.stringify` 두 번째 인수는 _replacer_ 예요. replacer는 함수 또는 배열 둘 중 +하나가 될 수 있고, stringify 할 대상과 방법을 제어할 수 있게 해줘요. -replacer가 _배열_ 이라면, 배열에 이름이 포함된 속성만 JSON 문자열에 추가될 거에요. 이 경우, 이름을 가진 `"level"` 그리고 `"health"`속성들만 포함되고, `"username"`은 제외 돼요. `data` 은 이제 `"{"level":19, "health":90}"`에요. +replacer가 _배열_ 이라면, 배열에 이름이 포함된 속성만 JSON 문자열에 추가될 거에 +요. 이 경우, 이름을 가진 `"level"` 그리고 `"health"`속성들만 포함되고, +`"username"`은 제외 돼요. `data` 은 이제 `"{"level":19, "health":90}"`에요. -replacer가 _함수_ 라면, stringifying 할 객체의 모든 속성에 호출돼요. 이 함수로부터 리턴된 값은 JSON 문자열에 추가될 때 속성의 값이 될 거예요. 만약 값이 `undefined`라면, 이 속성은 JSON 문자열로부터 제외돼요. +replacer가 _함수_ 라면, stringifying 할 객체의 모든 속성에 호출돼요. 이 함수로부 +터 리턴된 값은 JSON 문자열에 추가될 때 속성의 값이 될 거예요. 만약 값이 +`undefined`라면, 이 속성은 JSON 문자열로부터 제외돼요.

@@ -1940,16 +2144,16 @@ replacer가 _함수_ 라면, stringifying 할 객체의 모든 속성에 호출 ###### 63. 무엇이 출력 될까요? ```javascript -let num = 10; +let num = 10 -const increaseNumber = () => num++; -const increasePassedNumber = number => number++; +const increaseNumber = () => num++ +const increasePassedNumber = number => number++ -const num1 = increaseNumber(); -const num2 = increasePassedNumber(num1); +const num1 = increaseNumber() +const num2 = increasePassedNumber(num1) -console.log(num1); -console.log(num2); +console.log(num1) +console.log(num2) ``` - A: `10`, `10` @@ -1962,9 +2166,14 @@ console.log(num2); #### 정답: A -단항 연산자 `++`는 _우선_ 피연산자의 값을 _리턴하고_, _그 후_ 피연산자의 값을 _증가해요_. `increaseNumber` 함수가 처음으로 리턴 한 `num`의 값은 `10` 이기 때문에, `num1`의 값은 `10`이고, 그 후엔 `num`의 값만 증가해요. +단항 연산자 `++`는 _우선_ 피연산자의 값을 _리턴하고_, _그 후_ 피연산자의 값을 +_증가해요_. `increaseNumber` 함수가 처음으로 리턴 한 `num`의 값은 `10` 이기 때문 +에, `num1`의 값은 `10`이고, 그 후엔 `num`의 값만 증가해요. -`num1`을 `increasePassedNumber`로 전달했기 때문에, `num2`는 `10`이에요. `number`는 `10`이에요(`num1`의 값은, 다시 한번, 단항 연산자가 `++`는 _우선_ 피연산자의 값을 _리턴하고_, _그 후_ 피연산자의 값을 _증가해요_. `number`의 값은 `10`이에요 즉, `num2`는 `10`이죠. +`num1`을 `increasePassedNumber`로 전달했기 때문에, `num2`는 `10`이에요. +`number`는 `10`이에요(`num1`의 값은, 다시 한번, 단항 연산자가 `++`는 _우선_ 피연 +산자의 값을 _리턴하고_, _그 후_ 피연산자의 값을 _증가해요_. `number`의 값은 +`10`이에요 즉, `num2`는 `10`이죠.

@@ -1974,16 +2183,16 @@ console.log(num2); ###### 64. 무엇이 출력 될까요? ```javascript -const value = { number: 10 }; +const value = { number: 10 } const multiply = (x = { ...value }) => { - console.log(x.number *= 2); -}; + console.log((x.number *= 2)) +} -multiply(); -multiply(); -multiply(value); -multiply(value); +multiply() +multiply() +multiply(value) +multiply(value) ``` - A: `20`, `40`, `80`, `160` @@ -1996,13 +2205,22 @@ multiply(value); #### 정답: C -ES6에서는, 기본값으로 파라미터를 초기화할 수 있어요. 함수에 값이 없이 전달되거나, 파라미터의 값이 `"undefined"`라면, 파라미터의 값은 기본값이 될 거예요. 이 경우, `value` 객체의 속성들을 새로운 객체 안으로 전개해요. 따라서 `x`는 `{ number: 10 }`을 기본값으로 가져요. +ES6에서는, 기본값으로 파라미터를 초기화할 수 있어요. 함수에 값이 없이 전달되거나 +, 파라미터의 값이 `"undefined"`라면, 파라미터의 값은 기본값이 될 거예요. 이 경우 +, `value` 객체의 속성들을 새로운 객체 안으로 전개해요. 따라서 `x`는 +`{ number: 10 }`을 기본값으로 가져요. -기본 인수는 _호출 시점_ 에 평가돼요! 함수를 부를 때마다, _새로운_ 객체를 만들어요. 처음에 두 번은 값 전달 없이 `multiply` 함수를 호출해요: `x`는 `{ number: 10 }`의 기본값을 가져요. 그다음 그 숫자를 곱셈한 값인 `20`을 출력해요. +기본 인수는 _호출 시점_ 에 평가돼요! 함수를 부를 때마다, _새로운_ 객체를 만들어 +요. 처음에 두 번은 값 전달 없이 `multiply` 함수를 호출해요: `x`는 +`{ number: 10 }`의 기본값을 가져요. 그다음 그 숫자를 곱셈한 값인 `20`을 출력해요 +. -세 번째로 곱셈을 호출할 때, 인수를 전달해요: 그 객체는 `value`를 불러요. `*=` 연산자는 실제로는 `x.number = x.number * 2`의 줄임말이에요: `x.number`의 값을 변경하고, 곱셈한 값 `20`을 출력해요 +세 번째로 곱셈을 호출할 때, 인수를 전달해요: 그 객체는 `value`를 불러요. `*=` 연 +산자는 실제로는 `x.number = x.number * 2`의 줄임말이에요: `x.number`의 값을 변경 +하고, 곱셈한 값 `20`을 출력해요 -네 번째에는, `value` 객체를 다시 한번 전달해요. `x.number`는 이전에 `20`으로 바뀌었기 때문에, `x.number *= 2`는 `40`을 출력해요. +네 번째에는, `value` 객체를 다시 한번 전달해요. `x.number`는 이전에 `20`으로 바 +뀌었기 때문에, `x.number *= 2`는 `40`을 출력해요.

@@ -2012,12 +2230,13 @@ ES6에서는, 기본값으로 파라미터를 초기화할 수 있어요. 함수 ###### 65. 무엇이 출력 될까요? ```javascript -[1, 2, 3, 4].reduce((x, y) => console.log(x, y)); +;[1, 2, 3, 4].reduce((x, y) => console.log(x, y)) ``` - A: `1` `2` 그리고 `3` `3` 그리고 `6` `4` - B: `1` `2` 그리고 `2` `3` 그리고 `3` `4` -- C: `1` `undefined` 그리고 `2` `undefined` 그리고 `3` `undefined` 그리고 `4` `undefined` +- C: `1` `undefined` 그리고 `2` `undefined` 그리고 `3` `undefined` 그리고 `4` + `undefined` - D: `1` `2` 그리고 `undefined` `3` 그리고 `undefined` `4`
정답 @@ -2025,17 +2244,26 @@ ES6에서는, 기본값으로 파라미터를 초기화할 수 있어요. 함수 #### 정답: D -`reduce` 메소드가 받은 첫 번째 인수는 _누산기_ 예요, 이 경우엔 `x`죠. 두 번째 인수 `y`는 _현재 값_ 예요. reduce 메소드에서, 배열에 있는 모든 요소에 콜백 함수를 실행하므로 궁극적으로는 하나의 값을 얻을 수 있어요. +`reduce` 메소드가 받은 첫 번째 인수는 _누산기_ 예요, 이 경우엔 `x`죠. 두 번째 인 +수 `y`는 _현재 값_ 예요. reduce 메소드에서, 배열에 있는 모든 요소에 콜백 함수를 +실행하므로 궁극적으로는 하나의 값을 얻을 수 있어요. 이 예제에서는, 값을 리턴하지 않고, 단지 누적된 값과 현재 값을 출력해요. -누산기의 값은 콜백 함수가 이전에 리턴한 값이에요. 만약 추가적인 `초기값` 인수를 `reduce` 메소드에 전달하지 않았다면, 누산기는 첫번째 부른 첫 번째 요소와 동일해요. +누산기의 값은 콜백 함수가 이전에 리턴한 값이에요. 만약 추가적인 `초기값` 인수를 +`reduce` 메소드에 전달하지 않았다면, 누산기는 첫번째 부른 첫 번째 요소와 동일해 +요. -첫 번째 부를 땐, 누산기 (`x`)는 `1` 이에요, 그리고 현재 값인 (`y`)는 `2`예요. 콜백 함수로부터 리턴되지 않았어요, 누산기와 현재 값을 출력해요: `1` 그리고 `2`가 출력돼요. +첫 번째 부를 땐, 누산기 (`x`)는 `1` 이에요, 그리고 현재 값인 (`y`)는 `2`예요. 콜 +백 함수로부터 리턴되지 않았어요, 누산기와 현재 값을 출력해요: `1` 그리고 `2`가 +출력돼요. -함수에서 값을 리턴하지 않았다면, `undefined`를 리턴해요. 다음번에 부를 때, 누산기는 `undefined`고, 그리고 현재 값은 `3`이에요. `undefined` 그리고 `3`이 출력돼요. +함수에서 값을 리턴하지 않았다면, `undefined`를 리턴해요. 다음번에 부를 때, 누산 +기는 `undefined`고, 그리고 현재 값은 `3`이에요. `undefined` 그리고 `3`이 출력돼 +요. -네 번째 부를 땐, 또 콜백 함수에서 리턴받지 않았어요. 누산기는 다시 `undefined`고, 현재 값은 `4`예요. `undefined` 그리고 `4`가 출력돼요. +네 번째 부를 땐, 또 콜백 함수에서 리턴받지 않았어요. 누산기는 다시 `undefined`고 +, 현재 값은 `4`예요. `undefined` 그리고 `4`가 출력돼요.

@@ -2047,32 +2275,31 @@ ES6에서는, 기본값으로 파라미터를 초기화할 수 있어요. 함수 ```javascript class Dog { constructor(name) { - this.name = name; + this.name = name } -}; +} class Labrador extends Dog { - // 1 + // 1 constructor(name, size) { - this.size = size; + this.size = size } // 2 constructor(name, size) { - super(name); - this.size = size; + super(name) + this.size = size } // 3 constructor(size) { - super(name); - this.size = size; + super(name) + this.size = size } - // 4 + // 4 constructor(name, size) { - this.name = name; - this.size = size; + this.name = name + this.size = size } - -}; +} ``` - A: 1 @@ -2085,11 +2312,15 @@ class Labrador extends Dog { #### 정답: B -이 파생 클래스에서, `super`를 부르기 전에는 `this` 키워드에 접근할 수 없어요. 그렇게 하려고 한다면, 참조에러를 던질 거에요: 1과 4는 참조 에러를 던져요 +이 파생 클래스에서, `super`를 부르기 전에는 `this` 키워드에 접근할 수 없어요. 그 +렇게 하려고 한다면, 참조에러를 던질 거에요: 1과 4는 참조 에러를 던져요 -`super` 키워드를 가지고, 부모 클래스 생성자에 주어진 인수들을 부를 수 있어요. 부모 생성자는 `name` 인수를 받아요, 그래서 `name`을 `super`로 전달해야 해요. +`super` 키워드를 가지고, 부모 클래스 생성자에 주어진 인수들을 부를 수 있어요. 부 +모 생성자는 `name` 인수를 받아요, 그래서 `name`을 `super`로 전달해야 해요. -`Labrador` 클래스는 인수를 2개 받는데, `Dog`로 부터 확장된 `name`과 `Labrador` 클래스의 추가 속성인 `size`예요. 그 두 개는 `Labrador` 생성자 함수에 전달되어야 하는데, 올바르게 사용된 건 2번째 생성자예요. +`Labrador` 클래스는 인수를 2개 받는데, `Dog`로 부터 확장된 `name`과 `Labrador` +클래스의 추가 속성인 `size`예요. 그 두 개는 `Labrador` 생성자 함수에 전달되어야 +하는데, 올바르게 사용된 건 2번째 생성자예요.

@@ -2100,13 +2331,13 @@ class Labrador extends Dog { ```javascript // index.js -console.log('running index.js'); -import { sum } from './sum.js'; -console.log(sum(1, 2)); +console.log('running index.js') +import { sum } from './sum.js' +console.log(sum(1, 2)) // sum.js -console.log('running sum.js'); -export const sum = (a, b) => a + b; +console.log('running sum.js') +export const sum = (a, b) => a + b ``` - A: `running index.js`, `running sum.js`, `3` @@ -2119,9 +2350,14 @@ export const sum = (a, b) => a + b; #### 정답: B -`import` 키워드를 사용하면, 모든 import된 modules은 _우선-파싱_ 되어요. import된 모듈은 _처음에_ 실행되는 것을 의미하고, import한 파일 안에 있는 코드는 _나중에_ 실행돼요. +`import` 키워드를 사용하면, 모든 import된 modules은 _우선-파싱_ 되어요. import된 +모듈은 _처음에_ 실행되는 것을 의미하고, import한 파일 안에 있는 코드는 _나중에_ +실행돼요. -이것은 CommonJSd의 `require()`와 `import`의 차이예요! `require()`을 사용하면, 런타임 중 코드에서 필요한 시점에 의존성 모듈을 로드 할 수 있어요. 만약 `import` 대신에 `require`을 사용하면, `running index.js`, `running sum.js`, `3`으로 콘솔에 출력될 거에요. +이것은 CommonJSd의 `require()`와 `import`의 차이예요! `require()`을 사용하면, 런 +타임 중 코드에서 필요한 시점에 의존성 모듈을 로드 할 수 있어요. 만약 `import` 대 +신에 `require`을 사용하면, `running index.js`, `running sum.js`, `3`으로 콘솔에 +출력될 거에요.

@@ -2146,7 +2382,11 @@ console.log(Symbol('foo') === Symbol('foo')) #### 정답: A -모든 심볼은 완전히 유니크해요. 심볼에 전달된 인수의 목적은, 심볼에 설명을 제공하는 거에요. 심볼의 값은 전달된 인수에 따라 달라지지 않아요. 동등성을 테스트할 때, 새로운 심볼 객체를 만들어요: 첫번째 `Symbol('foo')`와 두번째 `Symbol('foo')`. 이 두개의 값들은 유니크하며, 서로 같지 않아요, `Symbol('foo') === Symbol('foo')`는 `false`를 리턴해요. +모든 심볼은 완전히 유니크해요. 심볼에 전달된 인수의 목적은, 심볼에 설명을 제공하 +는 거에요. 심볼의 값은 전달된 인수에 따라 달라지지 않아요. 동등성을 테스트할 때, +새로운 심볼 객체를 만들어요: 첫번째 `Symbol('foo')`와 두번째 `Symbol('foo')`. 이 +두개의 값들은 유니크하며, 서로 같지 않아요, `Symbol('foo') === Symbol('foo')`는 +`false`를 리턴해요.

@@ -2156,24 +2396,30 @@ console.log(Symbol('foo') === Symbol('foo')) ###### 69. 무엇이 출력 될까요? ```javascript -const name = "Lydia Hallie" +const name = 'Lydia Hallie' console.log(name.padStart(13)) console.log(name.padStart(2)) ``` - A: `"Lydia Hallie"`, `"Lydia Hallie"` -- B: `" Lydia Hallie"`, `" Lydia Hallie"` (`"[13x whitespace]Lydia Hallie"`, `"[2x whitespace]Lydia Hallie"`) -- C: `" Lydia Hallie"`, `"Lydia Hallie"` (`"[1x whitespace]Lydia Hallie"`, `"Lydia Hallie"`) -- D: `"Lydia Hallie"`, `"Lyd"`, +- B: `" Lydia Hallie"`, `" Lydia Hallie"` (`"[13x whitespace]Lydia Hallie"`, + `"[2x whitespace]Lydia Hallie"`) +- C: `" Lydia Hallie"`, `"Lydia Hallie"` (`"[1x whitespace]Lydia Hallie"`, + `"Lydia Hallie"`) +- D: `"Lydia Hallie"`, `"Lyd"`,
정답

#### 정답: C -`padStart` 메소드를 사용하면, 문자열의 시작 부분에 패딩을 추가해 줄 수 있어요. 이 메소드에 전달된 값은 패딩을 포함한 문자열의 _전체_ 길이예요. 문자열 `"Lydia Hallie"`의 길이는 `12`예요. `name.padStart(13)`은 문자열의 시작점에 1 스페이스를 삽입해요, 따라서 12 + 1 은 13이죠. +`padStart` 메소드를 사용하면, 문자열의 시작 부분에 패딩을 추가해 줄 수 있어요. +이 메소드에 전달된 값은 패딩을 포함한 문자열의 _전체_ 길이예요. 문자열 +`"Lydia Hallie"`의 길이는 `12`예요. `name.padStart(13)`은 문자열의 시작점에 1 스 +페이스를 삽입해요, 따라서 12 + 1 은 13이죠. -`padStart` 메소드에 전달된 인수가 배열의 길이보다 작다면, 패딩은 추가되지 않을 거예요. +`padStart` 메소드에 전달된 인수가 배열의 길이보다 작다면, 패딩은 추가되지 않을 +거예요.

@@ -2183,7 +2429,7 @@ console.log(name.padStart(2)) ###### 70. 무엇이 출력 될까요? ```javascript -console.log("🥑" + "💻"); +console.log('🥑' + '💻') ``` - A: `"🥑💻"` @@ -2196,7 +2442,8 @@ console.log("🥑" + "💻"); #### 정답: A -`+` 연산자를 가지고, 문자열을 연결 시킬 수 있어요. 이 경우에는, 문자열 `"🥑"`과 문자열 `"💻"`을 연결해, 결과 `"🥑💻"`를 얻었어요. +`+` 연산자를 가지고, 문자열을 연결 시킬 수 있어요. 이 경우에는, 문자열 `"🥑"`과 +문자열 `"💻"`을 연결해, 결과 `"🥑💻"`를 얻었어요.

@@ -2207,16 +2454,16 @@ console.log("🥑" + "💻"); ```javascript function* startGame() { - const answer = yield "Do you love JavaScript?"; - if (answer !== "Yes") { - return "Oh wow... Guess we're gone here"; + const answer = yield 'Do you love JavaScript?' + if (answer !== 'Yes') { + return "Oh wow... Guess we're gone here" } - return "JavaScript loves you back ❤️"; + return 'JavaScript loves you back ❤️' } -const game = startGame(); -console.log(/* 1 */); // Do you love JavaScript? -console.log(/* 2 */); // JavaScript loves you back ❤️ +const game = startGame() +console.log(/* 1 */) // Do you love JavaScript? +console.log(/* 2 */) // JavaScript loves you back ❤️ ``` - A: `game.next("Yes").value` 그리고 `game.next().value` @@ -2229,11 +2476,17 @@ console.log(/* 2 */); // JavaScript loves you back ❤️ #### 정답: C -제너레이터 함수는 `yield` 키워드를 보면 실행을 "멈춰"요. 첫 번째로, `game.next().value`를 불러, 함수가 "Do you love JavaScript?" 문자열을 넘겨주도록 할 수 있어요. +제너레이터 함수는 `yield` 키워드를 보면 실행을 "멈춰"요. 첫 번째로, +`game.next().value`를 불러, 함수가 "Do you love JavaScript?" 문자열을 넘겨주도록 +할 수 있어요. -`yield` 키워드를 처음으로 찾기 전까지, 모든 줄이 실행되요. 첫 번째 줄에 있는 함수는 `yield` 키워드를 가지고 있어요: 첫 번째 yield으로 실행을 멈춰요! _이것은 `answer` 변수가 아직 정의되지 않았는 뜻이에요_ +`yield` 키워드를 처음으로 찾기 전까지, 모든 줄이 실행되요. 첫 번째 줄에 있는 함 +수는 `yield` 키워드를 가지고 있어요: 첫 번째 yield으로 실행을 멈춰요! _이것은 +`answer` 변수가 아직 정의되지 않았는 뜻이에요_ -`game.next("Yes").value`을 부를때, `"Yes"`의 경우에서 이전 `yield`는 `next()` 함수가 전달한 파라미터의 값으로 대체돼요. `answer` 변수의 값은 이제 `"Yes"`에요. if문의 조건은 `false`를 리턴해, `JavaScript loves you back ❤️`를 출력돼요 +`game.next("Yes").value`을 부를때, `"Yes"`의 경우에서 이전 `yield`는 `next()` 함 +수가 전달한 파라미터의 값으로 대체돼요. `answer` 변수의 값은 이제 `"Yes"`에요. +if문의 조건은 `false`를 리턴해, `JavaScript loves you back ❤️`를 출력돼요

@@ -2243,7 +2496,7 @@ console.log(/* 2 */); // JavaScript loves you back ❤️ ###### 72. 무엇이 출력 될까요? ```javascript -console.log(String.raw`Hello\nworld`); +console.log(String.raw`Hello\nworld`) ``` - A: `Hello world!` @@ -2256,9 +2509,10 @@ console.log(String.raw`Hello\nworld`); #### 정답: C -`String.raw`는 escapes (`\n`, `\v`, `\t` 등.)에서의 문자열을 무시해요! 백슬래시는 다음과 같이 끝나면 문제가 될 수 있어요 +`String.raw`는 escapes (`\n`, `\v`, `\t` 등.)에서의 문자열을 무시해요! 백슬래시 +는 다음과 같이 끝나면 문제가 될 수 있어요 -``console.log(`C:\Documents\Projects\table.html`)`` +`` console.log(`C:\Documents\Projects\table.html`) `` 이렇게 될 거예요: @@ -2279,11 +2533,11 @@ console.log(String.raw`Hello\nworld`); ```javascript async function getData() { - return await Promise.resolve("I made it!"); + return await Promise.resolve('I made it!') } -const data = getData(); -console.log(data); +const data = getData() +console.log(data) ``` - A: `"I made it!"` @@ -2296,9 +2550,12 @@ console.log(data); #### 정답: C -async 함수는 항상 promise를 리턴해요. `await`는 promise가 resolve 할 때까지 기다려야 해요: pending promise는 `data`를 설정하기 위해 부른 `getData()`가 리턴한 것을 가져요. +async 함수는 항상 promise를 리턴해요. `await`는 promise가 resolve 할 때까지 기다 +려야 해요: pending promise는 `data`를 설정하기 위해 부른 `getData()`가 리턴한 것 +을 가져요. -resolve된 값 `"I made it"`에 접근하고 싶다면, `data`에 `.then()` 메소드를 사용해야해요. +resolve된 값 `"I made it"`에 접근하고 싶다면, `data`에 `.then()` 메소드를 사용해 +야해요. `data.then(res => console.log(res))` @@ -2313,11 +2570,11 @@ resolve된 값 `"I made it"`에 접근하고 싶다면, `data`에 `.then()` 메 ```javascript function addToList(item, list) { - return list.push(item); + return list.push(item) } -const result = addToList("apple", ["banana"]); -console.log(result); +const result = addToList('apple', ['banana']) +console.log(result) ``` - A: `['banana', 'apple']` @@ -2330,9 +2587,13 @@ console.log(result); #### 정답: B -`.push()`메소드는 새로운 배열의 _길이_ 를 리턴해요! 이전에, 배열은 한 개의 요소(문자열 `"banana"`)를 포함되어있고 길이는 `1`예요. 배열에 문자열 `"apple"`을 추가한 후, 배열은 두 개 요소를 포함하고, 그리고 길이 `2`를 가져요. `addToList` 함수로부터 리턴돼요. +`.push()`메소드는 새로운 배열의 _길이_ 를 리턴해요! 이전에, 배열은 한 개의 요소( +문자열 `"banana"`)를 포함되어있고 길이는 `1`예요. 배열에 문자열 `"apple"`을 추가 +한 후, 배열은 두 개 요소를 포함하고, 그리고 길이 `2`를 가져요. `addToList` 함수 +로부터 리턴돼요. -`push` 메소드는 원본 배열을 수정해요. 만약 함수로부터 _배열의 길이_ 대신에 _배열_ 을 리턴하고 싶다면, `item`을 푸시한 후 `list`를 리턴해야해요. +`push` 메소드는 원본 배열을 수정해요. 만약 함수로부터 _배열의 길이_ 대신에 _배 +열_ 을 리턴하고 싶다면, `item`을 푸시한 후 `list`를 리턴해야해요.

@@ -2342,14 +2603,14 @@ console.log(result); ###### 75. 무엇이 출력 될까요? ```javascript -const box = { x: 10, y: 20 }; +const box = { x: 10, y: 20 } -Object.freeze(box); +Object.freeze(box) -const shape = box; -shape.x = 100; +const shape = box +shape.x = 100 -console.log(shape); +console.log(shape) ``` - A: `{ x: 100, y: 20 }` @@ -2362,11 +2623,16 @@ console.log(shape); #### 정답: B -`Object.freeze`는 객체의 속성들을 추가, 삭제 혹은 수정하는 걸 불가능하게 만들어요(다른 객체로서의 속성들의 값이 아닌 한). +`Object.freeze`는 객체의 속성들을 추가, 삭제 혹은 수정하는 걸 불가능하게 만들어 +요(다른 객체로서의 속성들의 값이 아닌 한). -변수 `shape`을 생성할 때, 동결 객체 `box`와 동일하게 설정했고, `shape` 역시 동결 객체를 참조해요. `Object.isFrozen`을 사용해 객체의 동결 여부를 확인할 수 있어요. 이 경우, `Object.isFrozen(shape)`은 참을 리턴하고, 따라서 변수 `shape`는 동결 객체 참조를 가져요. +변수 `shape`을 생성할 때, 동결 객체 `box`와 동일하게 설정했고, `shape` 역시 동결 +객체를 참조해요. `Object.isFrozen`을 사용해 객체의 동결 여부를 확인할 수 있어요. +이 경우, `Object.isFrozen(shape)`은 참을 리턴하고, 따라서 변수 `shape`는 동결 객 +체 참조를 가져요. -`shape`가 동결 상태이므로, `x`의 값은 객체가 아니며, `x`의 속성을 수정할 수 없어요. `x`는 여전히 `10`이고, `{ x: 10, y: 20 }`가 출력돼요. +`shape`가 동결 상태이므로, `x`의 값은 객체가 아니며, `x`의 속성을 수정할 수 없어 +요. `x`는 여전히 `10`이고, `{ x: 10, y: 20 }`가 출력돼요.

@@ -2376,9 +2642,9 @@ console.log(shape); ###### 76. 무엇이 출력 될까요? ```javascript -const { name: myName } = { name: "Lydia" }; +const { name: myName } = { name: 'Lydia' } -console.log(name); +console.log(name) ``` - A: `"Lydia"` @@ -2391,9 +2657,11 @@ console.log(name); #### 정답: D -오른쪽에 있는 객체로부터 속성 `name`을 unpack할 때, `myName`라는 이름을 가진 변수에 값 `"Lydia"`을 할당해요. +오른쪽에 있는 객체로부터 속성 `name`을 unpack할 때, `myName`라는 이름을 가진 변 +수에 값 `"Lydia"`을 할당해요. -`{ name: myName }`은, JavaScript에게 오른쪽에 있는 `name`속성 값을 가진 `myName`이라고 불리는 새로운 변수를 만든다고 말하는 거예요. +`{ name: myName }`은, JavaScript에게 오른쪽에 있는 `name`속성 값을 가진 +`myName`이라고 불리는 새로운 변수를 만든다고 말하는 거예요. `name`을 출력하려고 하면, 변수는 정의되지 않아, ReferenceError를 던질거예요. @@ -2406,7 +2674,7 @@ console.log(name); ```javascript function sum(a, b) { - return a + b; + return a + b } ``` @@ -2418,9 +2686,12 @@ function sum(a, b) { #### 정답: A -pure 함수는 _항상_ 같은 결과를 리턴하는 함수예요, 만약 같은 인수가 전달 된다면 말이죠. +pure 함수는 _항상_ 같은 결과를 리턴하는 함수예요, 만약 같은 인수가 전달 된다면 +말이죠. -`sum` 함수는 항상 같은 결과를 리턴해요. 만약 `1`과 `2`를 전달하면, _항상_ 부작용 없이 `3`을 리턴할 거예요. `5`와 `10`을 전달하면, _항상_ `15`를 리턴할 거예요. 이게 pure 함수의 정의예요. +`sum` 함수는 항상 같은 결과를 리턴해요. 만약 `1`과 `2`를 전달하면, _항상_ 부작용 +없이 `3`을 리턴할 거예요. `5`와 `10`을 전달하면, _항상_ `15`를 리턴할 거예요. 이 +게 pure 함수의 정의예요.

@@ -2431,22 +2702,22 @@ pure 함수는 _항상_ 같은 결과를 리턴하는 함수예요, 만약 같 ```javascript const add = () => { - const cache = {}; + const cache = {} return num => { if (num in cache) { - return `From cache! ${cache[num]}`; + return `From cache! ${cache[num]}` } else { - const result = num + 10; - cache[num] = result; - return `Calculated! ${result}`; + const result = num + 10 + cache[num] = result + return `Calculated! ${result}` } - }; -}; + } +} -const addFunction = add(); -console.log(addFunction(10)); -console.log(addFunction(10)); -console.log(addFunction(5 * 2)); +const addFunction = add() +console.log(addFunction(10)) +console.log(addFunction(10)) +console.log(addFunction(5 * 2)) ``` - A: `Calculated! 20` `Calculated! 20` `Calculated! 20` @@ -2459,15 +2730,25 @@ console.log(addFunction(5 * 2)); #### 정답: C -`add`함수는 _memoization_ 함수예요. memoization으로, 함수 실행 속도를 높이기 위해 함수의 결과를 캐시에 저장할 수 있어요. 이 경우, 이전에 리턴된 값을 저장한 `cache` 객체를 만들어요. +`add`함수는 _memoization_ 함수예요. memoization으로, 함수 실행 속도를 높이기 위 +해 함수의 결과를 캐시에 저장할 수 있어요. 이 경우, 이전에 리턴된 값을 저장한 +`cache` 객체를 만들어요. -같은 인수로 `addFunction` 함수를 다시 부르면, 우선 cache 안에 값을 갖고 있는지 확인해요. 만약 그렇다면, 캐시에 저장된 값이 리턴되어, 실행시간이 절약돼요. 캐시에 저장되지 않았다면, 값을 계산하고 나중에 저장해요. +같은 인수로 `addFunction` 함수를 다시 부르면, 우선 cache 안에 값을 갖고 있는지 +확인해요. 만약 그렇다면, 캐시에 저장된 값이 리턴되어, 실행시간이 절약돼요. 캐시 +에 저장되지 않았다면, 값을 계산하고 나중에 저장해요. -같은 값으로 `addFunction`함수를 세 번 불러요: 첫 번째 호출 때에는, `num`가 `10`일 때 함수의 값은 아직 저장되지 않았어요. if문의 조건 `num in cache` 은 `false`을 리턴하고, else 블록이 실행돼요: `Calculated! 20`을 출력하고, 결과 값은 cache 객체에 추가돼요. `cache` 이제 `{ 10: 20 }`와 같아요. +같은 값으로 `addFunction`함수를 세 번 불러요: 첫 번째 호출 때에는, `num`가 +`10`일 때 함수의 값은 아직 저장되지 않았어요. if문의 조건 `num in cache` 은 +`false`을 리턴하고, else 블록이 실행돼요: `Calculated! 20`을 출력하고, 결과 값은 +cache 객체에 추가돼요. `cache` 이제 `{ 10: 20 }`와 같아요. -두 번째엔, `cache`객체는 `10`을 위해 리턴될 값을 포함하고 있어요. if문의 조건 `num in cache`은 `true`를 리턴하고, `'From cache! 20'`이 출력돼요. +두 번째엔, `cache`객체는 `10`을 위해 리턴될 값을 포함하고 있어요. if문의 조건 +`num in cache`은 `true`를 리턴하고, `'From cache! 20'`이 출력돼요. -세 번째에는, `5 * 2`을 `10`으로 평가하여 함수에 전달해요. `cache` 객체는 `10`을 위해 리턴될 값을 포함하고 있어요. if문의 조건 `num in cache`은 `true`를 리턴하고, `'From cache! 20'`이 출력돼요. +세 번째에는, `5 * 2`을 `10`으로 평가하여 함수에 전달해요. `cache` 객체는 `10`을 +위해 리턴될 값을 포함하고 있어요. if문의 조건 `num in cache`은 `true`를 리턴하고 +, `'From cache! 20'`이 출력돼요.

@@ -2477,34 +2758,38 @@ console.log(addFunction(5 * 2)); ###### 79. 무엇이 출력 될까요? ```javascript -const myLifeSummedUp = ["☕", "💻", "🍷", "🍫"] +const myLifeSummedUp = ['☕', '💻', '🍷', '🍫'] for (let item in myLifeSummedUp) { - console.log(item); + console.log(item) } for (let item of myLifeSummedUp) { - console.log(item); + console.log(item) } ``` - A: `0` `1` `2` `3` 그리고 `"☕"` ` "💻"` `"🍷"` `"🍫"` - B: `"☕"` ` "💻"` `"🍷"` `"🍫"` 그리고 `"☕"` ` "💻"` `"🍷"` `"🍫"` - C: `"☕"` ` "💻"` `"🍷"` `"🍫"` 그리고 `0` `1` `2` `3` -- D: `0` `1` `2` `3` 그리고 `{0: "☕", 1: "💻", 2: "🍷", 3: "🍫"}` +- D: `0` `1` `2` `3` 그리고 `{0: "☕", 1: "💻", 2: "🍷", 3: "🍫"}`
정답

#### 정답: A -_for-in_ 루프에서는, **열거 가능한** 속성들에 대해 반복 할 수 있어요. 배열에서, 열거 가능한 속성들은 배열 요소들의 "키"이고, 실제로는 그들의 인덱스죠. 배열을 다음과 같이 볼 수 있어요: +_for-in_ 루프에서는, **열거 가능한** 속성들에 대해 반복 할 수 있어요. 배열에서, +열거 가능한 속성들은 배열 요소들의 "키"이고, 실제로는 그들의 인덱스죠. 배열을 다 +음과 같이 볼 수 있어요: `{0: "☕", 1: "💻", 2: "🍷", 3: "🍫"}` 여기서 키는 열거 가능한 속성이에요. `0` `1` `2` `3`이 출력되죠. -_for-of_ 루프에서는, **반복 가능한** 속성을 가진 요소에 대해 반복 할 수 있어요. 배열은 반복 가능해요. 배열을 반복할 때, "item" 변수는 현재 반복중인 요소로, `"☕"` ` "💻"` `"🍷"` `"🍫"`이 출력돼요. +_for-of_ 루프에서는, **반복 가능한** 속성을 가진 요소에 대해 반복 할 수 있어요. +배열은 반복 가능해요. 배열을 반복할 때, "item" 변수는 현재 반복중인 요소로, +`"☕"` ` "💻"` `"🍷"` `"🍫"`이 출력돼요.

@@ -2515,22 +2800,24 @@ _for-of_ 루프에서는, **반복 가능한** 속성을 가진 요소에 대해 ```javascript const list = [1 + 2, 1 * 2, 1 / 2] -console.log(list); +console.log(list) ``` - A: `["1 + 2", "1 * 2", "1 / 2"]` - B: `["12", 2, 0.5]` - C: `[3, 2, 0.5]` -- D: `[1, 1, 1]` +- D: `[1, 1, 1]`
정답

#### 정답: C -배열 요소들은 모든 값을 포함 할 수 있어요. Numbers, strings, objects, 다른 arrays, null, boolean 값, undefined, 그리고 자료형, 함수, 연산자와 같은 표현식들 +배열 요소들은 모든 값을 포함 할 수 있어요. Numbers, strings, objects, 다른 +arrays, null, boolean 값, undefined, 그리고 자료형, 함수, 연산자와 같은 표현식들 -요소는 리턴된 값과 같아질 거예요. `1 + 2`는 `3`을 리턴하고, `1 * 2`는 `2`를 리턴하고, `1 / 2` 는 `0.5`을 리턴해요. +요소는 리턴된 값과 같아질 거예요. `1 + 2`는 `3`을 리턴하고, `1 * 2`는 `2`를 리턴 +하고, `1 / 2` 는 `0.5`을 리턴해요.

@@ -2544,26 +2831,28 @@ function sayHi(name) { return `Hi there, ${name}` } -console.log(sayHi()); +console.log(sayHi()) ``` - A: `Hi there, ` - B: `Hi there, undefined` - C: `Hi there, null` -- D: `ReferenceError` +- D: `ReferenceError`
정답

#### 정답: B -기본값으로, 함수에 값이 전달되지 않으면, 인수는 `undefined` 값을 가져요. 이 경우, `name` 인수를 위한 값을 전달하지 않았어요. `name`은 `undefined`로 출력돼요. +기본값으로, 함수에 값이 전달되지 않으면, 인수는 `undefined` 값을 가져요. 이 경우 +, `name` 인수를 위한 값을 전달하지 않았어요. `name`은 `undefined`로 출력돼요. ES6에서, 기본값 `undefined` 값을 기본값 파라미터로 덮어쓸 수 있어요. 예를 들면: `function sayHi(name = "Lydia") { ... }` -이 경우, 값을 전달하지 않거나 `undefined`를 전달하면, `name`은 항상 문자열 `Lydia`가 될 거예요. +이 경우, 값을 전달하지 않거나 `undefined`를 전달하면, `name`은 항상 문자열 +`Lydia`가 될 거예요.

@@ -2573,21 +2862,21 @@ ES6에서, 기본값 `undefined` 값을 기본값 파라미터로 덮어쓸 수 ###### 82. 무엇이 출력 될까요? ```javascript -var status = "😎"; +var status = '😎' setTimeout(() => { - const status = "😍"; + const status = '😍' const data = { - status: "🥑", + status: '🥑', getStatus() { - return this.status; - } - }; + return this.status + }, + } - console.log(data.getStatus()); - console.log(data.getStatus.call(this)); -}, 0); + console.log(data.getStatus()) + console.log(data.getStatus.call(this)) +}, 0) ``` - A: `"🥑"` 그리고 `"😍"` @@ -2600,9 +2889,16 @@ setTimeout(() => { #### 정답: B -`this`키워드의 값은 사용하는 곳에 따라 달라요. **메소드**에서 `getStatus`메소드 처럼, `this`키워드는 _메소드가 속한 객체_ 를 참조해요. 이 메소드는 `data` 객체에 속해 있어, `this`는 `data`객체를 참조해요. `this.status`를 출력할 때, `data`객체의 `status` 속성 `"🥑"`이 출력돼요. +`this`키워드의 값은 사용하는 곳에 따라 달라요. **메소드**에서 `getStatus`메소드 +처럼, `this`키워드는 _메소드가 속한 객체_ 를 참조해요. 이 메소드는 `data` 객체에 +속해 있어, `this`는 `data`객체를 참조해요. `this.status`를 출력할 때, `data`객체 +의 `status` 속성 `"🥑"`이 출력돼요. -`call` 메소드에서는, `this` 키워드가 참조하는 객체를 바꿀 수 있어요. **함수**에서, `this` 키워드는 _함수가 속한 객체_ 를 참조해요. `setTimeout` 함수를 _전역 객체_ 에 선언했고, `setTimeout` 함수 안에서, `this`키워드는 _전역 객체_ 를 참조해요. 전역 객체에서, 변수는 `"😎"`값을 가진 _status_ 를 부르죠. `this.status`를 출력하면, `"😎"`이 출력돼요. +`call` 메소드에서는, `this` 키워드가 참조하는 객체를 바꿀 수 있어요. **함수**에 +서, `this` 키워드는 _함수가 속한 객체_ 를 참조해요. `setTimeout` 함수를 _전역 객 +체_ 에 선언했고, `setTimeout` 함수 안에서, `this`키워드는 _전역 객체_ 를 참조해 +요. 전역 객체에서, 변수는 `"😎"`값을 가진 _status_ 를 부르죠. `this.status`를 출 +력하면, `"😎"`이 출력돼요.

@@ -2613,14 +2909,14 @@ setTimeout(() => { ```javascript const person = { - name: "Lydia", - age: 21 -}; + name: 'Lydia', + age: 21, +} -let city = person.city; -city = "Amsterdam"; +let city = person.city +city = 'Amsterdam' -console.log(person); +console.log(person) ``` - A: `{ name: "Lydia", age: 21 }` @@ -2633,11 +2929,14 @@ console.log(person); #### 정답: A -`city` 변수를 `person` 객체의 `city`라고 불리는 속성 값으로 설정 했어요. 이 객체에서는 `city`라고 불리는 속성이 없기 때문에, `city`는 `undefined`의 값을 가져요. +`city` 변수를 `person` 객체의 `city`라고 불리는 속성 값으로 설정 했어요. 이 객체 +에서는 `city`라고 불리는 속성이 없기 때문에, `city`는 `undefined`의 값을 가져요. -`person`객체 자체를 참조 _하지않는_ 다는 걸 참고해요! 변수 `city`는 `person` 객체의 `city` 현재 속성 값으로 설정 했을 뿐이죠. +`person`객체 자체를 참조 _하지않는_ 다는 걸 참고해요! 변수 `city`는 `person` 객 +체의 `city` 현재 속성 값으로 설정 했을 뿐이죠. -그러므로, 우리는 `city`를 문자열 `"Amsterdam"`로 설정 했어요. 이건 person 객체를 바꾸지 않아요: 여기서 객체를 참조하는 건 없어요. +그러므로, 우리는 `city`를 문자열 `"Amsterdam"`로 설정 했어요. 이건 person 객체를 +바꾸지 않아요: 여기서 객체를 참조하는 건 없어요. `person`객체를 출력할 때, 수정되지 않은 객체가 리턴 받아요. @@ -2651,15 +2950,15 @@ console.log(person); ```javascript function checkAge(age) { if (age < 18) { - const message = "Sorry, you're too young."; + const message = "Sorry, you're too young." } else { - const message = "Yay! You're old enough!"; + const message = "Yay! You're old enough!" } - return message; + return message } -console.log(checkAge(21)); +console.log(checkAge(21)) ``` - A: `"Sorry, you're too young."` @@ -2672,7 +2971,9 @@ console.log(checkAge(21)); #### 정답: C -`const`와 `let` 키워드를 사용한 변수는 _블록-스코프_ 예요. 블록은 중괄호 (`{ }`) 사이에 있는 것이죠. 이 경우, if/else 표현식의 중괄호를 의미해요. 블록 안에 선언된 건 블록 밖의 변수들을 참조하지 못해, ReferenceError를 던져요. +`const`와 `let` 키워드를 사용한 변수는 _블록-스코프_ 예요. 블록은 중괄호 (`{ }`) +사이에 있는 것이죠. 이 경우, if/else 표현식의 중괄호를 의미해요. 블록 안에 선언 +된 건 블록 밖의 변수들을 참조하지 못해, ReferenceError를 던져요.

@@ -2684,7 +2985,7 @@ console.log(checkAge(21)); ```javascript fetch('https://www.website.com/api/user/1') .then(res => res.json()) - .then(res => console.log(res)); + .then(res => console.log(res)) ``` - A: `fetch` 메소드의 결과 @@ -2697,7 +2998,8 @@ fetch('https://www.website.com/api/user/1') #### 정답: C -두번째 `.then`에서의 `res`의 값은 이전`.then`에서 리턴된 값이에요. 이것 처럼 `.then`을 계속해서 연결할 수 있고, 값은 계속해서 다음 핸들러로 전달 돼요. +두번째 `.then`에서의 `res`의 값은 이전`.then`에서 리턴된 값이에요. 이것 처럼 +`.then`을 계속해서 연결할 수 있고, 값은 계속해서 다음 핸들러로 전달 돼요.

@@ -2722,9 +3024,12 @@ function getName(name) { #### 정답: A -`!!name`에서, 우리는 `name`의 값이 참 같은지 거짓 같은지 결정해요. 만약 테스트 하려는 name이 참 같다면, `!name`은 `false`를 리턴해요. `!false` (실제로는 `!!name`)는 `true`를 리턴해요. +`!!name`에서, 우리는 `name`의 값이 참 같은지 거짓 같은지 결정해요. 만약 테스트 +하려는 name이 참 같다면, `!name`은 `false`를 리턴해요. `!false` (실제로는 +`!!name`)는 `true`를 리턴해요. -`hasName`을 `name`으로 설정하면, `hasName`은 불린 값 `true`가 아니라, `getName` 함수에 전달된 값으로 설정해요. +`hasName`을 `name`으로 설정하면, `hasName`은 불린 값 `true`가 아니라, `getName` +함수에 전달된 값으로 설정해요. `new Boolean(true)`은 불린 값 자체가 아닌, 감싼 객체를 리턴해요. @@ -2738,7 +3043,7 @@ function getName(name) { ###### 87. 무엇이 출력 될까요? ```javascript -console.log("I want pizza"[0]); +console.log('I want pizza'[0]) ``` - A: `"""` @@ -2751,9 +3056,12 @@ console.log("I want pizza"[0]); #### 정답: B -문자열의 특정 인덱스의 문자를 얻으려면, 대괄호 표기법을 사용하면 돼요. 문자열의 첫 번째 문자는 인덱스 0과 기타등등을 가지고 있어요. 이 경우 문자 `"I'`인 인덱스 0이 출력되는 요소를 갖길 원해요. +문자열의 특정 인덱스의 문자를 얻으려면, 대괄호 표기법을 사용하면 돼요. 문자열의 +첫 번째 문자는 인덱스 0과 기타등등을 가지고 있어요. 이 경우 문자 `"I'`인 인덱스 +0이 출력되는 요소를 갖길 원해요. -이 방법은 IE7 이하에서는 지원되지 않는다는 것을 유의하세요. 이 경우, `.charAt()`를 사용하세요. +이 방법은 IE7 이하에서는 지원되지 않는다는 것을 유의하세요. 이 경우, +`.charAt()`를 사용하세요.

@@ -2780,9 +3088,14 @@ sum(10) #### 정답: B -기본 파라미터의 값은 기본 파라미터를 정의하기 _전_ 이라면, 함수의 다른 파라미터와 같게 설정 할 수 있어요. 우리는 `sum` 함수에 값 `10`을 전달 했어요. 만약 `sum` 함수에 인수의 값을 하나만 받았다면, `num2`를 위한 값은 전달되지 않고, `num1`은 전달된 값과 같다는 의미에요. `num1`의 기본값은 `num1`의 값인 `10`과 같아요. `num1 + num2`는 `20`을 리턴해요. +기본 파라미터의 값은 기본 파라미터를 정의하기 _전_ 이라면, 함수의 다른 파라미터 +와 같게 설정 할 수 있어요. 우리는 `sum` 함수에 값 `10`을 전달 했어요. 만약 `sum` +함수에 인수의 값을 하나만 받았다면, `num2`를 위한 값은 전달되지 않고, `num1`은 +전달된 값과 같다는 의미에요. `num1`의 기본값은 `num1`의 값인 `10`과 같아요. +`num1 + num2`는 `20`을 리턴해요. -만약 기본 파리미터가 정의된 _후_ (오른쪽에) 기본 파라미터의 값을 설정하려고 시도한다면, 파라미터의 값은 아직 초기화되지 않아, 오류를 던질 거에요. +만약 기본 파리미터가 정의된 _후_ (오른쪽에) 기본 파라미터의 값을 설정하려고 시도 +한다면, 파라미터의 값은 아직 초기화되지 않아, 오류를 던질 거에요.

@@ -2792,12 +3105,12 @@ sum(10) ###### 89. 무엇이 출력 될까요? ```javascript -// module.js -export default () => "Hello world" -export const name = "Lydia" +// module.js +export default () => 'Hello world' +export const name = 'Lydia' -// index.js -import * as data from "./module" +// index.js +import * as data from './module' console.log(data) ``` @@ -2812,9 +3125,14 @@ console.log(data) #### 정답: A -`import * as name` 신택스를 사용해서, `module.js` 파일에 있는 _모든 exports_ 를 `index.js` 파일 안에 `data`라고 불리는 새로운 객체를 생성해요. `module.js` 파일에는, 2개의 export가 있어요: default export 와 named export. default export는 문자열 `"Hello World"`을 리턴하는 함수고, named export는 문자열 `"Lydia"`의 값을 가진 `name`이라고 불리는 변수예요. +`import * as name` 신택스를 사용해서, `module.js` 파일에 있는 _모든 exports_ 를 +`index.js` 파일 안에 `data`라고 불리는 새로운 객체를 생성해요. `module.js` 파일 +에는, 2개의 export가 있어요: default export 와 named export. default export는 문 +자열 `"Hello World"`을 리턴하는 함수고, named export는 문자열 `"Lydia"`의 값을 +가진 `name`이라고 불리는 변수예요. -`data` 객체는 default export를 위한 `default` 속성을 가지고, 다른 속성들은 named exports의 이름들과 그에 해당하는 값들을 가져요. +`data` 객체는 default export를 위한 `default` 속성을 가지고, 다른 속성들은 named +exports의 이름들과 그에 해당하는 값들을 가져요.

@@ -2830,7 +3148,7 @@ class Person { } } -const member = new Person("John") +const member = new Person('John') console.log(typeof member) ``` @@ -2844,15 +3162,17 @@ console.log(typeof member) #### 정답: C -Class는 함수 생성자를 위한 문법적 설탕이에요. 함수 생성자로서 `Person` 클래스와 동등한 것은 다음과 같아요: +Class는 함수 생성자를 위한 문법적 설탕이에요. 함수 생성자로서 `Person` 클래스와 +동등한 것은 다음과 같아요: ```javascript function Person() { - this.name = name; + this.name = name } ``` -`new`와 함께 불려진 함수 생성자는 `Person`의 인스턴스를 생성하고, `typeof` 키워드는 인스턴스의 `"object"`를 리턴해요. `typeof member`는 `"object"`을 리턴해요. +`new`와 함께 불려진 함수 생성자는 `Person`의 인스턴스를 생성하고, `typeof` 키워 +드는 인스턴스의 `"object"`를 리턴해요. `typeof member`는 `"object"`을 리턴해요.

@@ -2877,9 +3197,12 @@ console.log(newList.push(5)) #### 정답: D -`.push` 메소드는 배열 자체가 아니라, 배열의 _새로운 길이_ 를 리턴해요! `newList`를 `[1, 2, 3].push(4)`과 동일하게 설정함으로써, `newList`를 배열의 새로운 길이와 동일하게 설정했어요: `4`. +`.push` 메소드는 배열 자체가 아니라, 배열의 _새로운 길이_ 를 리턴해요! +`newList`를 `[1, 2, 3].push(4)`과 동일하게 설정함으로써, `newList`를 배열의 새로 +운 길이와 동일하게 설정했어요: `4`. -그리고나서, `.push` 메소드를 `newList`에 사용하려고 했어요. `newList`는 숫자 값 `4` 이기 때문에, `.push` 메소드를 사용할 수 없어요: TypeError가 던져져요. +그리고나서, `.push` 메소드를 `newList`에 사용하려고 했어요. `newList`는 숫자 값 +`4` 이기 때문에, `.push` 메소드를 사용할 수 없어요: TypeError가 던져져요.

@@ -2890,17 +3213,18 @@ console.log(newList.push(5)) ```javascript function giveLydiaPizza() { - return "Here is pizza!" + return 'Here is pizza!' } -const giveLydiaChocolate = () => "Here's chocolate... now go hit the gym already." +const giveLydiaChocolate = () => + "Here's chocolate... now go hit the gym already." console.log(giveLydiaPizza.prototype) console.log(giveLydiaChocolate.prototype) ``` -- A: `{ constructor: ...}` `{ constructor: ...}` -- B: `{}` `{ constructor: ...}` +- A: `{ constructor: ...}` `{ constructor: ...}` +- B: `{}` `{ constructor: ...}` - C: `{ constructor: ...}` `{}` - D: `{ constructor: ...}` `undefined` @@ -2909,7 +3233,11 @@ console.log(giveLydiaChocolate.prototype) #### 정답: D -`giveLydiaPizza`와 같은 정규 함수는, `생성자` 속성을 가진 `프로토타입` 객체(프로토타입 객체)를 속성으로 가져요. 그러나 `giveLydiaChocolate` 함수와 같은 화살표 함수에서는, `prototype` 속성을 가지고 있지 않아요. `giveLydiaChocolate.prototype`을 사용해 `prototype` 속성에 접근하려고 할때, `undefined`이 리턴될 거에요. +`giveLydiaPizza`와 같은 정규 함수는, `생성자` 속성을 가진 `프로토타입` 객체(프로 +토타입 객체)를 속성으로 가져요. 그러나 `giveLydiaChocolate` 함수와 같은 화살표 +함수에서는, `prototype` 속성을 가지고 있지 않아요. +`giveLydiaChocolate.prototype`을 사용해 `prototype` 속성에 접근하려고 할때, +`undefined`이 리턴될 거에요.

@@ -2920,9 +3248,9 @@ console.log(giveLydiaChocolate.prototype) ```javascript const person = { - name: "Lydia", - age: 21 -}; + name: 'Lydia', + age: 21, +} for (const [x, y] of Object.entries(person)) { console.log(x, y) @@ -2930,7 +3258,7 @@ for (const [x, y] of Object.entries(person)) { ``` - A: `name` `Lydia` 그리고 `age` `21` -- B: `["name", "Lydia"]` 그리고 `["age", 21]` +- B: `["name", "Lydia"]` 그리고 `["age", 21]` - C: `["name", "age"]` 그리고 `undefined` - D: `Error` @@ -2941,12 +3269,16 @@ for (const [x, y] of Object.entries(person)) { `Object.entries(person)`은 키와 값을 세트로 가진 배열의 배열을 리턴해요: -`[ [ 'name', 'Lydia' ], [ 'age', 21 ] ]` +`[ [ 'name', 'Lydia' ], [ 'age', 21 ] ]` -`for-of` 루프를 사용해서, 배열 안에 각 요소를 계속해서 반복할 수 있는데, 이 경우엔 하위 배열이에요. 하위 배열을 `const [x, y]`을 사용해, for-of 루프에서 즉시 분해할 수 있어요. `x`는 하위 배열의 첫 번째 요소와 같고, `y`는 하위 배열의 두 번째 요소와 같아요. +`for-of` 루프를 사용해서, 배열 안에 각 요소를 계속해서 반복할 수 있는데, 이 경우 +엔 하위 배열이에요. 하위 배열을 `const [x, y]`을 사용해, for-of 루프에서 즉시 분 +해할 수 있어요. `x`는 하위 배열의 첫 번째 요소와 같고, `y`는 하위 배열의 두 번째 +요소와 같아요. -첫번째 하위요소는 `[ "name", "Lydia" ]`로, `x`는 `"name"`, `y`는 `"Lydia"`을 출력해요. -두번째 하위요소는 `[ "age", 21 ]`로, `x`는 `"age"`, `y`는 `21`을 출력해요. +첫번째 하위요소는 `[ "name", "Lydia" ]`로, `x`는 `"name"`, `y`는 `"Lydia"`을 출 +력해요. 두번째 하위요소는 `[ "age", 21 ]`로, `x`는 `"age"`, `y`는 `21`을 출력해 +요.

@@ -2964,7 +3296,7 @@ console.log(getItems(["banana", "apple"], "pear", "orange")) ``` - A: `["banana", "apple", "pear", "orange"]` -- B: `[["banana", "apple"], "pear", "orange"]` +- B: `[["banana", "apple"], "pear", "orange"]` - C: `["banana", "apple", ["pear"], "orange"]` - D: `SyntaxError` @@ -2973,17 +3305,21 @@ console.log(getItems(["banana", "apple"], "pear", "orange")) #### 정답: D -`...args`은 나머지 파라미터예요. 나머지 파라미터의 값은 모든 나머지 인수들을 포함한 배열이며, **마지막 파라미터만 될 수 있어요**! 지금 예시에서는, 나머지 파라미터는 두번째 파라미터예요. 이것은 불가능하고, 신택스 에러를 던지게 될거에요. +`...args`은 나머지 파라미터예요. 나머지 파라미터의 값은 모든 나머지 인수들을 포 +함한 배열이며, **마지막 파라미터만 될 수 있어요**! 지금 예시에서는, 나머지 파라 +미터는 두번째 파라미터예요. 이것은 불가능하고, 신택스 에러를 던지게 될거에요. ```javascript function getItems(fruitList, favoriteFruit, ...args) { return [...fruitList, ...args, favoriteFruit] } -getItems(["banana", "apple"], "pear", "orange") +getItems(['banana', 'apple'], 'pear', 'orange') ``` -The above example works. This returns the array `[ 'banana', 'apple', 'orange', 'pear' ]` +The above example works. This returns the array +`[ 'banana', 'apple', 'orange', 'pear' ]` +

@@ -2993,12 +3329,9 @@ The above example works. This returns the array `[ 'banana', 'apple', 'orange', ```javascript function nums(a, b) { - if - (a > b) - console.log('a is bigger') - else - console.log('b is bigger') - return + if (a > b) console.log('a is bigger') + else console.log('b is bigger') + return a + b } @@ -3016,16 +3349,23 @@ console.log(nums(1, 2)) #### 정답: B -JavaScript에서, 세미콜론을 (`;`)을 명시적으로 포함하여 쓰지 _않_ 더라도, JavaScript 엔진은 여전히 문 뒤에 그들을 추가해줘요. 이것은 **자동 세미콜론 삽입**이라고 불려요. 예를 들어 문은 변수, 또는 `throw`, `return`, `break` 등과 같은 키워드가 될 수도 있어요. +JavaScript에서, 세미콜론을 (`;`)을 명시적으로 포함하여 쓰지 _않_ 더라도, +JavaScript 엔진은 여전히 문 뒤에 그들을 추가해줘요. 이것은 **자동 세미콜론 삽 +입**이라고 불려요. 예를 들어 문은 변수, 또는 `throw`, `return`, `break` 등과 같 +은 키워드가 될 수도 있어요. -여기, `return`문을 썼고, 다른 값 `a + b`은 _새로운 줄_ 에 쓰였어요. 그러나, 새로운 줄이기 때문에, 엔진은 실제로 그 값이 리턴되길 바라는지 알 수 없어요. 대신에, 자동적으로 `return` 뒤에 세미콜론을 더해줘요. 이것을 볼 수 있을거에요: +여기, `return`문을 썼고, 다른 값 `a + b`은 _새로운 줄_ 에 쓰였어요. 그러나, 새로 +운 줄이기 때문에, 엔진은 실제로 그 값이 리턴되길 바라는지 알 수 없어요. 대신에, +자동적으로 `return` 뒤에 세미콜론을 더해줘요. 이것을 볼 수 있을거에요: ```javascript - return; - a + b +return +a + b ``` -`return` 키워드 뒤에 함수가 실행되는 것이 중단되기 때문에, `a + b`의 의미는 도달되지 않아요. 여기서 처럼, 만약 아무 값도 리턴되지 않는다면, 함수는 `undefined`를 리턴할 거예요. `if/else`문 뒤에는 자동으로 삽입되는 게 없다는 걸 유의해요! +`return` 키워드 뒤에 함수가 실행되는 것이 중단되기 때문에, `a + b`의 의미는 도달 +되지 않아요. 여기서 처럼, 만약 아무 값도 리턴되지 않는다면, 함수는 `undefined`를 +리턴할 거예요. `if/else`문 뒤에는 자동으로 삽입되는 게 없다는 걸 유의해요!

@@ -3037,13 +3377,13 @@ JavaScript에서, 세미콜론을 (`;`)을 명시적으로 포함하여 쓰지 _ ```javascript class Person { constructor() { - this.name = "Lydia" + this.name = 'Lydia' } } Person = class AnotherPerson { constructor() { - this.name = "Sarah" + this.name = 'Sarah' } } @@ -3061,7 +3401,9 @@ console.log(member.name) #### 정답: B -다른 클래스/함수 생성자로 클래스를 설정할 수 있어요. 이 경우, `Person`을 `AnotherPerson`로 설정했어요. 이 생성자의 name은 `Sarah`예요, 따라서 새로운 `Person`의 인스턴스 `member`의 name 속성은 `"Sarah"`예요. +다른 클래스/함수 생성자로 클래스를 설정할 수 있어요. 이 경우, `Person`을 +`AnotherPerson`로 설정했어요. 이 생성자의 name은 `Sarah`예요, 따라서 새로운 +`Person`의 인스턴스 `member`의 name 속성은 `"Sarah"`예요.

@@ -3072,7 +3414,7 @@ console.log(member.name) ```javascript const info = { - [Symbol('a')]: 'b' + [Symbol('a')]: 'b', } console.log(info) @@ -3089,9 +3431,15 @@ console.log(Object.keys(info)) #### 정답: D -심볼은 _열거 불가능_ 해요. Object.keys 메소드는 객체의 모든 _열거 가능_ 한 키 속성들을 리턴해요. 심볼은 보이지 않고, 빈 객체가 리턴돼요. 객체 전체를 출력할때, 모든 속성들은 보여요, 심지어 열거 불가능한 것이라해도. +심볼은 _열거 불가능_ 해요. Object.keys 메소드는 객체의 모든 _열거 가능_ 한 키 속 +성들을 리턴해요. 심볼은 보이지 않고, 빈 객체가 리턴돼요. 객체 전체를 출력할때, +모든 속성들은 보여요, 심지어 열거 불가능한 것이라해도. -이것은 심볼의 많은 특성 중 하나에요: 완전히 고유한 값(예를들어 2개의 라이브러리를 같은 객체의 속성으로 추가하고 싶을때, 객체의 우연한 이름 충돌을 방지해요)을 나타내는 것 외에, 이 방법으로 객체의 속성을 "숨길" 수 있어요(비록 완전히는 아닐지라도. 여전히 `Object.getOwnPropertySymbols()` 메소드를 사용해 심볼에 접근 할 수 있어요). +이것은 심볼의 많은 특성 중 하나에요: 완전히 고유한 값(예를들어 2개의 라이브러리 +를 같은 객체의 속성으로 추가하고 싶을때, 객체의 우연한 이름 충돌을 방지해요)을 +나타내는 것 외에, 이 방법으로 객체의 속성을 "숨길" 수 있어요(비록 완전히는 아닐 +지라도. 여전히 `Object.getOwnPropertySymbols()` 메소드를 사용해 심볼에 접근 할 +수 있어요).

@@ -3121,15 +3469,22 @@ console.log(getUser(user)) #### 정답: A -`getList`함수는 배열을 인수로 받았어요. `getList` 함수의 괄호 사이에 있는 배열을 즉시 분해 했어요: +`getList`함수는 배열을 인수로 받았어요. `getList` 함수의 괄호 사이에 있는 배열을 +즉시 분해 했어요: - `[x, ...y] = [1, 2, 3, 4]` +`[x, ...y] = [1, 2, 3, 4]` -나머지 파라미터를 사용해 `...y`에 모든 "남은" 인수들을 배열에 넣었어요. 이 경우에서 남아있는 인수는 `2`, `3` 그리고 `4`예요. `y`의 값은 배열이고, 모든 나머지 파라미터를 포함하고 있어요. 이 경우 `x`의 값은 `1`이기 때문에, `[x, y]`는 `[1, [2, 3, 4]]`로 출력돼요. +나머지 파라미터를 사용해 `...y`에 모든 "남은" 인수들을 배열에 넣었어요. 이 경우 +에서 남아있는 인수는 `2`, `3` 그리고 `4`예요. `y`의 값은 배열이고, 모든 나머지 +파라미터를 포함하고 있어요. 이 경우 `x`의 값은 `1`이기 때문에, `[x, y]`는 +`[1, [2, 3, 4]]`로 출력돼요. -`getUser` 함수는 배열을 받았어요. 화살표 함수에서, 우리가 한개의 값을 리턴한다면 중괄호를 사용할 _필요_ 가 없어요. 그러나, 만약 화살표 함수에서 _객체_ 를 리턴하고 싶다면, 괄호 사이에 리턴할 값을 써야해요, 그렇지 않다면 아무 값도 리턴받을 수 없어요! 다음 함수에서는 객체가 리턴 될 거에요: +`getUser` 함수는 배열을 받았어요. 화살표 함수에서, 우리가 한개의 값을 리턴한다면 +중괄호를 사용할 _필요_ 가 없어요. 그러나, 만약 화살표 함수에서 _객체_ 를 리턴하 +고 싶다면, 괄호 사이에 리턴할 값을 써야해요, 그렇지 않다면 아무 값도 리턴받을 수 +없어요! 다음 함수에서는 객체가 리턴 될 거에요: -```const getUser = user => ({ name: user.name, age: user.age })``` +`const getUser = user => ({ name: user.name, age: user.age })` 이 경우 값이 리턴되는 값이 없으므로, 함수는 `undefined`을 리턴할거에요. @@ -3141,7 +3496,7 @@ console.log(getUser(user)) ###### 99. 무엇이 출력 될까요? ```javascript -const name = "Lydia" +const name = 'Lydia' console.log(name()) ``` @@ -3156,13 +3511,18 @@ console.log(name()) #### 정답: C -변수 `name`은 문자열을 값으로 가지고 있고, 함수가 아니죠, 따라서 호출할 수 없어요. +변수 `name`은 문자열을 값으로 가지고 있고, 함수가 아니죠, 따라서 호출할 수 없어 +요. -TypeErrors는 값이 예상된 유형이 아닐 경우 던져져요. JavaScript는 `name`을 호출하려고 했기 때문에 함수일거라 예상했어요. 그러나 문자열이였기 때문에, TypeError가 던져져요: name은 함수가 아니죠! +TypeErrors는 값이 예상된 유형이 아닐 경우 던져져요. JavaScript는 `name`을 호출하 +려고 했기 때문에 함수일거라 예상했어요. 그러나 문자열이였기 때문에, TypeError가 +던져져요: name은 함수가 아니죠! -SyntaxErrors는 어떤 것을 썼을때 JavaScript에서 유효하지 않을 때 던져져요, 예를들어 `return`을 `retrun`로 썼을때 말이죠. +SyntaxErrors는 어떤 것을 썼을때 JavaScript에서 유효하지 않을 때 던져져요, 예를들 +어 `return`을 `retrun`로 썼을때 말이죠. -ReferenceErrors는 JavaScript가 접근하려고 하는 값의 참조를 찾을 수 없을 때 던져져요. +ReferenceErrors는 JavaScript가 접근하려고 하는 값의 참조를 찾을 수 없을 때 던져 +져요.

@@ -3188,9 +3548,12 @@ You should${'' && `n't`} see a therapist after so much JavaScript lol` #### 정답: B -`[]`은 참 같은 값이에요. `&&` 연산자를 사용할 때, 만약 왼쪽에 있는 값이 참 같은 값이라면 오른쪽 값은 리턴될 거에요. 이 경우, 왼쪽의 값 `[]`은 참 같은 값이에요, 따라서 `'Im'`은 리턴될 거예요. +`[]`은 참 같은 값이에요. `&&` 연산자를 사용할 때, 만약 왼쪽에 있는 값이 참 같은 +값이라면 오른쪽 값은 리턴될 거에요. 이 경우, 왼쪽의 값 `[]`은 참 같은 값이에요, +따라서 `'Im'`은 리턴될 거예요. -`""`은 거짓 같은 값이에요. 만약 왼쪽 값이 거짓 같은 값이라면, 리턴되는 것은 없어요. `n't`은 리턴되지 않아요. +`""`은 거짓 같은 값이에요. 만약 왼쪽 값이 거짓 같은 값이라면, 리턴되는 것은 없어 +요. `n't`은 리턴되지 않아요.

@@ -3200,9 +3563,9 @@ You should${'' && `n't`} see a therapist after so much JavaScript lol` ###### 101. 무엇이 출력 될까요? ```javascript -const one = (false || {} || null) -const two = (null || false || "") -const three = ([] || 0 || true) +const one = false || {} || null +const two = null || false || '' +const three = [] || 0 || true console.log(one, two, three) ``` @@ -3217,13 +3580,17 @@ console.log(one, two, three) #### 정답: C -`||` 연산자를 사용하면, 최초의 참 같은 피연산자를 리턴해요. 만약 모든 값이 거짓 같다면, 마지막 피연산자를 리턴해요. +`||` 연산자를 사용하면, 최초의 참 같은 피연산자를 리턴해요. 만약 모든 값이 거짓 +같다면, 마지막 피연산자를 리턴해요. -`(false || {} || null)`: 빈 객체 `{}`는 진짜 같은 값이에요. 이것은 최초로(그리고 유일하게) 진짜 같은 값이라 리턴돼요. `one`은 `{}`이에요. +`(false || {} || null)`: 빈 객체 `{}`는 진짜 같은 값이에요. 이것은 최초로(그리고 +유일하게) 진짜 같은 값이라 리턴돼요. `one`은 `{}`이에요. -`(null || false || "")`: 모든 피연산자는 가짜 같은 값이에요. 이것은 마지막 피연산자 `""`가 리턴된다는 것을 의미해요. `two`는 `""`이에요. +`(null || false || "")`: 모든 피연산자는 가짜 같은 값이에요. 이것은 마지막 피연 +산자 `""`가 리턴된다는 것을 의미해요. `two`는 `""`이에요. -`([] || 0 || "")`: 빈 배열 `[]`은 진짜 같은 값이에요. 이것은 최초의 진짜 같은 값이라 리턴돼요. `three`은 `[]`이에요. +`([] || 0 || "")`: 빈 배열 `[]`은 진짜 같은 값이에요. 이것은 최초의 진짜 같은 값 +이라 리턴돼요. `three`은 `[]`이에요.

@@ -3259,15 +3626,24 @@ secondFunction() #### 정답: D -promise를 사용하면, 기본적으로 _이 함수를 실행하고 싶지만, 시간이 좀 걸릴 수 있으니 실행 중에 잠시 미뤄둘거에요. 확실한 값이 resoloved(혹은 rejected)로 전달되었을 때와 콜 스택이 비었을 때 이 값을 사용하고 싶어요_ 라고 말해요. +promise를 사용하면, 기본적으로 _이 함수를 실행하고 싶지만, 시간이 좀 걸릴 수 있 +으니 실행 중에 잠시 미뤄둘거에요. 확실한 값이 resoloved(혹은 rejected)로 전달되 +었을 때와 콜 스택이 비었을 때 이 값을 사용하고 싶어요_ 라고 말해요. -`async` 함수 안에서 `.then`과 `await` 두개의 키워드에서 값을 얻을 수 있어요. 비록 `.then`과 `await`에서 프라미스의 값을 얻을 수 있지만, 그들은 약간 다르게 작동해요. +`async` 함수 안에서 `.then`과 `await` 두개의 키워드에서 값을 얻을 수 있어요. 비 +록 `.then`과 `await`에서 프라미스의 값을 얻을 수 있지만, 그들은 약간 다르게 작동 +해요. -첫번째 `firstFunction`에서, (뭐랄까) myPromise 함수가 실행되는 것을 미뤘지만, 다른 코드를 계속해서 실행하는데, 이 경우 `console.log('second')`에요. 그리고나서, 함수는 콜스택이 비워져 있는 걸 본 다음 출력된 문자열 `I have resolved`를 resolved로 전달해요. +첫번째 `firstFunction`에서, (뭐랄까) myPromise 함수가 실행되는 것을 미뤘지만, 다 +른 코드를 계속해서 실행하는데, 이 경우 `console.log('second')`에요. 그리고나서, +함수는 콜스택이 비워져 있는 걸 본 다음 출력된 문자열 `I have resolved`를 +resolved로 전달해요. -`secondFunction`에서의 await 키워드를 사용하면, 말 그대로 다음 라인으로 옮기기 전 값이 resoloved함수로 전달될 때 까지 async 함수의 실행을 중단해요. +`secondFunction`에서의 await 키워드를 사용하면, 말 그대로 다음 라인으로 옮기기 +전 값이 resoloved함수로 전달될 때 까지 async 함수의 실행을 중단해요. -이것은 `myPromise`이 값 `I have resolved`을 얻을 때 까지 기다린다는 의미이며, 단 한 번 발생하면, 다음라인으로 이동해요: `second`이 출력되죠. +이것은 `myPromise`이 값 `I have resolved`을 얻을 때 까지 기다린다는 의미이며, 단 +한 번 발생하면, 다음라인으로 이동해요: `second`이 출력되죠.

@@ -3280,8 +3656,8 @@ promise를 사용하면, 기본적으로 _이 함수를 실행하고 싶지만, const set = new Set() set.add(1) -set.add("Lydia") -set.add({ name: "Lydia" }) +set.add('Lydia') +set.add({ name: 'Lydia' }) for (let item of set) { console.log(item + 2) @@ -3298,13 +3674,19 @@ for (let item of set) { #### 정답: C -`+` 연산자는 숫자로 나타난 값을 더하는데 사용될 뿐만 아니라, 문자열을 연결해주는데 사용 할 수 있어요. JavaScript 엔진은 하나 이상의 값들이 숫자가 아닌 것을 발견 했을 때, 숫자를 문자열로 강제로 변환해요. +`+` 연산자는 숫자로 나타난 값을 더하는데 사용될 뿐만 아니라, 문자열을 연결해주는 +데 사용 할 수 있어요. JavaScript 엔진은 하나 이상의 값들이 숫자가 아닌 것을 발견 +했을 때, 숫자를 문자열로 강제로 변환해요. 첫번째 `1`은, 숫자로된 값이에요. `1 + 2`는 숫자 3을 리턴해요. -그러나, 두번째는 문자열 `"Lydia"`이에요. `"Lydia"`은 문자열이고, `2`는 숫자에요: `2`는 문자열로 강제 변환되어요. `"Lydia"`그리고 `"2"`이 연결되어, 문자열 `"Lydia2"`이 리턴되요. +그러나, 두번째는 문자열 `"Lydia"`이에요. `"Lydia"`은 문자열이고, `2`는 숫자에요: +`2`는 문자열로 강제 변환되어요. `"Lydia"`그리고 `"2"`이 연결되어, 문자열 +`"Lydia2"`이 리턴되요. -`{ name: "Lydia" }`은 객체에요. 객체가 아닌 숫자나 객체는 문자열이 아니므로, 둘다 문자화되어요. 정규 객체를 문자화 할때, `"[object Object]"`가 돼요. `"[object Object]"`는 `"2"`와 연결되어 `"[object Object]2"`가 돼요. +`{ name: "Lydia" }`은 객체에요. 객체가 아닌 숫자나 객체는 문자열이 아니므로, 둘 +다 문자화되어요. 정규 객체를 문자화 할때, `"[object Object]"`가 돼요. +`"[object Object]"`는 `"2"`와 연결되어 `"[object Object]2"`가 돼요.

@@ -3327,9 +3709,14 @@ Promise.resolve(5) #### 정답: C -promise이나 non-promise이 아니더라도 값의 모든 타입은 `Promise.resolve`으로 전달 할 수 있어요. 메소드 그 자체는 resolved 값을 가진 promise를 리턴해요 (``). 정규 함수를 전달한다면, 정규 값을 가진 resolved promise를 얻게 될거에요. 만약 promise를 전달한다면, 전달된 promise의 resolved 값과 resolved promise를 얻게 될거에요. +promise이나 non-promise이 아니더라도 값의 모든 타입은 `Promise.resolve`으로 전달 +할 수 있어요. 메소드 그 자체는 resolved 값을 가진 promise를 리턴해요 +(``). 정규 함수를 전달한다면, 정규 값을 가진 resolved promise를 얻게 +될거에요. 만약 promise를 전달한다면, 전달된 promise의 resolved 값과 resolved +promise를 얻게 될거에요. -이 경우, 숫자 값 `5`를 전달했어요. 이것은 값 `5`를 가진 resolved promise를 리턴해요. +이 경우, 숫자 값 `5`를 전달했어요. 이것은 값 `5`를 가진 resolved promise를 리턴 +해요.

@@ -3341,13 +3728,13 @@ promise이나 non-promise이 아니더라도 값의 모든 타입은 `Promise.re ```javascript function compareMembers(person1, person2 = person) { if (person1 !== person2) { - console.log("Not the same!") + console.log('Not the same!') } else { - console.log("They are the same!") + console.log('They are the same!') } } -const person = { name: "Lydia" } +const person = { name: 'Lydia' } compareMembers(person) ``` @@ -3362,11 +3749,14 @@ compareMembers(person) #### 정답: B -객체는 참조에 의해 전달되었어요. 엄격한 같은 비교 (`===`)로 객체를 검사한다면, 그들의 참조를 비교할거에요. +객체는 참조에 의해 전달되었어요. 엄격한 같은 비교 (`===`)로 객체를 검사한다면, +그들의 참조를 비교할거에요. -`person2`의 기본 값을 `person` 객체와 동일하게 설정 하고, `person` 객체를 `person1`의 값으로 전달 했어요. +`person2`의 기본 값을 `person` 객체와 동일하게 설정 하고, `person` 객체를 +`person1`의 값으로 전달 했어요. -이것은 두개의 값은 메모리의 같은 장소의 참조를 가지고 있다는 걸 의미해요, 그렇기 때문에 그들은 같아요. +이것은 두개의 값은 메모리의 같은 장소의 참조를 가지고 있다는 걸 의미해요, 그렇기 +때문에 그들은 같아요. `else`구문 안에 코드블럭이 실행되면, `They are the same!`을 출력해요. @@ -3386,7 +3776,7 @@ const colorConfig = { yellow: false, } -const colors = ["pink", "red", "blue"] +const colors = ['pink', 'red', 'blue'] console.log(colorConfig.colors[1]) ``` @@ -3401,11 +3791,22 @@ console.log(colorConfig.colors[1]) #### 정답: D -JavaScript에서, 객체의 속성에 접근하는 2가지 방법을 가지고 있어요: 괄호 표기법, 또는 점 표기법. 이 예제에서는, 괄호표기법 (`colorConfig["colors"]`) 대신 점 표기법 (`colorConfig.colors`)을 사용 했어요. +JavaScript에서, 객체의 속성에 접근하는 2가지 방법을 가지고 있어요: 괄호 표기법, +또는 점 표기법. 이 예제에서는, 괄호표기법 (`colorConfig["colors"]`) 대신 점 표기 +법 (`colorConfig.colors`)을 사용 했어요. -점 표기법에서, JavaScript는 정확한 이름을 가진 객체의 속성을 찾으려 해요. 이 예제에서 JavaScript는 `colorConfig` 객체의 `colors`라고 불리는 속성을 찾으려고 했어요. 그곳에는 `colors`라고 불리는 속성이 없어요, 그래서 `undefined`을 리턴해요. 그리고 나서, `[1]`을 사용해서 첫번째 요소의 값에 접근하려고 했어요. `undefined`의 값에는 이것을 할 수 없어요, 그래서 `TypeError`를 던져요: `Cannot read property '1' of undefined`. +점 표기법에서, JavaScript는 정확한 이름을 가진 객체의 속성을 찾으려 해요. 이 예 +제에서 JavaScript는 `colorConfig` 객체의 `colors`라고 불리는 속성을 찾으려고 했 +어요. 그곳에는 `colors`라고 불리는 속성이 없어요, 그래서 `undefined`을 리턴해요. +그리고 나서, `[1]`을 사용해서 첫번째 요소의 값에 접근하려고 했어요. +`undefined`의 값에는 이것을 할 수 없어요, 그래서 `TypeError`를 던져요: +`Cannot read property '1' of undefined`. -JavaScript 문장을 해석(또는 참조형 변수를 원시 데이터 타입으로 만들어 주도록) 해요. 괄호 표기법을 사용할때, 첫번째로 열린 괄호 `[`을 보고 닫힌 괄호 `]`를 찾을 때 까지 계속 진행되는 것으로 보여요. 그러고 나서야, 문장을 평가할거에요. 만약 `colorConfig[colors[1]]`을 사용했다면, `colorConfig` 객체의 속성 `red` 의 값이 리턴될 거에요. +JavaScript 문장을 해석(또는 참조형 변수를 원시 데이터 타입으로 만들어 주도록) 해 +요. 괄호 표기법을 사용할때, 첫번째로 열린 괄호 `[`을 보고 닫힌 괄호 `]`를 찾을 +때 까지 계속 진행되는 것으로 보여요. 그러고 나서야, 문장을 평가할거에요. 만약 +`colorConfig[colors[1]]`을 사용했다면, `colorConfig` 객체의 속성 `red` 의 값이 +리턴될 거에요.

@@ -3426,7 +3827,9 @@ console.log('❤️' === '❤️') #### 정답: A -엔진에서, 이모티콘은 유니코드에요. 하트 이모티콘의 유니코드는 `"U+2764 U+FE0F"`에요. 같은 이모티콘의 유니코드는 항상 같아요, 따라서 각각 다른 두개의 같은 문자열을 비교하는 것이므로 true를 리턴해요. +엔진에서, 이모티콘은 유니코드에요. 하트 이모티콘의 유니코드는 +`"U+2764 U+FE0F"`에요. 같은 이모티콘의 유니코드는 항상 같아요, 따라서 각각 다른 +두개의 같은 문자열을 비교하는 것이므로 true를 리턴해요.

@@ -3442,13 +3845,13 @@ emojis.map(x => x + '✨') emojis.filter(x => x !== '🥑') emojis.find(x => x !== '🥑') emojis.reduce((acc, cur) => acc + '✨') -emojis.slice(1, 2, '✨') +emojis.slice(1, 2, '✨') emojis.splice(1, 2, '✨') ``` - A: `All of them` - B: `map` `reduce` `slice` `splice` -- C: `map` `slice` `splice` +- C: `map` `slice` `splice` - D: `splice`
정답 @@ -3456,9 +3859,12 @@ emojis.splice(1, 2, '✨') #### 정답: D -`splice` method를 사용하면, 요소를 삭제, 대체하거나 추가함으로써 원본 배열을 수정해요. 이 경우에서, 인덱스 1에서 부터 2개의 아이템을 제거했어요. (`'🥑'` 와 `'😍'`를 삭제했어요) 그리고 ✨ 이모티콘을 대신 추가했죠. +`splice` method를 사용하면, 요소를 삭제, 대체하거나 추가함으로써 원본 배열을 수 +정해요. 이 경우에서, 인덱스 1에서 부터 2개의 아이템을 제거했어요. (`'🥑'` 와 +`'😍'`를 삭제했어요) 그리고 ✨ 이모티콘을 대신 추가했죠. -`map`, `filter` 그리고 `slice` 는 새로운 배열을 리턴해하고, `find` 요소를 리턴하며, `reduce` 감소된 값을 리턴해요. +`map`, `filter` 그리고 `slice` 는 새로운 배열을 리턴해하고, `find` 요소를 리턴하 +며, `reduce` 감소된 값을 리턴해요.

@@ -3478,7 +3884,7 @@ console.log(food) - A: `['🍕', '🍫', '🥑', '🍔']` - B: `['🍝', '🍫', '🥑', '🍔']` -- C: `['🍝', '🍕', '🍫', '🥑', '🍔']` +- C: `['🍝', '🍕', '🍫', '🥑', '🍔']` - D: `ReferenceError`
정답 @@ -3486,9 +3892,18 @@ console.log(food) #### 정답: A -`info` 객체의 `favoriteFood` 속성 값을 피자 이모티콘 `'🍕'`와 같게 설정했어요. 문자는 원시 데이터 형이에요. JavaScript에서, 원시 데이터 형은 (객체가 아닌 모든 것) _값_ 에 의해 상호 작용해요. 이 경우, `info` 객체의 `favoriteFood` 속성 값을 `food` 배열 안의 첫 번째 요소와 같게 설정했어요. 문자열은 원시 데이터 형이므로 값에의해 상호 작용해요. (좀 더 알고싶다면 내 [블로그 포스트](https://www.theavocoder.com/complete-javascript/2018/12/21/by-value-vs-by-reference)를 참고하세요.) +`info` 객체의 `favoriteFood` 속성 값을 피자 이모티콘 `'🍕'`와 같게 설정했어요. +문자는 원시 데이터 형이에요. JavaScript에서, 원시 데이터 형은 (객체가 아닌 모든 +것) _값_ 에 의해 상호 작용해요. 이 경우, `info` 객체의 `favoriteFood` 속성 값을 +`food` 배열 안의 첫 번째 요소와 같게 설정했어요. 문자열은 원시 데이터 형이므로 +값에의해 상호 작용해요. (좀 더 알고싶다면 내 +[블로그 포스트](https://www.theavocoder.com/complete-javascript/2018/12/21/by-value-vs-by-reference)를 +참고하세요.) -그리고나서, `info` 객체의 `favoriteFood` 속성 값을 바꿨어요. `favoriteFood`의 값은 단지 배열의 첫 번째 요소의 값을 _복사_ 했기 때문에 `food` 배열은 바뀌지 않고, `food[0]` 요소의 메모리 공간과 같은 참조를 갖지 않아요. food를 출력할 때, 여전히 원본 배열 ['🍕', '🍫', '🥑', '🍔']` 이에요. +그리고나서, `info` 객체의 `favoriteFood` 속성 값을 바꿨어요. `favoriteFood`의 값 +은 단지 배열의 첫 번째 요소의 값을 _복사_ 했기 때문에 `food` 배열은 바뀌지 않고, +`food[0]` 요소의 메모리 공간과 같은 참조를 갖지 않아요. food를 출력할 때, 여전히 +원본 배열 ['🍕', '🍫', '🥑', '🍔']` 이에요.

@@ -3511,8 +3926,9 @@ JSON.parse() #### 정답: A -`JSON.parse()`메소드를 사용하면, JSON 문자열의 구문을 분석하여 JavaScript 값으로 생성해요. -With the `JSON.parse()` method, we can parse JSON string to a JavaScript value. +`JSON.parse()`메소드를 사용하면, JSON 문자열의 구문을 분석하여 JavaScript 값으로 +생성해요. With the `JSON.parse()` method, we can parse JSON string to a +JavaScript value. ```javascript // 숫자를 유효한 JSON 문자열로 변환해요, 그리고 나서 JSON 문자열의 구문을 분석해 JavaScript 값으로 생성해요. @@ -3524,7 +3940,7 @@ const jsonArray = JSON.stringify([1, 2, 3]) // '[1, 2, 3]' JSON.parse(jsonArray) // [1, 2, 3] // 객체를 유효한 JSON 문자열로 변환해요, 그리고 나서 JSON 문자열의 구문을 분석해 JavaScript 값으로 생성해요. -const jsonArray = JSON.stringify({ name: "Lydia" }) // '{"name":"Lydia"}' +const jsonArray = JSON.stringify({ name: 'Lydia' }) // '{"name":"Lydia"}' JSON.parse(jsonArray) // { name: 'Lydia' } ``` @@ -3533,7 +3949,7 @@ JSON.parse(jsonArray) // { name: 'Lydia' } --- -###### 111. 무엇이 출력 될까요? +###### 111. 무엇이 출력 될까요? ```javascript let name = 'Lydia' @@ -3556,11 +3972,18 @@ getName() #### 정답: D -각 기능에는 자체 _실행 컨텍스트_ (또는 _범위_)가 있어요. `getName` 함수는 먼저 자체 컨텍스트(범위) 내에서 접근하려고 하는 변수 `name`이 포함되어 있는지 살펴봐요: `let` 키워드와 함께 선언 했기 때문에 `'Sarah'`의 값을 가져요. +각 기능에는 자체 _실행 컨텍스트_ (또는 _범위_)가 있어요. `getName` 함수는 먼저 +자체 컨텍스트(범위) 내에서 접근하려고 하는 변수 `name`이 포함되어 있는지 살펴봐 +요: `let` 키워드와 함께 선언 했기 때문에 `'Sarah'`의 값을 가져요. -`let` 키워드 (그리고 `const`)를 사용한 변수는 끌어올려지지만, `var`와 다르게 초기화 되지는 않아요. 그들을 선언 (초기화) 하는 줄 전에 접근 할 수 없어요. "일시적 사각지대"라고 불려요. 그들을 선언하기 전에 접근하려고 한다면, JavaScript는 `ReferenceError`를 던져요. +`let` 키워드 (그리고 `const`)를 사용한 변수는 끌어올려지지만, `var`와 다르게 +초기화 되지는 않아요. 그들을 선언 (초기화) 하는 줄 전에 접근 할 수 없어요 +. "일시적 사각지대"라고 불려요. 그들을 선언하기 전에 접근하려고 한다면, +JavaScript는 `ReferenceError`를 던져요. -`getName` 함수 안에 `name` 변수를 선언하지 않았다면, javaScript 엔진은 _스코프 체인_ 을 내려다 보지 않았을 거예요. 외부 범위에 `Lydia`의 값을 가진 `name` 변수가 있어요. 이 경우엔 `Lydia`를 출력할거예요. +`getName` 함수 안에 `name` 변수를 선언하지 않았다면, javaScript 엔진은 _스코프 +체인_ 을 내려다 보지 않았을 거예요. 외부 범위에 `Lydia`의 값을 가진 `name` 변수 +가 있어요. 이 경우엔 `Lydia`를 출력할거예요. ```javascript let name = 'Lydia' @@ -3581,11 +4004,11 @@ getName() // Lydia ```javascript function* generatorOne() { - yield ['a', 'b', 'c']; + yield ['a', 'b', 'c'] } function* generatorTwo() { - yield* ['a', 'b', 'c']; + yield* ['a', 'b', 'c'] } const one = generatorOne() @@ -3605,17 +4028,23 @@ console.log(two.next().value) #### 정답: C -`yield` 키워드를 사용하면, 제너레이터 함수 안의 값을 `중단` 했어요. `yield`키워드를 사용하면, 다른 제너레이터 함수 또는 반복 가능한 객체(예를들면 배열)의 값을 중단 시킬 수 있어요. +`yield` 키워드를 사용하면, 제너레이터 함수 안의 값을 `중단` 했어요. `yield`키워 +드를 사용하면, 다른 제너레이터 함수 또는 반복 가능한 객체(예를들면 배열)의 값을 +중단 시킬 수 있어요. -`generatorOne`에서, 전체 배열 `['a', 'b', 'c']`을 `yield` 키워드를 사용해서 중단 했어요. `one` (`one.next().value`)의 `next` 메소드가 리턴 한 객체의 `value`속성 값은 전체 배열 `['a', 'b', 'c']`과 같아요. +`generatorOne`에서, 전체 배열 `['a', 'b', 'c']`을 `yield` 키워드를 사용해서 중단 +했어요. `one` (`one.next().value`)의 `next` 메소드가 리턴 한 객체의 `value`속성 +값은 전체 배열 `['a', 'b', 'c']`과 같아요. ```javascript console.log(one.next().value) // ['a', 'b', 'c'] console.log(one.next().value) // undefined ``` -`generatorTwo`에서, `yield*` 키워드를 사용했어요. `two`의 첫번째 값이 중단 되었다는 의미이고, 반복자의 첫번째로 중단된 값과 같아요.반복자는 배열 `['a', 'b', 'c']` 이에요. -처음으로 중단된 값은 `a`이고, 따라서 첫번째 순서에서 `two.next().value`를 부르면 `a`를 리턴해요. +`generatorTwo`에서, `yield*` 키워드를 사용했어요. `two`의 첫번째 값이 중단 되었 +다는 의미이고, 반복자의 첫번째로 중단된 값과 같아요.반복자는 배열 +`['a', 'b', 'c']` 이에요. 처음으로 중단된 값은 `a`이고, 따라서 첫번째 순서에서 +`two.next().value`를 부르면 `a`를 리턴해요. ```javascript console.log(two.next().value) // 'a' @@ -3645,7 +4074,10 @@ console.log(`${(x => x)('I love')} to program`) #### 정답: A -템플릿 리터러를 사용한 표현식은 첫번째로 평가돼요. 문자열은 표현식의 리턴된 값을 포함하게 된다는 것을 의미하고, 이 경우 함수 `(x => x)('I love')`는 즉시 호출 돼요. 화살표 함수 `x => x`의 인수 값으로 `I love`를 전달 했어요. `x`는 `'I love'`이고 리턴 될 거에요. 이 결과는 `I love to program` 이에요. +템플릿 리터러를 사용한 표현식은 첫번째로 평가돼요. 문자열은 표현식의 리턴된 값을 +포함하게 된다는 것을 의미하고, 이 경우 함수 `(x => x)('I love')`는 즉시 호출 돼 +요. 화살표 함수 `x => x`의 인수 값으로 `I love`를 전달 했어요. `x`는 +`'I love'`이고 리턴 될 거에요. 이 결과는 `I love to program` 이에요.

@@ -3658,7 +4090,7 @@ console.log(`${(x => x)('I love')} to program`) let config = { alert: setInterval(() => { console.log('Alert!') - }, 1000) + }, 1000), } config = null @@ -3674,7 +4106,11 @@ config = null #### 정답: C -일반적으로 객체를 `null`로 설정했을때, 객체는 더 이상의 객체 참조가 없어 _쓰레기 수집_ 되어요. 그러나, `setInterval`을 가진 콜백 함수는 화살표 함수 (`config` 객체로 감싸진) 이기 때문에, 콜백 함수는 여전히 `config` 객체의 참조를 갖고 있고, 객체는 쓰레기 수집 되지 않아요. 쓰레기 수집 되지 않았기 때문에, `setInterval` 콜백 함수는 여전히 매 1000ms (1s) 마다 호출 돼요, +일반적으로 객체를 `null`로 설정했을때, 객체는 더 이상의 객체 참조가 없어 _쓰레기 +수집_ 되어요. 그러나, `setInterval`을 가진 콜백 함수는 화살표 함수 (`config` 객 +체로 감싸진) 이기 때문에, 콜백 함수는 여전히 `config` 객체의 참조를 갖고 있고, +객체는 쓰레기 수집 되지 않아요. 쓰레기 수집 되지 않았기 때문에, `setInterval` 콜 +백 함수는 여전히 매 1000ms (1s) 마다 호출 돼요,

@@ -3707,10 +4143,15 @@ myMap.get(() => 'greeting') #### 정답: B -`set` 메소드를 사용해서 키/값을 쌍으로 추가할 때, 키는 `set`함수로 전달 된 첫 번째 인수의 값이 되고, 값은 `set`함수로 전달된 두 번째 인수의 값이 될거에요. 이 경우에선 키는 _함수_ `() => 'greeting'`이고, 값은 `'Hello world'` 에요. `myMap`은 이제 `{ () => 'greeting' => 'Hello world!' }` 예요. +`set` 메소드를 사용해서 키/값을 쌍으로 추가할 때, 키는 `set`함수로 전달 된 첫 번 +째 인수의 값이 되고, 값은 `set`함수로 전달된 두 번째 인수의 값이 될거에요. 이 경 +우에선 키는 _함수_ `() => 'greeting'`이고, 값은 `'Hello world'` 에요. `myMap`은 +이제 `{ () => 'greeting' => 'Hello world!' }` 예요. -1은 틀렸어요, 키는 `'greeting'`가 아니라 `() => 'greeting'`이기 때문이에요. -3은 틀렸어요, `get`메소드에 새로 생성한 함수를 전달 했기 때문이에요. 객체는 _참조_에 의해 상호작용해요. 함수는 객체이고, 그들이 같다고 하더라도 두 함수가 절대로 같지 않은 이유예요: 메모리 안 다른 장소의 참조를 가지고 있어요. +1은 틀렸어요, 키는 `'greeting'`가 아니라 `() => 'greeting'`이기 때문이에요. 3은 +틀렸어요, `get`메소드에 새로 생성한 함수를 전달 했기 때문이에요. 객체는 *참조*에 +의해 상호작용해요. 함수는 객체이고, 그들이 같다고 하더라도 두 함수가 절대로 같지 +않은 이유예요: 메모리 안 다른 장소의 참조를 가지고 있어요.

@@ -3721,14 +4162,14 @@ myMap.get(() => 'greeting') ```javascript const person = { - name: "Lydia", - age: 21 + name: 'Lydia', + age: 21, } -const changeAge = (x = { ...person }) => x.age += 1 +const changeAge = (x = { ...person }) => (x.age += 1) const changeAgeAndName = (x = { ...person }) => { x.age += 1 - x.name = "Sarah" + x.name = 'Sarah' } changeAge(person) @@ -3747,11 +4188,18 @@ console.log(person) #### 정답: C -`changeAge`와 `changeAgeAndName`함수 둘다 기본 파라미터를 가지고 있는데 즉, _새롭게_ 만들어진 객체 `{ ...person }`를 가지고 있어요. 이 객체는 `person` 객체의 모든 키/값의 복사본을 가지고 있어요. +`changeAge`와 `changeAgeAndName`함수 둘다 기본 파라미터를 가지고 있는데 즉, _새 +롭게_ 만들어진 객체 `{ ...person }`를 가지고 있어요. 이 객체는 `person` 객체의 +모든 키/값의 복사본을 가지고 있어요. -첫번째로, `changeAge`함수를 호출 했고, 그것의 인수로 `person` 객체를 전달 했어요. 이 함수는 `age`속성의 값을 1 증가 시켜요. `person`은 이제 `{ name: "Lydia", age: 22 }`이에요. +첫번째로, `changeAge`함수를 호출 했고, 그것의 인수로 `person` 객체를 전달 했어요 +. 이 함수는 `age`속성의 값을 1 증가 시켜요. `person`은 이제 +`{ name: "Lydia", age: 22 }`이에요. -그리고나서, `changeAgeAndName` 함수를 호출 했지만, 파라미터를 전달하지 않았어요. 대신에, `x`의 값은 _새로운_ 객체와 같아요: `{ ...person }`. 새로운 객체이기 때문에, `person`객체의 속성들의 값에 영향을 주지 않아요. `person`은 여전히 `{ name: "Lydia", age: 22 }`와 같아요. +그리고나서, `changeAgeAndName` 함수를 호출 했지만, 파라미터를 전달하지 않았어요. +대신에, `x`의 값은 _새로운_ 객체와 같아요: `{ ...person }`. 새로운 객체이기 때문 +에, `person`객체의 속성들의 값에 영향을 주지 않아요. `person`은 여전히 +`{ name: "Lydia", age: 22 }`와 같아요.

From 97354017bdf02263e67173de96817336ebf3226d Mon Sep 17 00:00:00 2001 From: wisecare-justin Date: Thu, 29 Apr 2021 09:54:28 +0900 Subject: [PATCH 039/193] =?UTF-8?q?Revert=20"=E2=9C=8F=EF=B8=8F=20Fix=20ty?= =?UTF-8?q?po=20in=20q12=20answer"?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit This reverts commit 63f696049641ecfd0a9574db4d35b5fd195d0bbe. --- ko-KR/README-ko_KR.md | 1706 +++++++++++++++-------------------------- 1 file changed, 629 insertions(+), 1077 deletions(-) diff --git a/ko-KR/README-ko_KR.md b/ko-KR/README-ko_KR.md index 8c3b416c..a5e85cab 100644 --- a/ko-KR/README-ko_KR.md +++ b/ko-KR/README-ko_KR.md @@ -1,23 +1,15 @@ # (고급) JavaScript 질문 목록 -JavaScript 에 관한 객관식 문제를 -[Instagram](https://www.instagram.com/theavocoder)에 매일 게시하고 있어요, 물론 -여기에도 게시할 거예요! +JavaScript 에 관한 객관식 문제를 [Instagram](https://www.instagram.com/theavocoder)에 매일 게시하고 있어요, 물론 여기에도 게시할 거예요! -초급부터 고급까지: JavaScript를 얼마나 잘 알고 있는지 테스트하거나, 지식을 조금 -더 새롭게 하거나, 코딩 면접을 준비하세요! :muscle: :rocket: 이 기록을 매주 새로 -운 질문으로 업데이트해요. 마지막 업데이트: 10월 09 -일 +초급부터 고급까지: JavaScript를 얼마나 잘 알고 있는지 테스트하거나, 지식을 조금 더 새롭게 하거나, 코딩 면접을 준비하세요! :muscle: :rocket: 이 기록을 매주 새로운 질문으로 업데이트해요. 마지막 업데이트: 10월 09일 -정답은 질문 아래 접힌 부분에 있고, 간단히 클릭하면 펼칠 수 있어요. 행운을 빌어요 -:heart: +정답은 질문 아래 접힌 부분에 있고, 간단히 클릭하면 펼칠 수 있어요. 행운을 빌어요 :heart: 질문이 더 추가될 때마다 이메일을 받고 싶나요?
-✨✉이메일 업 -데이트 구독 ✉✨ +✨✉이메일 업데이트 구독 ✉✨ 사용 가능한 언어 목록: - - [🇸🇦 العربية](./ar-AR/README_AR.md) - [🇪🇬 اللغة العامية](./ar-EG/README_ar-EG.md) - [🇧🇦 Bosanski](./bs-BS/README-bs_BS.md) @@ -37,19 +29,20 @@ JavaScript 에 관한 객관식 문제를 - [🇨🇳 简体中文](./zh-CN/README-zh_CN.md) - [🇹🇼 繁體中文](./zh-TW/README_zh-TW.md) + --- ###### 1. 무엇이 출력 될까요? ```javascript function sayHi() { - console.log(name) - console.log(age) - var name = 'Lydia' - let age = 21 + console.log(name); + console.log(age); + var name = "Lydia"; + let age = 21; } -sayHi() +sayHi(); ``` - A: `Lydia` 그리고 `undefined` @@ -62,15 +55,9 @@ sayHi() #### 정답: D -함수 내에서, 우선 `var` 키워드를 사용해 `name` 변수를 선언해요. 이것은 변수가 정 -의된 행에 실제로 도달할 때까지, `undefined`의 기본값으로 호이스팅 되(생성단계에 -메모리 공간이 설정)는 것을 의미해요. `name` 변수를 출력하려는 줄에서 아직 변수를 -정의하고 있지 않기 때문에, `undefined` 값을 유지하고 있어요. +함수 내에서, 우선 `var` 키워드를 사용해 `name` 변수를 선언해요. 이것은 변수가 정의된 행에 실제로 도달할 때까지, `undefined`의 기본값으로 호이스팅 되(생성단계에 메모리 공간이 설정)는 것을 의미해요. `name` 변수를 출력하려는 줄에서 아직 변수를 정의하고 있지 않기 때문에, `undefined` 값을 유지하고 있어요. -`let` 키워드(그리고 `const`)를 가지는 변수들은, `var`와는 달리, 호이스팅 되지만 -초기화 되지 않아요. 그것들을 선언(초기화)하는 줄 전에는 접근할 수 없어요. -이것은 "일시적 사각지대"라고 불려요. 선언되기 전 변수에 접근하려고 하면, -JavaScript는 `ReferenceError`를 던져요. +`let` 키워드(그리고 `const`)를 가지는 변수들은, `var`와는 달리, 호이스팅 되지만 초기화 되지 않아요. 그것들을 선언(초기화)하는 줄 전에는 접근할 수 없어요. 이것은 "일시적 사각지대"라고 불려요. 선언되기 전 변수에 접근하려고 하면, JavaScript는 `ReferenceError`를 던져요.

@@ -81,11 +68,11 @@ JavaScript는 `ReferenceError`를 던져요. ```javascript for (var i = 0; i < 3; i++) { - setTimeout(() => console.log(i), 1) + setTimeout(() => console.log(i), 1); } for (let i = 0; i < 3; i++) { - setTimeout(() => console.log(i), 1) + setTimeout(() => console.log(i), 1); } ``` @@ -98,15 +85,9 @@ for (let i = 0; i < 3; i++) { #### 정답: C -JavaScript의 이벤트 큐 때문에, `setTimeout`의 콜백 함수는 루프가 실행된 _후에_ -호출돼요. 첫 번째의 루프 변수 `i`는 `var` 키워드를 사용해 선언되어 있기 때문에, -이 값은 전역 변수가 돼요. 루프 동안, 단항 연산자 `++`를 사용하여, 매번 `i`의 값 -을 `1`씩 증가했어요. `setTimeout`콜백 함수가 호출되기까지, 첫 번째 예에서 `i`는 -`3`이에요. +JavaScript의 이벤트 큐 때문에, `setTimeout`의 콜백 함수는 루프가 실행된 _후에_ 호출돼요. 첫 번째의 루프 변수 `i`는 `var` 키워드를 사용해 선언되어 있기 때문에, 이 값은 전역 변수가 돼요. 루프 동안, 단항 연산자 `++`를 사용하여, 매번 `i`의 값을 `1`씩 증가했어요. `setTimeout`콜백 함수가 호출되기까지, 첫 번째 예에서 `i`는 `3`이에요. -두 번째 루프에서, 변수 `i`는 `let` 키워드를 사용해 선언되었어요: `let`(그리고 -`const`) 키워드로 선언된 변수는 블록 범위예요(블록은 `{ }` 사이의 모든 것). 각각 -의 반복 동안, `i`는 새로운 값을 가지고, 각각의 값은 루프 안쪽 범위에 있어요. +두 번째 루프에서, 변수 `i`는 `let` 키워드를 사용해 선언되었어요: `let`(그리고 `const`) 키워드로 선언된 변수는 블록 범위예요(블록은 `{ }` 사이의 모든 것). 각각의 반복 동안, `i`는 새로운 값을 가지고, 각각의 값은 루프 안쪽 범위에 있어요.

@@ -119,13 +100,13 @@ JavaScript의 이벤트 큐 때문에, `setTimeout`의 콜백 함수는 루프 const shape = { radius: 10, diameter() { - return this.radius * 2 + return this.radius * 2; }, - perimeter: () => 2 * Math.PI * this.radius, -} + perimeter: () => 2 * Math.PI * this.radius +}; -console.log(shape.diameter()) -console.log(shape.perimeter()) +console.log(shape.diameter()); +console.log(shape.perimeter()); ``` - A: `20` 그리고 `62.83185307179586` @@ -138,12 +119,9 @@ console.log(shape.perimeter()) #### 정답: B -`diameter`의 값은 정규 함수지만, `perimeter`의 값은 화살표 함수라는 점을 유의하 -세요. +`diameter`의 값은 정규 함수지만, `perimeter`의 값은 화살표 함수라는 점을 유의하세요. -화살표 함수에서, `this` 키워드는 통상적인 함수와는 다르게 현재 주위의 범위를 참 -조해요! 이것은 `perimeter`를 부르면, shape 객체가 아닌 그 주위의 범위(예를 들면 -window)를 참조하는 것을 의미해요. +화살표 함수에서, `this` 키워드는 통상적인 함수와는 다르게 현재 주위의 범위를 참조해요! 이것은 `perimeter`를 부르면, shape 객체가 아닌 그 주위의 범위(예를 들면 window)를 참조하는 것을 의미해요. 그 객체에는 `radius`라는 값은 없기 때문에 `undefined`를 리턴해요. @@ -155,8 +133,8 @@ window)를 참조하는 것을 의미해요. ###### 4. 무엇이 출력 될까요? ```javascript -;+true -!'Lydia' ++true; +!"Lydia"; ``` - A: `1` 그리고 `false` @@ -168,11 +146,9 @@ window)를 참조하는 것을 의미해요. #### 정답: A -단항 더하기는 피연산자를 숫자로 변환하려 시도해요. `true`는 `1`이고, `false`는 -`0`이에요. +단항 더하기는 피연산자를 숫자로 변환하려 시도해요. `true`는 `1`이고, `false`는 `0`이에요. -문자열 `'Lydia'`는 참 같은 값이에요. 실제로는, "이 참 같은 값이 거짓 같은 값인가 -?"를 물어보고 있어요. 이것은 `false`를 리턴해요. +문자열 `'Lydia'`는 참 같은 값이에요. 실제로는, "이 참 같은 값이 거짓 같은 값인가?"를 물어보고 있어요. 이것은 `false`를 리턴해요.

@@ -183,13 +159,13 @@ window)를 참조하는 것을 의미해요. ```javascript const bird = { - size: 'small', -} + size: "small" +}; const mouse = { - name: 'Mickey', - small: true, -} + name: "Mickey", + small: true +}; ``` - A: `mouse.bird.size` 는 유효하지 않아요 @@ -202,21 +178,13 @@ const mouse = { #### 정답: A -JavaScript에서, 모든 객체 키는 문자열이에요 (심볼이 아닌 한). 비록 그것을 문자열 -_형_ 으로 입력하지 않아도, 항상 내부적으로 문자열로 변환돼요. +JavaScript에서, 모든 객체 키는 문자열이에요 (심볼이 아닌 한). 비록 그것을 문자열 _형_ 으로 입력하지 않아도, 항상 내부적으로 문자열로 변환돼요. -JavaScript는 문장을 해석(또는 박스 해제)해요. 대괄호 표기를 사용하면, 첫 번째 열 -린 대괄호 `[`를 보고 닫힌 대괄호 `]`를 찾을 때까지 진행해요. 그때에만, 그 문장을 -평가할 거예요. +JavaScript는 문장을 해석(또는 박스 해제)해요. 대괄호 표기를 사용하면, 첫 번째 열린 대괄호 `[`를 보고 닫힌 대괄호 `]`를 찾을 때까지 진행해요. 그때에만, 그 문장을 평가할 거예요. -`mouse[bird.size]`: 먼저 `"small"`인 `bird.size`를 평가해요. `mouse["small"]` 은 -`true`를 리턴해요. +`mouse[bird.size]`: 먼저 `"small"`인 `bird.size`를 평가해요. `mouse["small"]` 은 `true`를 리턴해요. -그러나, 닷 표기법에서, 이것은 발생하지 않아요, `mouse`는 `bird`라고 불리는 키를 -가지고 있지 않아요. 즉, `mouse.bird`는 `undefined`를 의미해요. 그 후, 닷 표기법 -을 사용해 `size`를 물어봐요. `mouse.bird.size`. `mouse.bird`는 `undefined`로, 실 -제로는 `undefined.size`를 물어보고 있어요. 이것은 유효하지 않기 때문에, -`Cannot read property "size" of undefined`와 비슷한 에러를 던질 거예요. +그러나, 닷 표기법에서, 이것은 발생하지 않아요, `mouse`는 `bird`라고 불리는 키를 가지고 있지 않아요. 즉, `mouse.bird`는 `undefined`를 의미해요. 그 후, 닷 표기법을 사용해 `size`를 물어봐요. `mouse.bird.size`. `mouse.bird`는 `undefined`로, 실제로는 `undefined.size`를 물어보고 있어요. 이것은 유효하지 않기 때문에, `Cannot read property "size" of undefined`와 비슷한 에러를 던질 거예요.

@@ -226,12 +194,12 @@ JavaScript는 문장을 해석(또는 박스 해제)해요. 대괄호 표기를 ###### 6. 무엇이 출력 될까요? ```javascript -let c = { greeting: 'Hey!' } -let d +let c = { greeting: "Hey!" }; +let d; -d = c -c.greeting = 'Hello' -console.log(d.greeting) +d = c; +c.greeting = "Hello"; +console.log(d.greeting); ``` - A: `Hello` @@ -247,8 +215,7 @@ console.log(d.greeting) JavaScript에서, 모든 객체는 서로 동일하게 설정하면 _참조_ 에 따라 상호작용해요. -우선 변수 `c`는 객체에 대한 값을 유지해요. 그 후, `c`와 동일한 객체 참조를 `d`에 -할당해요. +우선 변수 `c`는 객체에 대한 값을 유지해요. 그 후, `c`와 동일한 객체 참조를 `d`에 할당해요. @@ -262,13 +229,13 @@ JavaScript에서, 모든 객체는 서로 동일하게 설정하면 _참조_ 에 ###### 7. 무엇이 출력 될까요? ```javascript -let a = 3 -let b = new Number(3) -let c = 3 +let a = 3; +let b = new Number(3); +let c = 3; -console.log(a == b) -console.log(a === b) -console.log(b === c) +console.log(a == b); +console.log(a === b); +console.log(b === c); ``` - A: `true` `false` `true` @@ -281,14 +248,11 @@ console.log(b === c) #### 정답: C -`new Number()`는, 내장 함수 생성자예요. 숫자처럼 보이지만, 실제로는 숫자가 아니 -에요: 많은 추가 특성이 있고 그것은 객체예요. +`new Number()`는, 내장 함수 생성자예요. 숫자처럼 보이지만, 실제로는 숫자가 아니에요: 많은 추가 특성이 있고 그것은 객체예요. -`==`연산자를 사용할 때, 그건 같은 _값_ 을 가졌는지 여부만 확인해요. 그것들은 모 -두`3`의 값을 가지고 있으므로, `true`를 리턴해요. +`==`연산자를 사용할 때, 그건 같은 _값_ 을 가졌는지 여부만 확인해요. 그것들은 모두`3`의 값을 가지고 있으므로, `true`를 리턴해요. -그러나, `===`연산자를 사용할 때, 값 _과_ 형 둘 다 같아야 해요. 이건 아니에요: -`new Number()`는 숫자가 아니에요. **객체**에요. 그래서 둘 다 `false`를 리턴해요. +그러나, `===`연산자를 사용할 때, 값 _과_ 형 둘 다 같아야 해요. 이건 아니에요: `new Number()`는 숫자가 아니에요. **객체**에요. 그래서 둘 다 `false`를 리턴해요.

@@ -300,17 +264,17 @@ console.log(b === c) ```javascript class Chameleon { static colorChange(newColor) { - this.newColor = newColor - return this.newColor + this.newColor = newColor; + return this.newColor; } - constructor({ newColor = 'green' } = {}) { - this.newColor = newColor + constructor({ newColor = "green" } = {}) { + this.newColor = newColor; } } -const freddie = new Chameleon({ newColor: 'purple' }) -console.log(freddie.colorChange('orange')) +const freddie = new Chameleon({ newColor: "purple" }); +console.log(freddie.colorChange("orange")); ``` - A: `orange` @@ -323,10 +287,7 @@ console.log(freddie.colorChange('orange')) #### 정답: D -`colorChange`함수는 정적이에요. 정적 메소드는 그것들이 만들어지는 생성자 상에서 -만 살아있도록 설계되어 있어, 어떤 자식들도 상속받을 수 없어요. `freddie`는 자식 -이기 때문에, 이 함수는 상속되지 않고, `freddie`인스턴스에서는 이용할 수 없어요: -`TypeError`가 던져져요. +`colorChange`함수는 정적이에요. 정적 메소드는 그것들이 만들어지는 생성자 상에서만 살아있도록 설계되어 있어, 어떤 자식들도 상속받을 수 없어요. `freddie`는 자식이기 때문에, 이 함수는 상속되지 않고, `freddie`인스턴스에서는 이용할 수 없어요: `TypeError`가 던져져요.

@@ -336,9 +297,9 @@ console.log(freddie.colorChange('orange')) ###### 9. 무엇이 출력 될까요? ```javascript -let greeting // Typo! -greetign = {} -console.log(greetign) +let greeting; // Typo! +greetign = {}; +console.log(greetign); ``` - A: `{}` @@ -350,12 +311,9 @@ console.log(greetign) #### 정답: A -역 객체에 빈 객체를 방금 만들었기 때문에, 객체는 출력돼요. `greeting`을 -`greettign`으로 잘못 입력했을 경우, JS 인터프리터는 실제로 이것을 -`global.greettign = {}` (또는 브라우저의 `window.greetign = {}`) 라고 간주해요. +역 객체에 빈 객체를 방금 만들었기 때문에, 객체는 출력돼요. `greeting`을 `greettign`으로 잘못 입력했을 경우, JS 인터프리터는 실제로 이것을 `global.greettign = {}` (또는 브라우저의 `window.greetign = {}`) 라고 간주해요. -이것을 피하기 위해서, `"use strict"`를 사용할 수 있어요. 이렇게 하면 변수를 어떤 -것과 동일하게 설정하기 전에 변수를 선언했는지 확인할 수 있어요. +이것을 피하기 위해서, `"use strict"`를 사용할 수 있어요. 이렇게 하면 변수를 어떤 것과 동일하게 설정하기 전에 변수를 선언했는지 확인할 수 있어요.

@@ -366,10 +324,10 @@ console.log(greetign) ```javascript function bark() { - console.log('Woof!') + console.log("Woof!"); } -bark.animal = 'dog' +bark.animal = "dog"; ``` - A: 별일 없어요, 이건 완전히 괜찮아요! @@ -382,11 +340,9 @@ bark.animal = 'dog' #### 정답: A -함수는 객체이기 때문에, 이건 JavaScript에서는 가능해요! (윈시형 이외는 모두 객체 -) +함수는 객체이기 때문에, 이건 JavaScript에서는 가능해요! (윈시형 이외는 모두 객체) -함수는 특별한 종류의 객체예요. 당신이 쓴 코드는 실제 함수가 아니에요. 함수는 속 -성을 가진 객체예요. 이 속성은 호출이 가능해요. +함수는 특별한 종류의 객체예요. 당신이 쓴 코드는 실제 함수가 아니에요. 함수는 속성을 가진 객체예요. 이 속성은 호출이 가능해요.

@@ -397,16 +353,16 @@ bark.animal = 'dog' ```javascript function Person(firstName, lastName) { - this.firstName = firstName - this.lastName = lastName + this.firstName = firstName; + this.lastName = lastName; } -const member = new Person('Lydia', 'Hallie') -Person.getFullName = function () { - return `${this.firstName} ${this.lastName}` -} +const member = new Person("Lydia", "Hallie"); +Person.getFullName = function() { + return `${this.firstName} ${this.lastName}`; +}; -console.log(member.getFullName()) +console.log(member.getFullName()); ``` - A: `TypeError` @@ -419,21 +375,15 @@ console.log(member.getFullName()) #### 정답: A -생성자에는 보통의 객체처럼 속성을 추가할 수 없어요. 한 번에 모든 객체에 기능을 -추가하고 싶다면, 프로토타입을 사용해야 해요. 그래서 이 경우에, +생성자에는 보통의 객체처럼 속성을 추가할 수 없어요. 한 번에 모든 객체에 기능을 추가하고 싶다면, 프로토타입을 사용해야 해요. 그래서 이 경우에, ```js -Person.prototype.getFullName = function () { - return `${this.firstName} ${this.lastName}` -} +Person.prototype.getFullName = function() { + return `${this.firstName} ${this.lastName}`; +}; ``` -`member.getFullName()`은 작동해요. 이것은 왜 유익할까요? 이 메소드를 생성자 자체 -에 추가했다고 할게요. 아마도 모든 `Person` 인스턴스는 이 메소드가 필요하지 않을 -수도 있어요. 그 경우 그들은 계속해서 속성을 갖고 있기 때문에, 각각의 인스턴스를 -위한 메모리 공간을 소비하게 되어, 많은 메모리 공간을 낭비하게 될 거예요. 대신에, -프로토타입을 추가하는 것만으로, 메모리의 한 지점을 가지지만, 모든 것들은 그것에 -접근할 수 있어요. +`member.getFullName()`은 작동해요. 이것은 왜 유익할까요? 이 메소드를 생성자 자체에 추가했다고 할게요. 아마도 모든 `Person` 인스턴스는 이 메소드가 필요하지 않을 수도 있어요. 그 경우 그들은 계속해서 속성을 갖고 있기 때문에, 각각의 인스턴스를 위한 메모리 공간을 소비하게 되어, 많은 메모리 공간을 낭비하게 될 거예요. 대신에, 프로토타입을 추가하는 것만으로, 메모리의 한 지점을 가지지만, 모든 것들은 그것에 접근할 수 있어요.

@@ -444,20 +394,19 @@ Person.prototype.getFullName = function () { ```javascript function Person(firstName, lastName) { - this.firstName = firstName - this.lastName = lastName + this.firstName = firstName; + this.lastName = lastName; } -const lydia = new Person('Lydia', 'Hallie') -const sarah = Person('Sarah', 'Smith') +const lydia = new Person("Lydia", "Hallie"); +const sarah = Person("Sarah", "Smith"); -console.log(lydia) -console.log(sarah) +console.log(lydia); +console.log(sarah); ``` - A: `Person {firstName: "Lydia", lastName: "Hallie"}` 그리고 `undefined` -- B: `Person {firstName: "Lydia", lastName: "Hallie"}` 그리고 - `Person {firstName: "Sarah", lastName: "Smith"}` +- B: `Person {firstName: "Lydia", lastName: "Hallie"}` 그리고 `Person {firstName: "Sarah", lastName: "Smith"}` - C: `Person {firstName: "Lydia", lastName: "Hallie"}` 그리고 `{}` - D:`Person {firstName: "Lydia", lastName: "Hallie"}` 그리고 `ReferenceError` @@ -466,14 +415,9 @@ console.log(sarah) #### 정답: A -`sarah`에게 `new` 키워드를 사용하지 않았어요. `new`를 사용한 경우, 이것은 우리가 -만든 새로운 빈 객체를 참조해요. 그러나, `new`를 추가하지 않으면 **전역변수**를 -참조해요! +`sarah`에게 `new` 키워드를 사용하지 않았어요. `new`를 사용한 경우, 이것은 우리가 만든 새로운 빈 객체를 참조해요. 그러나, `new`를 추가하지 않으면 **전역변수**를 참조해요! -`this.firstName`은 `"Sarah"`이고, `this.lastName`은 `"Smith"`이라고 말했었어요. -(그렇지만) 우리가 실제로 한 일은 `global.firstName = 'Sarah'` 그리고 -`global.lastName = 'Smith'`를 정의하는 것이에요. `sarah` 자체는 `undefined`로 남 -아있어요. 따라서 `Person`함수의 값을 리턴하지 않아요. +`this.firstName`은 `"Sarah"`이고, `this.lastName`은 `"Smith"`이리고 말했었어요. (그렇지만) 우리는 실제로 한 일은 `global.firstName = 'Sarah'` 그리고 `global.lastName = 'Smith'`를 정의하는 것이에요. `sarah` 자체는 `undefined`로 남아있어요. 따라서 `Person`함수의 값을 리턴하지 않아요.

@@ -492,8 +436,7 @@ console.log(sarah) #### 정답: D -**capturing** 단계 동안에, 이벤트는 조상 요소를 거쳐 목표 요소까지 내려가요. 그 -런 다음 **target** 요소에 도달하고, **bubbling**이 시작돼요. +**capturing** 단계 동안에, 이벤트는 조상 요소를 거쳐 목표 요소까지 내려가요. 그런 다음 **target** 요소에 도달하고, **bubbling**이 시작돼요. @@ -512,12 +455,7 @@ console.log(sarah) #### 정답: B -**기본 객체**를 제외한, 모든 객체는 프로토타입을 가져요. 기본 객체는 사용자에 의 -해 만들어지거나 `new` 키워드를 사용하여 만들어져요. 기본 객체는 `.toString`과 같 -은 몇 개의 메소드와 속성에 접근할 수 있어요. 이것이 내장 JavaScript 메소드를 사 -용할 수 있는 이유죠! 이러한 모든 메소드는 프로토타입에서 이용할 수 있어요. -JavaScript가 당신의 객체를 직접 찾을 수 없더라도, 당신이 접근할 수 있도록 프로토 -타입 체인으로 내려가서 찾을 거에요. +**기본 객체**를 제외한, 모든 객체는 프로토타입을 가져요. 기본 객체는 사용자에 의해 만들어지거나 `new` 키워드를 사용하여 만들어져요. 기본 객체는 `.toString`과 같은 몇 개의 메소드와 속성에 접근할 수 있어요. 이것이 내장 JavaScript 메소드를 사용할 수 있는 이유죠! 이러한 모든 메소드는 프로토타입에서 이용할 수 있어요. JavaScript가 당신의 객체를 직접 찾을 수 없더라도, 당신이 접근할 수 있도록 프로토타입 체인으로 내려가서 찾을 거에요.

@@ -528,10 +466,10 @@ JavaScript가 당신의 객체를 직접 찾을 수 없더라도, 당신이 접 ```javascript function sum(a, b) { - return a + b + return a + b; } -sum(1, '2') +sum(1, "2"); ``` - A: `NaN` @@ -544,14 +482,9 @@ sum(1, '2') #### 정답: C -JavaScript는 **동적으로 만들어진 언어**에요: 특정 변수가 어떤 형인지 지정하지 않 -아요. 변수는 당신이 모르는 사이에 자동으로 다른 형으로 변환될 수 있는데, 이걸 -_암묵적 형 변환_ 이라고 불러요. **Coercion**은 하나의 형을 다른 형으로 변환해요. +JavaScript는 **동적으로 만들어진 언어**에요: 특정 변수가 어떤 형인지 지정하지 않아요. 변수는 당신이 모르는 사이에 자동으로 다른 형으로 변환될 수 있는데, 이걸 _암묵적 형 변환_ 이라고 불러요. **Coercion**은 하나의 형을 다른 형으로 변환해요. -이 예제에서, 함수가 이해하고 값을 리턴하도록, JavaScript는 숫자 `1`을 문자열로 -변환해요. 수형 (`1`)와 문자열형 (`'2'`)의 추가 중에는, 숫자는 문자열로 취급해요. -`"Hello" + "World"`처럼 문자열을 연결할 수 있어요, 따라서 여기 `"1" + "2"`는 -`"12"`을 리턴하는 일이 발생해요. +이 예제에서, 함수가 이해하고 값을 리턴하도록, JavaScript는 숫자 `1`을 문자열로 변환해요. 수형 (`1`)와 문자열형 (`'2'`)의 추가 중에는, 숫자는 문자열로 취급해요. `"Hello" + "World"`처럼 문자열을 연결할 수 있어요, 따라서 여기 `"1" + "2"`는 `"12"`을 리턴하는 일이 발생해요.

@@ -561,10 +494,10 @@ _암묵적 형 변환_ 이라고 불러요. **Coercion**은 하나의 형을 다 ###### 16. 무엇이 출력 될까요? ```javascript -let number = 0 -console.log(number++) -console.log(++number) -console.log(number) +let number = 0; +console.log(number++); +console.log(++number); +console.log(number); ``` - A: `1` `1` `2` @@ -598,15 +531,15 @@ console.log(number) ```javascript function getPersonInfo(one, two, three) { - console.log(one) - console.log(two) - console.log(three) + console.log(one); + console.log(two); + console.log(three); } -const person = 'Lydia' -const age = 21 +const person = "Lydia"; +const age = 21; -getPersonInfo`${person} is ${age} years old` +getPersonInfo`${person} is ${age} years old`; ``` - A: `"Lydia"` `21` `["", " is ", " years old"]` @@ -618,8 +551,7 @@ getPersonInfo`${person} is ${age} years old` #### 정답: B -태그드 템플릿 리터럴을 사용하는 경우, 첫 번째 인수의 값은 항상 문자열 값의 배열 -이에요. 나머지 인수는 식을 통과한 값을 얻어요. +태그드 템플릿 리터럴을 사용하는 경우, 첫 번째 인수의 값은 항상 문자열 값의 배열이에요. 나머지 인수는 식을 통과한 값을 얻어요.

@@ -631,15 +563,15 @@ getPersonInfo`${person} is ${age} years old` ```javascript function checkAge(data) { if (data === { age: 18 }) { - console.log('You are an adult!') + console.log("You are an adult!"); } else if (data == { age: 18 }) { - console.log('You are still an adult.') + console.log("You are still an adult."); } else { - console.log(`Hmm.. You don't have an age I guess`) + console.log(`Hmm.. You don't have an age I guess`); } } -checkAge({ age: 18 }) +checkAge({ age: 18 }); ``` - A: `You are an adult!` @@ -651,15 +583,11 @@ checkAge({ age: 18 }) #### 정답: C -동등성을 테스트할 때, 원시형은 그 _값_ 에 따라 비교되며, 객체는 그들의 _참조_ 에 -따라 비교돼요. JavaScript 객체가 메모리 내의 같은 장소를 참조하고 있는지를 확인 -해요. +동등성을 테스트할 때, 원시형은 그 _값_ 에 따라 비교되며, 객체는 그들의 _참조_ 에 따라 비교돼요. JavaScript 객체가 메모리 내의 같은 장소를 참조하고 있는지를 확인해요. -비교하고 있는 두 개의 객체는 그것이 없어요: 파라미터로 전달된 객체와 동등성을 확 -인하기 위해 사용한 객체는 메모리 내의 다른 장소를 참조해요. +비교하고 있는 두 개의 객체는 그것이 없어요: 파라미터로 전달된 객체와 동등성을 확인하기 위해 사용한 객체는 메모리 내의 다른 장소를 참조해요. -이것이 `{ age: 18 } === { age: 18 }` 그리고 `{ age: 18 } == { age: 18 }` 두 개 -다 `false`를 리턴하는 이유죠. +이것이 `{ age: 18 } === { age: 18 }` 그리고 `{ age: 18 } == { age: 18 }` 두 개 다 `false`를 리턴하는 이유죠.

@@ -670,10 +598,10 @@ checkAge({ age: 18 }) ```javascript function getAge(...args) { - console.log(typeof args) + console.log(typeof args); } -getAge(21) +getAge(21); ``` - A: `"number"` @@ -686,8 +614,7 @@ getAge(21) #### 정답: C -rest 파라미터 (`...args`.)는 모든 남아있는 인수들을 하나의 배열로 "집합" 해요. -배열은 객체이므로, `typeof args`는 `"object"`를 리턴해요. +rest 파라미터 (`...args`.)는 모든 남아있는 인수들을 하나의 배열로 "집합" 해요. 배열은 객체이므로, `typeof args`는 `"object"`를 리턴해요.

@@ -698,12 +625,12 @@ rest 파라미터 (`...args`.)는 모든 남아있는 인수들을 하나의 배 ```javascript function getAge() { - 'use strict' - age = 21 - console.log(age) + "use strict"; + age = 21; + console.log(age); } -getAge() +getAge(); ``` - A: `21` @@ -716,10 +643,7 @@ getAge() #### 정답: C -`"use strict"`을 사용하면, 실수로 전역 변수를 선언하지 않게 할 수 있어요. -`age`라는 변수를 선언한 적이 전혀 없고, `"use strict"`을 사용하고 있으므로, 참조 -에러를 던지게 될 거예요. 만약 `"use strict"`을 사용하지 않았다면, 이건 작동할 거 -예요, `age` 속성이 전역 객체에 추가된 것이기 때문이죠. +`"use strict"`을 사용하면, 실수로 전역 변수를 선언하지 않게 할 수 있어요. `age`라는 변수를 선언한 적이 전혀 없고, `"use strict"`을 사용하고 있으므로, 참조 에러를 던지게 될 거예요. 만약 `"use strict"`을 사용하지 않았다면, 이건 작동할 거예요, `age` 속성이 전역 객체에 추가된 것이기 때문이죠.

@@ -729,7 +653,7 @@ getAge() ###### 21. `sum`의 값은 무엇일까요? ```javascript -const sum = eval('10*10+5') +const sum = eval("10*10+5"); ``` - A: `105` @@ -742,9 +666,7 @@ const sum = eval('10*10+5') #### 정답: A -`eval` 문자열로서 통과된 코드를 평가해요. 이 경우와 같이 만약 그것이 표현식이라 -면, 표현 식을 평가해요. 표현 식은 `10 * 10 + 5`이에요. 이것은 숫자 `105`를 리턴 -해요. +`eval` 문자열로서 통과된 코드를 평가해요. 이 경우와 같이 만약 그것이 표현식이라면, 표현 식을 평가해요. 표현 식은 `10 * 10 + 5`이에요. 이것은 숫자 `105`를 리턴해요.

@@ -754,7 +676,7 @@ const sum = eval('10*10+5') ###### 22. cool_secret에 몇 시간이나 접근이 가능할까요? ```javascript -sessionStorage.setItem('cool_secret', 123) +sessionStorage.setItem("cool_secret", 123); ``` - A: 영원히, 데이터는 사라지지 않아요. @@ -769,8 +691,7 @@ sessionStorage.setItem('cool_secret', 123) `sessionStorage`에 저장된 데이터는 _탭_ 을 닫은 후에 삭제돼요. -만약 `localStorage`를 사용했다면, 예를 들어 `localStorage.clear()`를 호출하지 않 -는 한, 데이터는 영원할 거예요. +만약 `localStorage`를 사용했다면, 예를 들어 `localStorage.clear()`를 호출하지 않는 한, 데이터는 영원할 거예요.

@@ -780,10 +701,10 @@ sessionStorage.setItem('cool_secret', 123) ###### 23. 무엇이 출력 될까요? ```javascript -var num = 8 -var num = 10 +var num = 8; +var num = 10; -console.log(num) +console.log(num); ``` - A: `8` @@ -796,8 +717,7 @@ console.log(num) #### 정답: B -`var` 키워드를 사용하면, 같은 이름으로 복수의 변수를 선언할 수 있어요. 변수는 최 -신의 값을 유지해요. +`var` 키워드를 사용하면, 같은 이름으로 복수의 변수를 선언할 수 있어요. 변수는 최신의 값을 유지해요. 블록 스코프의 `let` 또는 `const`에서는 할 수 없어요. @@ -809,13 +729,13 @@ console.log(num) ###### 24. 무엇이 출력 될까요? ```javascript -const obj = { 1: 'a', 2: 'b', 3: 'c' } -const set = new Set([1, 2, 3, 4, 5]) +const obj = { 1: "a", 2: "b", 3: "c" }; +const set = new Set([1, 2, 3, 4, 5]); -obj.hasOwnProperty('1') -obj.hasOwnProperty(1) -set.has('1') -set.has(1) +obj.hasOwnProperty("1"); +obj.hasOwnProperty(1); +set.has("1"); +set.has(1); ``` - A: `false` `true` `false` `true` @@ -828,11 +748,9 @@ set.has(1) #### 정답: C -모든 객체 키는(심볼 제외) 문자열로 직접 입력하지 않아도, 내부적으로는 문자열이에 -요. 이것이 `obj.hasOwnProperty('1')`도 true를 리턴하는 이유죠. +모든 객체 키는(심볼 제외) 문자열로 직접 입력하지 않아도, 내부적으로는 문자열이에요. 이것이 `obj.hasOwnProperty('1')`도 true를 리턴하는 이유죠. -set에서는 작동하지 않아요. set에는 `'1'`이 없어요: `set.has('1')`는 `false`를 리 -턴해요. 그것은 수형인 `1`을 가지고 있어, `set.has(1)`는 `true`를 리턴해요. +set에서는 작동하지 않아요. set에는 `'1'`이 없어요: `set.has('1')`는 `false`를 리턴해요. 그것은 수형인 `1`을 가지고 있어, `set.has(1)`는 `true`를 리턴해요.

@@ -842,8 +760,8 @@ set에서는 작동하지 않아요. set에는 `'1'`이 없어요: `set.has('1') ###### 25. 무엇이 출력 될까요? ```javascript -const obj = { a: 'one', b: 'two', a: 'three' } -console.log(obj) +const obj = { a: "one", b: "two", a: "three" }; +console.log(obj); ``` - A: `{ a: "one", b: "two" }` @@ -856,8 +774,7 @@ console.log(obj) #### 정답: C -같은 이름의 키를 두 개 가지고 있다면, 여전히 첫 번째 위치에 있지만, 마지막에 지 -정된 값으로 대체될 거예요. +같은 이름의 키를 두 개 가지고 있다면, 여전히 첫 번째 위치에 있지만, 마지막에 지정된 값으로 대체될 거예요.

@@ -875,8 +792,7 @@ console.log(obj) #### 정답: A -기본적인 실행 콘텍스트는 전역 실행 문장이에요: 당신의 코드 모든 곳에서 접근할 수 -있어요. +기본적인 실행 콘텍스트는 전역 실행 문장이에요: 당신의 코드 모든 곳에서 접근할 수 있어요.

@@ -887,8 +803,8 @@ console.log(obj) ```javascript for (let i = 1; i < 5; i++) { - if (i === 3) continue - console.log(i) + if (i === 3) continue; + console.log(i); } ``` @@ -913,12 +829,12 @@ for (let i = 1; i < 5; i++) { ```javascript String.prototype.giveLydiaPizza = () => { - return 'Just give Lydia pizza already!' -} + return "Just give Lydia pizza already!"; +}; -const name = 'Lydia' +const name = "Lydia"; -name.giveLydiaPizza() +name.giveLydiaPizza(); ``` - A: `"Just give Lydia pizza already!"` @@ -931,9 +847,7 @@ name.giveLydiaPizza() #### 정답: A -`String`은 내장 생성자로 속성을 추가할 수 있어요. 단지 프로토타입이라는 메소드를 -추가했어요. 원시형 문자열은 문자열 프로토타입 함수에 의해 생성된 문자열 객체로 -자동 변환돼요. 그래서, 모든 문자열(문자열 객체)은 그 메소드에 접근할 수 있어요! +`String`은 내장 생성자로 속성을 추가할 수 있어요. 단지 프로토타입이라는 메소드를 추가했어요. 원시형 문자열은 문자열 프로토타입 함수에 의해 생성된 문자열 객체로 자동 변환돼요. 그래서, 모든 문자열(문자열 객체)은 그 메소드에 접근할 수 있어요!

@@ -943,14 +857,14 @@ name.giveLydiaPizza() ###### 29. 무엇이 출력 될까요? ```javascript -const a = {} -const b = { key: 'b' } -const c = { key: 'c' } +const a = {}; +const b = { key: "b" }; +const c = { key: "c" }; -a[b] = 123 -a[c] = 456 +a[b] = 123; +a[c] = 456; -console.log(a[b]) +console.log(a[b]); ``` - A: `123` @@ -963,16 +877,11 @@ console.log(a[b]) #### 정답: B -객체 키는 자동으로 문자열로 변환돼요. 객체 `a`의 키 값으로 `123`을 세팅하려고 해 -요. +객체 키는 자동으로 문자열로 변환돼요. 객체 `a`의 키 값으로 `123`을 세팅하려고 해요. -그러나, 객체를 문자열화 하면 `"[object Object]"`가 돼요. 그래서 여기서 말하고자 -하는 건 `a["object Object"] = 123`이라는 거예요. 그 후, 같은 일을 다시 시도해요. -`c`는 암묵적으로 문자열화 한 다른 객체에요. 그래서 `a["object Object"] = 456`이 -돼요. +그러나, 객체를 문자열화 하면 `"[object Object]"`가 돼요. 그래서 여기서 말하고자 하는 건 `a["object Object"] = 123`이라는 거예요. 그 후, 같은 일을 다시 시도해요. `c`는 암묵적으로 문자열화 한 다른 객체에요. 그래서 `a["object Object"] = 456`이 돼요. -그 후, `a[b]`는 출력하면 실제로는 `a["object Object"]`에요. 단지 `456`을 설정했 -기 때문에, `456`을 리턴해요. +그 후, `a[b]`는 출력하면 실제로는 `a["object Object"]`에요. 단지 `456`을 설정했기 때문에, `456`을 리턴해요.

@@ -982,13 +891,13 @@ console.log(a[b]) ###### 30. 무엇이 출력 될까요? ```javascript -const foo = () => console.log('First') -const bar = () => setTimeout(() => console.log('Second')) -const baz = () => console.log('Third') +const foo = () => console.log("First"); +const bar = () => setTimeout(() => console.log("Second")); +const baz = () => console.log("Third"); -bar() -foo() -baz() +bar(); +foo(); +baz(); ``` - A: `First` `Second` `Third` @@ -1003,11 +912,9 @@ baz() 처음에 `setTimeout`함수를 호출했어요. 그러나 그것은 마지막에 출력돼요. -브라우저에는 런타임 엔진뿐만 아니라 `WebAPI`라고 불리는 것도 있기 때문이에요. -`WebAPI`는 `setTimeout`함수를 최초에 부여하는데, DOM을 예로 들 수 있어요. +브라우저에는 런타임 엔진뿐만 아니라 `WebAPI`라고 불리는 것도 있기 때문이에요. `WebAPI`는 `setTimeout`함수를 최초에 부여하는데, DOM을 예로 들 수 있어요. -_callback_ 이 WebAPI에 푸시된 후, `setTimeout`함수 자체(callback이 아니에요!)는 -stack에 사라졌어요. +_callback_ 이 WebAPI에 푸시된 후, `setTimeout`함수 자체(callback이 아니에요!)는 stack에 사라졌어요. @@ -1019,13 +926,11 @@ stack에 사라졌어요. -WebAPI는 준비가 될 때마다 stack에 항목을 추가할 수 없어요. 대신에, _queue_ 라고 -불리는 것에 callback 함수를 푸시해요. +WebAPI는 준비가 될 때마다 stack에 항목을 추가할 수 없어요. 대신에, _queue_ 라고 불리는 것에 callback 함수를 푸시해요. -여기서 event loop가 작동하기 시작해요. **event loop**는 stack과 task queue를 봐 -요. stack이 비어있다면, queue에 첫 번째의 것을 가져다가 stack 위로 푸시해요. +여기서 event loop가 작동하기 시작해요. **event loop**는 stack과 task queue를 봐요. stack이 비어있다면, queue에 첫 번째의 것을 가져다가 stack 위로 푸시해요. @@ -1041,7 +946,9 @@ WebAPI는 준비가 될 때마다 stack에 항목을 추가할 수 없어요. ```html
- +
``` @@ -1056,8 +963,7 @@ WebAPI는 준비가 될 때마다 stack에 항목을 추가할 수 없어요. #### 정답: C -가장 깊이 중첩된 요소가 이벤트를 발생시킬 이벤트 대상이에요. -`event.stopPropagation`을 통해서 버블링을 중단할 수 있어요. +가장 깊이 중첩된 요소가 이벤트를 발생시킬 이벤트 대상이에요. `event.stopPropagation`을 통해서 버블링을 중단할 수 있어요.

@@ -1068,7 +974,9 @@ WebAPI는 준비가 될 때마다 stack에 항목을 추가할 수 없어요. ```html
-

Click here!

+

+ Click here! +

``` @@ -1082,10 +990,7 @@ WebAPI는 준비가 될 때마다 stack에 항목을 추가할 수 없어요. #### 정답: A -`p`를 클릭하면, 2개의 로그를 볼 수 있어요: `p` 그리고 `div`. 이벤트의 전파 중에 -는 3단계가 있어요: 캡처링, 타겟, 버블링. 기본적으로, 이벤트 핸들러는 버블링 단계 -에서 시작돼요. (`useCapture`를 `true`로 설정하지 않는 한). 가장 깊게 중첩된 요소 -로부터 바깥쪽으로 나가요. +`p`를 클릭하면, 2개의 로그를 볼 수 있어요: `p` 그리고 `div`. 이벤트의 전파 중에는 3단계가 있어요: 캡처링, 타겟, 버블링. 기본적으로, 이벤트 핸들러는 버블링 단계에서 시작돼요. (`useCapture`를 `true`로 설정하지 않는 한). 가장 깊게 중첩된 요소로부터 바깥쪽으로 나가요.

@@ -1095,14 +1000,14 @@ WebAPI는 준비가 될 때마다 stack에 항목을 추가할 수 없어요. ###### 33. 무엇이 출력 될까요? ```javascript -const person = { name: 'Lydia' } +const person = { name: "Lydia" }; function sayHi(age) { - console.log(`${this.name} is ${age}`) + console.log(`${this.name} is ${age}`); } -sayHi.call(person, 21) -sayHi.bind(person, 21) +sayHi.call(person, 21); +sayHi.bind(person, 21); ``` - A: `undefined is 21` `Lydia is 21` @@ -1115,11 +1020,9 @@ sayHi.bind(person, 21) #### 정답: D -두 개 모두, `this` 키워드를 참조하고자 하는 객체로 보낼 수 있어요. 그러나, -`.call`은 _즉시 실행돼요_! +두 개 모두, `this` 키워드를 참조하고자 하는 객체로 보낼 수 있어요. 그러나, `.call`은 _즉시 실행돼요_! -`.bind.`는 함수의 _복사본_ 을 리턴하지만, 바인딩 콘텍스트죠! 이건 즉시 실행되지 -않아요. +`.bind.`는 함수의 _복사본_ 을 리턴하지만, 바인딩 콘텍스트죠! 이건 즉시 실행되지 않아요.

@@ -1130,10 +1033,10 @@ sayHi.bind(person, 21) ```javascript function sayHi() { - return (() => 0)() + return (() => 0)(); } -console.log(typeof sayHi()) +console.log(typeof sayHi()); ``` - A: `"object"` @@ -1146,12 +1049,9 @@ console.log(typeof sayHi()) #### 정답: B -`sayHi`함수는 즉시 호출 함수(IIFE)로서 리턴된 값을 리턴해요. 이 함수는 `0`을 리 -턴하고, 형은 `"number"`이에요. +`sayHi`함수는 즉시 호출 함수(IIFE)로서 리턴된 값을 리턴해요. 이 함수는 `0`을 리턴하고, 형은 `"number"`이에요. -참고: 단 7개의 내장형이 있어요: `null`, `undefined`, `boolean`, `number`, -`string`, `object`, `symbol` 그리고 `bigint`. `"function"`은 객체이기 때문에 형 -이 아니라 `"object"`형이에요. +참고: 단 7개의 내장형이 있어요: `null`, `undefined`, `boolean`, `number`, `string`, `object`, `symbol` 그리고 `bigint`. `"function"`은 객체이기 때문에 형이 아니라 `"object"`형이에요.

@@ -1161,12 +1061,12 @@ console.log(typeof sayHi()) ###### 35. 이 값들 중 어느 것이 거짓 같은 값 일까요? ```javascript -0 -new Number(0) -;('') -;(' ') -new Boolean(false) -undefined +0; +new Number(0); +(""); +(" "); +new Boolean(false); +undefined; ``` - A: `0`, `''`, `undefined` @@ -1198,7 +1098,7 @@ undefined ###### 36. 무엇이 출력 될까요? ```javascript -console.log(typeof typeof 1) +console.log(typeof typeof 1); ``` - A: `"number"` @@ -1211,7 +1111,8 @@ console.log(typeof typeof 1) #### 정답: B -`typeof 1` 은 `"number"`를 리턴해요. `typeof "number"`은 `"string"`을 리턴해요. +`typeof 1` 은 `"number"`를 리턴해요. +`typeof "number"`은 `"string"`을 리턴해요.

@@ -1221,9 +1122,9 @@ console.log(typeof typeof 1) ###### 37. 무엇이 출력 될까요? ```javascript -const numbers = [1, 2, 3] -numbers[10] = 11 -console.log(numbers) +const numbers = [1, 2, 3]; +numbers[10] = 11; +console.log(numbers); ``` - A: `[1, 2, 3, 7 x null, 11]` @@ -1236,14 +1137,12 @@ console.log(numbers) #### 정답: C -배열의 길이를 초과한 값을 배열의 요소로 설정하고자 할 때, JavaScript는 "empty -slots"라고 불리는 것을 생성해요. 이것은 실제로 `undefined`의 값을 가지고 있지만, -다음과 같은 것을 보게 될 거예요: +배열의 길이를 초과한 값을 배열의 요소로 설정하고자 할 때, JavaScript는 "empty slots"라고 불리는 것을 생성해요. 이것은 실제로 `undefined`의 값을 가지고 있지만, 다음과 같은 것을 보게 될 거예요: `[1, 2, 3, 7 x empty, 11]` -depending on where you run it (it's different for every browser, node, etc.) 실 -행 위치에 따라 달라요 (브라우저, node 등마다 달라요.) +depending on where you run it (it's different for every browser, node, etc.) +실행 위치에 따라 달라요 (브라우저, node 등마다 달라요.)

@@ -1253,17 +1152,17 @@ depending on where you run it (it's different for every browser, node, etc.) 실 ###### 38. 무엇이 출력 될까요? ```javascript -;(() => { - let x, y +(() => { + let x, y; try { - throw new Error() + throw new Error(); } catch (x) { - ;(x = 1), (y = 2) - console.log(x) + (x = 1), (y = 2); + console.log(x); } - console.log(x) - console.log(y) -})() + console.log(x); + console.log(y); +})(); ``` - A: `1` `undefined` `2` @@ -1276,15 +1175,11 @@ depending on where you run it (it's different for every browser, node, etc.) 실 #### 정답: A -`catch`블록은 `x`의 인수를 받아요. 이것은 인수를 전달할 때 변수로서의 `x`와는 달 -라요. 이 `x` 변수는 블록-스코프예요. +`catch`블록은 `x`의 인수를 받아요. 이것은 인수를 전달할 때 변수로서의 `x`와는 달라요. 이 `x` 변수는 블록-스코프예요. -후에, 블록-스코프 변수는 `1`로 설정하고, 변수 `y`의 값을 설정해요. 여기서, 블록- -스코프의 변수 `x`를 출력하는데, 이것은 `1`이에요. +후에, 블록-스코프 변수는 `1`로 설정하고, 변수 `y`의 값을 설정해요. 여기서, 블록-스코프의 변수 `x`를 출력하는데, 이것은 `1`이에요. -`catch` 블록 밖에서, `x`는 여전히 `undefined`이고 `y`는 `2`이에요. `catch` 블록 -밖에서 `console.log(x)`를 출력하면, `undefined`를 리턴하고. 그리고 `y`는 `2`를 -리턴해요. +`catch` 블록 밖에서, `x`는 여전히 `undefined`이고 `y`는 `2`이에요. `catch` 블록 밖에서 `console.log(x)`를 출력하면, `undefined`를 리턴하고. 그리고 `y`는 `2`를 리턴해요.

@@ -1305,15 +1200,9 @@ depending on where you run it (it's different for every browser, node, etc.) 실 JavaScript는 원시형과 객체만 가지고 있어요. -원시형은 `boolean`, `null`, `undefined`, `bigint`, `number`, `string` 그리고 -`symbol`이 있어요. +원시형은 `boolean`, `null`, `undefined`, `bigint`, `number`, `string` 그리고 `symbol`이 있어요. -원시형과 객체를 구별하는 법은 원시형에는 속성이나 메소드가 없어요. 그러나 -`'foo'.toUpperCase()`는 `'FOO'`로 평가되어, `TypeError`의 결과가 되지 않아요. 문 -자열과 같은 원시형이 속성 또는 메소드에 접근하려고 할 때, JavaScript는 래퍼 클래 -스 중 하나인 `String`을 사용하여 암묵적으로 감싸고, 표현 식이 평가된 후 즉시 래 -퍼를 폐기하기 때문이에요. `null` 그리고 `undefined`를 제외한 모든 원시형은 이러 -한 행동을 합니다. +원시형과 객체를 구별하는 법은 원시형에는 속성이나 메소드가 없어요. 그러나 `'foo'.toUpperCase()`는 `'FOO'`로 평가되어, `TypeError`의 결과가 되지 않아요. 문자열과 같은 원시형이 속성 또는 메소드에 접근하려고 할 때, JavaScript는 래퍼 클래스 중 하나인 `String`을 사용하여 암묵적으로 감싸고, 표현 식이 평가된 후 즉시 래퍼를 폐기하기 때문이에요. `null` 그리고 `undefined`를 제외한 모든 원시형은 이러한 행동을 합니다.

@@ -1323,15 +1212,12 @@ JavaScript는 원시형과 객체만 가지고 있어요. ###### 40. 무엇이 출력 될까요? ```javascript -;[ - [0, 1], - [2, 3], -].reduce( +[[0, 1], [2, 3]].reduce( (acc, cur) => { - return acc.concat(cur) + return acc.concat(cur); }, - [1, 2], -) + [1, 2] +); ``` - A: `[0, 1, 2, 3, 1, 2]` @@ -1344,12 +1230,9 @@ JavaScript는 원시형과 객체만 가지고 있어요. #### 정답: C -`[1, 2]`은 초깃값이에요. 이것이 최초의 값으로, 제일 처음의 `acc`의 값이에요. 처 -음 라운드 동안에 `acc`는 `[1,2]`이며, `cur`은 `[0, 1]`이에요. 그것들을 연결하면 -결과적으로 `[1, 2, 0, 1]`이 돼요. +`[1, 2]`은 초깃값이에요. 이것이 최초의 값으로, 제일 처음의 `acc`의 값이에요. 처음 라운드 동안에 `acc`는 `[1,2]`이며, `cur`은 `[0, 1]`이에요. 그것들을 연결하면 결과적으로 `[1, 2, 0, 1]`이 돼요. -그 후, `[1, 2, 0, 1]`은 `acc`이고, `[2, 3]`은 `cur`이 에요. 그것들을 연결하면 -`[1, 2, 0, 1, 2, 3]`을 얻게 돼요. +그 후, `[1, 2, 0, 1]`은 `acc`이고, `[2, 3]`은 `cur`이 에요. 그것들을 연결하면 `[1, 2, 0, 1, 2, 3]`을 얻게 돼요.

@@ -1359,9 +1242,9 @@ JavaScript는 원시형과 객체만 가지고 있어요. ###### 41. 무엇이 출력 될까요? ```javascript -!!null -!!'' -!!1 +!!null; +!!""; +!!1; ``` - A: `false` `true` `false` @@ -1374,11 +1257,9 @@ JavaScript는 원시형과 객체만 가지고 있어요. #### 정답: B -`null`은 거짓 같은 값이에요. `!null`은 `true`를 리턴해요. `!true`는 `false`를 리 -턴해요. +`null`은 거짓 같은 값이에요. `!null`은 `true`를 리턴해요. `!true`는 `false`를 리턴해요. -`""` 은 거짓 같은 값이에요. `!""`은 `true`를 리턴해요. `!true`는 `false`를 리턴 -해요. +`""` 은 거짓 같은 값이에요. `!""`은 `true`를 리턴해요. `!true`는 `false`를 리턴해요. `1`은 참 같은 값이에요. `!1`은 `false`를 리턴해요. `!false`는`true`를 리턴해요. @@ -1390,7 +1271,7 @@ JavaScript는 원시형과 객체만 가지고 있어요. ###### 42. `setInterval` 메소드는 브라우저에게 무엇을 리턴 할까요? ```javascript -setInterval(() => console.log('Hi'), 1000) +setInterval(() => console.log("Hi"), 1000); ``` - A: 유니크한 id @@ -1403,8 +1284,7 @@ setInterval(() => console.log('Hi'), 1000) #### 정답: A -이것은 유니크한 id를 리턴해요. 이 id는 `clearInterval()` 함수로 간격을 없애기 위 -해 사용될 수 있어요. +이것은 유니크한 id를 리턴해요. 이 id는 `clearInterval()` 함수로 간격을 없애기 위해 사용될 수 있어요.

@@ -1414,7 +1294,7 @@ setInterval(() => console.log('Hi'), 1000) ###### 43. 이것은 무엇을 리턴할까요? ```javascript -;[...'Lydia'] +[..."Lydia"]; ``` - A: `["L", "y", "d", "i", "a"]` @@ -1427,8 +1307,7 @@ setInterval(() => console.log('Hi'), 1000) #### 정답: A -문자열은 반복 가능한 객체예요. 스프레드 연산자는 반복 가능한 객체의 모든 문자를 -1개의 요소로 매핑해요. +문자열은 반복 가능한 객체예요. 스프레드 연산자는 반복 가능한 객체의 모든 문자를 1개의 요소로 매핑해요.

@@ -1439,14 +1318,14 @@ setInterval(() => console.log('Hi'), 1000) ```javascript function* generator(i) { - yield i - yield i * 2 + yield i; + yield i * 2; } -const gen = generator(10) +const gen = generator(10); -console.log(gen.next().value) -console.log(gen.next().value) +console.log(gen.next().value); +console.log(gen.next().value); ``` - A: `[0, 10], [10, 20]` @@ -1459,19 +1338,11 @@ console.log(gen.next().value) #### 정답: C -보통의 함수는 호출 후에 중단할 수 없어요. 하지만, 제너레이터 함수는 중간에 "멈췄 -다가", 나중에 중단된 부분부터 계속할 수 있어요. 제너레이터 함수는 `yield` 키워드 -를 만날 때마다, yield 뒤에 지정된 값을 넘겨줘요. 제너레이터 함수에서는 값을 _리 -턴_ 하지 않고, _넘겨준다_ 는 것을 유의하세요. +보통의 함수는 호출 후에 중단할 수 없어요. 하지만, 제너레이터 함수는 중간에 "멈췄다가", 나중에 중단된 부분부터 계속할 수 있어요. 제너레이터 함수는 `yield` 키워드를 만날 때마다, yield 뒤에 지정된 값을 넘겨줘요. 제너레이터 함수에서는 값을 _리턴_ 하지 않고, _넘겨준다_ 는 것을 유의하세요. -우선, 제너레이터 함수에서 `i`를 `10`으로 초기화해요. `next()` 메소드를 사용해 제 -너레이터 함수를 호출해요. 처음에 제너레이터 함수를 호출하면, `i`은 `10`이에요. -첫 번째 `yield` 키워드를 만났어요: 그것은 `i`의 값을 넘겨줘요. 이제 제너레이터는 -"멈추고", `10`을 출력해요. +우선, 제너레이터 함수에서 `i`를 `10`으로 초기화해요. `next()` 메소드를 사용해 제너레이터 함수를 호출해요. 처음에 제너레이터 함수를 호출하면, `i`은 `10`이에요. 첫 번째 `yield` 키워드를 만났어요: 그것은 `i`의 값을 넘겨줘요. 이제 제너레이터는 "멈추고", `10`을 출력해요. -그 후, `next()` 메소드를 사용해 다시 한번 함수를 호출해요. `i`는 여전히 `10`이에 -요. 이제, 다음 `yield` 키워드를 만나 `i * 2`를 넘겨줘요. `i`는 `10`이므로, -`10 * 2`, 즉 `20`을 리턴해요. 결과는 `10, 20`이에요. +그 후, `next()` 메소드를 사용해 다시 한번 함수를 호출해요. `i`는 여전히 `10`이에요. 이제, 다음 `yield` 키워드를 만나 `i * 2`를 넘겨줘요. `i`는 `10`이므로, `10 * 2`, 즉 `20`을 리턴해요. 결과는 `10, 20`이에요.

@@ -1482,14 +1353,14 @@ console.log(gen.next().value) ```javascript const firstPromise = new Promise((res, rej) => { - setTimeout(res, 500, 'one') -}) + setTimeout(res, 500, "one"); +}); const secondPromise = new Promise((res, rej) => { - setTimeout(res, 100, 'two') -}) + setTimeout(res, 100, "two"); +}); -Promise.race([firstPromise, secondPromise]).then(res => console.log(res)) +Promise.race([firstPromise, secondPromise]).then(res => console.log(res)); ``` - A: `"one"` @@ -1502,11 +1373,7 @@ Promise.race([firstPromise, secondPromise]).then(res => console.log(res)) #### 정답: B -복수의 프로미스를 `Promise.race` 메소드에 넘겨주면, _최초_ 의 프로미스를 해결/거 -부해요. `setTimeout` 메소드에 타이머를 전달해요: 첫 번째 프로미스 -(`firstPromise`)에는 500ms, 두 번째 프로미스(`secondPromise`)에는 100ms. 이것은 -`'two'`의 값을 가진 `secondPromise`가 최초로 해결한다는 것을 의미해요. 이제 -`res`는 `'two'`의 값을 유지하고 출력돼요. +복수의 프로미스를 `Promise.race` 메소드에 넘겨주면, _최초_ 의 프로미스를 해결/거부해요. `setTimeout` 메소드에 타이머를 전달해요: 첫 번째 프로미스(`firstPromise`)에는 500ms, 두 번째 프로미스(`secondPromise`)에는 100ms. 이것은 `'two'`의 값을 가진 `secondPromise`가 최초로 해결한다는 것을 의미해요. 이제 `res`는 `'two'`의 값을 유지하고 출력돼요.

@@ -1516,11 +1383,11 @@ Promise.race([firstPromise, secondPromise]).then(res => console.log(res)) ###### 46. 무엇이 출력 될까요? ```javascript -let person = { name: 'Lydia' } -const members = [person] -person = null +let person = { name: "Lydia" }; +const members = [person]; +person = null; -console.log(members) +console.log(members); ``` - A: `null` @@ -1537,10 +1404,7 @@ console.log(members) -그 후, `members`라는 변수를 선언해요. 배열의 첫 번째 요소에 `person` 변수의 값을 -대입해요. 서로를 같게 설정하면 _참조_ 에 의해 상호작용해요. 어떤 변수에서 다른 -변수로 참조를 할당하면, 그 참조의 _복사본_ 을 만들어요. (그들은 _같은_ 참조를 가 -지고 있지 않다는 것을 유의하세요!) +그 후, `members`라는 변수를 선언해요. 배열의 첫 번째 요소에 `person` 변수의 값을 대입해요. 서로를 같게 설정하면 _참조_ 에 의해 상호작용해요. 어떤 변수에서 다른 변수로 참조를 할당하면, 그 참조의 _복사본_ 을 만들어요. (그들은 _같은_ 참조를 가지고 있지 않다는 것을 유의하세요!) @@ -1548,11 +1412,7 @@ console.log(members) -배열의 첫 번째 요소는 객체에 대한 다른 (복사된) 참조를 가지고 있기 때문에, -`person` 변수의 값만 변경하고, 배열의 첫 번째 요소는 변경할 수 없어요. -`members`의 첫 번째 요소는 여전히 원본 객체에 대한 참조를 유지하고 있어요. -`members` 배열을 출력할 때, 첫 번째 요소는 여전히 객체의 값을 유지하고 있어 로그 -가 출력돼요. +배열의 첫 번째 요소는 객체에 대한 다른 (복사된) 참조를 가지고 있기 때문에, `person` 변수의 값만 변경하고, 배열의 첫 번째 요소는 변경할 수 없어요. `members`의 첫 번째 요소는 여전히 원본 객체에 대한 참조를 유지하고 있어요. `members` 배열을 출력할 때, 첫 번째 요소는 여전히 객체의 값을 유지하고 있어 로그가 출력돼요.

@@ -1563,12 +1423,12 @@ console.log(members) ```javascript const person = { - name: 'Lydia', - age: 21, -} + name: "Lydia", + age: 21 +}; for (const item in person) { - console.log(item) + console.log(item); } ``` @@ -1582,10 +1442,7 @@ for (const item in person) { #### 정답: B -`for-in` 루프를 사용하면, 객체 키를 통해서 반복할 수 있는데, 이 경우에서는 -`name` 그리고 `age`에요. 내부적으로, 객체 키는 문자열이에요 (심볼이 아니라면 말 -이죠). 모든 루프에서, `item`의 값은 반복된 현재의 키 값으로 설정해요. 우선, -`item`은 `name`으로 출력돼요. 그 후, `item`은 `age`로 출력돼요. +`for-in` 루프를 사용하면, 객체 키를 통해서 반복할 수 있는데, 이 경우에서는 `name` 그리고 `age`에요. 내부적으로, 객체 키는 문자열이에요 (심볼이 아니라면 말이죠). 모든 루프에서, `item`의 값은 반복된 현재의 키 값으로 설정해요. 우선, `item`은 `name`으로 출력돼요. 그 후, `item`은 `age`로 출력돼요.

@@ -1595,7 +1452,7 @@ for (const item in person) { ###### 48. 무엇이 출력 될까요? ```javascript -console.log(3 + 4 + '5') +console.log(3 + 4 + "5"); ``` - A: `"345"` @@ -1608,15 +1465,11 @@ console.log(3 + 4 + '5') #### 정답: B -연산자 결합성은 왼쪽에서 오른쪽 또는 오른쪽에서 왼쪽으로 컴파일러가 표현 식을 평 -가하는 순서가 돼요. 이것은 연산자가 _같은_ 우선순위를 가진 경우에만 해당돼요. 연 -산자의 종류는 한 개뿐이에요: `+`. 게다가, 결합성은 왼쪽에서 오른쪽이에요. +연산자 결합성은 왼쪽에서 오른쪽 또는 오른쪽에서 왼쪽으로 컴파일러가 표현 식을 평가하는 순서가 돼요. 이것은 연산자가 _같은_ 우선순위를 가진 경우에만 해당돼요. 연산자의 종류는 한 개뿐이에요: `+`. 게다가, 결합성은 왼쪽에서 오른쪽이에요. 처음으로 `3 + 4`가 평가돼요. 결과는 숫자 `7`이에요. -`7 + '5'`의 결과는 강제성 때문에 `"75"`가 돼요. JavaScript는 숫자 `7`을 문자열로 -변환하고, (자세한 내용은) 질문 15를 보세요. `+` 연산자를 사용해서 두 개의 문자열 -을 연결할 수 있어요. `"7" + "5"`의 결과는 `"75"`이에요. +`7 + '5'`의 결과는 강제성 때문에 `"75"`가 돼요. JavaScript는 숫자 `7`을 문자열로 변환하고, (자세한 내용은) 질문 15를 보세요. `+` 연산자를 사용해서 두 개의 문자열을 연결할 수 있어요. `"7" + "5"`의 결과는 `"75"`이에요.

@@ -1626,7 +1479,7 @@ console.log(3 + 4 + '5') ###### 49. `num`의 값은 무엇일까요? ```javascript -const num = parseInt('7*6', 10) +const num = parseInt("7*6", 10); ``` - A: `42` @@ -1639,13 +1492,9 @@ const num = parseInt('7*6', 10) #### 정답: C -문자열의 첫 번째 숫자만 리턴돼요. _진법_ 에 근거하여 (파싱하고자 하는 숫자의 기 -준을 명시하기 위한 두 번째 인수: 기본적인 10진수, 6진수, 8진수, 2진수 등), -`parseInt`는 문자열 내의 문자가 타당한지 여부를 확인해요. 진수에 유효한 숫자가 -아닌 문자를 만나면, 파싱을 멈추고, 다음 문자를 무시해요. +문자열의 첫 번째 숫자만 리턴돼요. _진법_ 에 근거하여 (파싱하고자 하는 숫자의 기준을 명시하기 위한 두 번째 인수: 기본적인 10진수, 6진수, 8진수, 2진수 등), `parseInt`는 문자열 내의 문자가 타당한지 여부를 확인해요. 진수에 유효한 숫자가 아닌 문자를 만나면, 파싱을 멈추고, 다음 문자를 무시해요. -`*`은 유효한 숫자가 아니에요. `"7"`만 십진수의 `7`로 파싱 돼요. 이제 `num`은 -`7`의 값을 유지해요. +`*`은 유효한 숫자가 아니에요. `"7"`만 십진수의 `7`로 파싱 돼요. 이제 `num`은 `7`의 값을 유지해요.

@@ -1655,10 +1504,10 @@ const num = parseInt('7*6', 10) ###### 50. 무엇이 출력 될까요? ```javascript -;[1, 2, 3].map(num => { - if (typeof num === 'number') return - return num * 2 -}) +[1, 2, 3].map(num => { + if (typeof num === "number") return; + return num * 2; + }); ``` - A: `[]` @@ -1671,13 +1520,9 @@ const num = parseInt('7*6', 10) #### 정답: C -배열을 매핑할 때, `num`의 값은 헌재 순환하고 있는 요소예요. 이 경우, 요소는 숫자 -이기 때문에, if 문의 조건 `typeof num === "number"`는 `true`를 리턴해요. map 합 -수는 새로운 배열을 만들고 함수에서 리턴된 값을 삽입해요. +배열을 매핑할 때, `num`의 값은 헌재 순환하고 있는 요소예요. 이 경우, 요소는 숫자이기 때문에, if 문의 조건 `typeof num === "number"`는 `true`를 리턴해요. map 합수는 새로운 배열을 만들고 함수에서 리턴된 값을 삽입해요. -그러나, 값을 리턴하지 않아요. 함수는 값을 리턴하지 않을 때, `undefined`를 리턴해 -요. 배열에서의 모든 요소에 대해 블록 함수가 호출되기 때문에, 각 요소에 대해 -`undefined`를 리턴해요. +그러나, 값을 리턴하지 않아요. 함수는 값을 리턴하지 않을 때, `undefined`를 리턴해요. 배열에서의 모든 요소에 대해 블록 함수가 호출되기 때문에, 각 요소에 대해 `undefined`를 리턴해요.

@@ -1688,16 +1533,16 @@ const num = parseInt('7*6', 10) ```javascript function getInfo(member, year) { - member.name = 'Lydia' - year = '1998' + member.name = "Lydia"; + year = "1998"; } -const person = { name: 'Sarah' } -const birthYear = '1997' +const person = { name: "Sarah" }; +const birthYear = "1997"; -getInfo(person, birthYear) +getInfo(person, birthYear); -console.log(person, birthYear) +console.log(person, birthYear); ``` - A: `{ name: "Lydia" }, "1997"` @@ -1710,19 +1555,11 @@ console.log(person, birthYear) #### 정답: A -인수들의 값이 객체가 아닌 한 _값_ 에 의해 전달돼요. 그 후 _참조_ 에 의해 전달돼 -요. `birthYear`는 객체가 아니라 문자열이기 때문에 값에 의해 전달돼요. 값으로 전 -달하면 값의 _복사본_ 이 만들어져요(질문 46을 보세요). +인수들의 값이 객체가 아닌 한 _값_ 에 의해 전달돼요. 그 후 _참조_ 에 의해 전달돼요. `birthYear`는 객체가 아니라 문자열이기 때문에 값에 의해 전달돼요. 값으로 전달하면 값의 _복사본_ 이 만들어져요(질문 46을 보세요). -변수 `birthYear`는 `"1997"`값에 대한 참조를 가져요. 인수 `year` 또한 `"1997"`에 -대한 참조를 가지지만, `birthYear`가 가진 참조 값과는 달라요. `year`에 `"1998"`을 -대입하여 `year`의 값을 업데이트할 때, `year`의 값만 업데이트해요. `birthYear`는 -여전히 `"1997"`이에요. +변수 `birthYear`는 `"1997"`값에 대한 참조를 가져요. 인수 `year` 또한 `"1997"`에 대한 참조를 가지지만, `birthYear`가 가진 참조 값과는 달라요. `year`에 `"1998"`을 대입하여 `year`의 값을 업데이트할 때, `year`의 값만 업데이트해요. `birthYear`는 여전히 `"1997"`이에요. -`person`의 값은 객체예요. 인수 `member`는 _같은_ 객체의 (복사된) 참조 값을 가져 -요. `member`객체의 속성이 갖는 참조를 변경하면, 두 개 모두 같은 객체를 참조 값을 -가지고 있기 때문에, `person`의 값 또한 변경돼요. 이제 `person`'의 `name` 속성은 -값 `"Lydia"`에요. +`person`의 값은 객체예요. 인수 `member`는 _같은_ 객체의 (복사된) 참조 값을 가져요. `member`객체의 속성이 갖는 참조를 변경하면, 두 개 모두 같은 객체를 참조 값을 가지고 있기 때문에, `person`의 값 또한 변경돼요. 이제 `person`'의 `name` 속성은값 `"Lydia"`에요.

@@ -1733,19 +1570,19 @@ console.log(person, birthYear) ```javascript function greeting() { - throw 'Hello world!' + throw "Hello world!"; } function sayHi() { try { - const data = greeting() - console.log('It worked!', data) + const data = greeting(); + console.log("It worked!", data); } catch (e) { - console.log('Oh no an error:', e) + console.log("Oh no an error:", e); } } -sayHi() +sayHi(); ``` - A: `"It worked! Hello world!"` @@ -1758,13 +1595,9 @@ sayHi() #### 정답: D -`throw`문을 사용해, 커스텀 에러를 만들 수 있어요. 이 표현 식을 사용해, 예외를 던 -질 수 있어요. 예외는 string, a number, a boolean or an -object이 될 수 있어요. 이 경우, 예외는 `'Hello world'` 문자열이에요. +`throw`문을 사용해, 커스텀 에러를 만들 수 있어요. 이 표현 식을 사용해, 예외를 던질 수 있어요. 예외는 string, a number, a boolean or an object이 될 수 있어요. 이 경우, 예외는 `'Hello world'` 문자열이에요. -`catch` 문을 사용해, `try` 블록에서 예외가 던져졌을 경우에 무엇을 할지 명시할 수 -있어요. 예외가 던져졌어요: 문자열 `'Hello world'`. `e`는 이제 문자열이고, 그것을 -출력해요. 결과는 `'Oh an error: Hello world'`예요. +`catch` 문을 사용해, `try` 블록에서 예외가 던져졌을 경우에 무엇을 할지 명시할 수 있어요. 예외가 던져졌어요: 문자열 `'Hello world'`. `e`는 이제 문자열이고, 그것을 출력해요. 결과는 `'Oh an error: Hello world'`예요.

@@ -1775,12 +1608,12 @@ sayHi() ```javascript function Car() { - this.make = 'Lamborghini' - return { make: 'Maserati' } + this.make = "Lamborghini"; + return { make: "Maserati" }; } -const myCar = new Car() -console.log(myCar.make) +const myCar = new Car(); +console.log(myCar.make); ``` - A: `"Lamborghini"` @@ -1793,8 +1626,7 @@ console.log(myCar.make) #### 정답: B -속성을 리턴할 때, 속성값은 생성자에 설정한 값이 아닌, _리턴된_ 값과 같아요. -`"Maserati"` 문자열을 리턴하기 때문에, `myCar.make`는 `"Maserati"`에요. +속성을 리턴할 때, 속성값은 생성자에 설정한 값이 아닌, _리턴된_ 값과 같아요. `"Maserati"` 문자열을 리턴하기 때문에, `myCar.make`는 `"Maserati"`에요.

@@ -1804,12 +1636,12 @@ console.log(myCar.make) ###### 54. 무엇이 출력 될까요? ```javascript -;(() => { - let x = (y = 10) -})() +(() => { + let x = (y = 10); +})(); -console.log(typeof x) -console.log(typeof y) +console.log(typeof x); +console.log(typeof y); ``` - A: `"undefined", "number"` @@ -1825,23 +1657,15 @@ console.log(typeof y) `let x = y = 10;`은 다음의 단축형이에요: ```javascript -y = 10 -let x = y +y = 10; +let x = y; ``` -`y`에 `10`을 대입하면, 실제로는 전역 객체에 속성 `y`를 추가해요(브라우저에서는 -`window`, Node에서는 `global`). 브라우저에서, `window.y`는 이제 `10`이에요. +`y`에 `10`을 대입하면, 실제로는 전역 객체에 속성 `y`를 추가해요(브라우저에서는 `window`, Node에서는 `global`). 브라우저에서, `window.y`는 이제 `10`이에요. -그 후, 변수 `x`를 `10`인 `y`를 값으로 선언해요. `let`키워드로 선언된 변수는 _블 -록 스코프_ 로, 선언된 블록 내에서만 정의돼요: 이 경우 즉시 호출 함수예요(IIFE). -`typeof`연산자를 사용할 때, 피연산자 `x`는 정의되지 않았어요: 선언된 블록 밖에서 -접근하려 했어요. 이것은 `x`가 선언되지 않음을 의미해요. 값을 할당하거나 선언하지 -않은 변수는 `"undefined"` 형이에요. `console.log(typeof x)`는 `"undefined"`를 리 -턴해요. +그 후, 변수 `x`를 `10`인 `y`를 값으로 선언해요. `let`키워드로 선언된 변수는 _블록 스코프_ 로, 선언된 블록 내에서만 정의돼요: 이 경우 즉시 호출 함수예요(IIFE). `typeof`연산자를 사용할 때, 피연산자 `x`는 정의되지 않았어요: 선언된 블록 밖에서 접근하려 했어요. 이것은 `x`가 선언되지 않음을 의미해요. 값을 할당하거나 선언하지 않은 변수는 `"undefined"` 형이에요. `console.log(typeof x)`는 `"undefined"`를 리턴해요. -그러나, `y`를 `10`으로 설정할 때 전역 변수 `y`를 만들었어요. 이 값은 코드 내 어 -디에서나 접근할 수 있어요. `y`는 정의되었고, `"number"`형의 값을 유지해요. -`console.log(typeof y)`는 `"number"`을 리턴해요. +그러나, `y`를 `10`으로 설정할 때 전역 변수 `y`를 만들었어요. 이 값은 코드 내 어디에서나 접근할 수 있어요. `y`는 정의되었고, `"number"`형의 값을 유지해요. `console.log(typeof y)`는 `"number"`을 리턴해요.

@@ -1853,21 +1677,21 @@ let x = y ```javascript class Dog { constructor(name) { - this.name = name + this.name = name; } } -Dog.prototype.bark = function () { - console.log(`Woof I am ${this.name}`) -} +Dog.prototype.bark = function() { + console.log(`Woof I am ${this.name}`); +}; -const pet = new Dog('Mara') +const pet = new Dog("Mara"); -pet.bark() +pet.bark(); -delete Dog.prototype.bark +delete Dog.prototype.bark; -pet.bark() +pet.bark(); ``` - A: `"Woof I am Mara"`, `TypeError` @@ -1880,13 +1704,9 @@ pet.bark() #### 정답: A -프로토타입에서도 `delete`키워드를 사용해, 객체로부터 속성을 삭제할 수 있어요. 프 -로토타입에서 속성을 삭제하면, 프로토타입 체인에서 더는 사용할 수 없게 돼요. 이 -경우, `bark` 함수는 `delete Dog.prototype.bark` 후에 프로토타입에서 더는 사용할 -수 없게 되지만, 그래도 여전히 그것에 접근하려고 해요. +프로토타입에서도 `delete`키워드를 사용해, 객체로부터 속성을 삭제할 수 있어요. 프로토타입에서 속성을 삭제하면, 프로토타입 체인에서 더는 사용할 수 없게 돼요. 이 경우, `bark` 함수는 `delete Dog.prototype.bark` 후에 프로토타입에서 더는 사용할 수 없게 되지만, 그래도 여전히 그것에 접근하려고 해요. -함수가 아닌 것을 호출하려고 할 때, `TypeError`가 던져져요. 이 경우 `pet.bark`는 -`undefined`이기 때문에, `TypeError: pet.bark is not a function`예요. +함수가 아닌 것을 호출하려고 할 때, `TypeError`가 던져져요. 이 경우 `pet.bark`는 `undefined`이기 때문에, `TypeError: pet.bark is not a function`예요.

@@ -1896,9 +1716,9 @@ pet.bark() ###### 56. 무엇이 출력 될까요? ```javascript -const set = new Set([1, 1, 2, 3, 4]) +const set = new Set([1, 1, 2, 3, 4]); -console.log(set) +console.log(set); ``` - A: `[1, 1, 2, 3, 4]` @@ -1913,8 +1733,7 @@ console.log(set) `Set`은 _unique_ 값의 집합 객체예요: 값은 set 내에서 단 한 번만 발생해요. -중복 값 `1`을 가진 반복 가능한 `[1, 1, 2, 3, 4]`을 전달하기 때문에, 그들 중 하나 -는 삭제돼요. 이것은 결과적으로 `{1, 2, 3, 4}`돼요. +중복 값 `1`을 가진 반복 가능한 `[1, 1, 2, 3, 4]`을 전달하기 때문에, 그들 중 하나는 삭제돼요. 이것은 결과적으로 `{1, 2, 3, 4}`돼요.

@@ -1925,17 +1744,17 @@ console.log(set) ```javascript // counter.js -let counter = 10 -export default counter +let counter = 10; +export default counter; ``` ```javascript // index.js -import myCounter from './counter' +import myCounter from "./counter"; -myCounter += 1 +myCounter += 1; -console.log(myCounter) +console.log(myCounter); ``` - A: `10` @@ -1948,11 +1767,9 @@ console.log(myCounter) #### 정답: C -import 된 모듈은 _read-only_ 예요 : import 된 모듈은 수정할 수 없어요. export 한 -모듈만 값을 변경할 수 있어요. +import 된 모듈은 _read-only_ 예요 : import 된 모듈은 수정할 수 없어요. export 한 모듈만 값을 변경할 수 있어요. -`myCounter`의 값을 증가시키려고 할 때, 에러를 던져요: `myCounter`는 read-only이 -고 수정할 수 없어요. +`myCounter`의 값을 증가시키려고 할 때, 에러를 던져요: `myCounter`는 read-only이고 수정할 수 없어요.

@@ -1962,11 +1779,11 @@ import 된 모듈은 _read-only_ 예요 : import 된 모듈은 수정할 수 없 ###### 58. 무엇이 출력 될까요? ```javascript -const name = 'Lydia' -age = 21 +const name = "Lydia"; +age = 21; -console.log(delete name) -console.log(delete age) +console.log(delete name); +console.log(delete age); ``` - A: `false`, `true` @@ -1979,14 +1796,9 @@ console.log(delete age) #### 정답: A -`delete`연산자는 불린 값을 리턴해요: 성공적으로 삭제를 한 경우 `true`를, 그렇지 -않다면 `false`를 리턴해요. 그러나, `var`, `const` 또는 `let` 키워드로 선언된 변 -수들은 `delete`연산자를 사용해서 삭제될 수 없어요. +`delete`연산자는 불린 값을 리턴해요: 성공적으로 삭제를 한 경우 `true`를, 그렇지 않다면 `false`를 리턴해요. 그러나, `var`, `const` 또는 `let` 키워드로 선언된 변수들은 `delete`연산자를 사용해서 삭제될 수 없어요. -`name` 변수는 `const`키워드로 선언되었기 때문에, 삭제에 실패해요. `age`를 `21`로 -설정할 때, 실제로는 `age`라는 속성을 전역 객체에 추가한 거죠. 이 방법으로 객체, -전역 객체의 속성들을 성공적으로 삭제할 수 있어요. `delete age`는 `true`를 리턴해 -요. +`name` 변수는 `const`키워드로 선언되었기 때문에, 삭제에 실패해요. `age`를 `21`로 설정할 때, 실제로는 `age`라는 속성을 전역 객체에 추가한 거죠. 이 방법으로 객체, 전역 객체의 속성들을 성공적으로 삭제할 수 있어요. `delete age`는 `true`를 리턴해요.

@@ -1996,10 +1808,10 @@ console.log(delete age) ###### 59. 무엇이 출력 될까요? ```javascript -const numbers = [1, 2, 3, 4, 5] -const [y] = numbers +const numbers = [1, 2, 3, 4, 5]; +const [y] = numbers; -console.log(y) +console.log(y); ``` - A: `[[1, 2, 3, 4, 5]]` @@ -2012,11 +1824,10 @@ console.log(y) #### 정답: C -구조 분해 할당을 통해 객체의 배열 또는 속성들로부터 변수를 해체할 수 있어요. 예 -를 들어: +구조 분해 할당을 통해 객체의 배열 또는 속성들로부터 변수를 해체할 수 있어요. 예를 들어: ```javascript -;[a, b] = [1, 2] +[a, b] = [1, 2]; ``` @@ -2024,13 +1835,12 @@ console.log(y) `a`는 이제 `1`이고, `b`는 이제 `2`예요. 질문에서 실제로 한 건 다음과 같아요: ```javascript -;[y] = [1, 2, 3, 4, 5] +[y] = [1, 2, 3, 4, 5]; ``` -이것은 `y`의 값은 숫자 `1`인 배열의 첫 번째 값과 같다는 것을 의미하죠. `y`를 출 -력하면 `1`이 리턴돼요. +이것은 `y`의 값은 숫자 `1`인 배열의 첫 번째 값과 같다는 것을 의미하죠. `y`를 출력하면 `1`이 리턴돼요.

@@ -2040,10 +1850,10 @@ console.log(y) ###### 60. 무엇이 출력 될까요? ```javascript -const user = { name: 'Lydia', age: 21 } -const admin = { admin: true, ...user } +const user = { name: "Lydia", age: 21 }; +const admin = { admin: true, ...user }; -console.log(admin) +console.log(admin); ``` - A: `{ admin: true, user: { name: "Lydia", age: 21 } }` @@ -2056,10 +1866,7 @@ console.log(admin) #### 정답: B -스프레드 연산자 `...` 를 사용해 객체를 결합할 수 있어요. 이것은 하나의 객체의 키 -/값의 쌍들을 복사본들로 만들어, 다른 객체에 추가해요. 이 경우, `user` 객체의 복 -사본들을 만들어, `admin` 객체에 추가해요. `admin` 객체는 이제 복사된 키/값의 쌍 -들이 들어있고, 결과는 `{ admin: true, name: "Lydia", age: 21 }` 예요. +스프레드 연산자 `...` 를 사용해 객체를 결합할 수 있어요. 이것은 하나의 객체의 키/값의 쌍들을 복사본들로 만들어, 다른 객체에 추가해요. 이 경우, `user` 객체의 복사본들을 만들어, `admin` 객체에 추가해요. `admin` 객체는 이제 복사된 키/값의 쌍들이 들어있고, 결과는 `{ admin: true, name: "Lydia", age: 21 }` 예요.

@@ -2069,12 +1876,12 @@ console.log(admin) ###### 61. 무엇이 출력 될까요? ```javascript -const person = { name: 'Lydia' } +const person = { name: "Lydia" }; -Object.defineProperty(person, 'age', { value: 21 }) +Object.defineProperty(person, "age", { value: 21 }); -console.log(person) -console.log(Object.keys(person)) +console.log(person); +console.log(Object.keys(person)); ``` - A: `{ name: "Lydia", age: 21 }`, `["name", "age"]` @@ -2087,15 +1894,9 @@ console.log(Object.keys(person)) #### 정답: B -`defineProperty`메소드로, 객체에 새로운 속성들을 추가하거나, 기존 것을 수정할 수 -있어요. `defineProperty` 메소드를 사용해 객체의 속성을 추가할 때, 기본적으로 객 -체의 속성들은 _비 열거자_ 예요. `Object.keys`메소드는 모든 _열거자_ 객체의 속성 -이름들을 리턴하는데, 이 경우는 `"name"` 뿐이에요. +`defineProperty`메소드로, 객체에 새로운 속성들을 추가하거나, 기존 것을 수정할 수 있어요. `defineProperty` 메소드를 사용해 객체의 속성을 추가할 때, 기본적으로 객체의 속성들은 _비 열거자_ 예요. `Object.keys`메소드는 모든 _열거자_ 객체의 속성 이름들을 리턴하는데, 이 경우는 `"name"` 뿐이에요. -`defineProperty`를 사용해 추가된 속성들은 기본적으로 변경할 수 없어요. -`writable`, `configurable` 그리고 `enumerable` 속성들을 사용해 덮어쓰기 할 수 있 -어요. `defineProperty`메소드의 방법은 객체에 추가할 속성들을 훨씬 더 정교하게 제 -어하도록 해줘요. +`defineProperty`를 사용해 추가된 속성들은 기본적으로 변경할 수 없어요. `writable`, `configurable` 그리고 `enumerable` 속성들을 사용해 덮어쓰기 할 수 있어요. `defineProperty`메소드의 방법은 객체에 추가할 속성들을 훨씬 더 정교하게 제어하도록 해줘요.

@@ -2106,13 +1907,13 @@ console.log(Object.keys(person)) ```javascript const settings = { - username: 'lydiahallie', + username: "lydiahallie", level: 19, - health: 90, -} + health: 90 +}; -const data = JSON.stringify(settings, ['level', 'health']) -console.log(data) +const data = JSON.stringify(settings, ["level", "health"]); +console.log(data); ``` - A: `"{"level":19, "health":90}"` @@ -2125,16 +1926,11 @@ console.log(data) #### 정답: A -`JSON.stringify` 두 번째 인수는 _replacer_ 예요. replacer는 함수 또는 배열 둘 중 -하나가 될 수 있고, stringify 할 대상과 방법을 제어할 수 있게 해줘요. +`JSON.stringify` 두 번째 인수는 _replacer_ 예요. replacer는 함수 또는 배열 둘 중 하나가 될 수 있고, stringify 할 대상과 방법을 제어할 수 있게 해줘요. -replacer가 _배열_ 이라면, 배열에 이름이 포함된 속성만 JSON 문자열에 추가될 거에 -요. 이 경우, 이름을 가진 `"level"` 그리고 `"health"`속성들만 포함되고, -`"username"`은 제외 돼요. `data` 은 이제 `"{"level":19, "health":90}"`에요. +replacer가 _배열_ 이라면, 배열에 이름이 포함된 속성만 JSON 문자열에 추가될 거에요. 이 경우, 이름을 가진 `"level"` 그리고 `"health"`속성들만 포함되고, `"username"`은 제외 돼요. `data` 은 이제 `"{"level":19, "health":90}"`에요. -replacer가 _함수_ 라면, stringifying 할 객체의 모든 속성에 호출돼요. 이 함수로부 -터 리턴된 값은 JSON 문자열에 추가될 때 속성의 값이 될 거예요. 만약 값이 -`undefined`라면, 이 속성은 JSON 문자열로부터 제외돼요. +replacer가 _함수_ 라면, stringifying 할 객체의 모든 속성에 호출돼요. 이 함수로부터 리턴된 값은 JSON 문자열에 추가될 때 속성의 값이 될 거예요. 만약 값이 `undefined`라면, 이 속성은 JSON 문자열로부터 제외돼요.

@@ -2144,16 +1940,16 @@ replacer가 _함수_ 라면, stringifying 할 객체의 모든 속성에 호출 ###### 63. 무엇이 출력 될까요? ```javascript -let num = 10 +let num = 10; -const increaseNumber = () => num++ -const increasePassedNumber = number => number++ +const increaseNumber = () => num++; +const increasePassedNumber = number => number++; -const num1 = increaseNumber() -const num2 = increasePassedNumber(num1) +const num1 = increaseNumber(); +const num2 = increasePassedNumber(num1); -console.log(num1) -console.log(num2) +console.log(num1); +console.log(num2); ``` - A: `10`, `10` @@ -2166,14 +1962,9 @@ console.log(num2) #### 정답: A -단항 연산자 `++`는 _우선_ 피연산자의 값을 _리턴하고_, _그 후_ 피연산자의 값을 -_증가해요_. `increaseNumber` 함수가 처음으로 리턴 한 `num`의 값은 `10` 이기 때문 -에, `num1`의 값은 `10`이고, 그 후엔 `num`의 값만 증가해요. +단항 연산자 `++`는 _우선_ 피연산자의 값을 _리턴하고_, _그 후_ 피연산자의 값을 _증가해요_. `increaseNumber` 함수가 처음으로 리턴 한 `num`의 값은 `10` 이기 때문에, `num1`의 값은 `10`이고, 그 후엔 `num`의 값만 증가해요. -`num1`을 `increasePassedNumber`로 전달했기 때문에, `num2`는 `10`이에요. -`number`는 `10`이에요(`num1`의 값은, 다시 한번, 단항 연산자가 `++`는 _우선_ 피연 -산자의 값을 _리턴하고_, _그 후_ 피연산자의 값을 _증가해요_. `number`의 값은 -`10`이에요 즉, `num2`는 `10`이죠. +`num1`을 `increasePassedNumber`로 전달했기 때문에, `num2`는 `10`이에요. `number`는 `10`이에요(`num1`의 값은, 다시 한번, 단항 연산자가 `++`는 _우선_ 피연산자의 값을 _리턴하고_, _그 후_ 피연산자의 값을 _증가해요_. `number`의 값은 `10`이에요 즉, `num2`는 `10`이죠.

@@ -2183,16 +1974,16 @@ _증가해요_. `increaseNumber` 함수가 처음으로 리턴 한 `num`의 값 ###### 64. 무엇이 출력 될까요? ```javascript -const value = { number: 10 } +const value = { number: 10 }; const multiply = (x = { ...value }) => { - console.log((x.number *= 2)) -} + console.log(x.number *= 2); +}; -multiply() -multiply() -multiply(value) -multiply(value) +multiply(); +multiply(); +multiply(value); +multiply(value); ``` - A: `20`, `40`, `80`, `160` @@ -2205,22 +1996,13 @@ multiply(value) #### 정답: C -ES6에서는, 기본값으로 파라미터를 초기화할 수 있어요. 함수에 값이 없이 전달되거나 -, 파라미터의 값이 `"undefined"`라면, 파라미터의 값은 기본값이 될 거예요. 이 경우 -, `value` 객체의 속성들을 새로운 객체 안으로 전개해요. 따라서 `x`는 -`{ number: 10 }`을 기본값으로 가져요. +ES6에서는, 기본값으로 파라미터를 초기화할 수 있어요. 함수에 값이 없이 전달되거나, 파라미터의 값이 `"undefined"`라면, 파라미터의 값은 기본값이 될 거예요. 이 경우, `value` 객체의 속성들을 새로운 객체 안으로 전개해요. 따라서 `x`는 `{ number: 10 }`을 기본값으로 가져요. -기본 인수는 _호출 시점_ 에 평가돼요! 함수를 부를 때마다, _새로운_ 객체를 만들어 -요. 처음에 두 번은 값 전달 없이 `multiply` 함수를 호출해요: `x`는 -`{ number: 10 }`의 기본값을 가져요. 그다음 그 숫자를 곱셈한 값인 `20`을 출력해요 -. +기본 인수는 _호출 시점_ 에 평가돼요! 함수를 부를 때마다, _새로운_ 객체를 만들어요. 처음에 두 번은 값 전달 없이 `multiply` 함수를 호출해요: `x`는 `{ number: 10 }`의 기본값을 가져요. 그다음 그 숫자를 곱셈한 값인 `20`을 출력해요. -세 번째로 곱셈을 호출할 때, 인수를 전달해요: 그 객체는 `value`를 불러요. `*=` 연 -산자는 실제로는 `x.number = x.number * 2`의 줄임말이에요: `x.number`의 값을 변경 -하고, 곱셈한 값 `20`을 출력해요 +세 번째로 곱셈을 호출할 때, 인수를 전달해요: 그 객체는 `value`를 불러요. `*=` 연산자는 실제로는 `x.number = x.number * 2`의 줄임말이에요: `x.number`의 값을 변경하고, 곱셈한 값 `20`을 출력해요 -네 번째에는, `value` 객체를 다시 한번 전달해요. `x.number`는 이전에 `20`으로 바 -뀌었기 때문에, `x.number *= 2`는 `40`을 출력해요. +네 번째에는, `value` 객체를 다시 한번 전달해요. `x.number`는 이전에 `20`으로 바뀌었기 때문에, `x.number *= 2`는 `40`을 출력해요.

@@ -2230,13 +2012,12 @@ ES6에서는, 기본값으로 파라미터를 초기화할 수 있어요. 함수 ###### 65. 무엇이 출력 될까요? ```javascript -;[1, 2, 3, 4].reduce((x, y) => console.log(x, y)) +[1, 2, 3, 4].reduce((x, y) => console.log(x, y)); ``` - A: `1` `2` 그리고 `3` `3` 그리고 `6` `4` - B: `1` `2` 그리고 `2` `3` 그리고 `3` `4` -- C: `1` `undefined` 그리고 `2` `undefined` 그리고 `3` `undefined` 그리고 `4` - `undefined` +- C: `1` `undefined` 그리고 `2` `undefined` 그리고 `3` `undefined` 그리고 `4` `undefined` - D: `1` `2` 그리고 `undefined` `3` 그리고 `undefined` `4`
정답 @@ -2244,26 +2025,17 @@ ES6에서는, 기본값으로 파라미터를 초기화할 수 있어요. 함수 #### 정답: D -`reduce` 메소드가 받은 첫 번째 인수는 _누산기_ 예요, 이 경우엔 `x`죠. 두 번째 인 -수 `y`는 _현재 값_ 예요. reduce 메소드에서, 배열에 있는 모든 요소에 콜백 함수를 -실행하므로 궁극적으로는 하나의 값을 얻을 수 있어요. +`reduce` 메소드가 받은 첫 번째 인수는 _누산기_ 예요, 이 경우엔 `x`죠. 두 번째 인수 `y`는 _현재 값_ 예요. reduce 메소드에서, 배열에 있는 모든 요소에 콜백 함수를 실행하므로 궁극적으로는 하나의 값을 얻을 수 있어요. 이 예제에서는, 값을 리턴하지 않고, 단지 누적된 값과 현재 값을 출력해요. -누산기의 값은 콜백 함수가 이전에 리턴한 값이에요. 만약 추가적인 `초기값` 인수를 -`reduce` 메소드에 전달하지 않았다면, 누산기는 첫번째 부른 첫 번째 요소와 동일해 -요. +누산기의 값은 콜백 함수가 이전에 리턴한 값이에요. 만약 추가적인 `초기값` 인수를 `reduce` 메소드에 전달하지 않았다면, 누산기는 첫번째 부른 첫 번째 요소와 동일해요. -첫 번째 부를 땐, 누산기 (`x`)는 `1` 이에요, 그리고 현재 값인 (`y`)는 `2`예요. 콜 -백 함수로부터 리턴되지 않았어요, 누산기와 현재 값을 출력해요: `1` 그리고 `2`가 -출력돼요. +첫 번째 부를 땐, 누산기 (`x`)는 `1` 이에요, 그리고 현재 값인 (`y`)는 `2`예요. 콜백 함수로부터 리턴되지 않았어요, 누산기와 현재 값을 출력해요: `1` 그리고 `2`가 출력돼요. -함수에서 값을 리턴하지 않았다면, `undefined`를 리턴해요. 다음번에 부를 때, 누산 -기는 `undefined`고, 그리고 현재 값은 `3`이에요. `undefined` 그리고 `3`이 출력돼 -요. +함수에서 값을 리턴하지 않았다면, `undefined`를 리턴해요. 다음번에 부를 때, 누산기는 `undefined`고, 그리고 현재 값은 `3`이에요. `undefined` 그리고 `3`이 출력돼요. -네 번째 부를 땐, 또 콜백 함수에서 리턴받지 않았어요. 누산기는 다시 `undefined`고 -, 현재 값은 `4`예요. `undefined` 그리고 `4`가 출력돼요. +네 번째 부를 땐, 또 콜백 함수에서 리턴받지 않았어요. 누산기는 다시 `undefined`고, 현재 값은 `4`예요. `undefined` 그리고 `4`가 출력돼요.

@@ -2275,31 +2047,32 @@ ES6에서는, 기본값으로 파라미터를 초기화할 수 있어요. 함수 ```javascript class Dog { constructor(name) { - this.name = name + this.name = name; } -} +}; class Labrador extends Dog { - // 1 + // 1 constructor(name, size) { - this.size = size + this.size = size; } // 2 constructor(name, size) { - super(name) - this.size = size + super(name); + this.size = size; } // 3 constructor(size) { - super(name) - this.size = size + super(name); + this.size = size; } - // 4 + // 4 constructor(name, size) { - this.name = name - this.size = size + this.name = name; + this.size = size; } -} + +}; ``` - A: 1 @@ -2312,15 +2085,11 @@ class Labrador extends Dog { #### 정답: B -이 파생 클래스에서, `super`를 부르기 전에는 `this` 키워드에 접근할 수 없어요. 그 -렇게 하려고 한다면, 참조에러를 던질 거에요: 1과 4는 참조 에러를 던져요 +이 파생 클래스에서, `super`를 부르기 전에는 `this` 키워드에 접근할 수 없어요. 그렇게 하려고 한다면, 참조에러를 던질 거에요: 1과 4는 참조 에러를 던져요 -`super` 키워드를 가지고, 부모 클래스 생성자에 주어진 인수들을 부를 수 있어요. 부 -모 생성자는 `name` 인수를 받아요, 그래서 `name`을 `super`로 전달해야 해요. +`super` 키워드를 가지고, 부모 클래스 생성자에 주어진 인수들을 부를 수 있어요. 부모 생성자는 `name` 인수를 받아요, 그래서 `name`을 `super`로 전달해야 해요. -`Labrador` 클래스는 인수를 2개 받는데, `Dog`로 부터 확장된 `name`과 `Labrador` -클래스의 추가 속성인 `size`예요. 그 두 개는 `Labrador` 생성자 함수에 전달되어야 -하는데, 올바르게 사용된 건 2번째 생성자예요. +`Labrador` 클래스는 인수를 2개 받는데, `Dog`로 부터 확장된 `name`과 `Labrador` 클래스의 추가 속성인 `size`예요. 그 두 개는 `Labrador` 생성자 함수에 전달되어야 하는데, 올바르게 사용된 건 2번째 생성자예요.

@@ -2331,13 +2100,13 @@ class Labrador extends Dog { ```javascript // index.js -console.log('running index.js') -import { sum } from './sum.js' -console.log(sum(1, 2)) +console.log('running index.js'); +import { sum } from './sum.js'; +console.log(sum(1, 2)); // sum.js -console.log('running sum.js') -export const sum = (a, b) => a + b +console.log('running sum.js'); +export const sum = (a, b) => a + b; ``` - A: `running index.js`, `running sum.js`, `3` @@ -2350,14 +2119,9 @@ export const sum = (a, b) => a + b #### 정답: B -`import` 키워드를 사용하면, 모든 import된 modules은 _우선-파싱_ 되어요. import된 -모듈은 _처음에_ 실행되는 것을 의미하고, import한 파일 안에 있는 코드는 _나중에_ -실행돼요. +`import` 키워드를 사용하면, 모든 import된 modules은 _우선-파싱_ 되어요. import된 모듈은 _처음에_ 실행되는 것을 의미하고, import한 파일 안에 있는 코드는 _나중에_ 실행돼요. -이것은 CommonJSd의 `require()`와 `import`의 차이예요! `require()`을 사용하면, 런 -타임 중 코드에서 필요한 시점에 의존성 모듈을 로드 할 수 있어요. 만약 `import` 대 -신에 `require`을 사용하면, `running index.js`, `running sum.js`, `3`으로 콘솔에 -출력될 거에요. +이것은 CommonJSd의 `require()`와 `import`의 차이예요! `require()`을 사용하면, 런타임 중 코드에서 필요한 시점에 의존성 모듈을 로드 할 수 있어요. 만약 `import` 대신에 `require`을 사용하면, `running index.js`, `running sum.js`, `3`으로 콘솔에 출력될 거에요.

@@ -2382,11 +2146,7 @@ console.log(Symbol('foo') === Symbol('foo')) #### 정답: A -모든 심볼은 완전히 유니크해요. 심볼에 전달된 인수의 목적은, 심볼에 설명을 제공하 -는 거에요. 심볼의 값은 전달된 인수에 따라 달라지지 않아요. 동등성을 테스트할 때, -새로운 심볼 객체를 만들어요: 첫번째 `Symbol('foo')`와 두번째 `Symbol('foo')`. 이 -두개의 값들은 유니크하며, 서로 같지 않아요, `Symbol('foo') === Symbol('foo')`는 -`false`를 리턴해요. +모든 심볼은 완전히 유니크해요. 심볼에 전달된 인수의 목적은, 심볼에 설명을 제공하는 거에요. 심볼의 값은 전달된 인수에 따라 달라지지 않아요. 동등성을 테스트할 때, 새로운 심볼 객체를 만들어요: 첫번째 `Symbol('foo')`와 두번째 `Symbol('foo')`. 이 두개의 값들은 유니크하며, 서로 같지 않아요, `Symbol('foo') === Symbol('foo')`는 `false`를 리턴해요.

@@ -2396,30 +2156,24 @@ console.log(Symbol('foo') === Symbol('foo')) ###### 69. 무엇이 출력 될까요? ```javascript -const name = 'Lydia Hallie' +const name = "Lydia Hallie" console.log(name.padStart(13)) console.log(name.padStart(2)) ``` - A: `"Lydia Hallie"`, `"Lydia Hallie"` -- B: `" Lydia Hallie"`, `" Lydia Hallie"` (`"[13x whitespace]Lydia Hallie"`, - `"[2x whitespace]Lydia Hallie"`) -- C: `" Lydia Hallie"`, `"Lydia Hallie"` (`"[1x whitespace]Lydia Hallie"`, - `"Lydia Hallie"`) -- D: `"Lydia Hallie"`, `"Lyd"`, +- B: `" Lydia Hallie"`, `" Lydia Hallie"` (`"[13x whitespace]Lydia Hallie"`, `"[2x whitespace]Lydia Hallie"`) +- C: `" Lydia Hallie"`, `"Lydia Hallie"` (`"[1x whitespace]Lydia Hallie"`, `"Lydia Hallie"`) +- D: `"Lydia Hallie"`, `"Lyd"`,
정답

#### 정답: C -`padStart` 메소드를 사용하면, 문자열의 시작 부분에 패딩을 추가해 줄 수 있어요. -이 메소드에 전달된 값은 패딩을 포함한 문자열의 _전체_ 길이예요. 문자열 -`"Lydia Hallie"`의 길이는 `12`예요. `name.padStart(13)`은 문자열의 시작점에 1 스 -페이스를 삽입해요, 따라서 12 + 1 은 13이죠. +`padStart` 메소드를 사용하면, 문자열의 시작 부분에 패딩을 추가해 줄 수 있어요. 이 메소드에 전달된 값은 패딩을 포함한 문자열의 _전체_ 길이예요. 문자열 `"Lydia Hallie"`의 길이는 `12`예요. `name.padStart(13)`은 문자열의 시작점에 1 스페이스를 삽입해요, 따라서 12 + 1 은 13이죠. -`padStart` 메소드에 전달된 인수가 배열의 길이보다 작다면, 패딩은 추가되지 않을 -거예요. +`padStart` 메소드에 전달된 인수가 배열의 길이보다 작다면, 패딩은 추가되지 않을 거예요.

@@ -2429,7 +2183,7 @@ console.log(name.padStart(2)) ###### 70. 무엇이 출력 될까요? ```javascript -console.log('🥑' + '💻') +console.log("🥑" + "💻"); ``` - A: `"🥑💻"` @@ -2442,8 +2196,7 @@ console.log('🥑' + '💻') #### 정답: A -`+` 연산자를 가지고, 문자열을 연결 시킬 수 있어요. 이 경우에는, 문자열 `"🥑"`과 -문자열 `"💻"`을 연결해, 결과 `"🥑💻"`를 얻었어요. +`+` 연산자를 가지고, 문자열을 연결 시킬 수 있어요. 이 경우에는, 문자열 `"🥑"`과 문자열 `"💻"`을 연결해, 결과 `"🥑💻"`를 얻었어요.

@@ -2454,16 +2207,16 @@ console.log('🥑' + '💻') ```javascript function* startGame() { - const answer = yield 'Do you love JavaScript?' - if (answer !== 'Yes') { - return "Oh wow... Guess we're gone here" + const answer = yield "Do you love JavaScript?"; + if (answer !== "Yes") { + return "Oh wow... Guess we're gone here"; } - return 'JavaScript loves you back ❤️' + return "JavaScript loves you back ❤️"; } -const game = startGame() -console.log(/* 1 */) // Do you love JavaScript? -console.log(/* 2 */) // JavaScript loves you back ❤️ +const game = startGame(); +console.log(/* 1 */); // Do you love JavaScript? +console.log(/* 2 */); // JavaScript loves you back ❤️ ``` - A: `game.next("Yes").value` 그리고 `game.next().value` @@ -2476,17 +2229,11 @@ console.log(/* 2 */) // JavaScript loves you back ❤️ #### 정답: C -제너레이터 함수는 `yield` 키워드를 보면 실행을 "멈춰"요. 첫 번째로, -`game.next().value`를 불러, 함수가 "Do you love JavaScript?" 문자열을 넘겨주도록 -할 수 있어요. +제너레이터 함수는 `yield` 키워드를 보면 실행을 "멈춰"요. 첫 번째로, `game.next().value`를 불러, 함수가 "Do you love JavaScript?" 문자열을 넘겨주도록 할 수 있어요. -`yield` 키워드를 처음으로 찾기 전까지, 모든 줄이 실행되요. 첫 번째 줄에 있는 함 -수는 `yield` 키워드를 가지고 있어요: 첫 번째 yield으로 실행을 멈춰요! _이것은 -`answer` 변수가 아직 정의되지 않았는 뜻이에요_ +`yield` 키워드를 처음으로 찾기 전까지, 모든 줄이 실행되요. 첫 번째 줄에 있는 함수는 `yield` 키워드를 가지고 있어요: 첫 번째 yield으로 실행을 멈춰요! _이것은 `answer` 변수가 아직 정의되지 않았는 뜻이에요_ -`game.next("Yes").value`을 부를때, `"Yes"`의 경우에서 이전 `yield`는 `next()` 함 -수가 전달한 파라미터의 값으로 대체돼요. `answer` 변수의 값은 이제 `"Yes"`에요. -if문의 조건은 `false`를 리턴해, `JavaScript loves you back ❤️`를 출력돼요 +`game.next("Yes").value`을 부를때, `"Yes"`의 경우에서 이전 `yield`는 `next()` 함수가 전달한 파라미터의 값으로 대체돼요. `answer` 변수의 값은 이제 `"Yes"`에요. if문의 조건은 `false`를 리턴해, `JavaScript loves you back ❤️`를 출력돼요

@@ -2496,7 +2243,7 @@ if문의 조건은 `false`를 리턴해, `JavaScript loves you back ❤️`를 ###### 72. 무엇이 출력 될까요? ```javascript -console.log(String.raw`Hello\nworld`) +console.log(String.raw`Hello\nworld`); ``` - A: `Hello world!` @@ -2509,10 +2256,9 @@ console.log(String.raw`Hello\nworld`) #### 정답: C -`String.raw`는 escapes (`\n`, `\v`, `\t` 등.)에서의 문자열을 무시해요! 백슬래시 -는 다음과 같이 끝나면 문제가 될 수 있어요 +`String.raw`는 escapes (`\n`, `\v`, `\t` 등.)에서의 문자열을 무시해요! 백슬래시는 다음과 같이 끝나면 문제가 될 수 있어요 -`` console.log(`C:\Documents\Projects\table.html`) `` +``console.log(`C:\Documents\Projects\table.html`)`` 이렇게 될 거예요: @@ -2533,11 +2279,11 @@ console.log(String.raw`Hello\nworld`) ```javascript async function getData() { - return await Promise.resolve('I made it!') + return await Promise.resolve("I made it!"); } -const data = getData() -console.log(data) +const data = getData(); +console.log(data); ``` - A: `"I made it!"` @@ -2550,12 +2296,9 @@ console.log(data) #### 정답: C -async 함수는 항상 promise를 리턴해요. `await`는 promise가 resolve 할 때까지 기다 -려야 해요: pending promise는 `data`를 설정하기 위해 부른 `getData()`가 리턴한 것 -을 가져요. +async 함수는 항상 promise를 리턴해요. `await`는 promise가 resolve 할 때까지 기다려야 해요: pending promise는 `data`를 설정하기 위해 부른 `getData()`가 리턴한 것을 가져요. -resolve된 값 `"I made it"`에 접근하고 싶다면, `data`에 `.then()` 메소드를 사용해 -야해요. +resolve된 값 `"I made it"`에 접근하고 싶다면, `data`에 `.then()` 메소드를 사용해야해요. `data.then(res => console.log(res))` @@ -2570,11 +2313,11 @@ resolve된 값 `"I made it"`에 접근하고 싶다면, `data`에 `.then()` 메 ```javascript function addToList(item, list) { - return list.push(item) + return list.push(item); } -const result = addToList('apple', ['banana']) -console.log(result) +const result = addToList("apple", ["banana"]); +console.log(result); ``` - A: `['banana', 'apple']` @@ -2587,13 +2330,9 @@ console.log(result) #### 정답: B -`.push()`메소드는 새로운 배열의 _길이_ 를 리턴해요! 이전에, 배열은 한 개의 요소( -문자열 `"banana"`)를 포함되어있고 길이는 `1`예요. 배열에 문자열 `"apple"`을 추가 -한 후, 배열은 두 개 요소를 포함하고, 그리고 길이 `2`를 가져요. `addToList` 함수 -로부터 리턴돼요. +`.push()`메소드는 새로운 배열의 _길이_ 를 리턴해요! 이전에, 배열은 한 개의 요소(문자열 `"banana"`)를 포함되어있고 길이는 `1`예요. 배열에 문자열 `"apple"`을 추가한 후, 배열은 두 개 요소를 포함하고, 그리고 길이 `2`를 가져요. `addToList` 함수로부터 리턴돼요. -`push` 메소드는 원본 배열을 수정해요. 만약 함수로부터 _배열의 길이_ 대신에 _배 -열_ 을 리턴하고 싶다면, `item`을 푸시한 후 `list`를 리턴해야해요. +`push` 메소드는 원본 배열을 수정해요. 만약 함수로부터 _배열의 길이_ 대신에 _배열_ 을 리턴하고 싶다면, `item`을 푸시한 후 `list`를 리턴해야해요.

@@ -2603,14 +2342,14 @@ console.log(result) ###### 75. 무엇이 출력 될까요? ```javascript -const box = { x: 10, y: 20 } +const box = { x: 10, y: 20 }; -Object.freeze(box) +Object.freeze(box); -const shape = box -shape.x = 100 +const shape = box; +shape.x = 100; -console.log(shape) +console.log(shape); ``` - A: `{ x: 100, y: 20 }` @@ -2623,16 +2362,11 @@ console.log(shape) #### 정답: B -`Object.freeze`는 객체의 속성들을 추가, 삭제 혹은 수정하는 걸 불가능하게 만들어 -요(다른 객체로서의 속성들의 값이 아닌 한). +`Object.freeze`는 객체의 속성들을 추가, 삭제 혹은 수정하는 걸 불가능하게 만들어요(다른 객체로서의 속성들의 값이 아닌 한). -변수 `shape`을 생성할 때, 동결 객체 `box`와 동일하게 설정했고, `shape` 역시 동결 -객체를 참조해요. `Object.isFrozen`을 사용해 객체의 동결 여부를 확인할 수 있어요. -이 경우, `Object.isFrozen(shape)`은 참을 리턴하고, 따라서 변수 `shape`는 동결 객 -체 참조를 가져요. +변수 `shape`을 생성할 때, 동결 객체 `box`와 동일하게 설정했고, `shape` 역시 동결 객체를 참조해요. `Object.isFrozen`을 사용해 객체의 동결 여부를 확인할 수 있어요. 이 경우, `Object.isFrozen(shape)`은 참을 리턴하고, 따라서 변수 `shape`는 동결 객체 참조를 가져요. -`shape`가 동결 상태이므로, `x`의 값은 객체가 아니며, `x`의 속성을 수정할 수 없어 -요. `x`는 여전히 `10`이고, `{ x: 10, y: 20 }`가 출력돼요. +`shape`가 동결 상태이므로, `x`의 값은 객체가 아니며, `x`의 속성을 수정할 수 없어요. `x`는 여전히 `10`이고, `{ x: 10, y: 20 }`가 출력돼요.

@@ -2642,9 +2376,9 @@ console.log(shape) ###### 76. 무엇이 출력 될까요? ```javascript -const { name: myName } = { name: 'Lydia' } +const { name: myName } = { name: "Lydia" }; -console.log(name) +console.log(name); ``` - A: `"Lydia"` @@ -2657,11 +2391,9 @@ console.log(name) #### 정답: D -오른쪽에 있는 객체로부터 속성 `name`을 unpack할 때, `myName`라는 이름을 가진 변 -수에 값 `"Lydia"`을 할당해요. +오른쪽에 있는 객체로부터 속성 `name`을 unpack할 때, `myName`라는 이름을 가진 변수에 값 `"Lydia"`을 할당해요. -`{ name: myName }`은, JavaScript에게 오른쪽에 있는 `name`속성 값을 가진 -`myName`이라고 불리는 새로운 변수를 만든다고 말하는 거예요. +`{ name: myName }`은, JavaScript에게 오른쪽에 있는 `name`속성 값을 가진 `myName`이라고 불리는 새로운 변수를 만든다고 말하는 거예요. `name`을 출력하려고 하면, 변수는 정의되지 않아, ReferenceError를 던질거예요. @@ -2674,7 +2406,7 @@ console.log(name) ```javascript function sum(a, b) { - return a + b + return a + b; } ``` @@ -2686,12 +2418,9 @@ function sum(a, b) { #### 정답: A -pure 함수는 _항상_ 같은 결과를 리턴하는 함수예요, 만약 같은 인수가 전달 된다면 -말이죠. +pure 함수는 _항상_ 같은 결과를 리턴하는 함수예요, 만약 같은 인수가 전달 된다면 말이죠. -`sum` 함수는 항상 같은 결과를 리턴해요. 만약 `1`과 `2`를 전달하면, _항상_ 부작용 -없이 `3`을 리턴할 거예요. `5`와 `10`을 전달하면, _항상_ `15`를 리턴할 거예요. 이 -게 pure 함수의 정의예요. +`sum` 함수는 항상 같은 결과를 리턴해요. 만약 `1`과 `2`를 전달하면, _항상_ 부작용 없이 `3`을 리턴할 거예요. `5`와 `10`을 전달하면, _항상_ `15`를 리턴할 거예요. 이게 pure 함수의 정의예요.

@@ -2702,22 +2431,22 @@ pure 함수는 _항상_ 같은 결과를 리턴하는 함수예요, 만약 같 ```javascript const add = () => { - const cache = {} + const cache = {}; return num => { if (num in cache) { - return `From cache! ${cache[num]}` + return `From cache! ${cache[num]}`; } else { - const result = num + 10 - cache[num] = result - return `Calculated! ${result}` + const result = num + 10; + cache[num] = result; + return `Calculated! ${result}`; } - } -} + }; +}; -const addFunction = add() -console.log(addFunction(10)) -console.log(addFunction(10)) -console.log(addFunction(5 * 2)) +const addFunction = add(); +console.log(addFunction(10)); +console.log(addFunction(10)); +console.log(addFunction(5 * 2)); ``` - A: `Calculated! 20` `Calculated! 20` `Calculated! 20` @@ -2730,25 +2459,15 @@ console.log(addFunction(5 * 2)) #### 정답: C -`add`함수는 _memoization_ 함수예요. memoization으로, 함수 실행 속도를 높이기 위 -해 함수의 결과를 캐시에 저장할 수 있어요. 이 경우, 이전에 리턴된 값을 저장한 -`cache` 객체를 만들어요. +`add`함수는 _memoization_ 함수예요. memoization으로, 함수 실행 속도를 높이기 위해 함수의 결과를 캐시에 저장할 수 있어요. 이 경우, 이전에 리턴된 값을 저장한 `cache` 객체를 만들어요. -같은 인수로 `addFunction` 함수를 다시 부르면, 우선 cache 안에 값을 갖고 있는지 -확인해요. 만약 그렇다면, 캐시에 저장된 값이 리턴되어, 실행시간이 절약돼요. 캐시 -에 저장되지 않았다면, 값을 계산하고 나중에 저장해요. +같은 인수로 `addFunction` 함수를 다시 부르면, 우선 cache 안에 값을 갖고 있는지 확인해요. 만약 그렇다면, 캐시에 저장된 값이 리턴되어, 실행시간이 절약돼요. 캐시에 저장되지 않았다면, 값을 계산하고 나중에 저장해요. -같은 값으로 `addFunction`함수를 세 번 불러요: 첫 번째 호출 때에는, `num`가 -`10`일 때 함수의 값은 아직 저장되지 않았어요. if문의 조건 `num in cache` 은 -`false`을 리턴하고, else 블록이 실행돼요: `Calculated! 20`을 출력하고, 결과 값은 -cache 객체에 추가돼요. `cache` 이제 `{ 10: 20 }`와 같아요. +같은 값으로 `addFunction`함수를 세 번 불러요: 첫 번째 호출 때에는, `num`가 `10`일 때 함수의 값은 아직 저장되지 않았어요. if문의 조건 `num in cache` 은 `false`을 리턴하고, else 블록이 실행돼요: `Calculated! 20`을 출력하고, 결과 값은 cache 객체에 추가돼요. `cache` 이제 `{ 10: 20 }`와 같아요. -두 번째엔, `cache`객체는 `10`을 위해 리턴될 값을 포함하고 있어요. if문의 조건 -`num in cache`은 `true`를 리턴하고, `'From cache! 20'`이 출력돼요. +두 번째엔, `cache`객체는 `10`을 위해 리턴될 값을 포함하고 있어요. if문의 조건 `num in cache`은 `true`를 리턴하고, `'From cache! 20'`이 출력돼요. -세 번째에는, `5 * 2`을 `10`으로 평가하여 함수에 전달해요. `cache` 객체는 `10`을 -위해 리턴될 값을 포함하고 있어요. if문의 조건 `num in cache`은 `true`를 리턴하고 -, `'From cache! 20'`이 출력돼요. +세 번째에는, `5 * 2`을 `10`으로 평가하여 함수에 전달해요. `cache` 객체는 `10`을 위해 리턴될 값을 포함하고 있어요. if문의 조건 `num in cache`은 `true`를 리턴하고, `'From cache! 20'`이 출력돼요.

@@ -2758,38 +2477,34 @@ cache 객체에 추가돼요. `cache` 이제 `{ 10: 20 }`와 같아요. ###### 79. 무엇이 출력 될까요? ```javascript -const myLifeSummedUp = ['☕', '💻', '🍷', '🍫'] +const myLifeSummedUp = ["☕", "💻", "🍷", "🍫"] for (let item in myLifeSummedUp) { - console.log(item) + console.log(item); } for (let item of myLifeSummedUp) { - console.log(item) + console.log(item); } ``` - A: `0` `1` `2` `3` 그리고 `"☕"` ` "💻"` `"🍷"` `"🍫"` - B: `"☕"` ` "💻"` `"🍷"` `"🍫"` 그리고 `"☕"` ` "💻"` `"🍷"` `"🍫"` - C: `"☕"` ` "💻"` `"🍷"` `"🍫"` 그리고 `0` `1` `2` `3` -- D: `0` `1` `2` `3` 그리고 `{0: "☕", 1: "💻", 2: "🍷", 3: "🍫"}` +- D: `0` `1` `2` `3` 그리고 `{0: "☕", 1: "💻", 2: "🍷", 3: "🍫"}`
정답

#### 정답: A -_for-in_ 루프에서는, **열거 가능한** 속성들에 대해 반복 할 수 있어요. 배열에서, -열거 가능한 속성들은 배열 요소들의 "키"이고, 실제로는 그들의 인덱스죠. 배열을 다 -음과 같이 볼 수 있어요: +_for-in_ 루프에서는, **열거 가능한** 속성들에 대해 반복 할 수 있어요. 배열에서, 열거 가능한 속성들은 배열 요소들의 "키"이고, 실제로는 그들의 인덱스죠. 배열을 다음과 같이 볼 수 있어요: `{0: "☕", 1: "💻", 2: "🍷", 3: "🍫"}` 여기서 키는 열거 가능한 속성이에요. `0` `1` `2` `3`이 출력되죠. -_for-of_ 루프에서는, **반복 가능한** 속성을 가진 요소에 대해 반복 할 수 있어요. -배열은 반복 가능해요. 배열을 반복할 때, "item" 변수는 현재 반복중인 요소로, -`"☕"` ` "💻"` `"🍷"` `"🍫"`이 출력돼요. +_for-of_ 루프에서는, **반복 가능한** 속성을 가진 요소에 대해 반복 할 수 있어요. 배열은 반복 가능해요. 배열을 반복할 때, "item" 변수는 현재 반복중인 요소로, `"☕"` ` "💻"` `"🍷"` `"🍫"`이 출력돼요.

@@ -2800,24 +2515,22 @@ _for-of_ 루프에서는, **반복 가능한** 속성을 가진 요소에 대해 ```javascript const list = [1 + 2, 1 * 2, 1 / 2] -console.log(list) +console.log(list); ``` - A: `["1 + 2", "1 * 2", "1 / 2"]` - B: `["12", 2, 0.5]` - C: `[3, 2, 0.5]` -- D: `[1, 1, 1]` +- D: `[1, 1, 1]`
정답

#### 정답: C -배열 요소들은 모든 값을 포함 할 수 있어요. Numbers, strings, objects, 다른 -arrays, null, boolean 값, undefined, 그리고 자료형, 함수, 연산자와 같은 표현식들 +배열 요소들은 모든 값을 포함 할 수 있어요. Numbers, strings, objects, 다른 arrays, null, boolean 값, undefined, 그리고 자료형, 함수, 연산자와 같은 표현식들 -요소는 리턴된 값과 같아질 거예요. `1 + 2`는 `3`을 리턴하고, `1 * 2`는 `2`를 리턴 -하고, `1 / 2` 는 `0.5`을 리턴해요. +요소는 리턴된 값과 같아질 거예요. `1 + 2`는 `3`을 리턴하고, `1 * 2`는 `2`를 리턴하고, `1 / 2` 는 `0.5`을 리턴해요.

@@ -2831,28 +2544,26 @@ function sayHi(name) { return `Hi there, ${name}` } -console.log(sayHi()) +console.log(sayHi()); ``` - A: `Hi there, ` - B: `Hi there, undefined` - C: `Hi there, null` -- D: `ReferenceError` +- D: `ReferenceError`
정답

#### 정답: B -기본값으로, 함수에 값이 전달되지 않으면, 인수는 `undefined` 값을 가져요. 이 경우 -, `name` 인수를 위한 값을 전달하지 않았어요. `name`은 `undefined`로 출력돼요. +기본값으로, 함수에 값이 전달되지 않으면, 인수는 `undefined` 값을 가져요. 이 경우, `name` 인수를 위한 값을 전달하지 않았어요. `name`은 `undefined`로 출력돼요. ES6에서, 기본값 `undefined` 값을 기본값 파라미터로 덮어쓸 수 있어요. 예를 들면: `function sayHi(name = "Lydia") { ... }` -이 경우, 값을 전달하지 않거나 `undefined`를 전달하면, `name`은 항상 문자열 -`Lydia`가 될 거예요. +이 경우, 값을 전달하지 않거나 `undefined`를 전달하면, `name`은 항상 문자열 `Lydia`가 될 거예요.

@@ -2862,21 +2573,21 @@ ES6에서, 기본값 `undefined` 값을 기본값 파라미터로 덮어쓸 수 ###### 82. 무엇이 출력 될까요? ```javascript -var status = '😎' +var status = "😎"; setTimeout(() => { - const status = '😍' + const status = "😍"; const data = { - status: '🥑', + status: "🥑", getStatus() { - return this.status - }, - } + return this.status; + } + }; - console.log(data.getStatus()) - console.log(data.getStatus.call(this)) -}, 0) + console.log(data.getStatus()); + console.log(data.getStatus.call(this)); +}, 0); ``` - A: `"🥑"` 그리고 `"😍"` @@ -2889,16 +2600,9 @@ setTimeout(() => { #### 정답: B -`this`키워드의 값은 사용하는 곳에 따라 달라요. **메소드**에서 `getStatus`메소드 -처럼, `this`키워드는 _메소드가 속한 객체_ 를 참조해요. 이 메소드는 `data` 객체에 -속해 있어, `this`는 `data`객체를 참조해요. `this.status`를 출력할 때, `data`객체 -의 `status` 속성 `"🥑"`이 출력돼요. +`this`키워드의 값은 사용하는 곳에 따라 달라요. **메소드**에서 `getStatus`메소드 처럼, `this`키워드는 _메소드가 속한 객체_ 를 참조해요. 이 메소드는 `data` 객체에 속해 있어, `this`는 `data`객체를 참조해요. `this.status`를 출력할 때, `data`객체의 `status` 속성 `"🥑"`이 출력돼요. -`call` 메소드에서는, `this` 키워드가 참조하는 객체를 바꿀 수 있어요. **함수**에 -서, `this` 키워드는 _함수가 속한 객체_ 를 참조해요. `setTimeout` 함수를 _전역 객 -체_ 에 선언했고, `setTimeout` 함수 안에서, `this`키워드는 _전역 객체_ 를 참조해 -요. 전역 객체에서, 변수는 `"😎"`값을 가진 _status_ 를 부르죠. `this.status`를 출 -력하면, `"😎"`이 출력돼요. +`call` 메소드에서는, `this` 키워드가 참조하는 객체를 바꿀 수 있어요. **함수**에서, `this` 키워드는 _함수가 속한 객체_ 를 참조해요. `setTimeout` 함수를 _전역 객체_ 에 선언했고, `setTimeout` 함수 안에서, `this`키워드는 _전역 객체_ 를 참조해요. 전역 객체에서, 변수는 `"😎"`값을 가진 _status_ 를 부르죠. `this.status`를 출력하면, `"😎"`이 출력돼요.

@@ -2909,14 +2613,14 @@ setTimeout(() => { ```javascript const person = { - name: 'Lydia', - age: 21, -} + name: "Lydia", + age: 21 +}; -let city = person.city -city = 'Amsterdam' +let city = person.city; +city = "Amsterdam"; -console.log(person) +console.log(person); ``` - A: `{ name: "Lydia", age: 21 }` @@ -2929,14 +2633,11 @@ console.log(person) #### 정답: A -`city` 변수를 `person` 객체의 `city`라고 불리는 속성 값으로 설정 했어요. 이 객체 -에서는 `city`라고 불리는 속성이 없기 때문에, `city`는 `undefined`의 값을 가져요. +`city` 변수를 `person` 객체의 `city`라고 불리는 속성 값으로 설정 했어요. 이 객체에서는 `city`라고 불리는 속성이 없기 때문에, `city`는 `undefined`의 값을 가져요. -`person`객체 자체를 참조 _하지않는_ 다는 걸 참고해요! 변수 `city`는 `person` 객 -체의 `city` 현재 속성 값으로 설정 했을 뿐이죠. +`person`객체 자체를 참조 _하지않는_ 다는 걸 참고해요! 변수 `city`는 `person` 객체의 `city` 현재 속성 값으로 설정 했을 뿐이죠. -그러므로, 우리는 `city`를 문자열 `"Amsterdam"`로 설정 했어요. 이건 person 객체를 -바꾸지 않아요: 여기서 객체를 참조하는 건 없어요. +그러므로, 우리는 `city`를 문자열 `"Amsterdam"`로 설정 했어요. 이건 person 객체를 바꾸지 않아요: 여기서 객체를 참조하는 건 없어요. `person`객체를 출력할 때, 수정되지 않은 객체가 리턴 받아요. @@ -2950,15 +2651,15 @@ console.log(person) ```javascript function checkAge(age) { if (age < 18) { - const message = "Sorry, you're too young." + const message = "Sorry, you're too young."; } else { - const message = "Yay! You're old enough!" + const message = "Yay! You're old enough!"; } - return message + return message; } -console.log(checkAge(21)) +console.log(checkAge(21)); ``` - A: `"Sorry, you're too young."` @@ -2971,9 +2672,7 @@ console.log(checkAge(21)) #### 정답: C -`const`와 `let` 키워드를 사용한 변수는 _블록-스코프_ 예요. 블록은 중괄호 (`{ }`) -사이에 있는 것이죠. 이 경우, if/else 표현식의 중괄호를 의미해요. 블록 안에 선언 -된 건 블록 밖의 변수들을 참조하지 못해, ReferenceError를 던져요. +`const`와 `let` 키워드를 사용한 변수는 _블록-스코프_ 예요. 블록은 중괄호 (`{ }`) 사이에 있는 것이죠. 이 경우, if/else 표현식의 중괄호를 의미해요. 블록 안에 선언된 건 블록 밖의 변수들을 참조하지 못해, ReferenceError를 던져요.

@@ -2985,7 +2684,7 @@ console.log(checkAge(21)) ```javascript fetch('https://www.website.com/api/user/1') .then(res => res.json()) - .then(res => console.log(res)) + .then(res => console.log(res)); ``` - A: `fetch` 메소드의 결과 @@ -2998,8 +2697,7 @@ fetch('https://www.website.com/api/user/1') #### 정답: C -두번째 `.then`에서의 `res`의 값은 이전`.then`에서 리턴된 값이에요. 이것 처럼 -`.then`을 계속해서 연결할 수 있고, 값은 계속해서 다음 핸들러로 전달 돼요. +두번째 `.then`에서의 `res`의 값은 이전`.then`에서 리턴된 값이에요. 이것 처럼 `.then`을 계속해서 연결할 수 있고, 값은 계속해서 다음 핸들러로 전달 돼요.

@@ -3024,12 +2722,9 @@ function getName(name) { #### 정답: A -`!!name`에서, 우리는 `name`의 값이 참 같은지 거짓 같은지 결정해요. 만약 테스트 -하려는 name이 참 같다면, `!name`은 `false`를 리턴해요. `!false` (실제로는 -`!!name`)는 `true`를 리턴해요. +`!!name`에서, 우리는 `name`의 값이 참 같은지 거짓 같은지 결정해요. 만약 테스트 하려는 name이 참 같다면, `!name`은 `false`를 리턴해요. `!false` (실제로는 `!!name`)는 `true`를 리턴해요. -`hasName`을 `name`으로 설정하면, `hasName`은 불린 값 `true`가 아니라, `getName` -함수에 전달된 값으로 설정해요. +`hasName`을 `name`으로 설정하면, `hasName`은 불린 값 `true`가 아니라, `getName` 함수에 전달된 값으로 설정해요. `new Boolean(true)`은 불린 값 자체가 아닌, 감싼 객체를 리턴해요. @@ -3043,7 +2738,7 @@ function getName(name) { ###### 87. 무엇이 출력 될까요? ```javascript -console.log('I want pizza'[0]) +console.log("I want pizza"[0]); ``` - A: `"""` @@ -3056,12 +2751,9 @@ console.log('I want pizza'[0]) #### 정답: B -문자열의 특정 인덱스의 문자를 얻으려면, 대괄호 표기법을 사용하면 돼요. 문자열의 -첫 번째 문자는 인덱스 0과 기타등등을 가지고 있어요. 이 경우 문자 `"I'`인 인덱스 -0이 출력되는 요소를 갖길 원해요. +문자열의 특정 인덱스의 문자를 얻으려면, 대괄호 표기법을 사용하면 돼요. 문자열의 첫 번째 문자는 인덱스 0과 기타등등을 가지고 있어요. 이 경우 문자 `"I'`인 인덱스 0이 출력되는 요소를 갖길 원해요. -이 방법은 IE7 이하에서는 지원되지 않는다는 것을 유의하세요. 이 경우, -`.charAt()`를 사용하세요. +이 방법은 IE7 이하에서는 지원되지 않는다는 것을 유의하세요. 이 경우, `.charAt()`를 사용하세요.

@@ -3088,14 +2780,9 @@ sum(10) #### 정답: B -기본 파라미터의 값은 기본 파라미터를 정의하기 _전_ 이라면, 함수의 다른 파라미터 -와 같게 설정 할 수 있어요. 우리는 `sum` 함수에 값 `10`을 전달 했어요. 만약 `sum` -함수에 인수의 값을 하나만 받았다면, `num2`를 위한 값은 전달되지 않고, `num1`은 -전달된 값과 같다는 의미에요. `num1`의 기본값은 `num1`의 값인 `10`과 같아요. -`num1 + num2`는 `20`을 리턴해요. +기본 파라미터의 값은 기본 파라미터를 정의하기 _전_ 이라면, 함수의 다른 파라미터와 같게 설정 할 수 있어요. 우리는 `sum` 함수에 값 `10`을 전달 했어요. 만약 `sum` 함수에 인수의 값을 하나만 받았다면, `num2`를 위한 값은 전달되지 않고, `num1`은 전달된 값과 같다는 의미에요. `num1`의 기본값은 `num1`의 값인 `10`과 같아요. `num1 + num2`는 `20`을 리턴해요. -만약 기본 파리미터가 정의된 _후_ (오른쪽에) 기본 파라미터의 값을 설정하려고 시도 -한다면, 파라미터의 값은 아직 초기화되지 않아, 오류를 던질 거에요. +만약 기본 파리미터가 정의된 _후_ (오른쪽에) 기본 파라미터의 값을 설정하려고 시도한다면, 파라미터의 값은 아직 초기화되지 않아, 오류를 던질 거에요.

@@ -3105,12 +2792,12 @@ sum(10) ###### 89. 무엇이 출력 될까요? ```javascript -// module.js -export default () => 'Hello world' -export const name = 'Lydia' +// module.js +export default () => "Hello world" +export const name = "Lydia" -// index.js -import * as data from './module' +// index.js +import * as data from "./module" console.log(data) ``` @@ -3125,14 +2812,9 @@ console.log(data) #### 정답: A -`import * as name` 신택스를 사용해서, `module.js` 파일에 있는 _모든 exports_ 를 -`index.js` 파일 안에 `data`라고 불리는 새로운 객체를 생성해요. `module.js` 파일 -에는, 2개의 export가 있어요: default export 와 named export. default export는 문 -자열 `"Hello World"`을 리턴하는 함수고, named export는 문자열 `"Lydia"`의 값을 -가진 `name`이라고 불리는 변수예요. +`import * as name` 신택스를 사용해서, `module.js` 파일에 있는 _모든 exports_ 를 `index.js` 파일 안에 `data`라고 불리는 새로운 객체를 생성해요. `module.js` 파일에는, 2개의 export가 있어요: default export 와 named export. default export는 문자열 `"Hello World"`을 리턴하는 함수고, named export는 문자열 `"Lydia"`의 값을 가진 `name`이라고 불리는 변수예요. -`data` 객체는 default export를 위한 `default` 속성을 가지고, 다른 속성들은 named -exports의 이름들과 그에 해당하는 값들을 가져요. +`data` 객체는 default export를 위한 `default` 속성을 가지고, 다른 속성들은 named exports의 이름들과 그에 해당하는 값들을 가져요.

@@ -3148,7 +2830,7 @@ class Person { } } -const member = new Person('John') +const member = new Person("John") console.log(typeof member) ``` @@ -3162,17 +2844,15 @@ console.log(typeof member) #### 정답: C -Class는 함수 생성자를 위한 문법적 설탕이에요. 함수 생성자로서 `Person` 클래스와 -동등한 것은 다음과 같아요: +Class는 함수 생성자를 위한 문법적 설탕이에요. 함수 생성자로서 `Person` 클래스와 동등한 것은 다음과 같아요: ```javascript function Person() { - this.name = name + this.name = name; } ``` -`new`와 함께 불려진 함수 생성자는 `Person`의 인스턴스를 생성하고, `typeof` 키워 -드는 인스턴스의 `"object"`를 리턴해요. `typeof member`는 `"object"`을 리턴해요. +`new`와 함께 불려진 함수 생성자는 `Person`의 인스턴스를 생성하고, `typeof` 키워드는 인스턴스의 `"object"`를 리턴해요. `typeof member`는 `"object"`을 리턴해요.

@@ -3197,12 +2877,9 @@ console.log(newList.push(5)) #### 정답: D -`.push` 메소드는 배열 자체가 아니라, 배열의 _새로운 길이_ 를 리턴해요! -`newList`를 `[1, 2, 3].push(4)`과 동일하게 설정함으로써, `newList`를 배열의 새로 -운 길이와 동일하게 설정했어요: `4`. +`.push` 메소드는 배열 자체가 아니라, 배열의 _새로운 길이_ 를 리턴해요! `newList`를 `[1, 2, 3].push(4)`과 동일하게 설정함으로써, `newList`를 배열의 새로운 길이와 동일하게 설정했어요: `4`. -그리고나서, `.push` 메소드를 `newList`에 사용하려고 했어요. `newList`는 숫자 값 -`4` 이기 때문에, `.push` 메소드를 사용할 수 없어요: TypeError가 던져져요. +그리고나서, `.push` 메소드를 `newList`에 사용하려고 했어요. `newList`는 숫자 값 `4` 이기 때문에, `.push` 메소드를 사용할 수 없어요: TypeError가 던져져요.

@@ -3213,18 +2890,17 @@ console.log(newList.push(5)) ```javascript function giveLydiaPizza() { - return 'Here is pizza!' + return "Here is pizza!" } -const giveLydiaChocolate = () => - "Here's chocolate... now go hit the gym already." +const giveLydiaChocolate = () => "Here's chocolate... now go hit the gym already." console.log(giveLydiaPizza.prototype) console.log(giveLydiaChocolate.prototype) ``` -- A: `{ constructor: ...}` `{ constructor: ...}` -- B: `{}` `{ constructor: ...}` +- A: `{ constructor: ...}` `{ constructor: ...}` +- B: `{}` `{ constructor: ...}` - C: `{ constructor: ...}` `{}` - D: `{ constructor: ...}` `undefined` @@ -3233,11 +2909,7 @@ console.log(giveLydiaChocolate.prototype) #### 정답: D -`giveLydiaPizza`와 같은 정규 함수는, `생성자` 속성을 가진 `프로토타입` 객체(프로 -토타입 객체)를 속성으로 가져요. 그러나 `giveLydiaChocolate` 함수와 같은 화살표 -함수에서는, `prototype` 속성을 가지고 있지 않아요. -`giveLydiaChocolate.prototype`을 사용해 `prototype` 속성에 접근하려고 할때, -`undefined`이 리턴될 거에요. +`giveLydiaPizza`와 같은 정규 함수는, `생성자` 속성을 가진 `프로토타입` 객체(프로토타입 객체)를 속성으로 가져요. 그러나 `giveLydiaChocolate` 함수와 같은 화살표 함수에서는, `prototype` 속성을 가지고 있지 않아요. `giveLydiaChocolate.prototype`을 사용해 `prototype` 속성에 접근하려고 할때, `undefined`이 리턴될 거에요.

@@ -3248,9 +2920,9 @@ console.log(giveLydiaChocolate.prototype) ```javascript const person = { - name: 'Lydia', - age: 21, -} + name: "Lydia", + age: 21 +}; for (const [x, y] of Object.entries(person)) { console.log(x, y) @@ -3258,7 +2930,7 @@ for (const [x, y] of Object.entries(person)) { ``` - A: `name` `Lydia` 그리고 `age` `21` -- B: `["name", "Lydia"]` 그리고 `["age", 21]` +- B: `["name", "Lydia"]` 그리고 `["age", 21]` - C: `["name", "age"]` 그리고 `undefined` - D: `Error` @@ -3269,16 +2941,12 @@ for (const [x, y] of Object.entries(person)) { `Object.entries(person)`은 키와 값을 세트로 가진 배열의 배열을 리턴해요: -`[ [ 'name', 'Lydia' ], [ 'age', 21 ] ]` +`[ [ 'name', 'Lydia' ], [ 'age', 21 ] ]` -`for-of` 루프를 사용해서, 배열 안에 각 요소를 계속해서 반복할 수 있는데, 이 경우 -엔 하위 배열이에요. 하위 배열을 `const [x, y]`을 사용해, for-of 루프에서 즉시 분 -해할 수 있어요. `x`는 하위 배열의 첫 번째 요소와 같고, `y`는 하위 배열의 두 번째 -요소와 같아요. +`for-of` 루프를 사용해서, 배열 안에 각 요소를 계속해서 반복할 수 있는데, 이 경우엔 하위 배열이에요. 하위 배열을 `const [x, y]`을 사용해, for-of 루프에서 즉시 분해할 수 있어요. `x`는 하위 배열의 첫 번째 요소와 같고, `y`는 하위 배열의 두 번째 요소와 같아요. -첫번째 하위요소는 `[ "name", "Lydia" ]`로, `x`는 `"name"`, `y`는 `"Lydia"`을 출 -력해요. 두번째 하위요소는 `[ "age", 21 ]`로, `x`는 `"age"`, `y`는 `21`을 출력해 -요. +첫번째 하위요소는 `[ "name", "Lydia" ]`로, `x`는 `"name"`, `y`는 `"Lydia"`을 출력해요. +두번째 하위요소는 `[ "age", 21 ]`로, `x`는 `"age"`, `y`는 `21`을 출력해요.

@@ -3296,7 +2964,7 @@ console.log(getItems(["banana", "apple"], "pear", "orange")) ``` - A: `["banana", "apple", "pear", "orange"]` -- B: `[["banana", "apple"], "pear", "orange"]` +- B: `[["banana", "apple"], "pear", "orange"]` - C: `["banana", "apple", ["pear"], "orange"]` - D: `SyntaxError` @@ -3305,21 +2973,17 @@ console.log(getItems(["banana", "apple"], "pear", "orange")) #### 정답: D -`...args`은 나머지 파라미터예요. 나머지 파라미터의 값은 모든 나머지 인수들을 포 -함한 배열이며, **마지막 파라미터만 될 수 있어요**! 지금 예시에서는, 나머지 파라 -미터는 두번째 파라미터예요. 이것은 불가능하고, 신택스 에러를 던지게 될거에요. +`...args`은 나머지 파라미터예요. 나머지 파라미터의 값은 모든 나머지 인수들을 포함한 배열이며, **마지막 파라미터만 될 수 있어요**! 지금 예시에서는, 나머지 파라미터는 두번째 파라미터예요. 이것은 불가능하고, 신택스 에러를 던지게 될거에요. ```javascript function getItems(fruitList, favoriteFruit, ...args) { return [...fruitList, ...args, favoriteFruit] } -getItems(['banana', 'apple'], 'pear', 'orange') +getItems(["banana", "apple"], "pear", "orange") ``` -The above example works. This returns the array -`[ 'banana', 'apple', 'orange', 'pear' ]` - +The above example works. This returns the array `[ 'banana', 'apple', 'orange', 'pear' ]`

@@ -3329,9 +2993,12 @@ The above example works. This returns the array ```javascript function nums(a, b) { - if (a > b) console.log('a is bigger') - else console.log('b is bigger') - return + if + (a > b) + console.log('a is bigger') + else + console.log('b is bigger') + return a + b } @@ -3349,23 +3016,16 @@ console.log(nums(1, 2)) #### 정답: B -JavaScript에서, 세미콜론을 (`;`)을 명시적으로 포함하여 쓰지 _않_ 더라도, -JavaScript 엔진은 여전히 문 뒤에 그들을 추가해줘요. 이것은 **자동 세미콜론 삽 -입**이라고 불려요. 예를 들어 문은 변수, 또는 `throw`, `return`, `break` 등과 같 -은 키워드가 될 수도 있어요. +JavaScript에서, 세미콜론을 (`;`)을 명시적으로 포함하여 쓰지 _않_ 더라도, JavaScript 엔진은 여전히 문 뒤에 그들을 추가해줘요. 이것은 **자동 세미콜론 삽입**이라고 불려요. 예를 들어 문은 변수, 또는 `throw`, `return`, `break` 등과 같은 키워드가 될 수도 있어요. -여기, `return`문을 썼고, 다른 값 `a + b`은 _새로운 줄_ 에 쓰였어요. 그러나, 새로 -운 줄이기 때문에, 엔진은 실제로 그 값이 리턴되길 바라는지 알 수 없어요. 대신에, -자동적으로 `return` 뒤에 세미콜론을 더해줘요. 이것을 볼 수 있을거에요: +여기, `return`문을 썼고, 다른 값 `a + b`은 _새로운 줄_ 에 쓰였어요. 그러나, 새로운 줄이기 때문에, 엔진은 실제로 그 값이 리턴되길 바라는지 알 수 없어요. 대신에, 자동적으로 `return` 뒤에 세미콜론을 더해줘요. 이것을 볼 수 있을거에요: ```javascript -return -a + b + return; + a + b ``` -`return` 키워드 뒤에 함수가 실행되는 것이 중단되기 때문에, `a + b`의 의미는 도달 -되지 않아요. 여기서 처럼, 만약 아무 값도 리턴되지 않는다면, 함수는 `undefined`를 -리턴할 거예요. `if/else`문 뒤에는 자동으로 삽입되는 게 없다는 걸 유의해요! +`return` 키워드 뒤에 함수가 실행되는 것이 중단되기 때문에, `a + b`의 의미는 도달되지 않아요. 여기서 처럼, 만약 아무 값도 리턴되지 않는다면, 함수는 `undefined`를 리턴할 거예요. `if/else`문 뒤에는 자동으로 삽입되는 게 없다는 걸 유의해요!

@@ -3377,13 +3037,13 @@ a + b ```javascript class Person { constructor() { - this.name = 'Lydia' + this.name = "Lydia" } } Person = class AnotherPerson { constructor() { - this.name = 'Sarah' + this.name = "Sarah" } } @@ -3401,9 +3061,7 @@ console.log(member.name) #### 정답: B -다른 클래스/함수 생성자로 클래스를 설정할 수 있어요. 이 경우, `Person`을 -`AnotherPerson`로 설정했어요. 이 생성자의 name은 `Sarah`예요, 따라서 새로운 -`Person`의 인스턴스 `member`의 name 속성은 `"Sarah"`예요. +다른 클래스/함수 생성자로 클래스를 설정할 수 있어요. 이 경우, `Person`을 `AnotherPerson`로 설정했어요. 이 생성자의 name은 `Sarah`예요, 따라서 새로운 `Person`의 인스턴스 `member`의 name 속성은 `"Sarah"`예요.

@@ -3414,7 +3072,7 @@ console.log(member.name) ```javascript const info = { - [Symbol('a')]: 'b', + [Symbol('a')]: 'b' } console.log(info) @@ -3431,15 +3089,9 @@ console.log(Object.keys(info)) #### 정답: D -심볼은 _열거 불가능_ 해요. Object.keys 메소드는 객체의 모든 _열거 가능_ 한 키 속 -성들을 리턴해요. 심볼은 보이지 않고, 빈 객체가 리턴돼요. 객체 전체를 출력할때, -모든 속성들은 보여요, 심지어 열거 불가능한 것이라해도. +심볼은 _열거 불가능_ 해요. Object.keys 메소드는 객체의 모든 _열거 가능_ 한 키 속성들을 리턴해요. 심볼은 보이지 않고, 빈 객체가 리턴돼요. 객체 전체를 출력할때, 모든 속성들은 보여요, 심지어 열거 불가능한 것이라해도. -이것은 심볼의 많은 특성 중 하나에요: 완전히 고유한 값(예를들어 2개의 라이브러리 -를 같은 객체의 속성으로 추가하고 싶을때, 객체의 우연한 이름 충돌을 방지해요)을 -나타내는 것 외에, 이 방법으로 객체의 속성을 "숨길" 수 있어요(비록 완전히는 아닐 -지라도. 여전히 `Object.getOwnPropertySymbols()` 메소드를 사용해 심볼에 접근 할 -수 있어요). +이것은 심볼의 많은 특성 중 하나에요: 완전히 고유한 값(예를들어 2개의 라이브러리를 같은 객체의 속성으로 추가하고 싶을때, 객체의 우연한 이름 충돌을 방지해요)을 나타내는 것 외에, 이 방법으로 객체의 속성을 "숨길" 수 있어요(비록 완전히는 아닐지라도. 여전히 `Object.getOwnPropertySymbols()` 메소드를 사용해 심볼에 접근 할 수 있어요).

@@ -3469,22 +3121,15 @@ console.log(getUser(user)) #### 정답: A -`getList`함수는 배열을 인수로 받았어요. `getList` 함수의 괄호 사이에 있는 배열을 -즉시 분해 했어요: +`getList`함수는 배열을 인수로 받았어요. `getList` 함수의 괄호 사이에 있는 배열을 즉시 분해 했어요: -`[x, ...y] = [1, 2, 3, 4]` + `[x, ...y] = [1, 2, 3, 4]` -나머지 파라미터를 사용해 `...y`에 모든 "남은" 인수들을 배열에 넣었어요. 이 경우 -에서 남아있는 인수는 `2`, `3` 그리고 `4`예요. `y`의 값은 배열이고, 모든 나머지 -파라미터를 포함하고 있어요. 이 경우 `x`의 값은 `1`이기 때문에, `[x, y]`는 -`[1, [2, 3, 4]]`로 출력돼요. +나머지 파라미터를 사용해 `...y`에 모든 "남은" 인수들을 배열에 넣었어요. 이 경우에서 남아있는 인수는 `2`, `3` 그리고 `4`예요. `y`의 값은 배열이고, 모든 나머지 파라미터를 포함하고 있어요. 이 경우 `x`의 값은 `1`이기 때문에, `[x, y]`는 `[1, [2, 3, 4]]`로 출력돼요. -`getUser` 함수는 배열을 받았어요. 화살표 함수에서, 우리가 한개의 값을 리턴한다면 -중괄호를 사용할 _필요_ 가 없어요. 그러나, 만약 화살표 함수에서 _객체_ 를 리턴하 -고 싶다면, 괄호 사이에 리턴할 값을 써야해요, 그렇지 않다면 아무 값도 리턴받을 수 -없어요! 다음 함수에서는 객체가 리턴 될 거에요: +`getUser` 함수는 배열을 받았어요. 화살표 함수에서, 우리가 한개의 값을 리턴한다면 중괄호를 사용할 _필요_ 가 없어요. 그러나, 만약 화살표 함수에서 _객체_ 를 리턴하고 싶다면, 괄호 사이에 리턴할 값을 써야해요, 그렇지 않다면 아무 값도 리턴받을 수 없어요! 다음 함수에서는 객체가 리턴 될 거에요: -`const getUser = user => ({ name: user.name, age: user.age })` +```const getUser = user => ({ name: user.name, age: user.age })``` 이 경우 값이 리턴되는 값이 없으므로, 함수는 `undefined`을 리턴할거에요. @@ -3496,7 +3141,7 @@ console.log(getUser(user)) ###### 99. 무엇이 출력 될까요? ```javascript -const name = 'Lydia' +const name = "Lydia" console.log(name()) ``` @@ -3511,18 +3156,13 @@ console.log(name()) #### 정답: C -변수 `name`은 문자열을 값으로 가지고 있고, 함수가 아니죠, 따라서 호출할 수 없어 -요. +변수 `name`은 문자열을 값으로 가지고 있고, 함수가 아니죠, 따라서 호출할 수 없어요. -TypeErrors는 값이 예상된 유형이 아닐 경우 던져져요. JavaScript는 `name`을 호출하 -려고 했기 때문에 함수일거라 예상했어요. 그러나 문자열이였기 때문에, TypeError가 -던져져요: name은 함수가 아니죠! +TypeErrors는 값이 예상된 유형이 아닐 경우 던져져요. JavaScript는 `name`을 호출하려고 했기 때문에 함수일거라 예상했어요. 그러나 문자열이였기 때문에, TypeError가 던져져요: name은 함수가 아니죠! -SyntaxErrors는 어떤 것을 썼을때 JavaScript에서 유효하지 않을 때 던져져요, 예를들 -어 `return`을 `retrun`로 썼을때 말이죠. +SyntaxErrors는 어떤 것을 썼을때 JavaScript에서 유효하지 않을 때 던져져요, 예를들어 `return`을 `retrun`로 썼을때 말이죠. -ReferenceErrors는 JavaScript가 접근하려고 하는 값의 참조를 찾을 수 없을 때 던져 -져요. +ReferenceErrors는 JavaScript가 접근하려고 하는 값의 참조를 찾을 수 없을 때 던져져요.

@@ -3548,12 +3188,9 @@ You should${'' && `n't`} see a therapist after so much JavaScript lol` #### 정답: B -`[]`은 참 같은 값이에요. `&&` 연산자를 사용할 때, 만약 왼쪽에 있는 값이 참 같은 -값이라면 오른쪽 값은 리턴될 거에요. 이 경우, 왼쪽의 값 `[]`은 참 같은 값이에요, -따라서 `'Im'`은 리턴될 거예요. +`[]`은 참 같은 값이에요. `&&` 연산자를 사용할 때, 만약 왼쪽에 있는 값이 참 같은 값이라면 오른쪽 값은 리턴될 거에요. 이 경우, 왼쪽의 값 `[]`은 참 같은 값이에요, 따라서 `'Im'`은 리턴될 거예요. -`""`은 거짓 같은 값이에요. 만약 왼쪽 값이 거짓 같은 값이라면, 리턴되는 것은 없어 -요. `n't`은 리턴되지 않아요. +`""`은 거짓 같은 값이에요. 만약 왼쪽 값이 거짓 같은 값이라면, 리턴되는 것은 없어요. `n't`은 리턴되지 않아요.

@@ -3563,9 +3200,9 @@ You should${'' && `n't`} see a therapist after so much JavaScript lol` ###### 101. 무엇이 출력 될까요? ```javascript -const one = false || {} || null -const two = null || false || '' -const three = [] || 0 || true +const one = (false || {} || null) +const two = (null || false || "") +const three = ([] || 0 || true) console.log(one, two, three) ``` @@ -3580,17 +3217,13 @@ console.log(one, two, three) #### 정답: C -`||` 연산자를 사용하면, 최초의 참 같은 피연산자를 리턴해요. 만약 모든 값이 거짓 -같다면, 마지막 피연산자를 리턴해요. +`||` 연산자를 사용하면, 최초의 참 같은 피연산자를 리턴해요. 만약 모든 값이 거짓 같다면, 마지막 피연산자를 리턴해요. -`(false || {} || null)`: 빈 객체 `{}`는 진짜 같은 값이에요. 이것은 최초로(그리고 -유일하게) 진짜 같은 값이라 리턴돼요. `one`은 `{}`이에요. +`(false || {} || null)`: 빈 객체 `{}`는 진짜 같은 값이에요. 이것은 최초로(그리고 유일하게) 진짜 같은 값이라 리턴돼요. `one`은 `{}`이에요. -`(null || false || "")`: 모든 피연산자는 가짜 같은 값이에요. 이것은 마지막 피연 -산자 `""`가 리턴된다는 것을 의미해요. `two`는 `""`이에요. +`(null || false || "")`: 모든 피연산자는 가짜 같은 값이에요. 이것은 마지막 피연산자 `""`가 리턴된다는 것을 의미해요. `two`는 `""`이에요. -`([] || 0 || "")`: 빈 배열 `[]`은 진짜 같은 값이에요. 이것은 최초의 진짜 같은 값 -이라 리턴돼요. `three`은 `[]`이에요. +`([] || 0 || "")`: 빈 배열 `[]`은 진짜 같은 값이에요. 이것은 최초의 진짜 같은 값이라 리턴돼요. `three`은 `[]`이에요.

@@ -3626,24 +3259,15 @@ secondFunction() #### 정답: D -promise를 사용하면, 기본적으로 _이 함수를 실행하고 싶지만, 시간이 좀 걸릴 수 있 -으니 실행 중에 잠시 미뤄둘거에요. 확실한 값이 resoloved(혹은 rejected)로 전달되 -었을 때와 콜 스택이 비었을 때 이 값을 사용하고 싶어요_ 라고 말해요. +promise를 사용하면, 기본적으로 _이 함수를 실행하고 싶지만, 시간이 좀 걸릴 수 있으니 실행 중에 잠시 미뤄둘거에요. 확실한 값이 resoloved(혹은 rejected)로 전달되었을 때와 콜 스택이 비었을 때 이 값을 사용하고 싶어요_ 라고 말해요. -`async` 함수 안에서 `.then`과 `await` 두개의 키워드에서 값을 얻을 수 있어요. 비 -록 `.then`과 `await`에서 프라미스의 값을 얻을 수 있지만, 그들은 약간 다르게 작동 -해요. +`async` 함수 안에서 `.then`과 `await` 두개의 키워드에서 값을 얻을 수 있어요. 비록 `.then`과 `await`에서 프라미스의 값을 얻을 수 있지만, 그들은 약간 다르게 작동해요. -첫번째 `firstFunction`에서, (뭐랄까) myPromise 함수가 실행되는 것을 미뤘지만, 다 -른 코드를 계속해서 실행하는데, 이 경우 `console.log('second')`에요. 그리고나서, -함수는 콜스택이 비워져 있는 걸 본 다음 출력된 문자열 `I have resolved`를 -resolved로 전달해요. +첫번째 `firstFunction`에서, (뭐랄까) myPromise 함수가 실행되는 것을 미뤘지만, 다른 코드를 계속해서 실행하는데, 이 경우 `console.log('second')`에요. 그리고나서, 함수는 콜스택이 비워져 있는 걸 본 다음 출력된 문자열 `I have resolved`를 resolved로 전달해요. -`secondFunction`에서의 await 키워드를 사용하면, 말 그대로 다음 라인으로 옮기기 -전 값이 resoloved함수로 전달될 때 까지 async 함수의 실행을 중단해요. +`secondFunction`에서의 await 키워드를 사용하면, 말 그대로 다음 라인으로 옮기기 전 값이 resoloved함수로 전달될 때 까지 async 함수의 실행을 중단해요. -이것은 `myPromise`이 값 `I have resolved`을 얻을 때 까지 기다린다는 의미이며, 단 -한 번 발생하면, 다음라인으로 이동해요: `second`이 출력되죠. +이것은 `myPromise`이 값 `I have resolved`을 얻을 때 까지 기다린다는 의미이며, 단 한 번 발생하면, 다음라인으로 이동해요: `second`이 출력되죠.

@@ -3656,8 +3280,8 @@ resolved로 전달해요. const set = new Set() set.add(1) -set.add('Lydia') -set.add({ name: 'Lydia' }) +set.add("Lydia") +set.add({ name: "Lydia" }) for (let item of set) { console.log(item + 2) @@ -3674,19 +3298,13 @@ for (let item of set) { #### 정답: C -`+` 연산자는 숫자로 나타난 값을 더하는데 사용될 뿐만 아니라, 문자열을 연결해주는 -데 사용 할 수 있어요. JavaScript 엔진은 하나 이상의 값들이 숫자가 아닌 것을 발견 -했을 때, 숫자를 문자열로 강제로 변환해요. +`+` 연산자는 숫자로 나타난 값을 더하는데 사용될 뿐만 아니라, 문자열을 연결해주는데 사용 할 수 있어요. JavaScript 엔진은 하나 이상의 값들이 숫자가 아닌 것을 발견 했을 때, 숫자를 문자열로 강제로 변환해요. 첫번째 `1`은, 숫자로된 값이에요. `1 + 2`는 숫자 3을 리턴해요. -그러나, 두번째는 문자열 `"Lydia"`이에요. `"Lydia"`은 문자열이고, `2`는 숫자에요: -`2`는 문자열로 강제 변환되어요. `"Lydia"`그리고 `"2"`이 연결되어, 문자열 -`"Lydia2"`이 리턴되요. +그러나, 두번째는 문자열 `"Lydia"`이에요. `"Lydia"`은 문자열이고, `2`는 숫자에요: `2`는 문자열로 강제 변환되어요. `"Lydia"`그리고 `"2"`이 연결되어, 문자열 `"Lydia2"`이 리턴되요. -`{ name: "Lydia" }`은 객체에요. 객체가 아닌 숫자나 객체는 문자열이 아니므로, 둘 -다 문자화되어요. 정규 객체를 문자화 할때, `"[object Object]"`가 돼요. -`"[object Object]"`는 `"2"`와 연결되어 `"[object Object]2"`가 돼요. +`{ name: "Lydia" }`은 객체에요. 객체가 아닌 숫자나 객체는 문자열이 아니므로, 둘다 문자화되어요. 정규 객체를 문자화 할때, `"[object Object]"`가 돼요. `"[object Object]"`는 `"2"`와 연결되어 `"[object Object]2"`가 돼요.

@@ -3709,14 +3327,9 @@ Promise.resolve(5) #### 정답: C -promise이나 non-promise이 아니더라도 값의 모든 타입은 `Promise.resolve`으로 전달 -할 수 있어요. 메소드 그 자체는 resolved 값을 가진 promise를 리턴해요 -(``). 정규 함수를 전달한다면, 정규 값을 가진 resolved promise를 얻게 -될거에요. 만약 promise를 전달한다면, 전달된 promise의 resolved 값과 resolved -promise를 얻게 될거에요. +promise이나 non-promise이 아니더라도 값의 모든 타입은 `Promise.resolve`으로 전달 할 수 있어요. 메소드 그 자체는 resolved 값을 가진 promise를 리턴해요 (``). 정규 함수를 전달한다면, 정규 값을 가진 resolved promise를 얻게 될거에요. 만약 promise를 전달한다면, 전달된 promise의 resolved 값과 resolved promise를 얻게 될거에요. -이 경우, 숫자 값 `5`를 전달했어요. 이것은 값 `5`를 가진 resolved promise를 리턴 -해요. +이 경우, 숫자 값 `5`를 전달했어요. 이것은 값 `5`를 가진 resolved promise를 리턴해요.

@@ -3728,13 +3341,13 @@ promise를 얻게 될거에요. ```javascript function compareMembers(person1, person2 = person) { if (person1 !== person2) { - console.log('Not the same!') + console.log("Not the same!") } else { - console.log('They are the same!') + console.log("They are the same!") } } -const person = { name: 'Lydia' } +const person = { name: "Lydia" } compareMembers(person) ``` @@ -3749,14 +3362,11 @@ compareMembers(person) #### 정답: B -객체는 참조에 의해 전달되었어요. 엄격한 같은 비교 (`===`)로 객체를 검사한다면, -그들의 참조를 비교할거에요. +객체는 참조에 의해 전달되었어요. 엄격한 같은 비교 (`===`)로 객체를 검사한다면, 그들의 참조를 비교할거에요. -`person2`의 기본 값을 `person` 객체와 동일하게 설정 하고, `person` 객체를 -`person1`의 값으로 전달 했어요. +`person2`의 기본 값을 `person` 객체와 동일하게 설정 하고, `person` 객체를 `person1`의 값으로 전달 했어요. -이것은 두개의 값은 메모리의 같은 장소의 참조를 가지고 있다는 걸 의미해요, 그렇기 -때문에 그들은 같아요. +이것은 두개의 값은 메모리의 같은 장소의 참조를 가지고 있다는 걸 의미해요, 그렇기 때문에 그들은 같아요. `else`구문 안에 코드블럭이 실행되면, `They are the same!`을 출력해요. @@ -3776,7 +3386,7 @@ const colorConfig = { yellow: false, } -const colors = ['pink', 'red', 'blue'] +const colors = ["pink", "red", "blue"] console.log(colorConfig.colors[1]) ``` @@ -3791,22 +3401,11 @@ console.log(colorConfig.colors[1]) #### 정답: D -JavaScript에서, 객체의 속성에 접근하는 2가지 방법을 가지고 있어요: 괄호 표기법, -또는 점 표기법. 이 예제에서는, 괄호표기법 (`colorConfig["colors"]`) 대신 점 표기 -법 (`colorConfig.colors`)을 사용 했어요. +JavaScript에서, 객체의 속성에 접근하는 2가지 방법을 가지고 있어요: 괄호 표기법, 또는 점 표기법. 이 예제에서는, 괄호표기법 (`colorConfig["colors"]`) 대신 점 표기법 (`colorConfig.colors`)을 사용 했어요. -점 표기법에서, JavaScript는 정확한 이름을 가진 객체의 속성을 찾으려 해요. 이 예 -제에서 JavaScript는 `colorConfig` 객체의 `colors`라고 불리는 속성을 찾으려고 했 -어요. 그곳에는 `colors`라고 불리는 속성이 없어요, 그래서 `undefined`을 리턴해요. -그리고 나서, `[1]`을 사용해서 첫번째 요소의 값에 접근하려고 했어요. -`undefined`의 값에는 이것을 할 수 없어요, 그래서 `TypeError`를 던져요: -`Cannot read property '1' of undefined`. +점 표기법에서, JavaScript는 정확한 이름을 가진 객체의 속성을 찾으려 해요. 이 예제에서 JavaScript는 `colorConfig` 객체의 `colors`라고 불리는 속성을 찾으려고 했어요. 그곳에는 `colors`라고 불리는 속성이 없어요, 그래서 `undefined`을 리턴해요. 그리고 나서, `[1]`을 사용해서 첫번째 요소의 값에 접근하려고 했어요. `undefined`의 값에는 이것을 할 수 없어요, 그래서 `TypeError`를 던져요: `Cannot read property '1' of undefined`. -JavaScript 문장을 해석(또는 참조형 변수를 원시 데이터 타입으로 만들어 주도록) 해 -요. 괄호 표기법을 사용할때, 첫번째로 열린 괄호 `[`을 보고 닫힌 괄호 `]`를 찾을 -때 까지 계속 진행되는 것으로 보여요. 그러고 나서야, 문장을 평가할거에요. 만약 -`colorConfig[colors[1]]`을 사용했다면, `colorConfig` 객체의 속성 `red` 의 값이 -리턴될 거에요. +JavaScript 문장을 해석(또는 참조형 변수를 원시 데이터 타입으로 만들어 주도록) 해요. 괄호 표기법을 사용할때, 첫번째로 열린 괄호 `[`을 보고 닫힌 괄호 `]`를 찾을 때 까지 계속 진행되는 것으로 보여요. 그러고 나서야, 문장을 평가할거에요. 만약 `colorConfig[colors[1]]`을 사용했다면, `colorConfig` 객체의 속성 `red` 의 값이 리턴될 거에요.

@@ -3827,9 +3426,7 @@ console.log('❤️' === '❤️') #### 정답: A -엔진에서, 이모티콘은 유니코드에요. 하트 이모티콘의 유니코드는 -`"U+2764 U+FE0F"`에요. 같은 이모티콘의 유니코드는 항상 같아요, 따라서 각각 다른 -두개의 같은 문자열을 비교하는 것이므로 true를 리턴해요. +엔진에서, 이모티콘은 유니코드에요. 하트 이모티콘의 유니코드는 `"U+2764 U+FE0F"`에요. 같은 이모티콘의 유니코드는 항상 같아요, 따라서 각각 다른 두개의 같은 문자열을 비교하는 것이므로 true를 리턴해요.

@@ -3845,13 +3442,13 @@ emojis.map(x => x + '✨') emojis.filter(x => x !== '🥑') emojis.find(x => x !== '🥑') emojis.reduce((acc, cur) => acc + '✨') -emojis.slice(1, 2, '✨') +emojis.slice(1, 2, '✨') emojis.splice(1, 2, '✨') ``` - A: `All of them` - B: `map` `reduce` `slice` `splice` -- C: `map` `slice` `splice` +- C: `map` `slice` `splice` - D: `splice`
정답 @@ -3859,12 +3456,9 @@ emojis.splice(1, 2, '✨') #### 정답: D -`splice` method를 사용하면, 요소를 삭제, 대체하거나 추가함으로써 원본 배열을 수 -정해요. 이 경우에서, 인덱스 1에서 부터 2개의 아이템을 제거했어요. (`'🥑'` 와 -`'😍'`를 삭제했어요) 그리고 ✨ 이모티콘을 대신 추가했죠. +`splice` method를 사용하면, 요소를 삭제, 대체하거나 추가함으로써 원본 배열을 수정해요. 이 경우에서, 인덱스 1에서 부터 2개의 아이템을 제거했어요. (`'🥑'` 와 `'😍'`를 삭제했어요) 그리고 ✨ 이모티콘을 대신 추가했죠. -`map`, `filter` 그리고 `slice` 는 새로운 배열을 리턴해하고, `find` 요소를 리턴하 -며, `reduce` 감소된 값을 리턴해요. +`map`, `filter` 그리고 `slice` 는 새로운 배열을 리턴해하고, `find` 요소를 리턴하며, `reduce` 감소된 값을 리턴해요.

@@ -3884,7 +3478,7 @@ console.log(food) - A: `['🍕', '🍫', '🥑', '🍔']` - B: `['🍝', '🍫', '🥑', '🍔']` -- C: `['🍝', '🍕', '🍫', '🥑', '🍔']` +- C: `['🍝', '🍕', '🍫', '🥑', '🍔']` - D: `ReferenceError`
정답 @@ -3892,18 +3486,9 @@ console.log(food) #### 정답: A -`info` 객체의 `favoriteFood` 속성 값을 피자 이모티콘 `'🍕'`와 같게 설정했어요. -문자는 원시 데이터 형이에요. JavaScript에서, 원시 데이터 형은 (객체가 아닌 모든 -것) _값_ 에 의해 상호 작용해요. 이 경우, `info` 객체의 `favoriteFood` 속성 값을 -`food` 배열 안의 첫 번째 요소와 같게 설정했어요. 문자열은 원시 데이터 형이므로 -값에의해 상호 작용해요. (좀 더 알고싶다면 내 -[블로그 포스트](https://www.theavocoder.com/complete-javascript/2018/12/21/by-value-vs-by-reference)를 -참고하세요.) +`info` 객체의 `favoriteFood` 속성 값을 피자 이모티콘 `'🍕'`와 같게 설정했어요. 문자는 원시 데이터 형이에요. JavaScript에서, 원시 데이터 형은 (객체가 아닌 모든 것) _값_ 에 의해 상호 작용해요. 이 경우, `info` 객체의 `favoriteFood` 속성 값을 `food` 배열 안의 첫 번째 요소와 같게 설정했어요. 문자열은 원시 데이터 형이므로 값에의해 상호 작용해요. (좀 더 알고싶다면 내 [블로그 포스트](https://www.theavocoder.com/complete-javascript/2018/12/21/by-value-vs-by-reference)를 참고하세요.) -그리고나서, `info` 객체의 `favoriteFood` 속성 값을 바꿨어요. `favoriteFood`의 값 -은 단지 배열의 첫 번째 요소의 값을 _복사_ 했기 때문에 `food` 배열은 바뀌지 않고, -`food[0]` 요소의 메모리 공간과 같은 참조를 갖지 않아요. food를 출력할 때, 여전히 -원본 배열 ['🍕', '🍫', '🥑', '🍔']` 이에요. +그리고나서, `info` 객체의 `favoriteFood` 속성 값을 바꿨어요. `favoriteFood`의 값은 단지 배열의 첫 번째 요소의 값을 _복사_ 했기 때문에 `food` 배열은 바뀌지 않고, `food[0]` 요소의 메모리 공간과 같은 참조를 갖지 않아요. food를 출력할 때, 여전히 원본 배열 ['🍕', '🍫', '🥑', '🍔']` 이에요.

@@ -3926,9 +3511,8 @@ JSON.parse() #### 정답: A -`JSON.parse()`메소드를 사용하면, JSON 문자열의 구문을 분석하여 JavaScript 값으로 -생성해요. With the `JSON.parse()` method, we can parse JSON string to a -JavaScript value. +`JSON.parse()`메소드를 사용하면, JSON 문자열의 구문을 분석하여 JavaScript 값으로 생성해요. +With the `JSON.parse()` method, we can parse JSON string to a JavaScript value. ```javascript // 숫자를 유효한 JSON 문자열로 변환해요, 그리고 나서 JSON 문자열의 구문을 분석해 JavaScript 값으로 생성해요. @@ -3940,7 +3524,7 @@ const jsonArray = JSON.stringify([1, 2, 3]) // '[1, 2, 3]' JSON.parse(jsonArray) // [1, 2, 3] // 객체를 유효한 JSON 문자열로 변환해요, 그리고 나서 JSON 문자열의 구문을 분석해 JavaScript 값으로 생성해요. -const jsonArray = JSON.stringify({ name: 'Lydia' }) // '{"name":"Lydia"}' +const jsonArray = JSON.stringify({ name: "Lydia" }) // '{"name":"Lydia"}' JSON.parse(jsonArray) // { name: 'Lydia' } ``` @@ -3949,7 +3533,7 @@ JSON.parse(jsonArray) // { name: 'Lydia' } --- -###### 111. 무엇이 출력 될까요? +###### 111. 무엇이 출력 될까요? ```javascript let name = 'Lydia' @@ -3972,18 +3556,11 @@ getName() #### 정답: D -각 기능에는 자체 _실행 컨텍스트_ (또는 _범위_)가 있어요. `getName` 함수는 먼저 -자체 컨텍스트(범위) 내에서 접근하려고 하는 변수 `name`이 포함되어 있는지 살펴봐 -요: `let` 키워드와 함께 선언 했기 때문에 `'Sarah'`의 값을 가져요. +각 기능에는 자체 _실행 컨텍스트_ (또는 _범위_)가 있어요. `getName` 함수는 먼저 자체 컨텍스트(범위) 내에서 접근하려고 하는 변수 `name`이 포함되어 있는지 살펴봐요: `let` 키워드와 함께 선언 했기 때문에 `'Sarah'`의 값을 가져요. -`let` 키워드 (그리고 `const`)를 사용한 변수는 끌어올려지지만, `var`와 다르게 -초기화 되지는 않아요. 그들을 선언 (초기화) 하는 줄 전에 접근 할 수 없어요 -. "일시적 사각지대"라고 불려요. 그들을 선언하기 전에 접근하려고 한다면, -JavaScript는 `ReferenceError`를 던져요. +`let` 키워드 (그리고 `const`)를 사용한 변수는 끌어올려지지만, `var`와 다르게 초기화 되지는 않아요. 그들을 선언 (초기화) 하는 줄 전에 접근 할 수 없어요. "일시적 사각지대"라고 불려요. 그들을 선언하기 전에 접근하려고 한다면, JavaScript는 `ReferenceError`를 던져요. -`getName` 함수 안에 `name` 변수를 선언하지 않았다면, javaScript 엔진은 _스코프 -체인_ 을 내려다 보지 않았을 거예요. 외부 범위에 `Lydia`의 값을 가진 `name` 변수 -가 있어요. 이 경우엔 `Lydia`를 출력할거예요. +`getName` 함수 안에 `name` 변수를 선언하지 않았다면, javaScript 엔진은 _스코프 체인_ 을 내려다 보지 않았을 거예요. 외부 범위에 `Lydia`의 값을 가진 `name` 변수가 있어요. 이 경우엔 `Lydia`를 출력할거예요. ```javascript let name = 'Lydia' @@ -4004,11 +3581,11 @@ getName() // Lydia ```javascript function* generatorOne() { - yield ['a', 'b', 'c'] + yield ['a', 'b', 'c']; } function* generatorTwo() { - yield* ['a', 'b', 'c'] + yield* ['a', 'b', 'c']; } const one = generatorOne() @@ -4028,23 +3605,17 @@ console.log(two.next().value) #### 정답: C -`yield` 키워드를 사용하면, 제너레이터 함수 안의 값을 `중단` 했어요. `yield`키워 -드를 사용하면, 다른 제너레이터 함수 또는 반복 가능한 객체(예를들면 배열)의 값을 -중단 시킬 수 있어요. +`yield` 키워드를 사용하면, 제너레이터 함수 안의 값을 `중단` 했어요. `yield`키워드를 사용하면, 다른 제너레이터 함수 또는 반복 가능한 객체(예를들면 배열)의 값을 중단 시킬 수 있어요. -`generatorOne`에서, 전체 배열 `['a', 'b', 'c']`을 `yield` 키워드를 사용해서 중단 -했어요. `one` (`one.next().value`)의 `next` 메소드가 리턴 한 객체의 `value`속성 -값은 전체 배열 `['a', 'b', 'c']`과 같아요. +`generatorOne`에서, 전체 배열 `['a', 'b', 'c']`을 `yield` 키워드를 사용해서 중단 했어요. `one` (`one.next().value`)의 `next` 메소드가 리턴 한 객체의 `value`속성 값은 전체 배열 `['a', 'b', 'c']`과 같아요. ```javascript console.log(one.next().value) // ['a', 'b', 'c'] console.log(one.next().value) // undefined ``` -`generatorTwo`에서, `yield*` 키워드를 사용했어요. `two`의 첫번째 값이 중단 되었 -다는 의미이고, 반복자의 첫번째로 중단된 값과 같아요.반복자는 배열 -`['a', 'b', 'c']` 이에요. 처음으로 중단된 값은 `a`이고, 따라서 첫번째 순서에서 -`two.next().value`를 부르면 `a`를 리턴해요. +`generatorTwo`에서, `yield*` 키워드를 사용했어요. `two`의 첫번째 값이 중단 되었다는 의미이고, 반복자의 첫번째로 중단된 값과 같아요.반복자는 배열 `['a', 'b', 'c']` 이에요. +처음으로 중단된 값은 `a`이고, 따라서 첫번째 순서에서 `two.next().value`를 부르면 `a`를 리턴해요. ```javascript console.log(two.next().value) // 'a' @@ -4074,10 +3645,7 @@ console.log(`${(x => x)('I love')} to program`) #### 정답: A -템플릿 리터러를 사용한 표현식은 첫번째로 평가돼요. 문자열은 표현식의 리턴된 값을 -포함하게 된다는 것을 의미하고, 이 경우 함수 `(x => x)('I love')`는 즉시 호출 돼 -요. 화살표 함수 `x => x`의 인수 값으로 `I love`를 전달 했어요. `x`는 -`'I love'`이고 리턴 될 거에요. 이 결과는 `I love to program` 이에요. +템플릿 리터러를 사용한 표현식은 첫번째로 평가돼요. 문자열은 표현식의 리턴된 값을 포함하게 된다는 것을 의미하고, 이 경우 함수 `(x => x)('I love')`는 즉시 호출 돼요. 화살표 함수 `x => x`의 인수 값으로 `I love`를 전달 했어요. `x`는 `'I love'`이고 리턴 될 거에요. 이 결과는 `I love to program` 이에요.

@@ -4090,7 +3658,7 @@ console.log(`${(x => x)('I love')} to program`) let config = { alert: setInterval(() => { console.log('Alert!') - }, 1000), + }, 1000) } config = null @@ -4106,11 +3674,7 @@ config = null #### 정답: C -일반적으로 객체를 `null`로 설정했을때, 객체는 더 이상의 객체 참조가 없어 _쓰레기 -수집_ 되어요. 그러나, `setInterval`을 가진 콜백 함수는 화살표 함수 (`config` 객 -체로 감싸진) 이기 때문에, 콜백 함수는 여전히 `config` 객체의 참조를 갖고 있고, -객체는 쓰레기 수집 되지 않아요. 쓰레기 수집 되지 않았기 때문에, `setInterval` 콜 -백 함수는 여전히 매 1000ms (1s) 마다 호출 돼요, +일반적으로 객체를 `null`로 설정했을때, 객체는 더 이상의 객체 참조가 없어 _쓰레기 수집_ 되어요. 그러나, `setInterval`을 가진 콜백 함수는 화살표 함수 (`config` 객체로 감싸진) 이기 때문에, 콜백 함수는 여전히 `config` 객체의 참조를 갖고 있고, 객체는 쓰레기 수집 되지 않아요. 쓰레기 수집 되지 않았기 때문에, `setInterval` 콜백 함수는 여전히 매 1000ms (1s) 마다 호출 돼요,

@@ -4143,15 +3707,10 @@ myMap.get(() => 'greeting') #### 정답: B -`set` 메소드를 사용해서 키/값을 쌍으로 추가할 때, 키는 `set`함수로 전달 된 첫 번 -째 인수의 값이 되고, 값은 `set`함수로 전달된 두 번째 인수의 값이 될거에요. 이 경 -우에선 키는 _함수_ `() => 'greeting'`이고, 값은 `'Hello world'` 에요. `myMap`은 -이제 `{ () => 'greeting' => 'Hello world!' }` 예요. +`set` 메소드를 사용해서 키/값을 쌍으로 추가할 때, 키는 `set`함수로 전달 된 첫 번째 인수의 값이 되고, 값은 `set`함수로 전달된 두 번째 인수의 값이 될거에요. 이 경우에선 키는 _함수_ `() => 'greeting'`이고, 값은 `'Hello world'` 에요. `myMap`은 이제 `{ () => 'greeting' => 'Hello world!' }` 예요. -1은 틀렸어요, 키는 `'greeting'`가 아니라 `() => 'greeting'`이기 때문이에요. 3은 -틀렸어요, `get`메소드에 새로 생성한 함수를 전달 했기 때문이에요. 객체는 *참조*에 -의해 상호작용해요. 함수는 객체이고, 그들이 같다고 하더라도 두 함수가 절대로 같지 -않은 이유예요: 메모리 안 다른 장소의 참조를 가지고 있어요. +1은 틀렸어요, 키는 `'greeting'`가 아니라 `() => 'greeting'`이기 때문이에요. +3은 틀렸어요, `get`메소드에 새로 생성한 함수를 전달 했기 때문이에요. 객체는 _참조_에 의해 상호작용해요. 함수는 객체이고, 그들이 같다고 하더라도 두 함수가 절대로 같지 않은 이유예요: 메모리 안 다른 장소의 참조를 가지고 있어요.

@@ -4162,14 +3721,14 @@ myMap.get(() => 'greeting') ```javascript const person = { - name: 'Lydia', - age: 21, + name: "Lydia", + age: 21 } -const changeAge = (x = { ...person }) => (x.age += 1) +const changeAge = (x = { ...person }) => x.age += 1 const changeAgeAndName = (x = { ...person }) => { x.age += 1 - x.name = 'Sarah' + x.name = "Sarah" } changeAge(person) @@ -4188,18 +3747,11 @@ console.log(person) #### 정답: C -`changeAge`와 `changeAgeAndName`함수 둘다 기본 파라미터를 가지고 있는데 즉, _새 -롭게_ 만들어진 객체 `{ ...person }`를 가지고 있어요. 이 객체는 `person` 객체의 -모든 키/값의 복사본을 가지고 있어요. +`changeAge`와 `changeAgeAndName`함수 둘다 기본 파라미터를 가지고 있는데 즉, _새롭게_ 만들어진 객체 `{ ...person }`를 가지고 있어요. 이 객체는 `person` 객체의 모든 키/값의 복사본을 가지고 있어요. -첫번째로, `changeAge`함수를 호출 했고, 그것의 인수로 `person` 객체를 전달 했어요 -. 이 함수는 `age`속성의 값을 1 증가 시켜요. `person`은 이제 -`{ name: "Lydia", age: 22 }`이에요. +첫번째로, `changeAge`함수를 호출 했고, 그것의 인수로 `person` 객체를 전달 했어요. 이 함수는 `age`속성의 값을 1 증가 시켜요. `person`은 이제 `{ name: "Lydia", age: 22 }`이에요. -그리고나서, `changeAgeAndName` 함수를 호출 했지만, 파라미터를 전달하지 않았어요. -대신에, `x`의 값은 _새로운_ 객체와 같아요: `{ ...person }`. 새로운 객체이기 때문 -에, `person`객체의 속성들의 값에 영향을 주지 않아요. `person`은 여전히 -`{ name: "Lydia", age: 22 }`와 같아요. +그리고나서, `changeAgeAndName` 함수를 호출 했지만, 파라미터를 전달하지 않았어요. 대신에, `x`의 값은 _새로운_ 객체와 같아요: `{ ...person }`. 새로운 객체이기 때문에, `person`객체의 속성들의 값에 영향을 주지 않아요. `person`은 여전히 `{ name: "Lydia", age: 22 }`와 같아요.

From 0500cbd3b2181ce18f4030d3b1d9d018e83fba33 Mon Sep 17 00:00:00 2001 From: wisecare-justin Date: Thu, 29 Apr 2021 10:03:03 +0900 Subject: [PATCH 040/193] =?UTF-8?q?=E2=9C=8F=EF=B8=8F=20Fix=20typo=20in=20?= =?UTF-8?q?q12=20answer=20for=20ko-KR?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ko-KR/README-ko_KR.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ko-KR/README-ko_KR.md b/ko-KR/README-ko_KR.md index a5e85cab..2fa390c8 100644 --- a/ko-KR/README-ko_KR.md +++ b/ko-KR/README-ko_KR.md @@ -417,7 +417,7 @@ console.log(sarah); `sarah`에게 `new` 키워드를 사용하지 않았어요. `new`를 사용한 경우, 이것은 우리가 만든 새로운 빈 객체를 참조해요. 그러나, `new`를 추가하지 않으면 **전역변수**를 참조해요! -`this.firstName`은 `"Sarah"`이고, `this.lastName`은 `"Smith"`이리고 말했었어요. (그렇지만) 우리는 실제로 한 일은 `global.firstName = 'Sarah'` 그리고 `global.lastName = 'Smith'`를 정의하는 것이에요. `sarah` 자체는 `undefined`로 남아있어요. 따라서 `Person`함수의 값을 리턴하지 않아요. +`this.firstName`은 `"Sarah"`이고, `this.lastName`은 `"Smith"`이라고 말했었어요. (그렇지만) 우리가 실제로 한 일은 `global.firstName = 'Sarah'` 그리고 `global.lastName = 'Smith'`를 정의하는 것이에요. `sarah` 자체는 `undefined`로 남아있어요. 따라서 `Person`함수의 값을 리턴하지 않아요.

From 256c7e25a3efa5ebf66c14315768a2dbf9596e41 Mon Sep 17 00:00:00 2001 From: Anthony <62673975+anthonyrovira@users.noreply.github.com> Date: Mon, 3 May 2021 10:46:01 +0200 Subject: [PATCH 041/193] Update README_fr-FR.md misspelling: "pas" => "par" --- fr-FR/README_fr-FR.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/fr-FR/README_fr-FR.md b/fr-FR/README_fr-FR.md index cda358f1..02ed9c44 100644 --- a/fr-FR/README_fr-FR.md +++ b/fr-FR/README_fr-FR.md @@ -175,7 +175,7 @@ const mouse = { En JavaScript, toutes les clés d'objet sont des chaînes de caractères (sauf si c'est un Symbol). Bien que nous ne puissions pas les _typer_ comme des chaînes de caractères, elles sont converties en chaînes de caractères sous le capot. -JavaScript interprète (ou décompresse) les instructions. Lorsque nous utilisons la notation pas crochet, il voit le premier crochet `[` et continue jusqu'à ce qu'il trouve le crochet fermant `]`. Seulement après, il évalue l'instruction. +JavaScript interprète (ou décompresse) les instructions. Lorsque nous utilisons la notation par crochet, il voit le premier crochet `[` et continue jusqu'à ce qu'il trouve le crochet fermant `]`. Seulement après, il évalue l'instruction. `mouse[bird.size]` : Premièrement, il évalue `bird.size`, qui est `"small"`. `mouse["small"]` retourne `true`. From 7c6430b40cdf40fdae93359d4563a056af461a8d Mon Sep 17 00:00:00 2001 From: wisecare-justin Date: Thu, 6 May 2021 14:21:36 +0900 Subject: [PATCH 042/193] =?UTF-8?q?=E2=9C=8F=EF=B8=8F=20Fix=20module=20obj?= =?UTF-8?q?ect=20default?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ko-KR/README-ko_KR.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/ko-KR/README-ko_KR.md b/ko-KR/README-ko_KR.md index 2fa390c8..b1685d36 100644 --- a/ko-KR/README-ko_KR.md +++ b/ko-KR/README-ko_KR.md @@ -2802,8 +2802,8 @@ import * as data from "./module" console.log(data) ``` -- A: `{ default: function default(), name: "Lydia" }` -- B: `{ default: function default() }` +- A: `{ default: [Function (anonymous)], name: "Lydia" }` +- B: `{ default: [Function (anonymous)] }` - C: `{ default: "Hello world", name: "Lydia" }` - D: Global object of `module.js` From 5aa45a78fa201e9400b421dfcff108eb2f971667 Mon Sep 17 00:00:00 2001 From: Swordword Date: Fri, 7 May 2021 17:46:56 +0800 Subject: [PATCH 043/193] Update README-zh_CN.md Typo --- zh-CN/README-zh_CN.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/zh-CN/README-zh_CN.md b/zh-CN/README-zh_CN.md index 29671ca5..14b606ed 100644 --- a/zh-CN/README-zh_CN.md +++ b/zh-CN/README-zh_CN.md @@ -3561,7 +3561,7 @@ getName() 带有`let`关键字(和`const`)的变量被提升,但是与`var`不同,它不会被***初始化***。 在我们声明(初始化)它们之前,无法访问它们。 这称为“暂时性死区”。 当我们尝试在声明变量之前访问变量时,JavaScript会抛出`ReferenceError: Cannot access 'name' before initialization`。 -如果我们不在`getName`函数中声明`name`变量,则javascript引擎会查看原型练。会找到其外部作用域有一个名为`name`的变量,其值为`Lydia`。 在这种情况下,它将打印`Lydia`: +如果我们不在`getName`函数中声明`name`变量,则javascript引擎会查看原型链。会找到其外部作用域有一个名为`name`的变量,其值为`Lydia`。 在这种情况下,它将打印`Lydia`: ```javascript let name = 'Lydia' From 8ca18e6c48ef255d0c35013a2f0c77663e5535e8 Mon Sep 17 00:00:00 2001 From: Vitali Zaidman Date: Fri, 7 May 2021 15:27:50 +0300 Subject: [PATCH 044/193] Improved 133 example and explanation there was a false assumption that `Promise.resolve(Promise.resolve('Promise!'))` resolves a Promise that needs to be resolved again while it just resolves with `Promise!` --- README.md | 36 ++++++++++++++++++++---------------- 1 file changed, 20 insertions(+), 16 deletions(-) diff --git a/README.md b/README.md index 18c3ccdc..3426228b 100644 --- a/README.md +++ b/README.md @@ -4277,44 +4277,48 @@ We invoke the `counterTwo.increment()`, which sets the `count` to `3`. Then, we ###### 133. What's the output? ```javascript -const myPromise = Promise.resolve(Promise.resolve('Promise!')); +const myPromise = Promise.resolve(Promise.resolve('Promise')); function funcOne() { - myPromise.then(res => res).then(res => console.log(res)); - setTimeout(() => console.log('Timeout!'), 0); - console.log('Last line!'); + setTimeout(() => console.log('Timeout 1!'), 0); + myPromise.then(res => res).then(res => console.log(`${res} 1!`)); + console.log('Last line 1!'); } async function funcTwo() { const res = await myPromise; - console.log(await res); - setTimeout(() => console.log('Timeout!'), 0); - console.log('Last line!'); + console.log(`${res} 2!`) + setTimeout(() => console.log('Timeout 2!'), 0); + console.log('Last line 2!'); } funcOne(); funcTwo(); ``` -- A: `Promise! Last line! Promise! Last line! Last line! Promise!` -- B: `Last line! Timeout! Promise! Last line! Timeout! Promise!` -- C: `Promise! Last line! Last line! Promise! Timeout! Timeout!` -- D: `Last line! Promise! Promise! Last line! Timeout! Timeout!` +- A: `Promise 1! Last line 1! Promise 2! Last line 2! Timeout 1! Timeout 2!` +- B: `Last line 1! Timeout 1! Promise 1! Last line 2! Promise2! Timeout 2! ` +- C: `Last line 1! Promise 2! Last line 2! Promise 1! Timeout 1! Timeout 2!` +- D: `Timeout 1! Promise 1! Last line 1! Promise 2! Timeout 2! Last line 2!`
Answer

#### Answer: D -First, we invoke `funcOne`. On the first line of `funcOne`, we call the `myPromise` promise, which is an _asynchronous_ operation. While the engine is busy completing the promise, it keeps on running the function `funcOne`. The next line is the _asynchronous_ `setTimeout` function, from which the callback is sent to the Web API. (see my article on the event loop here.) +First, we invoke `funcOne`. On the first line of `funcOne`, we call the _asynchronous_ `setTimeout` function, from which the callback is sent to the Web API. (see my article on the event loop here.) -Both the promise and the timeout are asynchronous operations, the function keeps on running while it's busy completing the promise and handling the `setTimeout` callback. This means that `Last line!` gets logged first, since this is not an asynchonous operation. This is the last line of `funcOne`, the promise resolved, and `Promise!` gets logged. However, since we're invoking `funcTwo()`, the call stack isn't empty, and the callback of the `setTimeout` function cannot get added to the callstack yet. +Then we call the `myPromise` promise, which is an _asynchronous_ operation. -In `funcTwo` we're, first _awaiting_ the myPromise promise. With the `await` keyword, we pause the execution of the function until the promise has resolved (or rejected). Then, we log the awaited value of `res` (since the promise itself returns a promise). This logs `Promise!`. +Both the promise and the timeout are asynchronous operations, the function keeps on running while it's busy completing the promise and handling the `setTimeout` callback. This means that `Last line 1!` gets logged first, since this is not an asynchonous operation. -The next line is the _asynchronous_ `setTimeout` function, from which the callback is sent to the Web API. +Since the callstack is not empty yet, the `setTimeout` function and promise in `funcOne` cannot get added to the callstack yet. -We get to the last line of `funcTwo`, which logs `Last line!` to the console. Now, since `funcTwo` popped off the call stack, the call stack is empty. The callbacks waiting in the queue (`() => console.log("Timeout!")` from `funcOne`, and `() => console.log("Timeout!")` from `funcTwo`) get added to the call stack one by one. The first callback logs `Timeout!`, and gets popped off the stack. Then, the second callback logs `Timeout!`, and gets popped off the stack. This logs `Last line! Promise! Promise! Last line! Timeout! Timeout!` +In `funcTwo`, the variable `res` gets `Promise` because `Promise.resolve(Promise.resolve('Promise'))` is equivalent to `Promise.resolve('Promise')` since resolving a promise just resolves it's value. The `await` in this line stops the execution of the function until it receives the resolution of the promise and then keeps on running synchronously until completion, so `Promise 2!` and then `Last line 2!` are logged and the `setTimeout` is sent to the Web API. + +Then the call stack is empty. Promises are _microtasks_ so they are resolved first when the call stack is empty so `Promise 1!` gets to be logged. + +Now, since `funcTwo` popped off the call stack, the call stack is empty. The callbacks waiting in the queue (`() => console.log("Timeout 1!")` from `funcOne`, and `() => console.log("Timeout 2!")` from `funcTwo`) get added to the call stack one by one. The first callback logs `Timeout 1!`, and gets popped off the stack. Then, the second callback logs `Timeout 2!`, and gets popped off the stack.

From 4a2aa8ff1e086621e735f3d63f71458b0542338b Mon Sep 17 00:00:00 2001 From: Vitali Zaidman Date: Fri, 7 May 2021 15:28:39 +0300 Subject: [PATCH 045/193] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 3426228b..e12b7bbe 100644 --- a/README.md +++ b/README.md @@ -4304,7 +4304,7 @@ funcTwo();
Answer

-#### Answer: D +#### Answer: C First, we invoke `funcOne`. On the first line of `funcOne`, we call the _asynchronous_ `setTimeout` function, from which the callback is sent to the Web API. (see my article on the event loop here.) From 1bfc7fa2ca39ce6759164c050fc687d24188f9c5 Mon Sep 17 00:00:00 2001 From: Swordword Date: Sat, 8 May 2021 17:35:08 +0800 Subject: [PATCH 046/193] Update README-zh_CN.md Typo --- zh-CN/README-zh_CN.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/zh-CN/README-zh_CN.md b/zh-CN/README-zh_CN.md index 14b606ed..f178684e 100644 --- a/zh-CN/README-zh_CN.md +++ b/zh-CN/README-zh_CN.md @@ -4388,7 +4388,7 @@ person.name; #### 答案: C -使用 Proxy 对象,我们可以给一个对象添加自定义行为。在这个 case,我们传递一个包含以下属性的对象 `handler` : `set` and `get`。每当我门 _设置_ 属性值时 `set` 被调用,每当我们 _获取_ 时 `get` 被调用。 +使用 Proxy 对象,我们可以给一个对象添加自定义行为。在这个 case,我们传递一个包含以下属性的对象 `handler` : `set` and `get`。每当我们 _设置_ 属性值时 `set` 被调用,每当我们 _获取_ 时 `get` 被调用。 第一个参数是一个空对象 `{}`,作为 `person` 的值。对于这个对象,自定义行为被定义在对象 `handler`。如果我们向对象 `person` 添加属性,`set` 将被调用。如果我们获取 `person` 的属性, `get` 将被调用。 From 4224333da7cadd395006ee623ed6ba20fddc1686 Mon Sep 17 00:00:00 2001 From: miguelmanalo Date: Mon, 10 May 2021 08:32:40 -0400 Subject: [PATCH 047/193] fixed small typo in Q 135 --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 18c3ccdc..f0921a95 100644 --- a/README.md +++ b/README.md @@ -4403,7 +4403,7 @@ person.name; #### Answer: C -With a Proxy object, we can add custom behavior to an object that we pass to it as the second argument. In this case, we pass the `handler` object which contained to properties: `set` and `get`. `set` gets invoked whenever we _set_ property values, `get` gets invoked whenever we _get_ (access) property values. +With a Proxy object, we can add custom behavior to an object that we pass to it as the second argument. In this case, we pass the `handler` object which contained two properties: `set` and `get`. `set` gets invoked whenever we _set_ property values, `get` gets invoked whenever we _get_ (access) property values. The first argument is an empty object `{}`, which is the value of `person`. To this object, the custom behavior specified in the `handler` object gets added. If we add a property to the `person` object, `set` will get invoked. If we access a property on the `person` object, `get` gets invoked. From fabdf44b881f01bfb83fc4a7ae135abfb5e37fa1 Mon Sep 17 00:00:00 2001 From: Raj Kapadia Date: Sat, 5 Jun 2021 23:54:59 +0530 Subject: [PATCH 048/193] Update #8. Freddie is not a child of Chameleon Freddie is an instance of Chameleon and not a child. --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index f0921a95..9cf5a5a3 100644 --- a/README.md +++ b/README.md @@ -299,7 +299,7 @@ console.log(freddie.colorChange('orange')); #### Answer: D -The `colorChange` function is static. Static methods are designed to live only on the constructor in which they are created, and cannot be passed down to any children. Since `freddie` is a child, the function is not passed down, and not available on the `freddie` instance: a `TypeError` is thrown. +The `colorChange` function is static. Static methods are designed to live only on the constructor in which they are created, and cannot be called on class objects. Since `freddie` is an object of class Chameleon, the function cannot be called upon it, and not available on the `freddie` instance: a `TypeError` is thrown.

From 7b5b03b70726457c10261e47c21fef16a76386ae Mon Sep 17 00:00:00 2001 From: Raj Kapadia Date: Sat, 5 Jun 2021 23:59:53 +0530 Subject: [PATCH 049/193] Update Q 8. Freddie is not a child of Chameleon Freddie is an instance of Chameleon and not a child. --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 9cf5a5a3..4ee4c8c1 100644 --- a/README.md +++ b/README.md @@ -299,7 +299,7 @@ console.log(freddie.colorChange('orange')); #### Answer: D -The `colorChange` function is static. Static methods are designed to live only on the constructor in which they are created, and cannot be called on class objects. Since `freddie` is an object of class Chameleon, the function cannot be called upon it, and not available on the `freddie` instance: a `TypeError` is thrown. +The `colorChange` function is static. Static methods are designed to live only on the constructor in which they are created, and cannot be passed down to any children or called upon class instances. Since `freddie` is an instance of class Chameleon, the function cannot be called upon it. A `TypeError` is thrown.

From 84e73412458fa1a08fd2e7fb34eab6b79f62bcfe Mon Sep 17 00:00:00 2001 From: Loan Alouache <30394488+Ninjeneer@users.noreply.github.com> Date: Thu, 17 Jun 2021 11:30:56 +0200 Subject: [PATCH 050/193] Fix EN => FR translation --- fr-FR/README_fr-FR.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/fr-FR/README_fr-FR.md b/fr-FR/README_fr-FR.md index 02ed9c44..3260e671 100644 --- a/fr-FR/README_fr-FR.md +++ b/fr-FR/README_fr-FR.md @@ -1069,7 +1069,7 @@ undefined; - A: `0`, `''`, `undefined` - B: `0`, `new Number(0)`, `''`, `new Boolean(false)`, `undefined` - C: `0`, `''`, `new Boolean(false)`, `undefined` -- D: All of them are falsy +- D: Toutes sont fausses
Réponse

From 31f90d71858a2ecf4f01b2f70f35d8255217a93f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=AF=AB=E8=A9=A9=E7=BE=8A?= Date: Fri, 2 Jul 2021 02:36:06 +0800 Subject: [PATCH 051/193] Translation zh-TW answer 76 --- zh-TW/README_zh-TW.md | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) diff --git a/zh-TW/README_zh-TW.md b/zh-TW/README_zh-TW.md index e24f0a88..1be6820d 100644 --- a/zh-TW/README_zh-TW.md +++ b/zh-TW/README_zh-TW.md @@ -2378,4 +2378,33 @@ console.log(shape);

+--- + +###### 76. 將會輸出什麽內容? + +```javascript +const { name: myName } = { name: "Lydia" }; + +console.log(name); +``` + +- A: `"Lydia"` +- B: `"myName"` +- C: `undefined` +- D: `ReferenceError` + +
答案 +

+ +#### 答案: D + +當我們從右側的物件解構屬性`name`時,我們將其值`Lydia`分配給名為`myName`的變數。 + +使用`{name:myName}`,我們是在告訴JavaScript我們要建立一個名為`myName`的新變數,並且其值是右側物件的`name`屬性的值。 + +當我們嘗試輸出`name`,一個未定義的變數時,就會引發`ReferenceError`。 + +

+
+ --- \ No newline at end of file From 47cd19a8b72246bc4294c76fb7ef1476acbc9878 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=AF=AB=E8=A9=A9=E7=BE=8A?= Date: Fri, 2 Jul 2021 02:43:53 +0800 Subject: [PATCH 052/193] Translation zh-TW answer 77 --- zh-TW/README_zh-TW.md | 84 ++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 83 insertions(+), 1 deletion(-) diff --git a/zh-TW/README_zh-TW.md b/zh-TW/README_zh-TW.md index 1be6820d..e795ace0 100644 --- a/zh-TW/README_zh-TW.md +++ b/zh-TW/README_zh-TW.md @@ -1434,7 +1434,7 @@ for (const item in person) { #### 答案: B -通過 `for-in` 循環,我們可以遍歷對象的鍵,在這個題目中的鍵是 `name` 和 `age`。 在內部,對象鍵是字串(strings)(如果它們不是 Symbol)。 +通過 `for-in` 循環,我們可以遍歷物件的鍵,在這個題目中的鍵是 `name` 和 `age`。 在內部,物件鍵是字串(strings)(如果它們不是 Symbol)。 在每次循環中,我們將 `item` 的值設置為等於其迭代的當前鍵。 第一輪循環中,`item` 等於 `name`,並輸出內容。 接著, `item` 等於 `age`,並輸出內容。

@@ -2407,4 +2407,86 @@ console.log(name);

+--- + +###### 77. 以下是純函數嗎? + +```javascript +function sum(a, b) { + return a + b; +} +``` + +- A: Yes +- B: No + +
答案 +

+ +#### 答案: B + +純函數一種若輸入參數相同,則永遠會得到相同輸出的函數。 + +在特定情況下,即使輸入相同參數,也不能得到相同的返回值: + +

+var a = b = {}
+a[Symbol.toPrimitive] = b[Symbol.toPrimitive] = () => Math.random()
+sum(a, b) // Uncertain
+
+ +所以它不是純函數。 + +

+
+ +--- + +###### 78. 將會輸出什麽內容? + +```javascript +const add = () => { + const cache = {}; + return num => { + if (num in cache) { + return `From cache! ${cache[num]}`; + } else { + const result = num + 10; + cache[num] = result; + return `Calculated! ${result}`; + } + }; +}; + +const addFunction = add(); +console.log(addFunction(10)); +console.log(addFunction(10)); +console.log(addFunction(5 * 2)); +``` + +- A: `Calculated! 20` `Calculated! 20` `Calculated! 20` +- B: `Calculated! 20` `From cache! 20` `Calculated! 20` +- C: `Calculated! 20` `From cache! 20` `From cache! 20` +- D: `Calculated! 20` `From cache! 20` `Error` + +
答案 +

+ +#### 答案: C + +`add`函數是一個記憶函數。通過記憶化,我們可以暫存函數的結果,以加快其執行速度。上述情況,我們建立一個`cache`物件,用於存儲先前存過的值。 + +如果我們使用相同的參數多次呼叫`addFunction`函數,它首先檢查暫存中是否已有該值,如果有,則回傳暫存值,節省執行時間。如果沒有,那麼它將計算該值,並存儲在暫存中。 + +我們用相同的值三次呼叫了`addFunction`函數: + +在第一次呼叫,`num`等於`10`時函數的值尚未暫存,if語句`num in cache`回傳`false`,else塊的代碼被執行:`Calculated! 20`,並且其結果被添加到暫存物件,`cache`現在看起來像`{10:20}`。 + +第二次,`cache`物件包含`10`的回傳值。 if語句 `num in cache` 回傳`true`,印出`From cache! 20`。 + +第三次,我們將`5 * 2`(值為10)傳遞給函數。 `cache`物件包含`10`的回傳值。 if語句 `num in cache` 回傳`true`,印出`From cache! 20`。 + +

+
+ --- \ No newline at end of file From c47809aa17e2f785a18f23d5b047cc5efc6ac3db Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=AF=AB=E8=A9=A9=E7=BE=8A?= Date: Fri, 2 Jul 2021 02:47:33 +0800 Subject: [PATCH 053/193] Translation zh-TW answer 79 --- zh-TW/README_zh-TW.md | 38 +++++++++++++++++++++++++++++++++++++- 1 file changed, 37 insertions(+), 1 deletion(-) diff --git a/zh-TW/README_zh-TW.md b/zh-TW/README_zh-TW.md index e795ace0..227e63a2 100644 --- a/zh-TW/README_zh-TW.md +++ b/zh-TW/README_zh-TW.md @@ -2489,4 +2489,40 @@ console.log(addFunction(5 * 2));

---- \ No newline at end of file +--- +###### 79. 输出什么? + +```javascript +const myLifeSummedUp = ["☕", "💻", "🍷", "🍫"] + +for (let item in myLifeSummedUp) { + console.log(item) +} + +for (let item of myLifeSummedUp) { + console.log(item) +} +``` + +- A: `0` `1` `2` `3` and `"☕"` ` "💻"` `"🍷"` `"🍫"` +- B: `"☕"` ` "💻"` `"🍷"` `"🍫"` and `"☕"` ` "💻"` `"🍷"` `"🍫"` +- C: `"☕"` ` "💻"` `"🍷"` `"🍫"` and `0` `1` `2` `3` +- D: `0` `1` `2` `3` and `{0: "☕", 1: "💻", 2: "🍷", 3: "🍫"}` + +
答案 +

+ +#### 答案: A + +透過`for-in`迴圈,我們可以遍歷一個物件**自有的**、**繼承的**、**可列舉的**、**非Symbol的**屬性。在陣列中,可列舉屬性是陣列元素的“鍵”, 即它們的索引。類似於下面這個物件: + +`{0: "☕", 1: "💻", 2: "🍷", 3: "🍫"}` + +其中鍵則是可列舉屬性,因此 `0`,`1`,`2`,`3`被記錄。 + +透過`for-of`迴圈,我們可以迭代**可迭代物件**(包括 `Array`,`Map`,`Set`,`String`,`arguments`等)。當我們迭代陣列時,在每次迭代中,不同屬性的值將被分配給變數`item`, 因此輸出`“☕”`,`“💻”`,`“🍷”`,`“🍫”`。 + +

+
+ +--- From 0aa2e63809c67bcaf88a4b1707d4a46d5aa6739c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=AF=AB=E8=A9=A9=E7=BE=8A?= Date: Fri, 2 Jul 2021 18:30:10 +0800 Subject: [PATCH 054/193] Translation zh-TW answer 80 --- zh-TW/README_zh-TW.md | 28 +++++++++++++++++++++++++++- 1 file changed, 27 insertions(+), 1 deletion(-) diff --git a/zh-TW/README_zh-TW.md b/zh-TW/README_zh-TW.md index 227e63a2..24b11f18 100644 --- a/zh-TW/README_zh-TW.md +++ b/zh-TW/README_zh-TW.md @@ -2490,7 +2490,7 @@ console.log(addFunction(5 * 2)); --- -###### 79. 输出什么? +###### 79. 將會輸出什麽內容? ```javascript const myLifeSummedUp = ["☕", "💻", "🍷", "🍫"] @@ -2526,3 +2526,29 @@ for (let item of myLifeSummedUp) { --- + +###### 80. 將會輸出什麽內容? + +```javascript +const list = [1 + 2, 1 * 2, 1 / 2] +console.log(list) +``` + +- A: `["1 + 2", "1 * 2", "1 / 2"]` +- B: `["12", 2, 0.5]` +- C: `[3, 2, 0.5]` +- D: `[1, 1, 1]` + +
答案 +

+ +#### 答案: C + +陣列元素可以包含任何值。數字,字符,布爾,物件,陣列,`null`,`undeifned`, 以及其他表達式,如日期,函數和計算式。 + +元素將等於回傳的值。 `1 + 2`回傳`3`,`1 * 2`回傳'2`,'1 / 2`回傳`0.5`。 + +

+
+ +--- \ No newline at end of file From fd8b3844d89211a422cf4a72184e8f22bc4cd908 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=AF=AB=E8=A9=A9=E7=BE=8A?= Date: Fri, 2 Jul 2021 18:32:46 +0800 Subject: [PATCH 055/193] Translation zh-TW answer 81 --- zh-TW/README_zh-TW.md | 32 ++++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) diff --git a/zh-TW/README_zh-TW.md b/zh-TW/README_zh-TW.md index 24b11f18..ffefac38 100644 --- a/zh-TW/README_zh-TW.md +++ b/zh-TW/README_zh-TW.md @@ -2551,4 +2551,36 @@ console.log(list)

+--- +###### 81. 將會輸出什麽內容? + +```javascript +function sayHi(name) { + return `Hi there, ${name}` +} + +console.log(sayHi()) +``` + +- A: `Hi there, ` +- B: `Hi there, undefined` +- C: `Hi there, null` +- D: `ReferenceError` + +
答案 +

+ +#### 答案: B + +預設情況下,如果不傳參數給函數,函數內參數的值將為`undefined`。上述情況,我們沒有給參數`name`傳值。 `name`等於`undefined`,並被印出。 + +在ES6中,我們可以使用預設參數覆蓋此預設的`undefined`值。例如: + +`function sayHi(name =“Lydia”){...}` + +在這種情況下,如果我們沒有傳遞值或者如果我們傳遞`undefined`,`name`總是等於字符`Lydia` + +

+
+ --- \ No newline at end of file From f05bda6d832da535895c1c4928da1a096613627a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=AF=AB=E8=A9=A9=E7=BE=8A?= Date: Fri, 2 Jul 2021 18:34:43 +0800 Subject: [PATCH 056/193] Translation zh-TW answer 82 --- zh-TW/README_zh-TW.md | 47 ++++++++++++++++++++++++++++++++++++++----- 1 file changed, 42 insertions(+), 5 deletions(-) diff --git a/zh-TW/README_zh-TW.md b/zh-TW/README_zh-TW.md index ffefac38..4833d2df 100644 --- a/zh-TW/README_zh-TW.md +++ b/zh-TW/README_zh-TW.md @@ -1324,13 +1324,13 @@ console.log(gen.next().value); #### 答案: C -一般函式不能在被調用後中途停止。但是, generator 可以在中途 "停止" 且之後可以從停止的位置繼續運行。 +一般函式不能在被呼叫後中途停止。但是, generator 可以在中途 "停止" 且之後可以從停止的位置繼續運行。 每當一個 generator 函式遇到一個 `yield` 關鍵字時,該函式就會產生其後指定的值。 請注意,在這種情況下,generator 函式不是 _return_ 值,而是 _yields_ 值。 -首先,我們使用等於 "10" 的 "i" 初始化 generator 函式。 我們使用 "next()" 方法調用 generator 函式。 第一次調用 generator 函式時, "i" 等於 "10"。 +首先,我們使用等於 "10" 的 "i" 初始化 generator 函式。 我們使用 "next()" 方法呼叫 generator 函式。 第一次呼叫 generator 函式時, "i" 等於 "10"。 它遇到第一個 `yield` 關鍵字:它產生 `i` 的值。 現在,generator 已 "暫停", 並且記錄了 "10"。 -然後,我們使用 `next()` 方法再次調用該函式。 它將從先前停止的地方繼續,仍然是 "i" 等於 "10"。 現在,它遇到下一個 `yield` 關鍵字,並產生 `i * 2` 。 +然後,我們使用 `next()` 方法再次呼叫該函式。 它將從先前停止的地方繼續,仍然是 "i" 等於 "10"。 現在,它遇到下一個 `yield` 關鍵字,並產生 `i * 2` 。 "i" 等於 "10",因此返回 "10 * 2",即 "20"。 故結果為10、20。

@@ -1709,7 +1709,7 @@ pet.bark(); 透過 `delete` 關鍵字,我們可以從物件中刪除它的屬性。同樣適用在原型(prototype)。通過刪除原型上的屬性,該屬性在原型鏈中將不可再被使用。 在這個案例中, `bark` 函式在 `delete Dog.prototype.bark` 之後的原型上不再可用,但是我們仍然嘗試訪問它。 -因此當我們嘗試調用不是函式的東西時,程式將拋出 `TypeError`。 在這個案例中,將為 `TypeError: pet.bark is not a function` ,因為 `pet.bark` 是 `undefined`。 +因此當我們嘗試呼叫不是函式的東西時,程式將拋出 `TypeError`。 在這個案例中,將為 `TypeError: pet.bark is not a function` ,因為 `pet.bark` 是 `undefined`。

@@ -2006,7 +2006,7 @@ multiply(value); 在ES6中,我們可以使用預設值初始化參數。如果沒有其他值傳遞給該函式或是傳入的參數是 `undefined`,則該參數的值為預設值。此案例中,我們將 `value` 物件的屬性擴展到一個新物件中,因此 `x` 具有預設值 `{number:10}`。 -預設值是在 _呼叫_ 時被 evaluated。每次調用該函式時,都會創建一個 _新_ 物件。我們在沒有傳遞值的情況下呼叫了 `multiply` 函式兩次:`x` 的預設值是 `{{number:10}`。因此,我們輸出該數字的相乘值,即 `20`。 +預設值是在 _呼叫_ 時被 evaluated。每次呼叫該函式時,都會創建一個 _新_ 物件。我們在沒有傳遞值的情況下呼叫了 `multiply` 函式兩次:`x` 的預設值是 `{{number:10}`。因此,我們輸出該數字的相乘值,即 `20`。 第三次呼叫時,我們確實傳遞了一個參數:名為 `value` 的物件。 `*=` 運算子實際上是 `x.number = x.number * 2` 的簡寫:因此我們修改了 `x.number` 的值,並記錄相乘後的值 `20`。 @@ -2583,4 +2583,41 @@ console.log(sayHi())

+--- +###### 82. 將會輸出什麽內容? + +```javascript +var status = "😎" + +setTimeout(() => { + const status = "😍" + + const data = { + status: "🥑", + getStatus() { + return this.status + } + } + + console.log(data.getStatus()) + console.log(data.getStatus.call(this)) +}, 0) +``` + +- A: `"🥑"` and `"😍"` +- B: `"🥑"` and `"😎"` +- C: `"😍"` and `"😎"` +- D: `"😎"` and `"😎"` + +
答案 +

+ +#### 答案: B + +`this`關鍵字的指向取決於使用它的位置。在**函數**中,比如`getStatus`,`this`指向的是呼叫它的物件,上述例子中`data`物件呼叫了`getStatus`,因此`this`指向的就是`data`物件。當我們輸出`this.status`時,`data`物件的`status`屬性被輸出,即`"🥑"`。 + +使用`call`方法,可以更改`this`指向的物件。 `data.getStatus.call(this)`是將`this`的指向由`data`物件更改為全局物件。在全局對像上,有一個名為`status`的變數,其值為`”😎“`。因此輸出`this.status`時,會輸出`“😎”`。 +

+
+ --- \ No newline at end of file From e877adea3072c3c77620e57c423ac26739e95c8d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=AF=AB=E8=A9=A9=E7=BE=8A?= Date: Fri, 2 Jul 2021 18:36:23 +0800 Subject: [PATCH 057/193] Translation zh-TW answer 83 --- zh-TW/README_zh-TW.md | 40 ++++++++++++++++++++++++++++++++++++++-- 1 file changed, 38 insertions(+), 2 deletions(-) diff --git a/zh-TW/README_zh-TW.md b/zh-TW/README_zh-TW.md index 4833d2df..96d31311 100644 --- a/zh-TW/README_zh-TW.md +++ b/zh-TW/README_zh-TW.md @@ -1160,7 +1160,7 @@ console.log(numbers); 程式中的 `catch` 區塊捕獲了一個例外情況且賦殖予 argument `x`。這個 `x` 是在區塊內產生的,其有效範圍只在區塊內(block-scoped),它跟 `console.log` 中所傳入的 `x` 並不是同一個。 -接著我們將此區塊變數 `x` 設置為等於 `1`,並設置變量 `y` 的值, 現在我們 console.log 區塊變數 `x`,無意外地它輸出 `1`。 +接著我們將此區塊變數 `x` 設置為等於 `1`,並設置變數 `y` 的值, 現在我們 console.log 區塊變數 `x`,無意外地它輸出 `1`。 而在 `catch` 區塊之外的 `x` 仍然是 `undefined` 且 `y` 是 `2`。 因此當我們想在 `catch` 區塊之外使用 `console.log(x)` 時,它返回 `undefined`,而 `y` 返回 `2`。 @@ -2616,7 +2616,43 @@ setTimeout(() => { `this`關鍵字的指向取決於使用它的位置。在**函數**中,比如`getStatus`,`this`指向的是呼叫它的物件,上述例子中`data`物件呼叫了`getStatus`,因此`this`指向的就是`data`物件。當我們輸出`this.status`時,`data`物件的`status`屬性被輸出,即`"🥑"`。 -使用`call`方法,可以更改`this`指向的物件。 `data.getStatus.call(this)`是將`this`的指向由`data`物件更改為全局物件。在全局對像上,有一個名為`status`的變數,其值為`”😎“`。因此輸出`this.status`時,會輸出`“😎”`。 +使用`call`方法,可以更改`this`指向的物件。 `data.getStatus.call(this)`是將`this`的指向由`data`物件更改為全局物件。在全局物件上,有一個名為`status`的變數,其值為`”😎“`。因此輸出`this.status`時,會輸出`“😎”`。 +

+ + +--- +###### 83. 將會輸出什麽內容? + +```javascript +const person = { + name: "Lydia", + age: 21 +} + +let city = person.city +city = "Amsterdam" + +console.log(person) +``` + +- A: `{ name: "Lydia", age: 21 }` +- B: `{ name: "Lydia", age: 21, city: "Amsterdam" }` +- C: `{ name: "Lydia", age: 21, city: undefined }` +- D: `"Amsterdam"` + +
答案 +

+ +#### 答案: A + +我們將變數`city`設置為等於`person`物件上名為`city`的屬性的值。這個物件上沒有名為`city`的屬性,因此變數`city`的值為`undefined`。 + +請注意,我們沒有引用`person`物件本身,只是將變數`city`設置為等於`person`物件上`city`屬性的當前值。 + +然後,我們將`city`設置為等於字符串`“Amsterdam”`。這不會更改person物件:沒有對該物件的引用。 + +因此輸出`person`物件時,會返回未修改的物件。 +

From 45f0efbe12a24f9dd87aeeec560d8cd82ec5880d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=AF=AB=E8=A9=A9=E7=BE=8A?= Date: Fri, 2 Jul 2021 18:38:46 +0800 Subject: [PATCH 058/193] Translation zh-TW answer 84 --- zh-TW/README_zh-TW.md | 32 ++++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) diff --git a/zh-TW/README_zh-TW.md b/zh-TW/README_zh-TW.md index 96d31311..67aa1450 100644 --- a/zh-TW/README_zh-TW.md +++ b/zh-TW/README_zh-TW.md @@ -2656,4 +2656,36 @@ console.log(person)

+--- +###### 84. 將會輸出什麽內容? + +```javascript +function checkAge(age) { + if (age < 18) { + const message = "Sorry, you're too young." + } else { + const message = "Yay! You're old enough!" + } + + return message +} + +console.log(checkAge(21)) +``` + +- A: `"Sorry, you're too young."` +- B: `"Yay! You're old enough!"` +- C: `ReferenceError` +- D: `undefined` + +
答案 +

+ +#### 答案: C + +`const`和`let`定義的變數是具有**區塊作用域**的,區塊是大括號(`{}`)之間的任何東西, 即上述情況`if / else`語句的大括號。由於區塊作用域,我們無法在定義的塊之外引用變數,因此拋出`ReferenceError`。 + +

+
+ --- \ No newline at end of file From e2235c0597d1586229217e499d1aa77deed146b4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=AF=AB=E8=A9=A9=E7=BE=8A?= Date: Fri, 2 Jul 2021 18:42:08 +0800 Subject: [PATCH 059/193] Translation zh-TW answer 85 --- zh-TW/README_zh-TW.md | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/zh-TW/README_zh-TW.md b/zh-TW/README_zh-TW.md index 67aa1450..d5d90713 100644 --- a/zh-TW/README_zh-TW.md +++ b/zh-TW/README_zh-TW.md @@ -2688,4 +2688,28 @@ console.log(checkAge(21))

+--- +###### 85. 將會輸出什麽內容? + +```javascript +fetch('https://www.website.com/api/user/1') + .then(res => res.json()) + .then(res => console.log(res)) +``` + +- A: `fetch`函數的結果 +- B: 第二次呼叫`fetch`函數的結果 +- C: 前一個`.then()`中回傳函數返回的結果 +- D: 總是`undefined` + +
答案 +

+ +#### 答案: C + +第二個`.then`中`res`的值等於前一個`.then`中函數返回的值。你可以像這樣繼續連接`.then`,將值傳遞給下一個處理程序。 + +

+
+ --- \ No newline at end of file From e8290d9d5716886662215a50d30668e00f94ec06 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=AF=AB=E8=A9=A9=E7=BE=8A?= Date: Fri, 2 Jul 2021 18:45:07 +0800 Subject: [PATCH 060/193] Translation zh-TW answer 86 --- zh-TW/README_zh-TW.md | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) diff --git a/zh-TW/README_zh-TW.md b/zh-TW/README_zh-TW.md index d5d90713..5880dc8b 100644 --- a/zh-TW/README_zh-TW.md +++ b/zh-TW/README_zh-TW.md @@ -2712,4 +2712,33 @@ fetch('https://www.website.com/api/user/1')

+--- +###### 86. 哪個選項是將`hasName`設為`true`的方法,前提是不能將`true`作為參數傳遞? + +```javascript +function getName(name) { + const hasName = // +} +``` + +- A: `!!name` +- B: `name` +- C: `new Boolean(name)` +- D: `name.length` + +
答案 +

+ +#### 答案: A + +使用邏輯非運算符`!`,將返回一個布林值,使用`!! name`,我們可以確定`name`的值是`true`還是`false`。如果`name`是`true`,那麼`!name`返回`false`。 `!false`返回`true`。 + +通過將`hasName`設置為`name`,可以將`hasName`設置為等於傳遞給`getName`函數的值,而不是布林值`true`。 + +`new Boolean(true)`返回一個物件包裝器,而不是布林值本身。 + +`name.length`返回傳遞的參數的長度,而不是布林值`true`。 + +

+
--- \ No newline at end of file From 3e7ac7090b58875bff5212f8c021a8152c2611d1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=AF=AB=E8=A9=A9=E7=BE=8A?= Date: Fri, 2 Jul 2021 18:47:04 +0800 Subject: [PATCH 061/193] Translation zh-TW answer 87 --- zh-TW/README_zh-TW.md | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/zh-TW/README_zh-TW.md b/zh-TW/README_zh-TW.md index 5880dc8b..e7d67175 100644 --- a/zh-TW/README_zh-TW.md +++ b/zh-TW/README_zh-TW.md @@ -2741,4 +2741,29 @@ function getName(name) {

+--- + +###### 87. 將會輸出什麽內容? + +```javascript +console.log("I want pizza"[0]) +``` + +- A: `"""` +- B: `"I"` +- C: `SyntaxError` +- D: `undefined` + +
答案 +

+ +#### 答案: B + +可以使用雙括號表示法獲取字串中特定索引的字串,字串中的第一個字串具有索引0,依此類推。在這種情況下,我們想要得到索引為0的元素,字串`'I'`被記錄。 + +請注意,IE7及更低版本不支援此方法。應該使用`.charAt()` + +

+
+ --- \ No newline at end of file From 253632bbdf92b7f877818beb4631ec0df8ecb99c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=AF=AB=E8=A9=A9=E7=BE=8A?= Date: Fri, 2 Jul 2021 18:48:42 +0800 Subject: [PATCH 062/193] Translation zh-TW answer 88 --- zh-TW/README_zh-TW.md | 36 ++++++++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) diff --git a/zh-TW/README_zh-TW.md b/zh-TW/README_zh-TW.md index e7d67175..5ff3509e 100644 --- a/zh-TW/README_zh-TW.md +++ b/zh-TW/README_zh-TW.md @@ -2766,4 +2766,40 @@ console.log("I want pizza"[0])

+--- +###### 88. 將會輸出什麽內容? + +```javascript +function sum(num1, num2 = num1) { + console.log(num1 + num2) +} + +sum(10) +``` + +- A: `NaN` +- B: `20` +- C: `ReferenceError` +- D: `undefined` + +
答案 +

+ +#### 答案: B + +您可以將預設參數的值設置為函數的另一個參數,只要另一個參數定義在其之前即可。我們將值`10`傳遞給`sum`函數。如果`sum`函數只接收1個參數,則意味著沒有傳遞`num2`的值,這種情況下,`num1`的值等於傳遞的值`10`。 `num2`的預設值是`num1`的值,即`10`。 ```num1 + num2```返回`20`。 + +如果您嘗試將預設參數的值設置為後面定義的參數,則可能導致參數的值尚未初始化,從而引發錯誤。比如: +```js +function test(m = n, n = 2) { + console.log(m, n) +} +test() // Uncaught ReferenceError: Cannot access 'n' before initialization +test(3) // 3 2 +test(3, 4) // 3 4 +``` + +

+
+ --- \ No newline at end of file From 56e36d600150ca30f9d29c03399e0a139d2613c1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=AF=AB=E8=A9=A9=E7=BE=8A?= Date: Fri, 2 Jul 2021 18:50:40 +0800 Subject: [PATCH 063/193] Translation zh-TW answer 89 --- zh-TW/README_zh-TW.md | 37 ++++++++++++++++++++++++++++++++++--- 1 file changed, 34 insertions(+), 3 deletions(-) diff --git a/zh-TW/README_zh-TW.md b/zh-TW/README_zh-TW.md index 5ff3509e..09270f51 100644 --- a/zh-TW/README_zh-TW.md +++ b/zh-TW/README_zh-TW.md @@ -1594,7 +1594,7 @@ sayHi(); #### 答案: D 使用 `throw` 語句,我們可以建立自定義的錯誤。 使用此語句,您可以觸發例外(exception)。例外可以是 `string`,`number`,`boolean` 或 `object`。 -在這種情況下,我們的例外是字符串 `Hello world`。 +在這種情況下,我們的例外是字串 `Hello world`。 通過 `catch` 語句,我們可以指定如果在 `try` 的程式區塊中拋出例外時該怎麼辦。 例如拋出例外:字串 `'Hello world'`。 現在, `e` 等於我們記錄的字串。 因此輸出結果將會是 `'Oh an error: Hello world'`。 @@ -2649,7 +2649,7 @@ console.log(person) 請注意,我們沒有引用`person`物件本身,只是將變數`city`設置為等於`person`物件上`city`屬性的當前值。 -然後,我們將`city`設置為等於字符串`“Amsterdam”`。這不會更改person物件:沒有對該物件的引用。 +然後,我們將`city`設置為等於字串`“Amsterdam”`。這不會更改person物件:沒有對該物件的引用。 因此輸出`person`物件時,會返回未修改的物件。 @@ -2802,4 +2802,35 @@ test(3, 4) // 3 4

---- \ No newline at end of file +--- +###### 89. 將會輸出什麽內容? + +```javascript +// module.js +export default () => "Hello world" +export const name = "Lydia" + +// index.js +import * as data from "./module" + +console.log(data) +``` + +- A: `{ default: function default(), name: "Lydia" }` +- B: `{ default: function default() }` +- C: `{ default: "Hello world", name: "Lydia" }` +- D: Global object of `module.js` + +
答案 +

+ +#### 答案: A + +使用`import * as name`語法,我們將`module.js`文件中所有`export`匯入到`index.js`文件中,並且建立了一個名為`data`的新物件。在`module.js`文件中,有兩個匯出:預設匯出和命名匯出。預設匯出是一個返回字串“Hello World”的函數,命名匯出是一個名為`name`的變數,其值為字串`“Lydia”`。 + +`data`物件具有預設匯出的`default`屬性,其他屬性具有指定exports的名稱及其對應的值。 + +

+
+ +--- From d9ed0cfa44a9163d55768c9fe570bb090986e8ee Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=AF=AB=E8=A9=A9=E7=BE=8A?= Date: Fri, 2 Jul 2021 18:52:39 +0800 Subject: [PATCH 064/193] Translation zh-TW answer 90 --- zh-TW/README_zh-TW.md | 37 +++++++++++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) diff --git a/zh-TW/README_zh-TW.md b/zh-TW/README_zh-TW.md index 09270f51..5f1d58f4 100644 --- a/zh-TW/README_zh-TW.md +++ b/zh-TW/README_zh-TW.md @@ -2834,3 +2834,40 @@ console.log(data) --- +###### 90. 將會輸出什麽內容? + +```javascript +class Person { + constructor(name) { + this.name = name + } +} + +const member = new Person("John") +console.log(typeof member) +``` + +- A: `"class"` +- B: `"function"` +- C: `"object"` +- D: `"string"` + +
答案 +

+ +#### 答案: C + +class是建構函數的語法糖,如果用建構函數的方式來重寫`Person`class則會是: + +```javascript +function Person() { + this.name = name +} +``` + +透過`new`來呼叫建構函數,將會產生建構函數`Person`的實例,對實例執行`typeof`關鍵字將返回`"object"`,上述情況輸出`"object"`。 + +

+
+ +--- \ No newline at end of file From 3f2adf57dfe928121ad495016c99d8ba435f803c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=AF=AB=E8=A9=A9=E7=BE=8A?= Date: Fri, 2 Jul 2021 18:54:56 +0800 Subject: [PATCH 065/193] Translation zh-TW answer 91 --- zh-TW/README_zh-TW.md | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) diff --git a/zh-TW/README_zh-TW.md b/zh-TW/README_zh-TW.md index 5f1d58f4..eaaf1973 100644 --- a/zh-TW/README_zh-TW.md +++ b/zh-TW/README_zh-TW.md @@ -2870,4 +2870,30 @@ function Person() {

+--- +###### 91. 將會輸出什麽內容? + +```javascript +let newList = [1, 2, 3].push(4) + +console.log(newList.push(5)) +``` + +- A: `[1, 2, 3, 4, 5]` +- B: `[1, 2, 3, 5]` +- C: `[1, 2, 3, 4]` +- D: `Error` + +
答案 +

+ +#### 答案: D + +`.push`函數回傳陣列的長度,而不是陣列本身!通過將`newList`設置為`[1,2,3].push(4)`,實際上`newList`等於陣列的新長度:`4`。 + +然後,嘗試在`newList`上使用`.push`函數。由於`newList`是數值`4`,拋出TypeError。 + +

+
+ --- \ No newline at end of file From 599eee504c6df69f64fe4e5c6ac97569f3fa5f3e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=AF=AB=E8=A9=A9=E7=BE=8A?= Date: Fri, 2 Jul 2021 18:56:20 +0800 Subject: [PATCH 066/193] Translation zh-TW answer 92 --- zh-TW/README_zh-TW.md | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) diff --git a/zh-TW/README_zh-TW.md b/zh-TW/README_zh-TW.md index eaaf1973..dc863560 100644 --- a/zh-TW/README_zh-TW.md +++ b/zh-TW/README_zh-TW.md @@ -2896,4 +2896,33 @@ console.log(newList.push(5))

+--- +###### 92. 將會輸出什麽內容? + +```javascript +function giveLydiaPizza() { + return "Here is pizza!" +} + +const giveLydiaChocolate = () => "Here's chocolate... now go hit the gym already." + +console.log(giveLydiaPizza.prototype) +console.log(giveLydiaChocolate.prototype) +``` + +- A: `{ constructor: ...}` `{ constructor: ...}` +- B: `{}` `{ constructor: ...}` +- C: `{ constructor: ...}` `{}` +- D: `{ constructor: ...}` `undefined` + +
答案 +

+ +#### 答案: D + +正規式函數,例如`giveLydiaPizza`函數,有一個`prototype`屬性,它是一個帶有`constructor`屬性的物件(原型物件)。然而,箭頭函數,例如`giveLydiaChocolate`函數,沒有這個`prototype`屬性。嘗試使用`giveLydiaChocolate.prototype`存取`prototype`屬性時會得到`undefined`。 + +

+
+ --- \ No newline at end of file From 8372719d70e7acc224b4e730361d6efb1b9dd83c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=AF=AB=E8=A9=A9=E7=BE=8A?= Date: Fri, 2 Jul 2021 18:57:48 +0800 Subject: [PATCH 067/193] Translation zh-TW answer 93 --- zh-TW/README_zh-TW.md | 35 +++++++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) diff --git a/zh-TW/README_zh-TW.md b/zh-TW/README_zh-TW.md index dc863560..c8228af2 100644 --- a/zh-TW/README_zh-TW.md +++ b/zh-TW/README_zh-TW.md @@ -2925,4 +2925,39 @@ console.log(giveLydiaChocolate.prototype)

+--- +###### 93. 將會輸出什麽內容? + +```javascript +const person = { + name: "Lydia", + age: 21 +} + +for (const [x, y] of Object.entries(person)) { + console.log(x, y) +} +``` + +- A: `name` `Lydia` and `age` `21` +- B: `["name", "Lydia"]` and `["age", 21]` +- C: `["name", "age"]` and `undefined` +- D: `Error` + +
答案 +

+ +#### 答案: A +`Object.entries()`函數回傳一個給定物件本身可枚舉屬性的鍵值對陣列,上述情況回傳一個二維陣列,陣列每個元素是一個包含鍵和值的陣列: + +`[['name','Lydia'],['age',21]]` + +使用`for-of`循環,我們可以迭代陣列中的每個元素,上述情況是子陣列。我們可以使用`const [x,y]`在`for-of`循環中解構子陣列。 `x`等於子陣列中的第一個元素,`y`等於子陣列中的第二個元素。 + +第一個子陣列是`[“name”,“Lydia”]`,其中`x`等於`name`,而`y`等於`Lydia`。 +第二個子陣列是`[“age”,21]`,其中`x`等於`age`,而`y`等於`21`。 + +

+
+ --- \ No newline at end of file From ff341ecfffa03694a358c31d4184a98bdcde4fd5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=AF=AB=E8=A9=A9=E7=BE=8A?= Date: Fri, 2 Jul 2021 18:59:18 +0800 Subject: [PATCH 068/193] Translation zh-TW answer 94 --- zh-TW/README_zh-TW.md | 35 +++++++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) diff --git a/zh-TW/README_zh-TW.md b/zh-TW/README_zh-TW.md index c8228af2..190b3086 100644 --- a/zh-TW/README_zh-TW.md +++ b/zh-TW/README_zh-TW.md @@ -2960,4 +2960,39 @@ for (const [x, y] of Object.entries(person)) {

+--- +###### 94. 將會輸出什麽內容? + +```javascript +function getItems(fruitList, ...args, favoriteFruit) { + return [...fruitList, ...args, favoriteFruit] +} + +getItems(["banana", "apple"], "pear", "orange") +``` + +- A: `["banana", "apple", "pear", "orange"]` +- B: `[["banana", "apple"], "pear", "orange"]` +- C: `["banana", "apple", ["pear"], "orange"]` +- D: `SyntaxError` + +
答案 +

+ +#### 答案: D + +`... args`是剩餘參數,剩餘參數的值是一個包含所有剩餘參數的陣列,**並且只能作為最後一個參數**。上面示範中,剩餘參數是第二個參數,這是不可能的,並會拋出語法錯誤。 + +```javascript +function getItems(fruitList, favoriteFruit, ...args) { + return [...fruitList, ...args, favoriteFruit] +} + +getItems(["banana", "apple"], "pear", "orange") +``` + +上面示範中是有效的,將會回傳陣列:`[ 'banana', 'apple', 'orange', 'pear' ]` +

+
+ --- \ No newline at end of file From c4a98fae48d5b6a2fb2e346e27b99e25f3c69e7d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=AF=AB=E8=A9=A9=E7=BE=8A?= Date: Fri, 2 Jul 2021 19:02:02 +0800 Subject: [PATCH 069/193] Translation zh-TW answer 95 --- zh-TW/README_zh-TW.md | 43 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 43 insertions(+) diff --git a/zh-TW/README_zh-TW.md b/zh-TW/README_zh-TW.md index 190b3086..26085d31 100644 --- a/zh-TW/README_zh-TW.md +++ b/zh-TW/README_zh-TW.md @@ -2995,4 +2995,47 @@ getItems(["banana", "apple"], "pear", "orange")

+--- +###### 95. 將會輸出什麽內容? + +```javascript +function nums(a, b) { + if + (a > b) + console.log('a is bigger') + else + console.log('b is bigger') + return + a + b +} + +console.log(nums(4, 2)) +console.log(nums(1, 2)) +``` + +- A: `a is bigger`, `6` and `b is bigger`, `3` +- B: `a is bigger`, `undefined` and `b is bigger`, `undefined` +- C: `undefined` and `undefined` +- D: `SyntaxError` + +
答案 +

+ +#### 答案: B + + +在JavaScript中,我們不必硬性寫分號(`;`),但是JavaScript引擎仍然在語法之後自動補上分號。這稱為**自動分號插入**。例如,一個語法可以是變數,或者像`throw`、`return`、`break`這樣的關鍵字。 + +在這裡,我們在新的一行上寫了一個`return`語法和另一個值`a + b `。然而,由於它是一個新的一行,引擎並不知道它實際上是我們想要回傳的值。相反,它會在`return`後面自動補上分號。你可以這樣看: + +```javascript + return; + a + b +``` + +這意味著永遠不會到達`a + b`,因為函數在`return`關鍵字之後停止運行。如果沒有回傳值,就像這裡,函數回傳`undefined`。注意,在`if/else`語法之後沒有自動插入! + +

+
+ --- \ No newline at end of file From 5f3814c0d1694b94eae865cf8edce5f25dbb2c01 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=AF=AB=E8=A9=A9=E7=BE=8A?= Date: Fri, 2 Jul 2021 19:05:22 +0800 Subject: [PATCH 070/193] Translation zh-TW answer 96 --- zh-TW/README_zh-TW.md | 37 +++++++++++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) diff --git a/zh-TW/README_zh-TW.md b/zh-TW/README_zh-TW.md index 26085d31..13a13ac9 100644 --- a/zh-TW/README_zh-TW.md +++ b/zh-TW/README_zh-TW.md @@ -3035,6 +3035,43 @@ console.log(nums(1, 2)) 這意味著永遠不會到達`a + b`,因為函數在`return`關鍵字之後停止運行。如果沒有回傳值,就像這裡,函數回傳`undefined`。注意,在`if/else`語法之後沒有自動插入! +

+ + +--- +###### 96. 將會輸出什麽內容? + +```javascript +class Person { + constructor() { + this.name = "Lydia" + } +} + +Person = class AnotherPerson { + constructor() { + this.name = "Sarah" + } +} + +const member = new Person() +console.log(member.name) +``` + +- A: `"Lydia"` +- B: `"Sarah"` +- C: `Error: cannot redeclare Person` +- D: `SyntaxError` + +
答案 +

+ +#### 答案: B + + +我們可以將class設置為等於其他class/函數建構函數。在這種情況下,我們將`Person`設置為`AnotherPerson`。這個建構函數的名字是`Sarah`,所以新的`Person`實例`member`上的name屬性是`Sarah`。 + +

From 8f918ceb2fa159d53c418a8b9c7605aec6885f6b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=AF=AB=E8=A9=A9=E7=BE=8A?= Date: Fri, 2 Jul 2021 19:07:17 +0800 Subject: [PATCH 071/193] Translation zh-TW answer 97 --- zh-TW/README_zh-TW.md | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) diff --git a/zh-TW/README_zh-TW.md b/zh-TW/README_zh-TW.md index 13a13ac9..9f270d27 100644 --- a/zh-TW/README_zh-TW.md +++ b/zh-TW/README_zh-TW.md @@ -3072,6 +3072,36 @@ console.log(member.name) 我們可以將class設置為等於其他class/函數建構函數。在這種情況下,我們將`Person`設置為`AnotherPerson`。這個建構函數的名字是`Sarah`,所以新的`Person`實例`member`上的name屬性是`Sarah`。 +

+ + +--- +###### 97. 將會輸出什麽內容? + +```javascript +const info = { + [Symbol('a')]: 'b' +} + +console.log(info) +console.log(Object.keys(info)) +``` + +- A: `{Symbol('a'): 'b'}` and `["{Symbol('a')"]` +- B: `{}` and `[]` +- C: `{ a: "b" }` and `["a"]` +- D: `{Symbol('a'): 'b'}` and `[]` + +
答案 +

+ +#### 答案: D + + +`Symbol`類型是不可枚舉的。 `Object.keys`函數回傳物件上的所有可枚舉的鍵屬性。 `Symbol`類型是不可見的,並返回一個空陣列。記錄整個物件時,所有屬性都是可見的,甚至是不可枚舉的屬性。 + +這是`Symbol`的眾多特性之一:除了表示完全唯一的值(防止物件意外名稱衝突,例如當使用2個想要向同一物件添加屬性的庫時),您還可以`隱藏`這種方式物件的屬性(儘管不完全。你仍然可以使用`Object.getOwnPropertySymbols()`函數存取`Symbol`。 +

From 82ecb88a0a3db2800db761ab93a9d4b07b0de546 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=AF=AB=E8=A9=A9=E7=BE=8A?= Date: Fri, 2 Jul 2021 19:10:13 +0800 Subject: [PATCH 072/193] Translation zh-TW answer 98 --- zh-TW/README_zh-TW.md | 40 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 40 insertions(+) diff --git a/zh-TW/README_zh-TW.md b/zh-TW/README_zh-TW.md index 9f270d27..e910e6a5 100644 --- a/zh-TW/README_zh-TW.md +++ b/zh-TW/README_zh-TW.md @@ -3105,4 +3105,44 @@ console.log(Object.keys(info))

+--- +###### 98. 將會輸出什麽內容? + +```javascript +const getList = ([x, ...y]) => [x, y] +const getUser = user => { name: user.name, age: user.age } + +const list = [1, 2, 3, 4] +const user = { name: "Lydia", age: 21 } + +console.log(getList(list)) +console.log(getUser(user)) +``` + +- A: `[1, [2, 3, 4]]` and `undefined` +- B: `[1, [2, 3, 4]]` and `{ name: "Lydia", age: 21 }` +- C: `[1, 2, 3, 4]` and `{ name: "Lydia", age: 21 }` +- D: `Error` and `{ name: "Lydia", age: 21 }` + +
答案 +

+ +#### 答案: A + +`getList`函數接收一個陣列作為其參數。在`getList`函數的括號之間,我們立即解構這個陣列。您可以這樣表達: + + `[x, ...y] = [1, 2, 3, 4]` + + +使用剩餘的參數`... y`,我們將所有剩餘參數放在一個陣列中。在這種情況下,其餘的參數是`2`,`3`和`4`。 `y`的值是一個陣列,包含所有其餘參數。在這種情況下,`x`的值等於`1`,所以當我們輸出`[x,y]`時,會輸出`[1,[2,3,4]]`。 + + `getUser`函數接收一個物件。對於箭頭函數,如果只回傳一個值,我們不必編寫大括號。但是,如果您想從一個箭頭函數回傳一個物件,您必須在小括號之間編寫它,否則不會回傳任何值!下面的函數將回傳一個物件: + +```const getUser = user => ({ name: user.name, age: user.age })``` + +由於在這種情況下不回傳任何值,因此該函數回傳`undefined`。 + +

+
+ --- \ No newline at end of file From 30bb4bb683d12c0cd6a85fed5ddcd72a926a7463 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=AF=AB=E8=A9=A9=E7=BE=8A?= Date: Fri, 2 Jul 2021 19:11:41 +0800 Subject: [PATCH 073/193] Translation zh-TW answer 99 --- zh-TW/README_zh-TW.md | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) diff --git a/zh-TW/README_zh-TW.md b/zh-TW/README_zh-TW.md index e910e6a5..37e186be 100644 --- a/zh-TW/README_zh-TW.md +++ b/zh-TW/README_zh-TW.md @@ -3145,4 +3145,33 @@ console.log(getUser(user))

+--- +###### 99. 將會輸出什麽內容? + +```javascript +const name = "Lydia" + +console.log(name()) +``` + +- A: `SyntaxError` +- B: `ReferenceError` +- C: `TypeError` +- D: `undefined` + +
答案 +

+ +#### 答案: C + +變數`name`保存字串的值,該字串不是函數,因此無法呼叫。 + +當值不是預期類型時,會拋出`TypeErrors`。 JavaScript期望`name`是一個函數,因為我們試圖呼叫它。但它是一個字串,因此拋出`TypeError`:`name is not a function` + +當你編寫了一些非有效的JavaScript時,會拋出語法錯誤,例如當你把`return`這個詞寫成`retrun`時。 +當JavaScript無法找到您嘗試存取的值的引用時,拋出`ReferenceErrors`。 + +

+
+ --- \ No newline at end of file From b35e5113e9c72dc7943c3029c43999b7ba1ca3d6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=AF=AB=E8=A9=A9=E7=BE=8A?= Date: Fri, 2 Jul 2021 19:14:15 +0800 Subject: [PATCH 074/193] =?UTF-8?q?=E2=9C=A8=F0=9F=8E=89=20Translation=20z?= =?UTF-8?q?h-TW=20answer=20100=20=E2=9C=A8=F0=9F=8E=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- zh-TW/README_zh-TW.md | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/zh-TW/README_zh-TW.md b/zh-TW/README_zh-TW.md index 37e186be..f75c17c7 100644 --- a/zh-TW/README_zh-TW.md +++ b/zh-TW/README_zh-TW.md @@ -3174,4 +3174,32 @@ console.log(name())

+--- +###### 100. 將會輸出什麽內容? + +```javascript +// 🎉✨ 耶! 我終於翻到100題了! 噢耶! ✨🎉 + +const output = `${[] && 'Im'}possible! +You should${'' && `n't`} see a therapist after so much JavaScript lol` +``` + +- A: `possible! You should see a therapist after so much JavaScript lol` +- B: `Impossible! You should see a therapist after so much JavaScript lol` +- C: `possible! You shouldn't see a therapist after so much JavaScript lol` +- D: `Impossible! You shouldn't see a therapist after so much JavaScript lol` + +
答案 +

+ +#### 答案: B + + +`[]`是一個真值。使用`&&`運算符,如果左側值是真值,則回傳右側值。在這種情況下,左側值`[]`是一個真值,所以回傳`Im`。 + +`""`是一個假值。如果左側值是假的,則不回傳任何內容。 `n't`不會被退回。 + +

+
+ --- \ No newline at end of file From 72a0b626486f8105a772b805bcd4b70e1a585c7e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=AF=AB=E8=A9=A9=E7=BE=8A?= Date: Fri, 2 Jul 2021 19:32:04 +0800 Subject: [PATCH 075/193] Translation zh-TW answer 101 --- zh-TW/README_zh-TW.md | 32 ++++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) diff --git a/zh-TW/README_zh-TW.md b/zh-TW/README_zh-TW.md index f75c17c7..8d277109 100644 --- a/zh-TW/README_zh-TW.md +++ b/zh-TW/README_zh-TW.md @@ -3202,4 +3202,36 @@ You should${'' && `n't`} see a therapist after so much JavaScript lol`

+--- +###### 101.將會輸出什麽內容? + +```javascript +const one = (false || {} || null) +const two = (null || false || "") +const three = ([] || 0 || true) + +console.log(one, two, three) +``` + +- A: `false` `null` `[]` +- B: `null` `""` `true` +- C: `{}` `""` `[]` +- D: `null` `null` `true` + +
答案 +

+ +#### 答案: C + +使用`||`運算子,我們可以得到第一個真值。如果所有值都是假值,則得到最後一個值。 + +`(false || {} || null)`:空物件`{}`是一個真值。這是第一個(也是唯一的)真值,它將被得到。 `one`等於`{}`。 + +`(null || false ||“”)`:所有值都是假值。這意味著得到傳遞的值`""`。 `two`等於`""`。 + +`([] || 0 ||“”)`:空陣列`[]`是一個真值。這是第一個得到的真值。 `three`等於`[]`。 + +

+
+ --- \ No newline at end of file From d4d0f89576685cf4ecd9aaca4b88e0b0110524e1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=AF=AB=E8=A9=A9=E7=BE=8A?= Date: Fri, 2 Jul 2021 19:38:01 +0800 Subject: [PATCH 076/193] Translation zh-TW answer 102 --- zh-TW/README_zh-TW.md | 43 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 43 insertions(+) diff --git a/zh-TW/README_zh-TW.md b/zh-TW/README_zh-TW.md index 8d277109..be7510a3 100644 --- a/zh-TW/README_zh-TW.md +++ b/zh-TW/README_zh-TW.md @@ -3231,6 +3231,49 @@ console.log(one, two, three) `([] || 0 ||“”)`:空陣列`[]`是一個真值。這是第一個得到的真值。 `three`等於`[]`。 +

+ + +--- +###### 102. 依序輸出什麼內容? + +```javascript +const myPromise = () => Promise.resolve('I have resolved!') + +function firstFunction() { + myPromise().then(res => console.log(res)) + console.log('second') +} + +async function secondFunction() { + console.log(await myPromise()) + console.log('second') +} + +firstFunction() +secondFunction() +``` + +- A: `I have resolved!`, `second` and `I have resolved!`, `second` +- B: `second`, `I have resolved!` and `second`, `I have resolved!` +- C: `I have resolved!`, `second` and `second`, `I have resolved!` +- D: `second`, `I have resolved!` and `I have resolved!`, `second` + +
答案 +

+ +#### 答案: D + + +有了promise,我們通常會說:當我想要呼叫某個函數,但是由於它可能需要一段時間,因此暫時將它放在一邊。只有當某個值被resolved/rejected,並且執行序為空時才使用這個值。 + +我們可以在`async`函數中通過`.then`和`await`關鍵字獲得該值。儘管我們可以通過`.then`和`await`獲得promise的值,但是它們的運作方式不同。 + +在`firstFunction`中,當執行到`myPromise`函數時我們將其放在一邊,即promise進入微任務佇列,其他後面的程式(`console.log('second')`)照常執行,因此`second `被輸出,`firstFunction`函數到此執行完畢,執行序中任務佇列被清空,此時開始執行微任務佇列中的任務,`I have resolved`被輸出。 + +在`secondFunction`函數中,我們通過`await`關鍵字,暫停了後面程式的執行,直到異步函數的值被解析才開始後面程式的執行。這意味著,它會等著直到 `myPromise` 以值`I have resolved`被`resolve`之後,下一行`second`才開始執行。 + +

From 7c33e1bd9775cd5e5e1abc07282906ad22a806cf Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=AF=AB=E8=A9=A9=E7=BE=8A?= Date: Fri, 2 Jul 2021 19:40:22 +0800 Subject: [PATCH 077/193] Translation zh-TW answer 103 --- zh-TW/README_zh-TW.md | 40 ++++++++++++++++++++++++++++++++++++++-- 1 file changed, 38 insertions(+), 2 deletions(-) diff --git a/zh-TW/README_zh-TW.md b/zh-TW/README_zh-TW.md index be7510a3..2ed4e82d 100644 --- a/zh-TW/README_zh-TW.md +++ b/zh-TW/README_zh-TW.md @@ -2731,7 +2731,7 @@ function getName(name) { #### 答案: A -使用邏輯非運算符`!`,將返回一個布林值,使用`!! name`,我們可以確定`name`的值是`true`還是`false`。如果`name`是`true`,那麼`!name`返回`false`。 `!false`返回`true`。 +使用邏輯非運算子`!`,將返回一個布林值,使用`!! name`,我們可以確定`name`的值是`true`還是`false`。如果`name`是`true`,那麼`!name`返回`false`。 `!false`返回`true`。 通過將`hasName`設置為`name`,可以將`hasName`設置為等於傳遞給`getName`函數的值,而不是布林值`true`。 @@ -3195,7 +3195,7 @@ You should${'' && `n't`} see a therapist after so much JavaScript lol` #### 答案: B -`[]`是一個真值。使用`&&`運算符,如果左側值是真值,則回傳右側值。在這種情況下,左側值`[]`是一個真值,所以回傳`Im`。 +`[]`是一個真值。使用`&&`運算子,如果左側值是真值,則回傳右側值。在這種情況下,左側值`[]`是一個真值,所以回傳`Im`。 `""`是一個假值。如果左側值是假的,則不回傳任何內容。 `n't`不會被退回。 @@ -3274,6 +3274,42 @@ secondFunction() 在`secondFunction`函數中,我們通過`await`關鍵字,暫停了後面程式的執行,直到異步函數的值被解析才開始後面程式的執行。這意味著,它會等著直到 `myPromise` 以值`I have resolved`被`resolve`之後,下一行`second`才開始執行。 +

+ + +--- +###### 103. 將會輸出什麽內容? + +```javascript +const set = new Set() + +set.add(1) +set.add("Lydia") +set.add({ name: "Lydia" }) + +for (let item of set) { + console.log(item + 2) +} +``` + +- A: `3`, `NaN`, `NaN` +- B: `3`, `7`, `NaN` +- C: `3`, `Lydia2`, `[Object object]2` +- D: `"12"`, `Lydia2`, `[Object object]2` + +
答案 +

+ +#### 答案: C + +“+”運算子不僅用於相加數字,還可以使用它來連接字串。每當JavaScript引擎發現一個或多個值不是數字時,就會將數字強制為字串。 + +第一個是數字1。 1 + 2得到數字3。 + +但是,第二個是字串“Lydia”。 “Lydia”是一個字串,2是一個數字:2被強制轉換為字串。 “Lydia”和“2”被連接起來,產生字串“Lydia2”。 + +`{name:“ Lydia”}`是一個物件。數字和物件都不是字串,因此將二者都字串化。每當我們對正規式物件進行字串化時,它就會變成`[Object object]`。與“2”串聯的“ [Object object]”成為“[Object object]2”。 +

From 7132b39196e0804167e348390d4811cdaacabfc2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=AF=AB=E8=A9=A9=E7=BE=8A?= Date: Fri, 2 Jul 2021 19:43:10 +0800 Subject: [PATCH 078/193] Translation zh-TW answer 104 --- zh-TW/README_zh-TW.md | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/zh-TW/README_zh-TW.md b/zh-TW/README_zh-TW.md index 2ed4e82d..f302192a 100644 --- a/zh-TW/README_zh-TW.md +++ b/zh-TW/README_zh-TW.md @@ -3313,4 +3313,27 @@ for (let item of set) {

+--- +###### 104. 將得到什麼 + +```javascript +Promise.resolve(5) +``` + +- A: `5` +- B: `Promise {: 5}` +- C: `Promise {: 5}` +- D: `Error` + +
答案 +

+ +#### 答案: C + +我們可以將我們想要的任何類型的值傳遞`Promise.resolve`,無論是否`promise`。該函數本身返回帶有已解析值的`Promise` (``)。如果您傳遞正規式函數,它將是具有正規式值的已解決`promise`。如果你通過了promise,它將是一個已經resolved的且帶有傳的值的promise。 + +上述情況,我們傳了數字5,因此返回一個resolved狀態的promise,resolve值為`5` + +

+
--- \ No newline at end of file From a55f4adc213d759a5bac9d88ba37e0cd7688c706 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=AF=AB=E8=A9=A9=E7=BE=8A?= Date: Fri, 2 Jul 2021 19:46:29 +0800 Subject: [PATCH 079/193] Translation zh-TW answer 105 --- zh-TW/README_zh-TW.md | 39 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) diff --git a/zh-TW/README_zh-TW.md b/zh-TW/README_zh-TW.md index f302192a..4aa042d1 100644 --- a/zh-TW/README_zh-TW.md +++ b/zh-TW/README_zh-TW.md @@ -3336,4 +3336,43 @@ Promise.resolve(5)

+--- + +###### 105. 將會輸出什麽內容? + +```javascript +function compareMembers(person1, person2 = person) { + if (person1 !== person2) { + console.log("Not the same!") + } else { + console.log("They are the same!") + } +} + +const person = { name: "Lydia" } + +compareMembers(person) +``` + +- A: `Not the same!` +- B: `They are the same!` +- C: `ReferenceError` +- D: `SyntaxError` + +
答案 +

+ +#### 答案: B + +物件通過參考位址傳遞。當我們檢查物件的嚴格相等性(===)時,我們正在比較它們的參考位址。 + +我們將“person2”的預設值設置為“person”物件,並將“person”對像作為“person1”的值傳遞。 + +這意味著兩個值都引用內存中的同一位置,因此它們是相等的。 + +運行“ else”語句中的代碼塊,並記錄`They are the same!` 。 + +

+
+ --- \ No newline at end of file From 8b8c411201ff88e5001fd635df1840538fa33ce5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=AF=AB=E8=A9=A9=E7=BE=8A?= Date: Fri, 2 Jul 2021 19:57:53 +0800 Subject: [PATCH 080/193] Translation zh-TW answer 106 --- zh-TW/README_zh-TW.md | 41 ++++++++++++++++++++++++++++++++++++++++- 1 file changed, 40 insertions(+), 1 deletion(-) diff --git a/zh-TW/README_zh-TW.md b/zh-TW/README_zh-TW.md index 4aa042d1..528dd5ae 100644 --- a/zh-TW/README_zh-TW.md +++ b/zh-TW/README_zh-TW.md @@ -3375,4 +3375,43 @@ compareMembers(person)

---- \ No newline at end of file +--- +###### 106. 將會輸出什麽內容? + + +```javascript +const colorConfig = { + red: true, + blue: false, + green: true, + black: true, + yellow: false, +} + +const colors = ["pink", "red", "blue"] + +console.log(colorConfig.colors[1]) +``` + +- A: `true` +- B: `false` +- C: `undefined` +- D: `TypeError` + +
答案 +

+ +#### 答案: D + +在JavaScript中,我們有兩種存取物件屬性的方法:括號表示法或點表示法。在此範例中,我們使用點表示法(`colorConfig.colors`)代替括號表示法(`colorConfig [“ colors”]`)。 + +使用點表示法,JavaScript會嘗試使用該確切名稱在物件上查找屬性。在此範例中,JavaScript嘗試在colorconfig物件上找到名為colors的屬性。沒有名為“colors”的屬性,因此得到“undefined”。 +然後,我們嘗試使用`[1]`存取第一個元素的值。我們無法對未定義的值執行此操作,因此會拋出`Cannot read property '1' of undefined`。 + +JavaScript解釋(或取消裝箱)語句。當我們使用中括號表示法時,它會看到第一個左方括號`[`並一直進行下去,直到找到右方括號`]`。只有這樣,它才會評估該語句。如果我們使用了colorConfig [colors [1]],它將得到colorConfig物件上red屬性的值。 + + +

+
+ +--- From 94275af56540695e4be4b79524268a71e6da00a3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=AF=AB=E8=A9=A9=E7=BE=8A?= Date: Sat, 3 Jul 2021 02:47:39 +0800 Subject: [PATCH 081/193] Translation zh-TW answer 107 ~ 120 --- zh-TW/README_zh-TW.md | 454 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 454 insertions(+) diff --git a/zh-TW/README_zh-TW.md b/zh-TW/README_zh-TW.md index 528dd5ae..628edef6 100644 --- a/zh-TW/README_zh-TW.md +++ b/zh-TW/README_zh-TW.md @@ -3411,6 +3411,460 @@ console.log(colorConfig.colors[1]) JavaScript解釋(或取消裝箱)語句。當我們使用中括號表示法時,它會看到第一個左方括號`[`並一直進行下去,直到找到右方括號`]`。只有這樣,它才會評估該語句。如果我們使用了colorConfig [colors [1]],它將得到colorConfig物件上red屬性的值。 +

+ + +--- +###### 107. 將會輸出什麽內容? + +```javascript +console.log('❤️' === '❤️') +``` + +- A: `true` +- B: `false` + +
答案 +

+ +#### 答案: A + +在內部,表情符號是unicode。 heat表情符號的unicode是`“ U + 2764 U + FE0F”`。對於相同的表情符號,它們總是相同的,因此我們將兩個相等的字串相互比較,這將返回true。 + +

+
+ +--- +###### 108. 哪些函數修改了原本的陣列? + + +```javascript +const emojis = ['✨', '🥑', '😍'] + +emojis.map(x => x + '✨') +emojis.filter(x => x !== '🥑') +emojis.find(x => x !== '🥑') +emojis.reduce((acc, cur) => acc + '✨') +emojis.slice(1, 2, '✨') +emojis.splice(1, 2, '✨') +``` + +- A: `All of them` +- B: `map` `reduce` `slice` `splice` +- C: `map` `slice` `splice` +- D: `splice` + +
答案 +

+ +#### 答案: D + +使用`splice`方法,我們透過刪除,取代或增加元素來修改原始陣列。在這種情況下,我們從索引1中刪除了2個元素(我們刪除了`'🥑'`和`'😍'`),同時增加了✨emoji表情。 + +`map`,`filter`和`slice`回傳一個新陣列,`find`回傳一個元素,而`reduce`回傳一個計算過的值。 + +

+
+ +--- +###### 109. 將會輸出什麽內容? + +```javascript +const food = ['🍕', '🍫', '🥑', '🍔'] +const info = { favoriteFood: food[0] } + +info.favoriteFood = '🍝' + +console.log(food) +``` + +- A: `['🍕', '🍫', '🥑', '🍔']` +- B: `['🍝', '🍫', '🥑', '🍔']` +- C: `['🍝', '🍕', '🍫', '🥑', '🍔']` +- D: `ReferenceError` + +
答案 +

+ +#### 答案: A + +我們將`info`物件上的`favoriteFood`屬性的值設置為披薩表情符號“🍕”的字串。字串是原始內容類型。在JavaScript中,原始內容類型通過值起作用 + +在這種情況下,我們將`info`物件上的`favoriteFood`屬性的值設置為等於`food`陣列中的第一個元素的值,字串為披薩表情符號(`'🍕'` )。字串是原始內容類型,並且通過值進行交換,我們更改`info`物件上`favoriteFood`屬性的值。 food陣列沒有改變,因為favoriteFood的值只是該陣列中第一個元素的值的複製,並且與該元素上的元素沒有相同的緩存引用食物`[0]`。當我們記錄食物時,它仍然是原始陣列`['🍕','🍫','🥑','🍔']`。 + +

+
+ +--- +###### 110. 這函數做了什麼 + +```javascript +JSON.parse() +``` + +- A: Parses JSON to a JavaScript value +- B: Parses a JavaScript object to JSON +- C: Parses any JavaScript value to JSON +- D: Parses JSON to a JavaScript object only + +
答案 +

+ +#### 答案: A + +使用`JSON.parse()`函數,我們可以將JSON字串解析為JavaScript值。 + +```javascript +// 將數字字串化為有效的JSON,然後將JSON字串解析為JavaScript值: +const jsonNumber = JSON.stringify(4) // '4' +JSON.parse(jsonNumber) // 4 + +// 將數組值字串化為有效的JSON,然後將JSON字串解析為JavaScript值: +const jsonArray = JSON.stringify([1, 2, 3]) // '[1, 2, 3]' +JSON.parse(jsonArray) // [1, 2, 3] + +// 將物件字串化為有效的JSON,然後將JSON字串解析為JavaScript值: +const jsonArray = JSON.stringify({ name: "Lydia" }) // '{"name":"Lydia"}' +JSON.parse(jsonArray) // { name: 'Lydia' } +``` +

+
+ +--- +###### 111. 將會輸出什麽內容? + +```javascript +let name = 'Lydia' + +function getName() { + console.log(name) + let name = 'Sarah' +} + +getName() +``` + +- A: Lydia +- B: Sarah +- C: `undefined` +- D: `ReferenceError` + +
答案 +

+ +#### 答案: D + +每個函數都有其自己的執行上下文。 `getName`函數首先在其自身的上下文(範圍)內查找,以查看其是否包含我們嘗試存取的變數`name`。上述情況,`getName`函數包含其自己的`name`變數:我們用`let`關鍵字和`Sarah`的值定義變數`name`。 + +帶有`let`關鍵字(和`const`)的變數被提升,但是與`var`不同,它不會被***初始化***。在我們定義(初始化)它們之前,無法存取它們。這稱為“暫時性死區”。當我們嘗試在定義變數之前存取變數時,JavaScript會拋出`ReferenceError: Cannot access 'name' before initialization`。 + +如果我們不在`getName`函數中定義`name`變數,則javascript引擎會查看原型鏈。會找到其外部作用域有一個名為`name`的變數,其值為`Lydia`。在這種情況下,它將輸出`Lydia`: + +```javascript +let name = 'Lydia' + +function getName() { + console.log(name) +} + +getName() // Lydia +``` + +

+
+ +--- +###### 112. 將會輸出什麽內容? + +```javascript +function* generatorOne() { + yield ['a', 'b', 'c']; +} + +function* generatorTwo() { + yield* ['a', 'b', 'c']; +} + +const one = generatorOne() +const two = generatorTwo() + +console.log(one.next().value) +console.log(two.next().value) +``` + +- A: `a` and `a` +- B: `a` and `undefined` +- C: `['a', 'b', 'c']` and `a` +- D: `a` and `['a', 'b', 'c']` + +
答案 +

+ +#### 答案: C + +透過`yield` 關鍵字, 我們在`Generator` 函數裡執行`yield`語法. 透過`yield*` 關鍵字, 我們可以在一個`Generator` 函數裡面執行(`yield`語法)另一個`Generator ` 函數, 或可遍歷的物件(如陣列). + +在函數 `generatorOne` 中, 我們透過 `yield` 關鍵字 yield 了一個完整的陣列 `['a', 'b', 'c']`。函數`one`透過`next`方法返回的物件的`value` 屬性的值 (`one.next().value`) 等價於陣列 `['a', 'b', 'c']`. + +```javascript +console.log(one.next().value) // ['a', 'b', 'c'] +console.log(one.next().value) // undefined +``` + +在函數 `generatorTwo` 中, 我們使用 `yield*` 關鍵字。就相當於函數`two`第一個`yield`的值, 等價於在迭代器中第一個 `yield` 的值。陣列`['a', 'b', 'c']`就是這個迭代器. 第一個`yield` 的值就是`a`, 所以我們第一次調用`two.next().value`時, 就返回`a`。 + +```javascript +console.log(two.next().value) // 'a' +console.log(two.next().value) // 'b' +console.log(two.next().value) // 'c' +console.log(two.next().value) // undefined +``` + +

+
+ +--- + +###### 113. 將會輸出什麽內容? + +```javascript +console.log(`${(x => x)('I love')} to program`) +``` + +- A: `I love to program` +- B: `undefined to program` +- C: `${(x => x)('I love') to program` +- D: `TypeError` + +
答案 +

+ +#### 答案: A + +帶有模板字面量的表達式優先被執行。相當於字串會包含表達式,這個立即執行函數`(x => x)('I love')` 回傳的值. 我們向箭頭函數`x => x` 傳遞`'I love'` 作為參數。 `x` 等價於回傳的 `'I love'`。這就是結果 `I love to program`。 + +

+
+ +--- +###### 114. 這會發生什麼? + +```javascript +let config = { + alert: setInterval(() => { + console.log('Alert!') + }, 1000) +} + +config = null +``` + +- A: `setInterval` 裡的函數不會被呼叫 +- B: `setInterval` 裡的函數被呼叫一次 +- C: `setInterval` 裡的函數仍然會被每秒鐘呼叫 +- D: 我們從沒呼叫過 `config.alert()`, config 為 `null` + +
答案 +

+ +#### 答案: C + +一般情況下當我們將物件賦值為 `null`, 那些物件會被進行 _垃圾回收(garbage collected)_ 因為已經沒有對這些物件的引用了。然而,`setInterval`的參數是一個箭頭函數(所以上下文綁定到物件 `config` 了),函數仍然保留著對 `config`的引用。只要存在引用,物件就不會被垃圾回收。因為沒有被垃圾回收,`setInterval` 的每1000ms (1s)會被呼叫一次。 + +

+
+ +--- +###### 115. 哪一个函數會回傳 `'Hello world!'` ? + +```javascript +const myMap = new Map() +const myFunc = () => 'greeting' + +myMap.set(myFunc, 'Hello world!') + +//1 +myMap.get('greeting') +//2 +myMap.get(myFunc) +//3 +myMap.get(() => 'greeting') +``` + +- A: 1 +- B: 2 +- C: 2 and 3 +- D: All of them + +
答案 +

+ +#### 答案: B + +當透過 `set` 函數增加一個鍵值對,一個傳遞給 `set`函數的參數將會是鍵名,第二個參數將會是值。在這個case裡,鍵名為 _函數_ `() => 'greeting'`,值為`'Hello world'`。 `myMap` 現在就是 `{ () => 'greeting' => 'Hello world!' }`。 + +1 是錯的,因為鍵名不是 `'greeting'` 而是 `() => 'greeting'`。 +3 是錯的,因為我們給`get` 函數傳遞了一個新的函數。物件受 _引用_ 影響。函數也是物件,因此兩個函數嚴格上並不等價,儘管他們相同:他們有兩個不同的緩存引用地址。 + +

+
+ +--- +###### 116. 將會輸出什麽內容? + +```javascript +const person = { + name: "Lydia", + age: 21 +} + +const changeAge = (x = { ...person }) => x.age += 1 +const changeAgeAndName = (x = { ...person }) => { + x.age += 1 + x.name = "Sarah" +} + +changeAge(person) +changeAgeAndName() + +console.log(person) +``` + +- A: `{name: "Sarah", age: 22}` +- B: `{name: "Sarah", age: 23}` +- C: `{name: "Lydia", age: 22}` +- D: `{name: "Lydia", age: 23}` + +
答案 +

+ +#### 答案: C + +函數 `changeAge` 和函數 `changeAgeAndName` 有著不同的參數,定義一個 _新_ 生成的物件 `{ ...person }`。這個物件有著所有 `person` 物件 中 k/v 值的副本。 + +首項, 我們呼叫 `changeAge` 函數並傳遞 `person` 物件作為它的參數。這個函數對 `age` 屬性進行加一操作。 `person` 現在是 `{ name: "Lydia", age: 22 }`。 + +然後,我們呼叫函數 `changeAgeAndName` ,然而我們沒有傳遞參數。取而代之,`x` 的值等價 _new_ 生成的物件: `{ ...person }`。因為它是一個新生成的物件,它並不會對物件 `person` 造成任何副作用。 `person` 仍然等價於 `{ name: "Lydia", age: 22 }`。 + +

+
+ +--- +###### 117. 下面哪個選項會回傳 `6`? + +```javascript +function sumValues(x, y, z) { + return x + y + z; +} +``` + +- A: `sumValues([...1, 2, 3])` +- B: `sumValues([...[1, 2, 3]])` +- C: `sumValues(...[1, 2, 3])` +- D: `sumValues([1, 2, 3])` + +
答案 +

+ +#### 答案: C + +通過展開語法 `...`,我們可以 _展開_ 單個可迭代的元素。函數 `sumValues` function 接收三個參數: `x`, `y` 和 `z`。 `...[1, 2, 3]` 的執行結果為 `1, 2, 3`,將會傳遞給函數 `sumValues`。 + +

+
+ +--- +###### 118. 將會輸出什麽內容? + +```javascript +let num = 1; +const list = ["🥳", "🤠", "🥰", "🤪"]; + +console.log(list[(num += 1)]); +``` + +- A: `🤠` +- B: `🥰` +- C: `SyntaxError` +- D: `ReferenceError` + +
答案 +

+ +#### 答案: B + +透過 `+=` 運算子,我們對變數 `num` 進行加 `1` 操作。 `num` 有初始值 `1`,因此 `1 + 1` 的執行結果為 `2`。陣列 `list` 的第二項為 🥰,`console.log(list[2])` 輸出 🥰. + +

+
+ +--- +###### 119. 將會輸出什麽內容? + +```javascript +const person = { + firstName: "Lydia", + lastName: "Hallie", + pet: { + name: "Mara", + breed: "Dutch Tulip Hound" + }, + getFullName() { + return `${this.firstName} ${this.lastName}`; + } +}; + +console.log(person.pet?.name); +console.log(person.pet?.family?.name); +console.log(person.getFullName?.()); +console.log(member.getLastName?.()); +``` + +- A: `undefined` `undefined` `undefined` `undefined` +- B: `Mara` `undefined` `Lydia Hallie` `undefined` +- C: `Mara` `null` `Lydia Hallie` `null` +- D: `null` `ReferenceError` `null` `ReferenceError` + +
答案 +

+ +#### 答案: B + +通過ES10 或TS3.7+[可選鏈運算子`?.`](https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Operators/%E5%8F%AF% E9%80%89%E9%93%BE),我們不再需要顯式檢測更深層的嵌套值是否有效。如果我們嘗試存取 `undefined` 或 `null` 的值 (_nullish_),表達將會短路並返回 `undefined`. + +`person.pet?.name`: `person` 有一個名為 `pet` 的屬性: `person.pet` 不是 nullish。它有個名為 `name` 的屬性,並返回字串 `Mara`。 +`person.pet?.family?.name`: `person` 有一個名為`pet` 的屬性: `person.pet` 不是nullish. `pet` _並沒有_ 一個名為`family` 的屬性, ` person.pet.family` 是nullish。表達式返回 `undefined`。 +`person.getFullName?.()`: `person` 有一個名為 `getFullName` 的屬性: `person.getFullName()` 不是 nullish 並可以被呼叫,返回字串 `Lydia Hallie`。 +`member.getLastName?.()`: `member` is not defined: `member.getLastName()` is nullish. The expression returns `undefined`. + +

+
+ +--- +###### 120. 將會輸出什麽內容? + +```javascript +const groceries = ["banana", "apple", "peanuts"]; + +if (groceries.indexOf("banana")) { + console.log("We have to buy bananas!"); +} else { + console.log(`We don't have to buy bananas!`); +} +``` + +- A: We have to buy bananas! +- B: We don't have to buy bananas +- C: `undefined` +- D: `1` + +
答案 +

+ +#### 答案: B + +我們傳遞了一個狀態 `groceries.indexOf("banana")` 給if語法。 `groceries.indexOf("banana")` 回傳 `0`, 一個 falsy 的值。因為if語法的狀態為 falsy,`else` 塊區內的代碼執行,並且 `We don't have to buy bananas!` 被輸出. +

From 2baed1a28d3efdd57115f052799a73dbf5c1615a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=AF=AB=E8=A9=A9=E7=BE=8A?= Date: Mon, 5 Jul 2021 01:55:04 +0800 Subject: [PATCH 082/193] Translation zh-TW answer 120 ~ 155 --- zh-TW/README_zh-TW.md | 1325 +++++++++++++++++++++++++++++++++++++++-- 1 file changed, 1260 insertions(+), 65 deletions(-) diff --git a/zh-TW/README_zh-TW.md b/zh-TW/README_zh-TW.md index 628edef6..347488e3 100644 --- a/zh-TW/README_zh-TW.md +++ b/zh-TW/README_zh-TW.md @@ -44,7 +44,7 @@ sayHi() #### 答案:D -在函式內部,我們首先透過 `var` 關鍵字宣告了 `name` 變數。這表示變數被提升了(記憶體位置在創建時期就被設置好了),直到程式執行到定義變數的那行之前,預設值都是 `undefined`。因為當我們印出 `name` 變數時,還沒有執行到定義變數的那一行程式碼,因此變數的值保持為 `undefined`。 +在函式內部,我們首先透過 `var` 關鍵字宣告了 `name` 變數。這表示變數被提升了(記憶體位置在建立時期就被設置好了),直到程式執行到定義變數的那行之前,預設值都是 `undefined`。因為當我們印出 `name` 變數時,還沒有執行到定義變數的那一行程式碼,因此變數的值保持為 `undefined`。 透過 `let` 和 `const` 關鍵字宣告的變數也會提升,但是和 `var` 不同,它們不會被初始化,在我們初始化之前是不能訪問它們的,這個行為被稱之為暫時性死區。當我們嘗試在初始化之前訪問它們時,JavaScript 將會抛出一個 `ReferenceError` 錯誤。 @@ -302,7 +302,7 @@ console.log(greetign) #### 答案:A -程式碼印出了一個物件,這是因為我們在全域物件上創建了一個空物件!當我們將 `greeting` 寫錯成 `greetign` 時,JS 解譯器實際上將它視爲 `global.greetign = {}` (或者在瀏覽器中視為 `window.greetign = {}`)。 +程式碼印出了一個物件,這是因為我們在全域物件上建立了一個空物件!當我們將 `greeting` 寫錯成 `greetign` 時,JS 解譯器實際上將它視爲 `global.greetign = {}` (或者在瀏覽器中視為 `window.greetign = {}`)。 為了避免這個狀況,我們可以使用 `"use strict"`,來確保當你宣告變數時,必須賦值。 @@ -977,7 +977,7 @@ WebAPI 不能隨時向堆疊内新增内容。相反,它會將回呼函式彈 #### 答案: A 輸出內容是 `p` 及 `div`。在事件傳播(event propagation) 期間,分為三個階段:捕獲(capturing),目標(target) 和冒泡(bubbling)。 -默認情況下,事件處理(event handlers) 在冒泡階段執行(除非您將useCapture設置為true)。 它從巢狀元素的最深層向外層。 +預設情況下,事件處理(event handlers) 在冒泡階段執行(除非您將useCapture設置為true)。 它從巢狀元素的最深層向外層。

@@ -1035,7 +1035,7 @@ console.log(typeof sayHi()); #### 答案: B -`sayHi` 函數會返回立即執行函式表示式(IIFE)的返回值。 該函數返回類型為 `"number"` 的 `0`。 +`sayHi` 函數會回傳立即執行函式表示式(IIFE)的回傳值。 該函數回傳類型為 `"number"` 的 `0`。 FYI: JS只有7種原生類型(type) : `null`, `undefined`, `boolean`, `number`, `string`, `object`, `symbol`, 和 `bigint`. `"function"` 不是一種類型而是物件。

@@ -1096,8 +1096,8 @@ console.log(typeof typeof 1); #### 答案: B -`typeof 1` 返回 `"number"` -`typeof "number"` 返回 `"string"` +`typeof 1` 回傳 `"number"` +`typeof "number"` 回傳 `"string"`

@@ -1162,7 +1162,7 @@ console.log(numbers); 接著我們將此區塊變數 `x` 設置為等於 `1`,並設置變數 `y` 的值, 現在我們 console.log 區塊變數 `x`,無意外地它輸出 `1`。 -而在 `catch` 區塊之外的 `x` 仍然是 `undefined` 且 `y` 是 `2`。 因此當我們想在 `catch` 區塊之外使用 `console.log(x)` 時,它返回 `undefined`,而 `y` 返回 `2`。 +而在 `catch` 區塊之外的 `x` 仍然是 `undefined` 且 `y` 是 `2`。 因此當我們想在 `catch` 區塊之外使用 `console.log(x)` 時,它回傳 `undefined`,而 `y` 回傳 `2`。

@@ -1243,18 +1243,18 @@ Primitive 不同於 object 的是它沒有任何的屬性(properties) 和方法( #### 答案: B -`null` 是 falsy. `!null` 返回 `true`. `!true` 返回 `false`. +`null` 是 falsy. `!null` 回傳 `true`. `!true` 回傳 `false`. -`""` 是 falsy. `!""` 返回 `true`. `!true` 返回 `false`. +`""` 是 falsy. `!""` 回傳 `true`. `!true` 回傳 `false`. -`1` 是 truthy. `!1` 返回 `false`. `!false` 返回 `true`. +`1` 是 truthy. `!1` 回傳 `false`. `!false` 回傳 `true`.

--- -###### 42. 在瀏覽器中 `setInterval` 方法會返回什麼? +###### 42. 在瀏覽器中 `setInterval` 方法會回傳什麼? ```javascript setInterval(() => console.log('Hi'), 1000); @@ -1270,14 +1270,14 @@ setInterval(() => console.log('Hi'), 1000); #### 答案: A -會返回一個唯一的 id,並可用於 `clearInterval()` 以清除該 interval。 +會回傳一個唯一的 id,並可用於 `clearInterval()` 以清除該 interval。

--- -###### 43. 將會返回何種結果? +###### 43. 將會回傳何種結果? ```javascript [...'Lydia']; @@ -1324,21 +1324,21 @@ console.log(gen.next().value); #### 答案: C -一般函式不能在被呼叫後中途停止。但是, generator 可以在中途 "停止" 且之後可以從停止的位置繼續運行。 +一般函式不能在被呼叫後中途停止。但是, generator 可以在中途 "停止" 且之後可以從停止的位置繼續執行。 每當一個 generator 函式遇到一個 `yield` 關鍵字時,該函式就會產生其後指定的值。 請注意,在這種情況下,generator 函式不是 _return_ 值,而是 _yields_ 值。 首先,我們使用等於 "10" 的 "i" 初始化 generator 函式。 我們使用 "next()" 方法呼叫 generator 函式。 第一次呼叫 generator 函式時, "i" 等於 "10"。 它遇到第一個 `yield` 關鍵字:它產生 `i` 的值。 現在,generator 已 "暫停", 並且記錄了 "10"。 然後,我們使用 `next()` 方法再次呼叫該函式。 它將從先前停止的地方繼續,仍然是 "i" 等於 "10"。 現在,它遇到下一個 `yield` 關鍵字,並產生 `i * 2` 。 -"i" 等於 "10",因此返回 "10 * 2",即 "20"。 故結果為10、20。 +"i" 等於 "10",因此回傳 "10 * 2",即 "20"。 故結果為10、20。

--- -###### 45. 將會返回何種結果? +###### 45. 將會回傳何種結果? ```javascript const firstPromise = new Promise((res, rej) => { @@ -1486,7 +1486,7 @@ const num = parseInt('7*6', 10); #### 答案: C -僅會返回字串中的第一個數字。 基於 _radix_ (第二個參數,用於指定我們要將其解析為哪種類型的數字:以10為基數,十六進制,八進制,二進制等),`parseInt` 檢查字串中的字元是否有效。 +僅會回傳字串中的第一個數字。 基於 _radix_ (第二個參數,用於指定我們要將其解析為哪種類型的數字:以10為基數,十六進制,八進制,二進制等),`parseInt` 檢查字串中的字元是否有效。 一旦遇到基數中無效數字的字元,它將停止解析並忽略以下字元。 `*` 不是合法的 `number`,所以程式僅將字串形態的 `"7"` 轉換至 decimal 形態的 `7`,故 `num` 現在的值為 `7`。 @@ -1515,10 +1515,10 @@ const num = parseInt('7*6', 10); #### 答案: C -當對陣列做映射(map) 時,`num` 的值等同於它當前正在循環的元素。在這種情況中元素均為 numbers,所以條件式 `typeof num === "number"` 會返回 `true` 的值。 -map 函式會建立一個新陣列,並插入該函式返回的值。 +當對陣列做映射(map) 時,`num` 的值等同於它當前正在循環的元素。在這種情況中元素均為 numbers,所以條件式 `typeof num === "number"` 會回傳 `true` 的值。 +map 函式會建立一個新陣列,並插入該函式回傳的值。 -但是我們不返回任何值。當我們不從函式返回值時,函式將返回 `undefined`。由於陣列中的每個元素都會呼叫該函式,因此對於每個元素,我們都返回 `undefined`。 +但是我們不回傳任何值。當我們不從函式回傳值時,函式將回傳 `undefined`。由於陣列中的每個元素都會呼叫該函式,因此對於每個元素,我們都回傳 `undefined`。

@@ -1626,7 +1626,7 @@ console.log(myCar.make); #### 答案: B -當您返回屬性(property) 時,該屬性的值等於 _returned_ 的值,而不是在函式建構式(constructor function)中設置的值。 我們返回字串 `Maserati`,因此 `mycar.make` 等於 `Maserati`。 +當您回傳屬性(property) 時,該屬性的值等於 _returned_ 的值,而不是在函式建構式(constructor function)中設置的值。 我們回傳字串 `Maserati`,因此 `mycar.make` 等於 `Maserati`。

@@ -1664,10 +1664,10 @@ let x = y; 當我們將 `y `設置為等於 `10` 時,我們實際上將屬性 `y` 加入到 global object 中(瀏覽器中的 `window`,Node中的 `global`)。 現在,瀏覽器中 `window.y` 現在等於 `10`。 接著我們宣告一個變數 `x`,並將其值賦予為 `y`,即 `10`。 用` let` 關鍵字宣告的變數是 _block scoped_ ,它們僅在宣告它們的區塊中定義; 另外此案例的函示是,立即函示表達式(IIFE)。 -當我們使用 `typeof` 運算子時, `x` 並未被定義:我們試圖在宣告它的區塊外訪問 `x`。這將獲得 `x` 並未被定義的結果。 未分配值或未宣告的值的類型為 `"undefined"`。 `console.log(typeof x)` 返回 `"undefined"`。 +當我們使用 `typeof` 運算子時, `x` 並未被定義:我們試圖在宣告它的區塊外訪問 `x`。這將獲得 `x` 並未被定義的結果。 未分配值或未宣告的值的類型為 `"undefined"`。 `console.log(typeof x)` 回傳 `"undefined"`。 -但是,當將 `y` 設置為 `10` 時,我們創建了global variable `y`。 在我們程式中的任何位置均可訪問此值。 -`y` 被定義,並且為類型 `number` 的值。 因此 `console.log(typeof y` 返回 `"number"`。 +但是,當將 `y` 設置為 `10` 時,我們建立了global variable `y`。 在我們程式中的任何位置均可訪問此值。 +`y` 被定義,並且為類型 `number` 的值。 因此 `console.log(typeof y` 回傳 `"number"`。

@@ -1799,9 +1799,9 @@ console.log(delete age); #### 答案: A -`delete` 運算子會返回一個布林值: 成功刪除物件的情況下會返回 `true`,反之則為 `false`。 但是經由 `var`,`const` 或是 `let` 關鍵字所宣告的變數是無法使用 `delete` 運算子刪除的。 +`delete` 運算子會回傳一個布林值: 成功刪除物件的情況下會回傳 `true`,反之則為 `false`。 但是經由 `var`,`const` 或是 `let` 關鍵字所宣告的變數是無法使用 `delete` 運算子刪除的。 -此處, `name` 無法成功刪除且會返回 `fasle`,因為它是經由 `const` 所宣告。當我們宣告 `age` 的值為 `21` 時,實際上我們做的是將一個名為 `age` 的屬性為添加到了全球物件中,您可以透過 `delete` 來刪除物件中的屬性,因此您也能刪除全球物件中的屬性,故將返回 `true`。 +此處, `name` 無法成功刪除且會回傳 `fasle`,因為它是經由 `const` 所宣告。當我們宣告 `age` 的值為 `21` 時,實際上我們做的是將一個名為 `age` 的屬性為添加到了全球物件中,您可以透過 `delete` 來刪除物件中的屬性,因此您也能刪除全球物件中的屬性,故將回傳 `true`。

@@ -1870,7 +1870,7 @@ console.log(admin); #### 答案: B 使用 spread 運算子可以合併物件(`...`)。它使您可以建立一個物件的鍵/值的複製,並將其添加到另一物件中。 -在這裡我們創建了 `user` 物件的複製並將其添加至 `admin` 物件。因此將輸出 `{ admin: true, name: "Lydia", age: 21 }`。 +在這裡我們建立了 `user` 物件的複製並將其添加至 `admin` 物件。因此將輸出 `{ admin: true, name: "Lydia", age: 21 }`。

@@ -1937,7 +1937,7 @@ console.log(data); 如果替換者是 _陣列_ ,僅將陣列中包含的屬性名稱加到 JSON 字串中。 此案例中,僅有 `"level"` and `"health"` 被包含,`"username"` 沒有被包含在內,因此 `data` 的值將為 `"{"level":19, "health":90}"`。 -如果替換者是 _函式_ ,在要字串化的每個物件屬性上將會呼叫此函式。從此函式返回的值將是加到 JSON 字串中的屬性的值。如果值為 `undefined`,則此屬性從 JSON 字串中排除。 +如果替換者是 _函式_ ,在要字串化的每個物件屬性上將會呼叫此函式。從此函式回傳的值將是加到 JSON 字串中的屬性的值。如果值為 `undefined`,則此屬性從 JSON 字串中排除。

@@ -1969,9 +1969,9 @@ console.log(num2); #### 答案: A -單元運算子 `++` 首先 _返回_ 操作數的值,然後 _遞增_ 操作數的值。 `num1` 的值是 `10`,因為 `increaseNumber` 函式首先返回 `num` 的值,即 `10`,之後才遞增 `num` 的值。 +單元運算子 `++` 首先 _回傳_ 操作數的值,然後 _遞增_ 操作數的值。 `num1` 的值是 `10`,因為 `increaseNumber` 函式首先回傳 `num` 的值,即 `10`,之後才遞增 `num` 的值。 -`num2` 是 `10`, 因為我們將 `num1` 傳遞給了 `increasePassedNumber`。 `number` 等於 `10`( `num1` 的值。同樣,單元運算子 `++` 首先 _返回_ 操作數的值,然後 _遞增_ 操作數的值。 +`num2` 是 `10`, 因為我們將 `num1` 傳遞給了 `increasePassedNumber`。 `number` 等於 `10`( `num1` 的值。同樣,單元運算子 `++` 首先 _回傳_ 操作數的值,然後 _遞增_ 操作數的值。 `number` 的值是 `10`,因此 `num2` 等於 `10`。

@@ -2006,7 +2006,7 @@ multiply(value); 在ES6中,我們可以使用預設值初始化參數。如果沒有其他值傳遞給該函式或是傳入的參數是 `undefined`,則該參數的值為預設值。此案例中,我們將 `value` 物件的屬性擴展到一個新物件中,因此 `x` 具有預設值 `{number:10}`。 -預設值是在 _呼叫_ 時被 evaluated。每次呼叫該函式時,都會創建一個 _新_ 物件。我們在沒有傳遞值的情況下呼叫了 `multiply` 函式兩次:`x` 的預設值是 `{{number:10}`。因此,我們輸出該數字的相乘值,即 `20`。 +預設值是在 _呼叫_ 時被 evaluated。每次呼叫該函式時,都會建立一個 _新_ 物件。我們在沒有傳遞值的情況下呼叫了 `multiply` 函式兩次:`x` 的預設值是 `{{number:10}`。因此,我們輸出該數字的相乘值,即 `20`。 第三次呼叫時,我們確實傳遞了一個參數:名為 `value` 的物件。 `*=` 運算子實際上是 `x.number = x.number * 2` 的簡寫:因此我們修改了 `x.number` 的值,並記錄相乘後的值 `20`。 @@ -2035,15 +2035,15 @@ multiply(value); `reduce` 方法接收的第一個參數是 _累加器(accumulator)_ ,在這種情況下是 `x`。 第二個參數是 _current value_ `y`。 使用 `reduce` 方法,我們對陣列中的每個元素執行一個 callback 函式,並在最終回一個值。 -在此示例中,我們不返回任何值,僅記錄了累加器的值和當前值。 +在此示例中,我們不回傳任何值,僅記錄了累加器的值和當前值。 -累加器的值等於 callback 函式先前返回的值。 如果沒有 `initialValue` 參數傳遞給 `reduce` 方法,則累加器的初始值將會等於第一個元素。 +累加器的值等於 callback 函式先前回傳的值。 如果沒有 `initialValue` 參數傳遞給 `reduce` 方法,則累加器的初始值將會等於第一個元素。 -在第一個呼叫中,累加器(`x`)為`1`,當前值(`y`)為`2`。 我們不從 callback 函式返回,而是輸出累加器和當前值:`1` 和 `2`。 +在第一個呼叫中,累加器(`x`)為`1`,當前值(`y`)為`2`。 我們不從 callback 函式回傳,而是輸出累加器和當前值:`1` 和 `2`。 -如果您不從 callback 函式返回值,則它將返回 `undefined`。 在下一次呼叫時,累加器為 `undefined`,當前值為 `3`。 於是 `undefined` 和 `3` 被輸出。 +如果您不從 callback 函式回傳值,則它將回傳 `undefined`。 在下一次呼叫時,累加器為 `undefined`,當前值為 `3`。 於是 `undefined` 和 `3` 被輸出。 -在第四次呼叫中,我們再次不從 callback 函式返回。 累加器再次為 `undefined`,當前值為 `4`。於是 `undefined` 和 `4` 被輸出。 +在第四次呼叫中,我們再次不從 callback 函式回傳。 累加器再次為 `undefined`,當前值為 `4`。於是 `undefined` 和 `4` 被輸出。

@@ -2240,7 +2240,7 @@ console.log(/* 2 */); // JavaScript 也愛你 ❤️ `startGame()` 函數會一行一行執行直到遇到 `yield` 關鍵字,在函數裡第一個就有一個 `yield` 關鍵字:所以執行到第一行就停止了! _此時answer變數還尚未定義_ -當我們呼叫 `game.next("Yes").value`,前一個 `yield` 被傳遞給 `next()` 的參數值所取代。此例我們使用 `Yes`。變數 `answer` 的值現在等於 `Yes`。 if 語句的條件返回 `false`,並且會返回 `JavaScript 也愛你 ❤️` 。 +當我們呼叫 `game.next("Yes").value`,前一個 `yield` 被傳遞給 `next()` 的參數值所取代。此例我們使用 `Yes`。變數 `answer` 的值現在等於 `Yes`。 if 語句的條件回傳 `false`,並且會回傳 `JavaScript 也愛你 ❤️` 。

@@ -2303,7 +2303,7 @@ console.log(data); #### 答案: C -一個異步函數總是返回一個 promise 。 `await` 仍然要等待 promise 的 resolve:當我們呼叫 `getData()` 等於 `data` 時,會得到一個等待的 promise。 +一個異步函數總是回傳一個 promise 。 `await` 仍然要等待 promise 的 resolve:當我們呼叫 `getData()` 等於 `data` 時,會得到一個等待的 promise。 如果我們想獲取 resolve 後的值`"I made it"`,我們可以在`data`上使用`.then()`函數: @@ -2339,7 +2339,7 @@ console.log(result); `.push()`函數回傳的是陣列的長度!原本陣列包含一個元素(字串`"香蕉"`),長度為`1`。後來將字串 `"apple"` 加到陣列中後,陣列包含兩個元素。所以會從`addToList`函數中得到,長度為 `"2"`。 -`push`函數修改了原來的陣列。如果你想從函數中返回 _陣列_ 而不是 _陳列的長度_ ,你應該在加完`item`到陣列後,回傳`list`。 +`push`函數修改了原來的陣列。如果你想從函數中回傳 _陣列_ 而不是 _陳列的長度_ ,你應該在加完`item`到陣列後,回傳`list`。

@@ -2427,7 +2427,7 @@ function sum(a, b) { 純函數一種若輸入參數相同,則永遠會得到相同輸出的函數。 -在特定情況下,即使輸入相同參數,也不能得到相同的返回值: +在特定情況下,即使輸入相同參數,也不能得到相同的回傳值:
 var a = b = {}
@@ -2544,7 +2544,7 @@ console.log(list)
 
 #### 答案: C
 
-陣列元素可以包含任何值。數字,字符,布爾,物件,陣列,`null`,`undeifned`, 以及其他表達式,如日期,函數和計算式。
+陣列元素可以包含任何值。數字,字符,布林,物件,陣列,`null`,`undeifned`, 以及其他表達式,如日期,函數和計算式。
 
 元素將等於回傳的值。 `1 + 2`回傳`3`,`1 * 2`回傳'2`,'1 / 2`回傳`0.5`。
 
@@ -2651,7 +2651,7 @@ console.log(person)
 
 然後,我們將`city`設置為等於字串`“Amsterdam”`。這不會更改person物件:沒有對該物件的引用。
 
-因此輸出`person`物件時,會返回未修改的物件。
+因此輸出`person`物件時,會回傳未修改的物件。
 
 

@@ -2699,7 +2699,7 @@ fetch('https://www.website.com/api/user/1') - A: `fetch`函數的結果 - B: 第二次呼叫`fetch`函數的結果 -- C: 前一個`.then()`中回傳函數返回的結果 +- C: 前一個`.then()`中回傳函數回傳的結果 - D: 總是`undefined`
答案 @@ -2707,7 +2707,7 @@ fetch('https://www.website.com/api/user/1') #### 答案: C -第二個`.then`中`res`的值等於前一個`.then`中函數返回的值。你可以像這樣繼續連接`.then`,將值傳遞給下一個處理程序。 +第二個`.then`中`res`的值等於前一個`.then`中函數回傳的值。你可以像這樣繼續連接`.then`,將值傳遞給下一個處理程序。

@@ -2731,13 +2731,13 @@ function getName(name) { #### 答案: A -使用邏輯非運算子`!`,將返回一個布林值,使用`!! name`,我們可以確定`name`的值是`true`還是`false`。如果`name`是`true`,那麼`!name`返回`false`。 `!false`返回`true`。 +使用邏輯非運算子`!`,將回傳一個布林值,使用`!! name`,我們可以確定`name`的值是`true`還是`false`。如果`name`是`true`,那麼`!name`回傳`false`。 `!false`回傳`true`。 通過將`hasName`設置為`name`,可以將`hasName`設置為等於傳遞給`getName`函數的值,而不是布林值`true`。 -`new Boolean(true)`返回一個物件包裝器,而不是布林值本身。 +`new Boolean(true)`回傳一個物件包裝器,而不是布林值本身。 -`name.length`返回傳遞的參數的長度,而不是布林值`true`。 +`name.length`回傳傳遞的參數的長度,而不是布林值`true`。

@@ -2787,7 +2787,7 @@ sum(10) #### 答案: B -您可以將預設參數的值設置為函數的另一個參數,只要另一個參數定義在其之前即可。我們將值`10`傳遞給`sum`函數。如果`sum`函數只接收1個參數,則意味著沒有傳遞`num2`的值,這種情況下,`num1`的值等於傳遞的值`10`。 `num2`的預設值是`num1`的值,即`10`。 ```num1 + num2```返回`20`。 +您可以將預設參數的值設置為函數的另一個參數,只要另一個參數定義在其之前即可。我們將值`10`傳遞給`sum`函數。如果`sum`函數只接收1個參數,則意味著沒有傳遞`num2`的值,這種情況下,`num1`的值等於傳遞的值`10`。 `num2`的預設值是`num1`的值,即`10`。 ```num1 + num2```回傳`20`。 如果您嘗試將預設參數的值設置為後面定義的參數,則可能導致參數的值尚未初始化,從而引發錯誤。比如: ```js @@ -2826,7 +2826,7 @@ console.log(data) #### 答案: A -使用`import * as name`語法,我們將`module.js`文件中所有`export`匯入到`index.js`文件中,並且建立了一個名為`data`的新物件。在`module.js`文件中,有兩個匯出:預設匯出和命名匯出。預設匯出是一個返回字串“Hello World”的函數,命名匯出是一個名為`name`的變數,其值為字串`“Lydia”`。 +使用`import * as name`語法,我們將`module.js`文件中所有`export`匯入到`index.js`文件中,並且建立了一個名為`data`的新物件。在`module.js`文件中,有兩個匯出:預設匯出和命名匯出。預設匯出是一個回傳字串“Hello World”的函數,命名匯出是一個名為`name`的變數,其值為字串`“Lydia”`。 `data`物件具有預設匯出的`default`屬性,其他屬性具有指定exports的名稱及其對應的值。 @@ -2865,7 +2865,7 @@ function Person() { } ``` -透過`new`來呼叫建構函數,將會產生建構函數`Person`的實例,對實例執行`typeof`關鍵字將返回`"object"`,上述情況輸出`"object"`。 +透過`new`來呼叫建構函數,將會產生建構函數`Person`的實例,對實例執行`typeof`關鍵字將回傳`"object"`,上述情況輸出`"object"`。

@@ -3033,7 +3033,7 @@ console.log(nums(1, 2)) a + b ``` -這意味著永遠不會到達`a + b`,因為函數在`return`關鍵字之後停止運行。如果沒有回傳值,就像這裡,函數回傳`undefined`。注意,在`if/else`語法之後沒有自動插入! +這意味著永遠不會到達`a + b`,因為函數在`return`關鍵字之後停止執行。如果沒有回傳值,就像這裡,函數回傳`undefined`。注意,在`if/else`語法之後沒有自動插入!

@@ -3098,7 +3098,7 @@ console.log(Object.keys(info)) #### 答案: D -`Symbol`類型是不可枚舉的。 `Object.keys`函數回傳物件上的所有可枚舉的鍵屬性。 `Symbol`類型是不可見的,並返回一個空陣列。記錄整個物件時,所有屬性都是可見的,甚至是不可枚舉的屬性。 +`Symbol`類型是不可枚舉的。 `Object.keys`函數回傳物件上的所有可枚舉的鍵屬性。 `Symbol`類型是不可見的,並回傳一個空陣列。記錄整個物件時,所有屬性都是可見的,甚至是不可枚舉的屬性。 這是`Symbol`的眾多特性之一:除了表示完全唯一的值(防止物件意外名稱衝突,例如當使用2個想要向同一物件添加屬性的庫時),您還可以`隱藏`這種方式物件的屬性(儘管不完全。你仍然可以使用`Object.getOwnPropertySymbols()`函數存取`Symbol`。 @@ -3330,9 +3330,9 @@ Promise.resolve(5) #### 答案: C -我們可以將我們想要的任何類型的值傳遞`Promise.resolve`,無論是否`promise`。該函數本身返回帶有已解析值的`Promise` (``)。如果您傳遞正規式函數,它將是具有正規式值的已解決`promise`。如果你通過了promise,它將是一個已經resolved的且帶有傳的值的promise。 +我們可以將我們想要的任何類型的值傳遞`Promise.resolve`,無論是否`promise`。該函數本身回傳帶有已解析值的`Promise` (``)。如果您傳遞正規式函數,它將是具有正規式值的已解決`promise`。如果你通過了promise,它將是一個已經resolved的且帶有傳的值的promise。 -上述情況,我們傳了數字5,因此返回一個resolved狀態的promise,resolve值為`5` +上述情況,我們傳了數字5,因此回傳一個resolved狀態的promise,resolve值為`5`

@@ -3366,11 +3366,11 @@ compareMembers(person) 物件通過參考位址傳遞。當我們檢查物件的嚴格相等性(===)時,我們正在比較它們的參考位址。 -我們將“person2”的預設值設置為“person”物件,並將“person”對像作為“person1”的值傳遞。 +我們將“person2”的預設值設置為“person”物件,並將“person”物件作為“person1”的值傳遞。 -這意味著兩個值都引用內存中的同一位置,因此它們是相等的。 +這意味著兩個值都引用緩存中的同一位置,因此它們是相等的。 -運行“ else”語句中的代碼塊,並記錄`They are the same!` 。 +執行“ else”語句中的代碼塊,並記錄`They are the same!` 。

@@ -3429,7 +3429,7 @@ console.log('❤️' === '❤️') #### 答案: A -在內部,表情符號是unicode。 heat表情符號的unicode是`“ U + 2764 U + FE0F”`。對於相同的表情符號,它們總是相同的,因此我們將兩個相等的字串相互比較,這將返回true。 +在內部,表情符號是unicode。 heat表情符號的unicode是`“ U + 2764 U + FE0F”`。對於相同的表情符號,它們總是相同的,因此我們將兩個相等的字串相互比較,這將回傳true。

@@ -3519,7 +3519,7 @@ JSON.parse() const jsonNumber = JSON.stringify(4) // '4' JSON.parse(jsonNumber) // 4 -// 將數組值字串化為有效的JSON,然後將JSON字串解析為JavaScript值: +// 將陣列值字串化為有效的JSON,然後將JSON字串解析為JavaScript值: const jsonArray = JSON.stringify([1, 2, 3]) // '[1, 2, 3]' JSON.parse(jsonArray) // [1, 2, 3] @@ -3604,14 +3604,14 @@ console.log(two.next().value) 透過`yield` 關鍵字, 我們在`Generator` 函數裡執行`yield`語法. 透過`yield*` 關鍵字, 我們可以在一個`Generator` 函數裡面執行(`yield`語法)另一個`Generator ` 函數, 或可遍歷的物件(如陣列). -在函數 `generatorOne` 中, 我們透過 `yield` 關鍵字 yield 了一個完整的陣列 `['a', 'b', 'c']`。函數`one`透過`next`方法返回的物件的`value` 屬性的值 (`one.next().value`) 等價於陣列 `['a', 'b', 'c']`. +在函數 `generatorOne` 中, 我們透過 `yield` 關鍵字 yield 了一個完整的陣列 `['a', 'b', 'c']`。函數`one`透過`next`方法回傳的物件的`value` 屬性的值 (`one.next().value`) 等價於陣列 `['a', 'b', 'c']`. ```javascript console.log(one.next().value) // ['a', 'b', 'c'] console.log(one.next().value) // undefined ``` -在函數 `generatorTwo` 中, 我們使用 `yield*` 關鍵字。就相當於函數`two`第一個`yield`的值, 等價於在迭代器中第一個 `yield` 的值。陣列`['a', 'b', 'c']`就是這個迭代器. 第一個`yield` 的值就是`a`, 所以我們第一次調用`two.next().value`時, 就返回`a`。 +在函數 `generatorTwo` 中, 我們使用 `yield*` 關鍵字。就相當於函數`two`第一個`yield`的值, 等價於在迭代器中第一個 `yield` 的值。陣列`['a', 'b', 'c']`就是這個迭代器. 第一個`yield` 的值就是`a`, 所以我們第一次呼叫`two.next().value`時, 就回傳`a`。 ```javascript console.log(two.next().value) // 'a' @@ -3830,11 +3830,11 @@ console.log(member.getLastName?.()); #### 答案: B -通過ES10 或TS3.7+[可選鏈運算子`?.`](https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Operators/%E5%8F%AF% E9%80%89%E9%93%BE),我們不再需要顯式檢測更深層的嵌套值是否有效。如果我們嘗試存取 `undefined` 或 `null` 的值 (_nullish_),表達將會短路並返回 `undefined`. +通過ES10 或TS3.7+[可選鏈運算子`?.`](https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Operators/%E5%8F%AF% E9%80%89%E9%93%BE),我們不再需要顯式檢測更深層的嵌套值是否有效。如果我們嘗試存取 `undefined` 或 `null` 的值 (_nullish_),表達將會短路並回傳 `undefined`. -`person.pet?.name`: `person` 有一個名為 `pet` 的屬性: `person.pet` 不是 nullish。它有個名為 `name` 的屬性,並返回字串 `Mara`。 -`person.pet?.family?.name`: `person` 有一個名為`pet` 的屬性: `person.pet` 不是nullish. `pet` _並沒有_ 一個名為`family` 的屬性, ` person.pet.family` 是nullish。表達式返回 `undefined`。 -`person.getFullName?.()`: `person` 有一個名為 `getFullName` 的屬性: `person.getFullName()` 不是 nullish 並可以被呼叫,返回字串 `Lydia Hallie`。 +`person.pet?.name`: `person` 有一個名為 `pet` 的屬性: `person.pet` 不是 nullish。它有個名為 `name` 的屬性,並回傳字串 `Mara`。 +`person.pet?.family?.name`: `person` 有一個名為`pet` 的屬性: `person.pet` 不是nullish. `pet` _並沒有_ 一個名為`family` 的屬性, ` person.pet.family` 是nullish。表達式回傳 `undefined`。 +`person.getFullName?.()`: `person` 有一個名為 `getFullName` 的屬性: `person.getFullName()` 不是 nullish 並可以被呼叫,回傳字串 `Lydia Hallie`。 `member.getLastName?.()`: `member` is not defined: `member.getLastName()` is nullish. The expression returns `undefined`.

@@ -3869,3 +3869,1198 @@ if (groceries.indexOf("banana")) { --- +###### 121. 將會輸出什麽內容? + +```javascript +const config = { + languages: [], + set language(lang) { + return this.languages.push(lang); + } +}; + +console.log(config.language); +``` + +- A: `function language(lang) { this.languages.push(lang }` +- B: `0` +- C: `[]` +- D: `undefined` + +
答案 +

+ +#### 答案: D + +函數 `language` 是一個 `setter`。 Setters 並不保存一個實際值,它們的使命在於 _修改_ 屬性。當呼叫函數 `setter`, 回傳 `undefined`。 + +

+
+ +--- + +###### 122. 將會輸出什麽內容? + +```javascript +const name = "Lydia Hallie"; + +console.log(!typeof name === "object"); +console.log(!typeof name === "string"); +``` + +- A: `false` `true` +- B: `true` `false` +- C: `false` `false` +- D: `true` `true` + +
答案 +

+ +#### 答案: C + +`typeof name` 回傳 `"string"`。字串 `"string"` 是一個 truthy 的值,因此 `!typeof name` 回傳一個布林值 `false`。 `false === "object"` 和 `false === "string"` 都回傳 `false`。 + +(如果我們想檢測一個值的類型,我們應該用 `!==` 而不是 `!typeof`) + +

+
+ +--- +###### 123. 將會輸出什麽內容? + +```javascript +const add = x => y => z => { + console.log(x, y, z); + return x + y + z; +}; + +add(4)(5)(6); +``` + +- A: `4` `5` `6` +- B: `6` `5` `4` +- C: `4` `function` `function` +- D: `undefined` `undefined` `6` + +
答案 +

+ +#### 答案: A + +函數 `add` 是一個回傳 回傳箭頭函數的箭頭函數 的箭頭函數(still with me?)。第一個函數接收一個值為 `4` 的參數 `x`。我們呼叫第二個函數,它接收一個值為 `5` 的參數 `y`。然後我們呼叫第三個函數,它接收一個值為 `6` 的參數 `z`。當我們嘗試在最後一個箭頭函數中獲取 `x`, `y` 和 `z` 的值,JS 引擎根據作用域鏈去找 `x` 和 `y` 的值。得到 `4` `5` `6`. + +

+
+ +--- +###### 124. 將會輸出什麽內容? + +```javascript +async function* range(start, end) { + for (let i = start; i <= end; i++) { + yield Promise.resolve(i); + } +} + +(async () => { + const gen = range(1, 3); + for await (const item of gen) { + console.log(item); + } +})(); +``` + +- A: `Promise {1}` `Promise {2}` `Promise {3}` +- B: `Promise {}` `Promise {}` `Promise {}` +- C: `1` `2` `3` +- D: `undefined` `undefined` `undefined` + +
答案 +

+ +#### 答案: C + +我們給 函數range 傳遞: `Promise{1}`, `Promise{2}`, `Promise{3}`,Generator 函數 `range` 回傳一個全是 async object promise 陣列。我們將 async object 賦值給變數 `gen`,之後我們使用`for await ... of` 進行循環遍歷。我們將回傳的 Promise 實例賦值給 `item`: 第一個回傳 `Promise{1}`, 第二個回傳 `Promise{2}`,之後是 `Promise{3}`。因為我們正 _awaiting_ `item` 的值,resolved 狀態的 promsie,promise陣列的resolved _值_ 以此為: `1`,`2`,`3`. + +

+
+ +--- +###### 125. 將會輸出什麽內容? + +```javascript +const myFunc = ({ x, y, z }) => { + console.log(x, y, z); +}; + +myFunc(1, 2, 3); +``` + +- A: `1` `2` `3` +- B: `{1: 1}` `{2: 2}` `{3: 3}` +- C: `{ 1: undefined }` `undefined` `undefined` +- D: `undefined` `undefined` `undefined` + +
答案 +

+ +#### 答案: D + +`myFunc` 預期接收一個包含 `x`, `y` 和 `z` 屬性的物件作為它的參數。因為我們僅僅傳遞三個單獨的數字值(1, 2, 3) 而不是一個含有`x`, `y` 和`z` 屬性的物件({x: 1, y: 2, z: 3}) , `x`, `y` 和`z` 有著各自的預設值`undefined`. + +

+
+ +--- +###### 126. 將會輸出什麽內容? + +```javascript +function getFine(speed, amount) { + const formattedSpeed = new Intl.NumberFormat({ + 'en-US', + { style: 'unit', unit: 'mile-per-hour' } + }).format(speed) + + const formattedAmount = new Intl.NumberFormat({ + 'en-US', + { style: 'currency', currency: 'USD' } + }).format(amount) + + return `The driver drove ${formattedSpeed} and has to pay ${formattedAmount}` +} + +console.log(getFine(130, 300)) +``` + +- A: The driver drove 130 and has to pay 300 +- B: The driver drove 130 mph and has to pay \$300.00 +- C: The driver drove undefined and has to pay undefined +- D: The driver drove 130.00 and has to pay 300.00 + +
答案 +

+ +#### 答案: B + +通過函數 `Intl.NumberFormat`,我們可以格式化任意區域的數字值。我們對數字值 `130` 進行 `mile-per-hour` 作為 `unit` 的 `en-US` 區域 格式化,結果為 `130 mph`。對數字值 `300` 進行 `USD` 作為 `currentcy` 的 `en-US` 區域格式化,結果為 `$300.00`. + +

+
+ +--- + +###### 127. 將會輸出什麽內容? + +```javascript +const spookyItems = ["👻", "🎃", "🕸"]; +({ item: spookyItems[3] } = { item: "💀" }); + +console.log(spookyItems); +``` + +- A: `["👻", "🎃", "🕸"]` +- B: `["👻", "🎃", "🕸", "💀"]` +- C: `["👻", "🎃", "🕸", { item: "💀" }]` +- D: `["👻", "🎃", "🕸", "[object Object]"]` + +
答案 +

+ +#### 答案: B + +通過解構物件們,我們可以從右手邊的物件中拆出值,並且將拆出的值分配給左手邊物件同名的屬性。在這種情況下,我們將值 "💀" 分配給 `spookyItems[3]`。相當於我們正在篡改陣列 `spookyItems`,我們給它添加了值 "💀"。當輸出 `spookyItems` 時,結果為 `["👻", "🎃", "🕸", "💀"]`。 + +

+
+ +--- + +###### 128. 將會輸出什麽內容? + +```javascript +const name = "Lydia Hallie"; +const age = 21; + +console.log(Number.isNaN(name)); +console.log(Number.isNaN(age)); + +console.log(isNaN(name)); +console.log(isNaN(age)); +``` + +- A: `true` `false` `true` `false` +- B: `true` `false` `false` `false` +- C: `false` `false` `true` `false` +- D: `false` `true` `false` `true` + +
答案 +

+ +#### 答案: C + +通過函數 `Number.isNaN`,你可以檢測你傳遞的值是否為 _數字值_ 並且是否等於 `NaN`。 `name` 不是一個數字值,因此 `Number.isNaN(name)` 回傳 `false`。 `age` 是一個數字值,但它不等於 `NaN`,因此 `Number.isNaN(age)` 回傳 `false`. + +通過函數 `isNaN`, 你可以檢測你傳遞的值是否一個 number。 `name` 不是一個 `number`,因此 `isNaN(name)` 回傳 `true`. `age` 是一個 `number` 因此 `isNaN(age)` 回傳 `false`. + +

+
+ +--- + +###### 129. 將會輸出什麽內容? + +```javascript +const randomValue = 21; + +function getInfo() { + console.log(typeof randomValue); + const randomValue = "Lydia Hallie"; +} + +getInfo(); +``` + +- A: `"number"` +- B: `"string"` +- C: `undefined` +- D: `ReferenceError` + +
答案 +

+ +#### 答案: D + +通過 `const` 關鍵字定義的變數在被初始化之前不可被引用:這被稱之為 _暫時性死區_。在函數 `getInfo` 中, 變數 `randomValue` 定義在`getInfo` 的作用域的此法環境中。在想要對`typeof randomValue` 進行log之前,變數`randomValue` 仍未被初始化: 錯誤`ReferenceError` 被拋出! JS引擎並不會根據作用域鍊網上尋找該變數,因為我們已經在`getInfo`函數中定義了`randomValue` 變數。 + +

+
+ +--- + +###### 130. 將會輸出什麽內容? + +```javascript +const myPromise = Promise.resolve("Woah some cool data"); + +(async () => { + try { + console.log(await myPromise); + } catch { + throw new Error(`Oops didn't work`); + } finally { + console.log("Oh finally!"); + } +})(); +``` + +- A: `Woah some cool data` +- B: `Oh finally!` +- C: `Woah some cool data` `Oh finally!` +- D: `Oops didn't work` `Oh finally!` + +
答案 +

+ +#### 答案: C + +在 `try` 塊區,我們輸出 `myPromise` 變數的 awaited 值: `"Woah some cool data"`。因為`try` 塊區沒有錯誤拋出,`catch` 塊區的代碼並不執行。 `finally` 塊區的代碼 _總是_ 執行,`"Oh finally!"` 被輸出。 + +

+
+ +--- + +###### 131. 將會輸出什麽內容? + +```javascript +const emojis = ["🥑", ["✨", "✨", ["🍕", "🍕"]]]; + +console.log(emojis.flat(1)); +``` + +- A: `['🥑', ['✨', '✨', ['🍕', '🍕']]]` +- B: `['🥑', '✨', '✨', ['🍕', '🍕']]` +- C: `['🥑', ['✨', '✨', '🍕', '🍕']]` +- D: `['🥑', '✨', '✨', '🍕', '🍕']` + +
答案 +

+ +#### 答案: B + +通過函數 `flat`, 我們可以建立一個新的, 已被扁平化的陣列。被扁平化的深度取決於我們傳遞的值。在這個case裡,我們傳遞了值 `1` (並不必要,這是預設值),相當於只有第一層的陣列才會被連接。即這個 case 裡的 `['🥑']` and `['✨', '✨', ['🍕', '🍕']]`。連接這兩個陣列得到結果 `['🥑', '✨', '✨', ['🍕', '🍕']]`. + +

+
+ +--- + +###### 132. 將會輸出什麽內容? + +```javascript +class Counter { + constructor() { + this.count = 0; + } + + increment() { + this.count++; + } +} + +const counterOne = new Counter(); +counterOne.increment(); +counterOne.increment(); + +const counterTwo = counterOne; +counterTwo.increment(); + +console.log(counterOne.count); +``` + +- A: `0` +- B: `1` +- C: `2` +- D: `3` + +
答案 +

+ +#### 答案: D + +`counterOne` 是類 `Counter` 的一個實例。類 Counter 包含一個`count` 屬性在它的建構函數里, 和一個 `increment` 函數。首先,我們通過 `counterOne.increment()` 呼叫函數 `increment` 兩次。現在, `counterOne.count` 為 `2`. + + + +然後,我們建立一個新的變數 `counterTwo` 並將 `counterOne` 的引用地址賦值給它。因為物件受引用地址的影響,我們剛剛建立了一個新的物件,其引用地址和 `counterOne` 的等價。因此它們指向同一塊緩存地址,任何對其的副作用都會影響 `counterTwo`。現在 `counterTwo.count` 為 `2`。 + +我們呼叫 `counterTwo.increment()` 將 `count` 的值設為 `3`。然後,我們輸出 `counterOne` 裡的count,結果為 `3`。 + + + +

+
+ +--- + +###### 133. 將會輸出什麽內容? + +```javascript +const myPromise = Promise.resolve(Promise.resolve("Promise!")); + +function funcOne() { + myPromise.then(res => res).then(res => console.log(res)); + setTimeout(() => console.log("Timeout!", 0)); + console.log("Last line!"); +} + +async function funcTwo() { + const res = await myPromise; + console.log(await res); + setTimeout(() => console.log("Timeout!", 0)); + console.log("Last line!"); +} + +funcOne(); +funcTwo(); +``` + +- A: `Promise! Last line! Promise! Last line! Last line! Promise!` +- B: `Last line! Timeout! Promise! Last line! Timeout! Promise!` +- C: `Promise! Last line! Last line! Promise! Timeout! Timeout!` +- D: `Last line! Promise! Promise! Last line! Timeout! Timeout!` + +
答案 +

+ +#### 答案: D + +首先,我們呼叫 `funcOne`。在函數 `funcOne` 的第一行,我們呼叫`myPromise` promise _異步操作_。當JS引擎在忙於執行 promise,它繼續執行函數 `funcOne`。下一行 _異步操作_ `setTimeout`,其回呼函數被 Web API 呼叫。 (詳情請參考我關於event loop的文章.) + +promise 和 timeout 都是異步操作,函數繼續執行當JS引擎忙於執行promise 和 處理 `setTimeout` 的呼叫。相當於 `Last line!` 首先被輸出, 因為它不是異步操作。執行完 `funcOne` 的最後一行,promise 狀態轉變為 resolved,`Promise!` 被輸出。然而,因為我們呼叫了 `funcTwo()`, 呼叫堆疊不為空,`setTimeout` 的回呼仍不能入堆疊。 + +我們現在處於 `funcTwo`,先 _awaiting_ myPromise。通過 `await` 關鍵字, 我們暫停了函數的執行直到 promise 狀態變為 resolved (或 rejected)。然後,我們輸出 `res` 的 awaited 值(因為 promise 本身回傳一個 promise)。接著輸出 `Promise!`。 + +下一行就是 _異步操作_ `setTimeout`,其回呼函數被 Web API 呼叫。 + +我們執行到函數 `funcTwo` 的最後一行,輸出 `Last line!`。現在,因為 `funcTwo` 出堆疊,呼叫堆疊為空。在事件佇列中等待的回呼函數(`() => console.log("Timeout!")` from `funcOne`, and `() => console.log("Timeout!")` from `funcTwo`)以此入堆疊。第一個回呼輸出 `Timeout!`,並出堆疊。然後,第二個回呼輸出 `Timeout!`,並出堆疊。得到結果 `Last line! Promise! Promise! Last line! Timeout! Timeout!` + +

+
+ +--- + +###### 134. 我们怎样才能在 `index.js` 中调用 `sum.js?` 中的 `sum`? + +```javascript +// sum.js +export default function sum(x) { + return x + x; +} + +// index.js +import * as sum from "./sum"; +``` + +- A: `sum(4)` +- B: `sum.sum(4)` +- C: `sum.default(4)` +- D: 預設導出不用 `*` 來導入,只能具名導出 + +
答案 +

+ +#### 答案: C + +使用符號 `*`,我們引入文件中的所有值,包括預設和具名。如果我們有以下文件: + +```javascript +// info.js +export const name = "Lydia"; +export const age = 21; +export default "I love JavaScript"; + +// index.js +import * as info from "./info"; +console.log(info); +``` + +將會輸出以下內容: + +```javascript +{ + default: "I love JavaScript", + name: "Lydia", + age: 21 +} +``` + +以 `sum` 為例,相當於以下形式引入值 `sum`: + +```javascript +{ default: function sum(x) { return x + x } } +``` + +我們可以通過呼叫 `sum.default` 來呼叫該函數 + +

+
+ +--- + +###### 135. 將會輸出什麽內容? + +```javascript +const handler = { + set: () => console.log("Added a new property!"), + get: () => console.log("Accessed a property!") +}; + +const person = new Proxy({}, handler); + +person.name = "Lydia"; +person.name; +``` + +- A: `Added a new property!` +- B: `Accessed a property!` +- C: `Added a new property!` `Accessed a property!` +- D: 沒有任何輸出 + +
答案 +

+ +#### 答案: C + +使用 Proxy 物件,我們可以給一個物件添加自定義行為。在這個 case,我們傳遞一個包含以下屬性的物件 `handler` : `set` and `get`。每當我門 _設置_ 屬性值時 `set` 被呼叫,每當我們 _獲取_ 時 `get` 被呼叫。 + +第一個參數是一個空物件 `{}`,作為 `person` 的值。對於這個物件,自定義行為被定義在物件 `handler`。如果我們向物件 `person` 添加屬性,`set` 將被呼叫。如果我們獲取 `person` 的屬性, `get` 將被呼叫。 + +首先,我們向 proxy 物件(`person.name = "Lydia"`)添加一個屬性 `name`。 `set` 被呼叫並輸出 `"Added a new property!"`。 + +然後,我們獲取 proxy 物件的一個屬性,物件 handler 的屬性 `get` 被呼叫。輸出 `"Accessed a property!"`。 + +

+
+ +--- + +###### 136. 以下哪一項會對物件 `person` 有副作用? + +```javascript +const person = { name: "Lydia Hallie" }; + +Object.seal(person); +``` + +- A: `person.name = "Evan Bacon"` +- B: `person.age = 21` +- C: `delete person.name` +- D: `Object.assign(person, { age: 21 })` + +
答案 +

+ +#### 答案: A + +使用 `Object.seal` 我們可以防止新屬性 _被添加_,或者存在屬性 _被移除_. + +然而,你仍然可以對存在屬性進行更改。 + +

+
+ +--- + +###### 137. 以下哪一項會對物件 `person` 有副作用? + +```javascript +const person = { + name: "Lydia Hallie", + address: { + street: "100 Main St" + } +}; + +Object.freeze(person); +``` + +- A: `person.name = "Evan Bacon"` +- B: `delete person.address` +- C: `person.address.street = "101 Main St"` +- D: `person.pet = { name: "Mara" }` + +
答案 +

+ +#### 答案: C + +使用函數 `Object.freeze` 對一個物件進行 _凍結_。不能對屬性進行添加,修改,刪除。 + +然而,它僅 對物件進行 _淺_ 凍結,意味著只有 物件中的 _直接_ 屬性被凍結。如果屬性是另一個 object,像案例中的 `address`,`address` 中的屬性沒有被凍結,仍然可以被修改。 + +

+
+ +--- + +###### 138. 將會輸出什麽內容? + +```javascript +const add = x => x + x; + +function myFunc(num = 2, value = add(num)) { + console.log(num, value); +} + +myFunc(); +myFunc(3); +``` + +- A: `2` `4` and `3` `6` +- B: `2` `NaN` and `3` `NaN` +- C: `2` `Error` and `3` `6` +- D: `2` `4` and `3` `Error` + +
答案 +

+ +#### 答案: A + +首先我們不傳遞任何參數呼叫 `myFunc()`。因為我們沒有傳遞參數,`num` 和 `value` 獲取它們各自的預設值:num 為 `2`, 而 `value` 為函數 `add` 的回傳值。對於函數 `add`,我們傳遞值為2的 `num` 作為參數。函數 `add` 回傳 `4` 作為 `value` 的值。 + +然後,我們呼叫 `myFunc(3)` 並傳遞值 `3` 參數 `num` 的值。我們沒有給 `value` 傳遞值。因為我們沒有給參數 `value` 傳遞值,它獲取預設值:函數 `add` 的回傳值。對於函數 `add`,我們傳遞值為3的 `num`給它。函數 `add` 回傳 `6` 作為 `value` 的值。 + +

+
+ +--- + +###### 139. 將會輸出什麽內容? + +```javascript +class Counter { + #number = 10 + + increment() { + this.#number++ + } + + getNum() { + return this.#number + } +} + +const counter = new Counter() +counter.increment() + +console.log(counter.#number) +``` + +- A: `10` +- B: `11` +- C: `undefined` +- D: `SyntaxError` + +
答案 +

+ +#### 答案: D + +在 ES2020 中,通過 `#` 我們可以給 class 添加私有變數。在 class 的外部我們無法存取該值。當我們嘗試輸出 `counter.#number`,語法錯誤被拋出:我們無法在 class `Counter` 外部存取它! + +

+
+ +--- + +###### 140. 选择哪一个? + +```javascript +const teams = [ + { name: "Team 1", members: ["Paul", "Lisa"] }, + { name: "Team 2", members: ["Laura", "Tim"] } +]; + +function* getMembers(members) { + for (let i = 0; i < members.length; i++) { + yield members[i]; + } +} + +function* getTeams(teams) { + for (let i = 0; i < teams.length; i++) { + // ✨ SOMETHING IS MISSING HERE ✨ + } +} + +const obj = getTeams(teams); +obj.next(); // { value: "Paul", done: false } +obj.next(); // { value: "Lisa", done: false } +``` + +- A: `yield getMembers(teams[i].members)` +- B: `yield* getMembers(teams[i].members)` +- C: `return getMembers(teams[i].members)` +- D: `return yield getMembers(teams[i].members)` + +
答案 +

+ +#### 答案: B + +為了遍歷 `teams` 陣列中物件的屬性 `members` 中的每一項,我們需要將 `teams[i].members` 傳遞給 Generator 函數 `getMembers`。 Generator 函數回傳一個 generator 物件。為了遍歷這個 generator 物件中的每一項,我們需要使用 `yield*`. + +如果我們沒有寫 `yield`,`return yield` 或者 `return`,整個 Generator 函數不會第一時間 return 當我們呼叫 `next` 函數. + +

+
+ +--- + +###### 141. 將會輸出什麽內容? + +```javascript +const person = { + name: "Lydia Hallie", + hobbies: ["coding"] +}; + +function addHobby(hobby, hobbies = person.hobbies) { + hobbies.push(hobby); + return hobbies; +} + +addHobby("running", []); +addHobby("dancing"); +addHobby("baking", person.hobbies); + +console.log(person.hobbies); +``` + +- A: `["coding"]` +- B: `["coding", "dancing"]` +- C: `["coding", "dancing", "baking"]` +- D: `["coding", "running", "dancing", "baking"]` + +
答案 +

+ +#### 答案: C + +函數 `addHobby` 接受兩個參數,`hobby` 和有著物件 `person` 中陣列 `hobbies` 預設值的 `hobbies`。 + +首相,我們呼叫函數 `addHobby`,並給 `hobby` 傳遞 `"running"` 以及給 `hobbies` 傳遞一個空陣列。因為我們給 `hobbies` 傳遞了空陣列,`"running"` 被添加到這個空陣列。 + +然後,我們呼叫函數 `addHobby`,並給 `hobby` 傳遞 `"dancing"`。我們不向 `hobbies` 傳遞值,因此它獲取其預設值 —— 物件 `person` 的 屬性 `hobbies`。我們向陣列 `person.hobbies` push `dancing`。 + +最後,我們呼叫函數 `addHobby`,並向 `hobby` 傳遞 值 `"bdaking"`,並且向 `hobbies` 傳遞 `person.hobbies`。我們向陣列 `person.hobbies` push `dancing`。 + +pushing `dancing` 和 `baking` 之後,`person.hobbies` 的值為 `["coding", "dancing", "baking"]` + +

+
+ +--- + +###### 142. 將會輸出什麽內容? + +```javascript +class Bird { + constructor() { + console.log("I'm a bird. 🦢"); + } +} + +class Flamingo extends Bird { + constructor() { + console.log("I'm pink. 🌸"); + super(); + } +} + +const pet = new Flamingo(); +``` + +- A: `I'm pink. 🌸` +- B: `I'm pink. 🌸` `I'm a bird. 🦢` +- C: `I'm a bird. 🦢` `I'm pink. 🌸` +- D: Nothing, we didn't call any method + +
答案 +

+ +#### 答案: B + +我們建立了class `Flamingo` 的實例 `pet`。當我們實例化這個實例,`Flamingo` 中的 `constructor` 被呼叫。首相,輸出 `"I'm pink. 🌸"`, 之後我們呼叫`super()`。 `super()` 呼叫父class的建構函數,`Bird`。 `Bird` 的建構函數被呼叫,並輸出 `"I'm a bird. 🦢"`。 + +

+
+ +--- + +###### 143. 哪一個選項會導致報錯? + +```javascript +const emojis = ["🎄", "🎅🏼", "🎁", "⭐"]; + +/* 1 */ emojis.push("🦌"); +/* 2 */ emojis.splice(0, 2); +/* 3 */ emojis = [...emojis, "🥂"]; +/* 4 */ emojis.length = 0; +``` + +- A: 1 +- B: 1 and 2 +- C: 3 and 4 +- D: 3 + +
答案 +

+ +#### 答案: D + +`const` 關鍵字意味著我們不能 _重定義_ 變數中的值,它 _僅可讀_。而然,值本身不可修改。陣列 `emojis` 中的值可被修改,如 push 新的值, 拼接,又或者將陣列的長度設置為0。 + +

+
+ +--- + +###### 144. 我們需要向對象 `person` 添加什麼,以致執行 `[...person]` 時獲得形如 `["Lydia Hallie", 21]` 的輸出? + +```javascript +const person = { + name: "Lydia Hallie", + age: 21 +} + +[...person] // ["Lydia Hallie", 21] +``` + +- A: 不需要,物件預設就是可迭代的 +- B: `*[Symbol.iterator]() { for (let x in this) yield* this[x] }` +- C: `*[Symbol.iterator]() { for (let x in this) yield* Object.values(this) }` +- D: `*[Symbol.iterator]() { for (let x in this) yield this }` + +
答案 +

+ +#### 答案: C + +物件預設並不是可迭代的。如果迭代規則被定義,則一個物件是可迭代的(An iterable is an iterable if the iterator protocol is present)。我們可以通過添加迭代器symbol `[Symbol.iterator]` 來定義迭代規則,其回傳一個 generator 物件,比如說構建一個 generator 函數 `*[Symbol.iterator]() {}`。如果我們想要回傳陣列 `["Lydia Hallie", 21]`: `yield* Object.values(this)`,這個 generator 函數一定要 yield 物件 `person` 的`Object.values`。 + +

+
+ +--- + +###### 145. 將會輸出什麽內容? +```javascript +let count = 0; +const nums = [0, 1, 2, 3]; + +nums.forEach(num => { + if (num) count += 1 +}) + +console.log(count) +``` + +- A: 1 +- B: 2 +- C: 3 +- D: 4 +
答案 +

+ +#### 答案: C + +在 `forEach` 循環內部的 `if` 會判斷 `num` 的值是truthy或者是falsy。因為 `nums` 陣列的第一個數字是 `0`,一個falsy值, `if` 語句代碼塊不會被執行。 `count` 僅僅在 `nums` 陣列的其他3個數字 `1`,`2`,`3` 時加1。因為 `count` 執行了3次加 `1` 運算,所以 `count` 的值為 `3`。 + +

+
+ +--- + +###### 146. 將會輸出什麽內容? + +```javascript +function getFruit(fruits) { + console.log(fruits?.[1]?.[1]) +} + +getFruit([['🍊', '🍌'], ['🍍']]) +getFruit() +getFruit([['🍍'], ['🍊', '🍌']]) +``` + +- A: `null`, `undefined`, 🍌 +- B: `[]`, `null`, 🍌 +- C: `[]`, `[]`, 🍌 +- D: `undefined`, `undefined`, 🍌 + +
答案 +

+ +#### 答案: D + +`?` 允許我們去選擇性地訪問物件內部更深層的嵌套屬性。我們嘗試輸出 `fruits` 陣列索引值為 `1` 的子陣列內部的索引值為 `1` 的元素。如果在 `fruits` 陣列索引值 為 `1` 的位置不存在元素,會直接回傳 `undefined`。如果 `fruits` 陣列在索引值為 `1` 的位置存在元素,但是子陣列在索引值為 `1` 的位置不存在元素,也會回傳 `undefined`。 + +首先,我們嘗試輸出 `[['🍊', '🍌'], ['🍍']]` 的子陣列 `['🍍']` 的第2個元素。這個子陣列只包含一個元素,也就意味著在索引值為 `1` 的位置不存在元素,所以回傳的是 `undefined` 。 + +其次,我們在沒有傳入任何參數呼叫了 `getFruits` 函數,也就意味著形參 `fruits` 的預設值為`undefined`。因為我們選擇性地鏈接了 `fruits` 在索引值為 `1` 的元素,因為在索引值為 `1` 的位置不存在元素,因此回傳的是 `undefined` 。 + +最後,我們嘗試輸出 `['🍍'], ['🍊', '🍌']` 的子陣列 `['🍊', '🍌']` 的第2個元素。子陣列索引值為 `1`的位置為 `🍌` ,因此它被輸出出了。 + +

+
+ +--- + +###### 147. 將會輸出什麽內容? + +```javascript +class Calc { + constructor() { + this.count = 0 + } + + increase() { + this.count ++ + } +} + +const calc = new Calc() +new Calc().increase() + +console.log(calc.count) +``` + +- A: `0` +- B: `1` +- C: `undefined` +- D: `ReferenceError` + +
答案 +

+ +#### 答案: A + +我們設置 `calc` 變數為 `Calc` 類的一個新實例。然後,我們初始化一個 `Calc` 的新實例,而且呼叫了這個實例的 `increase` 函數。因為count屬性是在 `Calc` class的constructor內部的,所以count屬性不會在 `Calc` 的原型鏈上共享出去。這就意味著calc實例的count值不會被更新,count仍然是 `0`。 + +

+
+ +--- + +###### 148. 將會輸出什麽內容? + +```javascript +const user = { + email: "e@mail.com", + password: "12345" +} + +const updateUser = ({ email, password }) => { + if (email) { + Object.assign(user, { email }) + } + + if (password) { + user.password = password + } + + return user +} + +const updatedUser = updateUser({ email: "new@email.com" }) + +console.log(updatedUser === user) +``` + +- A: `false` +- B: `true` +- C: `TypeError` +- D: `ReferenceError` + +
答案 +

+ +#### 答案: B + + `updateUser` 函數更新user的 `email` 和 `password` 屬性的值, 如果它們的值傳入函數, 函數回傳的就是 `user` 物件。 `updateUser` 函數的回傳值是 `user` 物件,意味著updatedUser的值與 `user` 指向的是同一個 `user` 物件。 `updatedUser === user` 為 `true`. + +

+
+ +--- + +###### 149. 將會輸出什麽內容? + +```javascript +const fruit = ['🍌', '🍊', '🍎'] + +fruit.slice(0, 1) +fruit.splice(0, 1) +fruit.unshift('🍇') + +console.log(fruit) +``` + +- A: `['🍌', '🍊', '🍎']` +- B: `['🍊', '🍎']` +- C: `['🍇', '🍊', '🍎']` +- D: `['🍇', '🍌', '🍊', '🍎']` + +
答案 +

+ +#### 答案: C + +首先,我們在fruit陣列上呼叫 `slice` 函數。 slice函數不會修改原始陣列,但是會回傳從陣列切片下來的值:香蕉emoji。 +其次,我們在fruit陣列上呼叫 `splice` 函數。 splice函數會修改原始陣列,也就意味著fruit陣列此時為 `['🍊', '🍎']`。 +最後,我們在fruit陣列上呼叫 `unshift` 函數,通過添加一個值的方式改變了原始陣列,添加的是'🍇',它成為了陣列的第一個元素。現在fruit陣列的組成為 `['🍇', '🍊', '🍎']`。 + +

+
+ +--- + +###### 150. 將會輸出什麽內容? + +```javascript +const animals = {}; +let dog = { emoji: '🐶' } +let cat = { emoji: '🐈' } + +animals[dog] = { ...dog, name: "Mara" } +animals[cat] = { ...cat, name: "Sara" } + +console.log(animals[dog]) +``` + +- A: `{ emoji: "🐶", name: "Mara" }` +- B: `{ emoji: "🐈", name: "Sara" }` +- C: `undefined` +- D: `ReferenceError` + +
答案 +

+ +#### 答案: B + +物件的鍵會被轉換為字符串。 + +因為 `dog` 的值是一個物件, `animals[dog]` 實際上意味著我們建立了一個叫做 `"object Object"` 的屬性來代表新的物件。 `animals["object Object"]` 現在等於 `{ emoji: "🐶", name: "Mara"}`。 + +`cat` 也是一個物件,`animals[cat]` 實際上意味著我們在用新的cat的屬性覆蓋 `animals[``"``object Object``"``]` 的值。 + +輸出`animals[dog]`,實際上是`animals["object Object"]`,這是因為轉化`dog`物件為一個字符串結果`"object Object"` ,所以回傳`{ emoji: "🐈" , name: "Sara" }`。 + +

+
+ +--- + +###### 151. 將會輸出什麽內容? + +```javascript +const user = { + email: "my@email.com", + updateEmail: email => { + this.email = email + } +} + +user.updateEmail("new@email.com") +console.log(user.email) +``` + +- A: `my@email.com` +- B: `new@email.com` +- C: `undefined` +- D: `ReferenceError` + +
答案 +

+ +#### 答案: A + +`updateEmail` 函數是一個箭頭函數,它沒有和 `user` 物件綁定。這就意味著 `this` 關鍵字不會引用到 `user` 物件,但是會引用到全局物件。 `user` 物件內部的 `email` 的值不會更新。當輸出​​ `user.email` 的時候, 原始值 `my@email.com` 被回傳。 + +

+
+ +--- + +###### 152. 將會輸出什麽內容? + +```javascript +const promise1 = Promise.resolve('First') +const promise2 = Promise.resolve('Second') +const promise3 = Promise.reject('Third') +const promise4 = Promise.resolve('Fourth') + +const runPromises = async () => { + const res1 = await Promise.all([promise1, promise2]) + const res2 = await Promise.all([promise3, promise4]) + return [res1, res2] +} + +runPromises() + .then(res => console.log(res)) + .catch(err => console.log(err)) +``` + +- A: `[['First', 'Second'], ['Fourth']]` +- B: `[['First', 'Second'], ['Third', 'Fourth']]` +- C: `[['First', 'Second']]` +- D: `'Third'` + +
答案 +

+ +#### 答案: D + + `Promise.all` 函數可以並行式執行promise。如果其中一個promise失敗了,`Promise.all` 函數會帶上被reject的promise的值_rejects_。在這個例子中, `promise3` 帶著 `"Third"` 值reject。我們在呼叫 `runPromises` 時在 `runPromises` 函數內部的 `catch` 函數去捕獲任意error從而捕獲到被reject的值。因為 `promise3` 帶著 `"Third"` 被reject,所以只有 `"Third"` 輸出。 + +

+
+ +--- + +###### 153. 哪個作為`method`的值可以輸出`{ name: "Lydia", age: 22 }`? + +```javascript +const keys = ["name", "age"] +const values = ["Lydia", 22] + +const method = /* ?? */ +Object[method](keys.map((_, i) => { + return [keys[i], values[i]] +})) // { name: "Lydia", age: 22 } +``` + +- A: `entries` +- B: `values` +- C: `fromEntries` +- D: `forEach` + +
答案 +

+ +#### 答案: C + +`fromEntries` 函數可以將二維陣列轉換為物件。在每個子陣列的第一個元素是key,在每個子陣列的第二個元素是value。在這個例子中,我們映射了 `keys` 陣列,它回傳了一個陣列,陣列的第一個元素為keys陣列當前索引的值,第二個元素為values陣列當前索引的值。 + +這樣就建立了一個包含正確keys和values的子陣列的陣列,因此結果為`{ name: "Lydia", age: 22 }`。 + +

+
+ +--- + +###### 154. 將會輸出什麽內容? + +```javascript +const createMember = ({ email, address = {}}) => { + const validEmail = /.+\@.+\..+/.test(email) + if (!validEmail) throw new Error("Valid email pls") + + return { + email, + address: address ? address : null + } +} + +const member = createMember({ email: "my@email.com" }) +console.log(member) +``` + +- A: `{ email: "my@email.com", address: null }` +- B: `{ email: "my@email.com" }` +- C: `{ email: "my@email.com", address: {} }` +- D: `{ email: "my@email.com", address: undefined }` + +
答案 +

+ +#### 答案: C + + `address` 的預設值是一個空物件 `{}`。當我們設置 `member` 變數為 `createMember` 函數回傳的物件,我們沒有為address參數傳值,意味著address的值為預設的空物件 `{}`。一個空物件是一個truthy值,意味著 `address ? address : null` 條件會回傳 `true`。 address的值為空物件 `{}`。 + +

+
+ +--- + +###### 155. 將會輸出什麽內容? + +```javascript +let randomValue = { name: "Lydia" } +randomValue = 23 + +if (!typeof randomValue === "string") { + console.log("It's not a string!") +} else { + console.log("Yay it's a string!") +} +``` + +- A: `It's not a string!` +- B: `Yay it's a string!` +- C: `TypeError` +- D: `undefined` + +
答案 +

+ +#### 答案: B + + `if` 語句的條件判斷 `!typeof randomValue` 的值是否等於 `"string"`。 `!` 操作符將這個值轉化為一個布林值。如果值是truthy的話,回傳值會是 `false`,如果值是falsy,回傳值會是 `true`。在這裡, `typeof randomValue` 的回傳值是一個truthy值 `"number"`,意味著 `!typeof randomValue` 的值是一個布林值 `false`。 + + `!typeof randomValue === "string"` 總是回傳false,因為我們實際上是在執行 `false === "string"`。因為條件回傳的是 `false`,所以 `else` 語句中的代碼塊會被執行,因此輸出 `Yay it's a string!` 。 + +

+
\ No newline at end of file From 30cbc2b77b653f19607213e3d75b93899ba100e0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Hiram=20E=2E=20P=C3=A9rez?= Date: Mon, 12 Jul 2021 09:15:24 -0500 Subject: [PATCH 083/193] README-ES.md: Question 11. Literal translation fix Question 11 about prototypes. Literal translation used in code snippet. Fix code snippet --- es-ES/README-ES.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/es-ES/README-ES.md b/es-ES/README-ES.md index 8569da2e..0e8dc473 100644 --- a/es-ES/README-ES.md +++ b/es-ES/README-ES.md @@ -375,11 +375,11 @@ console.log(member.getFullName()); #### Respuesta correcta: A -En JS no se pueden añadir propiedades a un constructor como se puede hacer con los objetos. Si se desea añadir una característica a todos los objetos a la vez, se debe utilizar el [prototipo](https://www.w3schools.com/js/js_object_prototypes.asp) en su lugar. Así que en este caso, +En JS no se pueden añadir propiedades a un constructor como se puede hacer con los objetos. Si se desea añadir una característica a todos los objetos a la vez, se debe utilizar [prototype](https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Objects/Object_prototypes) en su lugar. Así que en este caso, ```js -Persona.prototipo.getFullName = función () {) - devuelve `${este.nombre} ${este.apellido}`; +Person.prototype.getFullName = function () {) + return `${this.firstName} ${this.lastName}`; } ``` From 1e8de5eb1c64aee60ecd3d90e75e2a72fd8a2c7c Mon Sep 17 00:00:00 2001 From: Danah Date: Tue, 3 Aug 2021 00:33:22 +0900 Subject: [PATCH 084/193] Fix unnatural translations and reflect updates --- ko-KR/README-ko_KR.md | 1505 +++++++++++++++++++++-------------------- 1 file changed, 760 insertions(+), 745 deletions(-) diff --git a/ko-KR/README-ko_KR.md b/ko-KR/README-ko_KR.md index b1685d36..ff31a19c 100644 --- a/ko-KR/README-ko_KR.md +++ b/ko-KR/README-ko_KR.md @@ -1,15 +1,26 @@ -# (고급) JavaScript 질문 목록 +
+ +

JavaScript 질문

-JavaScript 에 관한 객관식 문제를 [Instagram](https://www.instagram.com/theavocoder)에 매일 게시하고 있어요, 물론 여기에도 게시할 거예요! +--- + +JavaScript에 관한 객관식 질문을 [Instagram](https://www.instagram.com/theavocoder) **스토리**에 올리고 있어요, 물론 여기에도 게시할 거예요! 마지막 업데이트: 6월 12일 + +기초부터 심화까지: JavaScript를 얼마나 잘 알고 있는지 테스트하거나, 지식을 조금 더 새롭게 하거나, 코딩 면접을 준비하세요! :muscle: :rocket: 이 저장소를 새로운 질문과 함께 주기적으로 업데이트해요. 질문 아래 **접힌 부분**에 답을 추가했어요, 답을 클릭하면 간단하게 펼쳐져요. 그냥 재미로 하는 거예요, 행운을 빌어요! :heart: -초급부터 고급까지: JavaScript를 얼마나 잘 알고 있는지 테스트하거나, 지식을 조금 더 새롭게 하거나, 코딩 면접을 준비하세요! :muscle: :rocket: 이 기록을 매주 새로운 질문으로 업데이트해요. 마지막 업데이트: 10월 09일 +내게 편하게 연락하세요! 😊
+Instagram || Twitter || LinkedIn || Blog -정답은 질문 아래 접힌 부분에 있고, 간단히 클릭하면 펼칠 수 있어요. 행운을 빌어요 :heart: +
+ +| 프로젝트에 자유롭게 사용하세요! 😃 이 저장소를 참고해 준다면 _정말_ 감사할 거예요, 저는 질문과 해설을 만들고(네 슬퍼요 하하), 커뮤니티는 제가 레포를 유지하고 개선하는 데 많은 도움을 줘요! 💪🏼 고맙고 좋은 시간 보내요! | +| ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -질문이 더 추가될 때마다 이메일을 받고 싶나요?
-✨✉이메일 업데이트 구독 ✉✨ +--- + +
사용 가능한 번역 18개 🇸🇦🇪🇬🇧🇦🇬🇧🇩🇪🇪🇸🇫🇷🇮🇩🇯🇵🇳🇱🇧🇷🇷🇺🇹🇭🇹🇷🇺🇦🇻🇳🇨🇳🇹🇼 +

-사용 가능한 언어 목록: - [🇸🇦 العربية](./ar-AR/README_AR.md) - [🇪🇬 اللغة العامية](./ar-EG/README_ar-EG.md) - [🇧🇦 Bosanski](./bs-BS/README-bs_BS.md) @@ -29,6 +40,8 @@ JavaScript 에 관한 객관식 문제를 [Instagram](https://www.instagram.com/ - [🇨🇳 简体中文](./zh-CN/README-zh_CN.md) - [🇹🇼 繁體中文](./zh-TW/README_zh-TW.md) +

+
--- @@ -38,7 +51,7 @@ JavaScript 에 관한 객관식 문제를 [Instagram](https://www.instagram.com/ function sayHi() { console.log(name); console.log(age); - var name = "Lydia"; + var name = 'Lydia'; let age = 21; } @@ -50,14 +63,14 @@ sayHi(); - C: `ReferenceError` 그리고 `21` - D: `undefined` 그리고 `ReferenceError` -
정답 +

-#### 정답: D +#### 답: D -함수 내에서, 우선 `var` 키워드를 사용해 `name` 변수를 선언해요. 이것은 변수가 정의된 행에 실제로 도달할 때까지, `undefined`의 기본값으로 호이스팅 되(생성단계에 메모리 공간이 설정)는 것을 의미해요. `name` 변수를 출력하려는 줄에서 아직 변수를 정의하고 있지 않기 때문에, `undefined` 값을 유지하고 있어요. +함수 안에서, 우선 `var` 키워드를 사용해 `name` 변수를 선언해요. 이것은 변수를 정의한 줄에 실제로 도달할 때까지, 기본값 `undefined`으로 호이스팅 되는 것(생성단계에 메모리 공간이 설정)을 의미해요. `name` 변수를 출력하려는 줄에서 아직 변수를 정의하지 않았기 때문에, `undefined` 값을 유지해요. -`let` 키워드(그리고 `const`)를 가지는 변수들은, `var`와는 달리, 호이스팅 되지만 초기화 되지 않아요. 그것들을 선언(초기화)하는 줄 전에는 접근할 수 없어요. 이것은 "일시적 사각지대"라고 불려요. 선언되기 전 변수에 접근하려고 하면, JavaScript는 `ReferenceError`를 던져요. +`var`와는 다르게 `let` 키워드(그리고 `const`)를 가진 변수는 호이스팅 되지만, 초기화 되지 않아요. 변수를 선언(초기화)하는 줄 전에는 접근할 수 없어요. 이건 "일시적 사각지대"라고 불려요. 변수가 선언되기 전 변수에 접근하려고 하면, JavaScript는 `ReferenceError`를 던져요.

@@ -80,14 +93,14 @@ for (let i = 0; i < 3; i++) { - B: `0 1 2` 그리고 `3 3 3` - C: `3 3 3` 그리고 `0 1 2` -
정답 +

-#### 정답: C +#### 답: C -JavaScript의 이벤트 큐 때문에, `setTimeout`의 콜백 함수는 루프가 실행된 _후에_ 호출돼요. 첫 번째의 루프 변수 `i`는 `var` 키워드를 사용해 선언되어 있기 때문에, 이 값은 전역 변수가 돼요. 루프 동안, 단항 연산자 `++`를 사용하여, 매번 `i`의 값을 `1`씩 증가했어요. `setTimeout`콜백 함수가 호출되기까지, 첫 번째 예에서 `i`는 `3`이에요. +JavaScript의 이벤트 큐 때문에, `setTimeout`의 콜백 함수는 루프가 실행된 _후에_ 호출돼요. 첫 번째의 루프의 변수 `i`는 `var` 키워드를 사용해 선언되어 전역 값이 돼요. 루프 동안, 단항 연산자 `++`를 사용해 매번 `i`의 값을 `1`씩 증가시켰어요. `setTimeout`콜백 함수가 호출되기까지, 첫 번째 예시에서의 `i`는 `3`이에요. -두 번째 루프에서, 변수 `i`는 `let` 키워드를 사용해 선언되었어요: `let`(그리고 `const`) 키워드로 선언된 변수는 블록 범위예요(블록은 `{ }` 사이의 모든 것). 각각의 반복 동안, `i`는 새로운 값을 가지고, 각각의 값은 루프 안쪽 범위에 있어요. +두 번째 루프에서, 변수 `i`는 `let` 키워드를 사용해 선언되었어요: `let`(그리고 `const`) 키워드로 선언된 변수는 블록-스코프예요(블록은 `{ }` 사이의 모든 것). 각각을 반복하는 동안, `i`는 새로운 값을 갖게 되고, 각각의 값은 루프 스코프 안에 있어요.

@@ -102,7 +115,7 @@ const shape = { diameter() { return this.radius * 2; }, - perimeter: () => 2 * Math.PI * this.radius + perimeter: () => 2 * Math.PI * this.radius, }; console.log(shape.diameter()); @@ -114,16 +127,16 @@ console.log(shape.perimeter()); - C: `20` 그리고 `63` - D: `NaN` 그리고 `63` -
정답 +

-#### 정답: B +#### 답: B -`diameter`의 값은 정규 함수지만, `perimeter`의 값은 화살표 함수라는 점을 유의하세요. +`diameter`의 값은 일반 함수지만, `perimeter`의 값은 화살표 함수라는 점을 유의하세요. -화살표 함수에서, `this` 키워드는 통상적인 함수와는 다르게 현재 주위의 범위를 참조해요! 이것은 `perimeter`를 부르면, shape 객체가 아닌 그 주위의 범위(예를 들면 window)를 참조하는 것을 의미해요. +화살표 함수에서 `this` 키워드는 일반 함수와는 다르게 현재 주변 스코프를 참조해요! 이것은 `perimeter`를 부를 때 shape 객체가 아닌 그것을 둘러싼 스코프(예를 들면 window)를 참조하는 것을 의미해요. -그 객체에는 `radius`라는 값은 없기 때문에 `undefined`를 리턴해요. +그 객체에는 `radius`라는 값은 없기 때문에 `undefined`를 반환해요.

@@ -134,57 +147,57 @@ console.log(shape.perimeter()); ```javascript +true; -!"Lydia"; +!'Lydia'; ``` - A: `1` 그리고 `false` - B: `false` 그리고 `NaN` - C: `false` 그리고 `false` -
정답 +

-#### 정답: A +#### 답: A -단항 더하기는 피연산자를 숫자로 변환하려 시도해요. `true`는 `1`이고, `false`는 `0`이에요. +단항 더하기는 피연산자를 숫자로 변환하려 해요. `true`는 `1`이고, `false`는 `0`이에요. -문자열 `'Lydia'`는 참 같은 값이에요. 실제로는, "이 참 같은 값이 거짓 같은 값인가?"를 물어보고 있어요. 이것은 `false`를 리턴해요. +문자열 `'Lydia'`는 참 같은 값이에요. 사실 우리가 물어본 건 "참 같은 이 값은 거짓인가?"예요. 이건 `false`를 반환해요.

--- -###### 5. 정답은 어느 것일까요? +###### 5. 답은 어느 것일까요? ```javascript const bird = { - size: "small" + size: 'small', }; const mouse = { - name: "Mickey", - small: true + name: 'Mickey', + small: true, }; ``` - A: `mouse.bird.size` 는 유효하지 않아요 - B: `mouse[bird.size]` 는 유효하지 않아요 -- C: `mouse[bird["size"]]` 는 유효하지 않아요 -- D: 이 모든 것들은 유효해요. +- C: `mouse[bird['size']]` 는 유효하지 않아요 +- D: 이 모든 것은 유효해요. -
정답 +

-#### 정답: A +#### 답: A -JavaScript에서, 모든 객체 키는 문자열이에요 (심볼이 아닌 한). 비록 그것을 문자열 _형_ 으로 입력하지 않아도, 항상 내부적으로 문자열로 변환돼요. +JavaScript에서 모든 객체의 키는 문자열이에요(심볼이 아닌 한). 객체의 키를 문자열 _형_ 으로 입력하지 않더라도, 항상 내부적으로 문자열로 변환돼요. -JavaScript는 문장을 해석(또는 박스 해제)해요. 대괄호 표기를 사용하면, 첫 번째 열린 대괄호 `[`를 보고 닫힌 대괄호 `]`를 찾을 때까지 진행해요. 그때에만, 그 문장을 평가할 거예요. +JavaScript는 문장을 해석(또는 분)해요. 대괄호 표기를 사용하면 첫 번째 열린 대괄호 `[`를 보고 닫힌 대괄호 `]`를 찾을 때까지 진행해요. 다 찾은 후에만 문장을 평가할 거예요. -`mouse[bird.size]`: 먼저 `"small"`인 `bird.size`를 평가해요. `mouse["small"]` 은 `true`를 리턴해요. +`mouse[bird.size]`: 먼저 `'small'`인 `bird.size`를 평가해요. `mouse['small']` 은 `true`를 반환해요. -그러나, 닷 표기법에서, 이것은 발생하지 않아요, `mouse`는 `bird`라고 불리는 키를 가지고 있지 않아요. 즉, `mouse.bird`는 `undefined`를 의미해요. 그 후, 닷 표기법을 사용해 `size`를 물어봐요. `mouse.bird.size`. `mouse.bird`는 `undefined`로, 실제로는 `undefined.size`를 물어보고 있어요. 이것은 유효하지 않기 때문에, `Cannot read property "size" of undefined`와 비슷한 에러를 던질 거예요. +그러나 이것은 점 표기법에서 발생하지 않아요. `mouse`가 `bird`라고 불리는 키를 가지고 있지 않기 때문에, `mouse.bird`는 `undefined`임을 의미해요. 그다음에, 점 표기법을 사용해 `size`를 물어봐요: `mouse.bird.size`. `mouse.bird`는 `undefined`이기 때문에, 사실 우리가 물어보는 건 `undefined.size`에요. 이건 유효하지 않아요, 그리고 `Cannot read property 'size' of undefined`와 비슷한 오류를 던질 거예요.

@@ -194,11 +207,11 @@ JavaScript는 문장을 해석(또는 박스 해제)해요. 대괄호 표기를 ###### 6. 무엇이 출력 될까요? ```javascript -let c = { greeting: "Hey!" }; +let c = { greeting: 'Hey!' }; let d; d = c; -c.greeting = "Hello"; +c.greeting = 'Hello'; console.log(d.greeting); ``` @@ -208,18 +221,18 @@ console.log(d.greeting); - D: `ReferenceError` - E: `TypeError` -
정답 +

-#### 정답: A +#### 답: A -JavaScript에서, 모든 객체는 서로 동일하게 설정하면 _참조_ 에 따라 상호작용해요. +JavaScript에서 모든 객체는 서로를 동일하게 설정하면 _참조_로 상호작용해요. -우선 변수 `c`는 객체에 대한 값을 유지해요. 그 후, `c`와 동일한 객체 참조를 `d`에 할당해요. +우선, 변수 `c`는 객체에 대한 값을 갖고 있어요. 그 후 `c`가 객체에 가지고 있는 것과 동일한 참조를 `d`에 할당해요. -한 개의 객체를 변경하면, 그것들 모두 변경해요. +하나의 객체를 변경하면, 모든 객체가 변해요.

@@ -243,16 +256,16 @@ console.log(b === c); - C: `true` `false` `false` - D: `false` `true` `true` -
정답 +

-#### 정답: C +#### 답: C -`new Number()`는, 내장 함수 생성자예요. 숫자처럼 보이지만, 실제로는 숫자가 아니에요: 많은 추가 특성이 있고 그것은 객체예요. +`new Number()`는, 내장 함수 생성자예요. 숫자처럼 보이지만, 사실 숫자가 아니에요: 많은 추가 특성이 있고 그것은 객체예요. -`==`연산자를 사용할 때, 그건 같은 _값_ 을 가졌는지 여부만 확인해요. 그것들은 모두`3`의 값을 가지고 있으므로, `true`를 리턴해요. +`==`연산자를 사용할 때는, 같은 _값_ 을 가졌는지 여부만 확인해요. 모두`3`의 값을 가지고 있음으로 `true`를 반환해요. -그러나, `===`연산자를 사용할 때, 값 _과_ 형 둘 다 같아야 해요. 이건 아니에요: `new Number()`는 숫자가 아니에요. **객체**에요. 그래서 둘 다 `false`를 리턴해요. +그러나, `===`연산자를 사용할 때는, 값 _그리고_ 형 둘 다 같아야 해요. 이건 아니에요: `new Number()`는 숫자가 아니에요. **객체**에요. 그래서 둘 다 `false`를 반환해요.

@@ -268,13 +281,13 @@ class Chameleon { return this.newColor; } - constructor({ newColor = "green" } = {}) { + constructor({ newColor = 'green' } = {}) { this.newColor = newColor; } } -const freddie = new Chameleon({ newColor: "purple" }); -console.log(freddie.colorChange("orange")); +const freddie = new Chameleon({ newColor: 'purple' }); +console.log(freddie.colorChange('orange')); ``` - A: `orange` @@ -282,12 +295,12 @@ console.log(freddie.colorChange("orange")); - C: `green` - D: `TypeError` -
정답 +

-#### 정답: D +#### 답: D -`colorChange`함수는 정적이에요. 정적 메소드는 그것들이 만들어지는 생성자 상에서만 살아있도록 설계되어 있어, 어떤 자식들도 상속받을 수 없어요. `freddie`는 자식이기 때문에, 이 함수는 상속되지 않고, `freddie`인스턴스에서는 이용할 수 없어요: `TypeError`가 던져져요. +`colorChange`함수는 정적이에요. 정적 메소드는 그것이 만들어지는 생성자에서만 살아있도록 설계되어, 어떤 자식들도 상속받을 수 없어요. `freddie`는 자식이기 때문에, 이 함수는 상속되지 않아 `freddie`인스턴스에서는 이용할 수 없어요: `TypeError`가 던져져요.

@@ -297,8 +310,8 @@ console.log(freddie.colorChange("orange")); ###### 9. 무엇이 출력 될까요? ```javascript -let greeting; // Typo! -greetign = {}; +let greeting; +greetign = {}; // Typo! console.log(greetign); ``` @@ -306,14 +319,14 @@ console.log(greetign); - B: `ReferenceError: greetign is not defined` - C: `undefined` -
정답 +

-#### 정답: A +#### 답: A -역 객체에 빈 객체를 방금 만들었기 때문에, 객체는 출력돼요. `greeting`을 `greettign`으로 잘못 입력했을 경우, JS 인터프리터는 실제로 이것을 `global.greettign = {}` (또는 브라우저의 `window.greetign = {}`) 라고 간주해요. +방금 전역 객체에 빈 객체를 만들었기 때문에, 객체는 출력돼요. `greeting`을 `greettign`으로 잘못 입력했을 때, JS 인터프리터는 `global.greettign = {}` (또는 브라우저의 `window.greetign = {}`)라고 간주해요. -이것을 피하기 위해서, `"use strict"`를 사용할 수 있어요. 이렇게 하면 변수를 어떤 것과 동일하게 설정하기 전에 변수를 선언했는지 확인할 수 있어요. +이것을 피하려면, `"use strict"`를 사용해요. 이렇게 하면 변수를 어떤 것과 동일하게 설정하기 전에 변수를 선언했는지 확인할 수 있어요.

@@ -324,10 +337,10 @@ console.log(greetign); ```javascript function bark() { - console.log("Woof!"); + console.log('Woof!'); } -bark.animal = "dog"; +bark.animal = 'dog'; ``` - A: 별일 없어요, 이건 완전히 괜찮아요! @@ -335,12 +348,12 @@ bark.animal = "dog"; - C: `"Woof"`이 출력돼요. - D: `ReferenceError` -
정답 +

-#### 정답: A +#### 답: A -함수는 객체이기 때문에, 이건 JavaScript에서는 가능해요! (윈시형 이외는 모두 객체) +JavaScript에서는 가능한데, 함수는 객체이기 때문이에요! (원시형 이외는 모두 객체) 함수는 특별한 종류의 객체예요. 당신이 쓴 코드는 실제 함수가 아니에요. 함수는 속성을 가진 객체예요. 이 속성은 호출이 가능해요. @@ -357,8 +370,8 @@ function Person(firstName, lastName) { this.lastName = lastName; } -const member = new Person("Lydia", "Hallie"); -Person.getFullName = function() { +const member = new Person('Lydia', 'Hallie'); +Person.getFullName = function () { return `${this.firstName} ${this.lastName}`; }; @@ -370,21 +383,21 @@ console.log(member.getFullName()); - C: `Lydia Hallie` - D: `undefined` `undefined` -

정답 +

-#### 정답: A +#### 답: A + +JavaScript에서, 함수는 객체이고 그렇기 때문에 메소드 `getFullName`은 생성자 함수 객체 자체에 추가돼요. 이런 이유로, 우리는 `Person.getFullName()`을 부를 수 있지만 `member.getFullName()`은 `TypeError`를 던져요. -생성자에는 보통의 객체처럼 속성을 추가할 수 없어요. 한 번에 모든 객체에 기능을 추가하고 싶다면, 프로토타입을 사용해야 해요. 그래서 이 경우에, +모든 객체 인스턴스에서 메소드를 사용할 수 있게 하려면, 메소드를 프로토타입 속성에 추가하세요. ```js -Person.prototype.getFullName = function() { +Person.prototype.getFullName = function () { return `${this.firstName} ${this.lastName}`; }; ``` -`member.getFullName()`은 작동해요. 이것은 왜 유익할까요? 이 메소드를 생성자 자체에 추가했다고 할게요. 아마도 모든 `Person` 인스턴스는 이 메소드가 필요하지 않을 수도 있어요. 그 경우 그들은 계속해서 속성을 갖고 있기 때문에, 각각의 인스턴스를 위한 메모리 공간을 소비하게 되어, 많은 메모리 공간을 낭비하게 될 거예요. 대신에, 프로토타입을 추가하는 것만으로, 메모리의 한 지점을 가지지만, 모든 것들은 그것에 접근할 수 있어요. -

@@ -398,8 +411,8 @@ function Person(firstName, lastName) { this.lastName = lastName; } -const lydia = new Person("Lydia", "Hallie"); -const sarah = Person("Sarah", "Smith"); +const lydia = new Person('Lydia', 'Hallie'); +const sarah = Person('Sarah', 'Smith'); console.log(lydia); console.log(sarah); @@ -410,14 +423,14 @@ console.log(sarah); - C: `Person {firstName: "Lydia", lastName: "Hallie"}` 그리고 `{}` - D:`Person {firstName: "Lydia", lastName: "Hallie"}` 그리고 `ReferenceError` -
정답 +

-#### 정답: A +#### 답: A -`sarah`에게 `new` 키워드를 사용하지 않았어요. `new`를 사용한 경우, 이것은 우리가 만든 새로운 빈 객체를 참조해요. 그러나, `new`를 추가하지 않으면 **전역변수**를 참조해요! +`sarah`에게 `new` 키워드를 사용하지 않았어요. `new`를 사용한 경우, `this`는 우리가 만든 새로운 빈 객체를 참조해요. 그러나, `new`를 추가하지 않으면 **전역 변수**를 참조해요! -`this.firstName`은 `"Sarah"`이고, `this.lastName`은 `"Smith"`이라고 말했었어요. (그렇지만) 우리가 실제로 한 일은 `global.firstName = 'Sarah'` 그리고 `global.lastName = 'Smith'`를 정의하는 것이에요. `sarah` 자체는 `undefined`로 남아있어요. 따라서 `Person`함수의 값을 리턴하지 않아요. +`this.firstName`은 `"Sarah"`이고, `this.lastName`은 `"Smith"`라고 말했었어요. (그렇지만)실제로는, `global.firstName = 'Sarah'` 그리고 `global.lastName = 'Smith'`를 정의한 거예요. `sarah` 자체는 `undefined`로 남아있어요, 그렇기 때문에 `Person`함수의 값을 반환하지 않아요.

@@ -431,12 +444,12 @@ console.log(sarah); - C: Target > Bubbling > Capturing - D: Capturing > Target > Bubbling -
정답 +

-#### 정답: D +#### 답: D -**capturing** 단계 동안에, 이벤트는 조상 요소를 거쳐 목표 요소까지 내려가요. 그런 다음 **target** 요소에 도달하고, **bubbling**이 시작돼요. +**capturing** 단계 동안에, 이벤트는 조상 요소를 거쳐 target 요소까지 내려가요. 그런 다음 **target** 요소에 도달하고, **bubbling**이 시작돼요. @@ -450,12 +463,12 @@ console.log(sarah); - A: true - B: false -

정답 +

-#### 정답: B +#### 답: B -**기본 객체**를 제외한, 모든 객체는 프로토타입을 가져요. 기본 객체는 사용자에 의해 만들어지거나 `new` 키워드를 사용하여 만들어져요. 기본 객체는 `.toString`과 같은 몇 개의 메소드와 속성에 접근할 수 있어요. 이것이 내장 JavaScript 메소드를 사용할 수 있는 이유죠! 이러한 모든 메소드는 프로토타입에서 이용할 수 있어요. JavaScript가 당신의 객체를 직접 찾을 수 없더라도, 당신이 접근할 수 있도록 프로토타입 체인으로 내려가서 찾을 거에요. +**기본 객체**를 제외한, 모든 객체는 프로토타입을 가져요. 기본 객체는 사용자가 만든 객체이거나 `new` 키워드를 사용해 만들어진 객체예요. 기본 객체는 `.toString`과 같은 몇 개의 메소드와 속성에 접근할 수 있어요. 이것이 내장 JavaScript 메소드를 사용할 수 있는 이유죠! 이러한 모든 메소드는 프로토타입에서 사용할 수 있어요. JavaScript가 당신의 객체를 바로 찾을 수 없더라도, 당신이 접근할 수 있도록 프로토타입 체인으로 내려가 찾을 거예요.

@@ -469,22 +482,22 @@ function sum(a, b) { return a + b; } -sum(1, "2"); +sum(1, '2'); ``` - A: `NaN` - B: `TypeError` -- C: `"12"` +- C: `'12'` - D: `3` -
정답 +

-#### 정답: C +#### 답: C -JavaScript는 **동적으로 만들어진 언어**에요: 특정 변수가 어떤 형인지 지정하지 않아요. 변수는 당신이 모르는 사이에 자동으로 다른 형으로 변환될 수 있는데, 이걸 _암묵적 형 변환_ 이라고 불러요. **Coercion**은 하나의 형을 다른 형으로 변환해요. +JavaScript는 **동적으로 유형화된 언어**에요: 특정 변수가 어떤 유형인지 명시하지 않아요. 변수는 당신이 모르는 사이에 자동으로 다른 유형으로 변환될 수 있는데, 이걸 _암묵적 형 변환_ 이라고 불러요. **Coercion**은 하나의 유형을 다른 유형으로 변환해요. -이 예제에서, 함수가 이해하고 값을 리턴하도록, JavaScript는 숫자 `1`을 문자열로 변환해요. 수형 (`1`)와 문자열형 (`'2'`)의 추가 중에는, 숫자는 문자열로 취급해요. `"Hello" + "World"`처럼 문자열을 연결할 수 있어요, 따라서 여기 `"1" + "2"`는 `"12"`을 리턴하는 일이 발생해요. +이 예제에서, JavaScript는 함수가 이해하고 값을 반환하도록 숫자 `1`을 문자열로 변환해요. 숫자 유형 (`1`)과 문자열 유형 (`'2'`)을 추가하는 동안, 숫자는 문자열로 취급돼요. `"Hello" + "World"`처럼 문자열을 연결해요, 따라서 여기서 일어나는 일은 `"1" + "2"`는 `"12"`에요.

@@ -505,22 +518,22 @@ console.log(number); - C: `0` `2` `2` - D: `0` `1` `2` -
정답 +

-#### 정답: C +#### 답: C **접미사** 단항 연산자 `++`: -1. 값 리턴 (이것은 `0`을 리턴해요) -2. 값 증가 (number는 지금 `1`이에요) +1. 값 반환 (`0`을 반환해요) +2. 값 증가 (지금 number는 `1`이에요) **접두사** 단항 연산자 `++`: -1. 값 증가 (number는 지금 `2`이에요) -2. 값 리턴 (이것은 `2`을 리턴해요) +1. 값 증가 (지금 number는 `2`이에요) +2. 값 반환 (`2`를 반환해요) -이건 `0 2 2`를 리턴해요. +`0 2 2`를 반환해요.

@@ -536,7 +549,7 @@ function getPersonInfo(one, two, three) { console.log(three); } -const person = "Lydia"; +const person = 'Lydia'; const age = 21; getPersonInfo`${person} is ${age} years old`; @@ -546,12 +559,12 @@ getPersonInfo`${person} is ${age} years old`; - B: `["", " is ", " years old"]` `"Lydia"` `21` - C: `"Lydia"` `["", " is ", " years old"]` `21` -
정답 +

-#### 정답: B +#### 답: B -태그드 템플릿 리터럴을 사용하는 경우, 첫 번째 인수의 값은 항상 문자열 값의 배열이에요. 나머지 인수는 식을 통과한 값을 얻어요. +태그가 지정된 템플릿 리터럴을 사용한다면, 첫 번째 인수의 값은 항상 문자열 값의 배열이에요. 나머지 인수는 표현식을 통과한 값을 가져요.

@@ -563,9 +576,9 @@ getPersonInfo`${person} is ${age} years old`; ```javascript function checkAge(data) { if (data === { age: 18 }) { - console.log("You are an adult!"); + console.log('You are an adult!'); } else if (data == { age: 18 }) { - console.log("You are still an adult."); + console.log('You are still an adult.'); } else { console.log(`Hmm.. You don't have an age I guess`); } @@ -578,16 +591,16 @@ checkAge({ age: 18 }); - B: `You are still an adult.` - C: `Hmm.. You don't have an age I guess` -
정답 +

-#### 정답: C +#### 답: C -동등성을 테스트할 때, 원시형은 그 _값_ 에 따라 비교되며, 객체는 그들의 _참조_ 에 따라 비교돼요. JavaScript 객체가 메모리 내의 같은 장소를 참조하고 있는지를 확인해요. +동등성을 테스트할 때, 원시형은 _값_ 으로 비교되고, 객체는 _참조_ 로 비교돼요. JavaScript는 객체가 메모리 내의 같은 장소를 참조하고 있는지를 확인해요. 비교하고 있는 두 개의 객체는 그것이 없어요: 파라미터로 전달된 객체와 동등성을 확인하기 위해 사용한 객체는 메모리 내의 다른 장소를 참조해요. -이것이 `{ age: 18 } === { age: 18 }` 그리고 `{ age: 18 } == { age: 18 }` 두 개 다 `false`를 리턴하는 이유죠. +`{ age: 18 } === { age: 18 }` 그리고 `{ age: 18 } == { age: 18 }` 두 개 다 `false`를 반환하는 이유예요.

@@ -609,12 +622,12 @@ getAge(21); - C: `"object"` - D: `"NaN"` -
정답 +

-#### 정답: C +#### 답: C -rest 파라미터 (`...args`.)는 모든 남아있는 인수들을 하나의 배열로 "집합" 해요. 배열은 객체이므로, `typeof args`는 `"object"`를 리턴해요. +rest 파라미터 (`...args`)는 남아있는 모든 인수을 하나의 배열로 "집합" 해요. 배열은 객체이니까 `typeof args`는 `"object"`를 반환해요.

@@ -625,7 +638,7 @@ rest 파라미터 (`...args`.)는 모든 남아있는 인수들을 하나의 배 ```javascript function getAge() { - "use strict"; + 'use strict'; age = 21; console.log(age); } @@ -638,12 +651,12 @@ getAge(); - C: `ReferenceError` - D: `TypeError` -
정답 +

-#### 정답: C +#### 답: C -`"use strict"`을 사용하면, 실수로 전역 변수를 선언하지 않게 할 수 있어요. `age`라는 변수를 선언한 적이 전혀 없고, `"use strict"`을 사용하고 있으므로, 참조 에러를 던지게 될 거예요. 만약 `"use strict"`을 사용하지 않았다면, 이건 작동할 거예요, `age` 속성이 전역 객체에 추가된 것이기 때문이죠. +`"use strict"`을 사용하면, 실수로 전역 변수를 선언하지 않게 해줘요. `age`라는 변수를 선언한 적이 전혀 없고, `"use strict"`을 사용하고 있으니, reference error를 던지게 될 거예요. 만약 `"use strict"`을 사용하지 않았다면 동작할 거예요, `age` 속성이 전역 객체에 추가된 것이기 때문이죠.

@@ -653,7 +666,7 @@ getAge(); ###### 21. `sum`의 값은 무엇일까요? ```javascript -const sum = eval("10*10+5"); +const sum = eval('10*10+5'); ``` - A: `105` @@ -661,12 +674,12 @@ const sum = eval("10*10+5"); - C: `TypeError` - D: `"10*10+5"` -
정답 +

-#### 정답: A +#### 답: A -`eval` 문자열로서 통과된 코드를 평가해요. 이 경우와 같이 만약 그것이 표현식이라면, 표현 식을 평가해요. 표현 식은 `10 * 10 + 5`이에요. 이것은 숫자 `105`를 리턴해요. +`eval` 문자열로 통과된 코드를 평가해요. 만약 그것이 이 경우처럼 표현 식이라면, 표현 식을 평가해요. 표현식은 `10 * 10 + 5`이에요. 이것은 숫자 `105`를 반환해요.

@@ -676,7 +689,7 @@ const sum = eval("10*10+5"); ###### 22. cool_secret에 몇 시간이나 접근이 가능할까요? ```javascript -sessionStorage.setItem("cool_secret", 123); +sessionStorage.setItem('cool_secret', 123); ``` - A: 영원히, 데이터는 사라지지 않아요. @@ -684,10 +697,10 @@ sessionStorage.setItem("cool_secret", 123); - C: 사용자가 탭뿐만 아니라, 브라우저 전체를 닫을 때. - D: 사용자가 자신의 컴퓨터를 종료시켰을 때. -
정답 +

-#### 정답: B +#### 답: B `sessionStorage`에 저장된 데이터는 _탭_ 을 닫은 후에 삭제돼요. @@ -712,12 +725,12 @@ console.log(num); - C: `SyntaxError` - D: `ReferenceError` -

정답 +

-#### 정답: B +#### 답: B -`var` 키워드를 사용하면, 같은 이름으로 복수의 변수를 선언할 수 있어요. 변수는 최신의 값을 유지해요. +`var` 키워드를 사용하면, 같은 이름으로 복수의 변수를 선언할 수 있어요. 변수는 최신의 값을 가져요. 블록 스코프의 `let` 또는 `const`에서는 할 수 없어요. @@ -729,12 +742,12 @@ console.log(num); ###### 24. 무엇이 출력 될까요? ```javascript -const obj = { 1: "a", 2: "b", 3: "c" }; +const obj = { 1: 'a', 2: 'b', 3: 'c' }; const set = new Set([1, 2, 3, 4, 5]); -obj.hasOwnProperty("1"); +obj.hasOwnProperty('1'); obj.hasOwnProperty(1); -set.has("1"); +set.has('1'); set.has(1); ``` @@ -743,14 +756,14 @@ set.has(1); - C: `true` `true` `false` `true` - D: `true` `true` `true` `true` -

정답 +

-#### 정답: C +#### 답: C -모든 객체 키는(심볼 제외) 문자열로 직접 입력하지 않아도, 내부적으로는 문자열이에요. 이것이 `obj.hasOwnProperty('1')`도 true를 리턴하는 이유죠. +모든 객체의 키는(심볼 제외) 문자열로 직접 입력하지 않았다고 해도 내부적으로는 문자열이에요. 이것이 `obj.hasOwnProperty('1')`도 true를 반환하는 이유예요. -set에서는 작동하지 않아요. set에는 `'1'`이 없어요: `set.has('1')`는 `false`를 리턴해요. 그것은 수형인 `1`을 가지고 있어, `set.has(1)`는 `true`를 리턴해요. +set에서는 동작하지 않아요. set에는 `'1'`이 없어요: `set.has('1')`은 `false`를 반환해요. 숫자 유형인 `1`을 가지고 있어, `set.has(1)`는 `true`를 반환해요.

@@ -760,7 +773,7 @@ set에서는 작동하지 않아요. set에는 `'1'`이 없어요: `set.has('1') ###### 25. 무엇이 출력 될까요? ```javascript -const obj = { a: "one", b: "two", a: "three" }; +const obj = { a: 'one', b: 'two', a: 'three' }; console.log(obj); ``` @@ -769,28 +782,28 @@ console.log(obj); - C: `{ a: "three", b: "two" }` - D: `SyntaxError` -
정답 +

-#### 정답: C +#### 답: C -같은 이름의 키를 두 개 가지고 있다면, 여전히 첫 번째 위치에 있지만, 마지막에 지정된 값으로 대체될 거예요. +같은 이름의 키를 두 개 갖고 있다면, 키는 대체 될 거예요. 여전히 첫 번째 위치에 있지만, 마지막으로 지정된 값을 가져요.

--- -###### 26. JavaScript의 global execution context는 두개를 작성해요. : 전역객체와 "this" 키워드에요. +###### 26. JavaScript의 전역 실행 컨텍스트는 두가지를 만들어요: 전역객체와 "this" 키워드에요. - A: true - B: false - C: 경우에 따라 달라요 -
정답 +

-#### 정답: A +#### 답: A 기본적인 실행 콘텍스트는 전역 실행 문장이에요: 당신의 코드 모든 곳에서 접근할 수 있어요. @@ -813,12 +826,12 @@ for (let i = 1; i < 5; i++) { - C: `1` `2` `4` - D: `1` `3` `4` -

정답 +

-#### 정답: C +#### 답: C -`continue` 표현 식은 특정 조건이 `true`를 리턴하면 반복 처리를 건너뛰어요. +`continue` 표현 식은 특정 조건이 `true`를 반환하면 반복 처리를 건너뛰어요.

@@ -829,10 +842,10 @@ for (let i = 1; i < 5; i++) { ```javascript String.prototype.giveLydiaPizza = () => { - return "Just give Lydia pizza already!"; + return 'Just give Lydia pizza already!'; }; -const name = "Lydia"; +const name = 'Lydia'; name.giveLydiaPizza(); ``` @@ -842,12 +855,12 @@ name.giveLydiaPizza(); - C: `SyntaxError` - D: `undefined` -
정답 +

-#### 정답: A +#### 답: A -`String`은 내장 생성자로 속성을 추가할 수 있어요. 단지 프로토타입이라는 메소드를 추가했어요. 원시형 문자열은 문자열 프로토타입 함수에 의해 생성된 문자열 객체로 자동 변환돼요. 그래서, 모든 문자열(문자열 객체)은 그 메소드에 접근할 수 있어요! +`String`은 내장 생성자로 속성을 추가할 수 있어요. 그냥 문자열 프로토타입에 메소드를 추가한거예요. 원시형 문자열은 문자열 프로토타입 함수가 생성한 문자열 객체로 자동 변환돼요. 그래서, 모든 문자열(문자열 객체)은 그 메소드에 접근할 수 있어요!

@@ -858,8 +871,8 @@ name.giveLydiaPizza(); ```javascript const a = {}; -const b = { key: "b" }; -const c = { key: "c" }; +const b = { key: 'b' }; +const c = { key: 'c' }; a[b] = 123; a[c] = 456; @@ -872,16 +885,16 @@ console.log(a[b]); - C: `undefined` - D: `ReferenceError` -
정답 +

-#### 정답: B +#### 답: B -객체 키는 자동으로 문자열로 변환돼요. 객체 `a`의 키 값으로 `123`을 세팅하려고 해요. +객체 키는 자동으로 문자열로 변환돼요. 객체 `a`에 키는 객체(b), 값은 `123`으로 설정하려고 해요. 그러나, 객체를 문자열화 하면 `"[object Object]"`가 돼요. 그래서 여기서 말하고자 하는 건 `a["object Object"] = 123`이라는 거예요. 그 후, 같은 일을 다시 시도해요. `c`는 암묵적으로 문자열화 한 다른 객체에요. 그래서 `a["object Object"] = 456`이 돼요. -그 후, `a[b]`는 출력하면 실제로는 `a["object Object"]`에요. 단지 `456`을 설정했기 때문에, `456`을 리턴해요. +그 후, `a[b]`를 출력하면 실제로는 `a["object Object"]`예요. 그냥 `456`을 설정했기 때문에, `456`을 반환해요.

@@ -891,9 +904,9 @@ console.log(a[b]); ###### 30. 무엇이 출력 될까요? ```javascript -const foo = () => console.log("First"); -const bar = () => setTimeout(() => console.log("Second")); -const baz = () => console.log("Third"); +const foo = () => console.log('First'); +const bar = () => setTimeout(() => console.log('Second')); +const baz = () => console.log('Third'); bar(); foo(); @@ -905,14 +918,14 @@ baz(); - C: `Second` `First` `Third` - D: `Second` `Third` `First` -
정답 +

-#### 정답: B +#### 답: B 처음에 `setTimeout`함수를 호출했어요. 그러나 그것은 마지막에 출력돼요. -브라우저에는 런타임 엔진뿐만 아니라 `WebAPI`라고 불리는 것도 있기 때문이에요. `WebAPI`는 `setTimeout`함수를 최초에 부여하는데, DOM을 예로 들 수 있어요. +브라우저에는 런타임 엔진뿐만 아니라 `WebAPI`라고 불리는 것도 존재해요. `WebAPI`는 `setTimeout`함수를 최초에 부여하는데, DOM을 예로 들 수 있어요. _callback_ 이 WebAPI에 푸시된 후, `setTimeout`함수 자체(callback이 아니에요!)는 stack에 사라졌어요. @@ -946,9 +959,7 @@ WebAPI는 준비가 될 때마다 stack에 항목을 추가할 수 없어요. ```html

- +
``` @@ -958,25 +969,23 @@ WebAPI는 준비가 될 때마다 stack에 항목을 추가할 수 없어요. - C: `button` - D: 중첩된 모든 요소의 배열 -
정답 +

-#### 정답: C +#### 답: C -가장 깊이 중첩된 요소가 이벤트를 발생시킬 이벤트 대상이에요. `event.stopPropagation`을 통해서 버블링을 중단할 수 있어요. +가장 깊이 중첩된 요소가 이벤트를 발생시킬 이벤트 대상이예요. `event.stopPropagation`을 통해서 버블링을 중단할 수 있어요.

--- -###### 32. p태그를 클릭하면 로그의 출력은 무엇일까요? +###### 32. p태그를 클릭하면 출력된 로그는 무엇일까요? ```html
-

- Click here! -

+

Click here!

``` @@ -985,12 +994,12 @@ WebAPI는 준비가 될 때마다 stack에 항목을 추가할 수 없어요. - C: `p` - D: `div` -
정답 +

-#### 정답: A +#### 답: A -`p`를 클릭하면, 2개의 로그를 볼 수 있어요: `p` 그리고 `div`. 이벤트의 전파 중에는 3단계가 있어요: 캡처링, 타겟, 버블링. 기본적으로, 이벤트 핸들러는 버블링 단계에서 시작돼요. (`useCapture`를 `true`로 설정하지 않는 한). 가장 깊게 중첩된 요소로부터 바깥쪽으로 나가요. +`p`를 클릭하면, 2개의 로그를 볼 수 있어요: `p` 그리고 `div`. 이벤트의 전파 중에는 3단계가 있어요: 캡처링, 타겟, 버블링. 기본적으로, 이벤트 핸들러는 버블링 단계에서 시작돼요. (`useCapture`를 `true`로 설정하지 않는 한). 가장 깊게 중첩된 요소에서 바깥쪽으로 가요.

@@ -1000,7 +1009,7 @@ WebAPI는 준비가 될 때마다 stack에 항목을 추가할 수 없어요. ###### 33. 무엇이 출력 될까요? ```javascript -const person = { name: "Lydia" }; +const person = { name: 'Lydia' }; function sayHi(age) { console.log(`${this.name} is ${age}`); @@ -1015,14 +1024,14 @@ sayHi.bind(person, 21); - C: `Lydia is 21` `Lydia is 21` - D: `Lydia is 21` `function` -
정답 +

-#### 정답: D +#### 답: D -두 개 모두, `this` 키워드를 참조하고자 하는 객체로 보낼 수 있어요. 그러나, `.call`은 _즉시 실행돼요_! +두 개 모두, `this` 키워드를 참조하고자 하는 객체로 보낼 수 있어요. 그렇지만, `.call`은 _즉시 실행돼요_! -`.bind.`는 함수의 _복사본_ 을 리턴하지만, 바인딩 콘텍스트죠! 이건 즉시 실행되지 않아요. +`.bind.`는 함수의 _복사본_ 을 반환하지만, 바인딩된 콘텍스트죠! 즉시 실행되지 않아요.

@@ -1044,27 +1053,27 @@ console.log(typeof sayHi()); - C: `"function"` - D: `"undefined"` -
정답 +

-#### 정답: B +#### 답: B -`sayHi`함수는 즉시 호출 함수(IIFE)로서 리턴된 값을 리턴해요. 이 함수는 `0`을 리턴하고, 형은 `"number"`이에요. +`sayHi`함수는 즉시 호출 함수 표현식(IIFE)으로서 반환된 값을 반환해요. 이 함수는 `0`을 반환하고, 형은 `"number"`이에요. -참고: 단 7개의 내장형이 있어요: `null`, `undefined`, `boolean`, `number`, `string`, `object`, `symbol` 그리고 `bigint`. `"function"`은 객체이기 때문에 형이 아니라 `"object"`형이에요. +참고: 내장된 형은 7개만 있어요: `null`, `undefined`, `boolean`, `number`, `string`, `object` 그리고 `symbol`. 함수는 객체이기 때문에 `"function"`은 형이 아니라 `"object"`형이에요.

--- -###### 35. 이 값들 중 어느 것이 거짓 같은 값 일까요? +###### 35. 이 값 중 어느 것이 거짓 같은 값 일까요? ```javascript 0; new Number(0); -(""); -(" "); +(''); +(' '); new Boolean(false); undefined; ``` @@ -1074,19 +1083,21 @@ undefined; - C: `0`, `''`, `new Boolean(false)`, `undefined` - D: 모든 값은 거짓 -
정답 +

-#### 정답: A +#### 답: A -단 6개의 거짓 같은 값이 있어요: +8개의 거짓 같은 값이 있어요: - `undefined` - `null` - `NaN` -- `0` -- `''` (빈 문자열) - `false` +- `''` (빈 문자열) +- `0` +- `-0` +- `-0n` (BigInt(0)) `new Number` 그리고 `new Boolean`과 같은 생성자 함수는 참 같은 값이에요. @@ -1106,13 +1117,13 @@ console.log(typeof typeof 1); - C: `"object"` - D: `"undefined"` -

정답 +

-#### 정답: B +#### 답: B -`typeof 1` 은 `"number"`를 리턴해요. -`typeof "number"`은 `"string"`을 리턴해요. +`typeof 1` 은 `"number"`를 반환해요. +`typeof "number"`은 `"string"`을 반환해요.

@@ -1132,16 +1143,15 @@ console.log(numbers); - C: `[1, 2, 3, 7 x empty, 11]` - D: `SyntaxError` -
정답 +

-#### 정답: C +#### 답: C -배열의 길이를 초과한 값을 배열의 요소로 설정하고자 할 때, JavaScript는 "empty slots"라고 불리는 것을 생성해요. 이것은 실제로 `undefined`의 값을 가지고 있지만, 다음과 같은 것을 보게 될 거예요: +배열의 길이를 초과한 값을 배열의 요소로 설정하고자 할 때, JavaScript는 "empty slots"라고 불리는 것을 생성해요. 이것은 사실 `undefined`의 값을 가지고 있지만, 다음과 같은 것을 보게 될 거예요: `[1, 2, 3, 7 x empty, 11]` -depending on where you run it (it's different for every browser, node, etc.) 실행 위치에 따라 달라요 (브라우저, node 등마다 달라요.)

@@ -1170,16 +1180,16 @@ depending on where you run it (it's different for every browser, node, etc.) - C: `1` `1` `2` - D: `1` `undefined` `undefined` -
정답 +

-#### 정답: A +#### 답: A -`catch`블록은 `x`의 인수를 받아요. 이것은 인수를 전달할 때 변수로서의 `x`와는 달라요. 이 `x` 변수는 블록-스코프예요. +`catch`블록은 인수`x`를 받아요. 이것은 인수를 전달할 때 변수로서의 `x`와는 달라요. 이 `x` 변수는 블록-스코프예요. 후에, 블록-스코프 변수는 `1`로 설정하고, 변수 `y`의 값을 설정해요. 여기서, 블록-스코프의 변수 `x`를 출력하는데, 이것은 `1`이에요. -`catch` 블록 밖에서, `x`는 여전히 `undefined`이고 `y`는 `2`이에요. `catch` 블록 밖에서 `console.log(x)`를 출력하면, `undefined`를 리턴하고. 그리고 `y`는 `2`를 리턴해요. +`catch` 블록 밖에서, `x`는 여전히 `undefined`이고 `y`는 `2`이에요. `catch` 블록 밖에서 `console.log(x)`를 출력하면, `undefined`를 반환하고. 그리고 `y`는 `2`를 반환해요.

@@ -1193,16 +1203,16 @@ depending on where you run it (it's different for every browser, node, etc.) - C: 함정 문제! objects만 - D: number 또는 object -
정답 +

-#### 정답: A +#### 답: A JavaScript는 원시형과 객체만 가지고 있어요. 원시형은 `boolean`, `null`, `undefined`, `bigint`, `number`, `string` 그리고 `symbol`이 있어요. -원시형과 객체를 구별하는 법은 원시형에는 속성이나 메소드가 없어요. 그러나 `'foo'.toUpperCase()`는 `'FOO'`로 평가되어, `TypeError`의 결과가 되지 않아요. 문자열과 같은 원시형이 속성 또는 메소드에 접근하려고 할 때, JavaScript는 래퍼 클래스 중 하나인 `String`을 사용하여 암묵적으로 감싸고, 표현 식이 평가된 후 즉시 래퍼를 폐기하기 때문이에요. `null` 그리고 `undefined`를 제외한 모든 원시형은 이러한 행동을 합니다. +원시형과 객체를 구별하는 법은 원시형에는 속성이나 메소드가 없어요. 그렇지만 `'foo'.toUpperCase()`는 `'FOO'`로 평가되어, 결과적으로 `TypeError`가 되지 않아요. 문자열과 같은 원시형이 속성 또는 메소드에 접근하려고 할 때, JavaScript는 래퍼 클래스 중 하나인 `String`을 사용하여 암묵적으로 감싸고, 표현 식이 평가된 후 즉시 래퍼를 폐기하기 때문이에요. `null` 그리고 `undefined`를 제외한 모든 원시형은 이러한 행동을 합니다.

@@ -1212,7 +1222,10 @@ JavaScript는 원시형과 객체만 가지고 있어요. ###### 40. 무엇이 출력 될까요? ```javascript -[[0, 1], [2, 3]].reduce( +[ + [0, 1], + [2, 3], +].reduce( (acc, cur) => { return acc.concat(cur); }, @@ -1225,14 +1238,14 @@ JavaScript는 원시형과 객체만 가지고 있어요. - C: `[1, 2, 0, 1, 2, 3]` - D: `[1, 2, 6]` -
정답 +

-#### 정답: C +#### 답: C -`[1, 2]`은 초깃값이에요. 이것이 최초의 값으로, 제일 처음의 `acc`의 값이에요. 처음 라운드 동안에 `acc`는 `[1,2]`이며, `cur`은 `[0, 1]`이에요. 그것들을 연결하면 결과적으로 `[1, 2, 0, 1]`이 돼요. +`[1, 2]`은 초기값이에요. 이것은 시작하는 최초의 값이고, `acc`의 제일 처음 값이에요. 처음 라운드 동안에 `acc`는 `[1,2]`이며, `cur`은 `[0, 1]`이에요. 그것을 연결하면 결과적으로 `[1, 2, 0, 1]`이 돼요. -그 후, `[1, 2, 0, 1]`은 `acc`이고, `[2, 3]`은 `cur`이 에요. 그것들을 연결하면 `[1, 2, 0, 1, 2, 3]`을 얻게 돼요. +그 후, `[1, 2, 0, 1]`은 `acc`이고, `[2, 3]`은 `cur`이에요. 그것을 연결하면 `[1, 2, 0, 1, 2, 3]`을 얻게 돼요.

@@ -1243,7 +1256,7 @@ JavaScript는 원시형과 객체만 가지고 있어요. ```javascript !!null; -!!""; +!!''; !!1; ``` @@ -1252,26 +1265,26 @@ JavaScript는 원시형과 객체만 가지고 있어요. - C: `false` `true` `true` - D: `true` `true` `false` -
정답 +

-#### 정답: B +#### 답: B -`null`은 거짓 같은 값이에요. `!null`은 `true`를 리턴해요. `!true`는 `false`를 리턴해요. +`null`은 거짓 같은 값이에요. `!null`은 `true`를 반환해요. `!true`는 `false`를 반환해요. -`""` 은 거짓 같은 값이에요. `!""`은 `true`를 리턴해요. `!true`는 `false`를 리턴해요. +`""` 은 거짓 같은 값이에요. `!""`은 `true`를 반환해요. `!true`는 `false`를 반환해요. -`1`은 참 같은 값이에요. `!1`은 `false`를 리턴해요. `!false`는`true`를 리턴해요. +`1`은 참 같은 값이에요. `!1`은 `false`를 반환해요. `!false`는 `true`를 반환해요.

--- -###### 42. `setInterval` 메소드는 브라우저에게 무엇을 리턴 할까요? +###### 42. `setInterval` 메소드는 브라우저에게 무엇을 반환 할까요? ```javascript -setInterval(() => console.log("Hi"), 1000); +setInterval(() => console.log('Hi'), 1000); ``` - A: 유니크한 id @@ -1279,22 +1292,22 @@ setInterval(() => console.log("Hi"), 1000); - C: 통과된 함수 - D: `undefined` -
정답 +

-#### 정답: A +#### 답: A -이것은 유니크한 id를 리턴해요. 이 id는 `clearInterval()` 함수로 간격을 없애기 위해 사용될 수 있어요. +이것은 유니크한 id를 반환해요. 이 id는 `clearInterval()` 함수의 간격을 없애기 위해 사용될 수 있어요.

--- -###### 43. 이것은 무엇을 리턴할까요? +###### 43. 이것은 무엇을 반환할까요? ```javascript -[..."Lydia"]; +[...'Lydia']; ``` - A: `["L", "y", "d", "i", "a"]` @@ -1302,12 +1315,12 @@ setInterval(() => console.log("Hi"), 1000); - C: `[[], "Lydia"]` - D: `[["L", "y", "d", "i", "a"]]` -
정답 +

-#### 정답: A +#### 답: A -문자열은 반복 가능한 객체예요. 스프레드 연산자는 반복 가능한 객체의 모든 문자를 1개의 요소로 매핑해요. +문자열은 반복 가능한 객체예요. 스프레드 연산자는 반복 가능한 객체의 모든 문자를 하나의 요소로 매핑해요.

@@ -1333,34 +1346,34 @@ console.log(gen.next().value); - C: `10, 20` - D: `0, 10` 그리고 `10, 20` -
정답 +

-#### 정답: C +#### 답: C -보통의 함수는 호출 후에 중단할 수 없어요. 하지만, 제너레이터 함수는 중간에 "멈췄다가", 나중에 중단된 부분부터 계속할 수 있어요. 제너레이터 함수는 `yield` 키워드를 만날 때마다, yield 뒤에 지정된 값을 넘겨줘요. 제너레이터 함수에서는 값을 _리턴_ 하지 않고, _넘겨준다_ 는 것을 유의하세요. +일반 함수는 호출 한 뒤 중간에 멈출 수 없어요. 하지만, 제너레이터 함수는 중간에 "멈췄다가", 나중에 중단된 부분부터 계속할 수 있어요. 제너레이터 함수는 `yield` 키워드를 만날 때마다, yield 뒤에 명시된 값을 넘겨줘요. 제너레이터 함수에서는 값을 _반환_ 하지 않고, 값을 _넘겨진다_ 는 것을 유의하세요. 우선, 제너레이터 함수에서 `i`를 `10`으로 초기화해요. `next()` 메소드를 사용해 제너레이터 함수를 호출해요. 처음에 제너레이터 함수를 호출하면, `i`은 `10`이에요. 첫 번째 `yield` 키워드를 만났어요: 그것은 `i`의 값을 넘겨줘요. 이제 제너레이터는 "멈추고", `10`을 출력해요. -그 후, `next()` 메소드를 사용해 다시 한번 함수를 호출해요. `i`는 여전히 `10`이에요. 이제, 다음 `yield` 키워드를 만나 `i * 2`를 넘겨줘요. `i`는 `10`이므로, `10 * 2`, 즉 `20`을 리턴해요. 결과는 `10, 20`이에요. +그 후, `next()` 메소드를 사용해 함수를 다시 호출해요. 이전에 멈춘 부분에서부터 다시 시작하고, `i`는 여전히 `10`이에요. 이제, 다음 `yield` 키워드를 만나 `i * 2`를 넘겨줘요. `i`는 `10`이므로, `10 * 2`, 즉 `20`을 반환해요. 결과는 `10, 20`이에요.

--- -###### 45. 이것은 무엇을 리턴할까요? +###### 45. 이것은 무엇을 반환할까요? ```javascript const firstPromise = new Promise((res, rej) => { - setTimeout(res, 500, "one"); + setTimeout(res, 500, 'one'); }); const secondPromise = new Promise((res, rej) => { - setTimeout(res, 100, "two"); + setTimeout(res, 100, 'two'); }); -Promise.race([firstPromise, secondPromise]).then(res => console.log(res)); +Promise.race([firstPromise, secondPromise]).then((res) => console.log(res)); ``` - A: `"one"` @@ -1368,12 +1381,12 @@ Promise.race([firstPromise, secondPromise]).then(res => console.log(res)); - C: `"two" "one"` - D: `"one" "two"` -
정답 +

-#### 정답: B +#### 답: B -복수의 프로미스를 `Promise.race` 메소드에 넘겨주면, _최초_ 의 프로미스를 해결/거부해요. `setTimeout` 메소드에 타이머를 전달해요: 첫 번째 프로미스(`firstPromise`)에는 500ms, 두 번째 프로미스(`secondPromise`)에는 100ms. 이것은 `'two'`의 값을 가진 `secondPromise`가 최초로 해결한다는 것을 의미해요. 이제 `res`는 `'two'`의 값을 유지하고 출력돼요. +복수의 프로미스를 `Promise.race` 메소드에 넘겨주면, _최초_ 의 프로미스를 해결/거부해요. `setTimeout` 메소드에 타이머를 전달해요: 첫 번째 프로미스(`firstPromise`)에는 500ms, 두 번째 프로미스(`secondPromise`)에는 100ms. 이것은 `'two'`의 값을 가진 `secondPromise`를 최초로 해결한다는 것을 의미해요. 이제 `res`는 `'two'`의 값을 갖고 출력돼요.

@@ -1383,7 +1396,7 @@ Promise.race([firstPromise, secondPromise]).then(res => console.log(res)); ###### 46. 무엇이 출력 될까요? ```javascript -let person = { name: "Lydia" }; +let person = { name: 'Lydia' }; const members = [person]; person = null; @@ -1395,16 +1408,16 @@ console.log(members); - C: `[{}]` - D: `[{ name: "Lydia" }]` -
정답 +

-#### 정답: D +#### 답: D 우선, 변수 `person`의 값을 `name` 속성을 가진 객체로 선언해요. -그 후, `members`라는 변수를 선언해요. 배열의 첫 번째 요소에 `person` 변수의 값을 대입해요. 서로를 같게 설정하면 _참조_ 에 의해 상호작용해요. 어떤 변수에서 다른 변수로 참조를 할당하면, 그 참조의 _복사본_ 을 만들어요. (그들은 _같은_ 참조를 가지고 있지 않다는 것을 유의하세요!) +그 후, `members`라는 변수를 선언해요. 배열의 첫 번째 요소에 `person` 변수의 값을 대입해요. 서로를 같게 설정하면 _참조_로 상호작용해요. 어떤 변수에서 다른 변수로 참조를 할당하면, 그 참조의 _복사본_ 을 만들어요. (그들은 _같은_ 참조를 가지고 있지 않다는 것을 유의하세요!) @@ -1412,7 +1425,7 @@ console.log(members); -배열의 첫 번째 요소는 객체에 대한 다른 (복사된) 참조를 가지고 있기 때문에, `person` 변수의 값만 변경하고, 배열의 첫 번째 요소는 변경할 수 없어요. `members`의 첫 번째 요소는 여전히 원본 객체에 대한 참조를 유지하고 있어요. `members` 배열을 출력할 때, 첫 번째 요소는 여전히 객체의 값을 유지하고 있어 로그가 출력돼요. +`person` 변수의 값만 변경할 수 있고, 배열의 첫 번째 요소는 객체에 대한 다른 (복사된) 참조를 가지고 있기 때문에 변경할 수 없어요. `members`의 첫 번째 요소는 여전히 원본 객체에 대한 참조를 유지하고 있어요. `members` 배열을 출력할 때, 첫 번째 요소는 여전히 객체의 값을 갖고 있어 로그가 출력돼요.

@@ -1423,8 +1436,8 @@ console.log(members); ```javascript const person = { - name: "Lydia", - age: 21 + name: 'Lydia', + age: 21, }; for (const item in person) { @@ -1437,12 +1450,12 @@ for (const item in person) { - C: `"Lydia", 21` - D: `["name", "Lydia"], ["age", 21]` -
정답 +

-#### 정답: B +#### 답: B -`for-in` 루프를 사용하면, 객체 키를 통해서 반복할 수 있는데, 이 경우에서는 `name` 그리고 `age`에요. 내부적으로, 객체 키는 문자열이에요 (심볼이 아니라면 말이죠). 모든 루프에서, `item`의 값은 반복된 현재의 키 값으로 설정해요. 우선, `item`은 `name`으로 출력돼요. 그 후, `item`은 `age`로 출력돼요. +`for-in` 루프를 사용하면, 객체의 키를 통해서 반복할 수 있는데, 이 경우에서는 `name` 그리고 `age`에요. 내부적으로, 객체의 키는 문자열이에요 (심볼이 아니라면 말이죠). 모든 루프에서, `item`의 값은 반복 중인 현재의 키 값으로 동일하게 설정해요. 우선, `item`은 `name`으로 출력돼요. 그 후, `item`은 `age`로 출력돼요.

@@ -1452,7 +1465,7 @@ for (const item in person) { ###### 48. 무엇이 출력 될까요? ```javascript -console.log(3 + 4 + "5"); +console.log(3 + 4 + '5'); ``` - A: `"345"` @@ -1460,16 +1473,16 @@ console.log(3 + 4 + "5"); - C: `12` - D: `"12"` -
정답 +

-#### 정답: B +#### 답: B -연산자 결합성은 왼쪽에서 오른쪽 또는 오른쪽에서 왼쪽으로 컴파일러가 표현 식을 평가하는 순서가 돼요. 이것은 연산자가 _같은_ 우선순위를 가진 경우에만 해당돼요. 연산자의 종류는 한 개뿐이에요: `+`. 게다가, 결합성은 왼쪽에서 오른쪽이에요. +연산자 결합성은 왼쪽에서 오른쪽 또는 오른쪽에서 왼쪽으로 컴파일러가 표현 식을 평가하는 순서가 돼요. 이것은 연산자가 _같은_ 우선순위를 가진 경우에만 해당돼요. 한 유형의 연산자만 있어요: `+`. 게다가, 결합성은 왼쪽에서 오른쪽이에요. 처음으로 `3 + 4`가 평가돼요. 결과는 숫자 `7`이에요. -`7 + '5'`의 결과는 강제성 때문에 `"75"`가 돼요. JavaScript는 숫자 `7`을 문자열로 변환하고, (자세한 내용은) 질문 15를 보세요. `+` 연산자를 사용해서 두 개의 문자열을 연결할 수 있어요. `"7" + "5"`의 결과는 `"75"`이에요. +`7 + '5'`의 결과는 강제성 때문에 `"75"`가 돼요. JavaScript는 숫자 `7`을 문자열로 변환하고, (관련된 자세한 설명은) 질문 15를 보세요. `+` 연산자를 사용해서 두 개의 문자열을 연결할 수 있어요. `"7" + "5"`의 결과는 `"75"`이에요.

@@ -1479,7 +1492,7 @@ console.log(3 + 4 + "5"); ###### 49. `num`의 값은 무엇일까요? ```javascript -const num = parseInt("7*6", 10); +const num = parseInt('7*6', 10); ``` - A: `42` @@ -1487,14 +1500,14 @@ const num = parseInt("7*6", 10); - C: `7` - D: `NaN` -
정답 +

-#### 정답: C +#### 답: C -문자열의 첫 번째 숫자만 리턴돼요. _진법_ 에 근거하여 (파싱하고자 하는 숫자의 기준을 명시하기 위한 두 번째 인수: 기본적인 10진수, 6진수, 8진수, 2진수 등), `parseInt`는 문자열 내의 문자가 타당한지 여부를 확인해요. 진수에 유효한 숫자가 아닌 문자를 만나면, 파싱을 멈추고, 다음 문자를 무시해요. +문자열의 첫 번째 숫자만 반환돼요. _진법_ 에 근거해(파싱하고자 하는 숫자의 기준을 명시하기 위한 두 번째 인수: 기본 10진수, 6진수, 8진수, 2진수 등), `parseInt`는 문자열 내의 문자가 타당한지 여부를 확인해요. 진수에 유효한 숫자가 아닌 문자를 만나면, 파싱을 멈추고, 다음 문자를 무시해요. -`*`은 유효한 숫자가 아니에요. `"7"`만 십진수의 `7`로 파싱 돼요. 이제 `num`은 `7`의 값을 유지해요. +`*`은 유효한 숫자가 아니에요. `"7"`만 십진수의 `7`로 파싱 돼요. 이제 `num`은 `7`의 값을 가져요.

@@ -1504,10 +1517,10 @@ const num = parseInt("7*6", 10); ###### 50. 무엇이 출력 될까요? ```javascript -[1, 2, 3].map(num => { - if (typeof num === "number") return; +[1, 2, 3].map((num) => { + if (typeof num === 'number') return; return num * 2; - }); +}); ``` - A: `[]` @@ -1515,14 +1528,14 @@ const num = parseInt("7*6", 10); - C: `[undefined, undefined, undefined]` - D: `[ 3 x empty ]` -
정답 +

-#### 정답: C +#### 답: C -배열을 매핑할 때, `num`의 값은 헌재 순환하고 있는 요소예요. 이 경우, 요소는 숫자이기 때문에, if 문의 조건 `typeof num === "number"`는 `true`를 리턴해요. map 합수는 새로운 배열을 만들고 함수에서 리턴된 값을 삽입해요. +배열을 매핑할 때, `num`의 값은 헌재 순환하고 있는 요소예요. 이 경우 요소는 숫자이기 때문에, if 문의 조건 `typeof num === "number"`는 `true`를 반환해요. map 함수는 새로운 배열을 만들고 함수에서 반환된 값을 삽입해요. -그러나, 값을 리턴하지 않아요. 함수는 값을 리턴하지 않을 때, `undefined`를 리턴해요. 배열에서의 모든 요소에 대해 블록 함수가 호출되기 때문에, 각 요소에 대해 `undefined`를 리턴해요. +그러나, 우리는 값을 반환하지 않아요. 함수는 값을 반환하지 않을 때 `undefined`를 반환해요. 배열에서의 모든 요소에 대해 함수 블록이 호출되므로, 각 요소에 대해 `undefined`를 반환해요.

@@ -1533,12 +1546,12 @@ const num = parseInt("7*6", 10); ```javascript function getInfo(member, year) { - member.name = "Lydia"; - year = "1998"; + member.name = 'Lydia'; + year = '1998'; } -const person = { name: "Sarah" }; -const birthYear = "1997"; +const person = { name: 'Sarah' }; +const birthYear = '1997'; getInfo(person, birthYear); @@ -1550,16 +1563,16 @@ console.log(person, birthYear); - C: `{ name: "Lydia" }, "1998"` - D: `{ name: "Sarah" }, "1997"` -
정답 +

-#### 정답: A +#### 답: A -인수들의 값이 객체가 아닌 한 _값_ 에 의해 전달돼요. 그 후 _참조_ 에 의해 전달돼요. `birthYear`는 객체가 아니라 문자열이기 때문에 값에 의해 전달돼요. 값으로 전달하면 값의 _복사본_ 이 만들어져요(질문 46을 보세요). +인수는 값이 객체가 아니면 _값_ 으로 전달되고, 그렇지 않으면(값이 객체면) _참조_ 로 전달돼요. `birthYear`는 객체가 아니라 문자열이기 때문에 값으로 전달돼요. 값으로 전달하면 값의 _복사본_ 이 만들어져요(질문 46을 보세요). 변수 `birthYear`는 `"1997"`값에 대한 참조를 가져요. 인수 `year` 또한 `"1997"`에 대한 참조를 가지지만, `birthYear`가 가진 참조 값과는 달라요. `year`에 `"1998"`을 대입하여 `year`의 값을 업데이트할 때, `year`의 값만 업데이트해요. `birthYear`는 여전히 `"1997"`이에요. -`person`의 값은 객체예요. 인수 `member`는 _같은_ 객체의 (복사된) 참조 값을 가져요. `member`객체의 속성이 갖는 참조를 변경하면, 두 개 모두 같은 객체를 참조 값을 가지고 있기 때문에, `person`의 값 또한 변경돼요. 이제 `person`'의 `name` 속성은값 `"Lydia"`에요. +`person`의 값은 객체예요. 인수 `member`는 _같은_ 객체의 (복사된) 참조를 가져요. 참조를 가진 `member`객체의 속성을 변경하면, 두 개 모두 같은 객체의 참조를 가지고 있기 때문에, `person`도 변경돼요. 이제 `person`'의 `name` 속성의 값은 `"Lydia"`예요.

@@ -1570,15 +1583,15 @@ console.log(person, birthYear); ```javascript function greeting() { - throw "Hello world!"; + throw 'Hello world!'; } function sayHi() { try { const data = greeting(); - console.log("It worked!", data); + console.log('It worked!', data); } catch (e) { - console.log("Oh no an error:", e); + console.log('Oh no an error:', e); } } @@ -1590,14 +1603,14 @@ sayHi(); - C: `SyntaxError: can only throw Error objects` - D: `"Oh no an error: Hello world!"` -
정답 +

-#### 정답: D +#### 답: D -`throw`문을 사용해, 커스텀 에러를 만들 수 있어요. 이 표현 식을 사용해, 예외를 던질 수 있어요. 예외는 string, a number, a boolean or an object이 될 수 있어요. 이 경우, 예외는 `'Hello world'` 문자열이에요. +`throw`문을 사용해, 사용자 지정 오류를 만들 수 있어요. 이 표현 식을 사용해, 예외를 던질 수 있어요. 예외는 문자열, 숫자, 불린 또는 객체가 될 수 있어요. 이 경우, 예외는 `'Hello world'` 문자열이에요. -`catch` 문을 사용해, `try` 블록에서 예외가 던져졌을 경우에 무엇을 할지 명시할 수 있어요. 예외가 던져졌어요: 문자열 `'Hello world'`. `e`는 이제 문자열이고, 그것을 출력해요. 결과는 `'Oh an error: Hello world'`예요. +`catch` 문을 사용해, `try` 블록에서 예외를 던진 경우 무엇을 할지 명시할 수 있어요. 예외가 던져졌어요: 문자열 `'Hello world'`. 이제 `e`는 문자열이고, 그것을 출력해요. 결과는 `'Oh an error: Hello world'`예요.

@@ -1608,8 +1621,8 @@ sayHi(); ```javascript function Car() { - this.make = "Lamborghini"; - return { make: "Maserati" }; + this.make = 'Lamborghini'; + return { make: 'Maserati' }; } const myCar = new Car(); @@ -1621,12 +1634,12 @@ console.log(myCar.make); - C: `ReferenceError` - D: `TypeError` -
정답 +

-#### 정답: B +#### 답: B -속성을 리턴할 때, 속성값은 생성자에 설정한 값이 아닌, _리턴된_ 값과 같아요. `"Maserati"` 문자열을 리턴하기 때문에, `myCar.make`는 `"Maserati"`에요. +속성을 반환할 때, 속성값은 생성자에 설정한 값이 아닌, _반환된_ 값과 같아요. `"Maserati"` 문자열을 반환하기 때문에, `myCar.make`는 `"Maserati"`예요.

@@ -1649,10 +1662,10 @@ console.log(typeof y); - C: `"object", "number"` - D: `"number", "undefined"` -
정답 +

-#### 정답: A +#### 답: A `let x = y = 10;`은 다음의 단축형이에요: @@ -1661,11 +1674,11 @@ y = 10; let x = y; ``` -`y`에 `10`을 대입하면, 실제로는 전역 객체에 속성 `y`를 추가해요(브라우저에서는 `window`, Node에서는 `global`). 브라우저에서, `window.y`는 이제 `10`이에요. +`y`에 `10`을 대입하면, 전역 객체에 속성 `y`를 추가해요(브라우저에서는 `window`, Node에서는 `global`). 브라우저에서, `window.y`는 이제 `10`이에요. -그 후, 변수 `x`를 `10`인 `y`를 값으로 선언해요. `let`키워드로 선언된 변수는 _블록 스코프_ 로, 선언된 블록 내에서만 정의돼요: 이 경우 즉시 호출 함수예요(IIFE). `typeof`연산자를 사용할 때, 피연산자 `x`는 정의되지 않았어요: 선언된 블록 밖에서 접근하려 했어요. 이것은 `x`가 선언되지 않음을 의미해요. 값을 할당하거나 선언하지 않은 변수는 `"undefined"` 형이에요. `console.log(typeof x)`는 `"undefined"`를 리턴해요. +그 후, 변수 `x`를 `10`인 `y`를 값으로 선언해요. `let`키워드로 선언된 변수는 _블록 스코프_ 로, 선언된 블록 내에서만 정의돼요: 이 경우에선 즉시 호출 함수예요(IIFE). `typeof`연산자를 사용할 때, 피연산자 `x`는 정의되지 않았어요: 우리는 선언된 블록 밖에서 접근하려 했어요. 이것은 `x`가 정의되지 않았음을 의미해요. 값을 할당하지 않거나 선언하지 않은 변수는 `"undefined"` 형이에요. `console.log(typeof x)`는 `"undefined"`를 반환해요. -그러나, `y`를 `10`으로 설정할 때 전역 변수 `y`를 만들었어요. 이 값은 코드 내 어디에서나 접근할 수 있어요. `y`는 정의되었고, `"number"`형의 값을 유지해요. `console.log(typeof y)`는 `"number"`을 리턴해요. +그러나, `y`를 `10`으로 설정할 때 전역 변수 `y`를 만들었어요. 이 값은 코드 내 어디에서나 접근할 수 있어요. `y`는 정의되어있고, `"number"`형의 값을 유지해요. `console.log(typeof y)`는 `"number"`을 반환해요.

@@ -1681,11 +1694,11 @@ class Dog { } } -Dog.prototype.bark = function() { +Dog.prototype.bark = function () { console.log(`Woof I am ${this.name}`); }; -const pet = new Dog("Mara"); +const pet = new Dog('Mara'); pet.bark(); @@ -1699,12 +1712,12 @@ pet.bark(); - C: `"Woof I am Mara"`, `undefined` - D: `TypeError`, `TypeError` -
정답 +

-#### 정답: A +#### 답: A -프로토타입에서도 `delete`키워드를 사용해, 객체로부터 속성을 삭제할 수 있어요. 프로토타입에서 속성을 삭제하면, 프로토타입 체인에서 더는 사용할 수 없게 돼요. 이 경우, `bark` 함수는 `delete Dog.prototype.bark` 후에 프로토타입에서 더는 사용할 수 없게 되지만, 그래도 여전히 그것에 접근하려고 해요. +프로토타입에서도 `delete`키워드를 사용해 객체의 속성을 삭제할 수 있어요. 프로토타입에서 속성을 삭제하면, 프로토타입 체인에서 더는 사용할 수 없어요. 이 경우, `bark` 함수는 `delete Dog.prototype.bark` 후에는 프로토타입에서 더는 사용할 수 없게 되었어요, 그러나 우리는 여전히 그것에 접근하려고 해요. 함수가 아닌 것을 호출하려고 할 때, `TypeError`가 던져져요. 이 경우 `pet.bark`는 `undefined`이기 때문에, `TypeError: pet.bark is not a function`예요. @@ -1726,14 +1739,14 @@ console.log(set); - C: `{1, 1, 2, 3, 4}` - D: `{1, 2, 3, 4}` -

정답 +

-#### 정답: D +#### 답: D `Set`은 _unique_ 값의 집합 객체예요: 값은 set 내에서 단 한 번만 발생해요. -중복 값 `1`을 가진 반복 가능한 `[1, 1, 2, 3, 4]`을 전달하기 때문에, 그들 중 하나는 삭제돼요. 이것은 결과적으로 `{1, 2, 3, 4}`돼요. +중복 값 `1`을 가진 반복 가능한 `[1, 1, 2, 3, 4]`을 전달하기 때문에, 그 중 하나는 삭제돼요. 이것은 결과적으로 `{1, 2, 3, 4}`돼요.

@@ -1750,7 +1763,7 @@ export default counter; ```javascript // index.js -import myCounter from "./counter"; +import myCounter from './counter'; myCounter += 1; @@ -1762,14 +1775,14 @@ console.log(myCounter); - C: `Error` - D: `NaN` -
정답 +

-#### 정답: C +#### 답: C -import 된 모듈은 _read-only_ 예요 : import 된 모듈은 수정할 수 없어요. export 한 모듈만 값을 변경할 수 있어요. +import 된 모듈은 _read-only_ 예요 : import 된 모듈은 수정할 수 없어요. export 한 모듈에서만 값을 변경할 수 있어요. -`myCounter`의 값을 증가시키려고 할 때, 에러를 던져요: `myCounter`는 read-only이고 수정할 수 없어요. +`myCounter`의 값을 증가시키려고 할 때, 오류를 던져요: `myCounter`는 read-only이고 수정할 수 없어요.

@@ -1791,14 +1804,14 @@ console.log(delete age); - C: `true`, `true` - D: `undefined`, `undefined` -
정답 +

-#### 정답: A +#### 답: A -`delete`연산자는 불린 값을 리턴해요: 성공적으로 삭제를 한 경우 `true`를, 그렇지 않다면 `false`를 리턴해요. 그러나, `var`, `const` 또는 `let` 키워드로 선언된 변수들은 `delete`연산자를 사용해서 삭제될 수 없어요. +`delete`연산자는 불린 값을 반환해요: 성공적으로 삭제를 한 경우 `true`를, 그렇지 않다면 `false`를 반환해요. 그러나, `var`, `const` 또는 `let` 키워드로 선언된 변수은 `delete`연산자를 사용해서 삭제될 수 없어요. -`name` 변수는 `const`키워드로 선언되었기 때문에, 삭제에 실패해요. `age`를 `21`로 설정할 때, 실제로는 `age`라는 속성을 전역 객체에 추가한 거죠. 이 방법으로 객체, 전역 객체의 속성들을 성공적으로 삭제할 수 있어요. `delete age`는 `true`를 리턴해요. +`name` 변수는 `const`키워드로 선언되었기 때문에, 삭제에 실패해요: `false`가 반환돼요. `age`를 `21`로 설정할 때, 사실은 `age`라는 속성을 전역 객체에 추가한 거죠. 이 방법으로 객체, 전역 객체의 속성을 성공적으로 삭제할 수 있어요, 그래서 `delete age`는 `true`를 반환해요.

@@ -1819,12 +1832,12 @@ console.log(y); - C: `1` - D: `[1]` -
정답 +

-#### 정답: C +#### 답: C -구조 분해 할당을 통해 객체의 배열 또는 속성들로부터 변수를 해체할 수 있어요. 예를 들어: +구조 분해 할당을 통해 객체의 배열 또는 속성으로부터 변수를 해체할 수 있어요. 예를 들어: ```javascript [a, b] = [1, 2]; @@ -1832,7 +1845,7 @@ console.log(y); -`a`는 이제 `1`이고, `b`는 이제 `2`예요. 질문에서 실제로 한 건 다음과 같아요: +`a`의 값은 이제 `1`이고, `b`의 값은 이제 `2`예요. 사실 이 질문에서 한 건 다음과 같아요: ```javascript [y] = [1, 2, 3, 4, 5]; @@ -1840,7 +1853,7 @@ console.log(y); -이것은 `y`의 값은 숫자 `1`인 배열의 첫 번째 값과 같다는 것을 의미하죠. `y`를 출력하면 `1`이 리턴돼요. +이것은 `y`의 값은 숫자 `1`인 배열의 첫 번째 값과 같다는 것을 의미해요. `y`를 출력하면 `1`이 반환돼요.

@@ -1850,7 +1863,7 @@ console.log(y); ###### 60. 무엇이 출력 될까요? ```javascript -const user = { name: "Lydia", age: 21 }; +const user = { name: 'Lydia', age: 21 }; const admin = { admin: true, ...user }; console.log(admin); @@ -1861,12 +1874,12 @@ console.log(admin); - C: `{ admin: true, user: ["Lydia", 21] }` - D: `{ admin: true }` -
정답 +

-#### 정답: B +#### 답: B -스프레드 연산자 `...` 를 사용해 객체를 결합할 수 있어요. 이것은 하나의 객체의 키/값의 쌍들을 복사본들로 만들어, 다른 객체에 추가해요. 이 경우, `user` 객체의 복사본들을 만들어, `admin` 객체에 추가해요. `admin` 객체는 이제 복사된 키/값의 쌍들이 들어있고, 결과는 `{ admin: true, name: "Lydia", age: 21 }` 예요. +스프레드 연산자 `...` 를 사용해 객체를 결합할 수 있어요. 이것은 한 객체의 키/값 쌍을 복사본으로 만들어, 다른 객체에 추가해요. 이 경우, `user` 객체의 복사본을 만들어, `admin` 객체에 추가해요. `admin` 객체는 이제 복사된 키/값 쌍이 들어있고, 결과는 `{ admin: true, name: "Lydia", age: 21 }` 예요.

@@ -1876,9 +1889,9 @@ console.log(admin); ###### 61. 무엇이 출력 될까요? ```javascript -const person = { name: "Lydia" }; +const person = { name: 'Lydia' }; -Object.defineProperty(person, "age", { value: 21 }); +Object.defineProperty(person, 'age', { value: 21 }); console.log(person); console.log(Object.keys(person)); @@ -1889,14 +1902,14 @@ console.log(Object.keys(person)); - C: `{ name: "Lydia"}`, `["name", "age"]` - D: `{ name: "Lydia"}`, `["age"]` -
정답 +

-#### 정답: B +#### 답: B -`defineProperty`메소드로, 객체에 새로운 속성들을 추가하거나, 기존 것을 수정할 수 있어요. `defineProperty` 메소드를 사용해 객체의 속성을 추가할 때, 기본적으로 객체의 속성들은 _비 열거자_ 예요. `Object.keys`메소드는 모든 _열거자_ 객체의 속성 이름들을 리턴하는데, 이 경우는 `"name"` 뿐이에요. +`defineProperty`메소드를 사용해, 객체에 새로운 속성을 추가하거나 기존 속성을 수정할 수 있어요. `defineProperty` 메소드를 사용해 객체의 속성을 추가할 때, 객체의 속성은 기본적으로 _비 열거자_ 예요. `Object.keys`메소드는 모든 _열거자_ 객체의 속성 이름을 반환하는데, 이 경우는 `"name"` 뿐이에요. -`defineProperty`를 사용해 추가된 속성들은 기본적으로 변경할 수 없어요. `writable`, `configurable` 그리고 `enumerable` 속성들을 사용해 덮어쓰기 할 수 있어요. `defineProperty`메소드의 방법은 객체에 추가할 속성들을 훨씬 더 정교하게 제어하도록 해줘요. +`defineProperty`를 사용해 추가된 속성은 기본적으로 변경할 수 없어요. `writable`, `configurable` 그리고 `enumerable` 속성을 사용해 덮어쓸 수 있어요. `defineProperty`메소드를 사용하는 방법은 객체에 추가하는 속성을 훨씬 더 많이 제어할 수 있어요.

@@ -1907,12 +1920,12 @@ console.log(Object.keys(person)); ```javascript const settings = { - username: "lydiahallie", + username: 'lydiahallie', level: 19, - health: 90 + health: 90, }; -const data = JSON.stringify(settings, ["level", "health"]); +const data = JSON.stringify(settings, ['level', 'health']); console.log(data); ``` @@ -1921,16 +1934,16 @@ console.log(data); - C: `"["level", "health"]"` - D: `"{"username": "lydiahallie", "level":19, "health":90}"` -
정답 +

-#### 정답: A +#### 답: A -`JSON.stringify` 두 번째 인수는 _replacer_ 예요. replacer는 함수 또는 배열 둘 중 하나가 될 수 있고, stringify 할 대상과 방법을 제어할 수 있게 해줘요. +`JSON.stringify` 두 번째 인수는 _replacer_ 예요. replacer는 함수 또는 배열일 수 있고, 문자열로 변환 할 대상과 방법을 제어할 수 있게 해줘요. -replacer가 _배열_ 이라면, 배열에 이름이 포함된 속성만 JSON 문자열에 추가될 거에요. 이 경우, 이름을 가진 `"level"` 그리고 `"health"`속성들만 포함되고, `"username"`은 제외 돼요. `data` 은 이제 `"{"level":19, "health":90}"`에요. +replacer가 _배열_ 이라면, 배열에 포함된 속성의 이름만 JSON 문자열에 추가될 거에요. 이 경우, 이름을 가진 `"level"` 그리고 `"health"`속성만 포함되고, `"username"`은 제외 돼요. `data` 은 이제 `"{"level":19, "health":90}"`에요. -replacer가 _함수_ 라면, stringifying 할 객체의 모든 속성에 호출돼요. 이 함수로부터 리턴된 값은 JSON 문자열에 추가될 때 속성의 값이 될 거예요. 만약 값이 `undefined`라면, 이 속성은 JSON 문자열로부터 제외돼요. +replacer가 _함수_ 라면, 문자열로 변환 할 객체의 모든 속성에 호출돼요. 이 함수로부터 반환된 값은 JSON 문자열에 추가될 때 속성의 값이 될 거예요. 만약 값이 `undefined`라면, 이 속성은 JSON 문자열에서 제외돼요.

@@ -1957,14 +1970,14 @@ console.log(num2); - C: `11`, `11` - D: `11`, `12` -
정답 +

-#### 정답: A +#### 답: A -단항 연산자 `++`는 _우선_ 피연산자의 값을 _리턴하고_, _그 후_ 피연산자의 값을 _증가해요_. `increaseNumber` 함수가 처음으로 리턴 한 `num`의 값은 `10` 이기 때문에, `num1`의 값은 `10`이고, 그 후엔 `num`의 값만 증가해요. +단항 연산자 `++`는 _우선_ 피연산자의 값을 _반환하고_, _그 후_ 피연산자의 값을 _증가시켜요_. `increaseNumber` 함수가 처음으로 반환 한 `num`의 값은 `10` 이기 때문에, `num1`의 값은 `10`이고, 그 후엔 `num`의 값만 증가해요. -`num1`을 `increasePassedNumber`로 전달했기 때문에, `num2`는 `10`이에요. `number`는 `10`이에요(`num1`의 값은, 다시 한번, 단항 연산자가 `++`는 _우선_ 피연산자의 값을 _리턴하고_, _그 후_ 피연산자의 값을 _증가해요_. `number`의 값은 `10`이에요 즉, `num2`는 `10`이죠. +`num1`을 `increasePassedNumber`로 전달했기 때문에, `num2`는 `10`이에요. `number`는 `10`이에요(`num1`의 값. 다시, 단항 연산자가 `++`는 _우선_ 피연산자의 값을 _반환하고_, _그 후_ 피연산자의 값을 _증가해요_. `number`의 값은 `10`이에요 즉, `num2`는 `10`이죠.

@@ -1977,7 +1990,7 @@ console.log(num2); const value = { number: 10 }; const multiply = (x = { ...value }) => { - console.log(x.number *= 2); + console.log((x.number *= 2)); }; multiply(); @@ -1991,18 +2004,18 @@ multiply(value); - C: `20`, `20`, `20`, `40` - D: `NaN`, `NaN`, `20`, `40` -
정답 +

-#### 정답: C +#### 답: C -ES6에서는, 기본값으로 파라미터를 초기화할 수 있어요. 함수에 값이 없이 전달되거나, 파라미터의 값이 `"undefined"`라면, 파라미터의 값은 기본값이 될 거예요. 이 경우, `value` 객체의 속성들을 새로운 객체 안으로 전개해요. 따라서 `x`는 `{ number: 10 }`을 기본값으로 가져요. +ES6에서, 기본값으로 파라미터를 초기화할 수 있어요. 함수에 값이 없이 전달되거나, 파라미터의 값이 `"undefined"`라면, 파라미터의 값은 기본값이 될 거예요. 이 경우, `value` 객체의 속성을 새로운 객체 안에 전개했어요. 따라서 `x`는 `{ number: 10 }`을 기본값으로 가져요. -기본 인수는 _호출 시점_ 에 평가돼요! 함수를 부를 때마다, _새로운_ 객체를 만들어요. 처음에 두 번은 값 전달 없이 `multiply` 함수를 호출해요: `x`는 `{ number: 10 }`의 기본값을 가져요. 그다음 그 숫자를 곱셈한 값인 `20`을 출력해요. +기본 인수는 _호출 시점_ 에 평가돼요! 함수를 부를 때마다, _새로운_ 객체를 만들어요. 처음 두 번은 값을 전달하지 않고, `multiply` 함수를 호출해요: `x`는 `{ number: 10 }`의 기본값을 가져요. 그다음 해당 숫자를 곱한 값인 `20`을 출력해요. -세 번째로 곱셈을 호출할 때, 인수를 전달해요: 그 객체는 `value`를 불러요. `*=` 연산자는 실제로는 `x.number = x.number * 2`의 줄임말이에요: `x.number`의 값을 변경하고, 곱셈한 값 `20`을 출력해요 +세 번째로 곱셈을 호출할 때, 인수를 전달해요: 그 객체는 `value`라고 불려요. `*=` 연산자는 사실 `x.number = x.number * 2`의 줄임말이에요: `x.number`의 값을 변경하고, 곱셈한 값 `20`을 출력해요 -네 번째에는, `value` 객체를 다시 한번 전달해요. `x.number`는 이전에 `20`으로 바뀌었기 때문에, `x.number *= 2`는 `40`을 출력해요. +네 번째엔, `value` 객체를 다시 한번 전달해요. `x.number`는 이전에 `20`으로 바뀌었기 때문에, `x.number *= 2`는 `40`을 출력해요.

@@ -2020,22 +2033,22 @@ ES6에서는, 기본값으로 파라미터를 초기화할 수 있어요. 함수 - C: `1` `undefined` 그리고 `2` `undefined` 그리고 `3` `undefined` 그리고 `4` `undefined` - D: `1` `2` 그리고 `undefined` `3` 그리고 `undefined` `4` -
정답 +

-#### 정답: D +#### 답: D -`reduce` 메소드가 받은 첫 번째 인수는 _누산기_ 예요, 이 경우엔 `x`죠. 두 번째 인수 `y`는 _현재 값_ 예요. reduce 메소드에서, 배열에 있는 모든 요소에 콜백 함수를 실행하므로 궁극적으로는 하나의 값을 얻을 수 있어요. +`reduce` 메소드가 받은 첫 번째 인수는 _누산기_ 예요, 이 경우엔 `x`죠. 두 번째 인수 `y`는 _현재 값_ 이에요. reduce 메소드에서, 배열에 있는 모든 요소에 콜백 함수를 실행하므로 궁극적으로는 하나의 값을 얻어요. -이 예제에서는, 값을 리턴하지 않고, 단지 누적된 값과 현재 값을 출력해요. +이 예제에서는, 값을 반환하지 않고, 단지 누적된 값과 현재 값을 출력해요. -누산기의 값은 콜백 함수가 이전에 리턴한 값이에요. 만약 추가적인 `초기값` 인수를 `reduce` 메소드에 전달하지 않았다면, 누산기는 첫번째 부른 첫 번째 요소와 동일해요. +누산기의 값은 콜백 함수가 이전에 반환한 값이에요. 만약 추가적인 `초기값` 인수를 `reduce` 메소드에 전달하지 않았다면, 누산기는 첫번째 부른 첫 번째 요소와 동일해요. -첫 번째 부를 땐, 누산기 (`x`)는 `1` 이에요, 그리고 현재 값인 (`y`)는 `2`예요. 콜백 함수로부터 리턴되지 않았어요, 누산기와 현재 값을 출력해요: `1` 그리고 `2`가 출력돼요. +첫 번째로 부를 땐, 누산기 (`x`)는 `1` 이에요, 그리고 현재 값인 (`y`)는 `2`예요. 콜백 함수로부터 반환되지 않았고, 누산기와 현재 값을 출력해요: `1` 그리고 `2`가 출력돼요. -함수에서 값을 리턴하지 않았다면, `undefined`를 리턴해요. 다음번에 부를 때, 누산기는 `undefined`고, 그리고 현재 값은 `3`이에요. `undefined` 그리고 `3`이 출력돼요. +함수에서 값을 반환하지 않았다면, `undefined`를 반환해요. 다음번에 부를 때, 누산기는 `undefined`고, 그리고 현재 값은 `3`이에요. `undefined` 그리고 `3`이 출력돼요. -네 번째 부를 땐, 또 콜백 함수에서 리턴받지 않았어요. 누산기는 다시 `undefined`고, 현재 값은 `4`예요. `undefined` 그리고 `4`가 출력돼요. +네 번째 부를 땐, 또 콜백 함수에서 반환받지 않았어요. 누산기는 다시 `undefined`고, 현재 값은 `4`예요. `undefined` 그리고 `4`가 출력돼요.

@@ -2052,7 +2065,7 @@ class Dog { }; class Labrador extends Dog { - // 1 + // 1 constructor(name, size) { this.size = size; } @@ -2066,7 +2079,7 @@ class Labrador extends Dog { super(name); this.size = size; } - // 4 + // 4 constructor(name, size) { this.name = name; this.size = size; @@ -2080,16 +2093,16 @@ class Labrador extends Dog { - C: 3 - D: 4 -
정답 +

-#### 정답: B +#### 답: B -이 파생 클래스에서, `super`를 부르기 전에는 `this` 키워드에 접근할 수 없어요. 그렇게 하려고 한다면, 참조에러를 던질 거에요: 1과 4는 참조 에러를 던져요 +파생 클래스에서, `super`를 부르기 전에는 `this` 키워드에 접근할 수 없어요. 그렇게 하려고 한다면, ReferenceError를 던질 거에요: 1과 4는 reference error를 던져요 -`super` 키워드를 가지고, 부모 클래스 생성자에 주어진 인수들을 부를 수 있어요. 부모 생성자는 `name` 인수를 받아요, 그래서 `name`을 `super`로 전달해야 해요. +`super` 키워드를 가지고, 부모 클래스 생성자에 주어진 인수를 부를 수 있어요. 부모 생성자는 `name` 인수를 받아요, 그래서 `name`을 `super`로 전달해야 해요. -`Labrador` 클래스는 인수를 2개 받는데, `Dog`로 부터 확장된 `name`과 `Labrador` 클래스의 추가 속성인 `size`예요. 그 두 개는 `Labrador` 생성자 함수에 전달되어야 하는데, 올바르게 사용된 건 2번째 생성자예요. +`Labrador` 클래스는 2개의 인수를 받는데, `Dog`로 부터 확장된 `name`과 `Labrador` 클래스의 추가 속성인 `size`예요. 그 두 개는 `Labrador` 생성자 함수에 전달되어야 하는데, 올바르게 사용된 건 2번째 생성자예요.

@@ -2114,10 +2127,10 @@ export const sum = (a, b) => a + b; - C: `running sum.js`, `3`, `running index.js` - D: `running index.js`, `undefined`, `running sum.js` -
정답 +

-#### 정답: B +#### 답: B `import` 키워드를 사용하면, 모든 import된 modules은 _우선-파싱_ 되어요. import된 모듈은 _처음에_ 실행되는 것을 의미하고, import한 파일 안에 있는 코드는 _나중에_ 실행돼요. @@ -2131,9 +2144,9 @@ export const sum = (a, b) => a + b; ###### 68. 무엇이 출력 될까요? ```javascript -console.log(Number(2) === Number(2)) -console.log(Boolean(false) === Boolean(false)) -console.log(Symbol('foo') === Symbol('foo')) +console.log(Number(2) === Number(2)); +console.log(Boolean(false) === Boolean(false)); +console.log(Symbol('foo') === Symbol('foo')); ``` - A: `true`, `true`, `false` @@ -2141,12 +2154,12 @@ console.log(Symbol('foo') === Symbol('foo')) - C: `true`, `false`, `true` - D: `true`, `true`, `true` -

정답 +

-#### 정답: A +#### 답: A -모든 심볼은 완전히 유니크해요. 심볼에 전달된 인수의 목적은, 심볼에 설명을 제공하는 거에요. 심볼의 값은 전달된 인수에 따라 달라지지 않아요. 동등성을 테스트할 때, 새로운 심볼 객체를 만들어요: 첫번째 `Symbol('foo')`와 두번째 `Symbol('foo')`. 이 두개의 값들은 유니크하며, 서로 같지 않아요, `Symbol('foo') === Symbol('foo')`는 `false`를 리턴해요. +모든 심볼은 완전히 유니크해요. 심볼에 전달된 인수의 목적은 심볼에 설명을 제공하는 거에요. 심볼의 값은 전달된 인수에 따라 달라지지 않아요. 동등성을 테스트할 때, 완전히 새로운 두 개의 심볼을 만들어요: 첫번째 `Symbol('foo')`와 두번째 `Symbol('foo')`. 이 두개의 값은 유니크하고, 서로 같지 않아요, `Symbol('foo') === Symbol('foo')`는 `false`를 반환해요.

@@ -2156,22 +2169,22 @@ console.log(Symbol('foo') === Symbol('foo')) ###### 69. 무엇이 출력 될까요? ```javascript -const name = "Lydia Hallie" -console.log(name.padStart(13)) -console.log(name.padStart(2)) +const name = 'Lydia Hallie'; +console.log(name.padStart(13)); +console.log(name.padStart(2)); ``` - A: `"Lydia Hallie"`, `"Lydia Hallie"` -- B: `" Lydia Hallie"`, `" Lydia Hallie"` (`"[13x whitespace]Lydia Hallie"`, `"[2x whitespace]Lydia Hallie"`) +- B: `" Lydia Hallie"`, `" Lydia Hallie"` (`"[13x whitespace]Lydia Hallie"`, `"[2x whitespace]Lydia Hallie"`) - C: `" Lydia Hallie"`, `"Lydia Hallie"` (`"[1x whitespace]Lydia Hallie"`, `"Lydia Hallie"`) -- D: `"Lydia Hallie"`, `"Lyd"`, +- D: `"Lydia Hallie"`, `"Lyd"`, -
정답 +

-#### 정답: C +#### 답: C -`padStart` 메소드를 사용하면, 문자열의 시작 부분에 패딩을 추가해 줄 수 있어요. 이 메소드에 전달된 값은 패딩을 포함한 문자열의 _전체_ 길이예요. 문자열 `"Lydia Hallie"`의 길이는 `12`예요. `name.padStart(13)`은 문자열의 시작점에 1 스페이스를 삽입해요, 따라서 12 + 1 은 13이죠. +`padStart` 메소드를 사용해, 문자열의 시작 부분에 패딩을 추가해 줄 수 있어요. 이 메소드에 전달된 값은 패딩을 포함한 문자열의 _전체_ 길이예요. 문자열 `"Lydia Hallie"`의 길이는 `12`예요. `name.padStart(13)`은 문자열의 시작점에 1 스페이스를 삽입해요, 따라서 12 + 1 은 13이죠. `padStart` 메소드에 전달된 인수가 배열의 길이보다 작다면, 패딩은 추가되지 않을 거예요. @@ -2183,20 +2196,20 @@ console.log(name.padStart(2)) ###### 70. 무엇이 출력 될까요? ```javascript -console.log("🥑" + "💻"); +console.log('🥑' + '💻'); ``` - A: `"🥑💻"` - B: `257548` - C: 해당 코드 주소를 포함하는 문자열 -- D: 에러 +- D: 오류 -

정답 +

-#### 정답: A +#### 답: A -`+` 연산자를 가지고, 문자열을 연결 시킬 수 있어요. 이 경우에는, 문자열 `"🥑"`과 문자열 `"💻"`을 연결해, 결과 `"🥑💻"`를 얻었어요. +`+` 연산자를 사용해, 문자열을 연결 시킬 수 있어요. 이 경우에는, 문자열 `"🥑"`과 문자열 `"💻"`을 연결해, 결과 `"🥑💻"`를 얻었어요.

@@ -2207,11 +2220,11 @@ console.log("🥑" + "💻"); ```javascript function* startGame() { - const answer = yield "Do you love JavaScript?"; - if (answer !== "Yes") { + const answer = yield 'Do you love JavaScript?'; + if (answer !== 'Yes') { return "Oh wow... Guess we're gone here"; } - return "JavaScript loves you back ❤️"; + return 'JavaScript loves you back ❤️'; } const game = startGame(); @@ -2224,16 +2237,16 @@ console.log(/* 2 */); // JavaScript loves you back ❤️ - C: `game.next().value` 그리고 `game.next("Yes").value` - D: `game.next.value()` 그리고 `game.next.value("Yes")` -
정답 +

-#### 정답: C +#### 답: C 제너레이터 함수는 `yield` 키워드를 보면 실행을 "멈춰"요. 첫 번째로, `game.next().value`를 불러, 함수가 "Do you love JavaScript?" 문자열을 넘겨주도록 할 수 있어요. -`yield` 키워드를 처음으로 찾기 전까지, 모든 줄이 실행되요. 첫 번째 줄에 있는 함수는 `yield` 키워드를 가지고 있어요: 첫 번째 yield으로 실행을 멈춰요! _이것은 `answer` 변수가 아직 정의되지 않았는 뜻이에요_ +`yield` 키워드를 처음으로 찾기 전까지, 모든 줄이 실행되요. 함수 안 첫 번째 줄에 `yield` 키워드가 있어요: 첫 번째 yield으로 실행을 멈춰요! _이것은 `answer` 변수가 아직 정의되지 않았는 뜻이에요!_ -`game.next("Yes").value`을 부를때, `"Yes"`의 경우에서 이전 `yield`는 `next()` 함수가 전달한 파라미터의 값으로 대체돼요. `answer` 변수의 값은 이제 `"Yes"`에요. if문의 조건은 `false`를 리턴해, `JavaScript loves you back ❤️`를 출력돼요 +`game.next("Yes").value`을 부를 때, 이전 `yield`는 `next()` 함수가 전달한 파라미터의 값으로 대체 되는데, 이 경우에는 `"Yes"`로 대체 돼요. `answer` 변수의 값은 이제 `"Yes"`예요. if문의 조건은 `false`를 반환해, `JavaScript loves you back ❤️`이 출력돼요.

@@ -2251,24 +2264,24 @@ console.log(String.raw`Hello\nworld`); - C: `Hello\nworld` - D: `Hello\n`
     `world` -
정답 +

-#### 정답: C +#### 답: C -`String.raw`는 escapes (`\n`, `\v`, `\t` 등.)에서의 문자열을 무시해요! 백슬래시는 다음과 같이 끝나면 문제가 될 수 있어요 +`String.raw`는 escapes(`\n`, `\v`, `\t` 등.)가 무시되는 문자열을 반환해요! 백슬래시는 다음과 같이 끝나면 문제가 될 수 있어요: -``console.log(`C:\Documents\Projects\table.html`)`` +`` const path = `C:\Documents\Projects\table.html` `` 이렇게 될 거예요: -`C:DocumentsProjects able.html` +`"C:DocumentsProjects able.html"` `String.raw`을 사용하면, 간단하게 escape를 무시하고 출력해요: `C:\Documents\Projects\table.html` -이 경우, 문자열은 `Hello\nworld`이 출력되요. +이 경우, 문자열 `Hello\nworld`이 출력되요.

@@ -2279,7 +2292,7 @@ console.log(String.raw`Hello\nworld`); ```javascript async function getData() { - return await Promise.resolve("I made it!"); + return await Promise.resolve('I made it!'); } const data = getData(); @@ -2291,12 +2304,12 @@ console.log(data); - C: `Promise {}` - D: `undefined` -
정답 +

-#### 정답: C +#### 답: C -async 함수는 항상 promise를 리턴해요. `await`는 promise가 resolve 할 때까지 기다려야 해요: pending promise는 `data`를 설정하기 위해 부른 `getData()`가 리턴한 것을 가져요. +async 함수는 항상 promise를 반환해요. `await`는 promise가 resolve 할 때까지 기다려야 해요: pending promise는 `data`를 설정하기 위해 부른 `getData()`가 반환한 것을 가져요. resolve된 값 `"I made it"`에 접근하고 싶다면, `data`에 `.then()` 메소드를 사용해야해요. @@ -2316,7 +2329,7 @@ function addToList(item, list) { return list.push(item); } -const result = addToList("apple", ["banana"]); +const result = addToList('apple', ['banana']); console.log(result); ``` @@ -2325,14 +2338,14 @@ console.log(result); - C: `true` - D: `undefined` -

정답 +

-#### 정답: B +#### 답: B -`.push()`메소드는 새로운 배열의 _길이_ 를 리턴해요! 이전에, 배열은 한 개의 요소(문자열 `"banana"`)를 포함되어있고 길이는 `1`예요. 배열에 문자열 `"apple"`을 추가한 후, 배열은 두 개 요소를 포함하고, 그리고 길이 `2`를 가져요. `addToList` 함수로부터 리턴돼요. +`.push()`메소드는 새로운 배열의 _길이_ 를 반환해요! 이전에, 배열은 한 개의 요소(문자열 `"banana"`)를 포함하고 길이는 `1`예요. 배열에 문자열 `"apple"`을 추가한 후, 배열은 두 개 요소를 포함하고, 길이 `2`를 가져요. `addToList` 함수로부터 반환 받은거예요. -`push` 메소드는 원본 배열을 수정해요. 만약 함수로부터 _배열의 길이_ 대신에 _배열_ 을 리턴하고 싶다면, `item`을 푸시한 후 `list`를 리턴해야해요. +`push` 메소드는 원본 배열을 수정해요. 만약 함수로부터 _배열의 길이_ 대신에 _배열_ 을 반환하고 싶다면, `item`을 푸시한 후 `list`를 반환해야해요.

@@ -2357,14 +2370,14 @@ console.log(shape); - C: `{ x: 100 }` - D: `ReferenceError` -
정답 +

-#### 정답: B +#### 답: B -`Object.freeze`는 객체의 속성들을 추가, 삭제 혹은 수정하는 걸 불가능하게 만들어요(다른 객체로서의 속성들의 값이 아닌 한). +`Object.freeze`는 객체의 속성을 추가, 삭제 혹은 수정하지 못하게 만들어요(다른 객체 속성의 값이 아닌 한). -변수 `shape`을 생성할 때, 동결 객체 `box`와 동일하게 설정했고, `shape` 역시 동결 객체를 참조해요. `Object.isFrozen`을 사용해 객체의 동결 여부를 확인할 수 있어요. 이 경우, `Object.isFrozen(shape)`은 참을 리턴하고, 따라서 변수 `shape`는 동결 객체 참조를 가져요. +변수 `shape`을 생성할 때, 동결 객체 `box`와 동일하게 설정했고, `shape` 역시 동결 객체를 참조해요. `Object.isFrozen`을 사용해 객체의 동결 여부를 확인할 수 있어요. 이 경우, `Object.isFrozen(shape)`은 true를 반환하고, 따라서 변수 `shape`는 동결 객체 참조를 가져요. `shape`가 동결 상태이므로, `x`의 값은 객체가 아니며, `x`의 속성을 수정할 수 없어요. `x`는 여전히 `10`이고, `{ x: 10, y: 20 }`가 출력돼요. @@ -2376,7 +2389,7 @@ console.log(shape); ###### 76. 무엇이 출력 될까요? ```javascript -const { name: myName } = { name: "Lydia" }; +const { name: myName } = { name: 'Lydia' }; console.log(name); ``` @@ -2386,23 +2399,23 @@ console.log(name); - C: `undefined` - D: `ReferenceError` -

정답 +

-#### 정답: D +#### 답: D -오른쪽에 있는 객체로부터 속성 `name`을 unpack할 때, `myName`라는 이름을 가진 변수에 값 `"Lydia"`을 할당해요. +오른쪽에 있는 객체로부터 속성 `name`을 분해할 때, `myName`라는 이름을 가진 변수에 값 `"Lydia"`을 할당해요. -`{ name: myName }`은, JavaScript에게 오른쪽에 있는 `name`속성 값을 가진 `myName`이라고 불리는 새로운 변수를 만든다고 말하는 거예요. +`{ name: myName }`은, JavaScript에게 오른쪽에 있는 `name`속성의 값을 가진 `myName`이라고 불리는 새로운 변수를 만든다고 말하는 거예요. -`name`을 출력하려고 하면, 변수는 정의되지 않아, ReferenceError를 던질거예요. +`name`을 출력하려고 하면, 변수는 정의되지 않아 ReferenceError를 던질거예요.

--- -###### 77. 이것은 pure 함수 일까요? +###### 77. 이것은 순수 함수 일까요? ```javascript function sum(a, b) { @@ -2413,14 +2426,14 @@ function sum(a, b) { - A: Yes - B: No -
정답 +

-#### 정답: A +#### 답: A -pure 함수는 _항상_ 같은 결과를 리턴하는 함수예요, 만약 같은 인수가 전달 된다면 말이죠. +순수 함수는 _항상_ 같은 결과를 반환하는 함수예요, 만약 같은 인수가 전달 된다면 말이죠. -`sum` 함수는 항상 같은 결과를 리턴해요. 만약 `1`과 `2`를 전달하면, _항상_ 부작용 없이 `3`을 리턴할 거예요. `5`와 `10`을 전달하면, _항상_ `15`를 리턴할 거예요. 이게 pure 함수의 정의예요. +`sum` 함수는 항상 같은 결과를 반환해요. 만약 `1`과 `2`를 전달하면, 부작용 없이 _항상_ `3`을 반환할 거예요. `5`와 `10`을 전달하면, _항상_ `15`를 반환할 거예요. 이게 순수 함수의 정의예요.

@@ -2432,7 +2445,7 @@ pure 함수는 _항상_ 같은 결과를 리턴하는 함수예요, 만약 같 ```javascript const add = () => { const cache = {}; - return num => { + return (num) => { if (num in cache) { return `From cache! ${cache[num]}`; } else { @@ -2454,20 +2467,20 @@ console.log(addFunction(5 * 2)); - C: `Calculated! 20` `From cache! 20` `From cache! 20` - D: `Calculated! 20` `From cache! 20` `Error` -
정답 +

-#### 정답: C +#### 답: C -`add`함수는 _memoization_ 함수예요. memoization으로, 함수 실행 속도를 높이기 위해 함수의 결과를 캐시에 저장할 수 있어요. 이 경우, 이전에 리턴된 값을 저장한 `cache` 객체를 만들어요. +`add`함수는 _memoized_ 함수예요. memoization 사용하면, 함수 실행 속도를 높이기 위해 함수의 결과를 캐시할 수 있어요. 이 경우, 이전에 반환된 값을 저장한 `cache` 객체를 만들어요. -같은 인수로 `addFunction` 함수를 다시 부르면, 우선 cache 안에 값을 갖고 있는지 확인해요. 만약 그렇다면, 캐시에 저장된 값이 리턴되어, 실행시간이 절약돼요. 캐시에 저장되지 않았다면, 값을 계산하고 나중에 저장해요. +같은 인수로 `addFunction` 함수를 다시 부르면, 우선 cache 안에 값을 갖고 있는지 확인해요. 만약 그렇다면, 캐시값이 반환되어 실행시간이 절약돼요. 캐시되지 않았다면, 값을 계산하고 나중에 저장해요. -같은 값으로 `addFunction`함수를 세 번 불러요: 첫 번째 호출 때에는, `num`가 `10`일 때 함수의 값은 아직 저장되지 않았어요. if문의 조건 `num in cache` 은 `false`을 리턴하고, else 블록이 실행돼요: `Calculated! 20`을 출력하고, 결과 값은 cache 객체에 추가돼요. `cache` 이제 `{ 10: 20 }`와 같아요. +같은 값으로 `addFunction`함수를 세 번 불러요: 첫 번째 호출 때에는, `num`가 `10`일 때 함수의 값은 아직 저장되지 않았어요. if문의 조건 `num in cache` 은 `false`을 반환하고, else 블록이 실행돼요: `Calculated! 20`을 출력하고, 결과 값은 cache 객체에 추가돼요. `cache`는 이제 `{ 10: 20 }` 처럼 보여요. -두 번째엔, `cache`객체는 `10`을 위해 리턴될 값을 포함하고 있어요. if문의 조건 `num in cache`은 `true`를 리턴하고, `'From cache! 20'`이 출력돼요. +두 번째엔, `cache`객체는 `10`을 위해 반환될 값을 포함하고 있어요. if문의 조건 `num in cache`은 `true`를 반환하고, `'From cache! 20'`이 출력돼요. -세 번째에는, `5 * 2`을 `10`으로 평가하여 함수에 전달해요. `cache` 객체는 `10`을 위해 리턴될 값을 포함하고 있어요. if문의 조건 `num in cache`은 `true`를 리턴하고, `'From cache! 20'`이 출력돼요. +세 번째에는, `5 * 2`을 `10`으로 평가해 함수에 전달해요. `cache` 객체는 `10`을 위해 반환될 값을 포함하고 있어요. if문의 조건 `num in cache`은 `true`를 반환하고, `'From cache! 20'`이 출력돼요.

@@ -2477,7 +2490,7 @@ console.log(addFunction(5 * 2)); ###### 79. 무엇이 출력 될까요? ```javascript -const myLifeSummedUp = ["☕", "💻", "🍷", "🍫"] +const myLifeSummedUp = ['☕', '💻', '🍷', '🍫']; for (let item in myLifeSummedUp) { console.log(item); @@ -2491,20 +2504,20 @@ for (let item of myLifeSummedUp) { - A: `0` `1` `2` `3` 그리고 `"☕"` ` "💻"` `"🍷"` `"🍫"` - B: `"☕"` ` "💻"` `"🍷"` `"🍫"` 그리고 `"☕"` ` "💻"` `"🍷"` `"🍫"` - C: `"☕"` ` "💻"` `"🍷"` `"🍫"` 그리고 `0` `1` `2` `3` -- D: `0` `1` `2` `3` 그리고 `{0: "☕", 1: "💻", 2: "🍷", 3: "🍫"}` +- D: `0` `1` `2` `3` 그리고 `{0: "☕", 1: "💻", 2: "🍷", 3: "🍫"}` -
정답 +

-#### 정답: A +#### 답: A -_for-in_ 루프에서는, **열거 가능한** 속성들에 대해 반복 할 수 있어요. 배열에서, 열거 가능한 속성들은 배열 요소들의 "키"이고, 실제로는 그들의 인덱스죠. 배열을 다음과 같이 볼 수 있어요: +_for-in_ 루프에서는, **열거 가능한** 속성에 대해 반복 할 수 있어요. 배열에서, 열거 가능한 속성은 배열 요소의 "키"이고, 사실 그들의 인덱스예요. 배열은 다음과 같이 볼 수 있어요: `{0: "☕", 1: "💻", 2: "🍷", 3: "🍫"}` -여기서 키는 열거 가능한 속성이에요. `0` `1` `2` `3`이 출력되죠. +여기서 키는 열거 가능한 속성이에요. `0` `1` `2` `3`이 출력되요. -_for-of_ 루프에서는, **반복 가능한** 속성을 가진 요소에 대해 반복 할 수 있어요. 배열은 반복 가능해요. 배열을 반복할 때, "item" 변수는 현재 반복중인 요소로, `"☕"` ` "💻"` `"🍷"` `"🍫"`이 출력돼요. +_for-of_ 루프에서는, **반복 가능한** 속성을 가진 요소에 대해 반복 할 수 있어요. 배열은 반복 가능해요. 배열을 반복할 때, "item" 변수는 현재 반복중인 요소와 같고, `"☕"` ` "💻"` `"🍷"` `"🍫"`이 출력돼요.

@@ -2514,23 +2527,23 @@ _for-of_ 루프에서는, **반복 가능한** 속성을 가진 요소에 대해 ###### 80. 무엇이 출력 될까요? ```javascript -const list = [1 + 2, 1 * 2, 1 / 2] +const list = [1 + 2, 1 * 2, 1 / 2]; console.log(list); ``` - A: `["1 + 2", "1 * 2", "1 / 2"]` - B: `["12", 2, 0.5]` - C: `[3, 2, 0.5]` -- D: `[1, 1, 1]` +- D: `[1, 1, 1]` -
정답 +

-#### 정답: C +#### 답: C -배열 요소들은 모든 값을 포함 할 수 있어요. Numbers, strings, objects, 다른 arrays, null, boolean 값, undefined, 그리고 자료형, 함수, 연산자와 같은 표현식들 +배열 요소은 모든 값을 가질 수 있어요. 숫자, 문자, 객체, 다른 배열, null, 불리언 값, undefined, 그리고 날짜, 함수, 연산자와 같은 표현식 -요소는 리턴된 값과 같아질 거예요. `1 + 2`는 `3`을 리턴하고, `1 * 2`는 `2`를 리턴하고, `1 / 2` 는 `0.5`을 리턴해요. +요소는 반환된 값과 같아질 거예요. `1 + 2`는 `3`을 반환하고, `1 * 2`는 `2`를 반환하고, `1 / 2` 는 `0.5`을 반환해요.

@@ -2541,25 +2554,25 @@ console.log(list); ```javascript function sayHi(name) { - return `Hi there, ${name}` + return `Hi there, ${name}`; } console.log(sayHi()); ``` -- A: `Hi there, ` +- A: `Hi there,` - B: `Hi there, undefined` - C: `Hi there, null` -- D: `ReferenceError` +- D: `ReferenceError` -
정답 +

-#### 정답: B +#### 답: B -기본값으로, 함수에 값이 전달되지 않으면, 인수는 `undefined` 값을 가져요. 이 경우, `name` 인수를 위한 값을 전달하지 않았어요. `name`은 `undefined`로 출력돼요. +기본적으로, 인수는 함수에 값이 전달되지 않으면 `undefined` 값을 가져요. 이 경우, `name` 인수를 위한 값을 전달하지 않았어요. `name`은 `undefined`로 출력돼요. -ES6에서, 기본값 `undefined` 값을 기본값 파라미터로 덮어쓸 수 있어요. 예를 들면: +ES6에서, 기본값 `undefined` 값을 기본값 매개변수로 덮어쓸 수 있어요. 예를 들면: `function sayHi(name = "Lydia") { ... }` @@ -2573,16 +2586,16 @@ ES6에서, 기본값 `undefined` 값을 기본값 파라미터로 덮어쓸 수 ###### 82. 무엇이 출력 될까요? ```javascript -var status = "😎"; +var status = '😎'; setTimeout(() => { - const status = "😍"; + const status = '😍'; const data = { - status: "🥑", + status: '🥑', getStatus() { return this.status; - } + }, }; console.log(data.getStatus()); @@ -2595,14 +2608,14 @@ setTimeout(() => { - C: `"😍"` 그리고 `"😎"` - D: `"😎"` 그리고 `"😎"` -

정답 +

-#### 정답: B +#### 답: B -`this`키워드의 값은 사용하는 곳에 따라 달라요. **메소드**에서 `getStatus`메소드 처럼, `this`키워드는 _메소드가 속한 객체_ 를 참조해요. 이 메소드는 `data` 객체에 속해 있어, `this`는 `data`객체를 참조해요. `this.status`를 출력할 때, `data`객체의 `status` 속성 `"🥑"`이 출력돼요. +`this`키워드의 값은 사용하는 곳에 따라 달라요. `getStatus`메소드 같은 **메소드**에서 `this`키워드는 _메소드가 속한 객체_ 를 참조해요. 이 메소드는 `data` 객체에 속해 있어, `this`는 `data`객체를 참조해요. `this.status`를 출력할 때, `data`객체의 `status` 속성 `"🥑"`이 출력돼요. -`call` 메소드에서는, `this` 키워드가 참조하는 객체를 바꿀 수 있어요. **함수**에서, `this` 키워드는 _함수가 속한 객체_ 를 참조해요. `setTimeout` 함수를 _전역 객체_ 에 선언했고, `setTimeout` 함수 안에서, `this`키워드는 _전역 객체_ 를 참조해요. 전역 객체에서, 변수는 `"😎"`값을 가진 _status_ 를 부르죠. `this.status`를 출력하면, `"😎"`이 출력돼요. +`call` 메소드를 사용해, `this` 키워드가 참조하는 객체를 바꿀 수 있어요. **함수**에서, `this` 키워드는 _함수가 속한 객체_ 를 참조해요. `setTimeout` 함수를 _전역 객체_ 에 선언했어요, 따라서 `setTimeout` 함수 안에서 `this`키워드는 _전역 객체_ 를 참조해요. 전역 객체에는 `"😎"`값을 가진 _status_ 라는 변수가 있어요. `this.status`를 출력하면, `"😎"`이 출력돼요.

@@ -2613,12 +2626,12 @@ setTimeout(() => { ```javascript const person = { - name: "Lydia", - age: 21 + name: 'Lydia', + age: 21, }; let city = person.city; -city = "Amsterdam"; +city = 'Amsterdam'; console.log(person); ``` @@ -2628,18 +2641,18 @@ console.log(person); - C: `{ name: "Lydia", age: 21, city: undefined }` - D: `"Amsterdam"` -
정답 +

-#### 정답: A +#### 답: A -`city` 변수를 `person` 객체의 `city`라고 불리는 속성 값으로 설정 했어요. 이 객체에서는 `city`라고 불리는 속성이 없기 때문에, `city`는 `undefined`의 값을 가져요. +`city` 변수를 `person` 객체의 `city`라고 불리는 속성 값으로 설정 했어요. 이 객체에서는 `city`라고 불리는 속성이 없기 때문에, 변수 `city`는 값 `undefined`를 가져요. -`person`객체 자체를 참조 _하지않는_ 다는 걸 참고해요! 변수 `city`는 `person` 객체의 `city` 현재 속성 값으로 설정 했을 뿐이죠. +`person`객체 자체를 참조 _하지않는다_ 는 걸 참고해요! 변수 `city`는 `person` 객체의 `city` 속성의 현재 값으로 설정 했을 뿐이에요. -그러므로, 우리는 `city`를 문자열 `"Amsterdam"`로 설정 했어요. 이건 person 객체를 바꾸지 않아요: 여기서 객체를 참조하는 건 없어요. +그 뒤, 우리는 `city`를 문자열 `"Amsterdam"`로 설정 했어요. 이건 person 객체를 바꾸지 않아요: 여기서 객체를 참조하는 건 없어요. -`person`객체를 출력할 때, 수정되지 않은 객체가 리턴 받아요. +`person`객체를 출력할 때, 수정되지 않은 객체를 반환 받아요.

@@ -2667,12 +2680,12 @@ console.log(checkAge(21)); - C: `ReferenceError` - D: `undefined` -
정답 +

-#### 정답: C +#### 답: C -`const`와 `let` 키워드를 사용한 변수는 _블록-스코프_ 예요. 블록은 중괄호 (`{ }`) 사이에 있는 것이죠. 이 경우, if/else 표현식의 중괄호를 의미해요. 블록 안에 선언된 건 블록 밖의 변수들을 참조하지 못해, ReferenceError를 던져요. +`const`와 `let` 키워드를 사용한 변수는 _블록-스코프_ 예요. 블록은 중괄호 (`{ }`) 사이에 있는 모든 것이에요. 이 경우, if/else 표현식의 중괄호를 의미해요. 변수가 선언된 블록 외부에서 참조할 수 없어요, ReferenceError를 던져요.

@@ -2683,8 +2696,8 @@ console.log(checkAge(21)); ```javascript fetch('https://www.website.com/api/user/1') - .then(res => res.json()) - .then(res => console.log(res)); + .then((res) => res.json()) + .then((res) => console.log(res)); ``` - A: `fetch` 메소드의 결과 @@ -2692,12 +2705,12 @@ fetch('https://www.website.com/api/user/1') - C: 이전 `.then()`에서 callback된 결과 - D: 항상 undefined -
정답 +

-#### 정답: C +#### 답: C -두번째 `.then`에서의 `res`의 값은 이전`.then`에서 리턴된 값이에요. 이것 처럼 `.then`을 계속해서 연결할 수 있고, 값은 계속해서 다음 핸들러로 전달 돼요. +두번째 `.then`에서의 `res`의 값은 이전`.then`에서 반환된 값이에요. 이것 처럼 `.then`을 계속해서 연결할 수 있고, 값은 계속해서 다음 핸들러로 전달 돼요.

@@ -2717,18 +2730,18 @@ function getName(name) { - C: `new Boolean(name)` - D: `name.length` -
정답 +

-#### 정답: A +#### 답: A -`!!name`에서, 우리는 `name`의 값이 참 같은지 거짓 같은지 결정해요. 만약 테스트 하려는 name이 참 같다면, `!name`은 `false`를 리턴해요. `!false` (실제로는 `!!name`)는 `true`를 리턴해요. +`!!name`에서, 우리는 `name`의 값이 참 같은지 거짓 같은지 여부를 결정해요. 만약 시험 하려는 name이 참 같다면, `!name`은 `false`를 반환해요. `!false`(실제로는 `!!name`)는 `true`를 반환해요. `hasName`을 `name`으로 설정하면, `hasName`은 불린 값 `true`가 아니라, `getName` 함수에 전달된 값으로 설정해요. -`new Boolean(true)`은 불린 값 자체가 아닌, 감싼 객체를 리턴해요. +`new Boolean(true)`은 불린 값 자체가 아닌, 감싼 객체를 반환해요. -`name.length`은 그것의 `true`의 여부가 아닌, 전달된 인수의 길이를 리턴해요. +`name.length`은 그것의 `true`의 여부가 아닌, 전달된 인수의 길이를 반환해요.

@@ -2738,7 +2751,7 @@ function getName(name) { ###### 87. 무엇이 출력 될까요? ```javascript -console.log("I want pizza"[0]); +console.log('I want pizza'[0]); ``` - A: `"""` @@ -2746,12 +2759,12 @@ console.log("I want pizza"[0]); - C: `SyntaxError` - D: `undefined` -
정답 +

-#### 정답: B +#### 답: B -문자열의 특정 인덱스의 문자를 얻으려면, 대괄호 표기법을 사용하면 돼요. 문자열의 첫 번째 문자는 인덱스 0과 기타등등을 가지고 있어요. 이 경우 문자 `"I'`인 인덱스 0이 출력되는 요소를 갖길 원해요. +문자열의 특정 인덱스의 문자를 얻으려면, 대괄호 표기법을 사용하면 돼요. 문자열의 첫 번째 문자는 인덱스 0과 기타등등을 가지고 있어요. 이 경우엔 인덱스가 0이고 문자 `"I'`가 출력되는 요소를 갖길 원해요. 이 방법은 IE7 이하에서는 지원되지 않는다는 것을 유의하세요. 이 경우, `.charAt()`를 사용하세요. @@ -2764,10 +2777,10 @@ console.log("I want pizza"[0]); ```javascript function sum(num1, num2 = num1) { - console.log(num1 + num2) + console.log(num1 + num2); } -sum(10) +sum(10); ``` - A: `NaN` @@ -2775,14 +2788,14 @@ sum(10) - C: `ReferenceError` - D: `undefined` -

정답 +

-#### 정답: B +#### 답: B -기본 파라미터의 값은 기본 파라미터를 정의하기 _전_ 이라면, 함수의 다른 파라미터와 같게 설정 할 수 있어요. 우리는 `sum` 함수에 값 `10`을 전달 했어요. 만약 `sum` 함수에 인수의 값을 하나만 받았다면, `num2`를 위한 값은 전달되지 않고, `num1`은 전달된 값과 같다는 의미에요. `num1`의 기본값은 `num1`의 값인 `10`과 같아요. `num1 + num2`는 `20`을 리턴해요. +기본값 매개변수를 이전에 정의한 함수의 다른 매개변수로 설정 할 수 있어요. 우리는 `sum` 함수에 값 `10`을 전달했어요. 만약 `sum` 함수에 인수의 값을 하나만 받았다면, `num2`의 값은 전달되지 않았고, `num1`은 전달된 값 `10`과 같다는 의미에요. `num2`의 기본값은 `num1`의 값인 `10`과 같아요. `num1 + num2`는 `20`을 반환해요. -만약 기본 파리미터가 정의된 _후_ (오른쪽에) 기본 파라미터의 값을 설정하려고 시도한다면, 파라미터의 값은 아직 초기화되지 않아, 오류를 던질 거에요. +만약 기본갑 매개변수가 정의된 _후_ (오른쪽에) 기본 파라미터의 값을 설정하려고 시도한다면, 파라미터의 값은 아직 초기화되지 않아, 오류를 던질 거에요.

@@ -2792,14 +2805,14 @@ sum(10) ###### 89. 무엇이 출력 될까요? ```javascript -// module.js -export default () => "Hello world" -export const name = "Lydia" +// module.js +export default () => 'Hello world'; +export const name = 'Lydia'; -// index.js -import * as data from "./module" +// index.js +import * as data from './module'; -console.log(data) +console.log(data); ``` - A: `{ default: [Function (anonymous)], name: "Lydia" }` @@ -2807,14 +2820,14 @@ console.log(data) - C: `{ default: "Hello world", name: "Lydia" }` - D: Global object of `module.js` -
정답 +

-#### 정답: A +#### 답: A -`import * as name` 신택스를 사용해서, `module.js` 파일에 있는 _모든 exports_ 를 `index.js` 파일 안에 `data`라고 불리는 새로운 객체를 생성해요. `module.js` 파일에는, 2개의 export가 있어요: default export 와 named export. default export는 문자열 `"Hello World"`을 리턴하는 함수고, named export는 문자열 `"Lydia"`의 값을 가진 `name`이라고 불리는 변수예요. +`import * as name` 신택스를 사용해, `module.js` 파일에 있는 _모든 exports_ 를 `index.js` 파일 안에 `data`라고 불리는 새로운 객체로 생성해요. `module.js` 파일에는, 2개의 export가 있어요: default export 와 named export. default export는 문자열 `"Hello World"`을 반환하는 함수이고, named export는 문자열 `"Lydia"`의 값을 가진 `name`이라고 불리는 변수예요. -`data` 객체는 default export를 위한 `default` 속성을 가지고, 다른 속성들은 named exports의 이름들과 그에 해당하는 값들을 가져요. +`data` 객체는 default export를 위한 `default` 속성을 가지고, 다른 속성은 named exports의 이름과 그에 해당하는 값을 가져요.

@@ -2826,12 +2839,12 @@ console.log(data) ```javascript class Person { constructor(name) { - this.name = name + this.name = name; } } -const member = new Person("John") -console.log(typeof member) +const member = new Person('John'); +console.log(typeof member); ``` - A: `"class"` @@ -2839,10 +2852,10 @@ console.log(typeof member) - C: `"object"` - D: `"string"` -
정답 +

-#### 정답: C +#### 답: C Class는 함수 생성자를 위한 문법적 설탕이에요. 함수 생성자로서 `Person` 클래스와 동등한 것은 다음과 같아요: @@ -2852,7 +2865,7 @@ function Person() { } ``` -`new`와 함께 불려진 함수 생성자는 `Person`의 인스턴스를 생성하고, `typeof` 키워드는 인스턴스의 `"object"`를 리턴해요. `typeof member`는 `"object"`을 리턴해요. +`new`와 함께 불려진 함수 생성자는 `Person`의 인스턴스를 생성하고, `typeof` 키워드는 인스턴스의 `"object"`를 반환해요. `typeof member`는 `"object"`을 반환해요.

@@ -2862,9 +2875,9 @@ function Person() { ###### 91. 무엇이 출력 될까요? ```javascript -let newList = [1, 2, 3].push(4) +let newList = [1, 2, 3].push(4); -console.log(newList.push(5)) +console.log(newList.push(5)); ``` - A: `[1, 2, 3, 4, 5]` @@ -2872,14 +2885,14 @@ console.log(newList.push(5)) - C: `[1, 2, 3, 4]` - D: `Error` -
정답 +

-#### 정답: D +#### 답: D -`.push` 메소드는 배열 자체가 아니라, 배열의 _새로운 길이_ 를 리턴해요! `newList`를 `[1, 2, 3].push(4)`과 동일하게 설정함으로써, `newList`를 배열의 새로운 길이와 동일하게 설정했어요: `4`. +`.push` 메소드는 배열 자체가 아니라, 배열의 _새로운 길이_ 를 반환해요! `newList`를 `[1, 2, 3].push(4)`과 동일하게 설정함으로써, `newList`를 배열의 새로운 길이와 동일하게 설정했어요: `4`. -그리고나서, `.push` 메소드를 `newList`에 사용하려고 했어요. `newList`는 숫자 값 `4` 이기 때문에, `.push` 메소드를 사용할 수 없어요: TypeError가 던져져요. +그리고서, `.push` 메소드를 `newList`에 사용하려고 했어요. `newList`는 숫자 값 `4` 이기 때문에, `.push` 메소드를 사용할 수 없어요: TypeError가 던져져요.

@@ -2890,26 +2903,27 @@ console.log(newList.push(5)) ```javascript function giveLydiaPizza() { - return "Here is pizza!" + return 'Here is pizza!'; } -const giveLydiaChocolate = () => "Here's chocolate... now go hit the gym already." +const giveLydiaChocolate = () => + "Here's chocolate... now go hit the gym already."; -console.log(giveLydiaPizza.prototype) -console.log(giveLydiaChocolate.prototype) +console.log(giveLydiaPizza.prototype); +console.log(giveLydiaChocolate.prototype); ``` -- A: `{ constructor: ...}` `{ constructor: ...}` -- B: `{}` `{ constructor: ...}` +- A: `{ constructor: ...}` `{ constructor: ...}` +- B: `{}` `{ constructor: ...}` - C: `{ constructor: ...}` `{}` - D: `{ constructor: ...}` `undefined` -
정답 +
Answer

-#### 정답: D +#### 답: D -`giveLydiaPizza`와 같은 정규 함수는, `생성자` 속성을 가진 `프로토타입` 객체(프로토타입 객체)를 속성으로 가져요. 그러나 `giveLydiaChocolate` 함수와 같은 화살표 함수에서는, `prototype` 속성을 가지고 있지 않아요. `giveLydiaChocolate.prototype`을 사용해 `prototype` 속성에 접근하려고 할때, `undefined`이 리턴될 거에요. +`giveLydiaPizza`와 같은 일반 함수는, `생성자` 속성을 가진 객체(프로토타입 객체)이고, `프로토타입` 속성을 갖고 있어요. 그러나 `giveLydiaChocolate` 함수와 같은 화살표 함수에서는, `prototype` 속성을 가지고 있지 않아요. `giveLydiaChocolate.prototype`을 사용해 `prototype` 속성에 접근하려고 할 때, `undefined`이 반환될 거에요.

@@ -2920,30 +2934,30 @@ console.log(giveLydiaChocolate.prototype) ```javascript const person = { - name: "Lydia", - age: 21 + name: 'Lydia', + age: 21, }; for (const [x, y] of Object.entries(person)) { - console.log(x, y) + console.log(x, y); } ``` - A: `name` `Lydia` 그리고 `age` `21` -- B: `["name", "Lydia"]` 그리고 `["age", 21]` +- B: `["name", "Lydia"]` 그리고 `["age", 21]` - C: `["name", "age"]` 그리고 `undefined` - D: `Error` -
정답 +

-#### 정답: A +#### 답: A -`Object.entries(person)`은 키와 값을 세트로 가진 배열의 배열을 리턴해요: +`Object.entries(person)`은 키와 객체를 포함한 중첩 배열의 배열을 반환해요: -`[ [ 'name', 'Lydia' ], [ 'age', 21 ] ]` +`[ [ 'name', 'Lydia' ], [ 'age', 21 ] ]` -`for-of` 루프를 사용해서, 배열 안에 각 요소를 계속해서 반복할 수 있는데, 이 경우엔 하위 배열이에요. 하위 배열을 `const [x, y]`을 사용해, for-of 루프에서 즉시 분해할 수 있어요. `x`는 하위 배열의 첫 번째 요소와 같고, `y`는 하위 배열의 두 번째 요소와 같아요. +`for-of` 루프를 사용해서, 배열 안에 각 요소를 반복할 수 있는데, 이 경우엔 하위 배열이에요. 하위 배열을 `const [x, y]`을 사용해, for-of 루프에서 즉시 분해할 수 있어요. `x`는 하위 배열의 첫 번째 요소와 같고, `y`는 하위 배열의 두 번째 요소와 같아요. 첫번째 하위요소는 `[ "name", "Lydia" ]`로, `x`는 `"name"`, `y`는 `"Lydia"`을 출력해요. 두번째 하위요소는 `[ "age", 21 ]`로, `x`는 `"age"`, `y`는 `21`을 출력해요. @@ -2960,30 +2974,31 @@ function getItems(fruitList, ...args, favoriteFruit) { return [...fruitList, ...args, favoriteFruit] } -console.log(getItems(["banana", "apple"], "pear", "orange")) +getItems(["banana", "apple"], "pear", "orange") ``` - A: `["banana", "apple", "pear", "orange"]` -- B: `[["banana", "apple"], "pear", "orange"]` +- B: `[["banana", "apple"], "pear", "orange"]` - C: `["banana", "apple", ["pear"], "orange"]` - D: `SyntaxError` -

정답 +

-#### 정답: D +#### 답: D -`...args`은 나머지 파라미터예요. 나머지 파라미터의 값은 모든 나머지 인수들을 포함한 배열이며, **마지막 파라미터만 될 수 있어요**! 지금 예시에서는, 나머지 파라미터는 두번째 파라미터예요. 이것은 불가능하고, 신택스 에러를 던지게 될거에요. +`...args`은 rest 파라미터예요. rest 파라미터의 값은 모든 나머지 인수을 포함한 배열이며, **마지막 파라미터만 될 수 있어요**! 지금 예시에서는, rest 파라미터는 두번째 파라미터예요. 이것은 불가능하고, syntax error를 던지게 될거에요. ```javascript function getItems(fruitList, favoriteFruit, ...args) { - return [...fruitList, ...args, favoriteFruit] + return [...fruitList, ...args, favoriteFruit]; } -getItems(["banana", "apple"], "pear", "orange") +getItems(['banana', 'apple'], 'pear', 'orange'); ``` -The above example works. This returns the array `[ 'banana', 'apple', 'orange', 'pear' ]` +위의 예시는 동작해요. 배열 `[ 'banana', 'apple', 'orange', 'pear' ]`을 반환해요. +

@@ -2993,17 +3008,14 @@ The above example works. This returns the array `[ 'banana', 'apple', 'orange', ```javascript function nums(a, b) { - if - (a > b) - console.log('a is bigger') - else - console.log('b is bigger') - return - a + b + if (a > b) console.log('a is bigger'); + else console.log('b is bigger'); + return + a + b; } -console.log(nums(4, 2)) -console.log(nums(1, 2)) +console.log(nums(4, 2)); +console.log(nums(1, 2)); ``` - A: `a is bigger`, `6` 그리고 `b is bigger`, `3` @@ -3011,21 +3023,21 @@ console.log(nums(1, 2)) - C: `undefined` 그리고 `undefined` - D: `SyntaxError` -
정답 +

-#### 정답: B +#### 답: B -JavaScript에서, 세미콜론을 (`;`)을 명시적으로 포함하여 쓰지 _않_ 더라도, JavaScript 엔진은 여전히 문 뒤에 그들을 추가해줘요. 이것은 **자동 세미콜론 삽입**이라고 불려요. 예를 들어 문은 변수, 또는 `throw`, `return`, `break` 등과 같은 키워드가 될 수도 있어요. +JavaScript에서, 세미콜론을 (`;`)을 명시적으로 _포함하여_ 쓰지 않더라도, JavaScript 엔진은 여전히 문 뒤에 그들을 추가해요. 이것은 **자동 세미콜론 삽입**이라고 불려요. 예를 들어 문은 변수, 또는 `throw`, `return`, `break` 등과 같은 키워드가 될 수도 있어요. -여기, `return`문을 썼고, 다른 값 `a + b`은 _새로운 줄_ 에 쓰였어요. 그러나, 새로운 줄이기 때문에, 엔진은 실제로 그 값이 리턴되길 바라는지 알 수 없어요. 대신에, 자동적으로 `return` 뒤에 세미콜론을 더해줘요. 이것을 볼 수 있을거에요: +여기, `return`문을 썼고, 다른 값 `a + b`은 _새로운 줄_ 에 쓰였어요. 그러나, 새로운 줄이기 때문에, 엔진은 실제로 그 값이 반환되길 바라는지 알 수 없어요. 대신에, 자동적으로 `return` 뒤에 세미콜론을 더해요. 이것을 볼 수 있을거에요: ```javascript - return; - a + b +return; +a + b; ``` -`return` 키워드 뒤에 함수가 실행되는 것이 중단되기 때문에, `a + b`의 의미는 도달되지 않아요. 여기서 처럼, 만약 아무 값도 리턴되지 않는다면, 함수는 `undefined`를 리턴할 거예요. `if/else`문 뒤에는 자동으로 삽입되는 게 없다는 걸 유의해요! +`return` 키워드 뒤에 함수가 실행되는 것이 중단되기 때문에, `a + b`의 의미는 도달되지 않아요. 여기서처럼, 만약 아무 값도 반환되지 않는다면 함수는 `undefined`를 반환해요. `if/else`문 뒤에는 아무것도 자동으로 삽입되지 않는다는 걸 유의해요!

@@ -3037,18 +3049,18 @@ JavaScript에서, 세미콜론을 (`;`)을 명시적으로 포함하여 쓰지 _ ```javascript class Person { constructor() { - this.name = "Lydia" + this.name = 'Lydia'; } } Person = class AnotherPerson { constructor() { - this.name = "Sarah" + this.name = 'Sarah'; } -} +}; -const member = new Person() -console.log(member.name) +const member = new Person(); +console.log(member.name); ``` - A: `"Lydia"` @@ -3056,12 +3068,12 @@ console.log(member.name) - C: `Error: cannot redeclare Person` - D: `SyntaxError` -
정답 +

-#### 정답: B +#### 답: B -다른 클래스/함수 생성자로 클래스를 설정할 수 있어요. 이 경우, `Person`을 `AnotherPerson`로 설정했어요. 이 생성자의 name은 `Sarah`예요, 따라서 새로운 `Person`의 인스턴스 `member`의 name 속성은 `"Sarah"`예요. +클래스를 다른 클래스/함수 생성자로 설정할 수 있어요. 이 경우, `Person`을 `AnotherPerson`로 설정했어요. 이 생성자의 name은 `Sarah`예요, 따라서 새로운 `Person`의 인스턴스 `member`의 name 속성은 `"Sarah"`예요.

@@ -3072,11 +3084,11 @@ console.log(member.name) ```javascript const info = { - [Symbol('a')]: 'b' -} + [Symbol('a')]: 'b', +}; -console.log(info) -console.log(Object.keys(info)) +console.log(info); +console.log(Object.keys(info)); ``` - A: `{Symbol('a'): 'b'}` 그리고 `["{Symbol('a')"]` @@ -3084,14 +3096,14 @@ console.log(Object.keys(info)) - C: `{ a: "b" }` 그리고 `["a"]` - D: `{Symbol('a'): 'b'}` 그리고 `[]` -
정답 +

-#### 정답: D +#### 답: D -심볼은 _열거 불가능_ 해요. Object.keys 메소드는 객체의 모든 _열거 가능_ 한 키 속성들을 리턴해요. 심볼은 보이지 않고, 빈 객체가 리턴돼요. 객체 전체를 출력할때, 모든 속성들은 보여요, 심지어 열거 불가능한 것이라해도. +심볼은 _열거 불가능_ 해요. Object.keys 메소드는 객체의 모든 _열거 가능_ 한 키 속성을 반환해요. 심볼은 보이지 않고, 빈 객체가 반환돼요. 객체 전체를 출력하면, 심지어 열거 불가능한 것이라도 모든 속성을 볼 수 있어요. -이것은 심볼의 많은 특성 중 하나에요: 완전히 고유한 값(예를들어 2개의 라이브러리를 같은 객체의 속성으로 추가하고 싶을때, 객체의 우연한 이름 충돌을 방지해요)을 나타내는 것 외에, 이 방법으로 객체의 속성을 "숨길" 수 있어요(비록 완전히는 아닐지라도. 여전히 `Object.getOwnPropertySymbols()` 메소드를 사용해 심볼에 접근 할 수 있어요). +이것은 심볼의 많은 특성 중 하나에요: 완전히 고유한 값(예를 들어 작업중인 2개의 라이브러리를 같은 객체의 속성으로 추가하고 싶을 때, 객체의 우연한 이름 충돌을 방지해요)을 나타내는 것 외에, 이 방법으로 객체의 속성을 "숨길" 수 있어요(비록 완전히는 아닐지라도. 여전히 `Object.getOwnPropertySymbols()` 메소드를 사용해 심볼에 접근 할 수 있어요).

@@ -3116,22 +3128,22 @@ console.log(getUser(user)) - C: `[1, 2, 3, 4]` 그리고 `{ name: "Lydia", age: 21 }` - D: `Error` 그리고 `{ name: "Lydia", age: 21 }` -
정답 +

-#### 정답: A +#### 답: A `getList`함수는 배열을 인수로 받았어요. `getList` 함수의 괄호 사이에 있는 배열을 즉시 분해 했어요: - `[x, ...y] = [1, 2, 3, 4]` +`[x, ...y] = [1, 2, 3, 4]` -나머지 파라미터를 사용해 `...y`에 모든 "남은" 인수들을 배열에 넣었어요. 이 경우에서 남아있는 인수는 `2`, `3` 그리고 `4`예요. `y`의 값은 배열이고, 모든 나머지 파라미터를 포함하고 있어요. 이 경우 `x`의 값은 `1`이기 때문에, `[x, y]`는 `[1, [2, 3, 4]]`로 출력돼요. +rest 파라미터를 사용해 `...y`에 모든 "남은" 인수을 배열에 넣었어요. 이 경우에서 남아있는 인수는 `2`, `3` 그리고 `4`예요. `y`의 값은 배열이고, 모든 rest 파라미터를 포함하고 있어요. 이 경우 `x`의 값은 `1`이기 때문에, `[x, y]`는 `[1, [2, 3, 4]]`로 출력돼요. -`getUser` 함수는 배열을 받았어요. 화살표 함수에서, 우리가 한개의 값을 리턴한다면 중괄호를 사용할 _필요_ 가 없어요. 그러나, 만약 화살표 함수에서 _객체_ 를 리턴하고 싶다면, 괄호 사이에 리턴할 값을 써야해요, 그렇지 않다면 아무 값도 리턴받을 수 없어요! 다음 함수에서는 객체가 리턴 될 거에요: +`getUser` 함수는 객체를 받았어요. 화살표 함수에서, 우리가 한개의 값을 반환한다면 중괄호를 사용할 _필요_ 가 없어요. 그러나, 만약 화살표 함수에서 _객체_ 를 반환하고 싶다면, 괄호 사이에 반환할 값을 써야해요, 그렇지 않다면 아무 값도 반환받을 수 없어요! 다음 함수에서는 객체가 반환 될 거에요: -```const getUser = user => ({ name: user.name, age: user.age })``` +`const getUser = user => ({ name: user.name, age: user.age })` -이 경우 값이 리턴되는 값이 없으므로, 함수는 `undefined`을 리턴할거에요. +이 경우 값이 반환되는 값이 없으므로, 함수는 `undefined`을 반환해요.

@@ -3141,9 +3153,9 @@ console.log(getUser(user)) ###### 99. 무엇이 출력 될까요? ```javascript -const name = "Lydia" +const name = 'Lydia'; -console.log(name()) +console.log(name()); ``` - A: `SyntaxError` @@ -3151,17 +3163,16 @@ console.log(name()) - C: `TypeError` - D: `undefined` -
정답 +

-#### 정답: C +#### 답: C -변수 `name`은 문자열을 값으로 가지고 있고, 함수가 아니죠, 따라서 호출할 수 없어요. +변수 `name`은 문자열을 값으로 가지고 있고, 함수가 아니에요, 따라서 호출할 수 없어요. -TypeErrors는 값이 예상된 유형이 아닐 경우 던져져요. JavaScript는 `name`을 호출하려고 했기 때문에 함수일거라 예상했어요. 그러나 문자열이였기 때문에, TypeError가 던져져요: name은 함수가 아니죠! +TypeErrors는 값이 예상된 유형이 아닐 경우 던져져요. JavaScript는 `name`을 호출하려고 했기 때문에 함수일거라 예상했어요. 그러나 문자열이였기 때문에, TypeError가 던져져요: name은 함수가 아니에요! SyntaxErrors는 어떤 것을 썼을때 JavaScript에서 유효하지 않을 때 던져져요, 예를들어 `return`을 `retrun`로 썼을때 말이죠. - ReferenceErrors는 JavaScript가 접근하려고 하는 값의 참조를 찾을 수 없을 때 던져져요.

@@ -3175,7 +3186,7 @@ ReferenceErrors는 JavaScript가 접근하려고 하는 값의 참조를 찾을 // 🎉✨ 이번이 내 100번째 질문이에요! ✨🎉 const output = `${[] && 'Im'}possible! -You should${'' && `n't`} see a therapist after so much JavaScript lol` +You should${'' && `n't`} see a therapist after so much JavaScript lol`; ``` - A: `possible! You should see a therapist after so much JavaScript lol` @@ -3183,14 +3194,14 @@ You should${'' && `n't`} see a therapist after so much JavaScript lol` - C: `possible! You shouldn't see a therapist after so much JavaScript lol` - D: `Impossible! You shouldn't see a therapist after so much JavaScript lol` -
정답 +

-#### 정답: B +#### 답: B -`[]`은 참 같은 값이에요. `&&` 연산자를 사용할 때, 만약 왼쪽에 있는 값이 참 같은 값이라면 오른쪽 값은 리턴될 거에요. 이 경우, 왼쪽의 값 `[]`은 참 같은 값이에요, 따라서 `'Im'`은 리턴될 거예요. +`[]`은 참 같은 값이에요. `&&` 연산자를 사용할 때, 왼쪽에 있는 값이 참 같은 값이라면 오른쪽 값은 반환될 거에요. 이 경우, 왼쪽의 값 `[]`은 참 같은 값이에요, 따라서 `'Im'`은 반환될 거예요. -`""`은 거짓 같은 값이에요. 만약 왼쪽 값이 거짓 같은 값이라면, 리턴되는 것은 없어요. `n't`은 리턴되지 않아요. +`""`은 거짓 같은 값이에요. 만약 왼쪽 값이 거짓 같은 값이라면, 반환되는 것은 없어요. `n't`은 반환되지 않아요.

@@ -3200,11 +3211,11 @@ You should${'' && `n't`} see a therapist after so much JavaScript lol` ###### 101. 무엇이 출력 될까요? ```javascript -const one = (false || {} || null) -const two = (null || false || "") -const three = ([] || 0 || true) +const one = false || {} || null; +const two = null || false || ''; +const three = [] || 0 || true; -console.log(one, two, three) +console.log(one, two, three); ``` - A: `false` `null` `[]` @@ -3212,18 +3223,18 @@ console.log(one, two, three) - C: `{}` `""` `[]` - D: `null` `null` `true` -
정답 +

-#### 정답: C +#### 답: C -`||` 연산자를 사용하면, 최초의 참 같은 피연산자를 리턴해요. 만약 모든 값이 거짓 같다면, 마지막 피연산자를 리턴해요. +`||` 연산자를 사용하면, 첫번째로 참 같은 피연산자를 반환해요. 만약 모든 값이 거짓 같다면, 마지막 피연산자를 반환해요. -`(false || {} || null)`: 빈 객체 `{}`는 진짜 같은 값이에요. 이것은 최초로(그리고 유일하게) 진짜 같은 값이라 리턴돼요. `one`은 `{}`이에요. +`(false || {} || null)`: 빈 객체 `{}`는 진짜 같은 값이에요. 이것은 최초로(그리고 유일하게) 진짜 같은 값이라 반환돼요. `one`은 `{}`이에요. -`(null || false || "")`: 모든 피연산자는 가짜 같은 값이에요. 이것은 마지막 피연산자 `""`가 리턴된다는 것을 의미해요. `two`는 `""`이에요. +`(null || false || "")`: 모든 피연산자는 가짜 같은 값이에요. 이것은 마지막 피연산자 `""`가 반환된다는 것을 의미해요. `two`는 `""`이에요. -`([] || 0 || "")`: 빈 배열 `[]`은 진짜 같은 값이에요. 이것은 최초의 진짜 같은 값이라 리턴돼요. `three`은 `[]`이에요. +`([] || 0 || "")`: 빈 배열 `[]`은 진짜 같은 값이에요. 이것은 첫번째로 진짜 같은 값이라 반환돼요. `three`은 `[]`이에요.

@@ -3233,20 +3244,20 @@ console.log(one, two, three) ###### 102. 무엇이 출력 될까요? ```javascript -const myPromise = () => Promise.resolve('I have resolved!') +const myPromise = () => Promise.resolve('I have resolved!'); function firstFunction() { - myPromise().then(res => console.log(res)) - console.log('second') + myPromise().then((res) => console.log(res)); + console.log('second'); } async function secondFunction() { - console.log(await myPromise()) - console.log('second') + console.log(await myPromise()); + console.log('second'); } -firstFunction() -secondFunction() +firstFunction(); +secondFunction(); ``` - A: `I have resolved!`, `second` 그리고 `I have resolved!`, `second` @@ -3254,20 +3265,20 @@ secondFunction() - C: `I have resolved!`, `second` 그리고 `second`, `I have resolved!` - D: `second`, `I have resolved!` 그리고 `I have resolved!`, `second` -
정답 +

-#### 정답: D +#### 답: D -promise를 사용하면, 기본적으로 _이 함수를 실행하고 싶지만, 시간이 좀 걸릴 수 있으니 실행 중에 잠시 미뤄둘거에요. 확실한 값이 resoloved(혹은 rejected)로 전달되었을 때와 콜 스택이 비었을 때 이 값을 사용하고 싶어요_ 라고 말해요. +promise를 사용하면, 기본적으로 _이 함수를 실행하고 싶지만, 시간이 좀 걸릴 수 있어 실행 중에 잠시 미뤄둘거에요. 확실한 값이 resoloved(혹은 rejected) 되었을 때와 콜 스택이 비었을 때, 이 값을 사용하고 싶어요_ 라고 말해요. -`async` 함수 안에서 `.then`과 `await` 두개의 키워드에서 값을 얻을 수 있어요. 비록 `.then`과 `await`에서 프라미스의 값을 얻을 수 있지만, 그들은 약간 다르게 작동해요. +`async` 함수 안에서 `.then`과 `await` 두 개의 키워드로 값을 얻을 수 있어요. 비록 `.then`과 `await` 모두 프라미스의 값을 얻을 수 있지만, 그들은 약간 다르게 작동해요. -첫번째 `firstFunction`에서, (뭐랄까) myPromise 함수가 실행되는 것을 미뤘지만, 다른 코드를 계속해서 실행하는데, 이 경우 `console.log('second')`에요. 그리고나서, 함수는 콜스택이 비워져 있는 걸 본 다음 출력된 문자열 `I have resolved`를 resolved로 전달해요. +`firstFunction`에서, (뭐랄까) myPromise 함수가 실행되는 것을 미뤘지만, 다른 코드, 이 경우엔 `console.log('second')`를 계속해서 실행해요. 그리고서, 함수는 콜스택이 비워져 있는 걸 본 다음 출력된 문자열 `I have resolved`를 resolved 해요. -`secondFunction`에서의 await 키워드를 사용하면, 말 그대로 다음 라인으로 옮기기 전 값이 resoloved함수로 전달될 때 까지 async 함수의 실행을 중단해요. +`secondFunction`에서 await 키워드를 사용하면, 말 그대로 다음 라인으로 옮기기 전에 값이 resoloved 될 때 까지 async 함수의 실행을 중단해요. -이것은 `myPromise`이 값 `I have resolved`을 얻을 때 까지 기다린다는 의미이며, 단 한 번 발생하면, 다음라인으로 이동해요: `second`이 출력되죠. +이것은 `myPromise`이 값 `I have resolved`을 resolve 할 때 까지 기다린다는 뜻이고, 단 한 번만 발생한 뒤, 다음라인으로 이동해요: `second`이 출력돼요.

@@ -3277,14 +3288,14 @@ promise를 사용하면, 기본적으로 _이 함수를 실행하고 싶지만, ###### 103. 무엇이 출력 될까요? ```javascript -const set = new Set() +const set = new Set(); -set.add(1) -set.add("Lydia") -set.add({ name: "Lydia" }) +set.add(1); +set.add('Lydia'); +set.add({ name: 'Lydia' }); for (let item of set) { - console.log(item + 2) + console.log(item + 2); } ``` @@ -3293,18 +3304,18 @@ for (let item of set) { - C: `3`, `Lydia2`, `[object Object]2` - D: `"12"`, `Lydia2`, `[object Object]2` -
정답 +

-#### 정답: C +#### 답: C -`+` 연산자는 숫자로 나타난 값을 더하는데 사용될 뿐만 아니라, 문자열을 연결해주는데 사용 할 수 있어요. JavaScript 엔진은 하나 이상의 값들이 숫자가 아닌 것을 발견 했을 때, 숫자를 문자열로 강제로 변환해요. +`+` 연산자는 숫자로 나타난 값을 더하는데 사용될 뿐만 아니라, 문자열을 연결하는데 사용해요. JavaScript 엔진은 하나 이상의 값이 숫자가 아닌 것을 발견 했을 때, 숫자를 문자열로 강제로 변환해요. -첫번째 `1`은, 숫자로된 값이에요. `1 + 2`는 숫자 3을 리턴해요. +첫번째 `1`은, 숫자로된 값이에요. `1 + 2`는 숫자 3을 반환해요. -그러나, 두번째는 문자열 `"Lydia"`이에요. `"Lydia"`은 문자열이고, `2`는 숫자에요: `2`는 문자열로 강제 변환되어요. `"Lydia"`그리고 `"2"`이 연결되어, 문자열 `"Lydia2"`이 리턴되요. +그러나, 두번째는 문자열 `"Lydia"`이에요. `"Lydia"`은 문자열이고, `2`는 숫자에요: `2`는 문자열로 강제 변환되어요. `"Lydia"`그리고 `"2"`이 연결되어, 문자열 `"Lydia2"`이 반환되요. -`{ name: "Lydia" }`은 객체에요. 객체가 아닌 숫자나 객체는 문자열이 아니므로, 둘다 문자화되어요. 정규 객체를 문자화 할때, `"[object Object]"`가 돼요. `"[object Object]"`는 `"2"`와 연결되어 `"[object Object]2"`가 돼요. +`{ name: "Lydia" }`은 객체에요. 객체가 아닌 숫자나 객체는 문자열이 아니므로, 둘다 문자화되어요. 일반 객체를 문자화 할때, `"[object Object]"`가 돼요. `"[object Object]"`는 `"2"`와 연결되어 `"[object Object]2"`가 돼요.

@@ -3314,7 +3325,7 @@ for (let item of set) { ###### 104. 값은 무엇일까요? ```javascript -Promise.resolve(5) +Promise.resolve(5); ``` - A: `5` @@ -3322,14 +3333,14 @@ Promise.resolve(5) - C: `Promise {: 5}` - D: `Error` -
정답 +

-#### 정답: C +#### 답: C -promise이나 non-promise이 아니더라도 값의 모든 타입은 `Promise.resolve`으로 전달 할 수 있어요. 메소드 그 자체는 resolved 값을 가진 promise를 리턴해요 (``). 정규 함수를 전달한다면, 정규 값을 가진 resolved promise를 얻게 될거에요. 만약 promise를 전달한다면, 전달된 promise의 resolved 값과 resolved promise를 얻게 될거에요. +promise 또는 non-promise가 아니더라도, 어떤 유형의 값이라도 `Promise.resolve`으로 전달 할 수 있어요. 메소드 그 자체는 resolved 값을 가진 promise를 반환해요 (``). 일반 함수를 전달한다면, 일반 값을 가진 resolved promise를 얻게 될거에요. 만약 promise를 전달한다면, 전달된 promise의 resolved 값과 resolved promise를 얻게 될거에요. -이 경우, 숫자 값 `5`를 전달했어요. 이것은 값 `5`를 가진 resolved promise를 리턴해요. +이 경우, 숫자 값 `5`를 전달했어요. 이것은 값 `5`를 가진 resolved promise를 반환해요.

@@ -3341,15 +3352,15 @@ promise이나 non-promise이 아니더라도 값의 모든 타입은 `Promise.re ```javascript function compareMembers(person1, person2 = person) { if (person1 !== person2) { - console.log("Not the same!") + console.log('Not the same!'); } else { - console.log("They are the same!") + console.log('They are the same!'); } } -const person = { name: "Lydia" } +const person = { name: 'Lydia' }; -compareMembers(person) +compareMembers(person); ``` - A: `Not the same!` @@ -3357,14 +3368,14 @@ compareMembers(person) - C: `ReferenceError` - D: `SyntaxError` -
정답 +

-#### 정답: B +#### 답: B -객체는 참조에 의해 전달되었어요. 엄격한 같은 비교 (`===`)로 객체를 검사한다면, 그들의 참조를 비교할거에요. +객체는 참조로 전달되었어요. 엄격한 동등 비교 (`===`)로 객체를 검사한다면, 그들의 참조를 비교할거에요. -`person2`의 기본 값을 `person` 객체와 동일하게 설정 하고, `person` 객체를 `person1`의 값으로 전달 했어요. +`person2`의 기본 값을 `person` 객체로 설정 하고, `person` 객체를 `person1`의 값으로 전달 했어요. 이것은 두개의 값은 메모리의 같은 장소의 참조를 가지고 있다는 걸 의미해요, 그렇기 때문에 그들은 같아요. @@ -3384,11 +3395,11 @@ const colorConfig = { green: true, black: true, yellow: false, -} +}; -const colors = ["pink", "red", "blue"] +const colors = ['pink', 'red', 'blue']; -console.log(colorConfig.colors[1]) +console.log(colorConfig.colors[1]); ``` - A: `true` @@ -3396,16 +3407,16 @@ console.log(colorConfig.colors[1]) - C: `undefined` - D: `TypeError` -

정답 +

-#### 정답: D +#### 답: D -JavaScript에서, 객체의 속성에 접근하는 2가지 방법을 가지고 있어요: 괄호 표기법, 또는 점 표기법. 이 예제에서는, 괄호표기법 (`colorConfig["colors"]`) 대신 점 표기법 (`colorConfig.colors`)을 사용 했어요. +JavaScript에서, 객체의 속성에 접근하는 2가지 방법을 가지고 있어요: 괄호 표기법, 또는 점 표기법. 이 예제에서는, 괄호 표기법 (`colorConfig["colors"]`) 대신 점 표기법 (`colorConfig.colors`)을 사용 했어요. -점 표기법에서, JavaScript는 정확한 이름을 가진 객체의 속성을 찾으려 해요. 이 예제에서 JavaScript는 `colorConfig` 객체의 `colors`라고 불리는 속성을 찾으려고 했어요. 그곳에는 `colors`라고 불리는 속성이 없어요, 그래서 `undefined`을 리턴해요. 그리고 나서, `[1]`을 사용해서 첫번째 요소의 값에 접근하려고 했어요. `undefined`의 값에는 이것을 할 수 없어요, 그래서 `TypeError`를 던져요: `Cannot read property '1' of undefined`. +점 표기법에서, JavaScript는 정확히 일치하는 이름을 가진 객체의 속성을 찾으려 해요. 이 예제에서 JavaScript는 `colorConfig` 객체의 `colors`라고 불리는 속성을 찾으려고 했어요. 그곳에는 `colors`라고 불리는 속성이 없어요, 그래서 `undefined`을 반환해요. 그리고 나서, `[1]`을 사용해서 첫번째 요소의 값에 접근하려고 했어요. `undefined`의 값에는 이것을 할 수 없어요, 그래서 `TypeError`를 던져요: `Cannot read property '1' of undefined`. -JavaScript 문장을 해석(또는 참조형 변수를 원시 데이터 타입으로 만들어 주도록) 해요. 괄호 표기법을 사용할때, 첫번째로 열린 괄호 `[`을 보고 닫힌 괄호 `]`를 찾을 때 까지 계속 진행되는 것으로 보여요. 그러고 나서야, 문장을 평가할거에요. 만약 `colorConfig[colors[1]]`을 사용했다면, `colorConfig` 객체의 속성 `red` 의 값이 리턴될 거에요. +JavaScript 문장을 해석(또는 참조형 변수를 원시 데이터 타입으로 만들어 주도록) 해요. 괄호 표기법을 사용할때, 첫번째로 열린 괄호 `[`을 보고 닫힌 괄호 `]`를 찾을 때 까지 계속 진행되는 것으로 보여요. 그러고 나서야, 문장을 평가할거에요. 만약 `colorConfig[colors[1]]`을 사용했다면, `colorConfig` 객체의 속성 `red` 의 값이 반환될 거에요.

@@ -3415,18 +3426,18 @@ JavaScript 문장을 해석(또는 참조형 변수를 원시 데이터 타입 ###### 107. 값은 무엇일까요? ```javascript -console.log('❤️' === '❤️') +console.log('❤️' === '❤️'); ``` - A: `true` - B: `false` -
정답 +

-#### 정답: A +#### 답: A -엔진에서, 이모티콘은 유니코드에요. 하트 이모티콘의 유니코드는 `"U+2764 U+FE0F"`에요. 같은 이모티콘의 유니코드는 항상 같아요, 따라서 각각 다른 두개의 같은 문자열을 비교하는 것이므로 true를 리턴해요. +엔진에서, 이모티콘은 유니코드에요. 하트 이모티콘의 유니코드는 `"U+2764 U+FE0F"`에요. 같은 이모티콘의 유니코드는 항상 같아요, 따라서 각각 다른 두개의 같은 문자열을 비교하는 것이므로 true를 반환해요.

@@ -3436,59 +3447,61 @@ console.log('❤️' === '❤️') ###### 108. 다음 중 원본 배열을 수정하는 method는 무엇일까요? ```javascript -const emojis = ['✨', '🥑', '😍'] +const emojis = ['✨', '🥑', '😍']; -emojis.map(x => x + '✨') -emojis.filter(x => x !== '🥑') -emojis.find(x => x !== '🥑') -emojis.reduce((acc, cur) => acc + '✨') -emojis.slice(1, 2, '✨') -emojis.splice(1, 2, '✨') +emojis.map((x) => x + '✨'); +emojis.filter((x) => x !== '🥑'); +emojis.find((x) => x !== '🥑'); +emojis.reduce((acc, cur) => acc + '✨'); +emojis.slice(1, 2, '✨'); +emojis.splice(1, 2, '✨'); ``` - A: `All of them` - B: `map` `reduce` `slice` `splice` -- C: `map` `slice` `splice` +- C: `map` `slice` `splice` - D: `splice` -
정답 +

-#### 정답: D +#### 답: D -`splice` method를 사용하면, 요소를 삭제, 대체하거나 추가함으로써 원본 배열을 수정해요. 이 경우에서, 인덱스 1에서 부터 2개의 아이템을 제거했어요. (`'🥑'` 와 `'😍'`를 삭제했어요) 그리고 ✨ 이모티콘을 대신 추가했죠. +`splice` method를 사용하면, 요소를 삭제, 대체하거나 추가함으로써 원본 배열을 수정해요. 이 경우에서, 인덱스 1에서 부터 2개의 아이템을 제거했어요. (`'🥑'` 와 `'😍'`를 삭제했어요) 그리고 ✨ 이모티콘을 대신 추가했어요. -`map`, `filter` 그리고 `slice` 는 새로운 배열을 리턴해하고, `find` 요소를 리턴하며, `reduce` 감소된 값을 리턴해요. +`map`, `filter` 그리고 `slice` 는 새로운 배열을 반환하고, `find` 는 요소를 반환하며, `reduce` 는 감소된 값을 반환해요.

--- -###### 109. 무엇이 출력 될까요? +###### 109. 무엇이 출력 될까요? ```javascript -const food = ['🍕', '🍫', '🥑', '🍔'] -const info = { favoriteFood: food[0] } +const food = ['🍕', '🍫', '🥑', '🍔']; +const info = { favoriteFood: food[0] }; -info.favoriteFood = '🍝' +info.favoriteFood = '🍝'; -console.log(food) +console.log(food); ``` - A: `['🍕', '🍫', '🥑', '🍔']` - B: `['🍝', '🍫', '🥑', '🍔']` -- C: `['🍝', '🍕', '🍫', '🥑', '🍔']` +- C: `['🍝', '🍕', '🍫', '🥑', '🍔']` - D: `ReferenceError` -
정답 +

-#### 정답: A +#### 답: A + +`info` 객체의 `favoriteFood` 속성 값을 피자 이모지 `'🍕'`으로 설정했어요. 문자는 원시 데이터 형이에요. JavaScript에서 원시 데이터 형은 참조로 상호 작용 하지 않아요. -`info` 객체의 `favoriteFood` 속성 값을 피자 이모티콘 `'🍕'`와 같게 설정했어요. 문자는 원시 데이터 형이에요. JavaScript에서, 원시 데이터 형은 (객체가 아닌 모든 것) _값_ 에 의해 상호 작용해요. 이 경우, `info` 객체의 `favoriteFood` 속성 값을 `food` 배열 안의 첫 번째 요소와 같게 설정했어요. 문자열은 원시 데이터 형이므로 값에의해 상호 작용해요. (좀 더 알고싶다면 내 [블로그 포스트](https://www.theavocoder.com/complete-javascript/2018/12/21/by-value-vs-by-reference)를 참고하세요.) +JavaScript에서, 원시 데이터 형은 (객체가 아닌 모든 것) _값_ 으로 상호 작용해요. 이 경우, `info` 객체의 `favoriteFood` 속성 값을 `food` 배열 안의 첫 번째 요소로 설정했어요. 이 경우 (`'🍕'`) 피자 이모지는 문자열이에요. 문자열은 원시 데이터 형이므로 값으로 상호 작용해요. (좀 더 알고싶다면 내 [블로그 포스트](https://www.theavocoder.com/complete-javascript/2018/12/21/by-value-vs-by-reference)를 참고하세요.) -그리고나서, `info` 객체의 `favoriteFood` 속성 값을 바꿨어요. `favoriteFood`의 값은 단지 배열의 첫 번째 요소의 값을 _복사_ 했기 때문에 `food` 배열은 바뀌지 않고, `food[0]` 요소의 메모리 공간과 같은 참조를 갖지 않아요. food를 출력할 때, 여전히 원본 배열 ['🍕', '🍫', '🥑', '🍔']` 이에요. +그리고나서, `info` 객체의 `favoriteFood` 속성 값을 바꿨어요. `favoriteFood`의 값은 단지 배열의 첫 번째 요소의 값을 _복사_ 했기 때문에 `food` 배열은 바뀌지 않고, `food[0]` 요소의 메모리 공간과 같은 참조를 갖지 않아요. food를 출력하면, 여전히 원본 배열 `['🍕', '🍫', '🥑', '🍔']` 이에요.

@@ -3498,34 +3511,33 @@ console.log(food) ###### 110. 이 메소드는 무엇을 할까요? ```javascript -JSON.parse() +JSON.parse(); ``` -- A: Parses JSON to a JavaScript value -- B: Parses a JavaScript object to JSON -- C: Parses any JavaScript value to JSON -- D: Parses JSON to a JavaScript object only +- A: JSON을 JavaScript 값으로 Parses +- B: JavaScript 객체를 JSON으로 Parses +- C: 모든 JavaScript 값을 JSON으로 Parses +- D: JSON을 JavaScript 객체로만 Parses -
정답 +

-#### 정답: A +#### 답: A -`JSON.parse()`메소드를 사용하면, JSON 문자열의 구문을 분석하여 JavaScript 값으로 생성해요. -With the `JSON.parse()` method, we can parse JSON string to a JavaScript value. +`JSON.parse()`메소드를 사용하면, JSON 문자열의 구문을 분석해 JavaScript 값으로 생성해요. ```javascript // 숫자를 유효한 JSON 문자열로 변환해요, 그리고 나서 JSON 문자열의 구문을 분석해 JavaScript 값으로 생성해요. -const jsonNumber = JSON.stringify(4) // '4' -JSON.parse(jsonNumber) // 4 +const jsonNumber = JSON.stringify(4); // '4' +JSON.parse(jsonNumber); // 4 // 배열 값을 유효한 JSON 문자열로 변환해요, 그리고 나서 JSON 문자열의 구문을 분석해 JavaScript 값으로 생성해요. -const jsonArray = JSON.stringify([1, 2, 3]) // '[1, 2, 3]' -JSON.parse(jsonArray) // [1, 2, 3] +const jsonArray = JSON.stringify([1, 2, 3]); // '[1, 2, 3]' +JSON.parse(jsonArray); // [1, 2, 3] // 객체를 유효한 JSON 문자열로 변환해요, 그리고 나서 JSON 문자열의 구문을 분석해 JavaScript 값으로 생성해요. -const jsonArray = JSON.stringify({ name: "Lydia" }) // '{"name":"Lydia"}' -JSON.parse(jsonArray) // { name: 'Lydia' } +const jsonArray = JSON.stringify({ name: 'Lydia' }); // '{"name":"Lydia"}' +JSON.parse(jsonArray); // { name: 'Lydia' } ```

@@ -3533,17 +3545,17 @@ JSON.parse(jsonArray) // { name: 'Lydia' } --- -###### 111. 무엇이 출력 될까요? +###### 111. 무엇이 출력 될까요? ```javascript -let name = 'Lydia' +let name = 'Lydia'; function getName() { - console.log(name) - let name = 'Sarah' + console.log(name); + let name = 'Sarah'; } -getName() +getName(); ``` - A: Lydia @@ -3551,25 +3563,25 @@ getName() - C: `undefined` - D: `ReferenceError` -
정답 +

-#### 정답: D +#### 답: D -각 기능에는 자체 _실행 컨텍스트_ (또는 _범위_)가 있어요. `getName` 함수는 먼저 자체 컨텍스트(범위) 내에서 접근하려고 하는 변수 `name`이 포함되어 있는지 살펴봐요: `let` 키워드와 함께 선언 했기 때문에 `'Sarah'`의 값을 가져요. +각 함수는 각자의 _실행 컨텍스트_ (또는 _스코프_)가 있어요. `getName`함수는 먼저 접근하려고 하는 변수 `name`가 자신의 컨텍스트(스코프) 내 포함하고 있는지 살펴봐요. 이 경우에, `getName`함수는 자체 `name` 변수를 포함해요.: `let` 키워드로 값이 `'Sarah'`인 변수 `name`을 선언해요. -`let` 키워드 (그리고 `const`)를 사용한 변수는 끌어올려지지만, `var`와 다르게 초기화 되지는 않아요. 그들을 선언 (초기화) 하는 줄 전에 접근 할 수 없어요. "일시적 사각지대"라고 불려요. 그들을 선언하기 전에 접근하려고 한다면, JavaScript는 `ReferenceError`를 던져요. +`let` 키워드 (그리고 `const`)를 사용한 변수는 호이스팅 되지만, `var`와는 다르게 초기화 되지 않아요. 그들을 선언(초기화)한 줄 전에서는 접근 할 수 없어요. 이것은 "일시적 사각지대"라고 불려요. 변수를 선언하기 전에 접근하려고 한다면, JavaScript는 `ReferenceError`를 던져요. -`getName` 함수 안에 `name` 변수를 선언하지 않았다면, javaScript 엔진은 _스코프 체인_ 을 내려다 보지 않았을 거예요. 외부 범위에 `Lydia`의 값을 가진 `name` 변수가 있어요. 이 경우엔 `Lydia`를 출력할거예요. +`getName` 함수 안에 `name` 변수를 선언하지 않았다면, javaScript 엔진은 _스코프 체인_ 을 살펴봤을 거예요. 외부 범위에는 값이 `Lydia`인 `name`이라는 변수가 있어요. 이 경우 `Lydia`를 출력할 거예요. ```javascript -let name = 'Lydia' +let name = 'Lydia'; function getName() { - console.log(name) + console.log(name); } -getName() // Lydia +getName(); // Lydia ```

@@ -3588,11 +3600,11 @@ function* generatorTwo() { yield* ['a', 'b', 'c']; } -const one = generatorOne() -const two = generatorTwo() +const one = generatorOne(); +const two = generatorTwo(); -console.log(one.next().value) -console.log(two.next().value) +console.log(one.next().value); +console.log(two.next().value); ``` - A: `a` 그리고 `a` @@ -3600,28 +3612,27 @@ console.log(two.next().value) - C: `['a', 'b', 'c']` 그리고 `a` - D: `a` 그리고 `['a', 'b', 'c']` -
정답 +

-#### 정답: C +#### 답: C -`yield` 키워드를 사용하면, 제너레이터 함수 안의 값을 `중단` 했어요. `yield`키워드를 사용하면, 다른 제너레이터 함수 또는 반복 가능한 객체(예를들면 배열)의 값을 중단 시킬 수 있어요. +`yield` 키워드를 사용해, 제너레이터 함수 안의 값을 `yield` 해요. `yield*` 키워드를 사용하면, 다른 제너레이터 함수 또는 반복 가능한 객체(예를 들면 배열)의 값을 yield 할 수 있어요. -`generatorOne`에서, 전체 배열 `['a', 'b', 'c']`을 `yield` 키워드를 사용해서 중단 했어요. `one` (`one.next().value`)의 `next` 메소드가 리턴 한 객체의 `value`속성 값은 전체 배열 `['a', 'b', 'c']`과 같아요. +`generatorOne`에서, 전체 배열 `['a', 'b', 'c']`을 `yield` 키워드를 사용해 넘겨줬어요. `one` (`one.next().value`)의 `next` 메소드가 반환한 객체의 `value`속성 값은 전체 배열 `['a', 'b', 'c']`과 같아요. ```javascript -console.log(one.next().value) // ['a', 'b', 'c'] -console.log(one.next().value) // undefined +console.log(one.next().value); // ['a', 'b', 'c'] +console.log(one.next().value); // undefined ``` -`generatorTwo`에서, `yield*` 키워드를 사용했어요. `two`의 첫번째 값이 중단 되었다는 의미이고, 반복자의 첫번째로 중단된 값과 같아요.반복자는 배열 `['a', 'b', 'c']` 이에요. -처음으로 중단된 값은 `a`이고, 따라서 첫번째 순서에서 `two.next().value`를 부르면 `a`를 리턴해요. +`generatorTwo`에서, `yield*` 키워드를 사용했어요. `two`의 첫 번째로 넘겨진 값이 이터레이터의 첫 번째 넘겨진 값과 같다는 의미에요. 이터레이터는 배열 `['a', 'b', 'c']` 이에요. 처음으로 넘겨진 값은 `a`이고, 따라서 첫 번째 순서에서 `two.next().value`를 부르면 `a`를 반환해요. ```javascript -console.log(two.next().value) // 'a' -console.log(two.next().value) // 'b' -console.log(two.next().value) // 'c' -console.log(two.next().value) // undefined +console.log(two.next().value); // 'a' +console.log(two.next().value); // 'b' +console.log(two.next().value); // 'c' +console.log(two.next().value); // undefined ```

@@ -3632,7 +3643,7 @@ console.log(two.next().value) // undefined ###### 113. 무엇이 출력 될까요? ```javascript -console.log(`${(x => x)('I love')} to program`) +console.log(`${((x) => x)('I love')} to program`); ``` - A: `I love to program` @@ -3640,12 +3651,12 @@ console.log(`${(x => x)('I love')} to program`) - C: `${(x => x)('I love') to program` - D: `TypeError` -
정답 +

-#### 정답: A +#### 답: A -템플릿 리터러를 사용한 표현식은 첫번째로 평가돼요. 문자열은 표현식의 리턴된 값을 포함하게 된다는 것을 의미하고, 이 경우 함수 `(x => x)('I love')`는 즉시 호출 돼요. 화살표 함수 `x => x`의 인수 값으로 `I love`를 전달 했어요. `x`는 `'I love'`이고 리턴 될 거에요. 이 결과는 `I love to program` 이에요. +템플릿 리터러를 사용한 표현식은 첫번째로 평가돼요. 문자열은 표현식의 반환된 값을 포함하게 된다는 것을 의미하고, 이 경우 함수 `(x => x)('I love')`는 즉시 호출 돼요. 화살표 함수 `x => x`의 인수 값으로 `I love`를 전달 했어요. `x`는 `'I love'`이고 반환 될 거에요. 이 결과는 `I love to program` 이에요.

@@ -3657,11 +3668,11 @@ console.log(`${(x => x)('I love')} to program`) ```javascript let config = { alert: setInterval(() => { - console.log('Alert!') - }, 1000) -} + console.log('Alert!'); + }, 1000), +}; -config = null +config = null; ``` - A: `setInterval` 콜백은 호출되지 않을거에요 @@ -3669,32 +3680,36 @@ config = null - C: `setInterval` 콜백은 여전히 매 초마다 호출돼요 - D: 결코 `config.alert()`를 호출 하지 않고, config 는 `null`이에요 -
정답 +

-#### 정답: C +#### 답: C -일반적으로 객체를 `null`로 설정했을때, 객체는 더 이상의 객체 참조가 없어 _쓰레기 수집_ 되어요. 그러나, `setInterval`을 가진 콜백 함수는 화살표 함수 (`config` 객체로 감싸진) 이기 때문에, 콜백 함수는 여전히 `config` 객체의 참조를 갖고 있고, 객체는 쓰레기 수집 되지 않아요. 쓰레기 수집 되지 않았기 때문에, `setInterval` 콜백 함수는 여전히 매 1000ms (1s) 마다 호출 돼요, +일반적으로 객체를 `null`로 설정했을 때, 객체는 더 이상 참조할 객체가 없어 _쓰레기 수집_ 되어요. 그러나, `setInterval`을 가진 콜백 함수는 화살표 함수 (`config` 객체로 감싸진) 이기 때문에, 콜백 함수는 여전히 `config` 객체를 참조 하고 있어요 +참조가 존재하는 한, 객체는 쓰레기 수집 되지 않아요. +이것은 interval이므로, `config`를 `null` 또는 `delete`-ing `config.alert`로 설정하면 interval이 쓰레기 수집되지 않아, interval은 계속 호출됩니다 +메모리에서 제거하기 위해서 `clearInterval(config.alert)`로 지워야 합니다. +지워지지 않았기 때문에, `setInterval` 콜백 함수는 매 1000ms (1s)마다 계속 호출 될 거에요.

--- -###### 115. 어느 method가 값 `'Hello world!'`를 리턴 할까요? +###### 115. 어느 method가 값 `'Hello world!'`를 반환 할까요? ```javascript -const myMap = new Map() -const myFunc = () => 'greeting' +const myMap = new Map(); +const myFunc = () => 'greeting'; -myMap.set(myFunc, 'Hello world!') +myMap.set(myFunc, 'Hello world!'); //1 -myMap.get('greeting') +myMap.get('greeting'); //2 -myMap.get(myFunc) +myMap.get(myFunc); //3 -myMap.get(() => 'greeting') +myMap.get(() => 'greeting'); ``` - A: 1 @@ -3702,15 +3717,15 @@ myMap.get(() => 'greeting') - C: 2 그리고 3 - D: 모두 -
정답 +

-#### 정답: B +#### 답: B -`set` 메소드를 사용해서 키/값을 쌍으로 추가할 때, 키는 `set`함수로 전달 된 첫 번째 인수의 값이 되고, 값은 `set`함수로 전달된 두 번째 인수의 값이 될거에요. 이 경우에선 키는 _함수_ `() => 'greeting'`이고, 값은 `'Hello world'` 에요. `myMap`은 이제 `{ () => 'greeting' => 'Hello world!' }` 예요. +키/값을 쌍으로 추가할 때 `set` 메소드를 사용하면, 키는 `set` 함수로 전달 된 첫 번째 인수의 값이 되고, 값은 `set` 함수로 전달된 두 번째 인수의 값이 될 거에요. 이 경우에 키는 _함수_ `() => 'greeting'`이고, 값은 `'Hello world'`예요. `myMap`은 이제 `{ () => 'greeting' => 'Hello world!' }` 예요. 1은 틀렸어요, 키는 `'greeting'`가 아니라 `() => 'greeting'`이기 때문이에요. -3은 틀렸어요, `get`메소드에 새로 생성한 함수를 전달 했기 때문이에요. 객체는 _참조_에 의해 상호작용해요. 함수는 객체이고, 그들이 같다고 하더라도 두 함수가 절대로 같지 않은 이유예요: 메모리 안 다른 장소의 참조를 가지고 있어요. +3은 틀렸어요, `get`메소드에 새로 생성한 함수를 파라미터로 전달 했기 때문이에요. 객체는 *참조*로 상호작용해요. 함수는 객체이기 때문에, 두 함수가 같다고 하더라도 절대로 동일하지 않아요: 메모리 안에 다른 장소의 참조를 가지고 있어요.

@@ -3721,20 +3736,20 @@ myMap.get(() => 'greeting') ```javascript const person = { - name: "Lydia", - age: 21 -} + name: 'Lydia', + age: 21, +}; -const changeAge = (x = { ...person }) => x.age += 1 +const changeAge = (x = { ...person }) => (x.age += 1); const changeAgeAndName = (x = { ...person }) => { - x.age += 1 - x.name = "Sarah" -} + x.age += 1; + x.name = 'Sarah'; +}; -changeAge(person) -changeAgeAndName() +changeAge(person); +changeAgeAndName(); -console.log(person) +console.log(person); ``` - A: `{name: "Sarah", age: 22}` @@ -3742,16 +3757,16 @@ console.log(person) - C: `{name: "Lydia", age: 22}` - D: `{name: "Lydia", age: 23}` -
정답 +

-#### 정답: C +#### 답: C -`changeAge`와 `changeAgeAndName`함수 둘다 기본 파라미터를 가지고 있는데 즉, _새롭게_ 만들어진 객체 `{ ...person }`를 가지고 있어요. 이 객체는 `person` 객체의 모든 키/값의 복사본을 가지고 있어요. +`changeAge`와 `changeAgeAndName`함수 모두 _새롭게_ 만들어진 객체 `{ ...person }`를 기본값 매개변수로 가지고 있어요. 이 객체는 `person` 객체의 모든 키/값의 복사본을 가지고 있어요. -첫번째로, `changeAge`함수를 호출 했고, 그것의 인수로 `person` 객체를 전달 했어요. 이 함수는 `age`속성의 값을 1 증가 시켜요. `person`은 이제 `{ name: "Lydia", age: 22 }`이에요. +첫번째로, `changeAge`함수를 호출 했고, 그것의 인수로 `person` 객체를 전달 했어요. 이 함수는 `age`속성의 값을 1 증가 시켜요. `person`은 이제 `{ name: "Lydia", age: 22 }`예요. -그리고나서, `changeAgeAndName` 함수를 호출 했지만, 파라미터를 전달하지 않았어요. 대신에, `x`의 값은 _새로운_ 객체와 같아요: `{ ...person }`. 새로운 객체이기 때문에, `person`객체의 속성들의 값에 영향을 주지 않아요. `person`은 여전히 `{ name: "Lydia", age: 22 }`와 같아요. +그리고서, `changeAgeAndName` 함수를 호출 했지만, 파라미터를 전달하지 않았어요. 대신에, `x`의 값은 _새로운_ 객체와 같아요: `{ ...person }`. 새로운 객체이기 때문에, `person`객체의 속성의 값에 영향을 주지 않아요. `person`은 여전히 `{ name: "Lydia", age: 22 }`와 같아요.

From ce4133436e2167f59a37e7b2105601751e846d38 Mon Sep 17 00:00:00 2001 From: Hamir Mahal Date: Sun, 8 Aug 2021 16:50:30 -0700 Subject: [PATCH 085/193] improve 87. What's the output? with minor changes --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index f0921a95..f196481d 100644 --- a/README.md +++ b/README.md @@ -2764,9 +2764,9 @@ console.log('I want pizza'[0]); #### Answer: B -In order to get an character on a specific index in a string, you can use bracket notation. The first character in the string has index 0, and so on. In this case we want to get the element which index is 0, the character `"I'`, which gets logged. +In order to get a character at a specific index of a string, you can use bracket notation. The first character in the string has index 0, and so on. In this case, we want to get the element with index 0, the character `"I'`, which gets logged. -Note that this method is not supported in IE7 and below. In that case, use `.charAt()` +Note that this method is not supported in IE7 and below. In that case, use `.charAt()`.

From deeebea9c0cf57e4fc8bacdef37cf1ce271ba4fb Mon Sep 17 00:00:00 2001 From: Danah Date: Mon, 9 Aug 2021 23:57:56 +0900 Subject: [PATCH 086/193] Translation 117 - 126 to ko-KR --- ko-KR/README-ko_KR.md | 318 +++++++++++++++++++++++++++++++++++++++++- 1 file changed, 313 insertions(+), 5 deletions(-) diff --git a/ko-KR/README-ko_KR.md b/ko-KR/README-ko_KR.md index ff31a19c..7ca39976 100644 --- a/ko-KR/README-ko_KR.md +++ b/ko-KR/README-ko_KR.md @@ -1320,7 +1320,7 @@ setInterval(() => console.log('Hi'), 1000); #### 답: A -문자열은 반복 가능한 객체예요. 스프레드 연산자는 반복 가능한 객체의 모든 문자를 하나의 요소로 매핑해요. +문자열은 반복 가능한 객체예요. spread 연산자는 반복 가능한 객체의 모든 문자를 하나의 요소로 매핑해요.

@@ -1879,7 +1879,7 @@ console.log(admin); #### 답: B -스프레드 연산자 `...` 를 사용해 객체를 결합할 수 있어요. 이것은 한 객체의 키/값 쌍을 복사본으로 만들어, 다른 객체에 추가해요. 이 경우, `user` 객체의 복사본을 만들어, `admin` 객체에 추가해요. `admin` 객체는 이제 복사된 키/값 쌍이 들어있고, 결과는 `{ admin: true, name: "Lydia", age: 21 }` 예요. +spread 연산자 `...` 를 사용해 객체를 결합할 수 있어요. 이것은 한 객체의 키/값 쌍을 복사본으로 만들어, 다른 객체에 추가해요. 이 경우, `user` 객체의 복사본을 만들어, `admin` 객체에 추가해요. `admin` 객체는 이제 복사된 키/값 쌍이 들어있고, 결과는 `{ admin: true, name: "Lydia", age: 21 }` 예요.

@@ -2918,7 +2918,7 @@ console.log(giveLydiaChocolate.prototype); - C: `{ constructor: ...}` `{}` - D: `{ constructor: ...}` `undefined` -
Answer +

#### 답: D @@ -3010,7 +3010,7 @@ getItems(['banana', 'apple'], 'pear', 'orange'); function nums(a, b) { if (a > b) console.log('a is bigger'); else console.log('b is bigger'); - return + return; a + b; } @@ -3497,7 +3497,7 @@ console.log(food); #### 답: A -`info` 객체의 `favoriteFood` 속성 값을 피자 이모지 `'🍕'`으로 설정했어요. 문자는 원시 데이터 형이에요. JavaScript에서 원시 데이터 형은 참조로 상호 작용 하지 않아요. +`info` 객체의 `favoriteFood` 속성 값을 피자 이모지 `'🍕'`으로 설정했어요. 문자는 원시 데이터 형이에요. JavaScript에서 원시 데이터 형은 참조로 상호 작용 하지 않아요. JavaScript에서, 원시 데이터 형은 (객체가 아닌 모든 것) _값_ 으로 상호 작용해요. 이 경우, `info` 객체의 `favoriteFood` 속성 값을 `food` 배열 안의 첫 번째 요소로 설정했어요. 이 경우 (`'🍕'`) 피자 이모지는 문자열이에요. 문자열은 원시 데이터 형이므로 값으로 상호 작용해요. (좀 더 알고싶다면 내 [블로그 포스트](https://www.theavocoder.com/complete-javascript/2018/12/21/by-value-vs-by-reference)를 참고하세요.) @@ -3770,3 +3770,311 @@ console.log(person);

+ +--- + +###### 117. 다음 선택지 중 어느 것이 `6`을 반환 할까요? + +```javascript +function sumValues(x, y, z) { + return x + y + z; +} +``` + +- A: `sumValues([...1, 2, 3])` +- B: `sumValues([...[1, 2, 3]])` +- C: `sumValues(...[1, 2, 3])` +- D: `sumValues([1, 2, 3])` + +
+

+ +#### 답: C + +연산자 `...`를 사용하면, 반복 가능한 객체를 개별요소로 _spread_ 펼칠 수 있어요. `sumValues` 함수는 인수 3개를 받았어요: `x`, `y` 그리고 `z`. `...[1, 2, 3]`를 `sumValues` 함수에 전달하면 `1, 2, 3` 가 될 거예요. + +

+
+ +--- + +###### 118. 무엇이 출력 될까요? + +```javascript +let num = 1; +const list = ['🥳', '🤠', '🥰', '🤪']; + +console.log(list[(num += 1)]); +``` + +- A: `🤠` +- B: `🥰` +- C: `SyntaxError` +- D: `ReferenceError` + +
+

+ +#### 답: B + +`+=` 연산자를 사용하면, `num`의 값을 `1` 씩 증가시켜요. `num`은 초기값 `1`을 가지고 있어요, 그래서 `1 + 1` 은 `2`예요.`list` 배열의 2번째 인덱스 아이템은 🥰 예요, `console.log(list[2])` 는 🥰 을 출력해요. + +

+
+ +--- + +###### 119. 무엇이 출력 될까요? + +```javascript +const person = { + firstName: 'Lydia', + lastName: 'Hallie', + pet: { + name: 'Mara', + breed: 'Dutch Tulip Hound', + }, + getFullName() { + return `${this.firstName} ${this.lastName}`; + }, +}; + +console.log(person.pet?.name); +console.log(person.pet?.family?.name); +console.log(person.getFullName?.()); +console.log(member.getLastName?.()); +``` + +- A: `undefined` `undefined` `undefined` `undefined` +- B: `Mara` `undefined` `Lydia Hallie` `ReferenceError` +- C: `Mara` `null` `Lydia Hallie` `null` +- D: `null` `ReferenceError` `null` `ReferenceError` + +
+

+ +#### 답: B + +optional chaining 연산자 `?.`를 사용하면, 더 깊이 중첩된 값이 유효한지 여부를 더는 분명하게 확인하지 않아도 돼요.`undefined` 또는 `null` 값 (_nullish_) 속성에 접근 하려고 할 때, 표현식을 평가하지 않고 `undefined`을 반환해요. + +`person.pet?.name`: `person`은 속성이름 `pet`을 가지고 있어요: `person.pet`은 nullish(null 또는 undefined)가 아니에요. `name`이라는 속성 이름을 가지고 있어, `Mara`를 반환해요. +`person.pet?.family?.name`: `person`은 속성이름 `pet`을 가지고 있어요: `person.pet`은 nullish가 아니에요. `pet`은 _not_ have a property called `family`라는 속성이 _없어요_, `person.pet.family`은 nullish예요. 표현식은 `undefined`을 반환해요. +`person.getFullName?.()`: `person`은 속성이름`getFullName`을 가지고 있어요: `person.getFullName()` 은 nullish기 아니고 호출 할 수 있어요, 따라서 `Lydia Hallie`을 반환해요. +`member.getLastName?.()`: `member`은 정의되지 않았어요: `member.getLastName()`은 nullish예요. 표현식은 `undefined`을 반환해요. + +

+
+ +--- + +###### 120. 무엇이 출력 될까요? + +```javascript +const groceries = ['banana', 'apple', 'peanuts']; + +if (groceries.indexOf('banana')) { + console.log('We have to buy bananas!'); +} else { + console.log(`We don't have to buy bananas!`); +} +``` + +- A: We have to buy bananas! +- B: We don't have to buy bananas +- C: `undefined` +- D: `1` + +
+

+ +#### 답: B + +if문에 조건 `groceries.indexOf("banana")`을 전달했어요. `groceries.indexOf("banana")`은 `0`을 반환하고, 이건 거짓 같은 값이에요. if문의 조건이 거짓 같은 값이기 때문에, 코드는 `else` 블록을 실행하고, `We don't have to buy bananas!`이 출력돼요. + +

+
+ +--- + +###### 121. 무엇이 출력 될까요? + +```javascript +const config = { + languages: [], + set language(lang) { + return this.languages.push(lang); + }, +}; + +console.log(config.language); +``` + +- A: `function language(lang) { this.languages.push(lang }` +- B: `0` +- C: `[]` +- D: `undefined` + +
+

+ +#### 답: D + +`language` 메소드는 `setter`예요. Setters는 실제 값을 유지하지 않아요, 그들의 목적은 속성을 _수정_ 하는 거예요. `setter` 메소드를 부르면, `undefined`가 반환돼요. + +

+
+ +--- + +###### 122. 무엇이 출력 될까요? + +```javascript +const name = 'Lydia Hallie'; + +console.log(!typeof name === 'object'); +console.log(!typeof name === 'string'); +``` + +- A: `false` `true` +- B: `true` `false` +- C: `false` `false` +- D: `true` `true` + +
+

+ +#### 답: C + +`typeof name`은 `"string"`을 반환해요. 문자열 `"string"`은 진짜 같은 값이고, `!typeof name`은 불리언 값 `false`을 반환해요. `false === "object"` 그리고 `false === "string"` 둘다 `false`을 반환해요. + +(특정한 형과 같은지(다른지) 알고 싶다면, `!typeof` 대신 `!==`을 사용 해야 해요.) + +

+
+ +--- + +###### 123. 무엇이 출력 될까요? + +```javascript +const add = (x) => (y) => (z) => { + console.log(x, y, z); + return x + y + z; +}; + +add(4)(5)(6); +``` + +- A: `4` `5` `6` +- B: `6` `5` `4` +- C: `4` `function` `function` +- D: `undefined` `undefined` `6` + +
+

+ +#### 답: A + +`add`함수는 화살표 함수를 반환하는 함수를 반환하고, 반환한 함수는 화살표 함수를 반환하고, 반환한 함수는 화살표 함수를 반환해요(아직 나와 함께인가요?). 첫 번째 함수는 값이 `4`인 인수 `x`를 받아요. 값이 `5`인 인수 `y`를 받은 두 번째 함수를 호출해요. 그리고 우리는 값이 `6`인 인수 `z`를 받은 세 번째 함수를 호출해요. 값 `x`, `y` 그리고 `z`를 가진 마지막 화살표 함수에 접근하려고 할 때, JS 엔진은 그에 따른 값 `x` 그리고 `y`를 찾기 위해 스코프 체인을 올라가요. 이건 `4` `5` `6`을 반환해요. + +

+
+ +--- + +###### 124. 무엇이 출력 될까요? + +```javascript +async function* range(start, end) { + for (let i = start; i <= end; i++) { + yield Promise.resolve(i); + } +} + +(async () => { + const gen = range(1, 3); + for await (const item of gen) { + console.log(item); + } +})(); +``` + +- A: `Promise {1}` `Promise {2}` `Promise {3}` +- B: `Promise {}` `Promise {}` `Promise {}` +- C: `1` `2` `3` +- D: `undefined` `undefined` `undefined` + +
+

+ +#### 답: C + +제너레이터 함수 `range`은 range에 전달한 각각의 아이템에 promise를 가진 async 객체를 반환해요: `Promise{1}`, `Promise{2}`, `Promise{3}`. 변수 `gen`을 async 객체로 만들고, 그후에 `for await ... of` 루프를 사용해서 순환해요. 변수 `item`은 반환된 Promise 값 만들어요: 첫번째는 `Promise{1}`, 그다음은 `Promise{2}`, 그다음은 `Promise{3}`. `item`의 값인 프로미스를 resolved 하기 위해 _기다리고_, resolved 된 프로미스의 _값_ 은 반환돼요: `1`, `2`, 그리고 `3`. + +

+
+ +--- + +###### 125. 무엇이 출력 될까요? + +```javascript +const myFunc = ({ x, y, z }) => { + console.log(x, y, z); +}; + +myFunc(1, 2, 3); +``` + +- A: `1` `2` `3` +- B: `{1: 1}` `{2: 2}` `{3: 3}` +- C: `{ 1: undefined }` `undefined` `undefined` +- D: `undefined` `undefined` `undefined` + +
+

+ +#### 답: D + +`myFunc`는 속성 `x`, `y` 그리고 `z`를 속성으로 가진 객체가 인수라고 예상해요. `x`, `y` 그리고 `z`의 속성을 가진 하나의 객체({x: 1, y: 2, z: 3}) 대신, 분리된 숫자 값 (1, 2, 3)을 전달했기 때문에 `x`, `y` 그리고 `z`는 기본값 `undefined`을 가져요. + +

+
+ +--- + +###### 126. 무엇이 출력 될까요? + +```javascript +function getFine(speed, amount) { + const formattedSpeed = new Intl.NumberFormat('en-US', { + style: 'unit', + unit: 'mile-per-hour', + }).format(speed); + + const formattedAmount = new Intl.NumberFormat('en-US', { + style: 'currency', + currency: 'USD', + }).format(amount); + + return `The driver drove ${formattedSpeed} and has to pay ${formattedAmount}`; +} + +console.log(getFine(130, 300)); +``` + +- A: The driver drove 130 and has to pay 300 +- B: The driver drove 130 mph and has to pay \$300.00 +- C: The driver drove undefined and has to pay undefined +- D: The driver drove 130.00 and has to pay 300.00 + +
+

+ +#### 답: B + +`Intl.NumberFormat` 메소드를 사용하면, 숫자 값을 원하는 로케일로 만들 수 있어요. 숫자 값 `130`을 `unit`이 `mile-per-hour`인 로케일 `en-US`로 만들면, `130 mph`가 돼요. 숫자 값 `300`을 `currency`가 `USD`인 로케일 `en-US`로 만들면 `$300.00`가 돼요. + +

+
+ From 337f865d557dc0fe21b504284d6eb2d2384e61ee Mon Sep 17 00:00:00 2001 From: vyron Date: Wed, 11 Aug 2021 13:38:52 +0800 Subject: [PATCH 087/193] fix EN => CN translation(126) --- zh-CN/README-zh_CN.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/zh-CN/README-zh_CN.md b/zh-CN/README-zh_CN.md index f178684e..d7ad5966 100644 --- a/zh-CN/README-zh_CN.md +++ b/zh-CN/README-zh_CN.md @@ -4032,15 +4032,15 @@ myFunc(1, 2, 3); ```javascript function getFine(speed, amount) { - const formattedSpeed = new Intl.NumberFormat({ + const formattedSpeed = new Intl.NumberFormat( 'en-US', { style: 'unit', unit: 'mile-per-hour' } - }).format(speed) + ).format(speed) - const formattedAmount = new Intl.NumberFormat({ + const formattedAmount = new Intl.NumberFormat( 'en-US', { style: 'currency', currency: 'USD' } - }).format(amount) + ).format(amount) return `The driver drove ${formattedSpeed} and has to pay ${formattedAmount}` } From a49f648e89b776b776d15dda8c856472b0b91c2c Mon Sep 17 00:00:00 2001 From: Danah Date: Wed, 11 Aug 2021 21:09:03 +0900 Subject: [PATCH 088/193] Translation 127 - 136 to ko-KR --- ko-KR/README-ko_KR.md | 364 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 364 insertions(+) diff --git a/ko-KR/README-ko_KR.md b/ko-KR/README-ko_KR.md index 7ca39976..65990057 100644 --- a/ko-KR/README-ko_KR.md +++ b/ko-KR/README-ko_KR.md @@ -4078,3 +4078,367 @@ console.log(getFine(130, 300));

+--- + +###### 127. 무엇이 출력 될까요? + +```javascript +const spookyItems = ['👻', '🎃', '🕸']; +({ item: spookyItems[3] } = { item: '💀' }); + +console.log(spookyItems); +``` + +- A: `["👻", "🎃", "🕸"]` +- B: `["👻", "🎃", "🕸", "💀"]` +- C: `["👻", "🎃", "🕸", { item: "💀" }]` +- D: `["👻", "🎃", "🕸", "[object Object]"]` + +
+

+ +#### 답: B + +객체를 분해함으로써, 오른쪽 객체의 값을 꺼내고, 꺼낸 값은 왼쪽 객체에 같은 속성 이름의 값으로 할당 할 수 있어요. 이 경우, 값 "💀"을 `spookyItems[3]`에 할당했어요. 이건 `spookyItems`을 수정, 즉 배열에 "💀"을 추가한다는 의미예요. `spookyItems`을 출력하면, `["👻", "🎃", "🕸", "💀"]`이 출력ㅗ대요. + +

+
+ +--- + +###### 128. 무엇이 출력 될까요? + +```javascript +const name = 'Lydia Hallie'; +const age = 21; + +console.log(Number.isNaN(name)); +console.log(Number.isNaN(age)); + +console.log(isNaN(name)); +console.log(isNaN(age)); +``` + +- A: `true` `false` `true` `false` +- B: `true` `false` `false` `false` +- C: `false` `false` `true` `false` +- D: `false` `true` `false` `true` + +
+

+ +#### 답: C + +`Number.isNaN` 메소드를 사용하면, 전달한 값이 _숫자 값_ 그리고 `NaN`인지 확인 할 수 있어요. `name`은 숫자 값이 아니에요, 따라서 `Number.isNaN(name)` 은 `false`을 반환해요. `age`는 숫자 값이지만, `NaN`은 아니에요, 따라서 `Number.isNaN(age)`은 `false`을 반환해요. + +`isNaN` 메소드를 사용하면, 전달한 값이 숫자가 아닌지 확인할 수 있어요. `name`은 숫자가 아니에요, 따라서 `isNaN(name)`은 true를 반환해요. `age`은 숫자이고, 따라서 `isNaN(age)`은 `false`을 반환해요. + +

+
+ +--- + +###### 129. 무엇이 출력 될까요? + +```javascript +const randomValue = 21; + +function getInfo() { + console.log(typeof randomValue); + const randomValue = 'Lydia Hallie'; +} + +getInfo(); +``` + +- A: `"number"` +- B: `"string"` +- C: `undefined` +- D: `ReferenceError` + +
+

+ +#### 답: D + +`const` 키워드를 사용해 선언된 변수는 초기화 되기 전에 참조 할 수 없어요: 이건 _일시적 사각지대_ 라고 불려요. `getInfo`힘수에서, 변수 `randomValue`는 함수 `getInfo`의 스코프 안에 있어요. `typeof randomValue`의 값을 출력하고 싶은 줄에서, 변수 `randomValue`는 아직 초기화 되지 않았어요: `ReferenceError`가 던져져요! 변수 `randomValue`를 함수 `getInfo`안에 선언했기 때문에 엔진은 스코프 체인 아래로 내려가지 않아요. + +

+
+ +--- + +###### 130. 무엇이 출력 될까요? + +```javascript +const myPromise = Promise.resolve('Woah some cool data'); + +(async () => { + try { + console.log(await myPromise); + } catch { + throw new Error(`Oops didn't work`); + } finally { + console.log('Oh finally!'); + } +})(); +``` + +- A: `Woah some cool data` +- B: `Oh finally!` +- C: `Woah some cool data` `Oh finally!` +- D: `Oops didn't work` `Oh finally!` + +
+

+ +#### 답: C + +`try` 블록에서, `myPromise`의 awaited 값을 출력하고 있어요: `"Woah some cool data"`. `try` 블록에서 오류가 없기 때문에, `catch` 블록 안의 코드는 실행되지 않아요. `finally` 블록 안의 코드는 _항상_ 실행되고, `"Oh finally!"`가 출력돼요. + +

+
+ +--- + +###### 131. 무엇이 출력 될까요? + +```javascript +const emojis = ['🥑', ['✨', '✨', ['🍕', '🍕']]]; + +console.log(emojis.flat(1)); +``` + +- A: `['🥑', ['✨', '✨', ['🍕', '🍕']]]` +- B: `['🥑', '✨', '✨', ['🍕', '🍕']]` +- C: `['🥑', ['✨', '✨', '🍕', '🍕']]` +- D: `['🥑', '✨', '✨', '🍕', '🍕']` + +
+

+ +#### 답: B + +`flat`를 사용하면, 새로운 평평한 배열을 만들어요. 평평한 배열의 깊이는 전달한 값에 달려있어요. 이 경우, 값 `1`(기본 값)을 전달했고,, 1번째 깊이에 있는 배열만 연결된다는 뜻이에요. 이 경우에선 `['🥑']` 그리고 `['✨', '✨', ['🍕', '🍕']]`. 두 배열을 연결하면 `['🥑', '✨', '✨', ['🍕', '🍕']]`가 돼요. + +

+
+ +--- + +###### 132. 무엇이 출력 될까요? + +```javascript +class Counter { + constructor() { + this.count = 0; + } + + increment() { + this.count++; + } +} + +const counterOne = new Counter(); +counterOne.increment(); +counterOne.increment(); + +const counterTwo = counterOne; +counterTwo.increment(); + +console.log(counterOne.count); +``` + +- A: `0` +- B: `1` +- C: `2` +- D: `3` + +
+

+ +#### 답: D + +`counterOne`는 클래스 `Counter`의 인스턴스예요. counter 클래스는 생성자 안에 속성 `count`와 `increment` 메소드를 포함해요. 우선, `counterOne.increment()`를 사용해 `increment` 메소드를 두 번 호출해요. 현재, `counterOne.count`는 `2`예요. + + + +그리고서, 새로운 변수 `counterTwo`를 만들고, `counterOne`과 동일하게 설정해요. 객체는 참조로 상호작용 하므로, `counterOne`을 가리키는 같은 메모리 영역에 새로운 참조를 만들었어요. 메모리의 같은 장소에 존재 하므로, 참조를 가진 `counterTwo` 객체의 모든 변화는, `counterOne` 객체에도 적용돼요. 지금, `counterTwo.count`은 `2`예요. + +`count`를 `3`으로 만드는 `counterTwo.increment()`를 호출해요. 그리고서, `counterOne`의 count를 출력하고, `3`이 출력돼요. + + + +

+
+ +--- + +###### 133. 무엇이 출력 될까요? + +```javascript +const myPromise = Promise.resolve(Promise.resolve('Promise!')); + +function funcOne() { + myPromise.then((res) => res).then((res) => console.log(res)); + setTimeout(() => console.log('Timeout!'), 0); + console.log('Last line!'); +} + +async function funcTwo() { + const res = await myPromise; + console.log(await res); + setTimeout(() => console.log('Timeout!'), 0); + console.log('Last line!'); +} + +funcOne(); +funcTwo(); +``` + +- A: `Promise! Last line! Promise! Last line! Last line! Promise!` +- B: `Last line! Timeout! Promise! Last line! Timeout! Promise!` +- C: `Promise! Last line! Last line! Promise! Timeout! Timeout!` +- D: `Last line! Promise! Promise! Last line! Timeout! Timeout!` + +
+

+ +#### 답: D + +우선, `funcOne`를 호출했어요. `funcOne`의 첫 번째 줄에서, _비동기_ 작업 `myPromise` 프로미스를 불러요. 엔진이 프로미스를 처리하느라고 바쁜 와중에도, 계속해서 `funcOne` 함수를 실행해요. 다음 줄은 _비동기_ `setTimeout` 함수이고, 콜백을 Web API로 보내요. (내가 작성한 이벤트 루프에 대한 글 보기 여기.) + +프라미스와 타임아웃 모두 비동기 작업이고, 함수는 프라미스 함수와 `setTimeout` 콜백을 처리하느라고 바쁜 와중에도 계속해서 실행해요. 이건 비동기 작업이 아닌 `Last line!`가 첫 번째로 출력된다는 걸 의미해요. 이건 `funcOne` 함수의 마지막 줄에 있고, 프라미스가 resolved 되어, `Promise!`가 출력돼요. 그러나, `funcTwo()`를 호출 했기 때문에, 콜 스택은 비어있지 않고, `setTimeout` 콜백 함수는 아직 콜 스택에 추가할 수 없어요. + +`funcTwo`에서, 우선 myPromise 프라미스를 _기다려요_. `await`키워드를 사용해서, 프라미스가 resolved (or rejected) 될 때까지 함수의 실행을 멈췄어요. 그리고서, `res`의 값을 기다렸다가 출력해요. (프라미스 자체가 프라미스를 반환하기 때문에). 이건 `Promise!`을 출력해요. + +다음 줄은 _비동기_ `setTimeout` 함수로, 콜백을 Web API로 보내요. + +`funcTwo`의 마지막 줄에서, `Last line!`가 콘솔에 출력돼요. 지금, `funcTwo`가 콜 스택에서 제거되었기 때문에, 콜 스택은 비어있어요. 대기열에서 대기 중인 콜백은(`funcOne`에서의 (`() => console.log("Timeout!")`, 그리고 `funcTwo`에서의 `() => console.log("Timeout!")`) 호출 스택에 하나씩 추가되어요. 첫 번째 콜백은 `Timeout!`을 출력하고, 스택에서 제거돼요. 그리고서, 두 번째 콜백은 `Timeout!`을 출력하고, 스택에서 제거돼요. 이건 `Last line! Promise! Promise! Last line! Timeout! Timeout!`을 출력해요. + +

+
+ +--- + +###### 134. `index.js`에서 `sum.js` 안에 있는 `sum`을 호출 하려면 어떻게 해야하나요? + +```javascript +// sum.js +export default function sum(x) { + return x + x; +} + +// index.js +import * as sum from './sum'; +``` + +- A: `sum(4)` +- B: `sum.sum(4)` +- C: `sum.default(4)` +- D: Default aren't imported with `*`, only named exports + +
+

+ +#### 답: C + +별표 `*`를 사용하면, 파일에서 내보낸 모든 값(기본값과 명명된 것 모두)을 가져와요. 만약 다음 파일을 가지고 있다면: + +```javascript +// info.js +export const name = 'Lydia'; +export const age = 21; +export default 'I love JavaScript'; + +// index.js +import * as info from './info'; +console.log(info); +``` + +아래와 같이 출력될 거예요: + +```javascript +{ + default: "I love JavaScript", + name: "Lydia", + age: 21 +} +``` + +`sum`을 예로 들자면, 가져온 `sum`의 값은 다음처럼 보인다는 의미에요: + +```javascript +{ default: function sum(x) { return x + x } } +``` + +`sum.default`을 불러 함수를 호출 할 수 있어요. + +

+
+ +--- + +###### 135. 무엇이 출력 될까요? + +```javascript +const handler = { + set: () => console.log('Added a new property!'), + get: () => console.log('Accessed a property!'), +}; + +const person = new Proxy({}, handler); + +person.name = 'Lydia'; +person.name; +``` + +- A: `Added a new property!` +- B: `Accessed a property!` +- C: `Added a new property!` `Accessed a property!` +- D: Nothing gets logged + +
+

+ +#### 답: C + +Proxy 객체를 사용하면, 두번째 인수로 전달 한 객체에 사용자 지정 동작을 추가 할 수 있어요. 이 경우엔, 두 개의 속성을 가진 `handler` 객체를 전달 했어요: `set` 과 `get` 속성 값을 _설정_ 할 때마다 `set`은 호출되고, `get`은 속성 값을 _얻을_ (접근)때 마다 호출되어요. + +첫 번째 인수는 빈 객체 `{}`고, `person`의 값이에요. 이 객체에 객체 `handler`의 사용자 지정 동작을 추가했어요. `person` 객체에 속성을 추가하면, `set` 이 호출 돼요. `person` 객체의 속성에 접근하면, `get` 이 호출 돼요. + +우선, 프록시 객체에 새로운 속성 `name`을 추가했어요(`person.name = "Lydia"`). `set`이 호출되고, `"Added a new property!"`을 출력 해요. + +그리고서, 프록시 객체의 속성 값에 접근하고, handler 객체의 속성 `get` 이 호출 돼요. `"Accessed a property!"`을 출력 해요. + +

+
+ +--- + +###### 136. 다음 중 어느 것이 `person` 객체를 수정 할 수 있을까요? + +```javascript +const person = { name: 'Lydia Hallie' }; + +Object.seal(person); +``` + +- A: `person.name = "Evan Bacon"` +- B: `person.age = 21` +- C: `delete person.name` +- D: `Object.assign(person, { age: 21 })` + +
+

+ +#### 답: A + +`Object.seal`을 사용하면, 새로운 속성이 _추가_ 되거나, 혹은 존재하는 속성이 _제거_ 되는 것을 막을 수 있어요. + +그러나, 여전히 존재하는 속성의 값을 수정 할 수 있어요. + +

+
+ +--- From 930e430c671e8d9c0b229866e3e6bc02943add70 Mon Sep 17 00:00:00 2001 From: Danah Date: Sun, 15 Aug 2021 15:03:44 +0900 Subject: [PATCH 089/193] fix variable name(141 question) --- README.md | 2 +- id-ID/README.md | 2 +- nl-NL/README.md | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index f0921a95..0a627036 100644 --- a/README.md +++ b/README.md @@ -4621,7 +4621,7 @@ console.log(person.hobbies); The `addHobby` function receives two arguments, `hobby` and `hobbies` with the default value of the `hobbies` array on the `person` object. -First, we invoke the `addHobby` function, and pass `"running"` as the value for `hobby` and an empty array as the value for `hobbies`. Since we pass an empty array as the value for `y`, `"running"` gets added to this empty array. +First, we invoke the `addHobby` function, and pass `"running"` as the value for `hobby` and an empty array as the value for `hobbies`. Since we pass an empty array as the value for `hobbies`, `"running"` gets added to this empty array. Then, we invoke the `addHobby` function, and pass `"dancing"` as the value for `hobby`. We didn't pass a value for `hobbies`, so it gets the default value, the `hobbies` property on the `person` object. We push the hobby `dancing` to the `person.hobbies` array. diff --git a/id-ID/README.md b/id-ID/README.md index 91c00382..21332103 100644 --- a/id-ID/README.md +++ b/id-ID/README.md @@ -4639,7 +4639,7 @@ console.log(person.hobbies); The `addHobby` function receives two arguments, `hobby` and `hobbies` with the default value of the `hobbies` array on the `person` object. -First, we invoke the `addHobby` function, and pass `"running"` as the value for `hobby` and an empty array as the value for `hobbies`. Since we pass an empty array as the value for `y`, `"running"` gets added to this empty array. +First, we invoke the `addHobby` function, and pass `"running"` as the value for `hobby` and an empty array as the value for `hobbies`. Since we pass an empty array as the value for `hobbies`, `"running"` gets added to this empty array. Then, we invoke the `addHobby` function, and pass `"dancing"` as the value for `hobby`. We didn't pass a value for `hobbies`, so it gets the default value, the `hobbies` property on the `person` object. We push the hobby `dancing` to the `person.hobbies` array. diff --git a/nl-NL/README.md b/nl-NL/README.md index 68f1527f..34193a0e 100644 --- a/nl-NL/README.md +++ b/nl-NL/README.md @@ -4613,7 +4613,7 @@ console.log(person.hobbies); De functie `addHobby` ontvangt twee arguemnten, `hobby` en `hobbies` met als standaard waarde de waarde van de array `hobbies` op het object `person`. -Eerst roepen we de functie `addHobby` aan en geven `"running"` mee als de waarde voor `hobby`, en een lege array als de waarde voor `hobbies`. Omdat we een lege array meegeven als de waarde voor `y` wordt `"running"` toegevoegd aan deze lege array. +Eerst roepen we de functie `addHobby` aan en geven `"running"` mee als de waarde voor `hobby`, en een lege array als de waarde voor `hobbies`. Omdat we een lege array meegeven als de waarde voor `hobbies` wordt `"running"` toegevoegd aan deze lege array. Daarna roepen we de functie `addHobby` aan en geven `"dancing"` mee als de waarde voor `hobby`. We gaven geen waarde mee voor `hobbies` dus krijgt het de standaard waarde, de propertie `hobbies` op het object `person`. We pushen daar de hobby `dancing` naar de array `person.hobbies`. From 6bb9aa3a34945014f13947c418aaf72c8fbb36ad Mon Sep 17 00:00:00 2001 From: Danah Date: Sun, 15 Aug 2021 17:44:59 +0900 Subject: [PATCH 090/193] Translation 137 - 155 to ko-KR --- ko-KR/README-ko_KR.md | 665 +++++++++++++++++++++++++++++++++++++++++- 1 file changed, 660 insertions(+), 5 deletions(-) diff --git a/ko-KR/README-ko_KR.md b/ko-KR/README-ko_KR.md index 65990057..04349860 100644 --- a/ko-KR/README-ko_KR.md +++ b/ko-KR/README-ko_KR.md @@ -1067,7 +1067,7 @@ console.log(typeof sayHi()); --- -###### 35. 이 값 중 어느 것이 거짓 같은 값 일까요? +###### 35. 이 값 중 어느 것이 거짓 같은 값일까요? ```javascript 0; @@ -2415,7 +2415,7 @@ console.log(name); --- -###### 77. 이것은 순수 함수 일까요? +###### 77. 이것은 순수 함수일까요? ```javascript function sum(a, b) { @@ -2717,7 +2717,7 @@ fetch('https://www.website.com/api/user/1') --- -###### 86. `true`를 인수로 전달 할 수 없도록 주어졌을 때, `hasName`을 `true`로 설정할 수 있는 방법은 어느 것 일까요? +###### 86. `true`를 인수로 전달 할 수 없도록 주어졌을 때, `hasName`을 `true`로 설정할 수 있는 방법은 어느 것일까요? ```javascript function getName(name) { @@ -3725,7 +3725,7 @@ myMap.get(() => 'greeting'); 키/값을 쌍으로 추가할 때 `set` 메소드를 사용하면, 키는 `set` 함수로 전달 된 첫 번째 인수의 값이 되고, 값은 `set` 함수로 전달된 두 번째 인수의 값이 될 거에요. 이 경우에 키는 _함수_ `() => 'greeting'`이고, 값은 `'Hello world'`예요. `myMap`은 이제 `{ () => 'greeting' => 'Hello world!' }` 예요. 1은 틀렸어요, 키는 `'greeting'`가 아니라 `() => 'greeting'`이기 때문이에요. -3은 틀렸어요, `get`메소드에 새로 생성한 함수를 파라미터로 전달 했기 때문이에요. 객체는 *참조*로 상호작용해요. 함수는 객체이기 때문에, 두 함수가 같다고 하더라도 절대로 동일하지 않아요: 메모리 안에 다른 장소의 참조를 가지고 있어요. +3은 틀렸어요, `get`메소드에 새로 생성한 함수를 파라미터로 전달 했기 때문이에요. 객체는 _참조_ 로 상호작용해요. 함수는 객체이기 때문에, 두 함수가 같다고 하더라도 절대로 동일하지 않아요: 메모리 안에 다른 장소의 참조를 가지고 있어요.

@@ -4306,7 +4306,7 @@ funcTwo(); #### 답: D -우선, `funcOne`를 호출했어요. `funcOne`의 첫 번째 줄에서, _비동기_ 작업 `myPromise` 프로미스를 불러요. 엔진이 프로미스를 처리하느라고 바쁜 와중에도, 계속해서 `funcOne` 함수를 실행해요. 다음 줄은 _비동기_ `setTimeout` 함수이고, 콜백을 Web API로 보내요. (내가 작성한 이벤트 루프에 대한 글 보기 여기.) +우선, `funcOne`를 호출했어요. `funcOne`의 첫 번째 줄에서, _비동기_ 작업 `myPromise` 프로미스를 불러요. 엔진이 프로미스를 처리하느라고 바쁜 와중에도, 계속해서 `funcOne` 함수를 실행해요. 다음 줄은 _비동기_ `setTimeout` 함수이고, 콜백을 Web API로 보내요. (내가 작성한 이벤트 루프에 대한 글 보기 여기.) 프라미스와 타임아웃 모두 비동기 작업이고, 함수는 프라미스 함수와 `setTimeout` 콜백을 처리하느라고 바쁜 와중에도 계속해서 실행해요. 이건 비동기 작업이 아닌 `Last line!`가 첫 번째로 출력된다는 걸 의미해요. 이건 `funcOne` 함수의 마지막 줄에 있고, 프라미스가 resolved 되어, `Promise!`가 출력돼요. 그러나, `funcTwo()`를 호출 했기 때문에, 콜 스택은 비어있지 않고, `setTimeout` 콜백 함수는 아직 콜 스택에 추가할 수 없어요. @@ -4442,3 +4442,658 @@ Object.seal(person);
--- + +###### 137. 다음 중 어느 것이 `person` 객체를 수정 할 수 있을까요? + +```javascript +const person = { + name: 'Lydia Hallie', + address: { + street: '100 Main St', + }, +}; + +Object.freeze(person); +``` + +- A: `person.name = "Evan Bacon"` +- B: `delete person.address` +- C: `person.address.street = "101 Main St"` +- D: `person.pet = { name: "Mara" }` + +
+

+ +#### 답: C + +`Object.freeze` 메소드는 객체를 _얼려요_ . 속성을 추가, 수정, 제거 할 수 없어요. + +하지만, 객체를 _얕은_ 수준으로만 얼리고, 이건 객체의 _직접적인_ 속성만 얼려진다는 의미예요. 속성이 `address` 와 같은 객체인 경우, 객체의 속성은 얼려지지 않고, 수정될 수 있어요. + +

+
+ +--- + +###### 138. 무엇이 출력 될까요? + +```javascript +const add = (x) => x + x; + +function myFunc(num = 2, value = add(num)) { + console.log(num, value); +} + +myFunc(); +myFunc(3); +``` + +- A: `2` `4` and `3` `6` +- B: `2` `NaN` and `3` `NaN` +- C: `2` `Error` and `3` `6` +- D: `2` `4` and `3` `Error` + +
+

+ +#### 답: A + +우선, `myFunc()` 를 어떤 인수도 전달하지 않고 호출했어요. 인수를 전달하지 않았기 때문에, `num` 와 `value` 는 그들의 기본값을 가져요: num 는 `2`, `value` 함수 `add`에서 반환된 값. `add` 함수에서, 값이 `2`인 `num`를 인수로 전달했어요. `add`는 `value`의 값인 `4`를 반환해요. + +그리고서, `myFunc(3)`를 호출하고 인수 `num`의 값으로 값 `3`을 전달했어요. `value` 값은 전달하지 않았어요. 인수 `value`에 값을 전달하지 않았기 때문에, 기본값을 가져요: 함수 `add`에서 반환된 값. `add`에서, 값 `3`을 가진 `num`을 전달해요. `add`는 `value`의 값으로 `6`을 반환해요. + +

+
+ +--- + +###### 139. 무엇이 출력 될까요? + +```javascript +class Counter { + #number = 10; + + increment() { + this.#number++; + } + + getNum() { + return this.#number; + } +} + +const counter = new Counter(); +counter.increment(); + +console.log(counter.#number); +``` + +- A: `10` +- B: `11` +- C: `undefined` +- D: `SyntaxError` + +
+

+ +#### 답: D + +ES2020에서, `#`을 사용한 private 변수를 추가 할 수 있어요. 클래스 외부에서 private 변수에 접근 할 수 없어요. `counter.#number`을 출력하려고 할 때, SyntaxError가 던져져요: `Counter` 클래스 외부에서 private 변수에 접근 할 수 없어요! + +

+
+ +--- + +###### 140. 무엇이 빠졌을까요? + +```javascript +const teams = [ + { name: 'Team 1', members: ['Paul', 'Lisa'] }, + { name: 'Team 2', members: ['Laura', 'Tim'] }, +]; + +function* getMembers(members) { + for (let i = 0; i < members.length; i++) { + yield members[i]; + } +} + +function* getTeams(teams) { + for (let i = 0; i < teams.length; i++) { + // ✨ SOMETHING IS MISSING HERE ✨ + } +} + +const obj = getTeams(teams); +obj.next(); // { value: "Paul", done: false } +obj.next(); // { value: "Lisa", done: false } +``` + +- A: `yield getMembers(teams[i].members)` +- B: `yield* getMembers(teams[i].members)` +- C: `return getMembers(teams[i].members)` +- D: `return yield getMembers(teams[i].members)` + +
+

+ +#### 답: B + +`teams` 배열의 `members`의 각 요소를 계속해서 반복하기 위해선, `teams[i].members`를 제너레이터 함수 `getMembers`에 전달해야해요. 제너레이터 함수는 제너리에터 객체를 리턴해요. 제너레이터 객체의 각 요소를 계속해서 반복 하기 위해선, `yield*`를 사용해야 해요. + +`yield`, `return yield` 또는 `return`를 쓰면, 모든 제너레이터 함수는 첫번째로 호출한 `next` 메소드가 반환한 값을 가져요. + +

+
+ +--- + +###### 141. 무엇이 출력 될까요? + +```javascript +const person = { + name: 'Lydia Hallie', + hobbies: ['coding'], +}; + +function addHobby(hobby, hobbies = person.hobbies) { + hobbies.push(hobby); + return hobbies; +} + +addHobby('running', []); +addHobby('dancing'); +addHobby('baking', person.hobbies); + +console.log(person.hobbies); +``` + +- A: `["coding"]` +- B: `["coding", "dancing"]` +- C: `["coding", "dancing", "baking"]` +- D: `["coding", "running", "dancing", "baking"]` + +
+

+ +#### 답: C + +`addHobby` 함수는 인수 두 개 `hobby` 와 `person` 객체의 배열 `hobbies`의 값을 기본값으로 가진 `hobbies`를 받아요. + +우선, `addHobby` 함수를 호출하고, `hobby`의 값으로 `"running"`을 그리고 `hobbies`의 값으로 빈 배열을 전달해요. `hobbies`의 값으로 빈 배열을 전달했기 때문에, `"running"`은 빈 배열에 추가돼요. + +그리고서, `addHobby` 함수를 호출하고, `hobby`의 값으로 `"dancing"`를 전달해요. `hobbies`에 값을 전달하지 않았고, `person` 객체의 속성 `hobbies`을 기본값으로 가져요. 배열 `person.hobbies`에 `dancing`를 추가해요. + +마지막으로, `addHobby` 함수를 호출해, `hobby`의 값으로 `"baking"`를 전달하고, `hobbies`의 값으로 배열 `person.hobbies`을 전달해요. 배열 `person.hobbies`에 `baking`을 추가해요. + +`dancing` 과 `baking`을 추가한 후, `person.hobbies`의 값은 `["coding", "dancing", "baking"]`예요. + +

+
+ +--- + +###### 142. 무엇이 출력 될까요? + +```javascript +class Bird { + constructor() { + console.log("I'm a bird. 🦢"); + } +} + +class Flamingo extends Bird { + constructor() { + console.log("I'm pink. 🌸"); + super(); + } +} + +const pet = new Flamingo(); +``` + +- A: `I'm pink. 🌸` +- B: `I'm pink. 🌸` `I'm a bird. 🦢` +- C: `I'm a bird. 🦢` `I'm pink. 🌸` +- D: Nothing, we didn't call any method + +
+

+ +#### 답: B + +`Flamingo` 클래스의 인스턴스인 변수 `pet` 생성했어요. 인스턴스를 인스턴스화 할 때, `Flamingo`의 `constructor`를 불러요. 우선, `"I'm pink. 🌸"`가 출력되고, 그 후에 `super()`를 불러요. `super()`는 부모 클래스 `Bird`의 constructor를 불러요. `Bird`의 constructor 를 불러, `"I'm a bird. 🦢"`가 출력돼요. + +

+
+ +--- + +###### 143. 다음 중 어느 것의 결과가 오류일까요? + +```javascript +const emojis = ['🎄', '🎅🏼', '🎁', '⭐']; + +/* 1 */ emojis.push('🦌'); +/* 2 */ emojis.splice(0, 2); +/* 3 */ emojis = [...emojis, '🥂']; +/* 4 */ emojis.length = 0; +``` + +- A: 1 +- B: 1 and 2 +- C: 3 and 4 +- D: 3 + +
+

+ +#### 답: D + +`const` 키워드는 단순히 변수의 값을 _재선언_ 할 수 없고, _읽기만_ 가능하다는 의미예요. 하지만, 값 자체가 불변하는 건 아니에요. 배열 `emojis`의 속성을 수정할 수 있는데, 예를 들자면 새로운 값을 추가하거나, 원본 배열 자체를 수정(splice)하거나, 배열의 길이를 0으로 설정 할 수 있어요. + +

+
+ +--- + +###### 144. `person`에 무엇을 추가해야 `[...person]`의 결과로 `["Lydia Hallie", 21]`를 얻을 수 있을까요? + +```javascript +const person = { + name: "Lydia Hallie", + age: 21 +} + +[...person] // ["Lydia Hallie", 21] +``` + +- A: 객체는 기본적으로 반복 가능 하므로, 아무것도 하지 않아요. +- B: `*[Symbol.iterator]() { for (let x in this) yield* this[x] }` +- C: `*[Symbol.iterator]() { yield* Object.values(this) }` +- D: `*[Symbol.iterator]() { for (let x in this) yield this }` + +
+

+ +#### 답: C + +객체는 기본적으로 반복 불가능해요. 반복 가능한 객체는 iterator protocol이 제공되면 반복 가능해요. 제너레이터 함수 `*[Symbol.iterator]() {}`을 만드는 제너레이터 객체를 반환하는 iterator symbol `[Symbol.iterator]`을 수동으로 추가 할 수 있어요. 배열 `["Lydia Hallie", 21]`을 반환 하려면 제너레이터 함수는 `person` 객체의 `Object.values`를 yield 해야해요: `yield* Object.values(this)`. + +

+
+ +--- + +###### 145. 무엇이 출력 될까요? + +```javascript +let count = 0; +const nums = [0, 1, 2, 3]; + +nums.forEach((num) => { + if (num) count += 1; +}); + +console.log(count); +``` + +- A: 1 +- B: 2 +- C: 3 +- D: 4 + +
+

+ +#### 답: C + +`forEach` 순환에 포함 된 `if` 조건문은 `num`의 값이 진짜 같은 값인지 또는 가짜 같은 값인지 확인해요. `nums`배열의 첫 번째 값은 거짓 같은 값 `0`이고, `if` 조건문의 코드 블럭은 실행되지 않아요. `count` 는 오직 `nums` 배열의 다른 숫자 3개에 대해서만 증가해요. `1`, `2` 그리고 `3`. `count`는 3번 동안 `1` 씩 증가하고, `count`의 값은 `3`이에요. + +

+
+ +--- + +###### 146. 무엇이 출력 될까요? + +```javascript +function getFruit(fruits) { + console.log(fruits?.[1]?.[1]); +} + +getFruit([['🍊', '🍌'], ['🍍']]); +getFruit(); +getFruit([['🍍'], ['🍊', '🍌']]); +``` + +- A: `null`, `undefined`, 🍌 +- B: `[]`, `null`, 🍌 +- C: `[]`, `[]`, 🍌 +- D: `undefined`, `undefined`, 🍌 + +
+

+ +#### 답: D + +`?`는 객체 내에서 더 깊이 중첩된 속성에 접근하는 것을 선택적으로 허용해요. `fruits`배열의 인덱스 `1`에 있는 하위 배열의 인덱스 `1`의 아이템을 출력하려해요. `fruits`배열의 인덱스 `1`에 하위 배열이 존재하지 않는다면, 간단히 `undefined`를 반환할 거예요. `fruits` 배열의 인덱스 `1`에 하위배열이 있지만, 하위 배열에 인덱스 `1` 의 아이템이 없다면, 그것 역시 `undefined`를 반환해요. + +우선, `[['🍊', '🍌'], ['🍍']]`의 하위 배열의 두 번째 아이템 `['🍍']`을 출력해요 . 하위 배열은 아이템 하나만 가지고 있고, 이건 인덱스 `1`에 대한 아이템을 갖고 있지 않다는 의미로 `undefined`를 반환해요. + +그리고서, 인수에 어떤 값도 전달하지 않은 `getFruits` 함수를 호출 하고, `fruits`은 기본값으로 값 `undefined`을 가져요. `fruits`의 인덱스 `1`의 아이템을 선택적으로 연결(conditionally chaining)하기 때문에, 인덱스 `1`에 아이템이 존재하지 않아 `undefined`를 반환해요. + +마지막으로, `['🍍'], ['🍊', '🍌']`의 하위 배열 `['🍊', '🍌']`의 두번째 아이템을 출력하려고 해요. 하위 배열의 인덱스 `1`의 아이템인 `🍌`이 출력돼요. + +

+
+ +--- + +###### 147. 무엇이 출력 될까요? + +```javascript +class Calc { + constructor() { + this.count = 0 + } + + increase() { + this.count ++ + } +} + +const calc = new Calc() +new Calc().increase() + +console.log(calc.count) +``` + +- A: `0` +- B: `1` +- C: `undefined` +- D: `ReferenceError` + +
+

+ +#### 답: A + +변수 `calc`를 `Calc` 클래스의 새로운 인스턴스로 설정 했어요. 그리고서, 새로운 인스턴스 `Calc`를 인스턴스화 하고, 이 인스턴스의 `increase` 메소드를 호출 했어요. 속성 count은 `Calc` 클래스의 생성자 안에 있기 때문에 , 속성 count은 `Calc`의 프로토타입에 공유될 수 없어요. 인스턴스 calc이 가리키는 count의 값은 업데이트 되지 않고, count는 여전히 `0`예요. + +

+
+ +--- + +###### 148. 무엇이 출력 될까요? + +```javascript +const user = { + email: "e@mail.com", + password: "12345" +} + +const updateUser = ({ email, password }) => { + if (email) { + Object.assign(user, { email }) + } + + if (password) { + user.password = password + } + + return user +} + +const updatedUser = updateUser({ email: "new@email.com" }) + +console.log(updatedUser === user) +``` + +- A: `false` +- B: `true` +- C: `TypeError` +- D: `ReferenceError` + +
+

+ +#### 답: B + +`updateUser` 함수는 값이 전달 되면 user의 속성 `email` 과 `password`의 값을 업데이트 하고, `user`객체를 반환해요. `updateUser` 함수의 반환된 값은 객체 `user` 이고, updateUser의 값은 `user`가 가리키는 `user` 객체의 참조와 같다는 의미예요. `updatedUser === user`는 `true`예요. + +

+
+ +--- + +###### 149. 무엇이 출력 될까요? + +```javascript +const fruit = ['🍌', '🍊', '🍎'] + +fruit.slice(0, 1) +fruit.splice(0, 1) +fruit.unshift('🍇') + +console.log(fruit) +``` + +- A: `['🍌', '🍊', '🍎']` +- B: `['🍊', '🍎']` +- C: `['🍇', '🍊', '🍎']` +- D: `['🍇', '🍌', '🍊', '🍎']` + +
+

+ +#### 답: C + +우선, fruit 배열에 `slice` 메소드를 호출해요. slice 메소드는 원본 배열을 수정하지 않지만, 배열에서 잘라낸(slice) 값을 반환해요: 바나나 이모지. +그리고서, fruit 배열에 `splice` 메소드를 호출해요. splice 메소드는 원본 배열을 수정하고, 이제 fruit 배열은 `['🍊', '🍎']`로 구성돼요. +마지막엔, `fruit` 배열에 `unshift` 메소드를 호출하고, 이 경우엔 제공된 값 ‘🍇’을 배열의 첫 번째 요소로 추가해 원본 배열을 수정해요. 이제 fruit 배열은 `['🍇', '🍊', '🍎']`로 구성돼요. + +

+
+ +--- + +###### 150. 무엇이 출력 될까요? + +```javascript +const animals = {}; +let dog = { emoji: '🐶' } +let cat = { emoji: '🐈' } + +animals[dog] = { ...dog, name: "Mara" } +animals[cat] = { ...cat, name: "Sara" } + +console.log(animals[dog]) +``` + +- A: `{ emoji: "🐶", name: "Mara" }` +- B: `{ emoji: "🐈", name: "Sara" }` +- C: `undefined` +- D: `ReferenceError` + +
+

+ +#### 답: B + +객체의 키는 문자열로 변환돼요. + +`dog`의 값은 객체 이므로, 사실 `animals[dog]`는 새로운 객체에 `"object Object"`라고 불리는 새로운 속성을 만든 걸 의미해요. 이제 `animals["object Object"]`는 `{ emoji: "🐶", name: "Mara"}`예요. + +`cat`도 물론 객체고, 사실 `animals[cat]`은 `animals[``"``object Object``"``]`을 새로운 속성 cat으로 덮어쓰고 있다는 것을 의미해요. + +`animals[dog]` 또는 `animals["object Object"]`(`dog` 객체를 문자열로 변환한 결과는 `"object Object"`)를 출력하면, `{ emoji: "🐈", name: "Sara" }`를 반환해요. + +

+
+ +--- + +###### 151. 무엇이 출력 될까요? + +```javascript +const user = { + email: "my@email.com", + updateEmail: email => { + this.email = email + } +} + +user.updateEmail("new@email.com") +console.log(user.email) +``` + +- A: `my@email.com` +- B: `new@email.com` +- C: `undefined` +- D: `ReferenceError` + +
+

+ +#### 답: A + +`updateEmail`함수는 화살표 함수로, `user`객체에 바인딩 되지 않았어요. `this`키워드는 `user`객체를 참조하지 않지만, 이 경우엔 전역 범위를 참조하고 있다는 의미예요. `user` 객체의 `email` 는 업데이트 되지 않아요. `user.email`을 출력할 때, `my@email.com`의 원래의 값이 반환되어요. + +

+
+ +--- + +###### 152. 무엇이 출력 될까요? + +```javascript +const promise1 = Promise.resolve('First') +const promise2 = Promise.resolve('Second') +const promise3 = Promise.reject('Third') +const promise4 = Promise.resolve('Fourth') + +const runPromises = async () => { + const res1 = await Promise.all([promise1, promise2]) + const res2 = await Promise.all([promise3, promise4]) + return [res1, res2] +} + +runPromises() + .then(res => console.log(res)) + .catch(err => console.log(err)) +``` + +- A: `[['First', 'Second'], ['Fourth']]` +- B: `[['First', 'Second'], ['Third', 'Fourth']]` +- C: `[['First', 'Second']]` +- D: `'Third'` + +
+

+ +#### 답: D + +`Promise.all` 메소드는 프로미스를 병렬로 실행해요. 만약 하나의 프로미스가 실패하면, `Promise.all` 메소드는 rejected 프로미스의 값을 가지고 _rejects_ 되어요. 이 경우, `promise3`는 값 `"Third"`과 함께 rejected 되었어요. `runPromises` 호출에 연결되어 있고 `runPromises` 함수 안에서 모든 에러를 잡은 `catch` 메소드에서 rejected 값을 잡아요. `promise3`가 이 값과 함께 rejected 되어 `"Third"`만 출력돼요. + +

+
+ +--- + +###### 153. 무엇이 `method`의 값이어야 `{ name: "Lydia", age: 22 }`를 출력할까요? + +```javascript +const keys = ["name", "age"] +const values = ["Lydia", 22] + +const method = /* ?? */ +Object[method](keys.map((_, i) => { + return [keys[i], values[i]] +})) // { name: "Lydia", age: 22 } +``` + +- A: `entries` +- B: `values` +- C: `fromEntries` +- D: `forEach` + +
+

+ +#### 답: C + +`fromEntries` 메소드는 2차원 배열을 객체로 변환해요. 각 하위 배열의 첫번 째 요소는 키가 될거고, 각 하위 배열의 요소의 두번째 요소는 값이 될거에요. 이 경우엔, keys배열에서 현재 인덱스의 아이템을 첫 번재 요소로, values의 배열에서 현재 인덱스의 아이템을 두번째 요소로 반환하는 `keys` 배열을 매핑해요. + +키와 값의 집합을 포함하고 있는 하위 배열을 만들었고, `{ name: "Lydia", age: 22 }`가 되어. + +

+
+ +--- + +###### 154. 무엇이 출력 될까요? + +```javascript +const createMember = ({ email, address = {}}) => { + const validEmail = /.+\@.+\..+/.test(email) + if (!validEmail) throw new Error("Valid email pls") + + return { + email, + address: address ? address : null + } +} + +const member = createMember({ email: "my@email.com" }) +console.log(member) +``` + +- A: `{ email: "my@email.com", address: null }` +- B: `{ email: "my@email.com" }` +- C: `{ email: "my@email.com", address: {} }` +- D: `{ email: "my@email.com", address: undefined }` + +
+

+ +#### 답: C + +`address`의 기본 값은 빈 객체 `{}`예요. 변수 `member`의 값을 `createMember` 함수에서 반환한 값으로 설정하고, address의 값을 전달하지 않았어요, address의 값은 빈 객체 `{}`가 기본 값이예요. 빈객체는 진짜 같은 값으로, 조건 `address ? address : null`에서 `true`를 반환한다는 의미예요. address의 값은 빈 객체 `{}`예요. + +

+
+ +--- + +###### 155. 무엇이 출력 될까요? + +```javascript +let randomValue = { name: "Lydia" } +randomValue = 23 + +if (!typeof randomValue === "string") { + console.log("It's not a string!") +} else { + console.log("Yay it's a string!") +} +``` + +- A: `It's not a string!` +- B: `Yay it's a string!` +- C: `TypeError` +- D: `undefined` + +
+

+ +#### 답: B + +`if`문 안에 조건은 `!typeof randomValue`값이 `"string"`와 같은지 여부를 확인해요. `!` 연산자는 값을 불리언 값으로 변환해요. 값이 진짜 같은 값이라면 반환될 값은 `false`가 될 거고, 만약 값이 가짜 같은 값이라면 반환될 값은 `true`가 될 거예요. 이 경우에서, `typeof randomValue`의 반환된 값은 진짜 같은 값인 `"number"`이고, `!typeof randomValue`의 값은 불리언 값 `false`라는 의미예요. + +`!typeof randomValue === "string"`은 실제로 `false === "string"`을 확인하기 때문에 항상 false를 반환해요. 조건은 `false`을 반환 하므로, `else`문의 코드 블록이 실행되어 `Yay it's a string!`가 출력돼요. + +

+
From 7eba1f03c3a3c40520b18b322b9d0ba8fb1d3983 Mon Sep 17 00:00:00 2001 From: Hamir Mahal Date: Sun, 12 Sep 2021 07:44:15 -0700 Subject: [PATCH 091/193] remove two unnecessary "the"s to improve 132 --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index f0921a95..fc9043e1 100644 --- a/README.md +++ b/README.md @@ -4265,7 +4265,7 @@ console.log(counterOne.count); Then, we create a new variable `counterTwo`, and set it equal to `counterOne`. Since objects interact by reference, we're just creating a new reference to the same spot in memory that `counterOne` points to. Since it has the same spot in memory, any changes made to the object that `counterTwo` has a reference to, also apply to `counterOne`. Currently, `counterTwo.count` is `2`. -We invoke the `counterTwo.increment()`, which sets the `count` to `3`. Then, we log the count on `counterOne`, which logs `3`. +We invoke `counterTwo.increment()`, which sets `count` to `3`. Then, we log the count on `counterOne`, which logs `3`. From bd57ae1252524de5e65c1ef6c0da60a993f5c5f6 Mon Sep 17 00:00:00 2001 From: Ouhan You Date: Wed, 22 Sep 2021 15:48:03 -0400 Subject: [PATCH 092/193] README-zh_CN.md: fix the wrong answer for question 144 Fix #570 --- zh-CN/README-zh_CN.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/zh-CN/README-zh_CN.md b/zh-CN/README-zh_CN.md index f178684e..322e8117 100644 --- a/zh-CN/README-zh_CN.md +++ b/zh-CN/README-zh_CN.md @@ -4696,7 +4696,7 @@ const person = { - A: 不需要,对象默认就是可迭代的 - B: `*[Symbol.iterator]() { for (let x in this) yield* this[x] }` -- C: `*[Symbol.iterator]() { for (let x in this) yield* Object.values(this) }` +- C: `*[Symbol.iterator]() { yield* Object.values(this) }` - D: `*[Symbol.iterator]() { for (let x in this) yield this }`
答案 From 26c3e7776201ab8beced061ae1ff79fe35df8fe8 Mon Sep 17 00:00:00 2001 From: Ara Oladipo <67078991+Ara-O@users.noreply.github.com> Date: Thu, 21 Oct 2021 10:08:44 -0400 Subject: [PATCH 093/193] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index a915735e..38508295 100644 --- a/README.md +++ b/README.md @@ -2402,7 +2402,7 @@ console.log(name);
Answer

-#### Answer: A +#### Answer: C When we unpack the property `name` from the object on the right-hand side, we assign its value `"Lydia"` to a variable with the name `myName`. From 40f0f68e36562106c8363385d88e9d5583bfa64c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=83=AD=E5=87=AF?= <935267851@qq.com> Date: Thu, 28 Oct 2021 14:52:28 +0800 Subject: [PATCH 094/193] Update READNE-zh-CN question 35 --- zh-CN/README-zh_CN.md | 8 +++++--- zh-TW/README_zh-TW.md | 8 +++++--- 2 files changed, 10 insertions(+), 6 deletions(-) diff --git a/zh-CN/README-zh_CN.md b/zh-CN/README-zh_CN.md index 6e63fc39..f961a86c 100644 --- a/zh-CN/README-zh_CN.md +++ b/zh-CN/README-zh_CN.md @@ -1056,16 +1056,18 @@ undefined #### 答案: A -只有 6 种 [falsy](https://developer.mozilla.org/zh-CN/docs/Glossary/Falsy) 值: +只有 8 种 [falsy](https://developer.mozilla.org/zh-CN/docs/Glossary/Falsy) 值: - `undefined` - `null` - `NaN` -- `0` -- `''` (empty string) - `false` +- `''` (空字串) +- `0` +- `-0` +- `0n` (BigInt(0)) `Function` 构造函数, 比如 `new Number` 和 `new Boolean`,是 [truthy](https://developer.mozilla.org/zh-CN/docs/Glossary/Truthy)。 diff --git a/zh-TW/README_zh-TW.md b/zh-TW/README_zh-TW.md index 347488e3..c7e32ee7 100644 --- a/zh-TW/README_zh-TW.md +++ b/zh-TW/README_zh-TW.md @@ -1064,14 +1064,16 @@ undefined; #### 答案: A -只有六個值是 falsy +只有八個值是 falsy - `undefined` - `null` - `NaN` -- `0` -- `''` (空字串) - `false` +- `''` (空字串) +- `0` +- `-0` +- `0n` (BigInt(0)) 函式建構式(Function constructors) 如 `new Number` 和 `new Boolean` 都為 truthy。 From a1cf54bffb13e05d6176b99e1c2750011aa602b2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=83=AD=E5=87=AF?= <935267851@qq.com> Date: Thu, 28 Oct 2021 14:55:38 +0800 Subject: [PATCH 095/193] Update READNE-zh-CN question 35 --- zh-CN/README-zh_CN.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/zh-CN/README-zh_CN.md b/zh-CN/README-zh_CN.md index f961a86c..64b9716f 100644 --- a/zh-CN/README-zh_CN.md +++ b/zh-CN/README-zh_CN.md @@ -1064,7 +1064,7 @@ undefined - `null` - `NaN` - `false` -- `''` (空字串) +- `''` (empty string) - `0` - `-0` - `0n` (BigInt(0)) From 9013e099c6b2d198db124c2e12aae84b4af9b2b5 Mon Sep 17 00:00:00 2001 From: sheleoni <85994674+sheleoni@users.noreply.github.com> Date: Sat, 25 Dec 2021 13:58:42 +0800 Subject: [PATCH 096/193] URLs to different langauges MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Updated links to different languages (利用可能な言語リスト) by pointing to the correct parent directory - the URLs in the previous version leads to a 404 error as it did not go one level up in the directory (dot slashed is used instead of dot-dot-slash). Link problem exists in other languages and needs updating as well. --- ja-JA/README-ja_JA.md | 34 +++++++++++++++++----------------- 1 file changed, 17 insertions(+), 17 deletions(-) diff --git a/ja-JA/README-ja_JA.md b/ja-JA/README-ja_JA.md index 19a11ca6..7be25a8b 100644 --- a/ja-JA/README-ja_JA.md +++ b/ja-JA/README-ja_JA.md @@ -8,24 +8,24 @@ 利用可能な言語リスト: -- [🇸🇦 العربية](./ar-AR/README_AR.md) -- [🇪🇬 اللغة العامية](./ar-EG/README_ar-EG.md) -- [🇧🇦 Bosanski](./bs-BS/README-bs_BS.md) -- [🇩🇪 Deutsch](./de-DE/README.md) +- [🇸🇦 العربية](../ar-AR/README_AR.md) +- [🇪🇬 اللغة العامية](../ar-EG/README_ar-EG.md) +- [🇧🇦 Bosanski](../bs-BS/README-bs_BS.md) +- [🇩🇪 Deutsch](../de-DE/README.md) - [🇬🇧 English](../README.md) -- [🇪🇸 Español](./es-ES/README-ES.md) -- [🇫🇷 Français](./fr-FR/README_fr-FR.md) -- [🇮🇩 Indonesia](./id-ID/README.md) -- [🇰🇷 한국어](./ko-KR/README-ko_KR.md) -- [🇳🇱 Nederlands](./nl-NL/README.md) -- [🇧🇷 Português Brasil](./pt-BR/README_pt_BR.md) -- [🇷🇺 Русский](./ru-RU/README.md) -- [🇹🇭 ไทย](./th-TH/README-th_TH.md) -- [🇹🇷 Türkçe](./tr-TR/README-tr_TR.md) -- [🇺🇦 Українська мова](./uk-UA/README.md) -- [🇻🇳 Tiếng Việt](./vi-VI/README-vi.md) -- [🇨🇳 简体中文](./zh-CN/README-zh_CN.md) -- [🇹🇼 繁體中文](./zh-TW/README_zh-TW.md) +- [🇪🇸 Español](../es-ES/README-ES.md) +- [🇫🇷 Français](../fr-FR/README_fr-FR.md) +- [🇮🇩 Indonesia](../id-ID/README.md) +- [🇰🇷 한국어](../ko-KR/README-ko_KR.md) +- [🇳🇱 Nederlands](../nl-NL/README.md) +- [🇧🇷 Português Brasil](../pt-BR/README_pt_BR.md) +- [🇷🇺 Русский](../ru-RU/README.md) +- [🇹🇭 ไทย](../th-TH/README-th_TH.md) +- [🇹🇷 Türkçe](../tr-TR/README-tr_TR.md) +- [🇺🇦 Українська мова](../uk-UA/README.md) +- [🇻🇳 Tiếng Việt](../vi-VI/README-vi.md) +- [🇨🇳 简体中文](../zh-CN/README-zh_CN.md) +- [🇹🇼 繁體中文](../zh-TW/README_zh-TW.md) --- ###### 1. 何が出力されるでしょうか? From bc8824d16f61f09e8d89af882691cf4c2e5682e7 Mon Sep 17 00:00:00 2001 From: zks Date: Sat, 1 Jan 2022 15:48:14 +0800 Subject: [PATCH 097/193] Fix typo --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 38508295..4cfa2556 100644 --- a/README.md +++ b/README.md @@ -4931,7 +4931,7 @@ Object keys are converted to strings. Since the value of `dog` is an object, `animals[dog]` actually means that we’re creating a new property called `"object Object"` equal to the new object. `animals["object Object"]` is now equal to `{ emoji: "🐶", name: "Mara"}`. -`cat` is also an object, which means that `animals[cat]` actually means that we’re overwriting the value of `animals[``"``object Object``"``]` with the new cat properties. +`cat` is also an object, which means that `animals[cat]` actually means that we’re overwriting the value of `animals["object Object"]` with the new cat properties. Logging `animals[dog]`, or actually `animals["object Object"]` since converting the `dog` object to a string results `"object Object"`, returns the `{ emoji: "🐈", name: "Sara" }`. From 534a68a5353b708afeadea079fb3377ca8cec1d7 Mon Sep 17 00:00:00 2001 From: kaka59 <626723761@qq.com> Date: Mon, 17 Jan 2022 21:33:30 +0800 Subject: [PATCH 098/193] docs(zh_CN): fix the answer of question 98, 119. modify the translation of question 61. --- zh-CN/README-zh_CN.md | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/zh-CN/README-zh_CN.md b/zh-CN/README-zh_CN.md index 64b9716f..8b674e0f 100644 --- a/zh-CN/README-zh_CN.md +++ b/zh-CN/README-zh_CN.md @@ -1873,7 +1873,7 @@ console.log(Object.keys(person)); 通过`defineProperty`方法,我们可以给对象添加一个新属性,或者修改已经存在的属性。而我们使用`defineProperty`方法给对象添加了一个属性之后,属性默认为 _不可枚举(not enumerable)_. `Object.keys`方法仅返回对象中 _可枚举(enumerable)_ 的属性,因此只剩下了`"name"`. -用`defineProperty`方法添加的属性默认不可变。你可以通过`writable`, `configurable` 和 `enumerable`属性来改变这一行为。这样的话, 相比于自己添加的属性,`defineProperty`方法添加的属性有了更多的控制权。 +用`defineProperty`方法添加的属性默认不可变。你可以通过`writable`, `configurable` 和 `enumerable`属性来改变这一行为。这样,`defineProperty`方法可以让您更好地控制要添加到对象的属性。

@@ -3110,7 +3110,7 @@ console.log(getList(list)) console.log(getUser(user)) ``` -- A: `[1, [2, 3, 4]]` and `undefined` +- A: `[1, [2, 3, 4]]` and `SyntaxError` - B: `[1, [2, 3, 4]]` and `{ name: "Lydia", age: 21 }` - C: `[1, 2, 3, 4]` and `{ name: "Lydia", age: 21 }` - D: `Error` and `{ name: "Lydia", age: 21 }` @@ -3127,11 +3127,11 @@ console.log(getUser(user)) 使用剩余的参数`... y`,我们将所有剩余参数放在一个数组中。 在这种情况下,其余的参数是`2`,`3`和`4`。 `y`的值是一个数组,包含所有其余参数。 在这种情况下,`x`的值等于`1`,所以当我们打印`[x,y]`时,会打印`[1,[2,3,4]]`。 - `getUser`函数接收一个对象。对于箭头函数,如果只返回一个值,我们不必编写花括号。但是,如果您想从一个箭头函数返回一个对象,您必须在圆括号之间编写它,否则不会返回任何值!下面的函数将返回一个对象: + `getUser`函数接收一个对象。对于箭头函数,如果只返回一个值,我们不必编写花括号。但是,如果您想从一个箭头函数返回一个对象,您必须将它写在圆括号之间,否则两个花括号之间的所有内容都将被解释为一个块语句!在这种情况下,花括号之间的代码不是有效的 JavaScript 代码,因此会抛出SyntaxError。 -```const getUser = user => ({ name: user.name, age: user.age })``` +以下函数将返回一个对象: -由于在这种情况下不返回任何值,因此该函数返回`undefined`。 +`const getUser = user => ({ name: user.name, age: user.age })`

@@ -3833,7 +3833,7 @@ console.log(member.getLastName?.()); ``` - A: `undefined` `undefined` `undefined` `undefined` -- B: `Mara` `undefined` `Lydia Hallie` `undefined` +- B: `Mara` `undefined` `Lydia Hallie` `ReferenceError` - C: `Mara` `null` `Lydia Hallie` `null` - D: `null` `ReferenceError` `null` `ReferenceError` @@ -3847,7 +3847,7 @@ console.log(member.getLastName?.()); `person.pet?.name`: `person` 有一个名为 `pet` 的属性: `person.pet` 不是 nullish。它有个名为 `name` 的属性,并返回字符串 `Mara`。 `person.pet?.family?.name`: `person` 有一个名为 `pet` 的属性: `person.pet` 不是 nullish. `pet` _并没有_ 一个名为 `family` 的属性, `person.pet.family` 是 nullish。表达式返回 `undefined`。 `person.getFullName?.()`: `person` 有一个名为 `getFullName` 的属性: `person.getFullName()` 不是 nullish 并可以被调用,返回字符串 `Lydia Hallie`。 -`member.getLastName?.()`: `member` is not defined: `member.getLastName()` is nullish. The expression returns `undefined`. +`member.getLastName?.()`: 变量`member` 不存在,因此会抛出错误`ReferenceError`。

From e2c07decc080953774377b33200dc2173bc8f3f5 Mon Sep 17 00:00:00 2001 From: Rahul RK <47377566+DevTMK@users.noreply.github.com> Date: Tue, 8 Feb 2022 20:46:29 +0530 Subject: [PATCH 099/193] Fix a typo in README.md Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 4cfa2556..78efa867 100644 --- a/README.md +++ b/README.md @@ -4438,7 +4438,7 @@ Object.seal(person); #### Answer: A -With `Object.seal` we can prevent new properies from being _added_, or existing properties to be _removed_. +With `Object.seal` we can prevent new properties from being _added_, or existing properties to be _removed_. However, you can still modify the value of existing properties. From b581f6cd3a4492570385085c17a2a025d6a2adb2 Mon Sep 17 00:00:00 2001 From: Hitendra <39190812+h1t3ndr4@users.noreply.github.com> Date: Thu, 21 Apr 2022 18:42:59 +0530 Subject: [PATCH 100/193] Spelling mistake updated question number 9, greetign changed to greeting --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 4cfa2556..da4e2284 100644 --- a/README.md +++ b/README.md @@ -310,8 +310,8 @@ The `colorChange` function is static. Static methods are designed to live only o ```javascript let greeting; -greetign = {}; // Typo! -console.log(greetign); +greeting = {}; // Typo! +console.log(greeting); ``` - A: `{}` From 0b560226c1d699f7594df895411839fdf0cdb47f Mon Sep 17 00:00:00 2001 From: ihavecoke Date: Thu, 21 Apr 2022 22:20:53 +0800 Subject: [PATCH 101/193] Autocorrect zh-CN lang text --- zh-CN/README-zh_CN.md | 440 +++++++++++++++++++++--------------------- 1 file changed, 220 insertions(+), 220 deletions(-) diff --git a/zh-CN/README-zh_CN.md b/zh-CN/README-zh_CN.md index 8b674e0f..59ae585e 100644 --- a/zh-CN/README-zh_CN.md +++ b/zh-CN/README-zh_CN.md @@ -288,7 +288,7 @@ console.log(greetign) #### 答案: A -代码打印出了一个对象,这是因为我们在全局对象上创建了一个空对象!当我们将 `greeting` 写错成 `greetign` 时,JS 解释器实际在上浏览器中将它视为 `global.greetign = {}` (或者 `window.greetign = {}`)。 +代码打印出了一个对象,这是因为我们在全局对象上创建了一个空对象!当我们将 `greeting` 写错成 `greetign` 时,JS 解释器实际在上浏览器中将它视为 `global.greetign = {}`(或者 `window.greetign = {}`)。 为了避免这个为题,我们可以使用 `"use strict"。这能确保当你声明变量时必须赋值。 @@ -307,7 +307,7 @@ function bark() { bark.animal = 'dog' ``` -- A: 正常运行! +- A: 正常运行! - B: `SyntaxError`. 你不能通过这种方式给函数增加属性。 - C: `undefined` - D: `ReferenceError` @@ -824,7 +824,7 @@ name.giveLydiaPizza() #### 答案: A -`String` 是内置的构造函数,我们可以向它添加属性。我只是在它的原型中添加了一个方法。基本类型字符串被自动转换为字符串对象,由字符串原型函数生成。因此,所有 string(string 对象)都可以访问该方法! +`String` 是内置的构造函数,我们可以向它添加属性。我只是在它的原型中添加了一个方法。基本类型字符串被自动转换为字符串对象,由字符串原型函数生成。因此,所有 string(string 对象) 都可以访问该方法!

@@ -891,7 +891,7 @@ baz() 这是因为在浏览器中,我们不仅有运行时引擎,还有一个叫做 `WebAPI` 的东西。`WebAPI` 提供了 `setTimeout` 函数,也包含其他的,例如 DOM。 -将 _callback_ 推送到 WebAPI 后,`setTimeout` 函数本身(但不是回调!)将从栈中弹出。 +将 _callback_ 推送到 WebAPI 后,`setTimeout` 函数本身 (但不是回调!) 将从栈中弹出。 @@ -899,7 +899,7 @@ baz() -`foo` 从栈中弹出,`baz` 被调用. 打印 `"Third"`。 +`foo` 从栈中弹出,`baz` 被调用。打印 `"Third"`。 @@ -918,7 +918,7 @@ WebAPI 不能随时向栈内添加内容。相反,它将回调函数推到名 --- -###### 31. 当点击按钮时,event.target是什么? +###### 31. 当点击按钮时,event.target 是什么? ```html
@@ -1026,9 +1026,9 @@ typeof sayHi() #### 答案: B -`sayHi` 方法返回的是立即执行函数(IIFE)的返回值.此立即执行函数的返回值是 `0`, 类型是 `number` +`sayHi` 方法返回的是立即执行函数 (IIFE) 的返回值。此立即执行函数的返回值是 `0`, 类型是 `number` -参考:只有7种内置类型:`null`,`undefined`,`boolean`,`number`,`string`,`object`, `symbol` 和 `bigint`。 ``function`` 不是一种类型,函数是对象,它的类型是``object``。 +参考:只有 7 种内置类型:`null`,`undefined`,`boolean`,`number`,`string`,`object`, `symbol` 和 `bigint`。 ``function`` 不是一种类型,函数是对象,它的类型是``object``。

@@ -1056,7 +1056,7 @@ undefined #### 答案: A -只有 8 种 [falsy](https://developer.mozilla.org/zh-CN/docs/Glossary/Falsy) 值: +只有 8 种 [falsy](https://developer.mozilla.org/zh-CN/docs/Glossary/Falsy) 值: @@ -1069,7 +1069,7 @@ undefined - `-0` - `0n` (BigInt(0)) -`Function` 构造函数, 比如 `new Number` 和 `new Boolean`,是 [truthy](https://developer.mozilla.org/zh-CN/docs/Glossary/Truthy)。 +`Function` 构造函数,比如 `new Number` 和 `new Boolean`,是 [truthy](https://developer.mozilla.org/zh-CN/docs/Glossary/Truthy)。

@@ -1251,7 +1251,7 @@ JavaScript 只有基本类型和对象。 setInterval(() => console.log('Hi'), 1000) ``` -- A: 一个唯一的id +- A: 一个唯一的 id - B: 该方法指定的毫秒数 - C: 传递的函数 - D: `undefined` @@ -1291,7 +1291,7 @@ string 类型是可迭代的。扩展运算符将迭代的每个字符映射成 --- -###### 44. 输出是什么? +###### 44. 输出是什么? ```javascript function* generator(i) { @@ -1315,9 +1315,9 @@ console.log(gen.next().value); #### 答案: C -一般的函数在执行之后是不能中途停下的。但是,生成器函数却可以中途“停下”,之后可以再从停下的地方继续。当生成器遇到`yield`关键字的时候,会生成`yield`后面的值。注意,生成器在这种情况下不 _返回_ (_return_ )值,而是 _生成_ (_yield_)值。 +一般的函数在执行之后是不能中途停下的。但是,生成器函数却可以中途 “停下”,之后可以再从停下的地方继续。当生成器遇到`yield`关键字的时候,会生成`yield`后面的值。注意,生成器在这种情况下不 _返回_ (_return_ ) 值,而是 _生成_ (_yield_) 值。 -首先,我们用`10`作为参数`i`来初始化生成器函数。然后使用`next()`方法一步步执行生成器。第一次执行生成器的时候,`i`的值为`10`,遇到第一个`yield`关键字,它要生成`i`的值。此时,生成器“暂停”,生成了`10`。 +首先,我们用`10`作为参数`i`来初始化生成器函数。然后使用`next()`方法一步步执行生成器。第一次执行生成器的时候,`i`的值为`10`,遇到第一个`yield`关键字,它要生成`i`的值。此时,生成器 “暂停”,生成了`10`。 然后,我们再执行`next()`方法。生成器会从刚才暂停的地方继续,这个时候`i`还是`10`。于是我们走到了第二个`yield`关键字处,这时候需要生成的值是`i*2`,`i`为`10`,那么此时生成的值便是`20`。所以这道题的最终结果是`10,20`。 @@ -1325,7 +1325,7 @@ console.log(gen.next().value);

-###### 45. 返回值是什么? +###### 45. 返回值是什么? ```javascript const firstPromise = new Promise((res, rej) => { @@ -1349,14 +1349,14 @@ Promise.race([firstPromise, secondPromise]).then(res => console.log(res)); #### 答案: B -当我们向`Promise.race`方法中传入多个`Promise`时,会进行 _优先_ 解析。在这个例子中,我们用`setTimeout`给`firstPromise`和`secondPromise`分别设定了500ms和100ms的定时器。这意味着`secondPromise`会首先解析出字符串`two`。那么此时`res`参数即为`two`,是为输出结果。 +当我们向`Promise.race`方法中传入多个`Promise`时,会进行 _优先_ 解析。在这个例子中,我们用`setTimeout`给`firstPromise`和`secondPromise`分别设定了 500ms 和 100ms 的定时器。这意味着`secondPromise`会首先解析出字符串`two`。那么此时`res`参数即为`two`,是为输出结果。

--- -###### 46. 输出是什么? +###### 46. 输出是什么? ```javascript let person = { name: "Lydia" }; @@ -1389,14 +1389,14 @@ console.log(members); -我们没有修改数组第一个元素的值,而只是修改了变量`person`的值,因为元素(复制而来)的引用与`person`不同。`members`的第一个元素仍然保持着对原始对象的引用。当我们输出`members`数组时,第一个元素会将引用的对象打印出来。 +我们没有修改数组第一个元素的值,而只是修改了变量`person`的值,因为元素(复制而来)的引用与`person`不同。`members`的第一个元素仍然保持着对原始对象的引用。当我们输出`members`数组时,第一个元素会将引用的对象打印出来。

--- -###### 47. 输出是什么? +###### 47. 输出是什么? ```javascript const person = { @@ -1419,14 +1419,14 @@ for (const item in person) { #### 答案: B -在`for-in`循环中,我们可以通过对象的key来进行迭代,也就是这里的`name`和`age`。在底层,对象的key都是字符串(如果他们不是Symbol的话)。在每次循环中,我们将`item`设定为当前遍历到的key.所以一开始,`item`是`name`,之后 `item`输出的则是`age`。 +在`for-in`循环中,我们可以通过对象的 key 来进行迭代,也就是这里的`name`和`age`。在底层,对象的 key 都是字符串(如果他们不是 Symbol 的话)。在每次循环中,我们将`item`设定为当前遍历到的 key.所以一开始,`item`是`name`,之后 `item`输出的则是`age`。

--- -###### 48. 输出是什么? +###### 48. 输出是什么? ```javascript console.log(3 + 4 + "5"); @@ -1446,14 +1446,14 @@ console.log(3 + 4 + "5"); `3 + 4`首先计算,得到数字`7`. -由于类型的强制转换,`7 + '5'`的结果是`"75"`. JavaScript将`7`转换成了字符串,可以参考问题15.我们可以用`+`号把两个字符串连接起来。 `"7" + "5"` 就得到了`"75"`. +由于类型的强制转换,`7 + '5'`的结果是`"75"`. JavaScript 将`7`转换成了字符串,可以参考问题 15.我们可以用`+`号把两个字符串连接起来。 `"7" + "5"` 就得到了`"75"`.

--- -###### 49. `num`的值是什么? +###### 49. `num`的值是什么? ```javascript const num = parseInt("7*6", 10); @@ -1469,7 +1469,7 @@ const num = parseInt("7*6", 10); #### 答案: C -只返回了字符串中第一个字母. 设定了 _进制_ 后 (也就是第二个参数,指定需要解析的数字是什么进制: 十进制、十六机制、八进制、二进制等等……),`parseInt` 检查字符串中的字符是否合法. 一旦遇到一个在指定进制中不合法的字符后,立即停止解析并且忽略后面所有的字符。 +只返回了字符串中第一个字母。设定了 _进制_ 后 (也就是第二个参数,指定需要解析的数字是什么进制:十进制、十六机制、八进制、二进制等等……),`parseInt` 检查字符串中的字符是否合法。一旦遇到一个在指定进制中不合法的字符后,立即停止解析并且忽略后面所有的字符。 `*`就是不合法的数字字符。所以只解析到`"7"`,并将其解析为十进制的`7`. `num`的值即为`7`. @@ -1478,7 +1478,7 @@ const num = parseInt("7*6", 10); --- -###### 50. 输出是什么? +###### 50. 输出是什么? ```javascript [1, 2, 3].map(num => { @@ -1497,7 +1497,7 @@ const num = parseInt("7*6", 10); #### 答案: C -对数组进行映射的时候,`num`就是当前循环到的元素. 在这个例子中,所有的映射都是number类型,所以if中的判断`typeof num === "number"`结果都是`true`.map函数创建了新数组并且将函数的返回值插入数组。 +对数组进行映射的时候,`num`就是当前循环到的元素。在这个例子中,所有的映射都是 number 类型,所以 if 中的判断`typeof num === "number"`结果都是`true`.map 函数创建了新数组并且将函数的返回值插入数组。 但是,没有任何值返回。当函数没有返回任何值时,即默认返回`undefined`.对数组中的每一个元素来说,函数块都得到了这个返回值,所以结果中每一个元素都是`undefined`. @@ -1506,7 +1506,7 @@ const num = parseInt("7*6", 10); --- -###### 51. 输出的是什么? +###### 51. 输出的是什么? ```javascript function getInfo(member, year) { @@ -1532,18 +1532,18 @@ console.log(person, birthYear); #### 答案: A -普通参数都是 _值_ 传递的,而对象则不同,是 _引用_ 传递。所以说,`birthYear`是值传递,因为他是个字符串而不是对象。当我们对参数进行值传递时,会创建一份该值的 _复制_ 。(可以参考问题46) +普通参数都是 _值_ 传递的,而对象则不同,是 _引用_ 传递。所以说,`birthYear`是值传递,因为他是个字符串而不是对象。当我们对参数进行值传递时,会创建一份该值的 _复制_ 。(可以参考问题 46) 变量`birthYear`有一个对`"1997"`的引用,而传入的参数也有一个对`"1997"`的引用,但二者的引用并不相同。当我们通过给 `year`赋值`"1998"`来更新`year`的值的时候我们只是更新了`year`(的引用)。此时`birthYear`仍然是`"1997"`. -而`person`是个对象。参数`member`引用与之 _相同的_ 对象。当我们修改`member`所引用对象的属性时,`person`的相应属性也被修改了,因为他们引用了相同的对象. `person`的 `name`属性也变成了 `"Lydia"`. +而`person`是个对象。参数`member`引用与之 _相同的_ 对象。当我们修改`member`所引用对象的属性时,`person`的相应属性也被修改了,因为他们引用了相同的对象。`person`的 `name`属性也变成了 `"Lydia"`.

--- -###### 52. 输出是什么? +###### 52. 输出是什么? ```javascript function greeting() { @@ -1572,7 +1572,7 @@ sayHi(); #### 答案: D -通过`throw`语句,我么可以创建自定义错误。 而通过它,我们可以抛出异常。异常可以是一个字符串, 一个 数字, 一个 布尔类型 或者是一个 对象。在本例中,我们的异常是字符串`'Hello world'`. +通过`throw`语句,我么可以创建自定义错误。 而通过它,我们可以抛出异常。异常可以是一个字符串,一个 数字,一个 布尔类型 或者是一个 对象。在本例中,我们的异常是字符串`'Hello world'`. 通过 `catch`语句,我们可以设定当`try`语句块中抛出异常后应该做什么处理。在本例中抛出的异常是字符串`'Hello world'`. `e`就是这个字符串,因此被输出。最终结果就是`'Oh an error: Hello world'`. @@ -1581,7 +1581,7 @@ sayHi(); --- -###### 53. 输出是什么? +###### 53. 输出是什么? ```javascript function Car() { @@ -1610,7 +1610,7 @@ console.log(myCar.make); --- -###### 54. 输出是什么? +###### 54. 输出是什么? ```javascript (() => { @@ -1631,16 +1631,16 @@ console.log(typeof y); #### 答案: A -`let x = y = 10;` 是下面这个表达式的缩写: +`let x = y = 10;` 是下面这个表达式的缩写: ```javascript y = 10; let x = y; ``` -我们设定`y`等于`10`时,我们实际上增加了一个属性`y`给全局对象(浏览器里的`window`, Nodejs里的`global`)。在浏览器中, `window.y`等于`10`. +我们设定`y`等于`10`时,我们实际上增加了一个属性`y`给全局对象 (浏览器里的`window`, Nodejs 里的`global`)。在浏览器中, `window.y`等于`10`. -然后我们声明了变量`x`等于`y`,也是`10`.但变量是使用 `let`声明的,它只作用于 _块级作用域_, 仅在声明它的块中有效;就是案例中的立即调用表达式(IIFE)。使用`typeof`操作符时, 操作值 `x`没有被定义:因为我们在`x`声明块的外部,无法调用它。这就意味着`x`未定义。未分配或是未声明的变量类型为`"undefined"`. `console.log(typeof x)`返回`"undefined"`. +然后我们声明了变量`x`等于`y`,也是`10`.但变量是使用 `let`声明的,它只作用于 _块级作用域_,仅在声明它的块中有效;就是案例中的立即调用表达式 (IIFE)。使用`typeof`操作符时,操作值 `x`没有被定义:因为我们在`x`声明块的外部,无法调用它。这就意味着`x`未定义。未分配或是未声明的变量类型为`"undefined"`. `console.log(typeof x)`返回`"undefined"`. 而我们创建了全局变量`y`,并且设定`y`等于`10`.这个值在我们的代码各处都访问的到。 `y`已经被定义了,而且有一个`"number"`类型的值。 `console.log(typeof y)`返回`"number"`. @@ -1649,7 +1649,7 @@ let x = y; --- -###### 55. 输出是什么? +###### 55. 输出是什么? ```javascript class Dog { @@ -1681,7 +1681,7 @@ pet.bark(); #### 答案: A -我们可以用`delete`关键字删除对象的属性,对原型也是适用的。删除了原型的属性后,该属性在原型链上就不可用了。在本例中,函数`bark`在执行了`delete Dog.prototype.bark`后不可用, 然而后面的代码还在调用它。 +我们可以用`delete`关键字删除对象的属性,对原型也是适用的。删除了原型的属性后,该属性在原型链上就不可用了。在本例中,函数`bark`在执行了`delete Dog.prototype.bark`后不可用,然而后面的代码还在调用它。 当我们尝试调用一个不存在的函数时`TypeError`异常会被抛出。在本例中就是 `TypeError: pet.bark is not a function`,因为`pet.bark`是`undefined`. @@ -1690,7 +1690,7 @@ pet.bark(); --- -###### 56. 输出是什么? +###### 56. 输出是什么? ```javascript const set = new Set([1, 1, 2, 3, 4]); @@ -1717,7 +1717,7 @@ console.log(set); --- -###### 57. 输出是什么? +###### 57. 输出是什么? ```javascript // counter.js @@ -1744,7 +1744,7 @@ console.log(myCounter); #### 答案: C -引入的模块是 _只读_ 的: 你不能修改引入的模块。只有导出他们的模块才能修改其值。 +引入的模块是 _只读_ 的:你不能修改引入的模块。只有导出他们的模块才能修改其值。 当我们给`myCounter`增加一个值的时候会抛出一个异常: `myCounter`是只读的,不能被修改。 @@ -1753,7 +1753,7 @@ console.log(myCounter); --- -###### 58. 输出是什么? +###### 58. 输出是什么? ```javascript const name = "Lydia"; @@ -1775,14 +1775,14 @@ console.log(delete age); `delete`操作符返回一个布尔值: `true`指删除成功,否则返回`false`. 但是通过 `var`, `const` 或 `let` 关键字声明的变量无法用 `delete` 操作符来删除。 -`name`变量由`const`关键字声明,所以删除不成功:返回 `false`. 而我们设定`age`等于`21`时,我们实际上添加了一个名为`age`的属性给全局对象。对象中的属性是可以删除的,全局对象也是如此,所以`delete age`返回`true`. +`name`变量由`const`关键字声明,所以删除不成功:返回 `false`. 而我们设定`age`等于`21`时,我们实际上添加了一个名为`age`的属性给全局对象。对象中的属性是可以删除的,全局对象也是如此,所以`delete age`返回`true`.

--- -###### 59. 输出是什么? +###### 59. 输出是什么? ```javascript const numbers = [1, 2, 3, 4, 5]; @@ -1809,7 +1809,7 @@ console.log(y); -`a`的值现在是`1`,`b`的值现在是`2`.而在题目中,我们是这么做的: +`a`的值现在是`1`,`b`的值现在是`2`.而在题目中,我们是这么做的: ```javascript [y] = [1, 2, 3, 4, 5]; @@ -1824,7 +1824,7 @@ console.log(y); --- -###### 60. 输出是什么? +###### 60. 输出是什么? ```javascript const user = { name: "Lydia", age: 21 }; @@ -1850,7 +1850,7 @@ console.log(admin); --- -###### 61. 输出是什么? +###### 61. 输出是什么? ```javascript const person = { name: "Lydia" }; @@ -1871,7 +1871,7 @@ console.log(Object.keys(person)); #### 答案: B -通过`defineProperty`方法,我们可以给对象添加一个新属性,或者修改已经存在的属性。而我们使用`defineProperty`方法给对象添加了一个属性之后,属性默认为 _不可枚举(not enumerable)_. `Object.keys`方法仅返回对象中 _可枚举(enumerable)_ 的属性,因此只剩下了`"name"`. +通过`defineProperty`方法,我们可以给对象添加一个新属性,或者修改已经存在的属性。而我们使用`defineProperty`方法给对象添加了一个属性之后,属性默认为 _不可枚举 (not enumerable)_. `Object.keys`方法仅返回对象中 _可枚举 (enumerable)_ 的属性,因此只剩下了`"name"`. 用`defineProperty`方法添加的属性默认不可变。你可以通过`writable`, `configurable` 和 `enumerable`属性来改变这一行为。这样,`defineProperty`方法可以让您更好地控制要添加到对象的属性。 @@ -1880,7 +1880,7 @@ console.log(Object.keys(person)); --- -###### 62. 输出是什么? +###### 62. 输出是什么? ```javascript const settings = { @@ -1903,19 +1903,19 @@ console.log(data); #### 答案: A -`JSON.stringify`的第二个参数是 _替代者(replacer)_. 替代者(replacer)可以是个函数或数组,用以控制哪些值如何被转换为字符串。 +`JSON.stringify`的第二个参数是 _替代者 (replacer)_. 替代者 (replacer) 可以是个函数或数组,用以控制哪些值如何被转换为字符串。 -如果替代者(replacer)是个 _数组_ ,那么就只有包含在数组中的属性将会被转化为字符串。在本例中,只有名为`"level"` 和 `"health"` 的属性被包括进来, `"username"`则被排除在外。 `data` 就等于 `"{"level":19, "health":90}"`. +如果替代者 (replacer) 是个 _数组_ ,那么就只有包含在数组中的属性将会被转化为字符串。在本例中,只有名为`"level"` 和 `"health"` 的属性被包括进来, `"username"`则被排除在外。 `data` 就等于 `"{"level":19, "health":90}"`. -而如果替代者(replacer)是个 _函数_,这个函数将被对象的每个属性都调用一遍。 -函数返回的值会成为这个属性的值,最终体现在转化后的JSON字符串中(译者注:Chrome下,经过实验,如果所有属性均返回同一个值的时候有异常,会直接将返回值作为结果输出而不会输出JSON字符串),而如果返回值为`undefined`,则该属性会被排除在外。 +而如果替代者 (replacer) 是个 _函数_,这个函数将被对象的每个属性都调用一遍。 +函数返回的值会成为这个属性的值,最终体现在转化后的 JSON 字符串中(译者注:Chrome 下,经过实验,如果所有属性均返回同一个值的时候有异常,会直接将返回值作为结果输出而不会输出 JSON 字符串),而如果返回值为`undefined`,则该属性会被排除在外。

--- -###### 63. 输出是什么? +###### 63. 输出是什么? ```javascript let num = 10; @@ -1940,16 +1940,16 @@ console.log(num2); #### 答案: A -一元操作符 `++` _先返回_ 操作值, _再累加_ 操作值。`num1`的值是`10`, 因为`increaseNumber`函数首先返回`num`的值,也就是`10`,随后再进行 `num`的累加。 +一元操作符 `++` _先返回_ 操作值,_再累加_ 操作值。`num1`的值是`10`,因为`increaseNumber`函数首先返回`num`的值,也就是`10`,随后再进行 `num`的累加。 -`num2`是`10`因为我们将 `num1`传入`increasePassedNumber`. `number`等于`10`(`num1`的值。同样道理,`++` _先返回_ 操作值, _再累加_ 操作值。) `number`是`10`,所以`num2`也是`10`. +`num2`是`10`因为我们将 `num1`传入`increasePassedNumber`. `number`等于`10`(`num1`的值。同样道理,`++` _先返回_ 操作值,_再累加_ 操作值。)`number`是`10`,所以`num2`也是`10`.

--- -###### 64. 输出什么? +###### 64. 输出什么? ```javascript const value = { number: 10 }; @@ -1974,7 +1974,7 @@ multiply(value); #### 答案: C -在ES6中,我们可以使用默认值初始化参数。如果没有给函数传参,或者传的参值为 `"undefined"` ,那么参数的值将是默认值。上述例子中,我们将 `value` 对象进行了解构并传到一个新对象中,因此 `x` 的默认值为 `{number:10}` 。 +在 ES6 中,我们可以使用默认值初始化参数。如果没有给函数传参,或者传的参值为 `"undefined"` ,那么参数的值将是默认值。上述例子中,我们将 `value` 对象进行了解构并传到一个新对象中,因此 `x` 的默认值为 `{number:10}` 。 默认参数在调用时才会进行计算,每次调用函数时,都会创建一个新的对象。我们前两次调用 `multiply` 函数且不传递值,那么每一次 `x` 的默认值都为 `{number:10}` ,因此打印出该数字的乘积值为`20`。 @@ -1987,7 +1987,7 @@ multiply(value); --- -###### 65. 输出什么? +###### 65. 输出什么? ```javascript [1, 2, 3, 4].reduce((x, y) => console.log(x, y)); @@ -2003,7 +2003,7 @@ multiply(value); #### 答案: D -`reducer` 函数接收4个参数: +`reducer` 函数接收 4 个参数: 1. Accumulator (acc) (累计器) 2. Current Value (cur) (当前值) @@ -2012,21 +2012,21 @@ multiply(value); `reducer` 函数的返回值将会分配给累计器,该返回值在数组的每个迭代中被记住,并最后成为最终的单个结果值。 -`reducer` 函数还有一个可选参数`initialValue`, 该参数将作为第一次调用回调函数时的第一个参数的值。如果没有提供`initialValue`,则将使用数组中的第一个元素。 +`reducer` 函数还有一个可选参数`initialValue`,该参数将作为第一次调用回调函数时的第一个参数的值。如果没有提供`initialValue`,则将使用数组中的第一个元素。 -在上述例子,`reduce`方法接收的第一个参数(Accumulator)是`x`, 第二个参数(Current Value)是`y`。 +在上述例子,`reduce`方法接收的第一个参数 (Accumulator) 是`x`,第二个参数 (Current Value) 是`y`。 在第一次调用时,累加器`x`为`1`,当前值`“y”`为`2`,打印出累加器和当前值:`1`和`2`。 -例子中我们的回调函数没有返回任何值,只是打印累加器的值和当前值。如果函数没有返回值,则默认返回`undefined`。 在下一次调用时,累加器为`undefined`,当前值为“3”, 因此`undefined`和`3`被打印出。 +例子中我们的回调函数没有返回任何值,只是打印累加器的值和当前值。如果函数没有返回值,则默认返回`undefined`。 在下一次调用时,累加器为`undefined`,当前值为 “3”,因此`undefined`和`3`被打印出。 -在第四次调用时,回调函数依然没有返回值。 累加器再次为 `undefined` ,当前值为“4”。 `undefined`和`4`被打印出。 +在第四次调用时,回调函数依然没有返回值。 累加器再次为 `undefined` ,当前值为 “4”。 `undefined`和`4`被打印出。

--- -###### 66. 使用哪个构造函数可以成功继承`Dog`类? +###### 66. 使用哪个构造函数可以成功继承`Dog`类? ```javascript class Dog { @@ -2069,17 +2069,17 @@ class Labrador extends Dog { #### 答案: B -在子类中,在调用`super`之前不能访问到`this`关键字。 如果这样做,它将抛出一个`ReferenceError`:1和4将引发一个引用错误。 +在子类中,在调用`super`之前不能访问到`this`关键字。 如果这样做,它将抛出一个`ReferenceError`:1 和 4 将引发一个引用错误。 使用`super`关键字,需要用给定的参数来调用父类的构造函数。 父类的构造函数接收`name`参数,因此我们需要将`name`传递给`super`。 -`Labrador`类接收两个参数,`name`参数是由于它继承了`Dog`,`size`作为`Labrador`类的额外属性,它们都需要传递给`Labrador`的构造函数,因此使用构造函数2正确完成。 +`Labrador`类接收两个参数,`name`参数是由于它继承了`Dog`,`size`作为`Labrador`类的额外属性,它们都需要传递给`Labrador`的构造函数,因此使用构造函数 2 正确完成。

--- -###### 67. 输出什么? +###### 67. 输出什么? ```javascript // index.js @@ -2104,14 +2104,14 @@ export const sum = (a, b) => a + b; `import`命令是编译阶段执行的,在代码运行之前。因此这意味着被导入的模块会先运行,而导入模块的文件会后执行。 -这是CommonJS中`require()`和`import`之间的区别。使用`require()`,您可以在运行代码时根据需要加载依赖项。 如果我们使用`require`而不是`import`,`running index.js`,`running sum.js`,`3`会被依次打印。 +这是 CommonJS 中`require()`和`import`之间的区别。使用`require()`,您可以在运行代码时根据需要加载依赖项。 如果我们使用`require`而不是`import`,`running index.js`,`running sum.js`,`3`会被依次打印。

--- -###### 68. 输出什么? +###### 68. 输出什么? ```javascript console.log(Number(2) === Number(2)) @@ -2129,14 +2129,14 @@ console.log(Symbol('foo') === Symbol('foo')) #### 答案: A -每个`Symbol`都是完全唯一的。传递给`Symbol`的参数只是给`Symbol`的一个描述。 `Symbol`的值不依赖于传递的参数。 当我们测试相等时,我们创建了两个全新的符号:第一个`Symbol('foo')`,第二个`Symbol('foo')`, 这两个值是唯一的,彼此不相等,因此返回`false`。 +每个`Symbol`都是完全唯一的。传递给`Symbol`的参数只是给`Symbol`的一个描述。 `Symbol`的值不依赖于传递的参数。 当我们测试相等时,我们创建了两个全新的符号:第一个`Symbol('foo')`,第二个`Symbol('foo')`,这两个值是唯一的,彼此不相等,因此返回`false`。

--- -###### 69. 输出什么? +###### 69. 输出什么? ```javascript const name = "Lydia Hallie" @@ -2154,7 +2154,7 @@ console.log(name.padStart(2)) #### 答案: C -使用`padStart`方法,我们可以在字符串的开头添加填充。传递给此方法的参数是字符串的总长度(包含填充)。字符串`Lydia Hallie`的长度为`12`, 因此`name.padStart(13)`在字符串的开头只会插入1(`13 - 12 = 1`)个空格。 +使用`padStart`方法,我们可以在字符串的开头添加填充。传递给此方法的参数是字符串的总长度(包含填充)。字符串`Lydia Hallie`的长度为`12`,因此`name.padStart(13)`在字符串的开头只会插入 1(`13 - 12 = 1`)个空格。 如果传递给`padStart`方法的参数小于字符串的长度,则不会添加填充。 @@ -2163,7 +2163,7 @@ console.log(name.padStart(2)) --- -###### 70. 输出什么? +###### 70. 输出什么? ```javascript console.log("🥑" + "💻"); @@ -2212,7 +2212,7 @@ console.log(/* 2 */); // JavaScript loves you back ❤️ #### 答案: C -`generator`函数在遇到`yield`关键字时会“暂停”其执行。 首先,我们需要让函数产生字符串`Do you love JavaScript?`,这可以通过调用`game.next().value`来完成。上述函数的第一行就有一个`yield`关键字,那么运行立即停止了,`yield`表达式本身没有返回值,或者说总是返回`undefined`, 这意味着此时变量 `答案` 为`undefined` +`generator`函数在遇到`yield`关键字时会 “暂停” 其执行。 首先,我们需要让函数产生字符串`Do you love JavaScript?`,这可以通过调用`game.next().value`来完成。上述函数的第一行就有一个`yield`关键字,那么运行立即停止了,`yield`表达式本身没有返回值,或者说总是返回`undefined`,这意味着此时变量 `答案` 为`undefined` `next`方法可以带一个参数,该参数会被当作上一个 `yield` 表达式的返回值。当我们调用`game.next("Yes").value`时,先前的 `yield` 的返回值将被替换为传递给`next()`函数的参数`"Yes"`。此时变量 `答案` 被赋值为 `"Yes"`,`if`语句返回`false`,所以`JavaScript loves you back ❤️`被打印。 @@ -2221,7 +2221,7 @@ console.log(/* 2 */); // JavaScript loves you back ❤️ --- -###### 72. 输出什么? +###### 72. 输出什么? ```javascript console.log(String.raw`Hello\nworld`); @@ -2261,7 +2261,7 @@ String.raw`C:\Documents\Projects\table.html` --- -###### 73. 输出什么? +###### 73. 输出什么? ```javascript async function getData() { @@ -2282,7 +2282,7 @@ console.log(data); #### 答案: C -异步函数始终返回一个promise。`await`仍然需要等待promise的解决:当我们调用`getData()`并将其赋值给`data`,此时`data`为`getData`方法返回的一个挂起的promise,该promise并没有解决。 +异步函数始终返回一个 promise。`await`仍然需要等待 promise 的解决:当我们调用`getData()`并将其赋值给`data`,此时`data`为`getData`方法返回的一个挂起的 promise,该 promise 并没有解决。 如果我们想要访问已解决的值`"I made it!"`,可以在`data`上使用`.then()`方法: @@ -2295,7 +2295,7 @@ console.log(data); --- -###### 74. 输出什么? +###### 74. 输出什么? ```javascript function addToList(item, list) { @@ -2316,16 +2316,16 @@ console.log(result); #### 答案: B -`push()`方法返回新数组的长度。一开始,数组包含一个元素(字符串`"banana"`),长度为1。 在数组中添加字符串`"apple"`后,长度变为2,并将从`addToList`函数返回。 +`push()`方法返回新数组的长度。一开始,数组包含一个元素(字符串`"banana"`),长度为 1。 在数组中添加字符串`"apple"`后,长度变为 2,并将从`addToList`函数返回。 -`push`方法修改原始数组,如果你想从函数返回数组而不是数组长度,那么应该在push `item`之后返回`list`。 +`push`方法修改原始数组,如果你想从函数返回数组而不是数组长度,那么应该在 push `item`之后返回`list`。

--- -###### 75. 输出什么? +###### 75. 输出什么? ```javascript const box = { x: 10, y: 20 }; @@ -2353,14 +2353,14 @@ console.log(shape) 由于`shape`被冻结,并且`x`的值不是对象,所以我们不能修改属性`x`。 `x`仍然等于`10`,`{x:10,y:20}`被打印。 -注意,上述例子我们对属性`x`进行修改,可能会导致抛出TypeError异常(最常见但不仅限于严格模式下时)。 +注意,上述例子我们对属性`x`进行修改,可能会导致抛出 TypeError 异常(最常见但不仅限于严格模式下时)。

--- -###### 76. 输出什么? +###### 76. 输出什么? ```javascript const { name: myName } = { name: "Lydia" }; @@ -2380,7 +2380,7 @@ console.log(name); 当我们从右侧的对象解构属性`name`时,我们将其值`Lydia`分配给名为`myName`的变量。 -使用`{name:myName}`,我们是在告诉JavaScript我们要创建一个名为`myName`的新变量,并且其值是右侧对象的`name`属性的值。 +使用`{name:myName}`,我们是在告诉 JavaScript 我们要创建一个名为`myName`的新变量,并且其值是右侧对象的`name`属性的值。 当我们尝试打印`name`,一个未定义的变量时,就会引发`ReferenceError`。 @@ -2389,7 +2389,7 @@ console.log(name); --- -###### 77. 以下是个纯函数么? +###### 77. 以下是个纯函数么? ```javascript function sum(a, b) { @@ -2405,7 +2405,7 @@ function sum(a, b) { #### 答案: A -纯函数在相同的输入值时,需产生相同的输出,其输出的结果,与输入值以外的其他隐藏信息或状态无关,也和由I/O设备产生的外部输出无关。 +纯函数在相同的输入值时,需产生相同的输出,其输出的结果,与输入值以外的其他隐藏信息或状态无关,也和由 I/O 设备产生的外部输出无关。 纯函数不会产生副作用。 纯函数与副作用的定义可参考: @@ -2416,7 +2416,7 @@ https://zh.wikipedia.org/wiki/%E5%89%AF%E4%BD%9C%E7%94%A8_(%E8%AE%A1%E7%AE%97%E6 --- -###### 78. 输出什么? +###### 78. 输出什么? ```javascript const add = () => { @@ -2454,18 +2454,18 @@ console.log(addFunction(5 * 2)); 我们用相同的值三次调用了`addFunction`函数: -在第一次调用,`num`等于`10`时函数的值尚未缓存,if语句`num in cache`返回`false`,else块的代码被执行:`Calculated! 20`,并且其结果被添加到缓存对象,`cache`现在看起来像`{10:20}`。 +在第一次调用,`num`等于`10`时函数的值尚未缓存,if 语句`num in cache`返回`false`,else 块的代码被执行:`Calculated! 20`,并且其结果被添加到缓存对象,`cache`现在看起来像`{10:20}`。 -第二次,`cache`对象包含`10`的返回值。 if语句 `num in cache` 返回`true`,`From cache! 20`被打印。 +第二次,`cache`对象包含`10`的返回值。 if 语句 `num in cache` 返回`true`,`From cache! 20`被打印。 -第三次,我们将`5 * 2`(值为10)传递给函数。 `cache`对象包含`10`的返回值。 if语句 `num in cache` 返回`true`,`From cache! 20`被打印。 +第三次,我们将`5 * 2`(值为 10) 传递给函数。 `cache`对象包含`10`的返回值。 if 语句 `num in cache` 返回`true`,`From cache! 20`被打印。

--- -###### 79. 输出什么? +###### 79. 输出什么? ```javascript const myLifeSummedUp = ["☕", "💻", "🍷", "🍫"] @@ -2489,20 +2489,20 @@ for (let item of myLifeSummedUp) { #### 答案: A -通过`for-in`循环,我们可以遍历一个对象**自有的**、**继承的**、**可枚举的**、**非Symbol的**属性。 在数组中,可枚举属性是数组元素的“键”, 即它们的索引。 类似于下面这个对象: +通过`for-in`循环,我们可以遍历一个对象**自有的**、**继承的**、**可枚举的**、**非 Symbol 的**属性。 在数组中,可枚举属性是数组元素的 “键”, 即它们的索引。 类似于下面这个对象: `{0: "☕", 1: "💻", 2: "🍷", 3: "🍫"}` 其中键则是可枚举属性,因此 `0`,`1`,`2`,`3`被记录。 -通过`for-of`循环,我们可以迭代**可迭代对象**(包括 `Array`,`Map`,`Set`,`String`,`arguments`等)。当我们迭代数组时,在每次迭代中,不同属性的值将被分配给变量`item`, 因此`“☕”`,`“💻”`,`“🍷”`,`“🍫”`被打印。 +通过`for-of`循环,我们可以迭代**可迭代对象**(包括 `Array`,`Map`,`Set`,`String`,`arguments`等)。当我们迭代数组时,在每次迭代中,不同属性的值将被分配给变量`item`,因此`“☕”`,`“💻”`,`“🍷”`,`“🍫”`被打印。

--- -###### 80. 输出什么? +###### 80. 输出什么? ```javascript const list = [1 + 2, 1 * 2, 1 / 2] @@ -2519,7 +2519,7 @@ console.log(list) #### 答案: C -数组元素可以包含任何值。 数字,字符串,布尔值,对象,数组,`null`,`undeifned`, 以及其他表达式,如日期,函数和计算。 +数组元素可以包含任何值。 数字,字符串,布尔值,对象,数组,`null`,`undeifned`,以及其他表达式,如日期,函数和计算。 元素将等于返回的值。 `1 + 2`返回`3`,`1 * 2`返回'2`,'1 / 2`返回`0.5`。 @@ -2528,7 +2528,7 @@ console.log(list) --- -###### 81. 输出什么? +###### 81. 输出什么? ```javascript function sayHi(name) { @@ -2550,7 +2550,7 @@ console.log(sayHi()) 默认情况下,如果不给函数传参,参数的值将为`undefined`。 上述情况,我们没有给参数`name`传值。 `name`等于`undefined`,并被打印。 -在ES6中,我们可以使用默认参数覆盖此默认的`undefined`值。 例如: +在 ES6 中,我们可以使用默认参数覆盖此默认的`undefined`值。 例如: `function sayHi(name =“Lydia”){...}` @@ -2561,7 +2561,7 @@ console.log(sayHi()) --- -###### 82. 输出什么? +###### 82. 输出什么? ```javascript var status = "😎" @@ -2599,7 +2599,7 @@ setTimeout(() => { --- -###### 83. 输出什么? +###### 83. 输出什么? ```javascript const person = { @@ -2627,7 +2627,7 @@ console.log(person) 请注意,我们没有引用`person`对象本身,只是将变量`city`设置为等于`person`对象上`city`属性的当前值。 -然后,我们将`city`设置为等于字符串`“Amsterdam”`。 这不会更改person对象:没有对该对象的引用。 +然后,我们将`city`设置为等于字符串`“Amsterdam”`。 这不会更改 person 对象:没有对该对象的引用。 因此打印`person`对象时,会返回未修改的对象。 @@ -2636,7 +2636,7 @@ console.log(person) --- -###### 84. 输出什么? +###### 84. 输出什么? ```javascript function checkAge(age) { @@ -2662,14 +2662,14 @@ console.log(checkAge(21)) #### 答案: C -`const`和`let`声明的变量是具有**块级作用域**的,块是大括号(`{}`)之间的任何东西, 即上述情况`if / else`语句的花括号。 由于块级作用域,我们无法在声明的块之外引用变量,因此抛出`ReferenceError`。 +`const`和`let`声明的变量是具有**块级作用域**的,块是大括号(`{}`)之间的任何东西,即上述情况`if / else`语句的花括号。 由于块级作用域,我们无法在声明的块之外引用变量,因此抛出`ReferenceError`。

--- -###### 85. 什么样的信息将被打印? +###### 85. 什么样的信息将被打印? ```javascript fetch('https://www.website.com/api/user/1') @@ -2694,7 +2694,7 @@ fetch('https://www.website.com/api/user/1') --- -###### 86. 哪个选项是将`hasName`设置为`true`的方法,前提是不能将`true`作为参数传递? +###### 86. 哪个选项是将`hasName`设置为`true`的方法,前提是不能将`true`作为参数传递? ```javascript function getName(name) { @@ -2723,7 +2723,7 @@ function getName(name) {

-###### 87. 输出什么? +###### 87. 输出什么? ```javascript console.log("I want pizza"[0]) @@ -2739,16 +2739,16 @@ console.log("I want pizza"[0]) #### 答案: B -可以使用方括号表示法获取字符串中特定索引的字符,字符串中的第一个字符具有索引0,依此类推。 在这种情况下,我们想要得到索引为0的元素,字符`'I'`被记录。 +可以使用方括号表示法获取字符串中特定索引的字符,字符串中的第一个字符具有索引 0,依此类推。 在这种情况下,我们想要得到索引为 0 的元素,字符`'I'`被记录。 -请注意,IE7及更低版本不支持此方法。 在这种情况下,应该使用`.charAt()` +请注意,IE7 及更低版本不支持此方法。 在这种情况下,应该使用`.charAt()`

--- -###### 88. 输出什么? +###### 88. 输出什么? ```javascript function sum(num1, num2 = num1) { @@ -2768,7 +2768,7 @@ sum(10) #### 答案: B -您可以将默认参数的值设置为函数的另一个参数,只要另一个参数定义在其之前即可。 我们将值`10`传递给`sum`函数。 如果`sum`函数只接收1个参数,则意味着没有传递`num2`的值,这种情况下,`num1`的值等于传递的值`10`。 `num2`的默认值是`num1`的值,即`10`。 ```num1 + num2```返回`20`。 +您可以将默认参数的值设置为函数的另一个参数,只要另一个参数定义在其之前即可。 我们将值`10`传递给`sum`函数。 如果`sum`函数只接收 1 个参数,则意味着没有传递`num2`的值,这种情况下,`num1`的值等于传递的值`10`。 `num2`的默认值是`num1`的值,即`10`。 ```num1 + num2```返回`20`。 如果您尝试将默认参数的值设置为后面定义的参数,则可能导致参数的值尚未初始化,从而引发错误。比如: ```js @@ -2785,7 +2785,7 @@ test(3, 4) // 3 4 --- -###### 89. 输出什么? +###### 89. 输出什么? ```javascript // module.js @@ -2808,16 +2808,16 @@ console.log(data) #### 答案: A -使用`import * as name`语法,我们将`module.js`文件中所有`export`导入到`index.js`文件中,并且创建了一个名为`data`的新对象。 在`module.js`文件中,有两个导出:默认导出和命名导出。 默认导出是一个返回字符串“Hello World”的函数,命名导出是一个名为`name`的变量,其值为字符串`“Lydia”`。 +使用`import * as name`语法,我们将`module.js`文件中所有`export`导入到`index.js`文件中,并且创建了一个名为`data`的新对象。 在`module.js`文件中,有两个导出:默认导出和命名导出。 默认导出是一个返回字符串 “Hello World” 的函数,命名导出是一个名为`name`的变量,其值为字符串`“Lydia”`。 -`data`对象具有默认导出的`default`属性,其他属性具有指定exports的名称及其对应的值。 +`data`对象具有默认导出的`default`属性,其他属性具有指定 exports 的名称及其对应的值。

--- -###### 90. 输出什么? +###### 90. 输出什么? ```javascript class Person { @@ -2855,7 +2855,7 @@ function Person() { --- -###### 91. 输出什么? +###### 91. 输出什么? ```javascript let newList = [1, 2, 3].push(4) @@ -2875,14 +2875,14 @@ console.log(newList.push(5)) `.push`方法返回数组的长度,而不是数组本身! 通过将`newList`设置为`[1,2,3].push(4)`,实际上`newList`等于数组的新长度:`4`。 -然后,尝试在`newList`上使用`.push`方法。 由于`newList`是数值`4`,抛出TypeError。 +然后,尝试在`newList`上使用`.push`方法。 由于`newList`是数值`4`,抛出 TypeError。

--- -###### 92. 输出什么? +###### 92. 输出什么? ```javascript function giveLydiaPizza() { @@ -2912,7 +2912,7 @@ console.log(giveLydiaChocolate.prototype) --- -###### 93. 输出什么? +###### 93. 输出什么? ```javascript const person = { @@ -2948,7 +2948,7 @@ for (const [x, y] of Object.entries(person)) { --- -###### 94. 输出什么? +###### 94. 输出什么? ```javascript function getItems(fruitList, ...args, favoriteFruit) { @@ -2984,7 +2984,7 @@ getItems(["banana", "apple"], "pear", "orange") --- -###### 95. 输出什么? +###### 95. 输出什么? ```javascript function nums(a, b) { @@ -3012,23 +3012,23 @@ console.log(nums(1, 2)) #### 答案: B -在JavaScript中,我们不必显式地编写分号(`;`),但是JavaScript引擎仍然在语句之后自动添加分号。这称为**自动分号插入**。例如,一个语句可以是变量,或者像`throw`、`return`、`break`这样的关键字。 +在 JavaScript 中,我们不必显式地编写分号 (`;`),但是 JavaScript 引擎仍然在语句之后自动添加分号。这称为**自动分号插入**。例如,一个语句可以是变量,或者像`throw`、`return`、`break`这样的关键字。 -在这里,我们在新的一行上写了一个`return`语句和另一个值`a + b `。然而,由于它是一个新行,引擎并不知道它实际上是我们想要返回的值。相反,它会在`return`后面自动添加分号。你可以这样看: +在这里,我们在新的一行上写了一个`return`语句和另一个值`a + b `。然而,由于它是一个新行,引擎并不知道它实际上是我们想要返回的值。相反,它会在`return`后面自动添加分号。你可以这样看: ```javascript return; a + b ``` -这意味着永远不会到达`a + b`,因为函数在`return`关键字之后停止运行。如果没有返回值,就像这里,函数返回`undefined`。注意,在`if/else`语句之后没有自动插入! +这意味着永远不会到达`a + b`,因为函数在`return`关键字之后停止运行。如果没有返回值,就像这里,函数返回`undefined`。注意,在`if/else`语句之后没有自动插入!

--- -###### 96. 输出什么? +###### 96. 输出什么? ```javascript class Person { @@ -3058,7 +3058,7 @@ console.log(member.name) #### 答案: B -我们可以将类设置为等于其他类/函数构造函数。 在这种情况下,我们将`Person`设置为`AnotherPerson`。 这个构造函数的名字是`Sarah`,所以新的`Person`实例`member`上的name属性是`Sarah`。 +我们可以将类设置为等于其他类/函数构造函数。 在这种情况下,我们将`Person`设置为`AnotherPerson`。 这个构造函数的名字是`Sarah`,所以新的`Person`实例`member`上的 name 属性是`Sarah`。

@@ -3066,7 +3066,7 @@ console.log(member.name) --- -###### 97. 输出什么? +###### 97. 输出什么? ```javascript const info = { @@ -3090,14 +3090,14 @@ console.log(Object.keys(info)) `Symbol`类型是不可枚举的。`Object.keys`方法返回对象上的所有可枚举的键属性。`Symbol`类型是不可见的,并返回一个空数组。 记录整个对象时,所有属性都是可见的,甚至是不可枚举的属性。 -这是`Symbol`的众多特性之一:除了表示完全唯一的值(防止对象意外名称冲突,例如当使用2个想要向同一对象添加属性的库时),您还可以`隐藏`这种方式对象的属性(尽管不完全。你仍然可以使用`Object.getOwnPropertySymbols()`方法访问 `Symbol`。 +这是`Symbol`的众多特性之一:除了表示完全唯一的值(防止对象意外名称冲突,例如当使用 2 个想要向同一对象添加属性的库时),您还可以`隐藏`这种方式对象的属性(尽管不完全。你仍然可以使用`Object.getOwnPropertySymbols()`方法访问 `Symbol`。

--- -###### 98. 输出什么? +###### 98. 输出什么? ```javascript const getList = ([x, ...y]) => [x, y] @@ -3127,7 +3127,7 @@ console.log(getUser(user)) 使用剩余的参数`... y`,我们将所有剩余参数放在一个数组中。 在这种情况下,其余的参数是`2`,`3`和`4`。 `y`的值是一个数组,包含所有其余参数。 在这种情况下,`x`的值等于`1`,所以当我们打印`[x,y]`时,会打印`[1,[2,3,4]]`。 - `getUser`函数接收一个对象。对于箭头函数,如果只返回一个值,我们不必编写花括号。但是,如果您想从一个箭头函数返回一个对象,您必须将它写在圆括号之间,否则两个花括号之间的所有内容都将被解释为一个块语句!在这种情况下,花括号之间的代码不是有效的 JavaScript 代码,因此会抛出SyntaxError。 + `getUser`函数接收一个对象。对于箭头函数,如果只返回一个值,我们不必编写花括号。但是,如果您想从一个箭头函数返回一个对象,您必须将它写在圆括号之间,否则两个花括号之间的所有内容都将被解释为一个块语句!在这种情况下,花括号之间的代码不是有效的 JavaScript 代码,因此会抛出 SyntaxError。 以下函数将返回一个对象: @@ -3138,7 +3138,7 @@ console.log(getUser(user)) --- -###### 99. 输出什么? +###### 99. 输出什么? ```javascript const name = "Lydia" @@ -3159,17 +3159,17 @@ console.log(name()) 变量`name`保存字符串的值,该字符串不是函数,因此无法调用。 -当值不是预期类型时,会抛出`TypeErrors`。 JavaScript期望`name`是一个函数,因为我们试图调用它。 但它是一个字符串,因此抛出`TypeError`:`name is not a function` +当值不是预期类型时,会抛出`TypeErrors`。 JavaScript 期望`name`是一个函数,因为我们试图调用它。 但它是一个字符串,因此抛出`TypeError`:`name is not a function` -当你编写了一些非有效的JavaScript时,会抛出语法错误,例如当你把`return`这个词写成`retrun`时。 -当JavaScript无法找到您尝试访问的值的引用时,抛出`ReferenceErrors`。 +当你编写了一些非有效的 JavaScript 时,会抛出语法错误,例如当你把`return`这个词写成`retrun`时。 +当 JavaScript 无法找到您尝试访问的值的引用时,抛出`ReferenceErrors`。

--- -###### 100. 输出什么? +###### 100. 输出什么? ```javascript // 🎉✨ This is my 100th question! ✨🎉 @@ -3198,7 +3198,7 @@ You should${'' && `n't`} see a therapist after so much JavaScript lol` --- -###### 101.输出什么? +###### 101.输出什么? ```javascript const one = (false || {} || null) @@ -3231,7 +3231,7 @@ console.log(one, two, three) --- -###### 102. 依次输出什么? +###### 102. 依次输出什么? ```javascript const myPromise = () => Promise.resolve('I have resolved!') @@ -3261,11 +3261,11 @@ secondFunction() #### 答案: D -有了promise,我们通常会说:当我想要调用某个方法,但是由于它可能需要一段时间,因此暂时将它放在一边。只有当某个值被resolved/rejected,并且执行栈为空时才使用这个值。 +有了 promise,我们通常会说:当我想要调用某个方法,但是由于它可能需要一段时间,因此暂时将它放在一边。只有当某个值被 resolved/rejected,并且执行栈为空时才使用这个值。 -我们可以在`async`函数中通过`.then`和`await`关键字获得该值。 尽管我们可以通过`.then`和`await`获得promise的价值,但是它们的工作方式有所不同。 +我们可以在`async`函数中通过`.then`和`await`关键字获得该值。 尽管我们可以通过`.then`和`await`获得 promise 的价值,但是它们的工作方式有所不同。 -在 `firstFunction`中,当运行到`myPromise`方法时我们将其放在一边,即promise进入微任务队列,其他后面的代码(`console.log('second')`)照常运行,因此`second`被打印出,`firstFunction`方法到此执行完毕,执行栈中宏任务队列被清空,此时开始执行微任务队列中的任务,`I have resolved`被打印出。 +在 `firstFunction`中,当运行到`myPromise`方法时我们将其放在一边,即 promise 进入微任务队列,其他后面的代码(`console.log('second')`)照常运行,因此`second`被打印出,`firstFunction`方法到此执行完毕,执行栈中宏任务队列被清空,此时开始执行微任务队列中的任务,`I have resolved`被打印出。 在`secondFunction`方法中,我们通过`await`关键字,暂停了后面代码的执行,直到异步函数的值被解析才开始后面代码的执行。这意味着,它会等着直到 `myPromise` 以值`I have resolved`被解决之后,下一行`second`才开始执行。 @@ -3275,7 +3275,7 @@ secondFunction() --- -###### 103. 输出什么? +###### 103. 输出什么? ```javascript const set = new Set() @@ -3299,20 +3299,20 @@ for (let item of set) { #### 答案: C -“+”运算符不仅用于添加数值,还可以使用它来连接字符串。 每当JavaScript引擎发现一个或多个值不是数字时,就会将数字强制为字符串。 +“+” 运算符不仅用于添加数值,还可以使用它来连接字符串。 每当 JavaScript 引擎发现一个或多个值不是数字时,就会将数字强制为字符串。 -第一个是数字1。 1 + 2返回数字3。 +第一个是数字 1。 1 + 2 返回数字 3。 -但是,第二个是字符串“Lydia”。 “Lydia”是一个字符串,2是一个数字:2被强制转换为字符串。 “Lydia”和“2”被连接起来,产生字符串“Lydia2”。 +但是,第二个是字符串 “Lydia”。 “Lydia” 是一个字符串,2 是一个数字:2 被强制转换为字符串。 “Lydia” 和 “2” 被连接起来,产生字符串 “Lydia2”。 -`{name:“ Lydia”}`是一个对象。 数字和对象都不是字符串,因此将二者都字符串化。 每当我们对常规对象进行字符串化时,它就会变成`[Object object]`。 与“2”串联的“ [Object object]”成为“[Object object]2”。 +`{name:“ Lydia”}`是一个对象。 数字和对象都不是字符串,因此将二者都字符串化。 每当我们对常规对象进行字符串化时,它就会变成`[Object object]`。 与 “2” 串联的 “ [Object object]” 成为 “[Object object]2”。

--- -###### 104. 结果是什么? +###### 104. 结果是什么? ```javascript Promise.resolve(5) @@ -3328,15 +3328,15 @@ Promise.resolve(5) #### 答案: C -我们可以将我们想要的任何类型的值传递`Promise.resolve`,无论是否`promise`。 该方法本身返回带有已解析值的`Promise` (``)。 如果您传递常规函数,它将是具有常规值的已解决`promise`。 如果你通过了promise,它将是一个已经resolved的且带有传的值的promise。 +我们可以将我们想要的任何类型的值传递`Promise.resolve`,无论是否`promise`。 该方法本身返回带有已解析值的`Promise` (``)。 如果您传递常规函数,它将是具有常规值的已解决`promise`。 如果你通过了 promise,它将是一个已经 resolved 的且带有传的值的 promise。 -上述情况,我们传了数字5,因此返回一个resolved状态的promise,resolve值为`5` +上述情况,我们传了数字 5,因此返回一个 resolved 状态的 promise,resolve 值为`5`

-###### 105. 输出什么? +###### 105. 输出什么? ```javascript function compareMembers(person1, person2 = person) { @@ -3364,18 +3364,18 @@ compareMembers(person) 对象通过引用传递。 当我们检查对象的严格相等性(===)时,我们正在比较它们的引用。 -我们将“person2”的默认值设置为“person”对象,并将“person”对象作为“person1”的值传递。 +我们将 “person2” 的默认值设置为 “person” 对象,并将 “person” 对象作为 “person1” 的值传递。 这意味着两个值都引用内存中的同一位置,因此它们是相等的。 -运行“ else”语句中的代码块,并记录`They are the same!` 。 +运行 “ else” 语句中的代码块,并记录`They are the same!` 。

--- -###### 106. 输出什么? +###### 106. 输出什么? ```javascript @@ -3402,12 +3402,12 @@ console.log(colorConfig.colors[1]) #### 答案: D -在JavaScript中,我们有两种访问对象属性的方法:括号表示法或点表示法。 在此示例中,我们使用点表示法(`colorConfig.colors`)代替括号表示法(`colorConfig [“ colors”]`)。 +在 JavaScript 中,我们有两种访问对象属性的方法:括号表示法或点表示法。 在此示例中,我们使用点表示法(`colorConfig.colors`)代替括号表示法(`colorConfig [“ colors”]`)。 -使用点表示法,JavaScript会尝试使用该确切名称在对象上查找属性。 在此示例中,JavaScript尝试在colorconfig对象上找到名为colors的属性。 没有名为“colors”的属性,因此返回“undefined”。 +使用点表示法,JavaScript 会尝试使用该确切名称在对象上查找属性。 在此示例中,JavaScript 尝试在 colorconfig 对象上找到名为 colors 的属性。 没有名为 “colors” 的属性,因此返回 “undefined”。 然后,我们尝试使用`[1]`访问第一个元素的值。 我们无法对未定义的值执行此操作,因此会抛出`Cannot read property '1' of undefined`。 -JavaScript解释(或取消装箱)语句。 当我们使用方括号表示法时,它会看到第一个左方括号`[`并一直进行下去,直到找到右方括号`]`。 只有这样,它才会评估该语句。 如果我们使用了colorConfig [colors [1]],它将返回colorConfig对象上red属性的值。 +JavaScript 解释(或取消装箱)语句。 当我们使用方括号表示法时,它会看到第一个左方括号`[`并一直进行下去,直到找到右方括号`]`。 只有这样,它才会评估该语句。 如果我们使用了 colorConfig [colors [1]],它将返回 colorConfig 对象上 red 属性的值。

@@ -3415,7 +3415,7 @@ JavaScript解释(或取消装箱)语句。 当我们使用方括号表示法 --- -###### 107. 输出什么? +###### 107. 输出什么? ```javascript console.log('❤️' === '❤️') @@ -3429,14 +3429,14 @@ console.log('❤️' === '❤️') #### 答案: A -在内部,表情符号是unicode。 heat表情符号的unicode是`“ U + 2764 U + FE0F”`。 对于相同的表情符号,它们总是相同的,因此我们将两个相等的字符串相互比较,这将返回true。 +在内部,表情符号是 unicode。 heat 表情符号的 unicode 是`“ U + 2764 U + FE0F”`。 对于相同的表情符号,它们总是相同的,因此我们将两个相等的字符串相互比较,这将返回 true。

--- -###### 108. 哪些方法修改了原数组? +###### 108. 哪些方法修改了原数组? ```javascript @@ -3460,7 +3460,7 @@ emojis.splice(1, 2, '✨') #### 答案: D -使用`splice`方法,我们通过删除,替换或添加元素来修改原始数组。 在这种情况下,我们从索引1中删除了2个元素(我们删除了`'🥑'`和`'😍'`),同时添加了✨emoji表情。 +使用`splice`方法,我们通过删除,替换或添加元素来修改原始数组。 在这种情况下,我们从索引 1 中删除了 2 个元素(我们删除了`'🥑'`和`'😍'`),同时添加了✨emoji 表情。 `map`,`filter`和`slice`返回一个新数组,`find`返回一个元素,而`reduce`返回一个减小的值。 @@ -3469,7 +3469,7 @@ emojis.splice(1, 2, '✨') --- -###### 109. 输出什么? +###### 109. 输出什么? ```javascript const food = ['🍕', '🍫', '🥑', '🍔'] @@ -3490,16 +3490,16 @@ console.log(food) #### 答案: A -我们将`info`对象上的`favoriteFood`属性的值设置为披萨表情符号“🍕”的字符串。字符串是原始数据类型。在JavaScript中,原始数据类型通过值起作用 +我们将`info`对象上的`favoriteFood`属性的值设置为披萨表情符号 “🍕” 的字符串。字符串是原始数据类型。在 JavaScript 中,原始数据类型通过值起作用 -在这种情况下,我们将`info`对象上的`favoriteFood`属性的值设置为等于`food`数组中的第一个元素的值,字符串为披萨表情符号(`'🍕'` )。字符串是原始数据类型,并且通过值进行交互,我们更改`info`对象上`favoriteFood`属性的值。 food数组没有改变,因为favoriteFood的值只是该数组中第一个元素的值的复制,并且与该元素上的元素没有相同的内存引用食物`[0]`。当我们记录食物时,它仍然是原始数组`['🍕','🍫','🥑','🍔']`。 +在这种情况下,我们将`info`对象上的`favoriteFood`属性的值设置为等于`food`数组中的第一个元素的值,字符串为披萨表情符号(`'🍕'` )。字符串是原始数据类型,并且通过值进行交互,我们更改`info`对象上`favoriteFood`属性的值。 food 数组没有改变,因为 favoriteFood 的值只是该数组中第一个元素的值的复制,并且与该元素上的元素没有相同的内存引用食物`[0]`。当我们记录食物时,它仍然是原始数组`['🍕','🍫','🥑','🍔']`。

--- -###### 110. 这个函数干了什么? +###### 110. 这个函数干了什么? ```javascript JSON.parse() @@ -3515,18 +3515,18 @@ JSON.parse() #### 答案: A -使用`JSON.parse()`方法,我们可以将JSON字符串解析为JavaScript值。 +使用`JSON.parse()`方法,我们可以将 JSON 字符串解析为 JavaScript 值。 ```javascript -// 将数字字符串化为有效的JSON,然后将JSON字符串解析为JavaScript值: +// 将数字字符串化为有效的 JSON,然后将 JSON 字符串解析为 JavaScript 值: const jsonNumber = JSON.stringify(4) // '4' JSON.parse(jsonNumber) // 4 -// 将数组值字符串化为有效的JSON,然后将JSON字符串解析为JavaScript值: +// 将数组值字符串化为有效的 JSON,然后将 JSON 字符串解析为 JavaScript 值: const jsonArray = JSON.stringify([1, 2, 3]) // '[1, 2, 3]' JSON.parse(jsonArray) // [1, 2, 3] -// 将对象字符串化为有效的JSON,然后将JSON字符串解析为JavaScript值: +// 将对象字符串化为有效的 JSON,然后将 JSON 字符串解析为 JavaScript 值: const jsonArray = JSON.stringify({ name: "Lydia" }) // '{"name":"Lydia"}' JSON.parse(jsonArray) // { name: 'Lydia' } ``` @@ -3536,7 +3536,7 @@ JSON.parse(jsonArray) // { name: 'Lydia' } --- -###### 111. 输出什么? +###### 111. 输出什么? ```javascript let name = 'Lydia' @@ -3561,9 +3561,9 @@ getName() 每个函数都有其自己的执行上下文。 `getName`函数首先在其自身的上下文(范围)内查找,以查看其是否包含我们尝试访问的变量`name`。 上述情况,`getName`函数包含其自己的`name`变量:我们用`let`关键字和`Sarah`的值声明变量`name`。 -带有`let`关键字(和`const`)的变量被提升,但是与`var`不同,它不会被***初始化***。 在我们声明(初始化)它们之前,无法访问它们。 这称为“暂时性死区”。 当我们尝试在声明变量之前访问变量时,JavaScript会抛出`ReferenceError: Cannot access 'name' before initialization`。 +带有`let`关键字(和`const`)的变量被提升,但是与`var`不同,它不会被*** 初始化***。 在我们声明(初始化)它们之前,无法访问它们。 这称为 “暂时性死区”。 当我们尝试在声明变量之前访问变量时,JavaScript 会抛出`ReferenceError: Cannot access 'name' before initialization`。 -如果我们不在`getName`函数中声明`name`变量,则javascript引擎会查看原型链。会找到其外部作用域有一个名为`name`的变量,其值为`Lydia`。 在这种情况下,它将打印`Lydia`: +如果我们不在`getName`函数中声明`name`变量,则 javascript 引擎会查看原型链。会找到其外部作用域有一个名为`name`的变量,其值为`Lydia`。 在这种情况下,它将打印`Lydia`: ```javascript let name = 'Lydia' @@ -3608,16 +3608,16 @@ console.log(two.next().value) #### 答案: C -通过 `yield` 关键字, 我们在 `Generator` 函数里执行`yield`表达式. 通过 `yield*` 关键字, 我们可以在一个`Generator` 函数里面执行(`yield`表达式)另一个 `Generator` 函数, 或可遍历的对象 (如数组). +通过 `yield` 关键字,我们在 `Generator` 函数里执行`yield`表达式。通过 `yield*` 关键字,我们可以在一个`Generator` 函数里面执行(`yield`表达式)另一个 `Generator` 函数,或可遍历的对象 (如数组). -在函数 `generatorOne` 中, 我们通过 `yield` 关键字 yield 了一个完整的数组 `['a', 'b', 'c']`。函数`one`通过`next`方法返回的对象的`value` 属性的值 (`one.next().value`) 等价于数组 `['a', 'b', 'c']`. +在函数 `generatorOne` 中,我们通过 `yield` 关键字 yield 了一个完整的数组 `['a', 'b', 'c']`。函数`one`通过`next`方法返回的对象的`value` 属性的值 (`one.next().value`) 等价于数组 `['a', 'b', 'c']`. ```javascript console.log(one.next().value) // ['a', 'b', 'c'] console.log(one.next().value) // undefined ``` -在函数 `generatorTwo` 中, 我们使用 `yield*` 关键字。就相当于函数`two`第一个`yield`的值, 等价于在迭代器中第一个 `yield` 的值。数组`['a', 'b', 'c']`就是这个迭代器. 第一个 `yield` 的值就是 `a`, 所以我们第一次调用 `two.next().value`时, 就返回`a`。 +在函数 `generatorTwo` 中,我们使用 `yield*` 关键字。就相当于函数`two`第一个`yield`的值,等价于在迭代器中第一个 `yield` 的值。数组`['a', 'b', 'c']`就是这个迭代器。第一个 `yield` 的值就是 `a`,所以我们第一次调用 `two.next().value`时,就返回`a`。 ```javascript console.log(two.next().value) // 'a' @@ -3647,14 +3647,14 @@ console.log(`${(x => x)('I love')} to program`) #### 答案: A -带有模板字面量的表达式首先被执行。相当于字符串会包含表达式,这个立即执行函数 `(x => x)('I love')` 返回的值. 我们向箭头函数 `x => x` 传递 `'I love'` 作为参数。`x` 等价于返回的 `'I love'`。这就是结果 `I love to program`。 +带有模板字面量的表达式首先被执行。相当于字符串会包含表达式,这个立即执行函数 `(x => x)('I love')` 返回的值。我们向箭头函数 `x => x` 传递 `'I love'` 作为参数。`x` 等价于返回的 `'I love'`。这就是结果 `I love to program`。

--- -###### 114. 将会发生什么? +###### 114. 将会发生什么? ```javascript let config = { @@ -3676,7 +3676,7 @@ config = null #### 答案: C -一般情况下当我们将对象赋值为 `null`, 那些对象会被进行 _垃圾回收(garbage collected)_ 因为已经没有对这些对象的引用了。然而,`setInterval`的参数是一个箭头函数(所以上下文绑定到对象 `config` 了),回调函数仍然保留着对 `config`的引用。只要存在引用,对象就不会被垃圾回收。因为没有被垃圾回收,`setInterval` 的回调每1000ms (1s)会被调用一次。 +一般情况下当我们将对象赋值为 `null`,那些对象会被进行 _垃圾回收(garbage collected)_ 因为已经没有对这些对象的引用了。然而,`setInterval`的参数是一个箭头函数(所以上下文绑定到对象 `config` 了),回调函数仍然保留着对 `config`的引用。只要存在引用,对象就不会被垃圾回收。因为没有被垃圾回收,`setInterval` 的回调每 1000ms (1s) 会被调用一次。

@@ -3709,7 +3709,7 @@ myMap.get(() => 'greeting') #### 答案: B -当通过 `set` 方法添加一个键值对,一个传递给 `set`方法的参数将会是键名,第二个参数将会是值。在这个case里,键名为 _函数_ `() => 'greeting'`,值为`'Hello world'`。 `myMap` 现在就是 `{ () => 'greeting' => 'Hello world!' }`。 +当通过 `set` 方法添加一个键值对,一个传递给 `set`方法的参数将会是键名,第二个参数将会是值。在这个 case 里,键名为 _函数_ `() => 'greeting'`,值为`'Hello world'`。 `myMap` 现在就是 `{ () => 'greeting' => 'Hello world!' }`。 1 是错的,因为键名不是 `'greeting'` 而是 `() => 'greeting'`。 3 是错的,因为我们给`get` 方法传递了一个新的函数。对象受 _引用_ 影响。函数也是对象,因此两个函数严格上并不等价,尽管他们相同:他们有两个不同的内存引用地址。 @@ -3751,9 +3751,9 @@ console.log(person) 函数 `changeAge` 和函数 `changeAgeAndName` 有着不同的参数,定义一个 _新_ 生成的对象 `{ ...person }`。这个对象有着所有 `person` 对象 中 k/v 值的副本。 -首项, 我们调用 `changeAge` 函数并传递 `person` 对象作为它的参数。这个函数对 `age` 属性进行加一操作。`person` 现在是 `{ name: "Lydia", age: 22 }`。 +首项,我们调用 `changeAge` 函数并传递 `person` 对象作为它的参数。这个函数对 `age` 属性进行加一操作。`person` 现在是 `{ name: "Lydia", age: 22 }`。 -然后,我们调用函数 `changeAgeAndName` ,然而我们没有传递参数。取而代之,`x` 的值等价 _new_ 生成的对象: `{ ...person }`。因为它是一个新生成的对象,它并不会对对象 `person` 造成任何副作用。`person` 仍然等价于 `{ name: "Lydia", age: 22 }`。 +然后,我们调用函数 `changeAgeAndName` ,然而我们没有传递参数。取而代之,`x` 的值等价 _new_ 生成的对象:`{ ...person }`。因为它是一个新生成的对象,它并不会对对象 `person` 造成任何副作用。`person` 仍然等价于 `{ name: "Lydia", age: 22 }`。

@@ -3845,7 +3845,7 @@ console.log(member.getLastName?.()); 通过 ES10 或 TS3.7+[可选链操作符 `?.`](https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Operators/%E5%8F%AF%E9%80%89%E9%93%BE),我们不再需要显式检测更深层的嵌套值是否有效。如果我们尝试获取 `undefined` 或 `null` 的值 (_nullish_),表达将会短路并返回 `undefined`. `person.pet?.name`: `person` 有一个名为 `pet` 的属性: `person.pet` 不是 nullish。它有个名为 `name` 的属性,并返回字符串 `Mara`。 -`person.pet?.family?.name`: `person` 有一个名为 `pet` 的属性: `person.pet` 不是 nullish. `pet` _并没有_ 一个名为 `family` 的属性, `person.pet.family` 是 nullish。表达式返回 `undefined`。 +`person.pet?.family?.name`: `person` 有一个名为 `pet` 的属性: `person.pet` 不是 nullish. `pet` _并没有_ 一个名为 `family` 的属性,`person.pet.family` 是 nullish。表达式返回 `undefined`。 `person.getFullName?.()`: `person` 有一个名为 `getFullName` 的属性: `person.getFullName()` 不是 nullish 并可以被调用,返回字符串 `Lydia Hallie`。 `member.getLastName?.()`: 变量`member` 不存在,因此会抛出错误`ReferenceError`。 @@ -3876,14 +3876,14 @@ if (groceries.indexOf("banana")) { #### 答案: B -我们传递了一个状态 `groceries.indexOf("banana")` 给if条件语句。`groceries.indexOf("banana")` 返回 `0`, 一个 falsy 的值。因为if条件语句的状态为 falsy,`else` 块区内的代码执行,并且 `We don't have to buy bananas!` 被输出. +我们传递了一个状态 `groceries.indexOf("banana")` 给 if 条件语句。`groceries.indexOf("banana")` 返回 `0`, 一个 falsy 的值。因为 if 条件语句的状态为 falsy,`else` 块区内的代码执行,并且 `We don't have to buy bananas!` 被输出。

--- -###### 121. 输出什么? +###### 121. 输出什么? ```javascript const config = { @@ -3941,7 +3941,7 @@ console.log(!typeof name === "string"); --- -###### 123. 输出什么? +###### 123. 输出什么? ```javascript const add = x => y => z => { @@ -3996,7 +3996,7 @@ async function* range(start, end) { #### 答案: C -我们给 函数range 传递: `Promise{1}`, `Promise{2}`, `Promise{3}`,Generator 函数 `range` 返回一个全是 async object promise 数组。我们将 async object 赋值给变量 `gen`,之后我们使用`for await ... of` 进行循环遍历。我们将返回的 Promise 实例赋值给 `item`: 第一个返回 `Promise{1}`, 第二个返回 `Promise{2}`,之后是 `Promise{3}`。因为我们正 _awaiting_ `item` 的值,resolved 状态的 promsie,promise数组的resolved _值_ 以此为: `1`,`2`,`3`. +我们给 函数 range 传递: `Promise{1}`, `Promise{2}`, `Promise{3}`,Generator 函数 `range` 返回一个全是 async object promise 数组。我们将 async object 赋值给变量 `gen`,之后我们使用`for await ... of` 进行循环遍历。我们将返回的 Promise 实例赋值给 `item`: 第一个返回 `Promise{1}`, 第二个返回 `Promise{2}`,之后是 `Promise{3}`。因为我们正 _awaiting_ `item` 的值,resolved 状态的 promsie,promise 数组的 resolved _值_ 以此为: `1`,`2`,`3`.

@@ -4148,7 +4148,7 @@ getInfo(); #### 答案: D -通过 `const` 关键字声明的变量在被初始化之前不可被引用:这被称之为 _暂时性死区_。在函数 `getInfo` 中, 变量 `randomValue` 声明在`getInfo` 的作用域的此法环境中。在想要对 `typeof randomValue` 进行log之前,变量 `randomValue` 仍未被初始化: 错误`ReferenceError` 被抛出! JS引擎并不会根据作用域链网上寻找该变量,因为我们已经在 `getInfo` 函数中声明了 `randomValue` 变量。 +通过 `const` 关键字声明的变量在被初始化之前不可被引用:这被称之为 _暂时性死区_。在函数 `getInfo` 中,变量 `randomValue` 声明在`getInfo` 的作用域的此法环境中。在想要对 `typeof randomValue` 进行 log 之前,变量 `randomValue` 仍未被初始化: 错误`ReferenceError` 被抛出!JS 引擎并不会根据作用域链网上寻找该变量,因为我们已经在 `getInfo` 函数中声明了 `randomValue` 变量。

@@ -4206,7 +4206,7 @@ console.log(emojis.flat(1)); #### 答案: B -通过方法 `flat`, 我们可以创建一个新的, 已被扁平化的数组。被扁平化的深度取决于我们传递的值。在这个case里,我们传递了值 `1` (并不必要,这是默认值),相当于只有第一层的数组才会被连接。即这个 case 里的 `['🥑']` and `['✨', '✨', ['🍕', '🍕']]`。连接这两个数组得到结果 `['🥑', '✨', '✨', ['🍕', '🍕']]`. +通过方法 `flat`, 我们可以创建一个新的,已被扁平化的数组。被扁平化的深度取决于我们传递的值。在这个 case 里,我们传递了值 `1` (并不必要,这是默认值),相当于只有第一层的数组才会被连接。即这个 case 里的 `['🥑']` and `['✨', '✨', ['🍕', '🍕']]`。连接这两个数组得到结果 `['🥑', '✨', '✨', ['🍕', '🍕']]`.

@@ -4246,13 +4246,13 @@ console.log(counterOne.count); #### 答案: D -`counterOne` 是类 `Counter` 的一个实例。类 Counter 包含一个`count` 属性在它的构造函数里, 和一个 `increment` 方法。首先,我们通过 `counterOne.increment()` 调用方法 `increment` 两次。现在, `counterOne.count` 为 `2`. +`counterOne` 是类 `Counter` 的一个实例。类 Counter 包含一个`count` 属性在它的构造函数里, 和一个 `increment` 方法。首先,我们通过 `counterOne.increment()` 调用方法 `increment` 两次。现在,`counterOne.count` 为 `2`. 然后,我们创建一个新的变量 `counterTwo` 并将 `counterOne` 的引用地址赋值给它。因为对象受引用地址的影响,我们刚刚创建了一个新的对象,其引用地址和 `counterOne` 的等价。因此它们指向同一块内存地址,任何对其的副作用都会影响 `counterTwo`。现在 `counterTwo.count` 为 `2`。 -我们调用 `counterTwo.increment()` 将 `count` 的值设为 `3`。然后,我们打印 `counterOne` 里的count,结果为 `3`。 +我们调用 `counterTwo.increment()` 将 `count` 的值设为 `3`。然后,我们打印 `counterOne` 里的 count,结果为 `3`。 @@ -4293,9 +4293,9 @@ funcTwo(); #### 答案: D -首先,我们调用 `funcOne`。在函数 `funcOne` 的第一行,我们调用`myPromise` promise _异步操作_。当JS引擎在忙于执行 promise,它继续执行函数 `funcOne`。下一行 _异步操作_ `setTimeout`,其回调函数被 Web API 调用。 (详情请参考我关于event loop的文章.) +首先,我们调用 `funcOne`。在函数 `funcOne` 的第一行,我们调用`myPromise` promise _异步操作_。当 JS 引擎在忙于执行 promise,它继续执行函数 `funcOne`。下一行 _异步操作_ `setTimeout`,其回调函数被 Web API 调用。 (详情请参考我关于 event loop 的文章.) -promise 和 timeout 都是异步操作,函数继续执行当JS引擎忙于执行promise 和 处理 `setTimeout` 的回调。相当于 `Last line!` 首先被输出, 因为它不是异步操作。执行完 `funcOne` 的最后一行,promise 状态转变为 resolved,`Promise!` 被打印。然而,因为我们调用了 `funcTwo()`, 调用栈不为空,`setTimeout` 的回调仍不能入栈。 +promise 和 timeout 都是异步操作,函数继续执行当 JS 引擎忙于执行 promise 和 处理 `setTimeout` 的回调。相当于 `Last line!` 首先被输出, 因为它不是异步操作。执行完 `funcOne` 的最后一行,promise 状态转变为 resolved,`Promise!` 被打印。然而,因为我们调用了 `funcTwo()`,调用栈不为空,`setTimeout` 的回调仍不能入栈。 我们现在处于 `funcTwo`,先 _awaiting_ myPromise。通过 `await` 关键字, 我们暂停了函数的执行直到 promise 状态变为 resolved (或 rejected)。然后,我们输出 `res` 的 awaited 值(因为 promise 本身返回一个 promise)。 接着输出 `Promise!`。 @@ -4392,9 +4392,9 @@ person.name; 使用 Proxy 对象,我们可以给一个对象添加自定义行为。在这个 case,我们传递一个包含以下属性的对象 `handler` : `set` and `get`。每当我们 _设置_ 属性值时 `set` 被调用,每当我们 _获取_ 时 `get` 被调用。 -第一个参数是一个空对象 `{}`,作为 `person` 的值。对于这个对象,自定义行为被定义在对象 `handler`。如果我们向对象 `person` 添加属性,`set` 将被调用。如果我们获取 `person` 的属性, `get` 将被调用。 +第一个参数是一个空对象 `{}`,作为 `person` 的值。对于这个对象,自定义行为被定义在对象 `handler`。如果我们向对象 `person` 添加属性,`set` 将被调用。如果我们获取 `person` 的属性,`get` 将被调用。 -首先,我们向 proxy 对象(`person.name = "Lydia"`)添加一个属性 `name`。`set` 被调用并输出 `"Added a new property!"`。 +首先,我们向 proxy 对象 (`person.name = "Lydia"`) 添加一个属性 `name`。`set` 被调用并输出 `"Added a new property!"`。 然后,我们获取 proxy 对象的一个属性,对象 handler 的属性 `get` 被调用。输出 `"Accessed a property!"`。 @@ -4485,9 +4485,9 @@ myFunc(3); #### 答案: A -首先我们不传递任何参数调用 `myFunc()`。因为我们没有传递参数,`num` 和 `value` 获取它们各自的默认值:num 为 `2`, 而 `value` 为函数 `add` 的返回值。对于函数 `add`,我们传递值为2的 `num` 作为参数。函数 `add` 返回 `4` 作为 `value` 的值。 +首先我们不传递任何参数调用 `myFunc()`。因为我们没有传递参数,`num` 和 `value` 获取它们各自的默认值:num 为 `2`,而 `value` 为函数 `add` 的返回值。对于函数 `add`,我们传递值为 2 的 `num` 作为参数。函数 `add` 返回 `4` 作为 `value` 的值。 -然后,我们调用 `myFunc(3)` 并传递值 `3` 参数 `num` 的值。我们没有给 `value` 传递值。因为我们没有给参数 `value` 传递值,它获取默认值:函数 `add` 的返回值。对于函数 `add`,我们传递值为3的 `num`给它。函数 `add` 返回 `6` 作为 `value` 的值。 +然后,我们调用 `myFunc(3)` 并传递值 `3` 参数 `num` 的值。我们没有给 `value` 传递值。因为我们没有给参数 `value` 传递值,它获取默认值:函数 `add` 的返回值。对于函数 `add`,我们传递值为 3 的 `num`给它。函数 `add` 返回 `6` 作为 `value` 的值。

@@ -4525,7 +4525,7 @@ console.log(counter.#number) #### 答案: D -在 ES2020 中,通过 `#` 我们可以给 class 添加私有变量。在 class 的外部我们无法获取该值。当我们尝试输出 `counter.#number`,语法错误被抛出:我们无法在 class `Counter` 外部获取它! +在 ES2020 中,通过 `#` 我们可以给 class 添加私有变量。在 class 的外部我们无法获取该值。当我们尝试输出 `counter.#number`,语法错误被抛出:我们无法在 class `Counter` 外部获取它!

@@ -4569,7 +4569,7 @@ obj.next(); // { value: "Lisa", done: false } 为了遍历 `teams` 数组中对象的属性 `members` 中的每一项,我们需要将 `teams[i].members` 传递给 Generator 函数 `getMembers`。Generator 函数返回一个 generator 对象。为了遍历这个 generator 对象中的每一项,我们需要使用 `yield*`. -如果我们没有写 `yield`,`return yield` 或者 `return`,整个 Generator 函数不会第一时间 return 当我们调用 `next` 方法. +如果我们没有写 `yield`,`return yield` 或者 `return`,整个 Generator 函数不会第一时间 return 当我们调用 `next` 方法。

@@ -4650,7 +4650,7 @@ const pet = new Flamingo(); #### 答案: B -我们创建了类 `Flamingo` 的实例 `pet`。当我们实例化这个实例,`Flamingo` 中的 `constructor` 被调用。首相,输出 `"I'm pink. 🌸"`, 之后我们调用`super()`。`super()` 调用父类的构造函数,`Bird`。`Bird` 的构造函数被调用,并输出 `"I'm a bird. 🦢"`。 +我们创建了类 `Flamingo` 的实例 `pet`。当我们实例化这个实例,`Flamingo` 中的 `constructor` 被调用。首相,输出 `"I'm pink. 🌸"`,之后我们调用`super()`。`super()` 调用父类的构造函数,`Bird`。`Bird` 的构造函数被调用,并输出 `"I'm a bird. 🦢"`。

@@ -4678,7 +4678,7 @@ const emojis = ["🎄", "🎅🏼", "🎁", "⭐"]; #### 答案: D -`const` 关键字意味着我们不能 _重定义_ 变量中的值,它 _仅可读_。而然,值本身不可修改。数组 `emojis` 中的值可被修改,如 push 新的值, 拼接,又或者将数组的长度设置为0。 +`const` 关键字意味着我们不能 _重定义_ 变量中的值,它 _仅可读_。而然,值本身不可修改。数组 `emojis` 中的值可被修改,如 push 新的值,拼接,又或者将数组的长度设置为 0。

@@ -4706,7 +4706,7 @@ const person = { #### 答案: C -对象默认并不是可迭代的。如果迭代规则被定义,则一个对象是可迭代的(An iterable is an iterable if the iterator protocol is present)。我们可以通过添加迭代器symbol `[Symbol.iterator]` 来定义迭代规则,其返回一个 generator 对象,比如说构建一个 generator 函数 `*[Symbol.iterator]() {}`。如果我们想要返回数组 `["Lydia Hallie", 21]`: `yield* Object.values(this)`,这个 generator 函数一定要 yield 对象 `person` 的`Object.values`。 +对象默认并不是可迭代的。如果迭代规则被定义,则一个对象是可迭代的(An iterable is an iterable if the iterator protocol is present)。我们可以通过添加迭代器 symbol `[Symbol.iterator]` 来定义迭代规则,其返回一个 generator 对象,比如说构建一个 generator 函数 `*[Symbol.iterator]() {}`。如果我们想要返回数组 `["Lydia Hallie", 21]`: `yield* Object.values(this)`,这个 generator 函数一定要 yield 对象 `person` 的`Object.values`。

@@ -4734,7 +4734,7 @@ console.log(count) #### 答案: C -在 `forEach` 循环内部的 `if` 会判断 `num` 的值是truthy或者是falsy。因为 `nums` 数组的第一个数字是 `0`,一个falsy值, `if` 语句代码块不会被执行。`count` 仅仅在 `nums` 数组的其他3个数字 `1`,`2`,`3` 时加1。因为 `count` 执行了3次加 `1` 运算,所以 `count` 的值为 `3`。 +在 `forEach` 循环内部的 `if` 会判断 `num` 的值是 truthy 或者是 falsy。因为 `nums` 数组的第一个数字是 `0`,一个 falsy 值, `if` 语句代码块不会被执行。`count` 仅仅在 `nums` 数组的其他 3 个数字 `1`,`2`,`3` 时加 1。因为 `count` 执行了 3 次加 `1` 运算,所以 `count` 的值为 `3`。

@@ -4765,11 +4765,11 @@ getFruit([['🍍'], ['🍊', '🍌']]) `?` 允许我们去选择性地访问对象内部更深层的嵌套属性。 我们尝试打印 `fruits` 数组索引值为 `1` 的子数组内部的索引值为 `1` 的元素。 如果在 `fruits` 数组索引值 为 `1` 的位置不存在元素,会直接返回 `undefined`。 如果 `fruits` 数组在索引值为 `1` 的位置存在元素,但是子数组在索引值为 `1` 的位置不存在元素,也会返回 `undefined`。 -首先,我们尝试打印 `[['🍊', '🍌'], ['🍍']]` 的子数组 `['🍍']` 的第2个元素。这个子数组只包含一个元素,也就意味着在索引值为 `1` 的位置不存在元素,所以返回的是 `undefined` 。 +首先,我们尝试打印 `[['🍊', '🍌'], ['🍍']]` 的子数组 `['🍍']` 的第 2 个元素。这个子数组只包含一个元素,也就意味着在索引值为 `1` 的位置不存在元素,所以返回的是 `undefined` 。 其次,我们在没有传入任何参数调用了 `getFruits` 函数,也就意味着形参 `fruits` 的默认值为`undefined`。因为我们选择性地链接了 `fruits` 在索引值为 `1` 的元素,因为在索引值为 `1` 的位置不存在元素,因此返回的是 `undefined` 。 -最后,我们尝试打印 `['🍍'], ['🍊', '🍌']` 的子数组 `['🍊', '🍌']` 的第2个元素。子数组索引值为 `1`的位置为 `🍌` ,因此它被打印出了。 +最后,我们尝试打印 `['🍍'], ['🍊', '🍌']` 的子数组 `['🍊', '🍌']` 的第 2 个元素。子数组索引值为 `1`的位置为 `🍌` ,因此它被打印出了。

@@ -4805,14 +4805,14 @@ console.log(calc.count) #### 答案: A -我们设置 `calc` 变量为 `Calc` 类的一个新实例。 然后,我们初始化一个 `Calc` 的新实例,而且调用了这个实例的 `increase` 方法。因为count属性是在 `Calc` class的constructor内部的,所以count属性不会在 `Calc` 的原型链上共享出去。这就意味着calc实例的count值不会被更新,count仍然是 `0`。 +我们设置 `calc` 变量为 `Calc` 类的一个新实例。 然后,我们初始化一个 `Calc` 的新实例,而且调用了这个实例的 `increase` 方法。因为 count 属性是在 `Calc` class 的 constructor 内部的,所以 count 属性不会在 `Calc` 的原型链上共享出去。这就意味着 calc 实例的 count 值不会被更新,count 仍然是 `0`。

--- -###### 148. 输出什么? +###### 148. 输出什么? ```javascript const user = { @@ -4847,14 +4847,14 @@ console.log(updatedUser === user) #### 答案: B - `updateUser` 函数更新user的 `email` 和 `password` 属性的值, 如果它们的值传入函数, 函数返回的就是 `user` 对象。 `updateUser` 函数的返回值是 `user` 对象,意味着updatedUser的值与 `user` 指向的是同一个 `user` 对象。`updatedUser === user` 为 `true`. + `updateUser` 函数更新 user 的 `email` 和 `password` 属性的值, 如果它们的值传入函数, 函数返回的就是 `user` 对象。 `updateUser` 函数的返回值是 `user` 对象,意味着 updatedUser 的值与 `user` 指向的是同一个 `user` 对象。`updatedUser === user` 为 `true`.

--- -###### 149. 输出什么? +###### 149. 输出什么? ```javascript const fruit = ['🍌', '🍊', '🍎'] @@ -4876,16 +4876,16 @@ console.log(fruit) #### 答案: C -首先,我们在fruit数组上调用 `slice` 方法。 slice方法不会修改原始数组,但是会返回从数组切片下来的值:香蕉emoji。 -其次,我们在fruit数组上调用 `splice` 方法。 splice方法会修改原始数组,也就意味着fruit数组此时为 `['🍊', '🍎']`。 -最后,我们在fruit数组上调用 `unshift` 方法,通过添加一个值的方式改变了原始数组,添加的是'🍇',它成为了数组的第一个元素。现在fruit数组的组成为 `['🍇', '🍊', '🍎']`。 +首先,我们在 fruit 数组上调用 `slice` 方法。 slice 方法不会修改原始数组,但是会返回从数组切片下来的值:香蕉 emoji。 +其次,我们在 fruit 数组上调用 `splice` 方法。 splice 方法会修改原始数组,也就意味着 fruit 数组此时为 `['🍊', '🍎']`。 +最后,我们在 fruit 数组上调用 `unshift` 方法,通过添加一个值的方式改变了原始数组,添加的是'🍇',它成为了数组的第一个元素。现在 fruit 数组的组成为 `['🍇', '🍊', '🍎']`。

--- -###### 150. 输出什么? +###### 150. 输出什么? ```javascript const animals = {}; @@ -4912,7 +4912,7 @@ console.log(animals[dog]) 因为 `dog` 的值是一个对象, `animals[dog]` 实际上意味着我们创建了一个叫做 `"object Object"` 的属性来代表新的对象。 `animals["object Object"]` 现在等于 `{ emoji: "🐶", name: "Mara"}`。 -`cat` 也是一个对象,`animals[cat]` 实际上意味着我们在用新的cat的属性覆盖 `animals[``"``object Object``"``]` 的值。 +`cat` 也是一个对象,`animals[cat]` 实际上意味着我们在用新的 cat 的属性覆盖 `animals[``"``object Object``"``]` 的值。 打印 `animals[dog]`,实际上是`animals["object Object"]`,这是因为转化`dog`对象为一个字符串结果 `"object Object"` ,所以返回 `{ emoji: "🐈", name: "Sara" }`。 @@ -4921,7 +4921,7 @@ console.log(animals[dog]) --- -###### 151. 输出什么? +###### 151. 输出什么? ```javascript const user = { @@ -4952,7 +4952,7 @@ console.log(user.email) --- -###### 152. 输出什么? +###### 152. 输出什么? ```javascript const promise1 = Promise.resolve('First') @@ -4981,7 +4981,7 @@ runPromises() #### 答案: D - `Promise.all` 方法可以并行式运行promise。如果其中一个promise失败了,`Promise.all` 方法会带上被reject的promise的值_rejects_。在这个例子中, `promise3` 带着 `"Third"` 值reject。我们在调用 `runPromises` 时在 `runPromises` 函数内部的 `catch` 方法去捕获任意error从而捕获到被reject的值。因为 `promise3` 带着 `"Third"` 被reject,所以只有 `"Third"` 打印。 + `Promise.all` 方法可以并行式运行 promise。如果其中一个 promise 失败了,`Promise.all` 方法会带上被 reject 的 promise 的值_rejects_。在这个例子中, `promise3` 带着 `"Third"` 值 reject。我们在调用 `runPromises` 时在 `runPromises` 函数内部的 `catch` 方法去捕获任意 error 从而捕获到被 reject 的值。因为 `promise3` 带着 `"Third"` 被 reject,所以只有 `"Third"` 打印。

@@ -5010,16 +5010,16 @@ Object[method](keys.map((_, i) => { #### 答案: C - `fromEntries` 方法可以将二维数组转换为对象。在每个子数组的第一个元素是key,在每个子数组的第二个元素是value。在这个例子中,我们映射了 `keys` 数组,它返回了一个数组,数组的第一个元素为keys数组当前索引的值,第二个元素为values数组当前索引的值。 + `fromEntries` 方法可以将二维数组转换为对象。在每个子数组的第一个元素是 key,在每个子数组的第二个元素是 value。在这个例子中,我们映射了 `keys` 数组,它返回了一个数组,数组的第一个元素为 keys 数组当前索引的值,第二个元素为 values 数组当前索引的值。 -这样就创建了一个包含正确keys和values的子数组的数组,因此结果为`{ name: "Lydia", age: 22 }`。 +这样就创建了一个包含正确 keys 和 values 的子数组的数组,因此结果为`{ name: "Lydia", age: 22 }`。

--- -###### 154. 输出什么? +###### 154. 输出什么? ```javascript const createMember = ({ email, address = {}}) => { @@ -5046,14 +5046,14 @@ console.log(member) #### 答案: C - `address` 的默认值是一个空对象 `{}`。当我们设置 `member` 变量为 `createMember` 函数返回的对象,我们没有为address参数传值,意味着address的值为默认的空对象 `{}`。一个空对象是一个truthy值,意味着 `address ? address : null` 条件会返回 `true`。address的值为空对象 `{}`。 + `address` 的默认值是一个空对象 `{}`。当我们设置 `member` 变量为 `createMember` 函数返回的对象,我们没有为 address 参数传值,意味着 address 的值为默认的空对象 `{}`。一个空对象是一个 truthy 值,意味着 `address ? address : null` 条件会返回 `true`。address 的值为空对象 `{}`。

--- -###### 155. 输出什么? +###### 155. 输出什么? ```javascript let randomValue = { name: "Lydia" } @@ -5076,9 +5076,9 @@ if (!typeof randomValue === "string") { #### 答案: B - `if` 语句的条件判断 `!typeof randomValue` 的值是否等于 `"string"`。 `!` 操作符将这个值转化为一个布尔值。如果值是truthy的话,返回值会是 `false`,如果值是falsy,返回值会是 `true`。在这里, `typeof randomValue` 的返回值是一个truthy值 `"number"`,意味着 `!typeof randomValue` 的值是一个布尔值 `false`。 + `if` 语句的条件判断 `!typeof randomValue` 的值是否等于 `"string"`。 `!` 操作符将这个值转化为一个布尔值。如果值是 truthy 的话,返回值会是 `false`,如果值是 falsy,返回值会是 `true`。在这里, `typeof randomValue` 的返回值是一个 truthy 值 `"number"`,意味着 `!typeof randomValue` 的值是一个布尔值 `false`。 - `!typeof randomValue === "string"` 总是返回false,因为我们实际上是在执行 `false === "string"`。因为条件返回的是 `false`,所以 `else` 语句中的代码块会被运行,因此打印 `Yay it's a string!` 。 + `!typeof randomValue === "string"` 总是返回 false,因为我们实际上是在执行 `false === "string"`。因为条件返回的是 `false`,所以 `else` 语句中的代码块会被运行,因此打印 `Yay it's a string!` 。

From f01389879c006b6cdeb6358b28152640f1782540 Mon Sep 17 00:00:00 2001 From: Artur Carvalho Date: Fri, 3 Jun 2022 11:18:58 +0200 Subject: [PATCH 102/193] Correct typo referencable => referenceable --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 4cfa2556..d3934cbf 100644 --- a/README.md +++ b/README.md @@ -4161,7 +4161,7 @@ getInfo(); #### Answer: D -Variables declared with the `const` keyword are not referencable before their initialization: this is called the _temporal dead zone_. In the `getInfo` function, the variable `randomValue` is scoped in the functional scope of `getInfo`. On the line where we want to log the value of `typeof randomValue`, the variable `randomValue` isn't initialized yet: a `ReferenceError` gets thrown! The engine didn't go down the scope chain since we declared the variable `randomValue` in the `getInfo` function. +Variables declared with the `const` keyword are not referenceable before their initialization: this is called the _temporal dead zone_. In the `getInfo` function, the variable `randomValue` is scoped in the functional scope of `getInfo`. On the line where we want to log the value of `typeof randomValue`, the variable `randomValue` isn't initialized yet: a `ReferenceError` gets thrown! The engine didn't go down the scope chain since we declared the variable `randomValue` in the `getInfo` function.

From c7d14f6098725bb58a391a2addbf91b0b043f21a Mon Sep 17 00:00:00 2001 From: luciacenetiempo Date: Wed, 8 Jun 2022 19:52:49 +0200 Subject: [PATCH 103/193] Italian version I translated the original from English into Italian, so as to facilitate understanding for Italian devs --- it-IT/README-IT.md | 5138 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 5138 insertions(+) create mode 100644 it-IT/README-IT.md diff --git a/it-IT/README-IT.md b/it-IT/README-IT.md new file mode 100644 index 00000000..3efee591 --- /dev/null +++ b/it-IT/README-IT.md @@ -0,0 +1,5138 @@ +
+ +

Domande di JavaScript

+ +--- + +Posto domande a risposta multipla sulle mie [Instagram](https://www.instagram.com/theavocoder) **stories**, che poi posterò anche qui! Ultimo aggiornamento: 23 Maggio + +Da base ad avanzato: metti alla prova quanto conosci JavaScript, rinfresca un po' le tue conoscenze o preparati per il tuo colloquio di programmazione! :muscle: :rocket: Aggiorno regolarmente questo repository con nuove domande. Ho aggiunto le risposte nelle **sezioni compresse** sotto le domande, cliccaci sopra per espanderle. È solo per divertimento, buona fortuna! :heart: + + +Sentiti libero di contattarmi! 😊
+Instagram || Twitter || LinkedIn || Blog +
+ +| Sentiti libero di usarli in un progetto! 😃 Apprezzerei _molto_ un riferimento a questa repository, creo le domande e le spiegazioni (sì, sono triste lol) e la community mi aiuta tantissimo a mantenerlo e migliorarlo! 💪🏼 Grazie e buon divertimento! | + + +Traduzione a cura di: Lucia Cenetiempo +|---| + +--- + +
Vedi le 18 traduzioni disponibili 🇸🇦🇪🇬🇧🇦🇩🇪🇪🇸🇫🇷🇮🇩🇯🇵🇰🇷🇳🇱🇧🇷🇷🇺🇹🇭🇹🇷🇺🇦🇻🇳🇨🇳🇹🇼 +

+ +- [🇸🇦 العربية](./ar-AR/README_AR.md) +- [🇪🇬 اللغة العامية](./ar-EG/README_ar-EG.md) +- [🇧🇦 Bosanski](./bs-BS/README-bs_BS.md) +- [🇩🇪 Deutsch](./de-DE/README.md) +- [🇬🇧 English](../README.md) +- [🇪🇸 Español](./es-ES/README-ES.md) +- [🇫🇷 Français](./fr-FR/README_fr-FR.md) +- [🇮🇩 Indonesia](./id-ID/README.md) +- [🇯🇵 日本語](./ja-JA/README-ja_JA.md) +- [🇰🇷 한국어](./ko-KR/README-ko_KR.md) +- [🇳🇱 Nederlands](./nl-NL/README.md) +- [🇧🇷 Português Brasil](./pt-BR/README_pt_BR.md) +- [🇷🇺 Русский](./ru-RU/README.md) +- [🇹🇭 ไทย](./th-TH/README-th_TH.md) +- [🇹🇷 Türkçe](./tr-TR/README-tr_TR.md) +- [🇺🇦 Українська мова](./uk-UA/README.md) +- [🇻🇳 Tiếng Việt](./vi-VI/README-vi.md) +- [🇨🇳 简体中文](./zh-CN/README-zh_CN.md) +- [🇹🇼 繁體中文](./zh-TW/README_zh-TW.md) + +

+
+ +--- + +###### 1. Qual è l'output? + +```javascript +function sayHi() { + console.log(name); + console.log(age); + var name = 'Lydia'; + let age = 21; +} + +sayHi(); +``` + +- A: `Lydia` e `undefined` +- B: `Lydia` e `ReferenceError` +- C: `ReferenceError` e `21` +- D: `undefined` e `ReferenceError` + +
+Risposta +

+ +#### Risposta: D + +All'interno della funzione, dichiariamo prima la variabile `name` con la parola chiave `var`. Ciò significa che la variabile viene sollevata all'interno del codice (ovvero lo spazio di memoria viene impostato durante la fase di creazione) e viene inizializzata con il valore predefinito di `undefined`, finché non arriviamo effettivamente alla riga in cui la definiamo. +Al momento in cui proviamo ad eseguire il log della variabile `name` non l'abbiamo ancora dichiarata, quindi mantiene il valore di `undefined`. + +Le variabili dichiarate con la chiave `let` (o `const`) vengono sollevate, ma a differenza delle variabili dichiarate con `var`, non vengono inizializzate. Per questo motivo non sono accessibili prima della loro dichiarazione (dove le inizializzaimo). Questa è chiamata "temporal dead zone". Quando proviamo ad accedere alle variabili prima che vengano dichiarate, JavaScript genera un `ReferenceError`. + +

+
+ +--- + +###### 2. Qual è l'output? + +```javascript +for (var i = 0; i < 3; i++) { + setTimeout(() => console.log(i), 1); +} + +for (let i = 0; i < 3; i++) { + setTimeout(() => console.log(i), 1); +} +``` + +- A: `0 1 2` e `0 1 2` +- B: `0 1 2` e `3 3 3` +- C: `3 3 3` e `0 1 2` + +
Risposta +

+ +#### Risposta: C + +A causa della coda degli eventi in JavaScript la funzione di callback `setTimeout` viene chiamata _dopo_ che il loop è stato eseguito. Poiché la variabile `i` nel primo loop è stata dichiarata usando la chiave `var`, questo valore è globale. Durante il loop abbiamo incrementato ogni volta il valore di `i` di `1` usando l'operatore unario `++`. Quando è stata invocata la funzione di callback `setTimeout`, `i` nel primo esempio risultava sin dal principio uguale a `3`. + +Nel secondo loop, la variabile `i` è stata dichiarata usando la chiave `let`: le variabili dichiarate con la chiave `let` (e `const`) hanno lo scope del blocco (un blocco è qualsiasi cosa tra `{ }`). Durante ogni iterazione, `i` avrà un nuovo valore e ogni valore avrà lo scope all'interno del loop. + +

+
+ +--- + +###### 3. Qual è l'output? + +```javascript +const shape = { + radius: 10, + diameter() { + return this.radius * 2; + }, + perimeter: () => 2 * Math.PI * this.radius, +}; + +console.log(shape.diameter()); +console.log(shape.perimeter()); +``` + +- A: `20` e `62.83185307179586` +- B: `20` e `NaN` +- C: `20` e `63` +- D: `NaN` e `63` + +
Risposta +

+ +#### Risposta: B + +Il valore di `diameter` è una funzione regolare, mentre il vaore di `perimeter` è gemerato con una arrow function. + +Nelle arrow functions, la chiave `this` fa riferimento al suo scope interno a differenza delle funzioni regolari. Questo vuol dire che quando richiamiamo `perimeter` non stiamo facendo riferimento all'oggetto shape, ma al suo ambito circostantr (ad esempio window). + +Non troviamo quindi alcun valore `radius` in quell'oggetto e quindi viene restituito `NaN`. + +

+
+ +--- + +###### 4. Qual è l'output? + +```javascript ++true; +!'Lydia'; +``` + +- A: `1` and `false` +- B: `false` and `NaN` +- C: `false` and `false` + +
Risposta +

+ +#### Risposta: A + +Il + unario tenta di convertire un operando in un numero. `true` equivale ad `1` e `false` equivale a `0`. + +La stringa `'Lydia'` è un valore veritiero. Quello che in realtà ci stiamo chiedendo con `!'Lydia'` è "questo valore veritiero è falso?". Per cui la risposta è `false`. + +

+
+ +--- + +###### 5. Quale affermazione è vera? + +```javascript +const bird = { + size: 'small', +}; + +const mouse = { + name: 'Mickey', + small: true, +}; +``` + +- A: `mouse.bird.size` non è valido +- B: `mouse[bird.size]` non è valido +- C: `mouse[bird["size"]]` non è valido +- D: Sono tutte valide + +
Risposta +

+ +#### Risposta: A + +In JavaScript, tutte le chiavi degli oggetti sono stringhe (a meno che non sia un simbolo). Anche se potremmo non scriverle come stringhe, vengono sempre convertite come tali. + +JavaScript interpreta le istruzioni, quindi quando usiamo la bracket notation, vede la prima parentesi aperta `[` e continua finché non trova la parentesi chiusa `]`. Solo allora valuterà la dichiarazione. + +Quando in javascript richiamiamo `mouse[bird.size]`: per prima cosa viene valorizzato `bird.size`, che è `"small"`, per JS viene tradotto quindi come `mouse["small"]` che restituisce `true`. + +Con l'utilizzo del punto questo non accade perchè `mouse` non ha una chiave chiamata `bird`, e questo significa che `mouse.bird` è `undefined`. Per Javascript quindi l'istruzione `mouse.bird.size` viene tradotta con `mouse.undefined.size` che è un valore non valido e che quindi genererà un errore simile a `Cannot read property "size" of undefined`. + +

+
+ +--- + +###### 6. Qual è l'output? + +```javascript +let c = { greeting: 'Hey!' }; +let d; + +d = c; +c.greeting = 'Hello'; +console.log(d.greeting); +``` + +- A: `Hello` +- B: `Hey!` +- C: `undefined` +- D: `ReferenceError` +- E: `TypeError` + +
Risposta +

+ +#### Risposta: A + +In JavaScript, tutti gli oggetti interagiscono per _referenza_ . + +La variabile `c` contiene come valore un oggetto. Alla variabile `d` assegnamo come valore il riferimento di `c` che quindi contiene l'oggetto (e non un suo clone). + + + +Quando modifichi il valore di questo oggetto, lo stai modificando sia per c che per d che contiene il suo riferimento. + +

+
+ +--- + +###### 7. Qual è l'output? + +```javascript +let a = 3; +let b = new Number(3); +let c = 3; + +console.log(a == b); +console.log(a === b); +console.log(b === c); +``` + +- A: `true` `false` `true` +- B: `false` `false` `true` +- C: `true` `false` `false` +- D: `false` `true` `true` + +
Risposta +

+ +#### Risposta: C + +`new Number()` è una funzione costruttore integrata. Nonostante sembri un numero, in realtà non lo è, si tratta infatti di un oggetto con un sacco di funzioni extra. + +Quando utilizziamo l'operatore `==`, stiamo verificando solo se il suo _valore_ è uguale . Entrambe le variabili hanno il valore di `3`, quindi il primo log restituisce `true`. + +Quando invece utilizziamo l'operatore `===`, stiamo verificando che sia il valore che il tipo di valore siano uguali. `new Number()` non è un numero, è un **oggetto** quindi entrambi i log restituiscono `false`. + +

+
+ +--- + +###### 8. Qual è l'output? + +```javascript +class Chameleon { + static colorChange(newColor) { + this.newColor = newColor; + return this.newColor; + } + + constructor({ newColor = 'green' } = {}) { + this.newColor = newColor; + } +} + +const freddie = new Chameleon({ newColor: 'purple' }); +console.log(freddie.colorChange('orange')); +``` + +- A: `orange` +- B: `purple` +- C: `green` +- D: `TypeError` + +
Risposta +

+ +#### Risposta: D + +The `colorChange` function is static. Static methods are designed to live only on the constructor in which they are created, and cannot be passed down to any children or called upon class instances. Since `freddie` is an instance of class Chameleon, the function cannot be called upon it. A `TypeError` is thrown. + +La funzione `colorChange` è statica. I metodi statici sono progettati per vivere solo nel costruttore in cui vengono creati e non possono essere passati a nessun figlio o richiamati su istanze di classe. Poiché `freddie` è un'istanza della classe `Chameleon`, la funzione non può essere chiamata su di essa. Viene restituito quindi un errore di tipo `TypeError`. + +

+
+ +--- + +###### 9. Qual è l'output? + +```javascript +let greeting; +greetign = {}; // Typo! +console.log(greetign); +``` + +- A: `{}` +- B: `ReferenceError: greetign is not defined` +- C: `undefined` + +
Risposta +

+ +#### Risposta: A + +Il nostro log restituisce un oggetto perchè abbiamo appena creato un oggetto vuoto come oggetto globale nel momento in cui per errore abbiamo digitato `greetign` al posto di `greeting`. +Il nostro interprete a quel punto ha letto `global.greetign = {}` (o `window.greetign = {}` se parliamo di un browser). + +Per evitare ciò, possiamo usare `"use strict"`. Questo assicura di aver dichiarato una variabile prima di impostarla uguale a qualsiasi cosa. + +

+
+ +--- + +###### 10. Cosa succede se facciamo questo? + +```javascript +function bark() { + console.log('Woof!'); +} + +bark.animal = 'dog'; +``` + +- A: Niente, va benissimo! +- B: `SyntaxError`. Non è possibile aggiungere proprietà a una funzione in questo modo. +- C: `"Woof"` viene registrato. +- D: `ReferenceError` + +
Risposta +

+ +#### Risposta: A + +In Javasript non succede nulla, perché le funzioni sono oggetti! (Tutto tranne i tipi primitivi sono oggetti) + +Una funzione è un tipo speciale di oggetto. Il codice che scrivi non è la funzione effettiva. La funzione è un oggetto con delle proprietà e quindi questa proprietà è invocabile. + +

+
+ +--- + +###### 11. Qual è l'output? + +```javascript +function Person(firstName, lastName) { + this.firstName = firstName; + this.lastName = lastName; +} + +const member = new Person('Lydia', 'Hallie'); +Person.getFullName = function() { + return `${this.firstName} ${this.lastName}`; +}; + +console.log(member.getFullName()); +``` + +- A: `TypeError` +- B: `SyntaxError` +- C: `Lydia Hallie` +- D: `undefined` `undefined` + +
Risposta +

+ +#### Risposta: A + +In JavaScript, le funzioni sono oggetti e quindi il metodo `getFullName` viene aggiunto al costruttore della funzione stessa. Per questo motivo possiamo chiamare `Person.getFullName()`, mentre `member.getFullName` genera un `TypeError`. + +Se vuoi che un metodo sia disponibile per tutte le istanze dell'oggetto, devi aggiungerlo alla proprietà del prototipo: + + +```js +Person.prototype.getFullName = function() { + return `${this.firstName} ${this.lastName}`; +}; +``` + +

+
+ +--- + +###### 12. Qual è l'output? + +```javascript +function Person(firstName, lastName) { + this.firstName = firstName; + this.lastName = lastName; +} + +const lydia = new Person('Lydia', 'Hallie'); +const sarah = Person('Sarah', 'Smith'); + +console.log(lydia); +console.log(sarah); +``` + +- A: `Person {firstName: "Lydia", lastName: "Hallie"}` and `undefined` +- B: `Person {firstName: "Lydia", lastName: "Hallie"}` and `Person {firstName: "Sarah", lastName: "Smith"}` +- C: `Person {firstName: "Lydia", lastName: "Hallie"}` and `{}` +- D: `Person {firstName: "Lydia", lastName: "Hallie"}` and `ReferenceError` + +
Risposta +

+ +#### Risposta: A + +Per la const `sarah`, non abbiamo usato la chiave `new`. Quando si usa `new`, `this` si riferisce al nuovo oggetto vuoto che creiamo. Tuttavia, se non aggiungiamo `new`, `this` si riferisce all'**oggetto globale**! + +Abbiamo quindi scritto che `this.firstName` equivale a `"Sarah"` e `this.lastName` equivale a `"Smith"`. Quello che abbiamo effettivamente fatto è definire `global.firstName = 'Sarah'` e `global.lastName = 'Smith'`. la const `sarah` viene lasciata come `non definita`, perchè non restituiamo un valore dalla funzione `Persona`. + +

+
+ +--- + +###### 13. Quali sono le tre fasi della propagazione degli eventi? + +- A: Target > Capturing > Bubbling +- B: Bubbling > Target > Capturing +- C: Target > Bubbling > Capturing +- D: Capturing > Target > Bubbling + +
Risposta +

+ +#### Risposta: D + +Durante la fase di **capturing**, l'evento passa attraverso gli elementi predecessori fino all'elemento target. Quindi raggiunge l'elemento **target** e inizia il **bubbling**. + + + +

+
+ +--- + +###### 14. Tutti gli oggetti hanno prototipi. + +- A: true +- B: false + +
Risposta +

+ +#### Risposta: B + +Tutti gli oggetti hanno prototipi, ad eccezione dell'**oggetto base**. L'oggetto base è l'oggetto creato dall'utente, o un oggetto creato usando la parola chiave `new`. L'oggetto base ha accesso ad alcuni metodi e proprietà, come `.toString`. Questo è il motivo per cui puoi utilizzare i metodi JavaScript built-in! Tutti questi metodi sono disponibili sul prototype. Quindi, anche se JavaScript non riesca a trovarlo direttamente sul tuo oggetto, scende lungo la chain del prototype e lo trova lì, il che lo rende accessibile anche per l'oggetto creato da te. + +

+
+ +--- + +###### 15. Qual è l'output? + +```javascript +function sum(a, b) { + return a + b; +} + +sum(1, '2'); +``` + +- A: `NaN` +- B: `TypeError` +- C: `"12"` +- D: `3` + +
Risposta +

+ +#### Risposta: C + +JavaScript è un **linguaggio tipizzato dinamicamente**: non specifichiamo quali tipi siano determinate variabili. I valori possono essere automaticamente convertiti in un altro tipo, questa azione è chiamato _coercizione implicita del tipo_. **Coercizione** è la conversione da un tipo all'altro. + +In questo esempio, JavaScript converte il numero `1` in una stringa, in modo che la funzione abbia un senso e restituisca un valore. Durante l'aggiunta di un tipo numerico (`1`) e di un tipo stringa (`'2'`), il numero viene trattato come una stringa. Possiamo concatenare stringhe come `"Hello" + "World"`, quindi quello che sta succedendo qui è `"1" + "2"` che restituisce `"12"`. + +

+
+ +--- + +###### 16. Qual è l'output? + +```javascript +let number = 0; +console.log(number++); +console.log(++number); +console.log(number); +``` + +- A: `1` `1` `2` +- B: `1` `2` `2` +- C: `0` `2` `2` +- D: `0` `1` `2` + +
Risposta +

+ +#### Risposta: C + +Utilizzando l'operatore unario come **postfisso** `number++` succede che: + +1. Restituisce prima il suo valore (`0`) +2. Subito dopo incrementa il valore di 1 (quindi è ora `1`) + +Utilizzando l'operatore unario come **prefisso** `++number` succede che: + +1. Incrementa prima il valore (il numero è ora `2`) +2. Restituisce subito dopo il valore già incrementato (`2`) + +Quindi il nostro log sarà `0 2 2`. + +

+
+ +--- + +###### 17. Qual è l'output? + +```javascript +function getPersonInfo(one, two, three) { + console.log(one); + console.log(two); + console.log(three); +} + +const person = 'Lydia'; +const age = 21; + +getPersonInfo`${person} is ${age} years old`; +``` + +- A: `"Lydia"` `21` `["", " is ", " years old"]` +- B: `["", " is ", " years old"]` `"Lydia"` `21` +- C: `"Lydia"` `["", " is ", " years old"]` `21` + +
Risposta +

+ +#### Risposta: B + +Utilizzando i template literals, il valore del primo argomento sarà un array di valori della stringa. Gli altri argomenti prenderanno i valori dell'espressione passata. + +

+
+ +--- + +###### 18. Qual è l'output? + +```javascript +function checkAge(data) { + if (data === { age: 18 }) { + console.log('You are an adult!'); + } else if (data == { age: 18 }) { + console.log('You are still an adult.'); + } else { + console.log(`Hmm.. You don't have an age I guess`); + } +} + +checkAge({ age: 18 }); +``` + +- A: `You are an adult!` +- B: `You are still an adult.` +- C: `Hmm.. You don't have an age I guess` + +
Risposta +

+ +#### Risposta: C + +Quando si verifica l'uguaglianza, i primitivi vengono confrontate in base al loro _valore_, mentre gli oggetti vengono confrontati in base al loro _riferimento_. JavaScript controlla se gli oggetti hanno un riferimento alla stessa posizione in memoria. + +I due oggetti che stiamo confrontando non lo hanno: l'oggetto che abbiamo passato come parametro si riferisce a una posizione di memoria diversa rispetto all'oggetto che abbiamo usato per verificare l'uguaglianza. + +Questo è il motivo per cui sia `{ age: 18 } === { age: 18 }` e `{ age: 18 } == { age: 18 }` restituiscono `false`. + +

+
+ +--- + +###### 19. Qual è l'output? + +```javascript +function getAge(...args) { + console.log(typeof args); +} + +getAge(21); +``` + +- A: `"number"` +- B: `"array"` +- C: `"object"` +- D: `"NaN"` + +
Risposta +

+ +#### Risposta: C + +Il parametro rest (`...args`) ci permette di "collettare" tutti gli argomenti in un array. L'array è un oggetto, quindi `typeof args` restituisce `"oggetto"` + +

+
+ +--- + +###### 20. Qual è l'output? + +```javascript +function getAge() { + 'use strict'; + age = 21; + console.log(age); +} + +getAge(); +``` + +- A: `21` +- B: `undefined` +- C: `ReferenceError` +- D: `TypeError` + +
Risposta +

+ +#### Risposta: C + +Con `"use strict"`, puoi assicurarti di non dichiarare variabili globali per sbaglio. In questo caso la variabile `age` non è mai stata dichiarata, e siccome usiamo `"use strict"`, genererà un `ReferenceError`. Se non avessimo usato `"use strict"`, avrebbe funzionato perchè la proprietà `age` sarebbe stata aggiunta all'oggetto globale. + +

+
+ +--- + +###### 21. Qual è il valore di `sum`? + +```javascript +const sum = eval('10*10+5'); +``` + +- A: `105` +- B: `"105"` +- C: `TypeError` +- D: `"10*10+5"` + +
Risposta +

+ +#### Risposta: A + +`eval` "valuta" i codici passati come stringa. Se è un'espressione, come in questo caso, valuta l'espressione. L'espressione è `10 * 10 + 5`. Quindi il valore restituito è il numero `105`. + +

+
+ +--- + +###### 22. Per quanto tempo cool_secret è accessibile? + +```javascript +sessionStorage.setItem('cool_secret', 123); +``` + +- A: Per sempre, i dati non vanno persi. +- B: Fin quando l'utente chiude la scheda. +- C: Fin quando l'utente chiude l'intero browser, non solo la scheda. +- D: Finquando l'utente spegne il proprio computer. + +
Risposta +

+ +#### Risposta: B + +I dati memorizzati in `sessionStorage` vengono rimossi dopo aver chiuso la _tab_. + +Se avessi usato `localStorage`, i dati sarebbero rimasti lì per sempre, a meno che, ad esempio, non fosse stato invocato `localStorage.clear()`. + +

+
+ +--- + +###### 23. Qual è l'output? + +```javascript +var num = 8; +var num = 10; + +console.log(num); +``` + +- A: `8` +- B: `10` +- C: `SyntaxError` +- D: `ReferenceError` + +
Risposta +

+ +#### Risposta: B + +Con la chiave `var` puoi dichiarare più variabili con lo stesso nome. La variabile conterrà quindi l'ultimo valore. + +Non puoi farlo con `let` o `const` poiché sono block-scoped. + +

+
+ +--- + +###### 24. Qual è l'output? + +```javascript +const obj = { 1: 'a', 2: 'b', 3: 'c' }; +const set = new Set([1, 2, 3, 4, 5]); + +obj.hasOwnProperty('1'); +obj.hasOwnProperty(1); +set.has('1'); +set.has(1); +``` + +- A: `false` `true` `false` `true` +- B: `false` `true` `true` `true` +- C: `true` `true` `false` `true` +- D: `true` `true` `true` `true` + +
Risposta +

+ +#### Risposta: C + +Tutte le chiavi degli oggetti (esclusi i simboli) sono stringhe, anche se non vengono scritte come tali. Questo è il motivo per cui anche `obj.hasOwnProperty('1')` restituisce true. + +Per i set non funziona allo stesso modo degli oggetti. Non c'è alcun `'1'` nel nostro set, per cui `set.has('1')` restituisce `false`, è però presente il tipo numerico `1` per cui `set.has(1)` restituisce `true`. + +

+
+ +--- + +###### 25. Qual è l'output? + +```javascript +const obj = { a: 'one', b: 'two', a: 'three' }; +console.log(obj); +``` + +- A: `{ a: "one", b: "two" }` +- B: `{ b: "two", a: "three" }` +- C: `{ a: "three", b: "two" }` +- D: `SyntaxError` + +
Risposta +

+ +#### Risposta: C + +Se hai due chiavi con lo stesso nome, questa verrà sostituita. Sarà quindi ancora nella sua prima posizione, ma con l'ultimo valore specificato. + +

+
+ +--- + +###### 26. Il contesto di esecuzione globale JavaScript crea due cose: l'oggetto globale e la parola chiave "this". + +- A: true +- B: false +- C: it depends + +
Risposta +

+ +#### Risposta: A + +Il contesto di esecuzione di base è il contesto di esecuzione globale: è ciò che è accessibile ovunque nel codice. + +

+
+ +--- + +###### 27. Qual è l'output? + +```javascript +for (let i = 1; i < 5; i++) { + if (i === 3) continue; + console.log(i); +} +``` + +- A: `1` `2` +- B: `1` `2` `3` +- C: `1` `2` `4` +- D: `1` `3` `4` + +
Risposta +

+ +#### Risposta: C + +L'istruzione `continue` salta un'iterazione se una certa condizione restituisce `true`. + +

+
+ +--- + +###### 28. Qual è l'output? + +```javascript +String.prototype.giveLydiaPizza = () => { + return 'Just give Lydia pizza already!'; +}; + +const name = 'Lydia'; + +name.giveLydiaPizza(); +``` + +- A: `"Just give Lydia pizza already!"` +- B: `TypeError: not a function` +- C: `SyntaxError` +- D: `undefined` + +
Risposta +

+ +#### Risposta: A + +`String` è un costruttore built-in, a cui possiamo aggiungere proprietà. In questo caso è stato appena aggiunto un metodo al suo prototipo. +Le stringhe primitive vengono automaticamente convertite in un oggetto stringa, generato dalla string prototype function. Quindi, tutte le stringhe hanno accesso a quel metodo! + +

+
+ +--- + +###### 29. Qual è l'output? + +```javascript +const a = {}; +const b = { key: 'b' }; +const c = { key: 'c' }; + +a[b] = 123; +a[c] = 456; + +console.log(a[b]); +``` + +- A: `123` +- B: `456` +- C: `undefined` +- D: `ReferenceError` + +
Risposta +

+ +#### Risposta: B + +Le chiavi degli oggetti vengono automaticamente convertite in stringhe. Stiamo cercando di impostare un oggetto come chiave per l'oggetto `a` con il valore di `123`. + +Tuttavia, quando convertiamo in stringa un oggetto, diventa `"[object Object]"`. Quindi quello che stiamo dicendo qui è che `a["[object Object]"] = 123`. `c` è un altro oggetto che stiamo implicitamente stringendo. Quindi, `a["[object Object]"] = 456`. + +Quindi, quando facciamo console.log di `a[b]`, che in realtà è `a["[object Object]"]` che abbiamo appena valorizzato con `456`, restituisce `456`. + +

+
+ +--- + +###### 30. Qual è l'output? + +```javascript +const foo = () => console.log('First'); +const bar = () => setTimeout(() => console.log('Second')); +const baz = () => console.log('Third'); + +bar(); +foo(); +baz(); +``` + +- A: `First` `Second` `Third` +- B: `First` `Third` `Second` +- C: `Second` `First` `Third` +- D: `Second` `Third` `First` + +
Risposta +

+ +#### Risposta: B + +Abbiamo una funzione `setTimeout` e l'abbiamo invocata per prima. Eppure, viene loggata per ultima. + +Questo succede perché nei browser non abbiamo solo il runtime engine, ma anche qualcosa chiamata `WebAPI`. La `WebAPI` ci fornisce la funzione `setTimeout` con cui iniziare, e per esempio il DOM. + +Dopo che la _callback_ è stata inviata alla `WebAPI`, la stessa funzione `setTimeout` (ma non la sua callback) viene eliminata dallo stack. + + + +Ora, `foo` viene invocato e `"First"` viene loggato. + + + +`foo` viene quindi tolto dallo stack e `baz` viene invocato. `"Third"` viene loggato. + + + +La WebAPI non può semplicemente aggiungere elementi allo stack ogni volta che è pronta, spinge quindi la funzione di callback in quella che chiamiamo _queue_. + + + +È qui che un ciclo di eventi inizia a funzionare. Un **event loop** esamina lo stack e la coda delle attività. Se lo stack è vuoto, prende la prima cosa in coda e la inserisce nello stack. + + + +`bar` viene invocato, `"Second"` viene registrato e viene tolto dallo stack. + +

+
+ +--- + +###### 31. Quale sarà event.target cliccando sul bottone? + +```html +
+
+ +
+
+``` + +- A: Outer `div` +- B: Inner `div` +- C: `button` +- D: An array of all nested elements. + +
Risposta +

+ +#### Risposta: C + +L'elemento annidato più in profondità è quello che ha causato l'evento ed è quindi l' event.target. Puoi stoppare la propagazione con `event.stopPropagation` + +

+
+ +--- + +###### 32. Cliccando sul paragrafo, quale sarà l'output loggato? + +```html +
+

+ Click here! +

+
+``` + +- A: `p` `div` +- B: `div` `p` +- C: `p` +- D: `div` + +
Risposta +

+ +#### Risposta: A + +Se clicchiamo su `p`, vediamo due log: `p` e `div`. Durante la propagazione dell'evento, ci sono 3 fasi: capturing, target, e bubbling. Di default, i gestori di eventi vengono eseguiti nella fase di bubbling (a meno che non si imposti `useCapture` su `true`) e va quindi dall'elemento annidato più profondo verso l'esterno. + +

+
+ +--- + +###### 33. Qual è l'output? + +```javascript +const person = { name: 'Lydia' }; + +function sayHi(age) { + return `${this.name} is ${age}`; +} + +console.log(sayHi.call(person, 21)); +console.log(sayHi.bind(person, 21)); +``` + +- A: `undefined is 21` `Lydia is 21` +- B: `function` `function` +- C: `Lydia is 21` `Lydia is 21` +- D: `Lydia is 21` `function` + +
Risposta +

+ +#### Risposta: D + +Con entrambi possiamo passare l'oggetto a cui vogliamo che la chiave `this` faccia riferimento. Tuttavia, anche `.call` viene _eseguito immediatamente_! + +`.bind.` restituisce una _copia_ della funzione, ma con un contesto vincolato! Non viene eseguito immediatamente. + +

+
+ +--- + +###### 34. Qual è l'output? + +```javascript +function sayHi() { + return (() => 0)(); +} + +console.log(typeof sayHi()); +``` + +- A: `"object"` +- B: `"number"` +- C: `"function"` +- D: `"undefined"` + +
Risposta +

+ +#### Risposta: B + +La funzione `sayHi` restituisce il valore dato dell'espressione della immediately invoked function expression (IIFE). Questa funzione ha restituito `0`, che è di tipo `"numero"`. + +Ci sono solo 7 tipi built-in: `null`, `undefined`, `boolean`, `number`, `string`, `object` e `symbol`. `"function"` non è un tipo, poiché le funzioni sono oggetti, è quindi di tipo "oggetto"`. + +

+
+ +--- + +###### 35. Quale di questi valori è falso? + +```javascript +0; +new Number(0); +(''); +(' '); +new Boolean(false); +undefined; +``` + +- A: `0`, `''`, `undefined` +- B: `0`, `new Number(0)`, `''`, `new Boolean(false)`, `undefined` +- C: `0`, `''`, `new Boolean(false)`, `undefined` +- D: Sono tutti falsi + +
Risposta +

+ +#### Risposta: A + +Ci sono 8 valori falsi: + +- `undefined` +- `null` +- `NaN` +- `false` +- `''` (empty string) +- `0` +- `-0` +- `0n` (BigInt(0)) + +I costruttori di funzioni, come `new Number` e `new Boolean` sono veritieri. + +

+
+ +--- + +###### 36. Qual è l'output? + +```javascript +console.log(typeof typeof 1); +``` + +- A: `"number"` +- B: `"string"` +- C: `"object"` +- D: `"undefined"` + +
Risposta +

+ +#### Risposta: B + +`typeof 1` ritorna `"number"`. +`typeof "number"` ritorna `"string"` + +

+
+ +--- + +###### 37. Qual è l'output? + +```javascript +const numbers = [1, 2, 3]; +numbers[10] = 11; +console.log(numbers); +``` + +- A: `[1, 2, 3, 7 x null, 11]` +- B: `[1, 2, 3, 11]` +- C: `[1, 2, 3, 7 x empty, 11]` +- D: `SyntaxError` + +
Risposta +

+ +#### Risposta: C + +Quando imposti un valore su un elemento in un array che supera la lunghezza dell'array JavaScript crea degli "slot vuoti". Questi in realtà hanno il valore di `undefined`, ma vedrai qualcosa come: + +`[1, 2, 3, 7 x empty, 11]` + +a seconda di dove lo esegui (è diverso per ogni browser, node, ecc.) + +

+
+ +--- + +###### 38. Qual è l'output? + +```javascript +(() => { + let x, y; + try { + throw new Error(); + } catch (x) { + (x = 1), (y = 2); + console.log(x); + } + console.log(x); + console.log(y); +})(); +``` + +- A: `1` `undefined` `2` +- B: `undefined` `undefined` `undefined` +- C: `1` `1` `2` +- D: `1` `undefined` `undefined` + +
Risposta +

+ +#### Risposta: A + +Il blocco `catch` riceve l'argomento `x` ma non è la stessa `x` della variabile, bensì passiamo un argomento della funzione. Questa "variabile" `x` è block-scoped quindi ha un ambito di blocco. + +Subito dopo impostiamo il valore di variabile block-scoped a "1" e impostiamo il valore della variabile "y". Ora facciamo un console.log della variabile block-scoped `x`, che è uguale a `1`. + +Fuori dal blocco `catch`, `x` è ancora `undefined` e `y` è `2` quindi quando facciamo `console.log(x)` al di fuori del blocco `catch`, otterremo `undefined` e `y` restituirà `2`. + +

+
+ +--- + +###### 39. Tutto in JavaScript è... + +- A: o un primitivo o un oggetto +- B: o una funzione o un oggetto +- C: Questa è unadomanda trabocchetto! Sono solo oggetti +- D: un numero o un oggetto + +
Risposta +

+ +#### Risposta: A + +JavaScript ha solo tipi primitivi e oggetti. + +I tipi primitivi sono `boolean`, `null`, `undefined`, `bigint`, `number`, `string` e `symbol`. + +Ciò che differenzia un tipo primitivo da un oggetto è che i primitivi non hanno proprietà o metodi. Tuttavia, noterai che `'foo'.toUpperCase()` restituisce `'FOO'` e non genera un `TypeError`. Questo perché quando si tenta di accedere a una proprietà o a un metodo su di un tipo primitivo come lo è una stringa, JavaScript racchiuderà implicitamente il tipo primitivo utilizzando una delle classi wrapper, ovvero "String", valuterà l'espressione ed eliminerà il weapper una volta terminato. Tutti i primitivi tranne `null` e `undefined` subiscono questo comportamento. + +

+
+ +--- + +###### 40. Qual è l'output? + +```javascript +[[0, 1], [2, 3]].reduce( + (acc, cur) => { + return acc.concat(cur); + }, + [1, 2], +); +``` + +- A: `[0, 1, 2, 3, 1, 2]` +- B: `[6, 1, 2]` +- C: `[1, 2, 0, 1, 2, 3]` +- D: `[1, 2, 6]` + +
Risposta +

+ +#### Risposta: C + +`[1, 2]` rappresenta il nostro valore interno. Ovvero il valore con cui iniziamo e il valore del primo `acc`. Durante il primo round, `acc` è `[1,2]` e `cur` è `[0, 1]`. Li concateniamo ottenendo `[1, 2, 0, 1]`. + +A questo punto `acc` corrisponderà a `[1, 2, 0, 1]` e `cur` sarà ancora `[2, 3]`. Li concateniamo e otteniamo `[1, 2, 0, 1, 2, 3]` +

+
+ +--- + +###### 41. Qual è l'output? + +```javascript +!!null; +!!''; +!!1; +``` + +- A: `false` `true` `false` +- B: `false` `false` `true` +- C: `false` `true` `true` +- D: `true` `true` `false` + +
Risposta +

+ +#### Risposta: B + +`null` è falso. `!null` restituisce `true`. `!true` restituisce `false`. + +`""` è falso. `!""` restituisce `true`. `!true` restituisce `false`. + +`1` è vero. `!1` restituisce `falso`. `!false` restituisce `true`. + +

+
+ +--- + +###### 42. Cosa restituisce il metodo `setInterval` nel browser? + +```javascript +setInterval(() => console.log('Hi'), 1000); +``` + +- A: un ID univoco +- B: la quantità di millisecondi specificata +- C: la funzione passata +- D: `undefined` + +
Risposta +

+ +#### Risposta: A + +Restituisce un ID univoco. Questo id può essere usato per cancellare quell'intervallo con la funzione `clearInterval()`. + +

+
+ +--- + +###### 43. Cosa restituisce? + +```javascript +[...'Lydia']; +``` + +- A: `["L", "y", "d", "i", "a"]` +- B: `["Lydia"]` +- C: `[[], "Lydia"]` +- D: `[["L", "y", "d", "i", "a"]]` + +
Risposta +

+ +#### Risposta: A + +Una stringa è un iterabile. L'operatore spread mappa ogni carattere di una stringa rendendola parte di array. + +

+
+ +--- + +###### 44. Qual è l'output? + +```javascript +function* generator(i) { + yield i; + yield i * 2; +} + +const gen = generator(10); + +console.log(gen.next().value); +console.log(gen.next().value); +``` + +- A: `[0, 10], [10, 20]` +- B: `20, 20` +- C: `10, 20` +- D: `0, 10 and 10, 20` + +
Risposta +

+ +#### Risposta: C + +Le funzioni regolari non possono essere interrotte a metà dopo l'invocazione. Tuttavia, una funzione "generator" può essere stoppata a metà e in seguito continuare da dove si era interrotta. Ogni volta che una funzione generator incontra una parola chiave `yield`, la funzione restituisce il valore specificato dopo di essa. Nota che la funzione del generator in quel caso non _restituisce (return)_ il valore, _rende (yeld)_ il valore. + +Come prima cosa inizializziamo la funzione del generator con `i` uguale a `10`. Invochiamo la funzione usando il metodo `next()`. La prima volta che invochiamo la funzione generator, `i` è uguale a `10`, incontra la prima parola chiave `yield` quindi restituisce il valore di `i`. Il generatore è ora "in pausa" e `10` viene loggato. + +Invochiamo di nuovo la funzione con il metodo `next()`. Inizia a continuare da dove si era fermata in precedenza, sempre con `i` uguale a `10`. Ora incontra il secondo `yield` e restituisce `i * 2`, quindi restituisce `10 * 2`, che è `20`. Ciò risulta in `10, 20`. + +

+
+ +--- + +###### 45. Cosa restituisce? + +```javascript +const firstPromise = new Promise((res, rej) => { + setTimeout(res, 500, 'one'); +}); + +const secondPromise = new Promise((res, rej) => { + setTimeout(res, 100, 'two'); +}); + +Promise.race([firstPromise, secondPromise]).then(res => console.log(res)); +``` + +- A: `"one"` +- B: `"two"` +- C: `"two" "one"` +- D: `"one" "two"` + +
Risposta +

+ +#### Risposta: B + +Quando passiamo più promises al metodo `Promise.race`, questo risolve/rifiuta la _prima_ promise. Al metodo `setTimeout` passiamo un timer: 500ms per la prima promise (`firstPromise`) e 100ms per la seconda promise (`secondPromise`). Ciò significa che `secondPromise` si risolve prima con il valore di `'due'`. `res` ora contiene il valore di `'two'`, che viene loggato. + +

+
+ +--- + +###### 46. Qual è l'output? + +```javascript +let person = { name: 'Lydia' }; +const members = [person]; +person = null; + +console.log(members); +``` + +- A: `null` +- B: `[null]` +- C: `[{}]` +- D: `[{ name: "Lydia" }]` + +
Risposta +

+ +#### Risposta: D + +Per prima cosa, dichiariamo una variabile `person` con un oggetto che ha una proprietà `name`. + + + +Quindi, dichiariamo una variabile chiamata `members`. Impostiamo il primo elemento di quell'array uguale al valore della variabile `person`. Gli oggetti interagiscono per _riferimento_ quando vengono impostati uguali tra loro. Quando assegni un riferimento da una variabile all'altra, esegui una _copia_ di quel riferimento. (nota che non hanno lo _stesso_ riferimento!) + + + +Quindi, impostiamo la variabile `person` uguale a `null`. + + + +Stiamo modificando solo il valore della variabile `person`, e non il primo elemento nell'array, poiché quell'elemento ha un riferimento diverso (copiato) dall'oggetto. Il primo elemento in `members` mantiene ancora il suo riferimento all'oggetto originale. Quando logghiamo l'array `members`, il primo elemento contiene ancora il valore dell'oggetto, che viene loggato. + +

+
+ +--- + +###### 47. Qual è l'output? + +```javascript +const person = { + name: 'Lydia', + age: 21, +}; + +for (const item in person) { + console.log(item); +} +``` + +- A: `{ name: "Lydia" }, { age: 21 }` +- B: `"name", "age"` +- C: `"Lydia", 21` +- D: `["name", "Lydia"], ["age", 21]` + +
Risposta +

+ +#### Risposta: B + +Con il ciclo `for-in`, possiamo iterare le chiavi degli oggetti, in questo caso `name` e `age`. Le chiavi degli oggetti sono stringhe (se non sono un simbolo). In ogni ciclo, impostiamo il valore di `item` uguale alla chiave corrente su cui sta iterando. Il primo `item` è uguale a `name` e viene loggato, `item` sarà poi uguale a `age`, che viene loggato. + +

+
+ +--- + +###### 48. Qual è l'output? + +```javascript +console.log(3 + 4 + '5'); +``` + +- A: `"345"` +- B: `"75"` +- C: `12` +- D: `"12"` + +
Risposta +

+ +#### Risposta: B + +Operator associativity is the order in which the compiler evaluates the expressions, either left-to-right or right-to-left. This only happens if all operators have the _same_ precedence. We only have one type of operator: `+`. For addition, the associativity is left-to-right. + +`3 + 4` gets evaluated first. This results in the number `7`. + +`7 + '5'` results in `"75"` because of coercion. JavaScript converts the number `7` into a string, see question 15. We can concatenate two strings using the `+`operator. `"7" + "5"` results in `"75"`. + + +L'associazione è l'ordine in cui il compilatore valuta le espressioni, da sinistra a destra o da destra a sinistra. Questo accade solo se tutti gli operatori hanno la _stessa_ precedenza. Abbiamo solo un tipo di operatore: `+`. Inoltre, l'associazione è da sinistra a destra. + +`3 + 4` viene valutato per primo. E risulta nell'addizione dei due valori che restituiscono quindi `7`. + +`7 + '5'` risulta in `"75"` per via della coercizione. JavaScript converte il numero `7` in una stringa, (vedi la domanda 15). Possiamo concatenare due stringhe usando l'operatore `+`. `"7" + "5"` risulta quindi in "75"`. + +

+
+ +--- + +###### 49. Qual è il valore di `num`? + +```javascript +const num = parseInt('7*6', 10); +``` + +- A: `42` +- B: `"42"` +- C: `7` +- D: `NaN` + +
Risposta +

+ +#### Risposta: C + +Viene restituito solo il primo valore della stringa. In base alla _radice_ (ovvero il secondo argomento per specificare sulla base di quale tipo di numero vogliamo analizzarlo: base 10, esadecimale, ottale, binario, ecc.), `parseInt` controlla se i caratteri nella stringa sono validi. Una volta che incontra un carattere che non è un numero valido nella radice, interrompe l'analisi e ignora i seguenti caratteri. + +`*` non è un numero valido. Analizza solo `"7"` nel decimale `7`. `num` ora contiene il valore di `7`. + +

+
+ +--- + +###### 50. Qual è l'output? + +```javascript +[1, 2, 3].map(num => { + if (typeof num === 'number') return; + return num * 2; +}); +``` + +- A: `[]` +- B: `[null, null, null]` +- C: `[undefined, undefined, undefined]` +- D: `[ 3 x empty ]` + +
Risposta +

+ +#### Risposta: C + +Quando si esegue il mapping sull'array, il valore di `num` è uguale all'elemento su cui sta attualmente scorrendo. In questo caso, gli elementi sono numeri, quindi la condizione dell'istruzione if `typeof num === "number"` restituisce `true`. La funzione map crea un nuovo array e inserisce i valori restituiti dalla funzione. + +Tuttavia, non ritorniamo un valore. Quando non ritorniamo un valore dalla funzione, la funzione restituisce `undefined`. Per ogni elemento nell'array, viene chiamato il blocco funzione, quindi per ogni elemento restituiamo `undefined`. + +

+
+ +--- + +###### 51. Qual è l'output? + +```javascript +function getInfo(member, year) { + member.name = 'Lydia'; + year = '1998'; +} + +const person = { name: 'Sarah' }; +const birthYear = '1997'; + +getInfo(person, birthYear); + +console.log(person, birthYear); +``` + +- A: `{ name: "Lydia" }, "1997"` +- B: `{ name: "Sarah" }, "1998"` +- C: `{ name: "Lydia" }, "1998"` +- D: `{ name: "Sarah" }, "1997"` + +
Risposta +

+ +#### Risposta: A + +Gli argomenti vengono passati come _valori_, a meno che il loro valore non sia un oggetto, quindi vengono passati come _reference_. `birthYear` viene passato per valore, poiché è una stringa, non un oggetto. Quando passiamo argomenti per valore, viene creata una _copia_ di quel valore (vedi domanda 46). + +La variabile `birthYear` ha un riferimento al valore `"1997"`. Anche l'argomento `year` fa riferimento al valore `"1997"`, ma non è lo stesso valore a cui fa riferimento `birthYear`. Quando aggiorniamo il valore di `year` impostando `year` uguale a `"1998"`, stiamo solo aggiornando il valore di `year`. `birthYear` è ancora uguale a `"1997"`. + +Il valore di `person` è un oggetto. L'argomento `member` ha un riferimento (copiato) dello stesso oggetto. Quando modifichiamo una proprietà dell'oggetto a cui `member` fa riferimento, verrà modificato anche il valore di `person`, poiché entrambi hanno un riferimento allo stesso oggetto. La proprietà `name` di `person` è ora uguale al valore `"Lydia"` +

+
+ +--- + +###### 52. Qual è l'output? + +```javascript +function greeting() { + throw 'Hello world!'; +} + +function sayHi() { + try { + const data = greeting(); + console.log('It worked!', data); + } catch (e) { + console.log('Oh no an error:', e); + } +} + +sayHi(); +``` + +- A: `It worked! Hello world!` +- B: `Oh no an error: undefined` +- C: `SyntaxError: can only throw Error objects` +- D: `Oh no an error: Hello world!` + +
Risposta +

+ +#### Risposta: D + +Con l'istruzione `throw`, possiamo creare errori personalizzati. Con questa istruzione, puoi generare eccezioni. Un'eccezione può essere una stringa, un numero, un booleano o un oggetto. In questo caso, la nostra eccezione è la stringa `'Hello world!'`. + +Con l'istruzione `catch`, possiamo specificare cosa fare se viene generata un'eccezione nel blocco `try`. Viene generata un'eccezione: la stringa `'Hello world!'`. `e` è ora uguale a quella stringa, che logghiamo. Ciò si traduce in `'Oh an error: Hello world!'`. + +

+
+ +--- + +###### 53. Qual è l'output? + +```javascript +function Car() { + this.make = 'Lamborghini'; + return { make: 'Maserati' }; +} + +const myCar = new Car(); +console.log(myCar.make); +``` + +- A: `"Lamborghini"` +- B: `"Maserati"` +- C: `ReferenceError` +- D: `TypeError` + +
Risposta +

+ +#### Risposta: B + +Quando si restituisce una proprietà, il valore della proprietà è uguale al valore _restituito_, non al valore impostato nella funzione di costruzione. Restituiamo la stringa `"Maserati"`, quindi `myCar.make` è uguale a `"Maserati"`. + +

+
+ +--- + +###### 54. Qual è l'output? + +```javascript +(() => { + let x = (y = 10); +})(); + +console.log(typeof x); +console.log(typeof y); +``` + +- A: `"undefined", "number"` +- B: `"number", "number"` +- C: `"object", "number"` +- D: `"number", "undefined"` + +
Risposta +

+ +#### Risposta: A + +`let x = (y = 10);` in realtà è un'abbreviazione per: + +```javascript +y = 10; +let x = y; +``` + +Quando impostiamo `y` uguale a `10`, in realtà aggiungiamo una proprietà `y` all'oggetto globale (`window` nel browser, `global` in Node). In un browser, `window.y` ora è uguale a `10`. + +Quindi, dichiariamo una variabile `x` con il valore di `y`, che è `10`. Le variabili dichiarate con la parola chiave `let` sono _block scoped_, ovvero sono definite solo all'interno del blocco in cui sono dichiarate, l'espressione di funzione immediatamente invocata (IIFE) in questo caso. Quando utilizziamo l'operatore `typeof`, l'operando `x` non è definito: stiamo cercando di accedere a `x` al di fuori del blocco in cui è dichiarato. Ciò significa che `x` non è definito. I valori a cui non è stato assegnato un valore o dichiarati sono di tipo `"undefined"`. `console.log(typeof x)` restituisce `"undefined"`. + +Tuttavia, abbiamo creato una variabile globale `y` quando abbiamo impostato `y` uguale a `10`. Questo valore è accessibile ovunque nel nostro codice. `y` è definito e contiene un valore di tipo `"number"`. `console.log(typeof y)` restituisce `"number"`. + +

+
+ +--- + +###### 55. Qual è l'output? + +```javascript +class Dog { + constructor(name) { + this.name = name; + } +} + +Dog.prototype.bark = function() { + console.log(`Woof I am ${this.name}`); +}; + +const pet = new Dog('Mara'); + +pet.bark(); + +delete Dog.prototype.bark; + +pet.bark(); +``` + +- A: `"Woof I am Mara"`, `TypeError` +- B: `"Woof I am Mara"`, `"Woof I am Mara"` +- C: `"Woof I am Mara"`, `undefined` +- D: `TypeError`, `TypeError` + +
Risposta +

+ +#### Risposta: A + +Possiamo eliminare le proprietà dagli oggetti usando la parola chiave `delete`, anche sul prototype. Eliminando una proprietà sul prototipo, questa non è più disponibile nella catena di prototype. In questo caso, la funzione `bark` non è più disponibile sul prototipo dopo `delete Dog.prototype.bark`, ma proviamo comunque ad accedervi. + +Quando proviamo a invocare qualcosa che non è una funzione, viene lanciato un `TypeError`. In questo caso `TypeError: pet.bark is not a function`, poiché `pet.bark` è `undefined`. + +

+
+ +--- + +###### 56. Qual è l'output? + +```javascript +const set = new Set([1, 1, 2, 3, 4]); + +console.log(set); +``` + +- A: `[1, 1, 2, 3, 4]` +- B: `[1, 2, 3, 4]` +- C: `{1, 1, 2, 3, 4}` +- D: `{1, 2, 3, 4}` + +
Risposta +

+ +#### Risposta: D + +L'oggetto `Set` è una collezione di valori _unici_: un valore può verificarsi solo una volta in un set. + +Abbiamo passato l'array `[1, 1, 2, 3, 4]` con il valore duplicato `1`. Poiché non possiamo avere due valori uguali in un set, uno di essi viene rimosso. Ciò risulta in `{1, 2, 3, 4}`. + +

+
+ +--- + +###### 57. Qual è l'output? + +```javascript +// counter.js +let counter = 10; +export default counter; +``` + +```javascript +// index.js +import myCounter from './counter'; + +myCounter += 1; + +console.log(myCounter); +``` + +- A: `10` +- B: `11` +- C: `Error` +- D: `NaN` + +
Risposta +

+ +#### Risposta: C + +Un modulo importato è di _sola lettura_: non è quindi possibile modificare il modulo importato. Solo il modulo che li esporta può cambiarne il valore. + +Quando proviamo ad incrementare il valore di `myCounter`, viene generato un errore: perchè `myCounter` è di sola lettura e non può essere modificato. + +

+
+ +--- + +###### 58. Qual è l'output? + +```javascript +const name = 'Lydia'; +age = 21; + +console.log(delete name); +console.log(delete age); +``` + +- A: `false`, `true` +- B: `"Lydia"`, `21` +- C: `true`, `true` +- D: `undefined`, `undefined` + +
Risposta +

+ +#### Risposta: A + +L'operatore `delete` restituisce un valore booleano: `true` su una cancellazione riuscita, altrimenti restituirà `false`. Tuttavia, le variabili dichiarate con la parola chiave `var`, `const` o `let` non possono essere cancellate usando l'operatore `delete`. + +La variabile `name` è stata dichiarata con la chiave `const`, quindi la sua cancellazione non va a buon fine e viene restituito `false`. Quando impostiamo `age` uguale a `21`, abbiamo effettivamente aggiunto una proprietà chiamata `age` all'oggetto globale. Puoi eliminare con successo le proprietà dagli oggetti in questo modo, anche l'oggetto globale, quindi `delete age` restituisce `true`. + +

+
+ +--- + +###### 59. Qual è l'output? + +```javascript +const numbers = [1, 2, 3, 4, 5]; +const [y] = numbers; + +console.log(y); +``` + +- A: `[[1, 2, 3, 4, 5]]` +- B: `[1, 2, 3, 4, 5]` +- C: `1` +- D: `[1]` + +
Risposta +

+ +#### Risposta: C + +Possiamo spacchettare i valori da un array o proprietà dagli oggetti attraverso la destrutturazione. Per esempio: + +```javascript +[a, b] = [1, 2]; +``` + + + +Il valore di `a` ora è `1`, e il valore di `b` è ora `2`. Quello che abbiamo effettivamente fatto nella domanda è: + +```javascript +[y] = [1, 2, 3, 4, 5]; +``` + + + +Questo significa che il valore di `y` è uguale al primo valore nell'array, che è il numero `1`. Quando registriamo `y`, viene restituito `1`. + +

+
+ +--- + +###### 60. Qual è l'output? + +```javascript +const user = { name: 'Lydia', age: 21 }; +const admin = { admin: true, ...user }; + +console.log(admin); +``` + +- A: `{ admin: true, user: { name: "Lydia", age: 21 } }` +- B: `{ admin: true, name: "Lydia", age: 21 }` +- C: `{ admin: true, user: ["Lydia", 21] }` +- D: `{ admin: true }` + +
Risposta +

+ +#### Risposta: B + +È possibile combinare oggetti utilizzando l'operatore spread `...`. Questo ti consente di creare copie delle coppie chiave/valore di un oggetto e aggiungerle a un altro oggetto. In questo caso, creiamo copie dell'oggetto `user` e le aggiungiamo all'oggetto `admin`. L'oggetto `admin` ora contiene le coppie chiave/valore copiate, che risultano in `{ admin: true, name: "Lydia", age: 21 }`. + +

+
+ +--- + +###### 61. Qual è l'output? + +```javascript +const person = { name: 'Lydia' }; + +Object.defineProperty(person, 'age', { value: 21 }); + +console.log(person); +console.log(Object.keys(person)); +``` + +- A: `{ name: "Lydia", age: 21 }`, `["name", "age"]` +- B: `{ name: "Lydia", age: 21 }`, `["name"]` +- C: `{ name: "Lydia"}`, `["name", "age"]` +- D: `{ name: "Lydia"}`, `["age"]` + +
Risposta +

+ +#### Risposta: B + +Con il metodo `defineProperty`, possiamo aggiungere nuove proprietà a un oggetto o modificare quelle esistenti. Quando aggiungiamo delle proprietà a un oggetto usando il metodo `defineProperty`, queste per impostazione predefinita sono _non enumerabili_. Il metodo `Object.keys` restituisce tutti i nomi di proprietà _enumerabili_ da un oggetto, in questo caso solo `"name"`. + +Le proprietà aggiunte usando il metodo `defineProperty` sono immutabili per impostazione predefinita. Puoi ignorare questo comportamento usando le proprietà `writable`, `configurable` ed `enumerable`. In questo modo, il metodo `defineProperty` ti dà molto più controllo sulle proprietà che stai aggiungendo a un oggetto. + +

+
+ +--- + +###### 62. Qual è l'output? + +```javascript +const settings = { + username: 'lydiahallie', + level: 19, + health: 90, +}; + +const data = JSON.stringify(settings, ['level', 'health']); +console.log(data); +``` + +- A: `"{"level":19, "health":90}"` +- B: `"{"username": "lydiahallie"}"` +- C: `"["level", "health"]"` +- D: `"{"username": "lydiahallie", "level":19, "health":90}"` + +
Risposta +

+ +#### Risposta: A + +Il secondo argomento di `JSON.stringify` è _replacer_. Il replacer può essere una funzione o un array e consente di controllare cosa e come i valori devono essere stringati. + +Se il replacer è un _array_, solo i nomi delle proprietà inclusi nell'array verranno aggiunti alla stringa JSON. In questo caso, sono incluse solo le proprietà con i nomi `"level"` e `"health"`, `"username"` è esclusa. `data` quindi ora è uguale a `"{"level":19, "health":90}"`. + +Se il replacer è una _funzione_, questa funzione viene chiamata su ogni proprietà nell'oggetto che stai stringendo. Il valore restituito da questa funzione sarà il valore della proprietà quando viene aggiunto alla stringa JSON. Se il valore è `undefined`, questa proprietà viene esclusa dalla stringa JSON. + +

+
+ +--- + +###### 63. Qual è l'output? + +```javascript +let num = 10; + +const increaseNumber = () => num++; +const increasePassedNumber = number => number++; + +const num1 = increaseNumber(); +const num2 = increasePassedNumber(num1); + +console.log(num1); +console.log(num2); +``` + +- A: `10`, `10` +- B: `10`, `11` +- C: `11`, `11` +- D: `11`, `12` + +
Risposta +

+ +#### Risposta: A + +L'operatore unario `++` _prima_ restituisce il valore dell'operando, _poi_ incrementa il valore dell'operando. Il valore di `num1` è `10`, poiché la funzione `increaseNumber` restituisce prima il valore di `num`, che è `10`, e solo successivamente incrementa il valore di `num`. + +`num2` è `10`, poiché abbiamo passato `num1` a `increasePassedNumber`. `number` è uguale a `10` (il valore di `num1`. Anche in questo caso, l'operatore unario `++` _prima_ restituisce il valore dell'operando, _poi_ lo incrementa. Il valore di `number` è ` 10`, quindi `num2` è uguale a `10`. + +

+
+ +--- + +###### 64. Qual è l'output? + +```javascript +const value = { number: 10 }; + +const multiply = (x = { ...value }) => { + console.log((x.number *= 2)); +}; + +multiply(); +multiply(); +multiply(value); +multiply(value); +``` + +- A: `20`, `40`, `80`, `160` +- B: `20`, `40`, `20`, `40` +- C: `20`, `20`, `20`, `40` +- D: `NaN`, `NaN`, `20`, `40` + +
Risposta +

+ +#### Risposta: C + +In ES6, possiamo inizializzare i parametri con un valore predefinito. Il valore del parametro sarà il valore predefinito se nessun altro valore è stato passato alla funzione o se è stato passato un valore `"undefined"`. In questo caso, distribuiamo le proprietà dell'oggetto `value` in un nuovo oggetto, quindi `x` ha il valore predefinito di `{ number: 10 }`. + +L'argomento predefinito viene valutato quando viene chiamato! Ogni volta che chiamiamo la funzione, viene creato un _nuovo_ oggetto. Invochiamo la funzione `multiply` le prime due volte senza passare un valore, quindi `x` ha il valore predefinito di `{ number: 10 }`. Quindi logghiamo il valore moltiplicato di quel numero, che è `20`. + +La terza volta che invochiamo la funzione multiply, passiamo un argomento: l'oggetto chiamato `value`. L'operatore `*=` è in realtà un'abbreviazione per `x.number = x.number * 2`: modifichiamo il valore di `x.number` e logghiamo il valore moltiplicato `20`. + +La quarta volta, passiamo di nuovo l'oggetto `value`, in questo caso `x.number` è stato precedentemente modificato in `20`, quindi `x.number *= 2` logga `40`. + +

+
+ +--- + +###### 65. Qual è l'output? + +```javascript +[1, 2, 3, 4].reduce((x, y) => console.log(x, y)); +``` + +- A: `1` `2` and `3` `3` and `6` `4` +- B: `1` `2` and `2` `3` and `3` `4` +- C: `1` `undefined` and `2` `undefined` and `3` `undefined` and `4` `undefined` +- D: `1` `2` and `undefined` `3` and `undefined` `4` + +
Risposta +

+ +#### Risposta: D + +Il primo argomento che il metodo `reduce` riceve è l'_accumulatore_, in questo caso `x`. Il secondo argomento è il _valore corrente_ `y`. +Con il metodo reduce, eseguiamo una funzione di callback su ogni elemento dell'array, che alla fine potrebbe risultare in un singolo valore. + +In questo esempio, non stiamo restituendo alcun valore, stiamo semplicemente loggando i valori dell'accumulatore e il valore corrente. + +Il valore dell'accumulatore è uguale al valore restituito in precedenza dalla funzione di callback. Se non si passa l'argomento opzionale `initialValue` al metodo `reduce`, l'accumulatore è uguale al primo elemento della prima chiamata. + +Alla prima chiamata, l'accumulatore (`x`) è `1` e il valore corrente (`y`) è `2`. Non facciamo un return con la funzione di callback ma logghiamo l'accumulatore e il valore corrente: `1` e `2` vengono loggati. + +Se non restituisci un valore da una funzione questa restituisce `undefined`. Alla chiamata successiva, l'accumulatore è `undefined` e il valore corrente è "3". `undefined` e `3` vengono loggati. + +Alla quarta chiamata, di nuovo non facciamo un return dalla funzione di callback. L'accumulatore è di nuovo `undefined` e il valore corrente è "4". `undefined` e `4` vengono loggati. +

+
+ +--- + +###### 66. Con quale costruttore possiamo estendere la classe `Dog`? + +```javascript +class Dog { + constructor(name) { + this.name = name; + } +}; + +class Labrador extends Dog { + // 1 + constructor(name, size) { + this.size = size; + } + // 2 + constructor(name, size) { + super(name); + this.size = size; + } + // 3 + constructor(size) { + super(name); + this.size = size; + } + // 4 + constructor(name, size) { + this.name = name; + this.size = size; + } + +}; +``` + +- A: 1 +- B: 2 +- C: 3 +- D: 4 + +
Risposta +

+ +#### Risposta: B + +In una classe derivata, non puoi accedere alla chiave `this` prima di chiamare `super`. Se provi a farlo, genererà un ReferenceError: 1 e 4 genererebbero un errore di riferimento. + +Con la chiave `super`, chiamiamo il costruttore di quella classe parent con gli argomenti forniti. Il costruttore del parent riceve l'argomento `name`, quindi passiamo `name` a `super`. + +La classe `Labrador` riceve due argomenti, `name` poiché estende `Dog`, e `size` come proprietà extra sulla classe `Labrador`. Entrambi devono essere passati alla funzione di costruzione su `Labrador`, cosa che viene eseguita correttamente usando il costruttore 2. + +

+
+ +--- + +###### 67. Qual è l'output? + +```javascript +// index.js +console.log('running index.js'); +import { sum } from './sum.js'; +console.log(sum(1, 2)); + +// sum.js +console.log('running sum.js'); +export const sum = (a, b) => a + b; +``` + +- A: `running index.js`, `running sum.js`, `3` +- B: `running sum.js`, `running index.js`, `3` +- C: `running sum.js`, `3`, `running index.js` +- D: `running index.js`, `undefined`, `running sum.js` + +
Risposta +

+ +#### Risposta: B + +Con la chiave `import` tutti i moduli importati sono _pre-parsed_. Ciò significa che i moduli importati vengono eseguiti _prima_, il codice nel file che importa il modulo viene eseguito _dopo_. + +Questa è una delle differenze tra `require()` in CommonJS e `import`. Con `require()`, puoi caricare le dipendenze su richiesta mentre il codice è in esecuzione. Se avessimo usato `require` invece di `import`, sulla console avremmo loggato `running index.js`, `running sum.js`, `3`. + +

+
+ +--- + +###### 68. Qual è l'output? + +```javascript +console.log(Number(2) === Number(2)); +console.log(Boolean(false) === Boolean(false)); +console.log(Symbol('foo') === Symbol('foo')); +``` + +- A: `true`, `true`, `false` +- B: `false`, `true`, `false` +- C: `true`, `false`, `true` +- D: `true`, `true`, `true` + +
Risposta +

+ +#### Risposta: A + +Ogni Simbolo è unico. Lo scopo dell'argomento passato a Symbol è di dargli una descrizione. Il valore del Symbol non dipende dall'argomento passato. Mentre testiamo l'uguaglianza, stiamo creando due simboli completamente nuovi: il primo `Symbol('foo')` e il secondo `Symbol('foo')`. Questi due valori sono unici e non uguali tra loro, `Symbol('foo') === Symbol('foo')` quindi restituisce `false`. + +

+
+ +--- + +###### 69. Qual è l'output? + +```javascript +const name = 'Lydia Hallie'; +console.log(name.padStart(13)); +console.log(name.padStart(2)); +``` + +- A: `"Lydia Hallie"`, `"Lydia Hallie"` +- B: `" Lydia Hallie"`, `" Lydia Hallie"` (`"[13x whitespace]Lydia Hallie"`, `"[2x whitespace]Lydia Hallie"`) +- C: `" Lydia Hallie"`, `"Lydia Hallie"` (`"[1x whitespace]Lydia Hallie"`, `"Lydia Hallie"`) +- D: `"Lydia Hallie"`, `"Lyd"`, + +
Risposta +

+ +#### Risposta: C + +Con il metodo `padStart`, possiamo aggiungere un riempimento all'inizio di una stringa. Il valore passato a questo metodo è la lunghezza _totale_ della stringa insieme al riempimento. La stringa `"Lydia Hallie"` ha una lunghezza di `12`. `name.padStart(13)` inserisce quindi 1 spazio all'inizio della stringa, perché 12 + 1 è 13. + +Se l'argomento passato al metodo `padStart` è inferiore alla lunghezza dell'array, non verrà aggiunto alcun riempimento. + +

+
+ +--- + +###### 70. Qual è l'output? + +```javascript +console.log('🥑' + '💻'); +``` + +- A: `"🥑💻"` +- B: `257548` +- C: A string containing their code points +- D: Error + +
Risposta +

+ +#### Risposta: A + +Con l'operatore `+` puoi concatenare stringhe. In questo caso, stiamo concatenando la stringa `"🥑"` con la stringa `"💻"`, ottenendo `"🥑💻"`. + +

+
+ +--- + +###### 71. Come possiamo loggare i valori commentati dopo l'istruzione console.log? + +```javascript +function* startGame() { + const answer = yield 'Do you love JavaScript?'; + if (answer !== 'Yes') { + return "Oh wow... Guess we're gone here"; + } + return 'JavaScript loves you back ❤️'; +} + +const game = startGame(); +console.log(/* 1 */); // Do you love JavaScript? +console.log(/* 2 */); // JavaScript loves you back ❤️ +``` + +- A: `game.next("Yes").value` and `game.next().value` +- B: `game.next.value("Yes")` and `game.next.value()` +- C: `game.next().value` and `game.next("Yes").value` +- D: `game.next.value()` and `game.next.value("Yes")` + +
Risposta +

+ +#### Risposta: C + +Una funzione generator "mette in pausa" la sua esecuzione quando incontra la parola chiave `yield`. Innanzitutto dobbiamo lasciare che la funzione produca la stringa "Ami JavaScript?", che può essere eseguita chiamando `game.next().value`. + +Ogni riga viene quindi eseguita, finché non trova la prima chiave `yield`. C'è una parola chiave `yield` sulla prima riga all'interno della funzione: l'esecuzione si interrompe con il primo rendimento! _Questo significa che la variabile `answer` non è ancora definita!_ + +Quando chiamiamo `game.next("Yes").value`, il precedente `yield` viene sostituito con il valore dei parametri passati alla funzione `next()`, in questo caso `"Yes"`. Il valore della variabile `answer` è ora uguale a `"Yes"`. La condizione dell'istruzione if restituisce `false` e `JavaScript loves you back ❤️` viene registrato. + +

+
+ +--- + +###### 72. Qual è l'output? + +```javascript +console.log(String.raw`Hello\nworld`); +``` + +- A: `Hello world!` +- B: `Hello`
     `world` +- C: `Hello\nworld` +- D: `Hello\n`
     `world` + +
Risposta +

+ +#### Risposta: C + +`String.raw` restituisce una stringa in cui gli escape (`\n`, `\v`, `\t` ecc.) vengono ignorati! I backslash possono essere un problema poiché potresti finire con qualcosa del tipo: + +`` const path = `C:\Documents\Projects\table.html` `` + +Il che risulterebbe in: + +`"C:DocumentsProjects able.html"` + +Con `String.raw`, il compilatore ignorerebbe semplicemente l'escape e stamperebbe: + +`C:\Documents\Projects\table.html` + +In questo caso, è la stringa `Hello\nworld` che viene loggata. + +

+
+ +--- + +###### 73. Qual è l'output? + +```javascript +async function getData() { + return await Promise.resolve('I made it!'); +} + +const data = getData(); +console.log(data); +``` + +- A: `"I made it!"` +- B: `Promise {: "I made it!"}` +- C: `Promise {}` +- D: `undefined` + +
Risposta +

+ +#### Risposta: C + +An async function always returns a promise. The `await` still has to wait for the promise to resolve: a pending promise gets returned when we call `getData()` in order to set `data` equal to it. + +If we wanted to get access to the resolved value `"I made it"`, we could have used the `.then()` method on `data`: + +`data.then(res => console.log(res))` + +This would've logged `"I made it!"` + + +Una funzione asincrona restituisce sempre una promise. L'`await` deve ancora attendere che la promise si risolva: una promise in sospeso viene restituita quando chiamiamo "getData()" per impostare "data" uguale ad essa. + +Se volessimo accedere al valore risolto `"I made it"`, potremmo usare il metodo `.then()` su `data`: + +`data.then(res => console.log(res))` + +Questo avrebbe loggato `"I made it!"` + +

+
+ +--- + +###### 74. Qual è l'output? + +```javascript +function addToList(item, list) { + return list.push(item); +} + +const result = addToList('apple', ['banana']); +console.log(result); +``` + +- A: `['apple', 'banana']` +- B: `2` +- C: `true` +- D: `undefined` + +
Risposta +

+ +#### Risposta: B + +Il metodo `.push()` restituisce la _lunghezza_ del nuovo array! +Inizialmente, l'array conteneva un solo elemento (la stringa `"banana"`) e aveva una lunghezza di `1`. Dopo aver aggiunto la stringa `"apple"` allo stesso array, questo contiene due elementi e ha una lunghezza di `2` + +Attravero la funzione `addToList`, il metodo `push` modifica l'array originale. +Per restituire l'_array_ dalla funzione invece della _lunghezza dell'array_, serve fare un return di `list` dopo aver inserito l'`item`. + +

+
+ +--- + +###### 75. Qual è l'output? + +```javascript +const box = { x: 10, y: 20 }; + +Object.freeze(box); + +const shape = box; +shape.x = 100; + +console.log(shape); +``` + +- A: `{ x: 100, y: 20 }` +- B: `{ x: 10, y: 20 }` +- C: `{ x: 100 }` +- D: `ReferenceError` + +
Risposta +

+ +#### Risposta: B + +`Object.freeze` rende impossibile aggiungere, rimuovere o modificare le proprietà di un oggetto (a meno che il valore della proprietà non sia un altro oggetto). + +Quando creiamo la variabile `shape` e la impostiamo come all'oggetto congelato `box`, anche `shape` si riferisce ad un oggetto congelato. +Puoi controllare se un oggetto è congelato usando `Object.isFrozen`. In questo caso, `Object.isFrozen(shape)` restituisce true, poiché la variabile `shape` ha un riferimento a un oggetto congelato. + +Poiché `shape` è congelata, e poiché il valore di `x` non è un oggetto, non possiamo modificare la proprietà `x`. +`x` è ancora uguale a `10` e `{ x: 10, y: 20 }` viene loggato. + +

+
+ +--- + +###### 76. Qual è l'output? + +```javascript +const { name: myName } = { name: 'Lydia' }; + +console.log(name); +``` + +- A: `"Lydia"` +- B: `"myName"` +- C: `undefined` +- D: `ReferenceError` + +
Risposta +

+ +#### Risposta: C + +Quando spacchettiamo la proprietà `name` dall'oggetto, assegniamo il suo valore `"Lydia"` a una variabile con il nome `myName`. + +Con `{ name: myName }`, diciamo a JavaScript che vogliamo creare una nuova variabile chiamata `myName` con il valore della proprietà `name`. + +Poiché proviamo a loggare `name`, una variabile che non è definita, viene restituito `undefined` nell'assegnazione. Successivamente, il valore di `Lydia` viene memorizzato tramite l'assegnazione di destrutturazione. + +

+
+ +--- + +###### 77. Questa è una funzione pura? + +```javascript +function sum(a, b) { + return a + b; +} +``` + +- A: Yes +- B: No + +
Risposta +

+ +#### Risposta: A + +Una funzione pura è una funzione che restituisce _sempre_ lo stesso risultato, se vengono passati gli stessi argomenti. + +La funzione `sum` restituisce sempre lo stesso risultato. Se le passiamo `1` e `2`, restituirà _sempre_ `3` senza effetti collaterali. Se passiamo `5` e `10`, restituirà _sempre_ `15` e così via. Questa è la definizione di funzione pura. + +

+
+ +--- + +###### 78. Qual è l'output? + +```javascript +const add = () => { + const cache = {}; + return num => { + if (num in cache) { + return `From cache! ${cache[num]}`; + } else { + const result = num + 10; + cache[num] = result; + return `Calculated! ${result}`; + } + }; +}; + +const addFunction = add(); +console.log(addFunction(10)); +console.log(addFunction(10)); +console.log(addFunction(5 * 2)); +``` + +- A: `Calculated! 20` `Calculated! 20` `Calculated! 20` +- B: `Calculated! 20` `From cache! 20` `Calculated! 20` +- C: `Calculated! 20` `From cache! 20` `From cache! 20` +- D: `Calculated! 20` `From cache! 20` `Error` + +
Risposta +

+ +#### Risposta: C + +La funzione `add` è una funzione _memoizzata_. Con la memorizzazione, possiamo memorizzare nella cache i risultati di una funzione per velocizzarne l'esecuzione. +In questo caso, creiamo un oggetto `cache` che memorizza i valori precedentemente restituiti. + +Se chiamiamo di nuovo la funzione `addFunction` con lo stesso argomento, prima controlla se ha già ottenuto quel valore nella sua cache, in tal caso, verrà restituito il valore delle cache, il che consente di risparmiare tempo di esecuzione. Altrimenti, se non è memorizzato nella cache, calcolerà il valore e lo memorizzerà in seguito. + +Chiamiamo la funzione `addFunction` tre volte con lo stesso valore: alla prima chiamata, il valore della funzione quando `num` è uguale a `10` non è ancora memorizzato nella cache. +La condizione dell'istruzione if `num in cache` restituisce `false`, e il blocco else viene eseguito: `Calculated! 20` viene loggato e il valore del risultato viene aggiunto all'oggetto cache. +`cache` ora è uguale a `{ 10: 20 }`. + +La seconda volta, l'oggetto `cache` contiene il valore che viene restituito per `10`. La condizione dell'istruzione if `num in cache` restituisce `true` e `'From cache! 20'` viene loggato. + +La terza volta, passiamo `5 * 2` alla funzione che viene valutata a `10`. L'oggetto `cache` contiene il valore che viene restituito `10`. La condizione dell'istruzione if `num in cache` restituisce `true` e `'From cache! 20'` viene registrato. + +

+
+ +--- + +###### 79. Qual è l'output? + +```javascript +const myLifeSummedUp = ['☕', '💻', '🍷', '🍫']; + +for (let item in myLifeSummedUp) { + console.log(item); +} + +for (let item of myLifeSummedUp) { + console.log(item); +} +``` + +- A: `0` `1` `2` `3` and `"☕"` `"💻"` `"🍷"` `"🍫"` +- B: `"☕"` `"💻"` `"🍷"` `"🍫"` and `"☕"` `"💻"` `"🍷"` `"🍫"` +- C: `"☕"` `"💻"` `"🍷"` `"🍫"` and `0` `1` `2` `3` +- D: `0` `1` `2` `3` and `{0: "☕", 1: "💻", 2: "🍷", 3: "🍫"}` + +
Risposta +

+ +#### Risposta: A + +Con un ciclo _for-in_, possiamo scorrere su proprietà **enumerabile**. In un array, le proprietà enumerabili sono le "chiavi" degli elementi dell'array, che sono in realtà i loro indici. Potresti immaginare un array come: + +`{0: "☕", 1: "💻", 2: "🍷", 3: "🍫"}` + +Dove le chiavi sono le proprietà enumerabili. `0` `1` `2` `3` viene quindi loggato. + +Con un ciclo _for-of_, possiamo iterare su **iterabili**. Un array è un iterabile. Quando iteriamo sull'array, la variabile "item" è uguale all'elemento su cui sta attualmente iterando, `"☕"` `"💻"` `"🍷"` `"🍫"` viene loggato. + +

+
+ +--- + +###### 80. Qual è l'output? + +```javascript +const list = [1 + 2, 1 * 2, 1 / 2]; +console.log(list); +``` + +- A: `["1 + 2", "1 * 2", "1 / 2"]` +- B: `["12", 2, 0.5]` +- C: `[3, 2, 0.5]` +- D: `[1, 1, 1]` + +
Risposta +

+ +#### Risposta: C + +Gli elementi di un array possono contenere qualsiasi valore. Numeri, stringhe, oggetti, altri array, null, booleani, undefined e altre espressioni come date, funzioni e calcoli. + +L'elemento sarà uguale al valore restituito. `1 + 2` restituirà quindi `3`, `1 * 2` restituirà `2` e `1 / 2` restituirà `0.5`. + +

+
+ +--- + +###### 81. Qual è l'output? + +```javascript +function sayHi(name) { + return `Hi there, ${name}`; +} + +console.log(sayHi()); +``` + +- A: `Hi there,` +- B: `Hi there, undefined` +- C: `Hi there, null` +- D: `ReferenceError` + +
Risposta +

+ +#### Risposta: B + +Di default, gli argomenti hanno il valore di `undefined`, a meno che un valore non sia stato passato alla funzione. In questo caso, non abbiamo passato un valore per l'argomento `name`. `name` è uguale a `undefined` che viene loggato. + +In ES6, possiamo sovrascrivere questo valore predefinito `undefined` con dei parametri predefiniti. Per esempio: + +`function sayHi(name = "Lydia") { ... }` + +In questo caso, se non abbiamo passato un valore o se abbiamo passato `undefined`, `name` sarà sempre uguale alla stringa `Lydia` + +

+
+ +--- + +###### 82. Qual è l'output? + +```javascript +var status = '😎'; + +setTimeout(() => { + const status = '😍'; + + const data = { + status: '🥑', + getStatus() { + return this.status; + }, + }; + + console.log(data.getStatus()); + console.log(data.getStatus.call(this)); +}, 0); +``` + +- A: `"🥑"` e `"😍"` +- B: `"🥑"` e `"😎"` +- C: `"😍"` e `"😎"` +- D: `"😎"` e `"😎"` + +
Risposta +

+ +#### Risposta: B + +Il valore della parola chiave `this` dipende da dove la usi. In un **metodo**, come il metodo `getStatus`, la parola chiave `this` si riferisce all'_oggetto a cui appartiene il metodo_. Nel nostro caso il metodo appartiene all'oggetto `data`, quindi `this` si riferisce all'oggetto `data`. Quando logghiamo `this.status`, stiamo chiedendo la proprietà `status` sull'oggetto `data` che è `"🥑"`. + +Con il metodo `call` possiamo cambiare l'oggetto a cui fa riferimento la parola chiave `this`. Nelle **funzioni**, la parola chiave `this` si riferisce all'_oggetto a cui appartiene la funzione_. Abbiamo dichiarato la funzione `setTimeout` sull'_oggetto globale_, quindi all'interno della funzione `setTimeout`, la parola chiave `this` si riferisce all'_oggetto globale_. Sull'oggetto globale c'è una variabile chiamata _status_ con il valore di `"😎"`. Quando si fa un console.log di `this.status`, otteniamo `"😎"`. + +

+
+ +--- + +###### 83. Qual è l'output? + +```javascript +const person = { + name: 'Lydia', + age: 21, +}; + +let city = person.city; +city = 'Amsterdam'; + +console.log(person); +``` + +- A: `{ name: "Lydia", age: 21 }` +- B: `{ name: "Lydia", age: 21, city: "Amsterdam" }` +- C: `{ name: "Lydia", age: 21, city: undefined }` +- D: `"Amsterdam"` + +
Risposta +

+ +#### Risposta: A + +Impostiamo la variabile `city` uguale al valore della proprietà chiamata `city` sull'oggetto `person`. Non c'è alcuna proprietà su questo oggetto chiamato `city`, quindi la variabile `city` ha il valore di `undefined`. + +Nota che _non_ stiamo facendo riferimento all'oggetto `person`! Impostiamo semplicemente la variabile `city` uguale al valore corrente della proprietà `city` sull'oggetto `person`. + +Quindi, impostiamo `city` uguale alla stringa `"Amsterdam"`. Questo non cambia l'oggetto person: non c'è alcun riferimento a quell'oggetto. + +Quando si logga l'oggetto `person`, viene restituito l'oggetto non modificato. + +

+
+ +--- + +###### 84. Qual è l'output? + +```javascript +function checkAge(age) { + if (age < 18) { + const message = "Sorry, you're too young."; + } else { + const message = "Yay! You're old enough!"; + } + + return message; +} + +console.log(checkAge(21)); +``` + +- A: `"Sorry, you're too young."` +- B: `"Yay! You're old enough!"` +- C: `ReferenceError` +- D: `undefined` + +
Risposta +

+ +#### Risposta: C + +Le variabili con la chiave `const` e `let` sono _block-scoped_. Un blocco è qualsiasi cosa si trovi tra parentesi graffe (`{ }`). In questo caso, le parentesi graffe delle istruzioni if/else. Non puoi fare riferimento a una variabile al di fuori del blocco in cui è dichiarata, viene quindi generato un ReferenceError. + +

+
+ +--- + +###### 85. Che tipo di informazioni verrebbero registrate? + +```javascript +fetch('https://www.website.com/api/user/1') + .then(res => res.json()) + .then(res => console.log(res)); +``` + +- A: Il risultato del metodo `fetch`. +- B: Il risultato della seconda invocazione del metodo `fetch`. +- C: Il risultato della callback nel precedente `.then()`. +- D: Sarebbe sempre undefined. + +
Risposta +

+ +#### Risposta: C + +Il valore di `res` nel secondo `.then` è uguale al valore restituito del precedente `.then`. Puoi continuare a concatenare i `.then` in questo modo, dove il valore viene passato al gestore successivo. + +

+
+ +--- + +###### 86. Quale opzione è un modo per impostare `hasName` uguale a `true`, se non puoi passare `true` come argomento? + +```javascript +function getName(name) { + const hasName = // +} +``` + +- A: `!!name` +- B: `name` +- C: `new Boolean(name)` +- D: `name.length` + +
Risposta +

+ +#### Risposta: A + +Con `!!name`, determiniamo se il valore di `name` è vero o falso. Se il nome è vero, cosa che vogliamo testare, `!name` restituisce `false`. +`!false` (che è `!!name`) restituisce `true`. + +Impostando `hasName` uguale a `name`, imposti `hasName` uguale a qualsiasi valore passato alla funzione `getName`, non il valore booleano `true`. + +`new Boolean(true)` restituisce un oggetto wrapper, non il valore booleano stesso. + +`name.length` restituisce la lunghezza dell'argomento passato, non se è `true`. + +

+
+ +--- + +###### 87. Qual è l'output? + +```javascript +console.log('I want pizza'[0]); +``` + +- A: `"""` +- B: `"I"` +- C: `SyntaxError` +- D: `undefined` + +
Risposta +

+ +#### Risposta: B + +Per ottenere un carattere in un indice specifico di una stringa, puoi usare la notazione tra parentesi. Il primo carattere nella stringa ha indice 0 e così via. In questo caso, vogliamo ottenere l'elemento con indice 0, il carattere `"I'`, che viene loggato. + +Tieni presente che questo metodo non è supportato in IE7 e versioni precedenti. In tal caso, usa `.charAt()`. + +

+
+ +--- + +###### 88. Qual è l'output? + +```javascript +function sum(num1, num2 = num1) { + console.log(num1 + num2); +} + +sum(10); +``` + +- A: `NaN` +- B: `20` +- C: `ReferenceError` +- D: `undefined` + +
Risposta +

+ +#### Risposta: B + +È possibile impostare il valore di un parametro predefinito uguale a un altro parametro della funzione, purché siano stati definiti _prima_ del parametro predefinito. Passiamo il valore `10` alla funzione `sum`. Se la funzione `sum` riceve solo 1 argomento, significa che il valore di `num2` non è passato e il valore di `num1` è uguale al valore passato `10` in questo caso. Il valore predefinito di `num2` è il valore di `num1`, che è `10`. `num1 + num2` restituisce `20`. + +Se stai cercando di impostare il valore di un parametro predefinito uguale a un parametro che è definito _dopo_ (a destra), il valore del parametro non è stato ancora inizializzato, il che genererà un errore. +

+
+ +--- + +###### 89. Qual è l'output? + +```javascript +// module.js +export default () => 'Hello world'; +export const name = 'Lydia'; + +// index.js +import * as data from './module'; + +console.log(data); +``` + +- A: `{ default: function default(), name: "Lydia" }` +- B: `{ default: function default() }` +- C: `{ default: "Hello world", name: "Lydia" }` +- D: Global object of `module.js` + +
Risposta +

+ +#### Risposta: A + +Con la sintassi `import * as name`, importiamo _tutte le esportazioni_ dal file `module.js` nel file `index.js` come nuovo oggetto chiamato `data`. Nel file `module.js` ci sono due esportazioni: l'esportazione predefinita e un'esportazione denominata. L'esportazione predefinita è una funzione che restituisce la stringa `"Hello World"`, e l'esportazione denominata è una variabile chiamata `name` che ha il valore della stringa `"Lydia"`. + +L'oggetto `data` ha una proprietà `default` per l'esportazione predefinita, altre proprietà hanno i nomi delle esportazioni e i loro valori corrispondenti. + +

+
+ +--- + +###### 90. Qual è l'output? + +```javascript +class Person { + constructor(name) { + this.name = name; + } +} + +const member = new Person('John'); +console.log(typeof member); +``` + +- A: `"class"` +- B: `"function"` +- C: `"object"` +- D: `"string"` + +
Risposta +

+ +#### Risposta: C + +Le classi sono come caramelle sintattiche. L'equivalente della classe `Person` come funzione sarebbe: + +```javascript +function Person() { + this.name = name; +} +``` + +Instanziando un costruttore con `new` si ottiene la creazione di un'istanza di `Person`, la chiave `typeof` restituisce `"object"`. `typeof member` restituisce `"object"`. + +

+
+ +--- + +###### 91. Qual è l'output? + +```javascript +let newList = [1, 2, 3].push(4); + +console.log(newList.push(5)); +``` + +- A: `[1, 2, 3, 4, 5]` +- B: `[1, 2, 3, 5]` +- C: `[1, 2, 3, 4]` +- D: `Error` + +
Risposta +

+ +#### Risposta: D + +Il metodo `.push` restituisce la _nuova lunghezza_ dell'array, non l'array stesso! Impostando `newList` uguale a `[1, 2, 3].push(4)`, settiamo `newList` uguale alla nuova lunghezza dell'array: `4`. + +Quindi quando proviamo a usare il metodo `.push` su `newList` poiché `newList` è il valore numerico `4`, non possiamo usare il metodo `.push` e viene generato un TypeError. + +

+
+ +--- + +###### 92. Qual è l'output? + +```javascript +function giveLydiaPizza() { + return 'Here is pizza!'; +} + +const giveLydiaChocolate = () => + "Here's chocolate... now go hit the gym already."; + +console.log(giveLydiaPizza.prototype); +console.log(giveLydiaChocolate.prototype); +``` + +- A: `{ constructor: ...}` `{ constructor: ...}` +- B: `{}` `{ constructor: ...}` +- C: `{ constructor: ...}` `{}` +- D: `{ constructor: ...}` `undefined` + +
Risposta +

+ +#### Risposta: D + +Le funzioni regolari, come la funzione `giveLydiaPizza`, hanno una proprietà `prototipo`, che è un oggetto (prototype object) con un `costruttore`. Tuttavia, le arrow functions, come la funzione `giveLydiaChocolate`, non hanno una proprietà `prototype`. Viene quindi restituito `undefined` quando si tenta di accedere alla proprietà `prototype` usando `giveLydiaChocolate.prototype`. +

+
+ +--- + +###### 93. Qual è l'output? + +```javascript +const person = { + name: 'Lydia', + age: 21, +}; + +for (const [x, y] of Object.entries(person)) { + console.log(x, y); +} +``` + +- A: `name` `Lydia` e `age` `21` +- B: `["name", "Lydia"]` e `["age", 21]` +- C: `["name", "age"]` e `undefined` +- D: `Error` + +
Risposta +

+ +#### Risposta: A + +`Object.entries(person)` restituisce un array di array nidificati, contenente le chiavi e gli oggetti: + +`[ [ 'name', 'Lydia' ], [ 'age', 21 ] ]` + +Usando il ciclo `for-of`, possiamo scorrere ogni elemento nell'array, i sottoarray in questo caso. Possiamo destrutturare i sottoarray istantaneamente nel ciclo for-of, usando `const [x, y]`. `x` è uguale al primo elemento, `y` è uguale al secondo elemento. + +Il primo sottoarray è `[ "name", "Lydia" ]`, con `x` uguale a `"name"`, e `y` uguale a `"Lydia"`, che vengono loggati. +Il secondo sottoarray è `[ "age", 21 ]`, con `x` uguale a `"age"`, e `y` uguale a `21`, che vengono loggati. + +

+
+ +--- + +###### 94. Qual è l'output? + +```javascript +function getItems(fruitList, ...args, favoriteFruit) { + return [...fruitList, ...args, favoriteFruit] +} + +getItems(["banana", "apple"], "pear", "orange") +``` + +- A: `["banana", "apple", "pear", "orange"]` +- B: `[["banana", "apple"], "pear", "orange"]` +- C: `["banana", "apple", ["pear"], "orange"]` +- D: `SyntaxError` + +
Risposta +

+ +#### Risposta: D + +`...args` è un parametro rest. Il valore del parametro rest è un array contenente tutti gli argomenti, **e può essere solo l'ultimo parametro**! In questo esempio, il parametro rest è in seconda posizione. Questo non è possibile e genererà un errore di sintassi. + +```javascript +function getItems(fruitList, favoriteFruit, ...args) { + return [...fruitList, ...args, favoriteFruit]; +} + +getItems(['banana', 'apple'], 'pear', 'orange'); +``` + +L'esempio qui sopra invece funziona e restituisce l'array `[ 'banana', 'apple', 'orange', 'pear' ]` + +

+
+ +--- + +###### 95. Qual è l'output? + +```javascript +function nums(a, b) { + if (a > b) console.log('a is bigger'); + else console.log('b is bigger'); + return + a + b; +} + +console.log(nums(4, 2)); +console.log(nums(1, 2)); +``` + +- A: `a is bigger`, `6` and `b is bigger`, `3` +- B: `a is bigger`, `undefined` and `b is bigger`, `undefined` +- C: `undefined` and `undefined` +- D: `SyntaxError` + +
Risposta +

+ +#### Risposta: B + +In JavaScript, non _è necessario_ scrivere il punto e virgola (`;`) in modo esplicito poichè il motore JavaScript li aggiunge comunque dopo le istruzioni. +Questo procedimento è chiamato **Automatic Semicolon Insertion**. Un'istruzione può ad esempio essere una variabile o parole chiave come `throw`, `return`, `break`, ecc. + +Qui, abbiamo scritto un'istruzione di `return` e un altro valore `a + b` su una _nuova riga_. Tuttavia, trattandosi di una nuova linea, il motore non sa che in realtà è il valore che volevamo restituire. Invece, ha aggiunto automaticamente un punto e virgola dopo "return". + +Potresti considerare ad esempio: + +```javascript +return; +a + b; +``` + +`a + b` non viene mai raggiunto, poiché la funzione smette di funzionare dopo la parola chiave `return`. +Se non viene restituito alcun valore, come qui, la funzione restituisce `undefined`. Nota: non c'è un inserimento automatico dopo le istruzioni `if/else`! + +

+
+ +--- + +###### 96. Qual è l'output? + +```javascript +class Person { + constructor() { + this.name = 'Lydia'; + } +} + +Person = class AnotherPerson { + constructor() { + this.name = 'Sarah'; + } +}; + +const member = new Person(); +console.log(member.name); +``` + +- A: `"Lydia"` +- B: `"Sarah"` +- C: `Error: cannot redeclare Person` +- D: `SyntaxError` + +
Risposta +

+ +#### Risposta: B + +Possiamo impostare classi uguali ad altre classi/costruttori di funzioni. In questo caso, impostiamo `Person` uguale a `AnotherPerson`. Il name su questo costruttore è `Sarah`, quindi la proprietà del nome di`Person` sulla nuova istanza `member` è `"Sarah"`. + +

+
+ +--- + +###### 97. Qual è l'output? + +```javascript +const info = { + [Symbol('a')]: 'b', +}; + +console.log(info); +console.log(Object.keys(info)); +``` + +- A: `{Symbol('a'): 'b'}` e `["{Symbol('a')"]` +- B: `{}` e `[]` +- C: `{ a: "b" }` e `["a"]` +- D: `{Symbol('a'): 'b'}` e `[]` + +
Risposta +

+ +#### Risposta: D + +Un simbolo non è _enumerabile_. Il metodo Object.keys restituisce tutte le proprietà _enumerabili_ su un oggetto. Il simbolo non sarà visibile e verrà restituito un array vuoto. Quando si logga l'intero oggetto, tutte le proprietà saranno visibili, anche quelle non enumerabili. + +Questa è una delle tante qualità di un simbolo: oltre a rappresentare un valore del tutto univoco (che evita collisioni accidentali di nomi sugli oggetti, ad esempio quando si lavora con 2 librerie che vogliono aggiungere proprietà allo stesso oggetto), puoi anche "nascondere" proprietà sugli oggetti in questo modo (anche se non del tutto. Puoi comunque accedere ai simboli usando il metodo `Object.getOwnPropertySymbols()`). + +

+
+ +--- + +###### 98. Qual è l'output? + +```javascript +const getList = ([x, ...y]) => [x, y] +const getUser = user => { name: user.name, age: user.age } + +const list = [1, 2, 3, 4] +const user = { name: "Lydia", age: 21 } + +console.log(getList(list)) +console.log(getUser(user)) +``` + +- A: `[1, [2, 3, 4]]` e `SyntaxError` +- B: `[1, [2, 3, 4]]` e `{ name: "Lydia", age: 21 }` +- C: `[1, 2, 3, 4]` e `{ name: "Lydia", age: 21 }` +- D: `Error` e `{ name: "Lydia", age: 21 }` + +
Risposta +

+ +#### Risposta: A + +La funzione `getList` riceve un array come argomento. Tra le parentesi della funzione `getList`, destrutturiamo subito questo array. Esempio: + +`[x, ...y] = [1, 2, 3, 4]` + +Con il parametro rest `...y`, mettiamo tutti gli argomenti "rimanenti" in un array. Gli argomenti rimanenti sono `2`, `3` e `4` in questo caso. +Il valore di `y` è un array, contenente tutti i parametri rimanenti. Il valore di `x` è uguale a `1` in questo caso, quindi quando facciamo un console.log di `[x, y]`, viene loggato `[1, [2, 3, 4]]`. + +La funzione `getUser` riceve un oggetto. Con le arrow functions, non _è necessario_ scrivere parentesi graffe se restituiamo solo un valore. Tuttavia, se vuoi restituire istantaneamente un _oggetto_ da una arrow function, devi scriverlo tra parentesi, altrimenti tutto ciò che si trova tra le due parentesi verrà interpretato come un'istruzione di blocco. In questo caso il codice tra parentesi non è un codice JavaScript valido, quindi viene generato un `SyntaxError`. + +La seguente funzione avrebbe restituito un oggetto: + +`const getUser = user => ({ name: user.name, age: user.age })` + +

+
+ +--- + +###### 99. Qual è l'output? + +```javascript +const name = 'Lydia'; + +console.log(name()); +``` + +- A: `SyntaxError` +- B: `ReferenceError` +- C: `TypeError` +- D: `undefined` + +
Risposta +

+ +#### Risposta: C + +La variabile `name` contiene il valore di una stringa, che non è una funzione, quindi non può essere invocata. + +I TypeErrors vengono generati quando un valore non è del tipo previsto. JavaScript "prevede" che `name` è una funzione poiché stiamo cercando di invocarla. In realtà è una stringa, quindi viene generato un TypeError: name is not a function! + +I SyntaxErrors vengono generati quando si scrive qualcosa che non è valido in JavaScript, ad esempio quando si scrive la parola `return` come `rerun`. +I ReferenceErrors vengono generati quando JavaScript non è in grado di trovare un riferimento a un valore a cui stai tentando di accedere. + +

+
+ +--- + +###### 100. Qual è il valore dell'output? + +```javascript +// 🎉✨ This is my 100th question! ✨🎉 + +const output = `${[] && 'Im'}possible! +You should${'' && `n't`} see a therapist after so much JavaScript lol`; +``` + +- A: `possible! You should see a therapist after so much JavaScript lol` +- B: `Impossible! You should see a therapist after so much JavaScript lol` +- C: `possible! You shouldn't see a therapist after so much JavaScript lol` +- D: `Impossible! You shouldn't see a therapist after so much JavaScript lol` + +
Risposta +

+ +#### Risposta: B + +`[]` è un valore vero. Con l'operatore `&&`, verrà restituito il valore di destra se il valore di sinistra è un valore reale. In questo caso, il valore di sinistra `[]` è un valore vero, quindi `"Im'` viene restituito. + +`""` è un valore falso. Se il valore di sinistra è falso, non viene restituito nulla. `n't` quindi non viene restituito. + +

+
+ +--- + +###### 101. Qual è il valore dell'output? + +```javascript +const one = false || {} || null; +const two = null || false || ''; +const three = [] || 0 || true; + +console.log(one, two, three); +``` + +- A: `false` `null` `[]` +- B: `null` `""` `true` +- C: `{}` `""` `[]` +- D: `null` `null` `true` + +
Risposta +

+ +#### Risposta: C + +Con l'operatore `||` possiamo restituire il primo operando veritiero. Se tutti i valori sono falsi, viene restituito l'ultimo operando. + +`(false || {} || null)`: l'oggetto vuoto `{}` è un valore veritiero. Questo è il primo (e unico) valore veritiero, che viene restituito. `one` è uguale a `{}`. + +`(null || false || "")`: tutti gli operandi sono valori falsi. Ciò significa che viene restituito l'ultimo operando, `""`. `two` è uguale a `""`. + +`([] || 0 || "")`: l'array vuoto`[]` è un valore veritiero. Questo è il primo valore veritiero, che viene restituito. `three` è uguale a `[]`. + +

+
+ +--- + +###### 102. Qual è il valore dell'output? + +```javascript +const myPromise = () => Promise.resolve('I have resolved!'); + +function firstFunction() { + myPromise().then(res => console.log(res)); + console.log('second'); +} + +async function secondFunction() { + console.log(await myPromise()); + console.log('second'); +} + +firstFunction(); +secondFunction(); +``` + +- A: `I have resolved!`, `second` e `I have resolved!`, `second` +- B: `second`, `I have resolved!` e `second`, `I have resolved!` +- C: `I have resolved!`, `second` e `second`, `I have resolved!` +- D: `second`, `I have resolved!` e `I have resolved!`, `second` + +
Risposta +

+ +#### Risposta: D + +Con una promise, in pratica diciamo _Voglio eseguire questa funzione, ma per ora la metto da parte mentre è in esecuzione poiché ciò potrebbe richiedere del tempo. Solo quando un determinato valore viene risolto (o rifiutato) e quando lo stack di chiamate è vuoto, voglio utilizzare questo valore._ + +Possiamo ottenere questo valore sia con `.then` che con la chiave `await` in una funzione `async`. Sebbene possiamo ottenere il valore di una promessa sia con `.then` che con `await`, funzionano in modo leggermente diverso. + +Nella `first Function`, abbiamo (più o meno) messo da parte la funzione myPromise mentre era in esecuzione, ma abbiamo continuato a eseguire l'altro codice, che in questo caso è `console.log('second')`. Quindi, la funzione è stata risolta con la stringa `I have resolved`, che è stata quindi loggata dopo aver visto che lo stack di chiamate era vuoto. + +Con await in `secondFunction`, mettiamo letteralmente in pausa l'esecuzione di una funzione asincrona fino a quando il valore non è stato risolto prima di passare alla riga successiva. + +Ciò significa che ha aspettato che `myPromise` si risolvesse con il valore `I have resolved`, e solo allora, siamo passati alla riga successiva e `second` è stato loggato. + +

+
+ +--- + +###### 103. Qual è il valore dell'output? + +```javascript +const set = new Set(); + +set.add(1); +set.add('Lydia'); +set.add({ name: 'Lydia' }); + +for (let item of set) { + console.log(item + 2); +} +``` + +- A: `3`, `NaN`, `NaN` +- B: `3`, `7`, `NaN` +- C: `3`, `Lydia2`, `[object Object]2` +- D: `"12"`, `Lydia2`, `[object Object]2` + +
Risposta +

+ +#### Risposta: C + +L'operatore `+` non viene utilizzato solo per aggiungere valori numerici, ma possiamo anche usarlo per concatenare stringhe. Ogni volta che il motore JavaScript vede che uno o più valori non sono un numero, forza il numero in una stringa. + +Il primo è `1`, che è un valore numerico. `1 + 2` restituisce il numero 3. + +Tuttavia, la seconda è una stringa `"Lydia"`. `"Lydia"` è una stringa e `2` è un numero: `2` viene forzato in una stringa. `"Lydia"` e `"2"` vengono concatenati, il che risulta nella stringa `"Lydia2"`. + +`{ name: "Lydia" }` è un oggetto. Né un numero né un oggetto sono una stringa, quindi li rende stringhe entrambi. Ogni volta che stringhiamo un oggetto regolare, diventa `"[object Object]"`. `"[object Object]"` concatenato con `2` diventa `"[object Object]"`. + +

+
+ +--- + +###### 104. Qual è il suo valore? + +```javascript +Promise.resolve(5); +``` + +- A: `5` +- B: `Promise {: 5}` +- C: `Promise {: 5}` +- D: `Error` + +
Risposta +

+ +#### Risposta: C + +Possiamo passare a `Promise.resolve` qualsiasi tipo di valore desideriamo, sia una promise che una non-promise. Il metodo stesso restituisce una promise con il valore risolto (``). Se si passa una funzione regolare, sarà una promise risolta con un valore regolare. Se mandi una promise, sarà una promise risolta con il valore risolto di quella promise passata. + +In questo caso, abbiamo appena passato il valore numerico `5`. Restituisce una promise risolta con il valore `5`. + +

+
+ +--- + +###### 105. Qual è il suo valore? + +```javascript +function compareMembers(person1, person2 = person) { + if (person1 !== person2) { + console.log('Not the same!'); + } else { + console.log('They are the same!'); + } +} + +const person = { name: 'Lydia' }; + +compareMembers(person); +``` + +- A: `Not the same!` +- B: `They are the same!` +- C: `ReferenceError` +- D: `SyntaxError` + +
Risposta +

+ +#### Risposta: B + +Gli oggetti vengono passati per riferimento. Quando controlliamo gli oggetti per strict equality (`===`), stiamo confrontando i loro riferimenti. + +Abbiamo impostato il valore predefinito per `person2` uguale all'oggetto `person` e abbiamo passato l'oggetto `person` come valore per `person1`. + +Ciò significa che entrambi i valori hanno un riferimento allo stesso punto in memoria, quindi sono uguali. + +Il blocco di codice nell'istruzione `else` viene eseguito e `They are the same!` viene loggato. + +

+
+ +--- + +###### 106. Qual è il suo valore? + +```javascript +const colorConfig = { + red: true, + blue: false, + green: true, + black: true, + yellow: false, +}; + +const colors = ['pink', 'red', 'blue']; + +console.log(colorConfig.colors[1]); +``` + +- A: `true` +- B: `false` +- C: `undefined` +- D: `TypeError` + +
Risposta +

+ +#### Risposta: D + +In JavaScript, abbiamo due modi per accedere alle proprietà di un oggetto: le bracket notation o le dot notation. In questo esempio, utilizziamo la notazione con il punto (`colorConfig.colors`) invece della notazione tra parentesi (`colorConfig["colors"]`). + +Con la notazione del punto, JavaScript tenta di trovare la proprietà sull'oggetto con quel nome esatto. In questo esempio, JavaScript tenta di trovare una proprietà chiamata `colors` sull'oggetto `colorConfig`. Non esiste una proprietà chiamata `colors`, quindi restituisce `undefined`. Quando proviamo ad accedere al valore del primo elemento usando `[1]`, non possiamo farlo su un valore che è `undefined`, quindi genera un `TypeError`: `Cannot read property '1' of undefined`. + +JavaScript interpreta (o decomprime) le istruzioni. Quando usiamo la notazione tra parentesi, vede la prima parentesi aperta `[` e continua finché non trova la parentesi chiusa `]`. Solo allora valuterà la dichiarazione. Se avessimo usato `colorConfig[colors[1]]`, avrebbe restituito il valore della proprietà `red` sull'oggetto `colorConfig`. + +

+
+ +--- + +###### 107. Qual è il suo valore? + +```javascript +console.log('❤️' === '❤️'); +``` + +- A: `true` +- B: `false` + +
Risposta +

+ +#### Risposta: A + +Le emoji sono unicode. L'unicode per l'emoji del cuore è `"U+2764 U+FE0F"`. Questi sono sempre gli stessi per gli stessi emoji, stiamo confrontando due stringhe uguali tra loro, e quindi restituisce true. + +

+
+ +--- + +###### 108. Quale di questi metodi modifica l'array originale? + +```javascript +const emojis = ['✨', '🥑', '😍']; + +emojis.map(x => x + '✨'); +emojis.filter(x => x !== '🥑'); +emojis.find(x => x !== '🥑'); +emojis.reduce((acc, cur) => acc + '✨'); +emojis.slice(1, 2, '✨'); +emojis.splice(1, 2, '✨'); +``` + +- A: `All of them` +- B: `map` `reduce` `slice` `splice` +- C: `map` `slice` `splice` +- D: `splice` + +
Risposta +

+ +#### Risposta: D + +Con il metodo `splice` modifichiamo l'array originale cancellando, sostituendo o aggiungendo elementi. In questo caso, abbiamo rimosso 2 elementi dall'indice 1 (abbiamo rimosso `'🥑'` e `'😍'`) e aggiunto invece l'emoji ✨. + +`map`, `filter` e `slice` restituiscono un nuovo array, `find` restituisce un elemento e `reduce` restituisce un valore ridotto. +

+
+ +--- + +###### 109. Qual è l'output? + +```javascript +const food = ['🍕', '🍫', '🥑', '🍔']; +const info = { favoriteFood: food[0] }; + +info.favoriteFood = '🍝'; + +console.log(food); +``` + +- A: `['🍕', '🍫', '🥑', '🍔']` +- B: `['🍝', '🍫', '🥑', '🍔']` +- C: `['🍝', '🍕', '🍫', '🥑', '🍔']` +- D: `ReferenceError` + +
Risposta +

+ +#### Risposta: A + +Impostiamo il valore della proprietà `favoriteFood` sull'oggetto `info` uguale alla stringa con l'emoji della pizza, `'🍕'`. Una stringa è un tipo di dati primitivo. In JavaScript, i tipi di dati primitivi non interagiscono per riferimento. + +In JavaScript, i tipi di dati primitivi (tutto ciò che non è un oggetto) interagiscono per _value_. In questo caso, impostiamo il valore della proprietà `favoriteFood` sull'oggetto `info` uguale al valore del primo elemento nell'array `food`, in questo caso la stringa con l'emoji della pizza (`'🍕'`). Una stringa è un tipo di dati primitivo e interagisce per valore (vedi il mio [blogpost](https://www.theavocoder.com/complete-javascript/2018/12/21/by-value-vs-by-reference) se sei interessato a saperne di più) + +Quindi, cambiamo il valore della proprietà `favoriteFood` sull'oggetto `info`. L'array `food` non è cambiato, poiché il valore di `favoriteFood` era semplicemente una _copia_ del valore del primo elemento nell'array e non ha un riferimento allo stesso punto in memoria dell'elemento su ` food[0]`. Quando logghiamo food, è ancora l'array originale, `['🍕', '🍫', '🥑', '🍔']`. +

+
+ +--- + +###### 110. Cosa fa questo metodo? + +```javascript +JSON.parse(); +``` + +- A: converte JSON in un valore JavaScript +- B: converte un oggetto JavaScript in JSON +- C: converte qualsiasi valore JavaScript in JSON +- D: converte JSON in un oggetto solo JavaScript + +
Risposta +

+ +#### Risposta: A + +Con il metodo `JSON.parse()`, possiamo analizzare la stringa JSON come un valore JavaScript. + +```javascript +// Stringhiamo un numero in un JSON valido, quindi analizziamo la stringa JSON come valore JavaScript: +const jsonNumber = JSON.stringify(4); // '4' +JSON.parse(jsonNumber); // 4 + +// Stringhiamo un array in un JSON valido, quindi analizziamo la stringa JSON come valore JavaScript: +const jsonArray = JSON.stringify([1, 2, 3]); // '[1, 2, 3]' +JSON.parse(jsonArray); // [1, 2, 3] + +// Stringhiamo un object in un JSON valido, quindi analizziamo la stringa JSON come valore JavaScript: +const jsonArray = JSON.stringify({ name: 'Lydia' }); // '{"name":"Lydia"}' +JSON.parse(jsonArray); // { name: 'Lydia' } +``` + +

+
+ +--- + +###### 111. Qual è l'output? + +```javascript +let name = 'Lydia'; + +function getName() { + console.log(name); + let name = 'Sarah'; +} + +getName(); +``` + +- A: Lydia +- B: Sarah +- C: `undefined` +- D: `ReferenceError` + +
Risposta +

+ +#### Risposta: D + +Ogni funzione ha il proprio _contesto di esecuzione_ (o _ambito_). La funzione `getName` cerca prima all'interno del proprio contesto (scope) per vedere se contiene la variabile `name` a cui stiamo cercando di accedere. In questo caso, la funzione `getName` contiene la propria variabile `name` perchè dichiariamo la variabile `name` con la chiave `let`, e con il valore di `'Sarah'`. + +Le variabili con la chiave `let` (e `const`) vengono sollevate, ma a differenza di `var`, non vengono inizializzate. Non sono quindi accessibili prima della riga in cui le dichiariamo (inizializziamo). Questa è chiamata "temporal dead zone". Quando proviamo ad accedere alle variabili prima che vengano dichiarate, JavaScript genera un `ReferenceError`. + +Se non avessimo dichiarato la variabile `name` all'interno della funzione `getName`, javascript avrebbe esaminato la _scope chain_. Lo scope esterno ha una variabile chiamata `name` con il valore di `Lydia`. In tal caso, avrebbe loggato "Lydia". + +```javascript +let name = 'Lydia'; + +function getName() { + console.log(name); +} + +getName(); // Lydia +``` + +

+
+ +--- + +###### 112. Qual è l'output? + +```javascript +function* generatorOne() { + yield ['a', 'b', 'c']; +} + +function* generatorTwo() { + yield* ['a', 'b', 'c']; +} + +const one = generatorOne(); +const two = generatorTwo(); + +console.log(one.next().value); +console.log(two.next().value); +``` + +- A: `a` e `a` +- B: `a` e `undefined` +- C: `['a', 'b', 'c']` e `a` +- D: `a` e `['a', 'b', 'c']` + +
Risposta +

+ +#### Risposta: C + +Con la parola chiave `yield`, otteniamo valori in una funzione generatore. Con la chiave `yield*`, possiamo produrre valori da un'altra funzione del generatore, o da un oggetto iterabile (per esempio un array). + +In `generatorOne`, produciamo l'intero array `['a', 'b', 'c']` usando la parola chiave `yield`. Il valore della proprietà `value` sull'oggetto restituito dal metodo `next` su `one` (`one.next().value`) è uguale all'intero array `['a', 'b', 'c']`. + +```javascript +console.log(one.next().value); // ['a', 'b', 'c'] +console.log(one.next().value); // undefined +``` + +In `generatorTwo`, utilizziamo la parola chiave `yield*`. Ciò significa che il primo valore ottenuto è `two`, ed è uguale al primo valore ottenuto nell'iteratore. L'iteratore è l'array `['a', 'b', 'c']`. Il primo valore ottenuto è `a`, quindi la prima volta che chiamiamo `two.next().value`, viene restituito `a`. + +```javascript +console.log(two.next().value); // 'a' +console.log(two.next().value); // 'b' +console.log(two.next().value); // 'c' +console.log(two.next().value); // undefined +``` + +

+
+ +--- + +###### 113. Qual è l'output? + +```javascript +console.log(`${(x => x)('I love')} to program`); +``` + +- A: `I love to program` +- B: `undefined to program` +- C: `${(x => x)('I love') to program` +- D: `TypeError` + +
Risposta +

+ +#### Risposta: A + +Le espressioni all'interno dei template literals vengono valutate per prime. Ciò significa che la stringa conterrà il valore restituito dell'espressione, in questo caso la funzione immediatamente invocata `(x => x)('I love')`. Passiamo il valore `'I love'` come argomento alla funzione freccia `x => x`. `x` è uguale a `'I love'`, che viene restituito. Ciò si traduce in `I love to program`. + +

+
+ +--- + +###### 114. Cosa accadrà? + +```javascript +let config = { + alert: setInterval(() => { + console.log('Alert!'); + }, 1000), +}; + +config = null; +``` + +- A: La callback `setInterval` non verrà invocata +- B: La callback `setInterval` viene invocata una volta +- C: La callback `setInterval` verrà comunque chiamata ogni secondo +- D: Non abbiamo mai invocato `config.alert()`, config è `null` + +
Risposta +

+ +#### Risposta: C + +Normalmente quando impostiamo oggetti uguali a `null`, quegli oggetti ottengono _garbage collected_ poiché non c'è più alcun riferimento a quell'oggetto. Tuttavia, poiché la funzione di callback all'interno di `setInterval` è una funzione freccia (quindi legata all'oggetto `config`), la funzione di callback mantiene ancora un riferimento all'oggetto `config`. +Finché c'è un riferimento, l'oggetto non verrà raccolto. +Poiché si tratta di un intervallo, impostare `config` su `null` o `delete`-ing `config.alert` non raccoglierà l'intervallo, quindi l'intervallo verrà comunque chiamato. +Dovrebbe essere cancellato con `clearInterval(config.alert)` per rimuoverlo dalla memoria. +Dal momento che non è stato cancellato, la funzione di callback `setInterval` verrà comunque invocata ogni 1000 ms (1 s). + +

+
+ +--- + +###### 115. Quali metodi restituiranno il valore `'Hello world!'`? + +```javascript +const myMap = new Map(); +const myFunc = () => 'greeting'; + +myMap.set(myFunc, 'Hello world!'); + +//1 +myMap.get('greeting'); +//2 +myMap.get(myFunc); +//3 +myMap.get(() => 'greeting'); +``` + +- A: 1 +- B: 2 +- C: 2 e 3 +- D: Tutti + +
Risposta +

+ +#### Risposta: B + +Quando si aggiunge una coppia chiave/valore usando il metodo `set`, la chiave sarà il valore del primo argomento passato alla funzione `set`, e il valore sarà il secondo argomento. La chiave è _function_ `() => 'greeting'` in questo caso, e il valore `'Hello world'`. `myMap` ora è `{ () => 'greeting' => 'Hello world!' }`. + +1 è sbagliato, poiché la chiave non è `'greeting'` ma `() => 'greeting'`. +3 è sbagliato, poiché stiamo creando una nuova funzione passandola come parametro al metodo `get`. L'oggetto interagisce per _reference_. Le funzioni sono oggetti, che è il motivo per cui due funzioni non sono mai rigorosamente uguali, anche se identiche: hanno un riferimento a un punto diverso della memoria. + +

+
+ +--- + +###### 116. Qual è l'output? + +```javascript +const person = { + name: 'Lydia', + age: 21, +}; + +const changeAge = (x = { ...person }) => (x.age += 1); +const changeAgeAndName = (x = { ...person }) => { + x.age += 1; + x.name = 'Sarah'; +}; + +changeAge(person); +changeAgeAndName(); + +console.log(person); +``` + +- A: `{name: "Sarah", age: 22}` +- B: `{name: "Sarah", age: 23}` +- C: `{name: "Lydia", age: 22}` +- D: `{name: "Lydia", age: 23}` + +
Risposta +

+ +#### Risposta: C + +Entrambe le funzioni `changeAge` e `changeAgeAndName` hanno un parametro predefinito, ovvero un oggetto _appena_ creato `{ ...person }`. Questo oggetto ha copie di tutte le chiavi/valori nell'oggetto `person`. + +Per prima cosa, invochiamo la funzione `changeAge` e passiamo l'oggetto `person` come argomento. Questa funzione aumenta il valore della proprietà `age` di 1. `person` ora è `{ name: "Lydia", age: 22 }`. + +Quindi, invochiamo la funzione `changeAgeAndName`, tuttavia non passiamo un parametro. Invece, il valore di `x` è uguale a un _nuovo_ oggetto: `{ ...person }`. Poiché si tratta di un nuovo oggetto, non influisce sui valori delle proprietà sull'oggetto `person`. `person` è ancora uguale a `{ name: "Lydia", age: 22 }`. +

+
+ +--- + +###### 117. Quale delle seguenti opzioni restituirà `6`? + +```javascript +function sumValues(x, y, z) { + return x + y + z; +} +``` + +- A: `sumValues([...1, 2, 3])` +- B: `sumValues([...[1, 2, 3]])` +- C: `sumValues(...[1, 2, 3])` +- D: `sumValues([1, 2, 3])` + +
Risposta +

+ +#### Risposta: C + +Con l'operatore spread `...`, possiamo _distribuire_ gli iterabili come singoli elementi. La funzione `sumValues` riceve tre argomenti: `x`, `y` e `z`. `...[1, 2, 3]` risulterà in `1, 2, 3`, che passiamo alla funzione `sumValues`. + +

+
+ +--- + +###### 118. Qual è l'output? + +```javascript +let num = 1; +const list = ['🥳', '🤠', '🥰', '🤪']; + +console.log(list[(num += 1)]); +``` + +- A: `🤠` +- B: `🥰` +- C: `SyntaxError` +- D: `ReferenceError` + +
Risposta +

+ +#### Risposta: B + +Con l'operando `+=`, stiamo incrementando il valore di `num` di `1`. `num` aveva il valore iniziale `1`, quindi `1 + 1` è `2`. L'elemento sul secondo indice nell'array `list` è 🥰, `console.log(list[2])` stampa 🥰. + +

+
+ +--- + +###### 119. Qual è l'output? + +```javascript +const person = { + firstName: 'Lydia', + lastName: 'Hallie', + pet: { + name: 'Mara', + breed: 'Dutch Tulip Hound', + }, + getFullName() { + return `${this.firstName} ${this.lastName}`; + }, +}; + +console.log(person.pet?.name); +console.log(person.pet?.family?.name); +console.log(person.getFullName?.()); +console.log(member.getLastName?.()); +``` + +- A: `undefined` `undefined` `undefined` `undefined` +- B: `Mara` `undefined` `Lydia Hallie` `ReferenceError` +- C: `Mara` `null` `Lydia Hallie` `null` +- D: `null` `ReferenceError` `null` `ReferenceError` + +
Risposta +

+ +#### Risposta: B + +Con l'operatore di concatenamento opzionale `?.`, non è più necessario verificare esplicitamente se i valori annidati più profondi sono validi o meno. Se stiamo cercando di accedere a una proprietà su un valore `undefined` o `null` (_nullish_), l'espressione va in cortocircuito e restituisce `undefined`. + +`person.pet?.name`: `person` ha una proprietà denominata `pet`: `person.pet` non è nullo. Ha una proprietà chiamata `name` e restituisce `Mara`. +`person.pet?.family?.name`: `person` ha una proprietà denominata `pet`: `person.pet` non è nullo. `pet` _non_ ha una proprietà chiamata `family`, `person.pet.family` è nullo. L'espressione restituisce `undefined`. +`person.getFullName?.()`: `person` ha una proprietà denominata `getFullName`: `person.getFullName()` non è nullo e può essere invocato, il che restituisce `Lydia Hallie`. +`member.getLastName?.()`: la variabile `member` non esiste quindi viene generato un `ReferenceError`! + +

+
+ +--- + +###### 120. Qual è l'output? + +```javascript +const groceries = ['banana', 'apple', 'peanuts']; + +if (groceries.indexOf('banana')) { + console.log('We have to buy bananas!'); +} else { + console.log(`We don't have to buy bananas!`); +} +``` + +- A: We have to buy bananas! +- B: We don't have to buy bananas +- C: `undefined` +- D: `1` + +
Risposta +

+ +#### Risposta: B + +Abbiamo passato la condizione `groceries.indexOf("banana")` all'istruzione if. `groceries.indexOf("banana")` restituisce `0`, che è un valore falso. Poiché la condizione nell'istruzione if è falsa, il codice nel blocco `else` viene eseguito e `We don't have to buy bananas!` viene registrato. + +

+
+ +--- + +###### 121. Qual è l'output? + +```javascript +const config = { + languages: [], + set language(lang) { + return this.languages.push(lang); + }, +}; + +console.log(config.language); +``` + +- A: `function language(lang) { this.languages.push(lang }` +- B: `0` +- C: `[]` +- D: `undefined` + +
Risposta +

+ +#### Risposta: D + +Il metodo `language` è un `setter`. I setter non detengono un valore effettivo, il loro scopo è _modificare_ le proprietà. Quando si chiama un metodo `setter`, viene restituito `undefined`. + +

+
+ +--- + +###### 122. Qual è l'output? + +```javascript +const name = 'Lydia Hallie'; + +console.log(!typeof name === 'object'); +console.log(!typeof name === 'string'); +``` + +- A: `false` `true` +- B: `true` `false` +- C: `false` `false` +- D: `true` `true` + +
Risposta +

+ +#### Risposta: C + +`typeof name` restituisce `"string"`. La stringa `"string"` è un valore veritiero, quindi `!typeof name` restituisce il valore booleano `false`. `false === "object"` e `false === "string"` restituiscono entrambi `false`. + +(Se volessimo verificare se il tipo era (non)uguale a un certo tipo, avremmo dovuto scrivere `!==` invece di `!typeof`) +

+
+ +--- + +###### 123. Qual è l'output? + +```javascript +const add = x => y => z => { + console.log(x, y, z); + return x + y + z; +}; + +add(4)(5)(6); +``` + +- A: `4` `5` `6` +- B: `6` `5` `4` +- C: `4` `function` `function` +- D: `undefined` `undefined` `6` + +
Risposta +

+ +#### Risposta: A + +La funzione `add` restituisce una arrow function, che restituisce una arrow function, che restituisce arrow function (mi segui ancora?). +La prima funzione riceve un argomento `x` con il valore di `4`. Invochiamo la seconda funzione, che riceve un argomento `y` con il valore `5`. Quindi invochiamo la terza funzione, che riceve un argomento `z` con il valore `6`. Quando si tenta di accedere ai valori `x`, `y` e `z` all'interno dell'ultima arrow function, il motore JS risale la catena dell'ambito per trovare i valori per `x` e `y`. Questo restituisce `4` `5` `6`. + +

+
+ +--- + +###### 124. Qual è l'output? + +```javascript +async function* range(start, end) { + for (let i = start; i <= end; i++) { + yield Promise.resolve(i); + } +} + +(async () => { + const gen = range(1, 3); + for await (const item of gen) { + console.log(item); + } +})(); +``` + +- A: `Promise {1}` `Promise {2}` `Promise {3}` +- B: `Promise {}` `Promise {}` `Promise {}` +- C: `1` `2` `3` +- D: `undefined` `undefined` `undefined` + +
Risposta +

+ +#### Risposta: C + +La funzione `range` restituisce un oggetto asincrono con promises per ogni elemento nell'intervallo che passiamo: `Promise{1}`, `Promise{2}`, `Promise{3}`. Impostiamo la variabile `gen` uguale all'oggetto asincrono, dopodiché lo eseguiamo in loop usando un ciclo `for await ... of`. Impostiamo la variabile `item` uguale ai valori Promise restituiti: prima `Promise{1}`, poi `Promise{2}`, quindi `Promise{3}`. Poiché stiamo _attendendo_ il valore di `item`, la promise risolta, vengono restituiti i _valori_ risolti delle promises: `1`, `2` e quindi `3`. + +

+
+ +--- + +###### 125. Qual è l'output? + +```javascript +const myFunc = ({ x, y, z }) => { + console.log(x, y, z); +}; + +myFunc(1, 2, 3); +``` + +- A: `1` `2` `3` +- B: `{1: 1}` `{2: 2}` `{3: 3}` +- C: `{ 1: undefined }` `undefined` `undefined` +- D: `undefined` `undefined` `undefined` + +
Risposta +

+ +#### Risposta: D + +`myFunc` si aspetta un oggetto con le proprietà `x`, `y` e `z` come argomento. Poiché stiamo passando solo tre valori numerici separati (1, 2, 3) invece di un oggetto con le proprietà `x`, `y` e `z` ({x: 1, y: 2, z: 3}), `x`, `y` e `z` hanno il loro valore predefinito di `undefined`. + +

+
+ +--- + +###### 126. Qual è l'output? + +```javascript +function getFine(speed, amount) { + const formattedSpeed = new Intl.NumberFormat('en-US', { + style: 'unit', + unit: 'mile-per-hour' + }).format(speed); + + const formattedAmount = new Intl.NumberFormat('en-US', { + style: 'currency', + currency: 'USD' + }).format(amount); + + return `The driver drove ${formattedSpeed} and has to pay ${formattedAmount}`; +} + +console.log(getFine(130, 300)) +``` + +- A: The driver drove 130 and has to pay 300 +- B: The driver drove 130 mph and has to pay \$300.00 +- C: The driver drove undefined and has to pay undefined +- D: The driver drove 130.00 and has to pay 300.00 + +
Risposta +

+ +#### Risposta: B + +Con il metodo `Intl.NumberFormat`, possiamo formattare i valori numerici in qualsiasi locale. Formattiamo il valore numerico `130` nella locale `en-US` come `unit` in `mile-per-hour`, che risulta in `130 mph`. Il valore numerico `300` nella locale `en-US` come `currency` in `USD` risulta in `$300.00`. + +

+
+ +--- + +###### 127. Qual è l'output? + +```javascript +const spookyItems = ['👻', '🎃', '🕸']; +({ item: spookyItems[3] } = { item: '💀' }); + +console.log(spookyItems); +``` + +- A: `["👻", "🎃", "🕸"]` +- B: `["👻", "🎃", "🕸", "💀"]` +- C: `["👻", "🎃", "🕸", { item: "💀" }]` +- D: `["👻", "🎃", "🕸", "[object Object]"]` + +
Risposta +

+ +#### Risposta: B + +By destructuring objects, we can unpack values from the right-hand object, and assign the unpacked value to the value of the same property name on the left-hand object. In this case, we're assigning the value "💀" to `spookyItems[3]`. This means that we're modifying the `spookyItems` array, we're adding the "💀" to it. When logging `spookyItems`, `["👻", "🎃", "🕸", "💀"]` gets logged. + +Destrutturando gli oggetti, possiamo decomprimere i valori dall'oggetto di destra e assegnare il valore decompresso al valore dello stesso nome di proprietà sull'oggetto di sinistra. In questo caso, stiamo assegnando il valore "💀" a `spookyItems[3]`. Ciò significa che stiamo modificando l'array `spookyItems`, stiamo aggiungendo il "💀" ad esso. Quando facciamo console.log di `spookyItems`, `["👻", "🎃", "🕸", "💀"]` viene loggato. + +

+
+ +--- + +###### 128. Qual è l'output? + +```javascript +const name = 'Lydia Hallie'; +const age = 21; + +console.log(Number.isNaN(name)); +console.log(Number.isNaN(age)); + +console.log(isNaN(name)); +console.log(isNaN(age)); +``` + +- A: `true` `false` `true` `false` +- B: `true` `false` `false` `false` +- C: `false` `false` `true` `false` +- D: `false` `true` `false` `true` + +
Risposta +

+ +#### Risposta: C + +Con il metodo `Number.isNaN`, puoi controllare se il valore passato è un _valore numerico_ e uguale a `NaN`. `name` non è un valore numerico, quindi `Number.isNaN(name)` restituisce `false`. `age` è un valore numerico, ma non è uguale a `NaN`, quindi `Numero.isNaN(age)` restituisce `false`. + +Con il metodo `isNaN`, puoi verificare se il valore che passi non è un numero. `name` non è un numero, quindi `isNaN(name)` restituisce true. `age` è un numero, quindi `isNaN(age)` restituisce `false`. +

+
+ +--- + +###### 129. Qual è l'output? + +```javascript +const randomValue = 21; + +function getInfo() { + console.log(typeof randomValue); + const randomValue = 'Lydia Hallie'; +} + +getInfo(); +``` + +- A: `"number"` +- B: `"string"` +- C: `undefined` +- D: `ReferenceError` + +
Risposta +

+ +#### Risposta: D + +Le variabili dichiarate con la chiave `const` non sono referenziabili prima della loro inizializzazione: questa viene chiamata _temporal dead zone_. Nella funzione `getInfo`, la variabile `randomValue` ha lo scopo nell'ambito funzionale di `getInfo`. Nella riga in cui vogliamo registrare il valore di `typeof randomValue`, la variabile `randomValue` non è ancora inizializzata: viene lanciato un `ReferenceError`! Il motore non è andato giù per la catena dell'ambito poiché abbiamo dichiarato la variabile `randomValue` nella funzione `getInfo`. +

+
+ +--- + +###### 130. Qual è l'output? + +```javascript +const myPromise = Promise.resolve('Woah some cool data'); + +(async () => { + try { + console.log(await myPromise); + } catch { + throw new Error(`Oops didn't work`); + } finally { + console.log('Oh finally!'); + } +})(); +``` + +- A: `Woah some cool data` +- B: `Oh finally!` +- C: `Woah some cool data` `Oh finally!` +- D: `Oops didn't work` `Oh finally!` + +
Risposta +

+ +#### Risposta: C + +Nel blocco `try`, stiamo loggando il valore atteso della variabile `myPromise`: `"Woah some cool data"`. Poiché non sono stati generati errori nel blocco `try`, il codice nel blocco `catch` non viene eseguito. Il codice nel blocco `finally` viene eseguito _sempre_, `"Oh finally!"` viene loggato. + +

+
+ +--- + +###### 131. Qual è l'output? + +```javascript +const emojis = ['🥑', ['✨', '✨', ['🍕', '🍕']]]; + +console.log(emojis.flat(1)); +``` + +- A: `['🥑', ['✨', '✨', ['🍕', '🍕']]]` +- B: `['🥑', '✨', '✨', ['🍕', '🍕']]` +- C: `['🥑', ['✨', '✨', '🍕', '🍕']]` +- D: `['🥑', '✨', '✨', '🍕', '🍕']` + +
Risposta +

+ +#### Risposta: B + +Con il metodo `flat`, possiamo creare un nuovo array appiattito. La profondità dell'array appiattito dipende dal valore che passiamo. In questo caso, abbiamo passato il valore `1` (cosa che non dovevamo fare, questo è il valore predefinito), il che significa che solo gli array sulla prima profondità verranno concatenati. `['🥑']` e `['✨', '✨', ['🍕', '🍕']]` in questo caso. Concatenando questi due array si ottengono `['🥑', '✨', '✨', ['🍕', '🍕']]`. +

+
+ +--- + +###### 132. Qual è l'output? + +```javascript +class Counter { + constructor() { + this.count = 0; + } + + increment() { + this.count++; + } +} + +const counterOne = new Counter(); +counterOne.increment(); +counterOne.increment(); + +const counterTwo = counterOne; +counterTwo.increment(); + +console.log(counterOne.count); +``` + +- A: `0` +- B: `1` +- C: `2` +- D: `3` + +
Risposta +

+ +#### Risposta: D + +`counterOne` è un'istanza della classe `Counter`. La classe counter contiene una proprietà `count` sul suo costruttore e un metodo `increment`. Per prima cosa, abbiamo invocato il metodo `increment` due volte chiamando `counterOne.increment()`. Attualmente, `counterOne.count` è `2`. + + + +Quindi, creiamo una nuova variabile `counterTwo` e la impostiamo uguale a `counterOne`. Poiché gli oggetti interagiscono per riferimento, stiamo semplicemente creando un nuovo riferimento allo stesso punto della memoria a cui punta `counterOne`. Poiché ha lo stesso punto in memoria, qualsiasi modifica apportata all'oggetto a cui fa riferimento `counterTwo`, si applica anche a `counterOne`. Attualmente, `counterTwo.count` è `2`. + +Invochiamo `counterTwo.increment()`, che imposta `count` su `3`. Quindi, logghiamo il conteggio su `counterOne`, che stampa `3`. + + + +

+
+ +--- + +###### 133. Qual è l'output? + +```javascript +const myPromise = Promise.resolve(Promise.resolve('Promise')); + +function funcOne() { + setTimeout(() => console.log('Timeout 1!'), 0); + myPromise.then(res => res).then(res => console.log(`${res} 1!`)); + console.log('Last line 1!'); +} + +async function funcTwo() { + const res = await myPromise; + console.log(`${res} 2!`) + setTimeout(() => console.log('Timeout 2!'), 0); + console.log('Last line 2!'); +} + +funcOne(); +funcTwo(); +``` + +- A: `Promise 1! Last line 1! Promise 2! Last line 2! Timeout 1! Timeout 2!` +- B: `Last line 1! Timeout 1! Promise 1! Last line 2! Promise2! Timeout 2! ` +- C: `Last line 1! Promise 2! Last line 2! Promise 1! Timeout 1! Timeout 2!` +- D: `Timeout 1! Promise 1! Last line 1! Promise 2! Timeout 2! Last line 2!` + +
Risposta +

+ +#### Risposta: C + +Innanzitutto, invochiamo `funcOne`. Sulla prima riga di `funcOne`, chiamiamo la funzione _asincrona_ `setTimeout`, da cui la callback viene inviato all'API Web. (vedi l'articolo sul ciclo degli eventi qui.) + +Quindi chiamiamo la promise `myPromise`, che è un'operazione _asincrona_. + +Sia la promise che il timeout sono operazioni asincrone, la funzione continua a funzionare mentre è impegnata a completare la promise e a gestire la callback `setTimeout`. Ciò significa che `Last line 1!` viene registrato per primo, poiché questa non è un'operazione asincrona. + +Poiché la callstack non è ancora vuota, la funzione `setTimeout` e la promise in `funcOne` non possono ancora essere aggiunte al callstack. + +In `funcTwo`, la variabile `res` ottiene `Promise` perché `Promise.resolve(Promise.resolve('Promise'))` è equivalente a `Promise.resolve('Promise')` poiché risolvere una promise risolve semplicemente che è valore. L'"attesa" in questa riga interrompe l'esecuzione della funzione fino a quando non riceve la risoluzione della promise e quindi continua a funzionare in modo sincrono fino al completamento, quindi `Promise 2!` e poi `Last line 2!` vengono registrati e "setTimeout ` viene inviato all'API Web. + +Quindi lo stack di chiamate è vuoto. Le promise sono _microattività_ quindi vengono risolte per prime quando lo stack di chiamate è vuoto, quindi `Promise 1!` viene registrato. + +Ora, da quando `funcTwo` è uscito dallo stack delle chiamate, lo stack delle chiamate è vuoto. Le callback in attesa nella coda (`() => console.log("Timeout 1!")` da `funcOne`, e `() => console.log("Timeout 2!")` da `funcTwo`) vengono aggiunti allo stack di chiamate uno per uno. Il primo callback registra `Timeout 1!` e viene eliminato dallo stack. Quindi, il secondo callback registra `Timeout 2!` e viene eliminato dallo stack. +

+
+ +--- + +###### 134. Come possiamo invocare `sum` in `sum.js` da `index.js?` + +```javascript +// sum.js +export default function sum(x) { + return x + x; +} + +// index.js +import * as sum from './sum'; +``` + +- A: `sum(4)` +- B: `sum.sum(4)` +- C: `sum.default(4)` +- D: I valori predefiniti non vengono importati con `*`, solo esportazioni nominali + +
Risposta +

+ +#### Risposta: C + +Con l'asterisco `*`, importiamo tutti i valori esportati da quel file, sia predefinito che nominale. Se avessimo il seguente file: + +```javascript +// info.js +export const name = 'Lydia'; +export const age = 21; +export default 'I love JavaScript'; + +// index.js +import * as info from './info'; +console.log(info); +``` + +Verrebbe loggato quanto segue: + +```javascript +{ + default: "I love JavaScript", + name: "Lydia", + age: 21 +} +``` + +Per l'esempio `sum`, significa che il valore importato `sum` è simile a quanto segue: + +```javascript +{ default: function sum(x) { return x + x } } +``` + +Possiamo invocare questa funzione, chiamando `sum.default` + +

+
+ +--- + +###### 135. Qual è l'output? + +```javascript +const handler = { + set: () => console.log('Added a new property!'), + get: () => console.log('Accessed a property!'), +}; + +const person = new Proxy({}, handler); + +person.name = 'Lydia'; +person.name; +``` + +- A: `Added a new property!` +- B: `Accessed a property!` +- C: `Added a new property!` `Accessed a property!` +- D: Nulla viene loggato + +
Risposta +

+ +#### Risposta: C + +Con un oggetto Proxy, possiamo aggiungere un comportamento personalizzato a un oggetto che gli passiamo come secondo argomento. In questo caso, passiamo all'oggetto `handler` che conteneva due proprietà: `set` e `get`. `set` viene invocato ogni volta che _settiamo_ valori di proprietà, `get` viene invocato ogni volta che _otteniamo_ (accediamo) valori di proprietà. + +Il primo argomento è un oggetto vuoto `{}`, che è il valore di `person`. A questo oggetto viene aggiunto il comportamento personalizzato specificato nell'oggetto `handler`. Se aggiungiamo una proprietà all'oggetto `person`, `set` verrà invocato. Se accediamo a una proprietà sull'oggetto `person`, `get` viene invocato. + +Innanzitutto, abbiamo aggiunto una nuova proprietà `name` all'oggetto proxy (`person.name = "Lydia"`). `set` viene invocato e registra `"Added a new property!"`. + +Quindi, accediamo a un valore di proprietà sull'oggetto proxy, la proprietà `get` sull'oggetto handler è stata invocata. `"Accessed a property!"` viene registrato. + +

+
+ +--- + +###### 136. Quale delle seguenti opzioni modificherà l'oggetto `persona`? + +```javascript +const person = { name: 'Lydia Hallie' }; + +Object.seal(person); +``` + +- A: `person.name = "Evan Bacon"` +- B: `person.age = 21` +- C: `delete person.name` +- D: `Object.assign(person, { age: 21 })` + +
Risposta +

+ +#### Risposta: A + +Con `Object.seal` possiamo impedire che nuove proprietà vengano _aggiunte_ o che proprietà esistenti vengano _rimosse_. + +Tuttavia, puoi comunque modificare il valore delle proprietà esistenti. + +

+
+ +--- + +###### 137. Quale delle seguenti opzioni modificherà l'oggetto `person`? + +```javascript +const person = { + name: 'Lydia Hallie', + address: { + street: '100 Main St', + }, +}; + +Object.freeze(person); +``` + +- A: `person.name = "Evan Bacon"` +- B: `delete person.address` +- C: `person.address.street = "101 Main St"` +- D: `person.pet = { name: "Mara" }` + +
Risposta +

+ +#### Risposta: C + +Il metodo `Object.freeze` _congela_ un oggetto. Nessuna proprietà può essere aggiunta, modificata o rimossa. + +Tuttavia, blocca solo _poco profondamente_ l'oggetto, il che significa che solo le proprietà _direct_ sull'oggetto sono bloccate. Se la proprietà è un altro oggetto, come `address` in questo caso, le proprietà su quell'oggetto non vengono bloccate e possono essere modificate. + +

+
+ +--- + +###### 138. Qual è l'output? + +```javascript +const add = x => x + x; + +function myFunc(num = 2, value = add(num)) { + console.log(num, value); +} + +myFunc(); +myFunc(3); +``` + +- A: `2` `4` and `3` `6` +- B: `2` `NaN` and `3` `NaN` +- C: `2` `Error` and `3` `6` +- D: `2` `4` and `3` `Error` + +
Risposta +

+ +#### Risposta: A + +Per prima cosa, abbiamo invocato `myFunc()` senza passare alcun argomento. Dal momento che non abbiamo passato argomenti, `num` e `value` hanno i loro valori predefiniti: num è `2` e `value` il valore restituito dalla funzione `add`. Alla funzione `add`, passiamo `num` come argomento, che aveva il valore di `2`. `add` restituisce `4`, che è il valore di `value`. + +Quindi, abbiamo invocato `myFunc(3)` e passato il valore `3` come valore per l'argomento `num`. Non abbiamo passato un argomento per `value`. +Poiché non abbiamo passato un valore per l'argomento `value`, ha ottenuto il valore predefinito: il valore restituito dalla funzione `add`. Ad `add` passiamo `num`, che ha il valore di `3`. `add` restituisce `6`, che è il valore di `value`. + +

+
+ +--- + +###### 139. Qual è l'output? + +```javascript +class Counter { + #number = 10 + + increment() { + this.#number++ + } + + getNum() { + return this.#number + } +} + +const counter = new Counter() +counter.increment() + +console.log(counter.#number) +``` + +- A: `10` +- B: `11` +- C: `undefined` +- D: `SyntaxError` + +
Risposta +

+ +#### Risposta: D + +In ES2020, possiamo aggiungere variabili private nelle classi usando `#`. Non possiamo accedere a queste variabili al di fuori della classe. Quando proviamo a registrare `counter.#number`, viene generato un SyntaxError: non possiamo accedervi al di fuori della classe `Counter`! + +

+
+ +--- + +###### 140. Cosa manca? + +```javascript +const teams = [ + { name: 'Team 1', members: ['Paul', 'Lisa'] }, + { name: 'Team 2', members: ['Laura', 'Tim'] }, +]; + +function* getMembers(members) { + for (let i = 0; i < members.length; i++) { + yield members[i]; + } +} + +function* getTeams(teams) { + for (let i = 0; i < teams.length; i++) { + // ✨ SOMETHING IS MISSING HERE ✨ + } +} + +const obj = getTeams(teams); +obj.next(); // { value: "Paul", done: false } +obj.next(); // { value: "Lisa", done: false } +``` + +- A: `yield getMembers(teams[i].members)` +- B: `yield* getMembers(teams[i].members)` +- C: `return getMembers(teams[i].members)` +- D: `return yield getMembers(teams[i].members)` + +
Risposta +

+ +#### Risposta: B + +Per scorrere i `members` in ogni elemento dell'array `teams`, dobbiamo passare `teams[i].members` alla funzione `getMembers`. La funzione restituisce un oggetto. Per scorrere ogni elemento in questo oggetto generatore, dobbiamo usare `yield*`. + +Se avessimo scritto `yield`, `return yield` o `return`, l'intera funzione del generatore sarebbe stata restituita la prima volta che abbiamo chiamato il metodo `next`. + +

+
+ +--- + +###### 141. Qual è l'output? + +```javascript +const person = { + name: 'Lydia Hallie', + hobbies: ['coding'], +}; + +function addHobby(hobby, hobbies = person.hobbies) { + hobbies.push(hobby); + return hobbies; +} + +addHobby('running', []); +addHobby('dancing'); +addHobby('baking', person.hobbies); + +console.log(person.hobbies); +``` + +- A: `["coding"]` +- B: `["coding", "dancing"]` +- C: `["coding", "dancing", "baking"]` +- D: `["coding", "running", "dancing", "baking"]` + +
Risposta +

+ +#### Risposta: C + +La funzione `addHobby` riceve due argomenti, `hobby` e `hobby` con il valore predefinito dell'array `hobbies` sull'oggetto `person`. + +Per prima cosa, invochiamo la funzione `addHobby` e passiamo `"running"` come valore per `hobby` e un array vuoto come valore per `hobby`. Poiché passiamo un array vuoto come valore per `hobby`, `"running"` viene aggiunto a questo array vuoto. + +Quindi, invochiamo la funzione `addHobby` e passiamo a `"dancing"` come valore per `hobby`. Non abbiamo passato un valore per `hobbies`, quindi ottiene il valore predefinito, la proprietà `hobbies` sull'oggetto `person`. Spostiamo l'hobby `dancing` nell'array `person.hobbies`. + +Infine, invochiamo la funzione `addHobby` e passiamo `"baking"` come valore per `hobby`, e l'array `person.hobbies` come valore per `hobby`. Spostiamo l'hobby `baking` nell'array `person.hobbies`. + +Dopo aver fatto un push di `dancing` e `baking`, il valore di `person.hobbies` è `["coding", "dancing", "baking"]` + +

+
+ +--- + +###### 142. Qual è l'output? + +```javascript +class Bird { + constructor() { + console.log("I'm a bird. 🦢"); + } +} + +class Flamingo extends Bird { + constructor() { + console.log("I'm pink. 🌸"); + super(); + } +} + +const pet = new Flamingo(); +``` + +- A: `I'm pink. 🌸` +- B: `I'm pink. 🌸` `I'm a bird. 🦢` +- C: `I'm a bird. 🦢` `I'm pink. 🌸` +- D: Niente, non abbiamo chiamato alcun metodo + +
Risposta +

+ +#### Risposta: B + +Creiamo la variabile `pet` che è un'istanza della classe `Flamingo`. Quando istanziamo questa istanza, il `constructor` su `Flamingo` viene chiamato. Per prima cosa, `"I'm pink. 🌸"` viene loggato, dopodiché chiamiamo `super()`. + +`super()` chiama il costruttore della classe genitore, `Bird`. Il costruttore in `Bird` viene chiamato e registra `"I'm a bird. 🦢"`. + +

+
+ +--- + +###### 143. Quale delle opzioni genera un errore? + +```javascript +const emojis = ['🎄', '🎅🏼', '🎁', '⭐']; + +/* 1 */ emojis.push('🦌'); +/* 2 */ emojis.splice(0, 2); +/* 3 */ emojis = [...emojis, '🥂']; +/* 4 */ emojis.length = 0; +``` + +- A: 1 +- B: 1 and 2 +- C: 3 and 4 +- D: 3 + +
Risposta +

+ +#### Risposta: D + +La chiave `const` significa che non possiamo _ridichiarare_ il valore di quella variabile, è di _sola lettura_. Tuttavia, il valore stesso non è immutabile. Le proprietà dell'array `emojis` possono essere modificate, ad esempio facendo un push di nuovi valori, collegandoli o impostando la lunghezza dell'array su 0. + +

+
+ +--- + +###### 144. Cosa dobbiamo aggiungere all'oggetto `person` per ottenere `["Lydia Hallie", 21]` come output di `[...person]`? + +```javascript +const person = { + name: "Lydia Hallie", + age: 21 +} + +[...person] // ["Lydia Hallie", 21] +``` + +- A: Nulla, gli oggetti sono iterabili di default +- B: `*[Symbol.iterator]() { for (let x in this) yield* this[x] }` +- C: `*[Symbol.iterator]() { yield* Object.values(this) }` +- D: `*[Symbol.iterator]() { for (let x in this) yield this }` + +
Risposta +

+ +#### Risposta: C + +Gli oggetti non sono iterabili per impostazione predefinita. Un iterabile è un iterabile se è presente il protocollo iteratore. +Possiamo aggiungerlo manualmente aggiungendo il simbolo dell'iteratore `[Symbol.iterator]`, che deve restituire un oggetto generatore, ad esempio trasformandolo in una funzione del generatore `*[Symbol.iterator]() {}`. Questa funzione di generazione deve fornire gli `Object.values` dell'oggetto `person` se vogliamo che restituisca l'array `["Lydia Hallie", 21]`: `yield* Object.values(this)`. + +

+
+ +--- + +###### 145. Qual è l'output? + +```javascript +let count = 0; +const nums = [0, 1, 2, 3]; + +nums.forEach(num => { + if (num) count += 1 +}) + +console.log(count) +``` + +- A: 1 +- B: 2 +- C: 3 +- D: 4 + +
Risposta +

+ +#### Risposta: C + +La condizione `if` all'interno del ciclo `forEach` controlla se il valore di `num` è veritiero o falso. Poiché il primo numero nell'array `nums` è `0`, ovvero un valore falso, il blocco di codice dell'istruzione `if` non verrà eseguito. `count` viene incrementato solo per gli altri 3 numeri nell'array `nums`, `1`, `2` e `3`. Poiché `count` viene incrementato di `1` 3 volte, il valore di `count` è `3`. + +

+
+ +--- + +###### 146. Qual è l'output? + +```javascript +function getFruit(fruits) { + console.log(fruits?.[1]?.[1]) +} + +getFruit([['🍊', '🍌'], ['🍍']]) +getFruit() +getFruit([['🍍'], ['🍊', '🍌']]) +``` + +- A: `null`, `undefined`, 🍌 +- B: `[]`, `null`, 🍌 +- C: `[]`, `[]`, 🍌 +- D: `undefined`, `undefined`, 🍌 + +
Risposta +

+ +#### Risposta: D + +Il `?` ci consente di accedere opzionalmente a proprietà nidificate più profonde all'interno degli oggetti. Stiamo cercando di registrare l'elemento sull'indice `1` all'interno del sottoarray che si trova sull'indice `1` dell'array `fruits`. Se il sottoarray sull'indice `1` nell'array `fruits` non esiste, restituirà semplicemente `undefined`. Se il sottoarray sull'indice `1` nell'array `fruits` esiste, ma questo sottoarray non ha un elemento nel suo indice `1`, restituirà comunque `undefined`. + +Innanzitutto, stiamo cercando di registrare il secondo elemento nel sottoarray `['🍍']` di `[['🍊', '🍌'], ['🍍']]`. Questo sottoarray contiene solo un elemento, il che significa che non c'è alcun elemento nell'indice `1`, e restituisce `undefined`. + +Quindi, stiamo invocando la funzione `getFruits` senza passare un valore come argomento, il che significa che `fruits` ha un valore di `undefined` per impostazione predefinita. Poiché stiamo concatenando condizionatamente l'elemento sull'indice `1` di `fruits`, restituisce `undefined` poiché questo elemento sull'indice `1` non esiste. + +Infine, stiamo cercando di registrare il secondo elemento nel sottoarray `['🍊', '🍌']` di `['🍍'], ['🍊', '🍌']`. L'elemento nell'indice `1` all'interno di questo sottoarray è `🍌`, che viene registrato. +

+
+ +--- + +###### 147. Qual è l'output? + +```javascript +class Calc { + constructor() { + this.count = 0 + } + + increase() { + this.count ++ + } +} + +const calc = new Calc() +new Calc().increase() + +console.log(calc.count) +``` + +- A: `0` +- B: `1` +- C: `undefined` +- D: `ReferenceError` + +
Risposta +

+ +#### Risposta: A + +Impostiamo la variabile `calc` uguale a una nuova istanza della classe `Calc`. Quindi, istanziamo una nuova `Calc` e invochiamo il metodo `increase` su questa istanza. Poiché la proprietà count è all'interno del costruttore della classe `Calc`, la proprietà count non è condivisa sul prototipo di `Calc`. Ciò significa che il valore di count non è stato aggiornato per l'istanza a cui punta il calc, count è ancora `0`. +

+
+ +--- + +###### 148. Qual è l'output? + +```javascript +const user = { + email: "e@mail.com", + password: "12345" +} + +const updateUser = ({ email, password }) => { + if (email) { + Object.assign(user, { email }) + } + + if (password) { + user.password = password + } + + return user +} + +const updatedUser = updateUser({ email: "new@email.com" }) + +console.log(updatedUser === user) +``` + +- A: `false` +- B: `true` +- C: `TypeError` +- D: `ReferenceError` + +
Risposta +

+ +#### Risposta: B + +La funzione `updateUser` aggiorna i valori delle proprietà `email` e `password` sull'utente se i loro valori vengono passati alla funzione, dopodiché la funzione restituisce l'oggetto `user`. Il valore restituito dalla funzione `updateUser` è l'oggetto `user`, il che significa che il valore di updateUser è un riferimento allo stesso oggetto `user` a cui punta `user`. `updatedUser === user` è uguale a `true`. + +

+
+ +--- + +###### 149. Qual è l'output? + +```javascript +const fruit = ['🍌', '🍊', '🍎'] + +fruit.slice(0, 1) +fruit.splice(0, 1) +fruit.unshift('🍇') + +console.log(fruit) +``` + +- A: `['🍌', '🍊', '🍎']` +- B: `['🍊', '🍎']` +- C: `['🍇', '🍊', '🍎']` +- D: `['🍇', '🍌', '🍊', '🍎']` + +
Risposta +

+ +#### Risposta: C + +Per prima cosa, invochiamo il metodo `slice` sull'array fruit. Il metodo slice non modifica l'array originale, ma restituisce il valore che ha tagliato fuori dall'array: l'emoji banana. +Quindi, invochiamo il metodo `splice` sull'array fruit. Il metodo splice modifica l'array originale, il che significa che l'array fruit ora è composto da `['🍊', '🍎']`. +Infine, invochiamo il metodo `unshift` sull'array `fruit`, che modifica l'array originale aggiungendo il valore fornito, '🍇' in questo caso, come primo elemento nell'array. L'array fruit ora è composto da `['🍇', '🍊', '🍎']`. + +

+
+ +--- + +###### 150. Qual è l'output? + +```javascript +const animals = {}; +let dog = { emoji: '🐶' } +let cat = { emoji: '🐈' } + +animals[dog] = { ...dog, name: "Mara" } +animals[cat] = { ...cat, name: "Sara" } + +console.log(animals[dog]) +``` + +- A: `{ emoji: "🐶", name: "Mara" }` +- B: `{ emoji: "🐈", name: "Sara" }` +- C: `undefined` +- D: `ReferenceError` + +
Risposta +

+ +#### Risposta: B + +Le chiavi degli oggetti vengono convertite in stringhe. + +Poiché il valore di `dog` è un oggetto, `animals[dog]` significa in realtà che stiamo creando una nuova proprietà chiamata `"object Object"` uguale al nuovo oggetto. +`animals["object Object"]` è ora uguale a `{ emoji: "🐶", name: "Mara"}`. + +Anche `cat` è un oggetto, il che significa che `animals[cat]` in realtà stiamo sovrascrivendo il valore di `animals["object Object"]` con le nuove proprietà cat. + +Loggando `animals[dog]`, o effettivamente `animals["object Object"]`, poiché la conversione dell'oggetto `dog` in una stringa risulta `"object Object"`, restituisce `{ emoji: "🐈", name: "Sara" }`. + +

+
+ +--- + +###### 151. Qual è l'output? + +```javascript +const user = { + email: "my@email.com", + updateEmail: email => { + this.email = email + } +} + +user.updateEmail("new@email.com") +console.log(user.email) +``` + +- A: `my@email.com` +- B: `new@email.com` +- C: `undefined` +- D: `ReferenceError` + +
Risposta +

+ +#### Risposta: A + +La funzione `updateEmail` è una arrow function e non è legata all'oggetto `user`. Ciò significa che la parola chiave `this` non si riferisce all'oggetto `user`, ma in questo caso si riferisce allo scope globale. Il valore di `email` all'interno dell'oggetto `user` non viene aggiornato. Quando si stampa il valore di `user.email`, viene restituito il valore originale ovvero `my@email.com`. + +

+
+ +--- + +###### 152. Qual è l'output? + +```javascript +const promise1 = Promise.resolve('First') +const promise2 = Promise.resolve('Second') +const promise3 = Promise.reject('Third') +const promise4 = Promise.resolve('Fourth') + +const runPromises = async () => { + const res1 = await Promise.all([promise1, promise2]) + const res2 = await Promise.all([promise3, promise4]) + return [res1, res2] +} + +runPromises() + .then(res => console.log(res)) + .catch(err => console.log(err)) +``` + +- A: `[['First', 'Second'], ['Fourth']]` +- B: `[['First', 'Second'], ['Third', 'Fourth']]` +- C: `[['First', 'Second']]` +- D: `'Third'` + +
Risposta +

+ +#### Risposta: D + +Il metodo `Promise.all` esegue le promise passate in parallelo. Se una promise fallisce, il metodo `Promise.all` effettua un _rejects_ con il valore della prmise rifiutata. In questo caso, `promise3` ha rifiutato con il valore `"Third"`. Stiamo rilevando il valore rifiutato nel metodo `catch` concatenato sulla chiamata `runPromises` per rilevare eventuali errori all'interno della funzione `runPromises`. Solo `"Third"` viene registrato, poiché `promise3` viene rifiutato con questo valore. + +

+
+ +--- + +###### 153. Quale dovrebbe essere il valore di `method` per loggare ` {nome: "Lydia", età: 22} `? + +```javascript +const keys = ["name", "age"] +const values = ["Lydia", 22] + +const method = /* ?? */ +Object[method](keys.map((_, i) => { + return [keys[i], values[i]] +})) // { name: "Lydia", age: 22 } +``` + +- A: `entries` +- B: `values` +- C: `fromEntries` +- D: `forEach` + +
Risposta +

+ +#### Risposta: C + +Il metodo `fromEntries` trasforma un array 2d in un oggetto. Il primo elemento in ogni sottoarray sarà la chiave e il secondo elemento in ogni sottoarray sarà il valore. In questo caso, stiamo mappando sull'array `keys`, che restituisce un array il cui primo elemento è l'elemento nell'array di chiavi sull'indice corrente e il secondo elemento è l'elemento dell'array di valori sull'indice corrente. + +Questo crea una matrice di sottoarray contenenti le chiavi e i valori corretti, che risulta in `{ nome: "Lydia", età: 22 }` + +

+
+ +--- + +###### 154. Qual è l'output? + +```javascript +const createMember = ({ email, address = {}}) => { + const validEmail = /.+\@.+\..+/.test(email) + if (!validEmail) throw new Error("Valid email pls") + + return { + email, + address: address ? address : null + } +} + +const member = createMember({ email: "my@email.com" }) +console.log(member) +``` + +- A: `{ email: "my@email.com", address: null }` +- B: `{ email: "my@email.com" }` +- C: `{ email: "my@email.com", address: {} }` +- D: `{ email: "my@email.com", address: undefined }` + +
Risposta +

+ +#### Risposta: C + +Il valore predefinito di `address` è un oggetto vuoto `{}`. Quando abbiamo impostato la variabile `member` uguale all'oggetto restituito dalla funzione `createMember`, non abbiamo passato un valore per address, il che significa che il valore di address è l'oggetto vuoto predefinito `{}`. Un oggetto vuoto è un valore veritiero, il che significa che la condizione `address ? address : null` restituisce `true`. Il valore di address è l'oggetto vuoto `{}`. + +

+
+ +--- + +###### 155. Qual è l'output? + +```javascript +let randomValue = { name: "Lydia" } +randomValue = 23 + +if (!typeof randomValue === "string") { + console.log("It's not a string!") +} else { + console.log("Yay it's a string!") +} +``` + +- A: `It's not a string!` +- B: `Yay it's a string!` +- C: `TypeError` +- D: `undefined` + +
Risposta +

+ +#### Risposta: B + +La condizione all'interno dell'istruzione `if` controlla se il valore di `!typeof randomValue` è uguale a `"string"`. L'operatore `!` converte il valore in un valore booleano. Se il valore è vero, il valore restituito sarà `false`, se il valore è falso, il valore restituito sarà `true`. In questo caso, il valore restituito di `typeof randomValue` è il vero valore `"number"`, il che significa che il valore di `!typeof randomValue` è il valore booleano `false`. + +`!typeof randomValue === "string"` restituisce sempre false, poiché stiamo effettivamente controllando `false === "string"`. Poiché la condizione ha restituito `false`, il blocco di codice dell'istruzione `else` viene eseguito e `Yay it's a string!` viene registrato. + +

+
From caac31985a41baffd045b3734e4f6845e6c9d097 Mon Sep 17 00:00:00 2001 From: luciacenetiempo Date: Wed, 8 Jun 2022 19:53:26 +0200 Subject: [PATCH 104/193] Italian version added in the listing translations for all languages Italian version added in the listing translations for all languages --- README.md | 1 + ar-AR/README_AR.md | 1 + bs-BS/README-bs_BS.md | 1 + de-DE/README.md | 1 + es-ES/README-ES.md | 1 + fr-FR/README_fr-FR.md | 1 + id-ID/README.md | 1 + ja-JA/README-ja_JA.md | 1 + ko-KR/README-ko_KR.md | 1 + nl-NL/README.md | 1 + pt-BR/README_pt_BR.md | 1 + ru-RU/README.md | 1 + th-TH/README.md | 1 + tr-TR/README-tr_TR.md | 1 + uk-UA/README.md | 1 + vi-VI/README-vi.md | 1 + 16 files changed, 16 insertions(+) diff --git a/README.md b/README.md index 4cfa2556..656ad534 100644 --- a/README.md +++ b/README.md @@ -27,6 +27,7 @@ Feel free to reach out to me! 😊
- [🇪🇸 Español](./es-ES/README-ES.md) - [🇫🇷 Français](./fr-FR/README_fr-FR.md) - [🇮🇩 Indonesia](./id-ID/README.md) +- [🇮🇹 Italiano](./it-IT/README.md) - [🇯🇵 日本語](./ja-JA/README-ja_JA.md) - [🇰🇷 한국어](./ko-KR/README-ko_KR.md) - [🇳🇱 Nederlands](./nl-NL/README.md) diff --git a/ar-AR/README_AR.md b/ar-AR/README_AR.md index c5380e02..ed9a9eac 100644 --- a/ar-AR/README_AR.md +++ b/ar-AR/README_AR.md @@ -21,6 +21,7 @@ - [🇪🇸 Español](./es-ES/README-ES.md) - [🇫🇷 Français](./fr-FR/README_fr-FR.md) - [🇮🇩 Indonesia](./id-ID/README.md) +- [🇮🇹 Italiano](./it-IT/README.md) - [🇯🇵 日本語](./ja-JA/README-ja_JA.md) - [🇰🇷 한국어](./ko-KR/README-ko_KR.md) - [🇳🇱 Nederlands](./nl-NL/README.md) diff --git a/bs-BS/README-bs_BS.md b/bs-BS/README-bs_BS.md index b2e89de5..7ff21b44 100644 --- a/bs-BS/README-bs_BS.md +++ b/bs-BS/README-bs_BS.md @@ -19,6 +19,7 @@ kliknite na njih da biste ih proširili. Sretno :heart: - [🇪🇸 Español](./es-ES/README-ES.md) - [🇫🇷 Français](./fr-FR/README_fr-FR.md) - [🇮🇩 Indonesia](./id-ID/README.md) +- [🇮🇹 Italiano](./it-IT/README.md) - [🇯🇵 日本語](./ja-JA/README-ja_JA.md) - [🇰🇷 한국어](./ko-KR/README-ko_KR.md) - [🇳🇱 Nederlands](./nl-NL/README.md) diff --git a/de-DE/README.md b/de-DE/README.md index 9242e097..47a5fa01 100644 --- a/de-DE/README.md +++ b/de-DE/README.md @@ -29,6 +29,7 @@ Kontaktiert mich, wenn ihr möchtet! 😊
- [🇪🇸 Español](./es-ES/README-ES.md) - [🇫🇷 Français](./fr-FR/README_fr-FR.md) - [🇮🇩 Indonesia](./id-ID/README.md) +- [🇮🇹 Italiano](./it-IT/README.md) - [🇯🇵 日本語](./ja-JA/README-ja_JA.md) - [🇰🇷 한국어](./ko-KR/README-ko_KR.md) - [🇳🇱 Nederlands](./nl-NL/README.md) diff --git a/es-ES/README-ES.md b/es-ES/README-ES.md index 0e8dc473..9794aa30 100644 --- a/es-ES/README-ES.md +++ b/es-ES/README-ES.md @@ -19,6 +19,7 @@ Lista de lenguajes disponibles: - [🇬🇧 English](../README.md) - [🇫🇷 Français](./fr-FR/README_fr-FR.md) - [🇮🇩 Indonesia](./id-ID/README.md) +- [🇮🇹 Italiano](./it-IT/README.md) - [🇯🇵 日本語](./ja-JA/README-ja_JA.md) - [🇰🇷 한국어](./ko-KR/README-ko_KR.md) - [🇳🇱 Nederlands](./nl-NL/README.md) diff --git a/fr-FR/README_fr-FR.md b/fr-FR/README_fr-FR.md index 3260e671..55bc8c07 100644 --- a/fr-FR/README_fr-FR.md +++ b/fr-FR/README_fr-FR.md @@ -13,6 +13,7 @@ Les réponses se trouvent dans les sections repliées en dessous des questions, - [🇬🇧 English](../README.md) - [🇪🇸 Español](./es-ES/README-ES.md) - [🇮🇩 Indonesia](./id-ID/README.md) +- [🇮🇹 Italiano](./it-IT/README.md) - [🇯🇵 日本語](./ja-JA/README-ja_JA.md) - [🇰🇷 한국어](./ko-KR/README-ko_KR.md) - [🇳🇱 Nederlands](./nl-NL/README.md) diff --git a/id-ID/README.md b/id-ID/README.md index 21332103..3a6932fe 100644 --- a/id-ID/README.md +++ b/id-ID/README.md @@ -23,6 +23,7 @@ Jangan sungkan untuk terhubung dengan saya! 😊
- [🇬🇧 English](../README.md) - [🇪🇸 Español](./es-ES/README-ES.md) - [🇫🇷 Français](./fr-FR/README_fr-FR.md) +- [🇮🇹 Italiano](./it-IT/README.md) - [🇯🇵 日本語](./ja-JA/README-ja_JA.md) - [🇰🇷 한국어](./ko-KR/README-ko_KR.md) - [🇳🇱 Nederlands](./nl-NL/README.md) diff --git a/ja-JA/README-ja_JA.md b/ja-JA/README-ja_JA.md index 7be25a8b..9d579e93 100644 --- a/ja-JA/README-ja_JA.md +++ b/ja-JA/README-ja_JA.md @@ -16,6 +16,7 @@ - [🇪🇸 Español](../es-ES/README-ES.md) - [🇫🇷 Français](../fr-FR/README_fr-FR.md) - [🇮🇩 Indonesia](../id-ID/README.md) +- [🇮🇹 Italiano](./it-IT/README.md) - [🇰🇷 한국어](../ko-KR/README-ko_KR.md) - [🇳🇱 Nederlands](../nl-NL/README.md) - [🇧🇷 Português Brasil](../pt-BR/README_pt_BR.md) diff --git a/ko-KR/README-ko_KR.md b/ko-KR/README-ko_KR.md index 04349860..9f8f7e98 100644 --- a/ko-KR/README-ko_KR.md +++ b/ko-KR/README-ko_KR.md @@ -29,6 +29,7 @@ - [🇪🇸 Español](./es-ES/README-ES.md) - [🇫🇷 Français](./fr-FR/README_fr-FR.md) - [🇮🇩 Indonesia](./id-ID/README.md) +- [🇮🇹 Italiano](./it-IT/README.md) - [🇯🇵 日本語](./ja-JA/README-ja_JA.md) - [🇳🇱 Nederlands](./nl-NL/README.md) - [🇧🇷 Português Brasil](./pt-BR/README_pt_BR.md) diff --git a/nl-NL/README.md b/nl-NL/README.md index 34193a0e..ab01483a 100644 --- a/nl-NL/README.md +++ b/nl-NL/README.md @@ -25,6 +25,7 @@ - [🇪🇸 Español](./es-ES/README-ES.md) - [🇫🇷 Français](./fr-FR/README_fr-FR.md) - [🇮🇩 Indonesia](./id-ID/README.md) +- [🇮🇹 Italiano](./it-IT/README.md) - [🇯🇵 日本語](./ja-JA/README-ja_JA.md) - [🇰🇷 한국어](./ko-KR/README-ko_KR.md) - [🇧🇷 Português Brasil](./pt-BR/README_pt_BR.md) diff --git a/pt-BR/README_pt_BR.md b/pt-BR/README_pt_BR.md index b23c927e..395dc496 100644 --- a/pt-BR/README_pt_BR.md +++ b/pt-BR/README_pt_BR.md @@ -14,6 +14,7 @@ As respostas estão em seções recolhidas abaixo das questões, basta clicar ne - [🇪🇸 Español](./es-ES/README-ES.md) - [🇫🇷 Français](./fr-FR/README_fr-FR.md) - [🇮🇩 Indonesia](./id-ID/README.md) +- [🇮🇹 Italiano](./it-IT/README.md) - [🇯🇵 日本語](./ja-JA/README-ja_JA.md) - [🇰🇷 한국어](./ko-KR/README-ko_KR.md) - [🇳🇱 Nederlands](./nl-NL/README.md) diff --git a/ru-RU/README.md b/ru-RU/README.md index 9f90c59c..91963045 100644 --- a/ru-RU/README.md +++ b/ru-RU/README.md @@ -19,6 +19,7 @@ - [🇪🇸 Español](./es-ES/README-ES.md) - [🇫🇷 Français](./fr-FR/README_fr-FR.md) - [🇮🇩 Indonesia](./id-ID/README.md) +- [🇮🇹 Italiano](./it-IT/README.md) - [🇯🇵 日本語](./ja-JA/README-ja_JA.md) - [🇰🇷 한국어](./ko-KR/README-ko_KR.md) - [🇳🇱 Nederlands](./nl-NL/README.md) diff --git a/th-TH/README.md b/th-TH/README.md index 8b9adea3..9cab8b2c 100644 --- a/th-TH/README.md +++ b/th-TH/README.md @@ -26,6 +26,7 @@ - [🇪🇸 Español](./es-ES/README-ES.md) - [🇫🇷 Français](./fr-FR/README_fr-FR.md) - [🇮🇩 Indonesia](./id-ID/README.md) +- [🇮🇹 Italiano](./it-IT/README.md) - [🇯🇵 日本語](./ja-JA/README-ja_JA.md) - [🇰🇷 한국어](./ko-KR/README-ko_KR.md) - [🇳🇱 Nederlands](./nl-NL/README.md) diff --git a/tr-TR/README-tr_TR.md b/tr-TR/README-tr_TR.md index 3d1edba8..b80c634d 100644 --- a/tr-TR/README-tr_TR.md +++ b/tr-TR/README-tr_TR.md @@ -20,6 +20,7 @@ Mevcut dillerin listesi: - [🇪🇸 Español](./es-ES/README-ES.md) - [🇫🇷 Français](./fr-FR/README_fr-FR.md) - [🇮🇩 Indonesia](./id-ID/README.md) +- [🇮🇹 Italiano](./it-IT/README.md) - [🇯🇵 日本語](./ja-JA/README-ja_JA.md) - [🇰🇷 한국어](./ko-KR/README-ko_KR.md) - [🇳🇱 Nederlands](./nl-NL/README.md) diff --git a/uk-UA/README.md b/uk-UA/README.md index 003a372e..e4b77264 100644 --- a/uk-UA/README.md +++ b/uk-UA/README.md @@ -14,6 +14,7 @@ - [🇪🇸 Español](./es-ES/README-ES.md) - [🇫🇷 Français](./fr-FR/README_fr-FR.md) - [🇮🇩 Indonesia](./id-ID/README.md) +- [🇮🇹 Italiano](./it-IT/README.md) - [🇯🇵 日本語](./ja-JA/README-ja_JA.md) - [🇰🇷 한국어](./ko-KR/README-ko_KR.md) - [🇳🇱 Nederlands](./nl-NL/README.md) diff --git a/vi-VI/README-vi.md b/vi-VI/README-vi.md index 64552622..9007f57e 100644 --- a/vi-VI/README-vi.md +++ b/vi-VI/README-vi.md @@ -15,6 +15,7 @@ Danh sách các ngôn ngữ khác: - [🇪🇸 Español](./es-ES/README-ES.md) - [🇫🇷 Français](./fr-FR/README_fr-FR.md) - [🇮🇩 Indonesia](./id-ID/README.md) +- [🇮🇹 Italiano](./it-IT/README.md) - [🇯🇵 日本語](./ja-JA/README-ja_JA.md) - [🇰🇷 한국어](./ko-KR/README-ko_KR.md) - [🇳🇱 Nederlands](./nl-NL/README.md) From 3ab52e937a49ebb3822248abd479e04421625ce4 Mon Sep 17 00:00:00 2001 From: Jacob Herper Date: Sat, 18 Jun 2022 22:25:52 +0100 Subject: [PATCH 105/193] Revert "Spelling mistake" --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index f9c695e2..5e75b43f 100644 --- a/README.md +++ b/README.md @@ -311,8 +311,8 @@ The `colorChange` function is static. Static methods are designed to live only o ```javascript let greeting; -greeting = {}; // Typo! -console.log(greeting); +greetign = {}; // Typo! +console.log(greetign); ``` - A: `{}` From 1f8a3fd12f6da4c68c477e911dc91de7ecab7cac Mon Sep 17 00:00:00 2001 From: luciacenetiempo Date: Mon, 20 Jun 2022 09:50:26 +0200 Subject: [PATCH 106/193] changed the name of the readme changed the name of the readme file from readme-it to readme to make all links work in other languages --- it-IT/{README-IT.md => README.md} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename it-IT/{README-IT.md => README.md} (100%) diff --git a/it-IT/README-IT.md b/it-IT/README.md similarity index 100% rename from it-IT/README-IT.md rename to it-IT/README.md From 65ae3522b44953037715819712d700b93cc96328 Mon Sep 17 00:00:00 2001 From: VITOR PEREIRA Date: Fri, 1 Jul 2022 17:26:13 -0300 Subject: [PATCH 107/193] =?UTF-8?q?Traduzido=20para=20o=20portugu=C3=AAs?= =?UTF-8?q?=20aos=2080.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- pt-BR/README_pt_BR.md | 399 ++++++++++++++++++++++++++++++++++++------ 1 file changed, 347 insertions(+), 52 deletions(-) diff --git a/pt-BR/README_pt_BR.md b/pt-BR/README_pt_BR.md index 395dc496..1022bc28 100644 --- a/pt-BR/README_pt_BR.md +++ b/pt-BR/README_pt_BR.md @@ -29,7 +29,7 @@ As respostas estão em seções recolhidas abaixo das questões, basta clicar ne --- -###### 1. Qual é a saída? +###### 1. Qual o resultado? ```javascript function sayHi() { @@ -61,7 +61,7 @@ Variáveis com a palavra-chave `let` (e `const`) são elevadas, mas diferente de --- -###### 2. Qual é a saída? +###### 2. Qual o resultado? ```javascript for (var i = 0; i < 3; i++) { @@ -91,7 +91,7 @@ No segundo laço, a variável `i` foi declarada usando a palavra-chave `let`: Va --- -###### 3. Qual é a saída? +###### 3. Qual o resultado? ```javascript const shape = { @@ -127,7 +127,7 @@ Não há `radius` fora de shape, então retorna `undefined`. --- -###### 4. Qual é a saída? +###### 4. Qual o resultado? ```javascript +true; @@ -189,7 +189,7 @@ Por outro lado, com a notação de ponto `.`, isso não acontece. `mouse` não t --- -###### 6. Qual é a saída? +###### 6. Qual o resultado? ```javascript let c = { greeting: "Hey!" }; @@ -224,7 +224,7 @@ Quando você muda um objeto, você muda todos eles. --- -###### 7. Qual é a saída? +###### 7. Qual o resultado? ```javascript let a = 3; @@ -257,7 +257,7 @@ Contudo, quando usamos o operador `===`, ambos valor e tipo tem de ser o --- -###### 8. Qual é a saída? +###### 8. Qual o resultado? ```javascript class Chameleon { @@ -293,7 +293,7 @@ Já que `freddie` é filho de `Chameleon`, a função não é herdada, e não es --- -###### 9. Qual é a saída? +###### 9. Qual o resultado? ```javascript let greeting; @@ -348,7 +348,7 @@ Uma função é um tipo especial de objeto. O código que você escreve não é --- -###### 11. Qual é a saída? +###### 11. Qual o resultado? ```javascript function Person(firstName, lastName) { @@ -391,7 +391,7 @@ faria `member.getFullName()` funcionar. Por quê isso é beneficial? Digamos que --- -###### 12. Qual é a saída? +###### 12. Qual o resultado? ```javascript function Person(firstName, lastName) { @@ -464,7 +464,7 @@ Todos objetos tem protótipos, exceto pelo **base object**. O base object tem ac --- -###### 15. Qual é a saída? +###### 15. Qual o resultado? ```javascript function sum(a, b) { @@ -493,7 +493,7 @@ Nesse exemplo, JavaScript converte o número `1` em uma string, para que a funç --- -###### 16. Qual é a saída? +###### 16. Qual o resultado? ```javascript let number = 0; @@ -529,7 +529,7 @@ Isso retorna `0 2 2`. --- -###### 17. Qual é a saída? +###### 17. Qual o resultado? ```javascript function getPersonInfo(one, two, three) { @@ -560,7 +560,7 @@ Se usamos template literals marcadas, ou tagged template literals, o valor do pr --- -###### 18. Qual é a saída? +###### 18. Qual o resultado? ```javascript function checkAge(data) { @@ -596,7 +596,7 @@ Os dois objetos que estamos comparando não são assim: O objeto que passamos co --- -###### 19. Qual é a saída? +###### 19. Qual o resultado? ```javascript function getAge(...args) { @@ -623,7 +623,7 @@ O operador _spread_ (`...args`.) retorna um array com os argumentos. Um array é --- -###### 20. Qual é a saída? +###### 20. Qual o resultado? ```javascript function getAge() { @@ -700,7 +700,7 @@ Se usássemos `localStorage`, o dado seria guardado para sempre, exceto se `loca --- -###### 23. Qual é a saída? +###### 23. Qual o resultado? ```javascript var num = 8; @@ -728,7 +728,7 @@ Você não pode fazer isso com `let` ou `const` uma vez que eles conferem o bloc --- -###### 24. Qual é a saída? +###### 24. Qual o resultado? ```javascript const obj = { 1: "a", 2: "b", 3: "c" }; @@ -759,7 +759,7 @@ Não funciona assim para `Set`. Não tem um `'1'` no nosso set: `set.has('1')` r --- -###### 25. Qual é a saída? +###### 25. Qual o resultado? ```javascript const obj = { a: "one", b: "two", a: "three" }; @@ -801,7 +801,7 @@ O contexto base de execução é o contexto global: É aquilo que está acessív --- -###### 27. Qual é a saída? +###### 27. Qual o resultado? ```javascript for (let i = 1; i < 5; i++) { @@ -827,7 +827,7 @@ A palavra-chave `continue` pula uma iteração se a condição retorna `true`. --- -###### 28. Qual é a saída? +###### 28. Qual o resultado? ```javascript String.prototype.giveLydiaPizza = () => { @@ -856,7 +856,7 @@ name.giveLydiaPizza(); --- -###### 29. Qual é a saída? +###### 29. Qual o resultado? ```javascript const a = {}; @@ -890,7 +890,7 @@ Então, fazemos o log de `a[b]`, o que na verdade é `a["object Object"]`. Acabm --- -###### 30. Qual é a saída? +###### 30. Qual o resultado? ```javascript const foo = () => console.log("First"); @@ -999,7 +999,7 @@ Se clicarmos em `p`, veremos dois itens adicionaos ao log: `p` e `div`. Durante --- -###### 33. Qual é a saída? +###### 33. Qual o resultado? ```javascript const person = { name: "Lydia" }; @@ -1031,7 +1031,7 @@ Com ambos, podemos passar o objeto que queremos que o `this` faça referência. --- -###### 34. Qual é a saída? +###### 34. Qual o resultado? ```javascript function sayHi() { @@ -1121,7 +1121,7 @@ console.log(typeof typeof 1); --- -###### 37. Qual é a saída? +###### 37. Qual o resultado? ```javascript const numbers = [1, 2, 3]; @@ -1150,7 +1150,7 @@ dependendo de onde você o executa, pois é diferente para cada navegador, node --- -###### 38. Qual é a saída? +###### 38. Qual o resultado? ```javascript (() => { @@ -1210,7 +1210,7 @@ O que diferencia um primitivo de um objeto é que primitivos não métodos ou pr --- -###### 40. Qual é a saída? +###### 40. Qual o resultado? ```javascript [[0, 1], [2, 3]].reduce( @@ -1240,7 +1240,7 @@ Então, `[1, 2, 0, 1]` é `acc` e `[2, 3]` é o `cur`. Concatenamos novamente, e --- -###### 41. Qual é a saída? +###### 41. Qual o resultado? ```javascript !!null; @@ -1315,7 +1315,7 @@ Strings são iteráveis. O operador do spread `...` mapeia todo caractére de um --- -###### 44. Qual é a saída? +###### 44. Qual o resultado? ```javascript function* generator(i) { @@ -1380,7 +1380,7 @@ Quando passamos múltiplas "promises" para a função `Promise.race`, ele resolv --- -###### 46. Qual é a saída? +###### 46. Qual o resultado? ```javascript let person = { name: "Lydia" }; @@ -1419,7 +1419,7 @@ Estamos apenas modificando o valor da variável `person`, e não o primeiro elem --- -###### 47. Qual é a saída? +###### 47. Qual o resultado? ```javascript const person = { @@ -1449,7 +1449,7 @@ Utilizando o loop `for-in`, podemos interar através das chaves do objeto, neste --- -###### 48. Qual é a saída? +###### 48. Qual o resultado? ```javascript console.log(3 + 4 + "5"); @@ -1501,7 +1501,7 @@ Apenas os primeiros números da string é retornado. Baseado no _radix_ (o segun --- -###### 50. Qual é a saída? +###### 50. Qual o resultado? ```javascript [1, 2, 3].map(num => { @@ -1529,7 +1529,7 @@ Entretanto, não se retorna o valor. Quando não se retorna um valor para a fun --- -###### 51. Qual é a saída? +###### 51. Qual o resultado? ```javascript function getInfo(member, year) { @@ -1563,7 +1563,7 @@ O valor de `person` é um objeto. O argumento `member` possui uma referência (c --- -###### 52. Qual é a saída? +###### 52. Qual o resultado? ```javascript function greeting() { @@ -1599,7 +1599,7 @@ Com a declaração `catch`, podemos especificar o que fazer se uma exceção for --- -###### 53. Qual é a saída? +###### 53. Qual o resultado? ```javascript function Car() { @@ -1627,7 +1627,7 @@ Quando você retorna uma propriedade, o valor da propriedade é igual ao valor _ --- -###### 54. Qual é a saída? +###### 54. Qual o resultado? ```javascript (() => { @@ -1665,7 +1665,7 @@ No entanto, criamos uma variável global `y` ao definir `y` igual a `10`. Este v --- -###### 55. Qual é a saída? +###### 55. Qual o resultado? ```javascript class Dog { @@ -1701,7 +1701,7 @@ Quando tentamos invocar algo que não é uma função, um `TypeError` é lançad --- -###### 56. Qual é a saída? +###### 56. Qual o resultado? ```javascript const set = new Set([1, 1, 2, 3, 4]); @@ -1727,7 +1727,7 @@ Passamos o iterável `[1, 1, 2, 3, 4]` com um valor `1` duplicado. Como não pod --- -###### 57. Qual é a saída? +###### 57. Qual o resultado? ```javascript // counter.js @@ -1761,7 +1761,7 @@ Quando tentamos aumentar o valor de `myCounter`, recebemos um erro: `myCounter` --- -###### 58. Qual é a saída? +###### 58. Qual o resultado? ```javascript const name = "Lydia"; @@ -1789,7 +1789,7 @@ A variável `name` foi declarada com `const`, portanto sua exclusão não é bem --- -###### 59. Qual é a saída? +###### 59. Qual o resultado? ```javascript const numbers = [1, 2, 3, 4, 5]; @@ -1830,7 +1830,7 @@ Isso significa que o valor de `y` é igual ao primeiro valor no array, que é o --- -###### 60. Qual é a saída? +###### 60. Qual o resultado? ```javascript const user = { name: "Lydia", age: 21 }; @@ -1885,7 +1885,7 @@ Assim, o método `defineProperty` dá a você muito mais controle sobre as propr --- -###### 62. Qual é a saída? +###### 62. Qual o resultado? ```javascript const settings = { @@ -1917,7 +1917,7 @@ Se o substituto (replacer) for uma _função_, essa função é chamada em c ada
--- -###### 63. Qual é a saída? +###### 63. Qual o resultado? ```javascript let num = 10; @@ -1950,7 +1950,7 @@ O operador unário `++` primeiro _retorna_ o valor do operando, depois _incremen
--- -###### 64. Qual é a saída? +###### 64. Qual o resultado? ```javascript const value = { number: 10 }; @@ -1987,7 +1987,7 @@ Na quarta vez, passamos o objeto `value` novamente. `x.number` foi modificado an
--- -###### 65. Qual é a saída? +###### 65. Qual o resultado? ```javascript [1, 2, 3, 4].reduce((x, y) => console.log(x, y)); @@ -2072,7 +2072,7 @@ A classe `Labrador` recebe dois argumentos, `name`, pois estende `Dog`, e `size`
--- -###### 67. Qual é a saída? +###### 67. Qual o resultado? ```javascript // index.js @@ -2103,7 +2103,7 @@ Esta é uma diferença entre `require()` no CommonJS e `import`! Com `require()`
--- -###### 68. Qual é a saída? +###### 68. Qual o resultado? ```javascript console.log(Number(2) === Number(2)); @@ -2127,7 +2127,7 @@ Todo símbolo (Symbol) é totalmente único. O objetivo do argumento passado ao
--- -###### 69. Qual é a saída? +###### 69. Qual o resultado? ```javascript const name = 'Lydia Hallie'; @@ -2153,7 +2153,7 @@ Se o argumento passado para o método `padStart` for menor que o comprimento da
--- -###### 70. Qual é a saída? +###### 70. Qual o resultado? ```javascript console.log('🥑' + '💻'); @@ -2211,4 +2211,299 @@ Quando chamamos `game.next("Sim").value`, o `yield` anterior é substituído pel

+--- + +###### 72. Qual é o resultado? + +```javascript +console.log(String.raw`Hello\nworld`); +``` + +- A: `Hello world!` +- B: `Hello`
     `world` +- C: `Hello\nworld` +- D: `Hello\n`
     `world` + +
Answer +

+ +#### Answer: C + +`String.raw` retorna um texto onde os escape (`\n`, `\v`, `\t` etc.) são ignorados! As barras invertidas podem ser um problema, pois você pode acabar com algo como: + +`` caminho const = `C:\Documents\Projects\table.html` `` + +O que resultaria em: + +`"C:DocumentsProjectstable.html"` + +Com `String.raw`, ele simplesmente ignoraria o escape e imprimiria: + +`C:\Documents\Projects\table.html` + +Neste caso, a string é `Hello\nworld`, que é registrada. + +

+
+ +--- +###### 73. Qual o resultado? + +```javascript +async function getData() { + return await Promise.resolve('I made it!'); +} + +const data = getData(); +console.log(data); +``` + +- A: `"I made it!"` +- B: `Promise {: "I made it!"}` +- C: `Promise {}` +- D: `undefined` + +
Answer +

+ +#### Resposta: C + +Uma função assíncrona sempre retorna uma promise. O `await` ainda tem que esperar que a promise seja resolvida: uma promise pendente é retornada quando chamamos `getData()` para definir `data` igual a ela. + +Se quiséssemos ter acesso ao valor resolvido `"I made it"`, poderíamos ter usado o método `.then()` em `data`: + +`data.then(res => console.log(res))` + +Isso teria registrado `"Consegui!"` + +

+
+ +--- +###### 74. Qual o resultado? + +```javascript +function addToList(item, list) { + return list.push(item); +} + +const result = addToList('apple', ['banana']); +console.log(result); +``` + +- A: `['apple', 'banana']` +- B: `2` +- C: `true` +- D: `undefined` + +
Answer +

+ +#### Answer: B + +O método `.push()` retorna o _length_ do novo array! Anteriormente, a matriz continha um elemento (a string `"banana"`) e tinha um comprimento de `1`. Depois de adicionar a string `"apple"` ao array, o array contém dois elementos e tem um comprimento de `2`. Isso é retornado da função `addToList`. + +O método `push` modifica o array original. Se você quisesse retornar o _array_ da função ao invés do _tamanho do array_, você deveria ter retornado `list` depois de enviar `item` para ele. + +

+
+ +--- + +###### 75. Qual o resultado? + +```javascript +const box = { x: 10, y: 20 }; + +Object.freeze(box); + +const shape = box; +shape.x = 100; + +console.log(shape); +``` + +- A: `{ x: 100, y: 20 }` +- B: `{ x: 10, y: 20 }` +- C: `{ x: 100 }` +- D: `ReferenceError` + +
Answer +

+ +#### Answer: B + +`Object.freeze` torna impossível adicionar, remover ou modificar propriedades de um objeto (a menos que o valor da propriedade seja outro objeto). + +Quando criamos a variável `shape` e a definimos igual ao objeto congelado `box`, `shape` também se refere a um objeto congelado. Você pode verificar se um objeto está congelado usando `Object.isFrozen`. Neste caso, `Object.isFrozen(shape)` retorna true, pois a variável `shape` tem uma referência a um objeto congelado. + +Como `shape` está congelado, e como o valor de `x` não é um objeto, não podemos modificar a propriedade `x`. `x` ainda é igual a `10`, e `{ x: 10, y: 20 }` é registrado. + +

+
+ +--- + +###### 76.Qual o resultado? + +```javascript +const { name: myName } = { name: 'Lydia' }; + +console.log(name); +``` + +- A: `"Lydia"` +- B: `"myName"` +- C: `undefined` +- D: `ReferenceError` + +
Answer +

+ +#### Answer: C + +Quando descompactamos a propriedade `name` do objeto do lado direito, atribuímos seu valor `"Lydia"` a uma variável com o nome `myName`. + +Com `{ name: myName }`, informamos ao JavaScript que queremos criar uma nova variável chamada `myName` com o valor da propriedade `name` no lado direito. + +Como tentamos registrar `name`, uma variável que não está definida, `undefined` é retornado na atribuição do lado esquerdo. Mais tarde, o valor de `Lydia` é armazenado através da atribuição de desestruturação. + +

+
+ +--- + +###### 77. É uma função pura? + +```javascript +function sum(a, b) { + return a + b; +} +``` + +- A: Yes +- B: No + +
Answer +

+ +#### Answer: A + +Uma função pura é uma função que _sempre_ retorna o mesmo resultado, se os mesmos argumentos forem passados. + +A função `sum` sempre retorna o mesmo resultado. Se passarmos `1` e` 2`, ele _sempre_ retornará `3` sem efeitos colaterais. Se passarmos `5` e `10`, ele _sempre_ retornará `15`, e assim por diante. Esta é a definição de uma função pura. + +

+
+ +--- + +###### 78. Qual o resultado? + +```javascript +const add = () => { + const cache = {}; + return num => { + if (num in cache) { + return `From cache! ${cache[num]}`; + } else { + const result = num + 10; + cache[num] = result; + return `Calculated! ${result}`; + } + }; +}; + +const addFunction = add(); +console.log(addFunction(10)); +console.log(addFunction(10)); +console.log(addFunction(5 * 2)); +``` + +- A: `Calculated! 20` `Calculated! 20` `Calculated! 20` +- B: `Calculated! 20` `From cache! 20` `Calculated! 20` +- C: `Calculated! 20` `From cache! 20` `From cache! 20` +- D: `Calculated! 20` `From cache! 20` `Error` + +
Answer +

+ +#### Answer: C + +A função `add` é uma função _memoized_. Com a memorização, podemos armazenar em cache os resultados de uma função para acelerar sua execução. Nesse caso, criamos um objeto `cache` que armazena os valores retornados anteriormente. + +Se chamarmos a função `addFunction` novamente com o mesmo argumento, ela primeiro verifica se já obteve esse valor em seu cache. Se for o caso, o valor dos caches será retornado, o que economiza tempo de execução. Caso contrário, se não estiver armazenado em cache, ele calculará o valor e o armazenará posteriormente. + +Chamamos a função `addFunction` três vezes com o mesmo valor: na primeira chamada, o valor da função quando `num` é igual a `10` ainda não é armazenado em cache. A condição da instrução if `num in cache` retorna `false`, e o bloco else é executado: `Calculated! 20` é registrado e o valor do resultado é adicionado ao objeto de cache. `cache` agora se parece com` {10:20} `. + +Na segunda vez, o objeto `cache` contém o valor que é retornado para `10`. A condição da instrução if `num in cache` retorna `true`, e `'From cache! 20'` é registrado. + +Na terceira vez, passamos `5 * 2` para a função que é avaliada como `10`. O objeto `cache` contém o valor que é retornado para `10`. A condição da instrução if `num in cache` retorna `true`, e `'From cache! 20'` é registrado. + +

+
+ +--- + +###### 79. Qual o resultado? + +```javascript +const myLifeSummedUp = ['☕', '💻', '🍷', '🍫']; + +for (let item in myLifeSummedUp) { + console.log(item); +} + +for (let item of myLifeSummedUp) { + console.log(item); +} +``` + +- A: `0` `1` `2` `3` and `"☕"` `"💻"` `"🍷"` `"🍫"` +- B: `"☕"` `"💻"` `"🍷"` `"🍫"` and `"☕"` `"💻"` `"🍷"` `"🍫"` +- C: `"☕"` `"💻"` `"🍷"` `"🍫"` and `0` `1` `2` `3` +- D: `0` `1` `2` `3` and `{0: "☕", 1: "💻", 2: "🍷", 3: "🍫"}` + +
Answer +

+ +#### Answer: A + +Com um loop _for-in_, podemos iterar sobre propriedades **enumeráveis​​**. Em um array, as propriedades enumeráveis ​​são as "chaves" dos elementos do array, que na verdade são seus índices. Você pode ver uma matriz como: + +`{0:" ☕ ", 1:" 💻 ", 2:" 🍷 ", 3:" 🍫 "}` + +Onde as chaves são as propriedades enumeráveis. `0`` 1` `2`` 3` são registrados. + +Com um loop _for-of_, podemos iterar sobre **iteráveis**. Um array é um iterável. Quando iteramos sobre o array, a variável "item" é igual ao elemento sobre o qual está iterando no momento, `" ☕ "` `" 💻 "` `" 🍷 "` `" 🍫 "` são registrados. + +

+
+ +--- + +###### 80. Qual o resultado? + +```javascript +const list = [1 + 2, 1 * 2, 1 / 2]; +console.log(list); +``` + +- A: `["1 + 2", "1 * 2", "1 / 2"]` +- B: `["12", 2, 0.5]` +- C: `[3, 2, 0.5]` +- D: `[1, 1, 1]` + +
Answer +

+ +#### Answer: C + +Os elementos da matriz podem conter qualquer valor. Números, strings, objetos, outras matrizes, valores nulos, booleanos, indefinidos e outras expressões, como datas, funções e cálculos. + +O elemento será igual ao valor retornado. `1 + 2` retorna` 3`, `1 * 2` retorna` 2` e `1 / 2` retorna` 0,5`. + +

+
+ --- \ No newline at end of file From ba6ed47ff3b4bc36a75969bec733ffc52b25c86c Mon Sep 17 00:00:00 2001 From: edim7 Date: Tue, 26 Jul 2022 00:52:36 +0200 Subject: [PATCH 108/193] question 28 fix - based on issue 672 - console log added --- README.md | 2 +- ar-AR/README_AR.md | 2 +- ar-EG/README_ar-EG.md | 2 +- bs-BS/README-bs_BS.md | 4 ++-- de-DE/README.md | 2 +- es-ES/README-ES.md | 2 +- fr-FR/README_fr-FR.md | 2 +- id-ID/README.md | 2 +- it-IT/README-IT.md | 2 +- ja-JA/README-ja_JA.md | 2 +- ko-KR/README-ko_KR.md | 2 +- nl-NL/README.md | 2 +- pt-BR/README_pt_BR.md | 2 +- ru-RU/README.md | 2 +- th-TH/README.md | 2 +- tr-TR/README-tr_TR.md | 2 +- uk-UA/README.md | 2 +- vi-VI/README-vi.md | 2 +- zh-TW/README_zh-TW.md | 2 +- 19 files changed, 20 insertions(+), 20 deletions(-) diff --git a/README.md b/README.md index 5e75b43f..8d35b03c 100644 --- a/README.md +++ b/README.md @@ -847,7 +847,7 @@ String.prototype.giveLydiaPizza = () => { const name = 'Lydia'; -name.giveLydiaPizza(); +console.log(name.giveLydiaPizza()) ``` - A: `"Just give Lydia pizza already!"` diff --git a/ar-AR/README_AR.md b/ar-AR/README_AR.md index ed9a9eac..92a52576 100644 --- a/ar-AR/README_AR.md +++ b/ar-AR/README_AR.md @@ -868,7 +868,7 @@ String.prototype.giveLydiaPizza = () => { const name = "Lydia"; -name.giveLydiaPizza(); +console.log(name.giveLydiaPizza()) ``` - A: `"Just give Lydia pizza already!"` diff --git a/ar-EG/README_ar-EG.md b/ar-EG/README_ar-EG.md index 656a2ccf..b9024d95 100644 --- a/ar-EG/README_ar-EG.md +++ b/ar-EG/README_ar-EG.md @@ -891,7 +891,7 @@ String.prototype.giveLydiaPizza = () => { const name = "Lydia"; -name.giveLydiaPizza(); +console.log(name.giveLydiaPizza()) ``` diff --git a/bs-BS/README-bs_BS.md b/bs-BS/README-bs_BS.md index 7ff21b44..2dedc78a 100644 --- a/bs-BS/README-bs_BS.md +++ b/bs-BS/README-bs_BS.md @@ -937,7 +937,7 @@ vraća "true". * * * * * -###### 28. Što je izlaz? +###### Što je izlaz? ```javascript String.prototype.giveLydiaPizza = () => { @@ -946,7 +946,7 @@ String.prototype.giveLydiaPizza = () => { const name = "Lydia"; -name.giveLydiaPizza(); +console.log(name.giveLydiaPizza()) ``` - A: `` Već daj Lizijinu pizzu! `` diff --git a/de-DE/README.md b/de-DE/README.md index 47a5fa01..2e6466b4 100644 --- a/de-DE/README.md +++ b/de-DE/README.md @@ -850,7 +850,7 @@ String.prototype.giveLydiaPizza = () => { const name = "Lydia"; -name.giveLydiaPizza(); +console.log(name.giveLydiaPizza()) ``` - A: `"Just give Lydia pizza already!"` diff --git a/es-ES/README-ES.md b/es-ES/README-ES.md index 9794aa30..7b754091 100644 --- a/es-ES/README-ES.md +++ b/es-ES/README-ES.md @@ -835,7 +835,7 @@ String.prototype.giveLydiaPizza = () => { const name = "Lydia"; -name.giveLydiaPizza(); +console.log(name.giveLydiaPizza()) ``` - A: `"Just give Lydia pizza already!"` diff --git a/fr-FR/README_fr-FR.md b/fr-FR/README_fr-FR.md index 55bc8c07..34f38e67 100644 --- a/fr-FR/README_fr-FR.md +++ b/fr-FR/README_fr-FR.md @@ -832,7 +832,7 @@ String.prototype.giveLydiaPizza = () => { const name = "Lydia"; -name.giveLydiaPizza(); +console.log(name.giveLydiaPizza()) ``` - A: `"Just give Lydia pizza already!"` diff --git a/id-ID/README.md b/id-ID/README.md index 3a6932fe..8e0e9411 100644 --- a/id-ID/README.md +++ b/id-ID/README.md @@ -839,7 +839,7 @@ String.prototype.giveLydiaPizza = () => { const name = 'Lydia'; -name.giveLydiaPizza(); +console.log(name.giveLydiaPizza()) ``` - A: `"Just give Lydia pizza already!"` diff --git a/it-IT/README-IT.md b/it-IT/README-IT.md index 3efee591..2cee9bf6 100644 --- a/it-IT/README-IT.md +++ b/it-IT/README-IT.md @@ -857,7 +857,7 @@ String.prototype.giveLydiaPizza = () => { const name = 'Lydia'; -name.giveLydiaPizza(); +console.log(name.giveLydiaPizza()) ``` - A: `"Just give Lydia pizza already!"` diff --git a/ja-JA/README-ja_JA.md b/ja-JA/README-ja_JA.md index 9d579e93..21d42099 100644 --- a/ja-JA/README-ja_JA.md +++ b/ja-JA/README-ja_JA.md @@ -855,7 +855,7 @@ String.prototype.giveLydiaPizza = () => { const name = "Lydia"; -name.giveLydiaPizza(); +console.log(name.giveLydiaPizza()) ``` - A: `"Just give Lydia pizza already!"` diff --git a/ko-KR/README-ko_KR.md b/ko-KR/README-ko_KR.md index 9f8f7e98..a31efa8e 100644 --- a/ko-KR/README-ko_KR.md +++ b/ko-KR/README-ko_KR.md @@ -848,7 +848,7 @@ String.prototype.giveLydiaPizza = () => { const name = 'Lydia'; -name.giveLydiaPizza(); +console.log(name.giveLydiaPizza()) ``` - A: `"Just give Lydia pizza already!"` diff --git a/nl-NL/README.md b/nl-NL/README.md index ab01483a..91479209 100644 --- a/nl-NL/README.md +++ b/nl-NL/README.md @@ -845,7 +845,7 @@ String.prototype.giveLydiaPizza = () => { const name = "Lydia"; -name.giveLydiaPizza(); +console.log(name.giveLydiaPizza()) ``` - A: `"Just give Lydia pizza already!"` diff --git a/pt-BR/README_pt_BR.md b/pt-BR/README_pt_BR.md index 395dc496..21cb1ed9 100644 --- a/pt-BR/README_pt_BR.md +++ b/pt-BR/README_pt_BR.md @@ -836,7 +836,7 @@ String.prototype.giveLydiaPizza = () => { const name = "Lydia"; -name.giveLydiaPizza(); +console.log(name.giveLydiaPizza()) ``` - A: `"Just give Lydia pizza already!"` diff --git a/ru-RU/README.md b/ru-RU/README.md index 91963045..1d19a247 100644 --- a/ru-RU/README.md +++ b/ru-RU/README.md @@ -837,7 +837,7 @@ String.prototype.giveLydiaPizza = () => { const name = "Lydia"; -name.giveLydiaPizza(); +console.log(name.giveLydiaPizza()) ``` - A: `"Just give Lydia pizza already!"` diff --git a/th-TH/README.md b/th-TH/README.md index 9cab8b2c..13a33c70 100644 --- a/th-TH/README.md +++ b/th-TH/README.md @@ -844,7 +844,7 @@ String.prototype.giveLydiaPizza = () => { const name = "Lydia"; -name.giveLydiaPizza(); +console.log(name.giveLydiaPizza()) ``` - A: `"Just give Lydia pizza already!"` diff --git a/tr-TR/README-tr_TR.md b/tr-TR/README-tr_TR.md index b80c634d..f03059f9 100644 --- a/tr-TR/README-tr_TR.md +++ b/tr-TR/README-tr_TR.md @@ -827,7 +827,7 @@ String.prototype.giveLydiaPizza = () => { const name = "Lydia"; -name.giveLydiaPizza(); +console.log(name.giveLydiaPizza()) ``` - A: `"Just give Lydia pizza already!"` diff --git a/uk-UA/README.md b/uk-UA/README.md index e4b77264..15ed5038 100644 --- a/uk-UA/README.md +++ b/uk-UA/README.md @@ -830,7 +830,7 @@ String.prototype.giveLydiaPizza = () => { const name = "Lydia"; -name.giveLydiaPizza(); +console.log(name.giveLydiaPizza()) ``` - A: `"Just give Lydia pizza already!"` diff --git a/vi-VI/README-vi.md b/vi-VI/README-vi.md index 9007f57e..36dd795a 100644 --- a/vi-VI/README-vi.md +++ b/vi-VI/README-vi.md @@ -833,7 +833,7 @@ String.prototype.giveLydiaPizza = () => { const name = "Lydia"; -name.giveLydiaPizza(); +console.log(name.giveLydiaPizza()) ``` - A: `"Just give Lydia pizza already!"` diff --git a/zh-TW/README_zh-TW.md b/zh-TW/README_zh-TW.md index c7e32ee7..5a2765a7 100644 --- a/zh-TW/README_zh-TW.md +++ b/zh-TW/README_zh-TW.md @@ -820,7 +820,7 @@ String.prototype.giveLydiaPizza = () => { const name = 'Lydia'; -name.giveLydiaPizza(); +console.log(name.giveLydiaPizza()) ``` - A: `"Just give Lydia pizza already!"` From 14ac4a50da95751fc34e5cda05537d86091a76e4 Mon Sep 17 00:00:00 2001 From: Raj Magar Date: Sun, 7 Aug 2022 04:27:27 +0530 Subject: [PATCH 109/193] Fix Question No. 37 --- README.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 5e75b43f..bedb664c 100644 --- a/README.md +++ b/README.md @@ -1142,9 +1142,9 @@ numbers[10] = 11; console.log(numbers); ``` -- A: `[1, 2, 3, 7 x null, 11]` +- A: `[1, 2, 3, null x 7, 11]` - B: `[1, 2, 3, 11]` -- C: `[1, 2, 3, 7 x empty, 11]` +- C: `[1, 2, 3, empty x 7, 11]` - D: `SyntaxError`
Answer @@ -1154,7 +1154,7 @@ console.log(numbers); When you set a value to an element in an array that exceeds the length of the array, JavaScript creates something called "empty slots". These actually have the value of `undefined`, but you will see something like: -`[1, 2, 3, 7 x empty, 11]` +`[1, 2, 3, empty x 7, 11]` depending on where you run it (it's different for every browser, node, etc.) From 9136c0465e7aa8a550e55a1ea65e343a5a2b0f09 Mon Sep 17 00:00:00 2001 From: Filippo Bristot Date: Sun, 14 Aug 2022 13:09:38 +0200 Subject: [PATCH 110/193] fix typos in README-IT questions 1-19 --- it-IT/README-IT.md | 31 +++++++++++++++---------------- 1 file changed, 15 insertions(+), 16 deletions(-) diff --git a/it-IT/README-IT.md b/it-IT/README-IT.md index 3efee591..8eaa75dd 100644 --- a/it-IT/README-IT.md +++ b/it-IT/README-IT.md @@ -138,9 +138,9 @@ console.log(shape.perimeter()); #### Risposta: B -Il valore di `diameter` è una funzione regolare, mentre il vaore di `perimeter` è gemerato con una arrow function. +Il valore di `diameter` è una funzione regolare, mentre il valore di `perimeter` è generato con una arrow function. -Nelle arrow functions, la chiave `this` fa riferimento al suo scope interno a differenza delle funzioni regolari. Questo vuol dire che quando richiamiamo `perimeter` non stiamo facendo riferimento all'oggetto shape, ma al suo ambito circostantr (ad esempio window). +Nelle arrow functions, la chiave `this` fa riferimento al suo scope interno a differenza delle funzioni regolari. Questo vuol dire che quando richiamiamo `perimeter` non stiamo facendo riferimento all'oggetto shape, ma al suo ambito circostante (ad esempio window). Non troviamo quindi alcun valore `radius` in quell'oggetto e quindi viene restituito `NaN`. @@ -201,9 +201,9 @@ In JavaScript, tutte le chiavi degli oggetti sono stringhe (a meno che non sia u JavaScript interpreta le istruzioni, quindi quando usiamo la bracket notation, vede la prima parentesi aperta `[` e continua finché non trova la parentesi chiusa `]`. Solo allora valuterà la dichiarazione. -Quando in javascript richiamiamo `mouse[bird.size]`: per prima cosa viene valorizzato `bird.size`, che è `"small"`, per JS viene tradotto quindi come `mouse["small"]` che restituisce `true`. +Quando in JavaScript richiamiamo `mouse[bird.size]`: per prima cosa viene valorizzato `bird.size`, che è `"small"`, per JS viene tradotto quindi come `mouse["small"]` che restituisce `true`. -Con l'utilizzo del punto questo non accade perchè `mouse` non ha una chiave chiamata `bird`, e questo significa che `mouse.bird` è `undefined`. Per Javascript quindi l'istruzione `mouse.bird.size` viene tradotta con `mouse.undefined.size` che è un valore non valido e che quindi genererà un errore simile a `Cannot read property "size" of undefined`. +Con l'utilizzo del punto questo non accade perché `mouse` non ha una chiave chiamata `bird`, e questo significa che `mouse.bird` è `undefined`. Per Javascript quindi l'istruzione `mouse.bird.size` viene tradotta con `mouse.undefined.size` che è un valore non valido e che quindi genererà un errore simile a `Cannot read property "size" of undefined`.

@@ -232,13 +232,13 @@ console.log(d.greeting); #### Risposta: A -In JavaScript, tutti gli oggetti interagiscono per _referenza_ . +In JavaScript, tutti gli oggetti interagiscono per _referenza_. -La variabile `c` contiene come valore un oggetto. Alla variabile `d` assegnamo come valore il riferimento di `c` che quindi contiene l'oggetto (e non un suo clone). +La variabile `c` contiene come valore un oggetto. Alla variabile `d` assegniamo come valore il riferimento di `c` che quindi contiene l'oggetto (e non un suo clone). -Quando modifichi il valore di questo oggetto, lo stai modificando sia per c che per d che contiene il suo riferimento. +Quando modifichi il valore di questo oggetto, lo stai modificando sia per `c`che per `d`, che contiene il suo riferimento.

@@ -269,7 +269,7 @@ console.log(b === c); `new Number()` è una funzione costruttore integrata. Nonostante sembri un numero, in realtà non lo è, si tratta infatti di un oggetto con un sacco di funzioni extra. -Quando utilizziamo l'operatore `==`, stiamo verificando solo se il suo _valore_ è uguale . Entrambe le variabili hanno il valore di `3`, quindi il primo log restituisce `true`. +Quando utilizziamo l'operatore `==`, stiamo verificando solo se il suo _valore_ è uguale. Entrambe le variabili hanno il valore di `3`, quindi il primo log restituisce `true`. Quando invece utilizziamo l'operatore `===`, stiamo verificando che sia il valore che il tipo di valore siano uguali. `new Number()` non è un numero, è un **oggetto** quindi entrambi i log restituiscono `false`. @@ -306,8 +306,6 @@ console.log(freddie.colorChange('orange')); #### Risposta: D -The `colorChange` function is static. Static methods are designed to live only on the constructor in which they are created, and cannot be passed down to any children or called upon class instances. Since `freddie` is an instance of class Chameleon, the function cannot be called upon it. A `TypeError` is thrown. - La funzione `colorChange` è statica. I metodi statici sono progettati per vivere solo nel costruttore in cui vengono creati e non possono essere passati a nessun figlio o richiamati su istanze di classe. Poiché `freddie` è un'istanza della classe `Chameleon`, la funzione non può essere chiamata su di essa. Viene restituito quindi un errore di tipo `TypeError`.

@@ -332,7 +330,8 @@ console.log(greetign); #### Risposta: A -Il nostro log restituisce un oggetto perchè abbiamo appena creato un oggetto vuoto come oggetto globale nel momento in cui per errore abbiamo digitato `greetign` al posto di `greeting`. +Il nostro log restituisce un oggetto perché abbiamo appena creato un oggetto vuoto come oggetto globale nel momento in cui per errore abbiamo digitato `greetign` al posto di `greeting`. + Il nostro interprete a quel punto ha letto `global.greetign = {}` (o `window.greetign = {}` se parliamo di un browser). Per evitare ciò, possiamo usare `"use strict"`. Questo assicura di aver dichiarato una variabile prima di impostarla uguale a qualsiasi cosa. @@ -362,7 +361,7 @@ bark.animal = 'dog'; #### Risposta: A -In Javasript non succede nulla, perché le funzioni sono oggetti! (Tutto tranne i tipi primitivi sono oggetti) +In Javascript non succede nulla, perché le funzioni sono oggetti! (Tutto tranne i tipi primitivi sono oggetti). Una funzione è un tipo speciale di oggetto. Il codice che scrivi non è la funzione effettiva. La funzione è un oggetto con delle proprietà e quindi questa proprietà è invocabile. @@ -440,7 +439,7 @@ console.log(sarah); Per la const `sarah`, non abbiamo usato la chiave `new`. Quando si usa `new`, `this` si riferisce al nuovo oggetto vuoto che creiamo. Tuttavia, se non aggiungiamo `new`, `this` si riferisce all'**oggetto globale**! -Abbiamo quindi scritto che `this.firstName` equivale a `"Sarah"` e `this.lastName` equivale a `"Smith"`. Quello che abbiamo effettivamente fatto è definire `global.firstName = 'Sarah'` e `global.lastName = 'Smith'`. la const `sarah` viene lasciata come `non definita`, perchè non restituiamo un valore dalla funzione `Persona`. +Abbiamo quindi scritto che `this.firstName` equivale a `"Sarah"` e `this.lastName` equivale a `"Smith"`. Quello che abbiamo effettivamente fatto è definire `global.firstName = 'Sarah'` e `global.lastName = 'Smith'`. La `const` `sarah` viene lasciata come `non definita`, perché non restituiamo un valore dalla funzione `Persona`.

@@ -478,7 +477,7 @@ Durante la fase di **capturing**, l'evento passa attraverso gli elementi predece #### Risposta: B -Tutti gli oggetti hanno prototipi, ad eccezione dell'**oggetto base**. L'oggetto base è l'oggetto creato dall'utente, o un oggetto creato usando la parola chiave `new`. L'oggetto base ha accesso ad alcuni metodi e proprietà, come `.toString`. Questo è il motivo per cui puoi utilizzare i metodi JavaScript built-in! Tutti questi metodi sono disponibili sul prototype. Quindi, anche se JavaScript non riesca a trovarlo direttamente sul tuo oggetto, scende lungo la chain del prototype e lo trova lì, il che lo rende accessibile anche per l'oggetto creato da te. +Tutti gli oggetti hanno prototipi, ad eccezione dell'**oggetto base**. L'oggetto base è l'oggetto creato dall'utente, o un oggetto creato usando la parola chiave `new`. L'oggetto base ha accesso ad alcuni metodi e proprietà, come `.toString`. Questo è il motivo per cui puoi utilizzare i metodi JavaScript built-in! Tutti questi metodi sono disponibili sul prototype. Quindi, anche se JavaScript non riesce a trovarlo direttamente sul tuo oggetto, scende lungo la chain del prototype e lo trova lì, il che lo rende accessibile anche per l'oggetto creato da te.

@@ -505,7 +504,7 @@ sum(1, '2'); #### Risposta: C -JavaScript è un **linguaggio tipizzato dinamicamente**: non specifichiamo quali tipi siano determinate variabili. I valori possono essere automaticamente convertiti in un altro tipo, questa azione è chiamato _coercizione implicita del tipo_. **Coercizione** è la conversione da un tipo all'altro. +JavaScript è un **linguaggio tipizzato dinamicamente**: non specifichiamo quali tipi siano determinate variabili. I valori possono essere automaticamente convertiti in un altro tipo, questa azione è chiamata _coercizione implicita del tipo_. **Coercizione** è la conversione da un tipo all'altro. In questo esempio, JavaScript converte il numero `1` in una stringa, in modo che la funzione abbia un senso e restituisca un valore. Durante l'aggiunta di un tipo numerico (`1`) e di un tipo stringa (`'2'`), il numero viene trattato come una stringa. Possiamo concatenare stringhe come `"Hello" + "World"`, quindi quello che sta succedendo qui è `"1" + "2"` che restituisce `"12"`. @@ -606,7 +605,7 @@ checkAge({ age: 18 }); #### Risposta: C -Quando si verifica l'uguaglianza, i primitivi vengono confrontate in base al loro _valore_, mentre gli oggetti vengono confrontati in base al loro _riferimento_. JavaScript controlla se gli oggetti hanno un riferimento alla stessa posizione in memoria. +Quando si verifica l'uguaglianza, i primitivi vengono confrontati in base al loro _valore_, mentre gli oggetti vengono confrontati in base al loro _riferimento_. JavaScript controlla se gli oggetti hanno un riferimento alla stessa posizione in memoria. I due oggetti che stiamo confrontando non lo hanno: l'oggetto che abbiamo passato come parametro si riferisce a una posizione di memoria diversa rispetto all'oggetto che abbiamo usato per verificare l'uguaglianza. From c3b0cbaf1215b803fc25b2366eb1b9ba32eb9d18 Mon Sep 17 00:00:00 2001 From: Filippo Bristot Date: Sun, 14 Aug 2022 13:22:15 +0200 Subject: [PATCH 111/193] fix typos in README-IT questions 20-39 --- it-IT/README-IT.md | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/it-IT/README-IT.md b/it-IT/README-IT.md index 8eaa75dd..1ac12b2a 100644 --- a/it-IT/README-IT.md +++ b/it-IT/README-IT.md @@ -665,7 +665,7 @@ getAge(); #### Risposta: C -Con `"use strict"`, puoi assicurarti di non dichiarare variabili globali per sbaglio. In questo caso la variabile `age` non è mai stata dichiarata, e siccome usiamo `"use strict"`, genererà un `ReferenceError`. Se non avessimo usato `"use strict"`, avrebbe funzionato perchè la proprietà `age` sarebbe stata aggiunta all'oggetto globale. +Con `"use strict"`, puoi assicurarti di non dichiarare variabili globali per sbaglio. In questo caso la variabile `age` non è mai stata dichiarata, e siccome usiamo `"use strict"`, genererà un `ReferenceError`. Se non avessimo usato `"use strict"`, avrebbe funzionato perché la proprietà `age` sarebbe stata aggiunta all'oggetto globale.

@@ -704,7 +704,7 @@ sessionStorage.setItem('cool_secret', 123); - A: Per sempre, i dati non vanno persi. - B: Fin quando l'utente chiude la scheda. - C: Fin quando l'utente chiude l'intero browser, non solo la scheda. -- D: Finquando l'utente spegne il proprio computer. +- D: Fin quando l'utente spegne il proprio computer.
Risposta

@@ -976,17 +976,17 @@ La WebAPI non può semplicemente aggiungere elementi allo stack ogni volta che ``` -- A: Outer `div` -- B: Inner `div` +- A: `div` esterno +- B: `div` interno - C: `button` -- D: An array of all nested elements. +- D: Un array di tutti gli elementi nidificati

Risposta

#### Risposta: C -L'elemento annidato più in profondità è quello che ha causato l'evento ed è quindi l' event.target. Puoi stoppare la propagazione con `event.stopPropagation` +L'elemento annidato più in profondità è quello che ha causato l'evento ed è quindi l'event.target. Puoi stoppare la propagazione con `event.stopPropagation`

@@ -1201,7 +1201,7 @@ a seconda di dove lo esegui (è diverso per ogni browser, node, ecc.) Il blocco `catch` riceve l'argomento `x` ma non è la stessa `x` della variabile, bensì passiamo un argomento della funzione. Questa "variabile" `x` è block-scoped quindi ha un ambito di blocco. -Subito dopo impostiamo il valore di variabile block-scoped a "1" e impostiamo il valore della variabile "y". Ora facciamo un console.log della variabile block-scoped `x`, che è uguale a `1`. +Subito dopo impostiamo il valore di variabile block-scoped a `1` e impostiamo il valore della variabile `y`. Ora facciamo un console.log della variabile block-scoped `x`, che è uguale a `1`. Fuori dal blocco `catch`, `x` è ancora `undefined` e `y` è `2` quindi quando facciamo `console.log(x)` al di fuori del blocco `catch`, otterremo `undefined` e `y` restituirà `2`. @@ -1214,7 +1214,7 @@ Fuori dal blocco `catch`, `x` è ancora `undefined` e `y` è `2` quindi quando f - A: o un primitivo o un oggetto - B: o una funzione o un oggetto -- C: Questa è unadomanda trabocchetto! Sono solo oggetti +- C: Questa è una domanda trabocchetto! Sono solo oggetti - D: un numero o un oggetto
Risposta @@ -1226,7 +1226,7 @@ JavaScript ha solo tipi primitivi e oggetti. I tipi primitivi sono `boolean`, `null`, `undefined`, `bigint`, `number`, `string` e `symbol`. -Ciò che differenzia un tipo primitivo da un oggetto è che i primitivi non hanno proprietà o metodi. Tuttavia, noterai che `'foo'.toUpperCase()` restituisce `'FOO'` e non genera un `TypeError`. Questo perché quando si tenta di accedere a una proprietà o a un metodo su di un tipo primitivo come lo è una stringa, JavaScript racchiuderà implicitamente il tipo primitivo utilizzando una delle classi wrapper, ovvero "String", valuterà l'espressione ed eliminerà il weapper una volta terminato. Tutti i primitivi tranne `null` e `undefined` subiscono questo comportamento. +Ciò che differenzia un tipo primitivo da un oggetto è che i primitivi non hanno proprietà o metodi. Tuttavia, noterai che `'foo'.toUpperCase()` restituisce `'FOO'` e non genera un `TypeError`. Questo perché quando si tenta di accedere a una proprietà o a un metodo su di un tipo primitivo come lo è una stringa, JavaScript racchiuderà implicitamente il tipo primitivo utilizzando una delle classi wrapper, ovvero "String", valuterà l'espressione ed eliminerà il wrapper una volta terminato. Tutti i primitivi tranne `null` e `undefined` subiscono questo comportamento.

From 94cd196269d6c09a3d1b0dd623618bee3c7d1959 Mon Sep 17 00:00:00 2001 From: Filippo Bristot Date: Sun, 14 Aug 2022 13:48:26 +0200 Subject: [PATCH 112/193] fix typos in README-IT questions 48, 57 --- it-IT/README-IT.md | 9 +-------- 1 file changed, 1 insertion(+), 8 deletions(-) diff --git a/it-IT/README-IT.md b/it-IT/README-IT.md index 1ac12b2a..021e8dda 100644 --- a/it-IT/README-IT.md +++ b/it-IT/README-IT.md @@ -1488,13 +1488,6 @@ console.log(3 + 4 + '5'); #### Risposta: B -Operator associativity is the order in which the compiler evaluates the expressions, either left-to-right or right-to-left. This only happens if all operators have the _same_ precedence. We only have one type of operator: `+`. For addition, the associativity is left-to-right. - -`3 + 4` gets evaluated first. This results in the number `7`. - -`7 + '5'` results in `"75"` because of coercion. JavaScript converts the number `7` into a string, see question 15. We can concatenate two strings using the `+`operator. `"7" + "5"` results in `"75"`. - - L'associazione è l'ordine in cui il compilatore valuta le espressioni, da sinistra a destra o da destra a sinistra. Questo accade solo se tutti gli operatori hanno la _stessa_ precedenza. Abbiamo solo un tipo di operatore: `+`. Inoltre, l'associazione è da sinistra a destra. `3 + 4` viene valutato per primo. E risulta nell'addizione dei due valori che restituiscono quindi `7`. @@ -1798,7 +1791,7 @@ console.log(myCounter); Un modulo importato è di _sola lettura_: non è quindi possibile modificare il modulo importato. Solo il modulo che li esporta può cambiarne il valore. -Quando proviamo ad incrementare il valore di `myCounter`, viene generato un errore: perchè `myCounter` è di sola lettura e non può essere modificato. +Quando proviamo ad incrementare il valore di `myCounter`, viene generato un errore: perché `myCounter` è di sola lettura e non può essere modificato.

From a1faf6565cf9d2f47a26f348ccadd23e33d5b139 Mon Sep 17 00:00:00 2001 From: Filippo Bristot Date: Sun, 14 Aug 2022 14:30:39 +0200 Subject: [PATCH 113/193] fix typos in README-IT questions 70-99 --- it-IT/README-IT.md | 33 ++++++++++++--------------------- 1 file changed, 12 insertions(+), 21 deletions(-) diff --git a/it-IT/README-IT.md b/it-IT/README-IT.md index 021e8dda..2ebb5f3b 100644 --- a/it-IT/README-IT.md +++ b/it-IT/README-IT.md @@ -2210,8 +2210,8 @@ console.log('🥑' + '💻'); - A: `"🥑💻"` - B: `257548` -- C: A string containing their code points -- D: Error +- C: Una stringa contenente i code points +- D: Errore
Risposta

@@ -2318,16 +2318,7 @@ console.log(data); #### Risposta: C -An async function always returns a promise. The `await` still has to wait for the promise to resolve: a pending promise gets returned when we call `getData()` in order to set `data` equal to it. - -If we wanted to get access to the resolved value `"I made it"`, we could have used the `.then()` method on `data`: - -`data.then(res => console.log(res))` - -This would've logged `"I made it!"` - - -Una funzione asincrona restituisce sempre una promise. L'`await` deve ancora attendere che la promise si risolva: una promise in sospeso viene restituita quando chiamiamo "getData()" per impostare "data" uguale ad essa. +Una funzione asincrona restituisce sempre una promise. L'`await` deve ancora attendere che la promise si risolva: una promise in sospeso viene restituita quando chiamiamo `getData()` per impostare `data` uguale ad essa. Se volessimo accedere al valore risolto `"I made it"`, potremmo usare il metodo `.then()` su `data`: @@ -2364,7 +2355,7 @@ console.log(result); Il metodo `.push()` restituisce la _lunghezza_ del nuovo array! Inizialmente, l'array conteneva un solo elemento (la stringa `"banana"`) e aveva una lunghezza di `1`. Dopo aver aggiunto la stringa `"apple"` allo stesso array, questo contiene due elementi e ha una lunghezza di `2` -Attravero la funzione `addToList`, il metodo `push` modifica l'array originale. +Attraverso la funzione `addToList`, il metodo `push` modifica l'array originale. Per restituire l'_array_ dalla funzione invece della _lunghezza dell'array_, serve fare un return di `list` dopo aver inserito l'`item`.

@@ -2497,7 +2488,7 @@ console.log(addFunction(5 * 2)); La funzione `add` è una funzione _memoizzata_. Con la memorizzazione, possiamo memorizzare nella cache i risultati di una funzione per velocizzarne l'esecuzione. In questo caso, creiamo un oggetto `cache` che memorizza i valori precedentemente restituiti. -Se chiamiamo di nuovo la funzione `addFunction` con lo stesso argomento, prima controlla se ha già ottenuto quel valore nella sua cache, in tal caso, verrà restituito il valore delle cache, il che consente di risparmiare tempo di esecuzione. Altrimenti, se non è memorizzato nella cache, calcolerà il valore e lo memorizzerà in seguito. +Se chiamiamo di nuovo la funzione `addFunction` con lo stesso argomento, prima controlla se ha già ottenuto quel valore nella sua cache, in tal caso, verrà restituito il valore della cache, consentendo di risparmiare tempo di esecuzione. Altrimenti, se non è memorizzato nella cache, calcolerà il valore e lo memorizzerà in seguito. Chiamiamo la funzione `addFunction` tre volte con lo stesso valore: alla prima chiamata, il valore della funzione quando `num` è uguale a `10` non è ancora memorizzato nella cache. La condizione dell'istruzione if `num in cache` restituisce `false`, e il blocco else viene eseguito: `Calculated! 20` viene loggato e il valore del risultato viene aggiunto all'oggetto cache. @@ -2536,7 +2527,7 @@ for (let item of myLifeSummedUp) { #### Risposta: A -Con un ciclo _for-in_, possiamo scorrere su proprietà **enumerabile**. In un array, le proprietà enumerabili sono le "chiavi" degli elementi dell'array, che sono in realtà i loro indici. Potresti immaginare un array come: +Con un ciclo _for-in_, possiamo scorrere su proprietà **enumerabili**. In un array, le proprietà enumerabili sono le "chiavi" degli elementi dell'array, che sono in realtà i loro indici. Potresti immaginare un array come: `{0: "☕", 1: "💻", 2: "🍷", 3: "🍫"}` @@ -2675,7 +2666,7 @@ Impostiamo la variabile `city` uguale al valore della proprietà chiamata `city` Nota che _non_ stiamo facendo riferimento all'oggetto `person`! Impostiamo semplicemente la variabile `city` uguale al valore corrente della proprietà `city` sull'oggetto `person`. -Quindi, impostiamo `city` uguale alla stringa `"Amsterdam"`. Questo non cambia l'oggetto person: non c'è alcun riferimento a quell'oggetto. +Quindi, impostiamo `city` uguale alla stringa `"Amsterdam"`. Questo non cambia l'oggetto `person`: non c'è alcun riferimento a quell'oggetto. Quando si logga l'oggetto `person`, viene restituito l'oggetto non modificato. @@ -2717,7 +2708,7 @@ Le variabili con la chiave `const` e `let` sono _block-scoped_. Un blocco è qua --- -###### 85. Che tipo di informazioni verrebbero registrate? +###### 85. Che tipo di informazioni verrebbero loggate? ```javascript fetch('https://www.website.com/api/user/1') @@ -2819,7 +2810,7 @@ sum(10); #### Risposta: B -È possibile impostare il valore di un parametro predefinito uguale a un altro parametro della funzione, purché siano stati definiti _prima_ del parametro predefinito. Passiamo il valore `10` alla funzione `sum`. Se la funzione `sum` riceve solo 1 argomento, significa che il valore di `num2` non è passato e il valore di `num1` è uguale al valore passato `10` in questo caso. Il valore predefinito di `num2` è il valore di `num1`, che è `10`. `num1 + num2` restituisce `20`. +È possibile impostare il valore di un parametro predefinito uguale a un altro parametro della funzione, purché sia stato definito _prima_ del parametro predefinito. Passiamo il valore `10` alla funzione `sum`. Se la funzione `sum` riceve solo 1 argomento, significa che il valore di `num2` non è passato e il valore di `num1` è uguale al valore passato `10` in questo caso. Il valore predefinito di `num2` è il valore di `num1`, che è `10`. `num1 + num2` restituisce `20`. Se stai cercando di impostare il valore di un parametro predefinito uguale a un parametro che è definito _dopo_ (a destra), il valore del parametro non è stato ancora inizializzato, il che genererà un errore.

@@ -3052,10 +3043,10 @@ console.log(nums(1, 2)); #### Risposta: B -In JavaScript, non _è necessario_ scrivere il punto e virgola (`;`) in modo esplicito poichè il motore JavaScript li aggiunge comunque dopo le istruzioni. +In JavaScript, non _è necessario_ scrivere il punto e virgola (`;`) in modo esplicito poiché il motore JavaScript li aggiunge comunque dopo le istruzioni. Questo procedimento è chiamato **Automatic Semicolon Insertion**. Un'istruzione può ad esempio essere una variabile o parole chiave come `throw`, `return`, `break`, ecc. -Qui, abbiamo scritto un'istruzione di `return` e un altro valore `a + b` su una _nuova riga_. Tuttavia, trattandosi di una nuova linea, il motore non sa che in realtà è il valore che volevamo restituire. Invece, ha aggiunto automaticamente un punto e virgola dopo "return". +Qui, abbiamo scritto un'istruzione di `return` e un altro valore `a + b` su una _nuova riga_. Tuttavia, trattandosi di una nuova linea, il motore non sa che in realtà è il valore che volevamo restituire. Invece, ha aggiunto automaticamente un punto e virgola dopo `return`. Potresti considerare ad esempio: @@ -3168,7 +3159,7 @@ La funzione `getList` riceve un array come argomento. Tra le parentesi della fun Con il parametro rest `...y`, mettiamo tutti gli argomenti "rimanenti" in un array. Gli argomenti rimanenti sono `2`, `3` e `4` in questo caso. Il valore di `y` è un array, contenente tutti i parametri rimanenti. Il valore di `x` è uguale a `1` in questo caso, quindi quando facciamo un console.log di `[x, y]`, viene loggato `[1, [2, 3, 4]]`. -La funzione `getUser` riceve un oggetto. Con le arrow functions, non _è necessario_ scrivere parentesi graffe se restituiamo solo un valore. Tuttavia, se vuoi restituire istantaneamente un _oggetto_ da una arrow function, devi scriverlo tra parentesi, altrimenti tutto ciò che si trova tra le due parentesi verrà interpretato come un'istruzione di blocco. In questo caso il codice tra parentesi non è un codice JavaScript valido, quindi viene generato un `SyntaxError`. +La funzione `getUser` riceve un oggetto. Con le arrow functions, non _è necessario_ scrivere parentesi graffe se restituiamo solo un valore. Tuttavia, se vuoi restituire istantaneamente un _oggetto_ da una arrow function, devi scriverlo tra parentesi tonde, altrimenti tutto ciò che si trova tra le due parentesi graffe verrà interpretato come un'istruzione di blocco. In questo caso il codice tra parentesi non è un codice JavaScript valido, quindi viene generato un `SyntaxError`. La seguente funzione avrebbe restituito un oggetto: From 522171a55e2825eb5cd979577fe57e3b1d5cabb8 Mon Sep 17 00:00:00 2001 From: Filippo Bristot Date: Sun, 14 Aug 2022 15:27:15 +0200 Subject: [PATCH 114/193] fix typos in README-IT questions 100-155 --- it-IT/README-IT.md | 22 ++++++++++------------ 1 file changed, 10 insertions(+), 12 deletions(-) diff --git a/it-IT/README-IT.md b/it-IT/README-IT.md index 2ebb5f3b..98ac7137 100644 --- a/it-IT/README-IT.md +++ b/it-IT/README-IT.md @@ -3292,7 +3292,7 @@ secondFunction(); Con una promise, in pratica diciamo _Voglio eseguire questa funzione, ma per ora la metto da parte mentre è in esecuzione poiché ciò potrebbe richiedere del tempo. Solo quando un determinato valore viene risolto (o rifiutato) e quando lo stack di chiamate è vuoto, voglio utilizzare questo valore._ -Possiamo ottenere questo valore sia con `.then` che con la chiave `await` in una funzione `async`. Sebbene possiamo ottenere il valore di una promessa sia con `.then` che con `await`, funzionano in modo leggermente diverso. +Possiamo ottenere questo valore sia con `.then` che con la chiave `await` in una funzione `async`. Sebbene possiamo ottenere il valore di una promise sia con `.then` che con `await`, funzionano in modo leggermente diverso. Nella `first Function`, abbiamo (più o meno) messo da parte la funzione myPromise mentre era in esecuzione, ma abbiamo continuato a eseguire l'altro codice, che in questo caso è `console.log('second')`. Quindi, la funzione è stata risolta con la stringa `I have resolved`, che è stata quindi loggata dopo aver visto che lo stack di chiamate era vuoto. @@ -3518,7 +3518,7 @@ console.log(food); Impostiamo il valore della proprietà `favoriteFood` sull'oggetto `info` uguale alla stringa con l'emoji della pizza, `'🍕'`. Una stringa è un tipo di dati primitivo. In JavaScript, i tipi di dati primitivi non interagiscono per riferimento. -In JavaScript, i tipi di dati primitivi (tutto ciò che non è un oggetto) interagiscono per _value_. In questo caso, impostiamo il valore della proprietà `favoriteFood` sull'oggetto `info` uguale al valore del primo elemento nell'array `food`, in questo caso la stringa con l'emoji della pizza (`'🍕'`). Una stringa è un tipo di dati primitivo e interagisce per valore (vedi il mio [blogpost](https://www.theavocoder.com/complete-javascript/2018/12/21/by-value-vs-by-reference) se sei interessato a saperne di più) +In JavaScript, i tipi di dati primitivi (tutto ciò che non è un oggetto) interagiscono per _value_. In questo caso, impostiamo il valore della proprietà `favoriteFood` sull'oggetto `info` uguale al valore del primo elemento nell'array `food`, in questo caso la stringa con l'emoji della pizza (`'🍕'`). Una stringa è un tipo di dati primitivo e interagisce per valore (vedi il mio [blogpost](https://www.theavocoder.com/complete-javascript/2018/12/21/by-value-vs-by-reference) se sei interessato a saperne di più). Quindi, cambiamo il valore della proprietà `favoriteFood` sull'oggetto `info`. L'array `food` non è cambiato, poiché il valore di `favoriteFood` era semplicemente una _copia_ del valore del primo elemento nell'array e non ha un riferimento allo stesso punto in memoria dell'elemento su ` food[0]`. Quando logghiamo food, è ancora l'array originale, `['🍕', '🍫', '🥑', '🍔']`.

@@ -3586,7 +3586,7 @@ getName(); #### Risposta: D -Ogni funzione ha il proprio _contesto di esecuzione_ (o _ambito_). La funzione `getName` cerca prima all'interno del proprio contesto (scope) per vedere se contiene la variabile `name` a cui stiamo cercando di accedere. In questo caso, la funzione `getName` contiene la propria variabile `name` perchè dichiariamo la variabile `name` con la chiave `let`, e con il valore di `'Sarah'`. +Ogni funzione ha il proprio _contesto di esecuzione_ (o _ambito_). La funzione `getName` cerca prima all'interno del proprio contesto (scope) per vedere se contiene la variabile `name` a cui stiamo cercando di accedere. In questo caso, la funzione `getName` contiene la propria variabile `name` perché dichiariamo la variabile `name` con la chiave `let`, e con il valore di `'Sarah'`. Le variabili con la chiave `let` (e `const`) vengono sollevate, ma a differenza di `var`, non vengono inizializzate. Non sono quindi accessibili prima della riga in cui le dichiariamo (inizializziamo). Questa è chiamata "temporal dead zone". Quando proviamo ad accedere alle variabili prima che vengano dichiarate, JavaScript genera un `ReferenceError`. @@ -3703,7 +3703,7 @@ config = null; #### Risposta: C -Normalmente quando impostiamo oggetti uguali a `null`, quegli oggetti ottengono _garbage collected_ poiché non c'è più alcun riferimento a quell'oggetto. Tuttavia, poiché la funzione di callback all'interno di `setInterval` è una funzione freccia (quindi legata all'oggetto `config`), la funzione di callback mantiene ancora un riferimento all'oggetto `config`. +Normalmente quando impostiamo oggetti uguali a `null`, quegli oggetti vengono _garbage collected_ poiché non c'è più alcun riferimento a quell'oggetto. Tuttavia, poiché la funzione di callback all'interno di `setInterval` è una funzione freccia (quindi legata all'oggetto `config`), la funzione di callback mantiene ancora un riferimento all'oggetto `config`. Finché c'è un riferimento, l'oggetto non verrà raccolto. Poiché si tratta di un intervallo, impostare `config` su `null` o `delete`-ing `config.alert` non raccoglierà l'intervallo, quindi l'intervallo verrà comunque chiamato. Dovrebbe essere cancellato con `clearInterval(config.alert)` per rimuoverlo dalla memoria. @@ -4116,8 +4116,6 @@ console.log(spookyItems); #### Risposta: B -By destructuring objects, we can unpack values from the right-hand object, and assign the unpacked value to the value of the same property name on the left-hand object. In this case, we're assigning the value "💀" to `spookyItems[3]`. This means that we're modifying the `spookyItems` array, we're adding the "💀" to it. When logging `spookyItems`, `["👻", "🎃", "🕸", "💀"]` gets logged. - Destrutturando gli oggetti, possiamo decomprimere i valori dall'oggetto di destra e assegnare il valore decompresso al valore dello stesso nome di proprietà sull'oggetto di sinistra. In questo caso, stiamo assegnando il valore "💀" a `spookyItems[3]`. Ciò significa che stiamo modificando l'array `spookyItems`, stiamo aggiungendo il "💀" ad esso. Quando facciamo console.log di `spookyItems`, `["👻", "🎃", "🕸", "💀"]` viene loggato.

@@ -4322,7 +4320,7 @@ funcTwo(); #### Risposta: C -Innanzitutto, invochiamo `funcOne`. Sulla prima riga di `funcOne`, chiamiamo la funzione _asincrona_ `setTimeout`, da cui la callback viene inviato all'API Web. (vedi l'articolo sul ciclo degli eventi qui.) +Innanzitutto, invochiamo `funcOne`. Sulla prima riga di `funcOne`, chiamiamo la funzione _asincrona_ `setTimeout`, da cui la callback viene inviato all'API Web. (vedi l'articolo sul ciclo degli eventi [qui](https://dev.to/lydiahallie/javascript-visualized-event-loop-3dif)) Quindi chiamiamo la promise `myPromise`, che è un'operazione _asincrona_. @@ -4330,9 +4328,9 @@ Sia la promise che il timeout sono operazioni asincrone, la funzione continua a Poiché la callstack non è ancora vuota, la funzione `setTimeout` e la promise in `funcOne` non possono ancora essere aggiunte al callstack. -In `funcTwo`, la variabile `res` ottiene `Promise` perché `Promise.resolve(Promise.resolve('Promise'))` è equivalente a `Promise.resolve('Promise')` poiché risolvere una promise risolve semplicemente che è valore. L'"attesa" in questa riga interrompe l'esecuzione della funzione fino a quando non riceve la risoluzione della promise e quindi continua a funzionare in modo sincrono fino al completamento, quindi `Promise 2!` e poi `Last line 2!` vengono registrati e "setTimeout ` viene inviato all'API Web. +In `funcTwo`, la variabile `res` ottiene `Promise` perché `Promise.resolve(Promise.resolve('Promise'))` è equivalente a `Promise.resolve('Promise')` poiché risolvere una promise risolve il suo valore. L'"attesa" in questa riga interrompe l'esecuzione della funzione fino a quando non riceve la risoluzione della promise e quindi continua a funzionare in modo sincrono fino al completamento, quindi `Promise 2!` e poi `Last line 2!` vengono registrati e `setTimeout` viene inviato all'API Web. -Quindi lo stack di chiamate è vuoto. Le promise sono _microattività_ quindi vengono risolte per prime quando lo stack di chiamate è vuoto, quindi `Promise 1!` viene registrato. +Quindi lo stack di chiamate è vuoto. Le promise sono _microattività_, quindi vengono risolte per prime quando lo stack di chiamate è vuoto, quindi `Promise 1!` viene registrato. Ora, da quando `funcTwo` è uscito dallo stack delle chiamate, lo stack delle chiamate è vuoto. Le callback in attesa nella coda (`() => console.log("Timeout 1!")` da `funcOne`, e `() => console.log("Timeout 2!")` da `funcTwo`) vengono aggiunti allo stack di chiamate uno per uno. Il primo callback registra `Timeout 1!` e viene eliminato dallo stack. Quindi, il secondo callback registra `Timeout 2!` e viene eliminato dallo stack.

@@ -4883,7 +4881,7 @@ console.log(updatedUser === user) #### Risposta: B -La funzione `updateUser` aggiorna i valori delle proprietà `email` e `password` sull'utente se i loro valori vengono passati alla funzione, dopodiché la funzione restituisce l'oggetto `user`. Il valore restituito dalla funzione `updateUser` è l'oggetto `user`, il che significa che il valore di updateUser è un riferimento allo stesso oggetto `user` a cui punta `user`. `updatedUser === user` è uguale a `true`. +La funzione `updateUser` aggiorna i valori delle proprietà `email` e `password` sull'utente se i loro valori vengono passati alla funzione, dopodiché la funzione restituisce l'oggetto `user`. Il valore restituito dalla funzione `updateUser` è l'oggetto `user`, il che significa che il valore di `updateUser` è un riferimento allo stesso oggetto `user` a cui punta `user`. `updatedUser === user` è uguale a `true`.

@@ -5018,7 +5016,7 @@ runPromises() #### Risposta: D -Il metodo `Promise.all` esegue le promise passate in parallelo. Se una promise fallisce, il metodo `Promise.all` effettua un _rejects_ con il valore della prmise rifiutata. In questo caso, `promise3` ha rifiutato con il valore `"Third"`. Stiamo rilevando il valore rifiutato nel metodo `catch` concatenato sulla chiamata `runPromises` per rilevare eventuali errori all'interno della funzione `runPromises`. Solo `"Third"` viene registrato, poiché `promise3` viene rifiutato con questo valore. +Il metodo `Promise.all` esegue le promise passate in parallelo. Se una promise fallisce, il metodo `Promise.all` effettua un _rejects_ con il valore della promise rifiutata. In questo caso, `promise3` ha rifiutato con il valore `"Third"`. Stiamo rilevando il valore rifiutato nel metodo `catch` concatenato sulla chiamata `runPromises` per rilevare eventuali errori all'interno della funzione `runPromises`. Solo `"Third"` viene registrato, poiché `promise3` viene rifiutato con questo valore.

@@ -5083,7 +5081,7 @@ console.log(member) #### Risposta: C -Il valore predefinito di `address` è un oggetto vuoto `{}`. Quando abbiamo impostato la variabile `member` uguale all'oggetto restituito dalla funzione `createMember`, non abbiamo passato un valore per address, il che significa che il valore di address è l'oggetto vuoto predefinito `{}`. Un oggetto vuoto è un valore veritiero, il che significa che la condizione `address ? address : null` restituisce `true`. Il valore di address è l'oggetto vuoto `{}`. +Il valore predefinito di `address` è un oggetto vuoto `{}`. Quando abbiamo impostato la variabile `member` uguale all'oggetto restituito dalla funzione `createMember`, non abbiamo passato un valore per `address`, il che significa che il valore di `address` è l'oggetto vuoto predefinito `{}`. Un oggetto vuoto è un valore veritiero, il che significa che la condizione `address ? address : null` restituisce `true`. Il valore di `address` è l'oggetto vuoto `{}`.

From 762fc3ea2d42caa7843b486ad5219d917d4a6c59 Mon Sep 17 00:00:00 2001 From: Filippo Bristot Date: Sun, 14 Aug 2022 15:29:54 +0200 Subject: [PATCH 115/193] Javascript -> JavaScript --- it-IT/README-IT.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/it-IT/README-IT.md b/it-IT/README-IT.md index 98ac7137..987bd117 100644 --- a/it-IT/README-IT.md +++ b/it-IT/README-IT.md @@ -203,7 +203,7 @@ JavaScript interpreta le istruzioni, quindi quando usiamo la bracket notation, v Quando in JavaScript richiamiamo `mouse[bird.size]`: per prima cosa viene valorizzato `bird.size`, che è `"small"`, per JS viene tradotto quindi come `mouse["small"]` che restituisce `true`. -Con l'utilizzo del punto questo non accade perché `mouse` non ha una chiave chiamata `bird`, e questo significa che `mouse.bird` è `undefined`. Per Javascript quindi l'istruzione `mouse.bird.size` viene tradotta con `mouse.undefined.size` che è un valore non valido e che quindi genererà un errore simile a `Cannot read property "size" of undefined`. +Con l'utilizzo del punto questo non accade perché `mouse` non ha una chiave chiamata `bird`, e questo significa che `mouse.bird` è `undefined`. Per JavaScript quindi l'istruzione `mouse.bird.size` viene tradotta con `mouse.undefined.size` che è un valore non valido e che quindi genererà un errore simile a `Cannot read property "size" of undefined`.

@@ -361,7 +361,7 @@ bark.animal = 'dog'; #### Risposta: A -In Javascript non succede nulla, perché le funzioni sono oggetti! (Tutto tranne i tipi primitivi sono oggetti). +In JavaScript non succede nulla, perché le funzioni sono oggetti! (Tutto tranne i tipi primitivi sono oggetti). Una funzione è un tipo speciale di oggetto. Il codice che scrivi non è la funzione effettiva. La funzione è un oggetto con delle proprietà e quindi questa proprietà è invocabile. @@ -3590,7 +3590,7 @@ Ogni funzione ha il proprio _contesto di esecuzione_ (o _ambito_). La funzione ` Le variabili con la chiave `let` (e `const`) vengono sollevate, ma a differenza di `var`, non vengono inizializzate. Non sono quindi accessibili prima della riga in cui le dichiariamo (inizializziamo). Questa è chiamata "temporal dead zone". Quando proviamo ad accedere alle variabili prima che vengano dichiarate, JavaScript genera un `ReferenceError`. -Se non avessimo dichiarato la variabile `name` all'interno della funzione `getName`, javascript avrebbe esaminato la _scope chain_. Lo scope esterno ha una variabile chiamata `name` con il valore di `Lydia`. In tal caso, avrebbe loggato "Lydia". +Se non avessimo dichiarato la variabile `name` all'interno della funzione `getName`, JavaScript avrebbe esaminato la _scope chain_. Lo scope esterno ha una variabile chiamata `name` con il valore di `Lydia`. In tal caso, avrebbe loggato "Lydia". ```javascript let name = 'Lydia'; From 2cf783371c62059629ebf2e0f195d5b3ff9bd441 Mon Sep 17 00:00:00 2001 From: cherednichenko Date: Sun, 14 Aug 2022 20:19:23 +0300 Subject: [PATCH 116/193] uk-UA. Add questions 44-46. Fix typos --- uk-UA/README.md | 128 +++++++++++++++++++++++++++++++++++++++++++----- 1 file changed, 117 insertions(+), 11 deletions(-) diff --git a/uk-UA/README.md b/uk-UA/README.md index e4b77264..4908e114 100644 --- a/uk-UA/README.md +++ b/uk-UA/README.md @@ -83,7 +83,7 @@ for (let i = 0; i < 3; i++) { Через черги подій в JavaScript, функція `setTimeout` викликається _після того_ як цикл буде завершено. Так як змінна `i` в першому циклі була визначена за допомогою `var`, вона буде глобальною. У циклі ми кожен раз збільшуємо значення `i` на `1`, використовуючи унарний оператор `++.` До моменту виконання функції `setTimeout` значення `i` дорівнюватиме `3`, як показано в першому прикладі. -У другому циклі змінна `i` визначена за допомогою `let`. Такі змінні (а також `const`) мають блочну область видимості (блок це що завгодно між `{}`). З кожною ітерацією `i` матиме нове значення, і кожне значення буде замкнуто в своїй області видимості всередині циклу. +У другому циклі змінна `i` визначена за допомогою `let`. Такі змінні (а також `const`) мають блокову область видимості (блок це що завгодно між `{}`). З кожною ітерацією `i` матиме нове значення, і кожне значення буде замкнуто у своїй області видимості всередині циклу.

@@ -422,10 +422,10 @@ console.log(sarah); ###### 13. Назвіть три фази поширення подій -- A: Мета (Target) > Захоплення (Capturing) > Всплиття (Bubbling) -- B: Всплиття (Bubbling) > Мета (Target) > Захоплення (Capturing) -- C: Мета (Target) > Всплиття (Bubbling) > Захоплення (Capturing) -- D: Захоплення (Capturing) > Мета (Target) > Всплиття (Bubbling) +- A: Мета (Target) > Захоплення (Capturing) > Спливання (Bubbling) +- B: Спливання (Bubbling) > Мета (Target) > Захоплення (Capturing) +- C: Мета (Target) > Спливання (Bubbling) > Захоплення (Capturing) +- D: Захоплення (Capturing) > Мета (Target) > Спливання (Bubbling)
Відповідь

@@ -478,7 +478,7 @@ sum(1, "2"); #### Відповідь: C -JavaScript це **динамічно тіпізірованна мова**: ми не визначаємо тип змінних. Змінні можуть автоматично бути перетворені з одного типу в інший без нашої участі, що називається _неявним приведенням типів_. **Приведення** це перетворення з одного типу в інший. +JavaScript це **динамічно типізована мова**: ми не визначаємо тип змінних. Змінні можуть автоматично бути перетворені з одного типу в інший без нашої участі, що називається _неявним приведенням типів_. **Приведення** це перетворення з одного типу в інший. У цьому прикладі, JavaScript конвертувати число `1` в рядок, щоб операція всередині функції мала сенс і повернула значення. Під час складання числа (`1`) і рядки (`'2'`) число перетворюється до рядка. Ми можемо додавати рядки ось так: `"Hello" + "World"`. Таким чином, "`1"` + `"2"` повертає "`12"`. @@ -662,7 +662,7 @@ const sum = eval("10*10+5"); #### Відповідь: A -`eval` виконує код, переданий у вигляді рядка. Якщо це рядок (як в даному випадку), то обчислюється вираз. Вираз `10 * 10 + 5` поверне число `105`. +`eval` виконує код, переданий у вигляді рядка. Якщо це рядок (як в такому випадку), то обчислюється вираз. Вираз `10 * 10 + 5` поверне число `105`.

@@ -788,7 +788,7 @@ console.log(obj); #### Відповідь: A -Базовий контекст виконання це глобальний контекст виконання: це те, що є де завгодно в твоєму коді. +Базовий контекст виконання це глобальний контекст виконання: це те, що є де завгодно у твоєму коді.

@@ -1045,7 +1045,7 @@ typeof sayHi(); #### Відповідь: B -Функція `sayHi` повертає значення, що повертається з _негайно викликаного функціонального вираза_ (IIFE). Результатом є `0` типу `"number"`. +Функція `sayHi` повертає значення, що повертається з _негайно викликаного функціонального виразу_ (IIFE). Результатом є `0` типу `"number"`. Для інформації: в JS 7 вбудованих типів: `null`, `undefined`, `boolean`, `number`, `string`, `object`, `symbol`, та `bigint`. `"Function"` не є окремим типом, тому що функції є об'єктами типу `"object"`. @@ -1193,7 +1193,7 @@ console.log(numbers); #### Відповідь: A -В JavaScript є тільки примітиви і об'єкти. +В JavaScript є тільки примітиви й об'єкти. Типи примітивів: `boolean`, `null`, `undefined`, `bigint`, `number`, `string`, та `symbol`. @@ -1286,7 +1286,7 @@ setInterval(() => console.log("Hi"), 1000); --- -###### 43. What does this return? +###### 43. Що повернеться? ```javascript [..."Lydia"]; @@ -1306,3 +1306,109 @@ setInterval(() => console.log("Hi"), 1000);

+ +--- + +###### 44. Що буде в консолі? + +```javascript +function* generator(i) { + yield i; + yield i * 2; +} + +const gen = generator(10); + +console.log(gen.next().value); +console.log(gen.next().value); +``` + +- A: `[0, 10], [10, 20]` +- B: `20, 20` +- C: `10, 20` +- D: `0, 10 and 10, 20` + +
Answer +

+ +#### Відповідь: C + +Звичайні функції не можна зупинити "на півдорозі" після виклику. Однак функція-генератор може зупинитися "на півдорозі", а потім продовжити з того місця, де вона зупинилась. Кожного разу, коли функція-генератор зустрічає ключове слово `yield`, функція видає значення, що вказане після нього. Зауважте, що функція-генератор в цьому випадку не _повертає_ (return) значення, вона _дає_ (yields) значення. + +Спочатку ми ініціалізуємо функцію-генератор з `i` рівним `10`. Ми викликаємо функцію-генератор за допомогою методу `next()`. Коли ми вперше викликаємо функцію генератора, `i` дорівнює `10`. Перше ключове слово `yield`: воно дає значення `i`. Генератор тепер "призупинено", і `10` записується у консоль. + +Потім ми знову викликаємо функцію за допомогою методу `next()`. Виконання коду продовжується там, де зупинилося раніше, все ще з `i` що дорівнює `10`. Тепер функція зустрічає наступне ключове слово `yield` і дає `i * 2`. `i` дорівнює `10`, тож віддається `10 * 2`, що дорівнює `20`. У результаті: `10, 20`. + +

+
+ + +--- + +###### 45. Що повернеться? + +```javascript +const firstPromise = new Promise((res, rej) => { + setTimeout(res, 500, 'one'); +}); + +const secondPromise = new Promise((res, rej) => { + setTimeout(res, 100, 'two'); +}); + +Promise.race([firstPromise, secondPromise]).then(res => console.log(res)); +``` + +- A: `"one"` +- B: `"two"` +- C: `"two" "one"` +- D: `"one" "two"` + +
Answer +

+ +#### Відповідь: B + +Коли ми передаємо кілька промісів методу `Promise.race`, він вирішує/відхиляє _перший_ проміс, яки вирішився/відхилився. Методу `setTimeout` ми передаємо таймер: 500 мс для першого промісу (`firstPromise`) та 100 мс для другого промісу (`secondPromise`). Це означає, що `secondPromise` вирішиться першим зі значенням `'two'`. `res` тепер містить значення `'two'`, яке буде зображено у консолі. + +

+
+ +--- + +###### 46. Що буде на виході? + +```javascript +let person = { name: 'Lydia' }; +const members = [person]; +person = null; + +console.log(members); +``` + +- A: `null` +- B: `[null]` +- C: `[{}]` +- D: `[{ name: "Lydia" }]` + +
Answer +

+ +#### Відповідь: D + +Спочатку ми оголошуємо змінну `person` що містить об'єкта, який має властивість `name`. + + + +Потім ми оголошуємо змінну `members`. Ми встановлюємо перший елемент масиву рівним значенню змінної `person`. Об'єкти взаємодіють за допомогою _посилання_, коли їх встановлюють рівними один одному. Коли ви призначаєте посилання з однієї змінної на іншу, ви робите _копію_ цього посилання. (зверніть увагу, що вони не мають _однакового_ посилання!) + + + +Далі ми встановлюємо змінну `person` рівною `null`. + + + +Ми лише змінюємо значення змінної `person`, а не перший елемент у масиві, оскільки цей елемент має інше (скопійоване) посилання на об’єкт.Перший елемент у `members` все ще містить своє посилання на вихідний об’єкт. Коли ми виводимо у консоль масив `members`, перший елемент усе ще містить значення об'єкта, який і показується у консолі. + +

+
From 7efc8f6dfbe88263c48607b432e7b1dba1067d3e Mon Sep 17 00:00:00 2001 From: Emanuel Cascone Date: Sun, 21 Aug 2022 17:27:00 -0300 Subject: [PATCH 117/193] fix: path of others readme.md --- pt-BR/README_pt_BR.md | 36 ++++++++++++++++++------------------ 1 file changed, 18 insertions(+), 18 deletions(-) diff --git a/pt-BR/README_pt_BR.md b/pt-BR/README_pt_BR.md index 395dc496..7d95e500 100644 --- a/pt-BR/README_pt_BR.md +++ b/pt-BR/README_pt_BR.md @@ -6,25 +6,25 @@ Do básico ao avançado: Teste quão bem você conhece o JavaScript, refresque u As respostas estão em seções recolhidas abaixo das questões, basta clicar nelas para expandir. Boa sorte :heart: -- [🇸🇦 العربية](./ar-AR/README_AR.md) -- [🇪🇬 اللغة العامية](./ar-EG/README_ar-EG.md) -- [🇧🇦 Bosanski](./bs-BS/README-bs_BS.md) -- [🇩🇪 Deutsch](./de-DE/README.md) +- [🇸🇦 العربية](../ar-AR/README_AR.md) +- [🇪🇬 اللغة العامية](../ar-EG/README_ar-EG.md) +- [🇧🇦 Bosanski](../bs-BS/README-bs_BS.md) +- [🇩🇪 Deutsch](../de-DE/README.md) - [🇬🇧 English](../README.md) -- [🇪🇸 Español](./es-ES/README-ES.md) -- [🇫🇷 Français](./fr-FR/README_fr-FR.md) -- [🇮🇩 Indonesia](./id-ID/README.md) -- [🇮🇹 Italiano](./it-IT/README.md) -- [🇯🇵 日本語](./ja-JA/README-ja_JA.md) -- [🇰🇷 한국어](./ko-KR/README-ko_KR.md) -- [🇳🇱 Nederlands](./nl-NL/README.md) -- [🇷🇺 Русский](./ru-RU/README.md) -- [🇹🇭 ไทย](./th-TH/README-th_TH.md) -- [🇹🇷 Türkçe](./tr-TR/README-tr_TR.md) -- [🇺🇦 Українська мова](./uk-UA/README.md) -- [🇻🇳 Tiếng Việt](./vi-VI/README-vi.md) -- [🇨🇳 简体中文](./zh-CN/README-zh_CN.md) -- [🇹🇼 繁體中文](./zh-TW/README_zh-TW.md) +- [🇪🇸 Español](../es-ES/README-ES.md) +- [🇫🇷 Français](../fr-FR/README_fr-FR.md) +- [🇮🇩 Indonesia](../id-ID/README.md) +- [🇮🇹 Italiano](../it-IT/README.md) +- [🇯🇵 日本語](../ja-JA/README-ja_JA.md) +- [🇰🇷 한국어](../ko-KR/README-ko_KR.md) +- [🇳🇱 Nederlands](../nl-NL/README.md) +- [🇷🇺 Русский](../ru-RU/README.md) +- [🇹🇭 ไทย](../th-TH/README-th_TH.md) +- [🇹🇷 Türkçe](../tr-TR/README-tr_TR.md) +- [🇺🇦 Українська мова](../uk-UA/README.md) +- [🇻🇳 Tiếng Việt](../vi-VI/README-vi.md) +- [🇨🇳 简体中文](../zh-CN/README-zh_CN.md) +- [🇹🇼 繁體中文](../zh-TW/README_zh-TW.md) --- From 20b6e7713cc189931761f473e56d709f84c4e977 Mon Sep 17 00:00:00 2001 From: Emanuel Cascone Date: Sun, 21 Aug 2022 17:29:44 -0300 Subject: [PATCH 118/193] fix: portuguese translation text on question 39 --- pt-BR/README_pt_BR.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pt-BR/README_pt_BR.md b/pt-BR/README_pt_BR.md index 7d95e500..b035f8b3 100644 --- a/pt-BR/README_pt_BR.md +++ b/pt-BR/README_pt_BR.md @@ -1203,7 +1203,7 @@ JavaScript tem somente tipos primitivos e objetos. Tipos primitivos são `boolean`, `null`, `undefined`, `bigint`, `number`, `string`, e `symbol`. -O que diferencia um primitivo de um objeto é que primitivos não métodos ou propriedades. Contudo, se você está atento vai lembrar que `'foo'.toUpperCase()` retorna `'FOO'` e não resulta em um `TypeError`. Isso acontece pois quando você tenta acessar uma propriedade ou método em um primitivo como, por exemplo, uma string, JavaScript vai transformar esse primitivo em objeto usando um _wrapper_, nesse caso o `String`, e discarta o wrapper imediatamente após executar o método ou propriedade. Todos os primitivos, com exceção de `null` e `undefined` exibem esse comportamento. +O que diferencia um primitivo de um objeto é que primitivos não possuem métodos ou propriedades. Contudo, se você está atento vai lembrar que `'foo'.toUpperCase()` retorna `'FOO'` e não resulta em um `TypeError`. Isso acontece pois quando você tenta acessar uma propriedade ou método em um primitivo como, por exemplo, uma string, JavaScript vai transformar esse primitivo em objeto usando um _wrapper_, nesse caso o `String`, e discarta o wrapper imediatamente após executar o método ou propriedade. Todos os primitivos, com exceção de `null` e `undefined` exibem esse comportamento.

From c1e4effa144d551943e96dd8de2621ccff991fa9 Mon Sep 17 00:00:00 2001 From: Emanuel Cascone Date: Sun, 21 Aug 2022 17:35:47 -0300 Subject: [PATCH 119/193] fix: paths of languages --- ar-AR/README_AR.md | 36 ++++++++++++++++++------------------ bs-BS/README-bs_BS.md | 36 ++++++++++++++++++------------------ de-DE/README.md | 36 ++++++++++++++++++------------------ es-ES/README-ES.md | 36 ++++++++++++++++++------------------ fr-FR/README_fr-FR.md | 36 ++++++++++++++++++------------------ id-ID/README.md | 36 ++++++++++++++++++------------------ it-IT/README-IT.md | 36 ++++++++++++++++++------------------ ja-JA/README-ja_JA.md | 2 +- ko-KR/README-ko_KR.md | 36 ++++++++++++++++++------------------ nl-NL/README.md | 36 ++++++++++++++++++------------------ ru-RU/README.md | 36 ++++++++++++++++++------------------ th-TH/README.md | 36 ++++++++++++++++++------------------ tr-TR/README-tr_TR.md | 36 ++++++++++++++++++------------------ uk-UA/README.md | 36 ++++++++++++++++++------------------ vi-VI/README-vi.md | 36 ++++++++++++++++++------------------ 15 files changed, 253 insertions(+), 253 deletions(-) diff --git a/ar-AR/README_AR.md b/ar-AR/README_AR.md index ed9a9eac..72343215 100644 --- a/ar-AR/README_AR.md +++ b/ar-AR/README_AR.md @@ -14,25 +14,25 @@ اللغات المتوفرة: -- [🇪🇬 اللغة العامية](./ar-EG/README_ar-EG.md) -- [🇧🇦 Bosanski](./bs-BS/README-bs_BS.md) -- [🇩🇪 Deutsch](./de-DE/README.md) +- [🇪🇬 اللغة العامية](../ar-EG/README_ar-EG.md) +- [🇧🇦 Bosanski](../bs-BS/README-bs_BS.md) +- [🇩🇪 Deutsch](../de-DE/README.md) - [🇬🇧 English](../README.md) -- [🇪🇸 Español](./es-ES/README-ES.md) -- [🇫🇷 Français](./fr-FR/README_fr-FR.md) -- [🇮🇩 Indonesia](./id-ID/README.md) -- [🇮🇹 Italiano](./it-IT/README.md) -- [🇯🇵 日本語](./ja-JA/README-ja_JA.md) -- [🇰🇷 한국어](./ko-KR/README-ko_KR.md) -- [🇳🇱 Nederlands](./nl-NL/README.md) -- [🇧🇷 Português Brasil](./pt-BR/README_pt_BR.md) -- [🇷🇺 Русский](./ru-RU/README.md) -- [🇹🇭 ไทย](./th-TH/README-th_TH.md) -- [🇹🇷 Türkçe](./tr-TR/README-tr_TR.md) -- [🇺🇦 Українська мова](./uk-UA/README.md) -- [🇻🇳 Tiếng Việt](./vi-VI/README-vi.md) -- [🇨🇳 简体中文](./zh-CN/README-zh_CN.md) -- [🇹🇼 繁體中文](./zh-TW/README_zh-TW.md) +- [🇪🇸 Español](../es-ES/README-ES.md) +- [🇫🇷 Français](../fr-FR/README_fr-FR.md) +- [🇮🇩 Indonesia](../id-ID/README.md) +- [🇮🇹 Italiano](../it-IT/README.md) +- [🇯🇵 日本語](../ja-JA/README-ja_JA.md) +- [🇰🇷 한국어](../ko-KR/README-ko_KR.md) +- [🇳🇱 Nederlands](../nl-NL/README.md) +- [🇧🇷 Português Brasil](../pt-BR/README_pt_BR.md) +- [🇷🇺 Русский](../ru-RU/README.md) +- [🇹🇭 ไทย](../th-TH/README-th_TH.md) +- [🇹🇷 Türkçe](../tr-TR/README-tr_TR.md) +- [🇺🇦 Українська мова](../uk-UA/README.md) +- [🇻🇳 Tiếng Việt](../vi-VI/README-vi.md) +- [🇨🇳 简体中文](../zh-CN/README-zh_CN.md) +- [🇹🇼 繁體中文](../zh-TW/README_zh-TW.md) ____________ diff --git a/bs-BS/README-bs_BS.md b/bs-BS/README-bs_BS.md index 7ff21b44..425f418e 100644 --- a/bs-BS/README-bs_BS.md +++ b/bs-BS/README-bs_BS.md @@ -12,25 +12,25 @@ Ovaj tjedni repo ažuriram s novim pitanjima. Odgovori su jednostavno dijelovima ispod pitanja kliknite na njih da biste ih proširili. Sretno :heart: -- [🇸🇦 العربية](./ar-AR/README_AR.md) -- [🇪🇬 اللغة العامية](./ar-EG/README_ar-EG.md) -- [🇩🇪 Deutsch](./de-DE/README.md) +- [🇸🇦 العربية](../ar-AR/README_AR.md) +- [🇪🇬 اللغة العامية](../ar-EG/README_ar-EG.md) +- [🇩🇪 Deutsch](../de-DE/README.md) - [🇬🇧 English](../README.md) -- [🇪🇸 Español](./es-ES/README-ES.md) -- [🇫🇷 Français](./fr-FR/README_fr-FR.md) -- [🇮🇩 Indonesia](./id-ID/README.md) -- [🇮🇹 Italiano](./it-IT/README.md) -- [🇯🇵 日本語](./ja-JA/README-ja_JA.md) -- [🇰🇷 한국어](./ko-KR/README-ko_KR.md) -- [🇳🇱 Nederlands](./nl-NL/README.md) -- [🇧🇷 Português Brasil](./pt-BR/README_pt_BR.md) -- [🇷🇺 Русский](./ru-RU/README.md) -- [🇹🇭 ไทย](./th-TH/README-th_TH.md) -- [🇹🇷 Türkçe](./tr-TR/README-tr_TR.md) -- [🇺🇦 Українська мова](./uk-UA/README.md) -- [🇻🇳 Tiếng Việt](./vi-VI/README-vi.md) -- [🇨🇳 简体中文](./zh-CN/README-zh_CN.md) -- [🇹🇼 繁體中文](./zh-TW/README_zh-TW.md) +- [🇪🇸 Español](../es-ES/README-ES.md) +- [🇫🇷 Français](../fr-FR/README_fr-FR.md) +- [🇮🇩 Indonesia](../id-ID/README.md) +- [🇮🇹 Italiano](../it-IT/README.md) +- [🇯🇵 日本語](../ja-JA/README-ja_JA.md) +- [🇰🇷 한국어](../ko-KR/README-ko_KR.md) +- [🇳🇱 Nederlands](../nl-NL/README.md) +- [🇧🇷 Português Brasil](../pt-BR/README_pt_BR.md) +- [🇷🇺 Русский](../ru-RU/README.md) +- [🇹🇭 ไทย](../th-TH/README-th_TH.md) +- [🇹🇷 Türkçe](../tr-TR/README-tr_TR.md) +- [🇺🇦 Українська мова](../uk-UA/README.md) +- [🇻🇳 Tiếng Việt](../vi-VI/README-vi.md) +- [🇨🇳 简体中文](../zh-CN/README-zh_CN.md) +- [🇹🇼 繁體中文](../zh-TW/README_zh-TW.md) * * * * * diff --git a/de-DE/README.md b/de-DE/README.md index 47a5fa01..4bc3e25c 100644 --- a/de-DE/README.md +++ b/de-DE/README.md @@ -22,25 +22,25 @@ Kontaktiert mich, wenn ihr möchtet! 😊
Alle 18 Übersetzungen anzeigen 🇸🇦🇪🇬🇧🇦🇩🇪🇪🇸🇫🇷🇮🇩🇯🇵🇰🇷🇳🇱🇧🇷🇷🇺🇹🇭🇹🇷🇺🇦🇻🇳🇨🇳🇹🇼

-- [🇸🇦 العربية](./ar-AR/README_AR.md) -- [🇪🇬 اللغة العامية](./ar-EG/README_ar-EG.md) -- [🇧🇦 Bosanski](./bs-BS/README-bs_BS.md) +- [🇸🇦 العربية](../ar-AR/README_AR.md) +- [🇪🇬 اللغة العامية](../ar-EG/README_ar-EG.md) +- [🇧🇦 Bosanski](../bs-BS/README-bs_BS.md) - [🇬🇧 English](../README.md) -- [🇪🇸 Español](./es-ES/README-ES.md) -- [🇫🇷 Français](./fr-FR/README_fr-FR.md) -- [🇮🇩 Indonesia](./id-ID/README.md) -- [🇮🇹 Italiano](./it-IT/README.md) -- [🇯🇵 日本語](./ja-JA/README-ja_JA.md) -- [🇰🇷 한국어](./ko-KR/README-ko_KR.md) -- [🇳🇱 Nederlands](./nl-NL/README.md) -- [🇧🇷 Português Brasil](./pt-BR/README_pt_BR.md) -- [🇷🇺 Русский](./ru-RU/README.md) -- [🇹🇭 ไทย](./th-TH/README-th_TH.md) -- [🇹🇷 Türkçe](./tr-TR/README-tr_TR.md) -- [🇺🇦 Українська мова](./uk-UA/README.md) -- [🇻🇳 Tiếng Việt](./vi-VI/README-vi.md) -- [🇨🇳 简体中文](./zh-CN/README-zh_CN.md) -- [🇹🇼 繁體中文](./zh-TW/README_zh-TW.md) +- [🇪🇸 Español](../es-ES/README-ES.md) +- [🇫🇷 Français](../fr-FR/README_fr-FR.md) +- [🇮🇩 Indonesia](../id-ID/README.md) +- [🇮🇹 Italiano](../it-IT/README.md) +- [🇯🇵 日本語](../ja-JA/README-ja_JA.md) +- [🇰🇷 한국어](../ko-KR/README-ko_KR.md) +- [🇳🇱 Nederlands](../nl-NL/README.md) +- [🇧🇷 Português Brasil](../pt-BR/README_pt_BR.md) +- [🇷🇺 Русский](../ru-RU/README.md) +- [🇹🇭 ไทย](../th-TH/README-th_TH.md) +- [🇹🇷 Türkçe](../tr-TR/README-tr_TR.md) +- [🇺🇦 Українська мова](../uk-UA/README.md) +- [🇻🇳 Tiếng Việt](../vi-VI/README-vi.md) +- [🇨🇳 简体中文](../zh-CN/README-zh_CN.md) +- [🇹🇼 繁體中文](../zh-TW/README_zh-TW.md)

diff --git a/es-ES/README-ES.md b/es-ES/README-ES.md index 9794aa30..b8e1e29e 100644 --- a/es-ES/README-ES.md +++ b/es-ES/README-ES.md @@ -12,25 +12,25 @@ Lista de lenguajes disponibles: -- [🇸🇦 العربية](./ar-AR/README_AR.md) -- [🇪🇬 اللغة العامية](./ar-EG/README_ar-EG.md) -- [🇧🇦 Bosanski](./bs-BS/README-bs_BS.md) -- [🇩🇪 Deutsch](./de-DE/README.md) +- [🇸🇦 العربية](../ar-AR/README_AR.md) +- [🇪🇬 اللغة العامية](../ar-EG/README_ar-EG.md) +- [🇧🇦 Bosanski](../bs-BS/README-bs_BS.md) +- [🇩🇪 Deutsch](../de-DE/README.md) - [🇬🇧 English](../README.md) -- [🇫🇷 Français](./fr-FR/README_fr-FR.md) -- [🇮🇩 Indonesia](./id-ID/README.md) -- [🇮🇹 Italiano](./it-IT/README.md) -- [🇯🇵 日本語](./ja-JA/README-ja_JA.md) -- [🇰🇷 한국어](./ko-KR/README-ko_KR.md) -- [🇳🇱 Nederlands](./nl-NL/README.md) -- [🇧🇷 Português Brasil](./pt-BR/README_pt_BR.md) -- [🇷🇺 Русский](./ru-RU/README.md) -- [🇹🇭 ไทย](./th-TH/README-th_TH.md) -- [🇹🇷 Türkçe](./tr-TR/README-tr_TR.md) -- [🇺🇦 Українська мова](./uk-UA/README.md) -- [🇻🇳 Tiếng Việt](./vi-VI/README-vi.md) -- [🇨🇳 简体中文](./zh-CN/README-zh_CN.md) -- [🇹🇼 繁體中文](./zh-TW/README_zh-TW.md) +- [🇫🇷 Français](../fr-FR/README_fr-FR.md) +- [🇮🇩 Indonesia](../id-ID/README.md) +- [🇮🇹 Italiano](../it-IT/README.md) +- [🇯🇵 日本語](../ja-JA/README-ja_JA.md) +- [🇰🇷 한국어](../ko-KR/README-ko_KR.md) +- [🇳🇱 Nederlands](../nl-NL/README.md) +- [🇧🇷 Português Brasil](../pt-BR/README_pt_BR.md) +- [🇷🇺 Русский](../ru-RU/README.md) +- [🇹🇭 ไทย](../th-TH/README-th_TH.md) +- [🇹🇷 Türkçe](../tr-TR/README-tr_TR.md) +- [🇺🇦 Українська мова](../uk-UA/README.md) +- [🇻🇳 Tiếng Việt](../vi-VI/README-vi.md) +- [🇨🇳 简体中文](../zh-CN/README-zh_CN.md) +- [🇹🇼 繁體中文](../zh-TW/README_zh-TW.md) --- diff --git a/fr-FR/README_fr-FR.md b/fr-FR/README_fr-FR.md index 55bc8c07..35fadb22 100644 --- a/fr-FR/README_fr-FR.md +++ b/fr-FR/README_fr-FR.md @@ -6,25 +6,25 @@ De la base aux subtilités du langage : testez votre compréhension de JavaScrip Les réponses se trouvent dans les sections repliées en dessous des questions, cliquez simplement dessus pour les faire apparaître. Bonne chance :heart: -- [🇸🇦 العربية](./ar-AR/README_AR.md) -- [🇪🇬 اللغة العامية](./ar-EG/README_ar-EG.md) -- [🇧🇦 Bosanski](./bs-BS/README-bs_BS.md) -- [🇩🇪 Deutsch](./de-DE/README.md) +- [🇸🇦 العربية](../ar-AR/README_AR.md) +- [🇪🇬 اللغة العامية](../ar-EG/README_ar-EG.md) +- [🇧🇦 Bosanski](../bs-BS/README-bs_BS.md) +- [🇩🇪 Deutsch](../de-DE/README.md) - [🇬🇧 English](../README.md) -- [🇪🇸 Español](./es-ES/README-ES.md) -- [🇮🇩 Indonesia](./id-ID/README.md) -- [🇮🇹 Italiano](./it-IT/README.md) -- [🇯🇵 日本語](./ja-JA/README-ja_JA.md) -- [🇰🇷 한국어](./ko-KR/README-ko_KR.md) -- [🇳🇱 Nederlands](./nl-NL/README.md) -- [🇧🇷 Português Brasil](./pt-BR/README_pt_BR.md) -- [🇷🇺 Русский](./ru-RU/README.md) -- [🇹🇭 ไทย](./th-TH/README-th_TH.md) -- [🇹🇷 Türkçe](./tr-TR/README-tr_TR.md) -- [🇺🇦 Українська мова](./uk-UA/README.md) -- [🇻🇳 Tiếng Việt](./vi-VI/README-vi.md) -- [🇨🇳 简体中文](./zh-CN/README-zh_CN.md) -- [🇹🇼 繁體中文](./zh-TW/README_zh-TW.md) +- [🇪🇸 Español](../es-ES/README-ES.md) +- [🇮🇩 Indonesia](../id-ID/README.md) +- [🇮🇹 Italiano](../it-IT/README.md) +- [🇯🇵 日本語](../ja-JA/README-ja_JA.md) +- [🇰🇷 한국어](../ko-KR/README-ko_KR.md) +- [🇳🇱 Nederlands](../nl-NL/README.md) +- [🇧🇷 Português Brasil](../pt-BR/README_pt_BR.md) +- [🇷🇺 Русский](../ru-RU/README.md) +- [🇹🇭 ไทย](../th-TH/README-th_TH.md) +- [🇹🇷 Türkçe](../tr-TR/README-tr_TR.md) +- [🇺🇦 Українська мова](../uk-UA/README.md) +- [🇻🇳 Tiếng Việt](../vi-VI/README-vi.md) +- [🇨🇳 简体中文](../zh-CN/README-zh_CN.md) +- [🇹🇼 繁體中文](../zh-TW/README_zh-TW.md) --- diff --git a/id-ID/README.md b/id-ID/README.md index 3a6932fe..e8b2e5ae 100644 --- a/id-ID/README.md +++ b/id-ID/README.md @@ -16,25 +16,25 @@ Jangan sungkan untuk terhubung dengan saya! 😊
Lihat 17 Terjemahan yang tersedia 🇪🇸🇮🇹🇩🇪 🇫🇷🇷🇺🇨🇳🇵🇹

-- [🇸🇦 العربية](./ar-AR/README_AR.md) -- [🇪🇬 اللغة العامية](./ar-EG/README_ar-EG.md) -- [🇧🇦 Bosanski](./bs-BS/README-bs_BS.md) -- [🇩🇪 Deutsch](./de-DE/README.md) +- [🇸🇦 العربية](../ar-AR/README_AR.md) +- [🇪🇬 اللغة العامية](../ar-EG/README_ar-EG.md) +- [🇧🇦 Bosanski](../bs-BS/README-bs_BS.md) +- [🇩🇪 Deutsch](../de-DE/README.md) - [🇬🇧 English](../README.md) -- [🇪🇸 Español](./es-ES/README-ES.md) -- [🇫🇷 Français](./fr-FR/README_fr-FR.md) -- [🇮🇹 Italiano](./it-IT/README.md) -- [🇯🇵 日本語](./ja-JA/README-ja_JA.md) -- [🇰🇷 한국어](./ko-KR/README-ko_KR.md) -- [🇳🇱 Nederlands](./nl-NL/README.md) -- [🇧🇷 Português Brasil](./pt-BR/README_pt_BR.md) -- [🇷🇺 Русский](./ru-RU/README.md) -- [🇹🇭 ไทย](./th-TH/README-th_TH.md) -- [🇹🇷 Türkçe](./tr-TR/README-tr_TR.md) -- [🇺🇦 Українська мова](./uk-UA/README.md) -- [🇻🇳 Tiếng Việt](./vi-VI/README-vi.md) -- [🇨🇳 简体中文](./zh-CN/README-zh_CN.md) -- [🇹🇼 繁體中文](./zh-TW/README_zh-TW.md) +- [🇪🇸 Español](../es-ES/README-ES.md) +- [🇫🇷 Français](../fr-FR/README_fr-FR.md) +- [🇮🇹 Italiano](../it-IT/README.md) +- [🇯🇵 日本語](../ja-JA/README-ja_JA.md) +- [🇰🇷 한국어](../ko-KR/README-ko_KR.md) +- [🇳🇱 Nederlands](../nl-NL/README.md) +- [🇧🇷 Português Brasil](../pt-BR/README_pt_BR.md) +- [🇷🇺 Русский](../ru-RU/README.md) +- [🇹🇭 ไทย](../th-TH/README-th_TH.md) +- [🇹🇷 Türkçe](../tr-TR/README-tr_TR.md) +- [🇺🇦 Українська мова](../uk-UA/README.md) +- [🇻🇳 Tiếng Việt](../vi-VI/README-vi.md) +- [🇨🇳 简体中文](../zh-CN/README-zh_CN.md) +- [🇹🇼 繁體中文](../zh-TW/README_zh-TW.md)

diff --git a/it-IT/README-IT.md b/it-IT/README-IT.md index 3efee591..a6e205b9 100644 --- a/it-IT/README-IT.md +++ b/it-IT/README-IT.md @@ -24,25 +24,25 @@ Traduzione a cura di: Lucia Cenetie
Vedi le 18 traduzioni disponibili 🇸🇦🇪🇬🇧🇦🇩🇪🇪🇸🇫🇷🇮🇩🇯🇵🇰🇷🇳🇱🇧🇷🇷🇺🇹🇭🇹🇷🇺🇦🇻🇳🇨🇳🇹🇼

-- [🇸🇦 العربية](./ar-AR/README_AR.md) -- [🇪🇬 اللغة العامية](./ar-EG/README_ar-EG.md) -- [🇧🇦 Bosanski](./bs-BS/README-bs_BS.md) -- [🇩🇪 Deutsch](./de-DE/README.md) +- [🇸🇦 العربية](../ar-AR/README_AR.md) +- [🇪🇬 اللغة العامية](../ar-EG/README_ar-EG.md) +- [🇧🇦 Bosanski](../bs-BS/README-bs_BS.md) +- [🇩🇪 Deutsch](../de-DE/README.md) - [🇬🇧 English](../README.md) -- [🇪🇸 Español](./es-ES/README-ES.md) -- [🇫🇷 Français](./fr-FR/README_fr-FR.md) -- [🇮🇩 Indonesia](./id-ID/README.md) -- [🇯🇵 日本語](./ja-JA/README-ja_JA.md) -- [🇰🇷 한국어](./ko-KR/README-ko_KR.md) -- [🇳🇱 Nederlands](./nl-NL/README.md) -- [🇧🇷 Português Brasil](./pt-BR/README_pt_BR.md) -- [🇷🇺 Русский](./ru-RU/README.md) -- [🇹🇭 ไทย](./th-TH/README-th_TH.md) -- [🇹🇷 Türkçe](./tr-TR/README-tr_TR.md) -- [🇺🇦 Українська мова](./uk-UA/README.md) -- [🇻🇳 Tiếng Việt](./vi-VI/README-vi.md) -- [🇨🇳 简体中文](./zh-CN/README-zh_CN.md) -- [🇹🇼 繁體中文](./zh-TW/README_zh-TW.md) +- [🇪🇸 Español](../es-ES/README-ES.md) +- [🇫🇷 Français](../fr-FR/README_fr-FR.md) +- [🇮🇩 Indonesia](../id-ID/README.md) +- [🇯🇵 日本語](../ja-JA/README-ja_JA.md) +- [🇰🇷 한국어](../ko-KR/README-ko_KR.md) +- [🇳🇱 Nederlands](../nl-NL/README.md) +- [🇧🇷 Português Brasil](../pt-BR/README_pt_BR.md) +- [🇷🇺 Русский](../ru-RU/README.md) +- [🇹🇭 ไทย](../th-TH/README-th_TH.md) +- [🇹🇷 Türkçe](../tr-TR/README-tr_TR.md) +- [🇺🇦 Українська мова](../uk-UA/README.md) +- [🇻🇳 Tiếng Việt](../vi-VI/README-vi.md) +- [🇨🇳 简体中文](../zh-CN/README-zh_CN.md) +- [🇹🇼 繁體中文](../zh-TW/README_zh-TW.md)

diff --git a/ja-JA/README-ja_JA.md b/ja-JA/README-ja_JA.md index 9d579e93..8186fb14 100644 --- a/ja-JA/README-ja_JA.md +++ b/ja-JA/README-ja_JA.md @@ -16,7 +16,7 @@ - [🇪🇸 Español](../es-ES/README-ES.md) - [🇫🇷 Français](../fr-FR/README_fr-FR.md) - [🇮🇩 Indonesia](../id-ID/README.md) -- [🇮🇹 Italiano](./it-IT/README.md) +- [🇮🇹 Italiano](../it-IT/README.md) - [🇰🇷 한국어](../ko-KR/README-ko_KR.md) - [🇳🇱 Nederlands](../nl-NL/README.md) - [🇧🇷 Português Brasil](../pt-BR/README_pt_BR.md) diff --git a/ko-KR/README-ko_KR.md b/ko-KR/README-ko_KR.md index 9f8f7e98..1d32f618 100644 --- a/ko-KR/README-ko_KR.md +++ b/ko-KR/README-ko_KR.md @@ -21,25 +21,25 @@
사용 가능한 번역 18개 🇸🇦🇪🇬🇧🇦🇬🇧🇩🇪🇪🇸🇫🇷🇮🇩🇯🇵🇳🇱🇧🇷🇷🇺🇹🇭🇹🇷🇺🇦🇻🇳🇨🇳🇹🇼

-- [🇸🇦 العربية](./ar-AR/README_AR.md) -- [🇪🇬 اللغة العامية](./ar-EG/README_ar-EG.md) -- [🇧🇦 Bosanski](./bs-BS/README-bs_BS.md) -- [🇩🇪 Deutsch](./de-DE/README.md) +- [🇸🇦 العربية](../ar-AR/README_AR.md) +- [🇪🇬 اللغة العامية](../ar-EG/README_ar-EG.md) +- [🇧🇦 Bosanski](../bs-BS/README-bs_BS.md) +- [🇩🇪 Deutsch](../de-DE/README.md) - [🇬🇧 English](../README.md) -- [🇪🇸 Español](./es-ES/README-ES.md) -- [🇫🇷 Français](./fr-FR/README_fr-FR.md) -- [🇮🇩 Indonesia](./id-ID/README.md) -- [🇮🇹 Italiano](./it-IT/README.md) -- [🇯🇵 日本語](./ja-JA/README-ja_JA.md) -- [🇳🇱 Nederlands](./nl-NL/README.md) -- [🇧🇷 Português Brasil](./pt-BR/README_pt_BR.md) -- [🇷🇺 Русский](./ru-RU/README.md) -- [🇹🇭 ไทย](./th-TH/README-th_TH.md) -- [🇹🇷 Türkçe](./tr-TR/README-tr_TR.md) -- [🇺🇦 Українська мова](./uk-UA/README.md) -- [🇻🇳 Tiếng Việt](./vi-VI/README-vi.md) -- [🇨🇳 简体中文](./zh-CN/README-zh_CN.md) -- [🇹🇼 繁體中文](./zh-TW/README_zh-TW.md) +- [🇪🇸 Español](../es-ES/README-ES.md) +- [🇫🇷 Français](../fr-FR/README_fr-FR.md) +- [🇮🇩 Indonesia](../id-ID/README.md) +- [🇮🇹 Italiano](../it-IT/README.md) +- [🇯🇵 日本語](../ja-JA/README-ja_JA.md) +- [🇳🇱 Nederlands](../nl-NL/README.md) +- [🇧🇷 Português Brasil](../pt-BR/README_pt_BR.md) +- [🇷🇺 Русский](../ru-RU/README.md) +- [🇹🇭 ไทย](../th-TH/README-th_TH.md) +- [🇹🇷 Türkçe](../tr-TR/README-tr_TR.md) +- [🇺🇦 Українська мова](../uk-UA/README.md) +- [🇻🇳 Tiếng Việt](../vi-VI/README-vi.md) +- [🇨🇳 简体中文](../zh-CN/README-zh_CN.md) +- [🇹🇼 繁體中文](../zh-TW/README_zh-TW.md)

diff --git a/nl-NL/README.md b/nl-NL/README.md index ab01483a..f65fa922 100644 --- a/nl-NL/README.md +++ b/nl-NL/README.md @@ -17,25 +17,25 @@
Zie alle 17 beschikbare vertalingen

-- [🇸🇦 العربية](./ar-AR/README_AR.md) -- [🇪🇬 اللغة العامية](./ar-EG/README_ar-EG.md) -- [🇧🇦 Bosanski](./bs-BS/README-bs_BS.md) -- [🇩🇪 Deutsch](./de-DE/README.md) +- [🇸🇦 العربية](../ar-AR/README_AR.md) +- [🇪🇬 اللغة العامية](../ar-EG/README_ar-EG.md) +- [🇧🇦 Bosanski](../bs-BS/README-bs_BS.md) +- [🇩🇪 Deutsch](../de-DE/README.md) - [🇬🇧 English](../README.md) -- [🇪🇸 Español](./es-ES/README-ES.md) -- [🇫🇷 Français](./fr-FR/README_fr-FR.md) -- [🇮🇩 Indonesia](./id-ID/README.md) -- [🇮🇹 Italiano](./it-IT/README.md) -- [🇯🇵 日本語](./ja-JA/README-ja_JA.md) -- [🇰🇷 한국어](./ko-KR/README-ko_KR.md) -- [🇧🇷 Português Brasil](./pt-BR/README_pt_BR.md) -- [🇷🇺 Русский](./ru-RU/README.md) -- [🇹🇭 ไทย](./th-TH/README-th_TH.md) -- [🇹🇷 Türkçe](./tr-TR/README-tr_TR.md) -- [🇺🇦 Українська мова](./uk-UA/README.md) -- [🇻🇳 Tiếng Việt](./vi-VI/README-vi.md) -- [🇨🇳 简体中文](./zh-CN/README-zh_CN.md) -- [🇹🇼 繁體中文](./zh-TW/README_zh-TW.md) +- [🇪🇸 Español](../es-ES/README-ES.md) +- [🇫🇷 Français](../fr-FR/README_fr-FR.md) +- [🇮🇩 Indonesia](../id-ID/README.md) +- [🇮🇹 Italiano](../it-IT/README.md) +- [🇯🇵 日本語](../ja-JA/README-ja_JA.md) +- [🇰🇷 한국어](../ko-KR/README-ko_KR.md) +- [🇧🇷 Português Brasil](../pt-BR/README_pt_BR.md) +- [🇷🇺 Русский](../ru-RU/README.md) +- [🇹🇭 ไทย](../th-TH/README-th_TH.md) +- [🇹🇷 Türkçe](../tr-TR/README-tr_TR.md) +- [🇺🇦 Українська мова](../uk-UA/README.md) +- [🇻🇳 Tiếng Việt](../vi-VI/README-vi.md) +- [🇨🇳 简体中文](../zh-CN/README-zh_CN.md) +- [🇹🇼 繁體中文](../zh-TW/README_zh-TW.md)

diff --git a/ru-RU/README.md b/ru-RU/README.md index 91963045..d98fc2c3 100644 --- a/ru-RU/README.md +++ b/ru-RU/README.md @@ -11,25 +11,25 @@ Список доступных переводов: -- [🇸🇦 العربية](./ar-AR/README_AR.md) -- [🇪🇬 اللغة العامية](./ar-EG/README_ar-EG.md) -- [🇧🇦 Bosanski](./bs-BS/README-bs_BS.md) -- [🇩🇪 Deutsch](./de-DE/README.md) +- [🇸🇦 العربية](../ar-AR/README_AR.md) +- [🇪🇬 اللغة العامية](../ar-EG/README_ar-EG.md) +- [🇧🇦 Bosanski](../bs-BS/README-bs_BS.md) +- [🇩🇪 Deutsch](../de-DE/README.md) - [🇬🇧 English](../README.md) -- [🇪🇸 Español](./es-ES/README-ES.md) -- [🇫🇷 Français](./fr-FR/README_fr-FR.md) -- [🇮🇩 Indonesia](./id-ID/README.md) -- [🇮🇹 Italiano](./it-IT/README.md) -- [🇯🇵 日本語](./ja-JA/README-ja_JA.md) -- [🇰🇷 한국어](./ko-KR/README-ko_KR.md) -- [🇳🇱 Nederlands](./nl-NL/README.md) -- [🇧🇷 Português Brasil](./pt-BR/README_pt_BR.md) -- [🇹🇭 ไทย](./th-TH/README-th_TH.md) -- [🇹🇷 Türkçe](./tr-TR/README-tr_TR.md) -- [🇺🇦 Українська мова](./uk-UA/README.md) -- [🇻🇳 Tiếng Việt](./vi-VI/README-vi.md) -- [🇨🇳 简体中文](./zh-CN/README-zh_CN.md) -- [🇹🇼 繁體中文](./zh-TW/README_zh-TW.md) +- [🇪🇸 Español](../es-ES/README-ES.md) +- [🇫🇷 Français](../fr-FR/README_fr-FR.md) +- [🇮🇩 Indonesia](../id-ID/README.md) +- [🇮🇹 Italiano](../it-IT/README.md) +- [🇯🇵 日本語](../ja-JA/README-ja_JA.md) +- [🇰🇷 한국어](../ko-KR/README-ko_KR.md) +- [🇳🇱 Nederlands](../nl-NL/README.md) +- [🇧🇷 Português Brasil](../pt-BR/README_pt_BR.md) +- [🇹🇭 ไทย](../th-TH/README-th_TH.md) +- [🇹🇷 Türkçe](../tr-TR/README-tr_TR.md) +- [🇺🇦 Українська мова](../uk-UA/README.md) +- [🇻🇳 Tiếng Việt](../vi-VI/README-vi.md) +- [🇨🇳 简体中文](../zh-CN/README-zh_CN.md) +- [🇹🇼 繁體中文](../zh-TW/README_zh-TW.md) --- diff --git a/th-TH/README.md b/th-TH/README.md index 9cab8b2c..90f37243 100644 --- a/th-TH/README.md +++ b/th-TH/README.md @@ -18,25 +18,25 @@ ลิสต์ภาษาอื่นๆ: -- [🇸🇦 العربية](./ar-AR/README_AR.md) -- [🇪🇬 اللغة العامية](./ar-EG/README_ar-EG.md) -- [🇧🇦 Bosanski](./bs-BS/README-bs_BS.md) -- [🇩🇪 Deutsch](./de-DE/README.md) +- [🇸🇦 العربية](../ar-AR/README_AR.md) +- [🇪🇬 اللغة العامية](../ar-EG/README_ar-EG.md) +- [🇧🇦 Bosanski](../bs-BS/README-bs_BS.md) +- [🇩🇪 Deutsch](../de-DE/README.md) - [🇬🇧 English](../README.md) -- [🇪🇸 Español](./es-ES/README-ES.md) -- [🇫🇷 Français](./fr-FR/README_fr-FR.md) -- [🇮🇩 Indonesia](./id-ID/README.md) -- [🇮🇹 Italiano](./it-IT/README.md) -- [🇯🇵 日本語](./ja-JA/README-ja_JA.md) -- [🇰🇷 한국어](./ko-KR/README-ko_KR.md) -- [🇳🇱 Nederlands](./nl-NL/README.md) -- [🇧🇷 Português Brasil](./pt-BR/README_pt_BR.md) -- [🇷🇺 Русский](./ru-RU/README.md) -- [🇹🇷 Türkçe](./tr-TR/README-tr_TR.md) -- [🇺🇦 Українська мова](./uk-UA/README.md) -- [🇻🇳 Tiếng Việt](./vi-VI/README-vi.md) -- [🇨🇳 简体中文](./zh-CN/README-zh_CN.md) -- [🇹🇼 繁體中文](./zh-TW/README_zh-TW.md) +- [🇪🇸 Español](../es-ES/README-ES.md) +- [🇫🇷 Français](../fr-FR/README_fr-FR.md) +- [🇮🇩 Indonesia](../id-ID/README.md) +- [🇮🇹 Italiano](../it-IT/README.md) +- [🇯🇵 日本語](../ja-JA/README-ja_JA.md) +- [🇰🇷 한국어](../ko-KR/README-ko_KR.md) +- [🇳🇱 Nederlands](../nl-NL/README.md) +- [🇧🇷 Português Brasil](../pt-BR/README_pt_BR.md) +- [🇷🇺 Русский](../ru-RU/README.md) +- [🇹🇷 Türkçe](../tr-TR/README-tr_TR.md) +- [🇺🇦 Українська мова](../uk-UA/README.md) +- [🇻🇳 Tiếng Việt](../vi-VI/README-vi.md) +- [🇨🇳 简体中文](../zh-CN/README-zh_CN.md) +- [🇹🇼 繁體中文](../zh-TW/README_zh-TW.md) --- diff --git a/tr-TR/README-tr_TR.md b/tr-TR/README-tr_TR.md index b80c634d..a6f29543 100644 --- a/tr-TR/README-tr_TR.md +++ b/tr-TR/README-tr_TR.md @@ -12,25 +12,25 @@ Daha fazla soru eklendikçe eposta almak ister misiniz?
Mevcut dillerin listesi: -- [🇸🇦 العربية](./ar-AR/README_AR.md) -- [🇪🇬 اللغة العامية](./ar-EG/README_ar-EG.md) -- [🇧🇦 Bosanski](./bs-BS/README-bs_BS.md) -- [🇩🇪 Deutsch](./de-DE/README.md) +- [🇸🇦 العربية](../ar-AR/README_AR.md) +- [🇪🇬 اللغة العامية](../ar-EG/README_ar-EG.md) +- [🇧🇦 Bosanski](../bs-BS/README-bs_BS.md) +- [🇩🇪 Deutsch](../de-DE/README.md) - [🇬🇧 English](../README.md) -- [🇪🇸 Español](./es-ES/README-ES.md) -- [🇫🇷 Français](./fr-FR/README_fr-FR.md) -- [🇮🇩 Indonesia](./id-ID/README.md) -- [🇮🇹 Italiano](./it-IT/README.md) -- [🇯🇵 日本語](./ja-JA/README-ja_JA.md) -- [🇰🇷 한국어](./ko-KR/README-ko_KR.md) -- [🇳🇱 Nederlands](./nl-NL/README.md) -- [🇧🇷 Português Brasil](./pt-BR/README_pt_BR.md) -- [🇷🇺 Русский](./ru-RU/README.md) -- [🇹🇭 ไทย](./th-TH/README-th_TH.md) -- [🇺🇦 Українська мова](./uk-UA/README.md) -- [🇻🇳 Tiếng Việt](./vi-VI/README-vi.md) -- [🇨🇳 简体中文](./zh-CN/README-zh_CN.md) -- [🇹🇼 繁體中文](./zh-TW/README_zh-TW.md) +- [🇪🇸 Español](../es-ES/README-ES.md) +- [🇫🇷 Français](../fr-FR/README_fr-FR.md) +- [🇮🇩 Indonesia](../id-ID/README.md) +- [🇮🇹 Italiano](../it-IT/README.md) +- [🇯🇵 日本語](../ja-JA/README-ja_JA.md) +- [🇰🇷 한국어](../ko-KR/README-ko_KR.md) +- [🇳🇱 Nederlands](../nl-NL/README.md) +- [🇧🇷 Português Brasil](../pt-BR/README_pt_BR.md) +- [🇷🇺 Русский](../ru-RU/README.md) +- [🇹🇭 ไทย](../th-TH/README-th_TH.md) +- [🇺🇦 Українська мова](../uk-UA/README.md) +- [🇻🇳 Tiếng Việt](../vi-VI/README-vi.md) +- [🇨🇳 简体中文](../zh-CN/README-zh_CN.md) +- [🇹🇼 繁體中文](../zh-TW/README_zh-TW.md) --- diff --git a/uk-UA/README.md b/uk-UA/README.md index e4b77264..fd7d5f35 100644 --- a/uk-UA/README.md +++ b/uk-UA/README.md @@ -6,25 +6,25 @@ Відповіді знаходяться в згорнутій секції нижче питань. Просто натисни на відповідь, щоб розгорнути. Успіхів! :heart: -- [🇸🇦 العربية](./ar-AR/README_AR.md) -- [🇪🇬 اللغة العامية](./ar-EG/README_ar-EG.md) -- [🇧🇦 Bosanski](./bs-BS/README-bs_BS.md) -- [🇩🇪 Deutsch](./de-DE/README.md) +- [🇸🇦 العربية](../ar-AR/README_AR.md) +- [🇪🇬 اللغة العامية](../ar-EG/README_ar-EG.md) +- [🇧🇦 Bosanski](../bs-BS/README-bs_BS.md) +- [🇩🇪 Deutsch](../de-DE/README.md) - [🇬🇧 English](../README.md) -- [🇪🇸 Español](./es-ES/README-ES.md) -- [🇫🇷 Français](./fr-FR/README_fr-FR.md) -- [🇮🇩 Indonesia](./id-ID/README.md) -- [🇮🇹 Italiano](./it-IT/README.md) -- [🇯🇵 日本語](./ja-JA/README-ja_JA.md) -- [🇰🇷 한국어](./ko-KR/README-ko_KR.md) -- [🇳🇱 Nederlands](./nl-NL/README.md) -- [🇧🇷 Português Brasil](./pt-BR/README_pt_BR.md) -- [🇷🇺 Русский](./ru-RU/README.md) -- [🇹🇭 ไทย](./th-TH/README-th_TH.md) -- [🇹🇷 Türkçe](./tr-TR/README-tr_TR.md) -- [🇻🇳 Tiếng Việt](./vi-VI/README-vi.md) -- [🇨🇳 简体中文](./zh-CN/README-zh_CN.md) -- [🇹🇼 繁體中文](./zh-TW/README_zh-TW.md) +- [🇪🇸 Español](../es-ES/README-ES.md) +- [🇫🇷 Français](../fr-FR/README_fr-FR.md) +- [🇮🇩 Indonesia](../id-ID/README.md) +- [🇮🇹 Italiano](../it-IT/README.md) +- [🇯🇵 日本語](../ja-JA/README-ja_JA.md) +- [🇰🇷 한국어](../ko-KR/README-ko_KR.md) +- [🇳🇱 Nederlands](../nl-NL/README.md) +- [🇧🇷 Português Brasil](../pt-BR/README_pt_BR.md) +- [🇷🇺 Русский](../ru-RU/README.md) +- [🇹🇭 ไทย](../th-TH/README-th_TH.md) +- [🇹🇷 Türkçe](../tr-TR/README-tr_TR.md) +- [🇻🇳 Tiếng Việt](../vi-VI/README-vi.md) +- [🇨🇳 简体中文](../zh-CN/README-zh_CN.md) +- [🇹🇼 繁體中文](../zh-TW/README_zh-TW.md) --- diff --git a/vi-VI/README-vi.md b/vi-VI/README-vi.md index 9007f57e..0da12826 100644 --- a/vi-VI/README-vi.md +++ b/vi-VI/README-vi.md @@ -7,25 +7,25 @@ Các câu hỏi sẽ từ cơ bản đến nâng cao: kiểm tra trình độ Ja Các đáp án được đặt dưới mỗi câu hỏi, hãy click để tham khảo chúng. Chúc may mắn :heart: Danh sách các ngôn ngữ khác: -- [🇸🇦 العربية](./ar-AR/README_AR.md) -- [🇪🇬 اللغة العامية](./ar-EG/README_ar-EG.md) -- [🇧🇦 Bosanski](./bs-BS/README-bs_BS.md) -- [🇩🇪 Deutsch](./de-DE/README.md) +- [🇸🇦 العربية](../ar-AR/README_AR.md) +- [🇪🇬 اللغة العامية](../ar-EG/README_ar-EG.md) +- [🇧🇦 Bosanski](../bs-BS/README-bs_BS.md) +- [🇩🇪 Deutsch](../de-DE/README.md) - [🇬🇧 English](../README.md) -- [🇪🇸 Español](./es-ES/README-ES.md) -- [🇫🇷 Français](./fr-FR/README_fr-FR.md) -- [🇮🇩 Indonesia](./id-ID/README.md) -- [🇮🇹 Italiano](./it-IT/README.md) -- [🇯🇵 日本語](./ja-JA/README-ja_JA.md) -- [🇰🇷 한국어](./ko-KR/README-ko_KR.md) -- [🇳🇱 Nederlands](./nl-NL/README.md) -- [🇧🇷 Português Brasil](./pt-BR/README_pt_BR.md) -- [🇷🇺 Русский](./ru-RU/README.md) -- [🇹🇭 ไทย](./th-TH/README-th_TH.md) -- [🇹🇷 Türkçe](./tr-TR/README-tr_TR.md) -- [🇺🇦 Українська мова](./uk-UA/README.md) -- [🇨🇳 简体中文](./zh-CN/README-zh_CN.md) -- [🇹🇼 繁體中文](./zh-TW/README_zh-TW.md) +- [🇪🇸 Español](../es-ES/README-ES.md) +- [🇫🇷 Français](../fr-FR/README_fr-FR.md) +- [🇮🇩 Indonesia](../id-ID/README.md) +- [🇮🇹 Italiano](../it-IT/README.md) +- [🇯🇵 日本語](../ja-JA/README-ja_JA.md) +- [🇰🇷 한국어](../ko-KR/README-ko_KR.md) +- [🇳🇱 Nederlands](../nl-NL/README.md) +- [🇧🇷 Português Brasil](../pt-BR/README_pt_BR.md) +- [🇷🇺 Русский](../ru-RU/README.md) +- [🇹🇭 ไทย](../th-TH/README-th_TH.md) +- [🇹🇷 Türkçe](../tr-TR/README-tr_TR.md) +- [🇺🇦 Українська мова](../uk-UA/README.md) +- [🇨🇳 简体中文](../zh-CN/README-zh_CN.md) +- [🇹🇼 繁體中文](../zh-TW/README_zh-TW.md) --- From 5c8edeb30e0ff0c431b87ace9c1d719b5e8a3900 Mon Sep 17 00:00:00 2001 From: Korsakov-ua-dn <74375578+Korsakov-ua-dn@users.noreply.github.com> Date: Wed, 7 Sep 2022 11:46:29 +0300 Subject: [PATCH 120/193] Corrected a typo from Hello => Hi --- ru-RU/README.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/ru-RU/README.md b/ru-RU/README.md index 525f6fd6..3f1e1cd3 100644 --- a/ru-RU/README.md +++ b/ru-RU/README.md @@ -2546,9 +2546,9 @@ function sayHi(name) { console.log(sayHi()) ``` -- A: `Hello there, ` -- B: `Hello there, undefined` -- C: `Hello there, null` +- A: `Hi there, ` +- B: `Hi there, undefined` +- C: `Hi there, null` - D: `ReferenceError`
Ответ From c343104a1fffd123b609f1e7553c2eb3f42b963f Mon Sep 17 00:00:00 2001 From: owkmear Date: Tue, 20 Sep 2022 16:57:41 +0300 Subject: [PATCH 121/193] Forgot question number --- bs-BS/README-bs_BS.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/bs-BS/README-bs_BS.md b/bs-BS/README-bs_BS.md index 020a1f4f..7e7f2398 100644 --- a/bs-BS/README-bs_BS.md +++ b/bs-BS/README-bs_BS.md @@ -937,7 +937,7 @@ vraća "true". * * * * * -###### Što je izlaz? +###### 28. Što je izlaz? ```javascript String.prototype.giveLydiaPizza = () => { From ab521503cd12f680a36b76a79e1caa681641dffd Mon Sep 17 00:00:00 2001 From: Sofya Tuymedova Date: Fri, 4 Nov 2022 20:28:40 +0300 Subject: [PATCH 122/193] Question 34 Perhaps this answer is outdated. I've suggested an answer based on the information from [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/typeof) --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 7f3c0e3e..b6c8ee9a 100644 --- a/README.md +++ b/README.md @@ -1063,8 +1063,8 @@ console.log(typeof sayHi()); #### Answer: B The `sayHi` function returns the returned value of the immediately invoked function expression (IIFE). This function returned `0`, which is type `"number"`. - -FYI: there are only 7 built-in types: `null`, `undefined`, `boolean`, `number`, `string`, `object`, and `symbol`. `"function"` is not a type, since functions are objects, it's of type `"object"`. + +FYI: `typeof` can return the following list of values: `undefined`, `boolean`, `number`, `bigint`, `string`, `symbol`, `function` and `object`. Note that `typeof null` returns `"object"`.

From 1132d4f5b206f5c875f10cd0f8973b6c2c3c5d84 Mon Sep 17 00:00:00 2001 From: Sofya Tuymedova Date: Sun, 6 Nov 2022 16:57:43 +0300 Subject: [PATCH 123/193] Fix typo --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 7f3c0e3e..edd0bc3b 100644 --- a/README.md +++ b/README.md @@ -2223,7 +2223,7 @@ With the `+` operator, you can concatenate strings. In this case, we are concate function* startGame() { const answer = yield 'Do you love JavaScript?'; if (answer !== 'Yes') { - return "Oh wow... Guess we're gone here"; + return "Oh wow... Guess we're done here"; } return 'JavaScript loves you back ❤️'; } From 11767f4989f91fcba81dee8948027c529e61e958 Mon Sep 17 00:00:00 2001 From: Sofya Tuymedova Date: Mon, 14 Nov 2022 01:10:13 +0300 Subject: [PATCH 124/193] Paraphrase --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 7f3c0e3e..024609f3 100644 --- a/README.md +++ b/README.md @@ -2378,7 +2378,7 @@ console.log(shape); `Object.freeze` makes it impossible to add, remove, or modify properties of an object (unless the property's value is another object). -When we create the variable `shape` and set it equal to the frozen object `box`, `shape` also refers to a frozen object. You can check whether an object is frozen by using `Object.isFrozen`. In this case, `Object.isFrozen(shape)` returns true, since the variable `shape` has a reference to a frozen object. +When we create the variable `shape` and set it equal to the frozen object `box`, `shape` also refers to a frozen object. You can check whether an object is frozen by using `Object.isFrozen`. In this case, `Object.isFrozen(shape)` would return true, since the variable `shape` has a reference to a frozen object. Since `shape` is frozen, and since the value of `x` is not an object, we cannot modify the property `x`. `x` is still equal to `10`, and `{ x: 10, y: 20 }` gets logged. From ea5cf2f5962a6d4070c457eca56288ffe8c1e07d Mon Sep 17 00:00:00 2001 From: Sofya Tuymedova Date: Thu, 17 Nov 2022 21:48:58 +0300 Subject: [PATCH 125/193] Question 90 I believe we need to pass name as an argument here --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 7f3c0e3e..1c12bf23 100644 --- a/README.md +++ b/README.md @@ -2861,7 +2861,7 @@ console.log(typeof member); Classes are syntactical sugar for function constructors. The equivalent of the `Person` class as a function constructor would be: ```javascript -function Person() { +function Person(name) { this.name = name; } ``` From 9179c8fa2554c3e85430bae41e56ceb5500a2467 Mon Sep 17 00:00:00 2001 From: Alexander Zelenkov Date: Fri, 2 Dec 2022 14:40:31 +0700 Subject: [PATCH 126/193] fix: rus translation in #14 --- ru-RU/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ru-RU/README.md b/ru-RU/README.md index 3f1e1cd3..af347b16 100644 --- a/ru-RU/README.md +++ b/ru-RU/README.md @@ -458,7 +458,7 @@ console.log(sarah); #### Ответ: B -Все объекты имеют прототипы, кроме **базового объекта**. Базовый объект имеет доступ до некоторых методов и свойств, таких как `.toString`. Именно поэтому мы можем использовать встроенные методы JavaScript! Все эти методы доступны в прототипе. Если JavaScript не может найти метод непосредственно у объекта, он продолжает поиск по цепочке прототипов пока не найдет. +Все объекты имеют прототипы, кроме **базового объекта**. Базовый объект - это объект создаваемый пользователем или объект, который создается с ключевым словом `new`. Базовый объект имеет доступ к некоторым методам и свойствам, таким как `.toString`. Именно поэтому мы можем использовать встроенные методы JavaScript! Все эти методы доступны в прототипе. Если JavaScript не может найти метод непосредственно у объекта, он продолжает поиск по цепочке прототипов пока не найдет.

From e9c9ac285ba6b0c389e8927eb75cbda03f7c7001 Mon Sep 17 00:00:00 2001 From: SeyyedKhandon Date: Wed, 7 Dec 2022 18:50:09 +0300 Subject: [PATCH 127/193] fix(q76): :memo: the answer and its explanation Also covered the old question. --- README.md | 40 ++++++++++++++++++++++++++++++++++------ 1 file changed, 34 insertions(+), 6 deletions(-) diff --git a/README.md b/README.md index c3083d3a..0e60b375 100644 --- a/README.md +++ b/README.md @@ -2390,9 +2390,9 @@ Since `shape` is frozen, and since the value of `x` is not an object, we cannot ###### 76. What's the output? ```javascript -const { name: myName } = { name: 'Lydia' }; +const { firstName: myName } = { firstName: 'Lydia' }; -console.log(name); +console.log(firstName); ``` - A: `"Lydia"` @@ -2403,13 +2403,41 @@ console.log(name);
Answer

-#### Answer: C +#### Answer: D + +By using [destructuring assignment](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment) syntax we can unpack values from arrays, or properties from objects, into distinct variables: + +```javascript +const { firstName } = { firstName: 'Lydia' }; +// ES5 version: +// var firstName = { firstName: 'Lydia' }.firstName; + +console.log(firstName); // "Lydia" +``` + +Also, a property can be unpacked from an object and assigned to a variable with a different name than the object property: -When we unpack the property `name` from the object on the right-hand side, we assign its value `"Lydia"` to a variable with the name `myName`. +```javascript +const { firstName: myName } = { firstName: 'Lydia' }; +// ES5 version: +// var myName = { firstName: 'Lydia' }.firstName; + +console.log(myName); // "Lydia" +console.log(firstName); // Uncaught ReferenceError: firstName is not defined +``` + +Therefore, `firstName` does not exist as a variable, thus attempting to access its value will raise a `ReferenceError`. + +**Note:** Be aware of the `global scope` properties: -With `{ name: myName }`, we tell JavaScript that we want to create a new variable called `myName` with the value of the `name` property on the right-hand side. +```javascript +const { name: myName } = { name: 'Lydia' }; + +console.log(myName); // "lydia" +console.log(name); // "" +``` -Since we try to log `name`, a variable that is not defined, `undefined` is returned on the left side assignment. Later, the value of `Lydia` is stored through the destructuring assignment. +`name` is a global scope property, so when javascript is unable to find the name as a local variable, it looks at the _outer scopes_, which in this case is **window/global**, so it can be accessed via `window.name`.

From abce03f00aa8e351aa6c0bda94ba423b6a52bccf Mon Sep 17 00:00:00 2001 From: SeyyedKhandon Date: Wed, 7 Dec 2022 19:27:51 +0300 Subject: [PATCH 128/193] fix(q76): :memo: add nodejs to the answer Update the explanation for Nodejs --- README.md | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 0e60b375..ebc971ed 100644 --- a/README.md +++ b/README.md @@ -2434,10 +2434,12 @@ Therefore, `firstName` does not exist as a variable, thus attempting to access i const { name: myName } = { name: 'Lydia' }; console.log(myName); // "lydia" -console.log(name); // "" +console.log(name); // "" ----- Browser e.g. Chrome +console.log(name); // ReferenceError: name is not defined ----- NodeJS + ``` -`name` is a global scope property, so when javascript is unable to find the name as a local variable, it looks at the _outer scopes_, which in this case is **window/global**, so it can be accessed via `window.name`. +`name` is a global scope property in the `browser`, so when javascript is unable to find the name as a local variable, it looks at the _outer scopes_, which in this case is **window**, so it can be accessed via `window.name`. But, in `NodeJS`, there is no such property on the `global` object, thus attempting to access a non-existent variable will raise a `ReferenceError`.

From c1df5c43ff4f7c76aac37ca7635e5fdf4216faed Mon Sep 17 00:00:00 2001 From: SeyyedKhandon Date: Sun, 11 Dec 2022 17:23:23 +0300 Subject: [PATCH 129/193] =?UTF-8?q?fix(q76):=20=F0=9F=93=9D=20Update=20exp?= =?UTF-8?q?lanations=20for=20GlobalScope?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Add some references and update what is actually happening in the browsers and nodejs enviroment. --- README.md | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index ebc971ed..be88b72c 100644 --- a/README.md +++ b/README.md @@ -2439,7 +2439,11 @@ console.log(name); // ReferenceError: name is not defined ----- NodeJS ``` -`name` is a global scope property in the `browser`, so when javascript is unable to find the name as a local variable, it looks at the _outer scopes_, which in this case is **window**, so it can be accessed via `window.name`. But, in `NodeJS`, there is no such property on the `global` object, thus attempting to access a non-existent variable will raise a `ReferenceError`. +Whenever Javascript is unable to find a variable within the _current scope_, it climbs up the [Scope chain](https://github.com/getify/You-Dont-Know-JS/blob/2nd-ed/scope-closures/ch3.md) and searches for it and if it reaches the top-level scope, aka **Global scope**, and still doesn't find it, it will throw a `ReferenceError`. + +- In **Browsers** such as _Chrome_, `name` is a _deprecated global scope property_. In this example, the code is running inside _global scope_ and there is no user defined local variable for `name`, therefore it searches the predefined _variables/properties_ in the global scope which is in case of browsers, it searches through `window` object and it will extract the [window.name](https://developer.mozilla.org/en-US/docs/Web/API/Window/name) value which is equal to an **empty string**. + +- In **NodeJS**, there is no such property on the `global` object, thus attempting to access a non-existent variable will raise a [ReferenceError](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/Not_defined).

From 7e38c32dacbc2f50237d16be9908a51def6e32ef Mon Sep 17 00:00:00 2001 From: Alex Ivanov Date: Fri, 30 Dec 2022 15:21:51 +0300 Subject: [PATCH 130/193] translation: update RU Signed-off-by: Alex Ivanov --- ru-RU/README.md | 992 +++++++++++++++++++++++++++++++++++++++--------- 1 file changed, 819 insertions(+), 173 deletions(-) diff --git a/ru-RU/README.md b/ru-RU/README.md index 3f1e1cd3..e2c68785 100644 --- a/ru-RU/README.md +++ b/ru-RU/README.md @@ -1,36 +1,47 @@ -# Список (продвинутых) вопросов по JavaScript +
+ +

Вопросы по JavaScript

-Я ежедневно публикую вопросы по JavaScript с вариантами ответов в своем [Instagram](https://www.instagram.com/theavocoder), которые дублируются в этом репозитории. +--- + +Я (Lydia Hallie) ежедневно публикую вопросы по JavaScript с вариантами ответов в своем [Instagram](https://www.instagram.com/theavocoder) **сторис**, которые дублируются в этом репозитории! Последнее обновление:
12 июня. -От базового до продвинутого: проверьте, насколько хорошо вы знаете JavaScript, немного освежите свои знания или подготовьтесь к собеседованию! :muscle: :rocket: Я обновляю репозиторий еженедельно новыми вопросами. Последнее обновление: 18 ноября. +От базового до продвинутого: проверьте, насколько хорошо вы знаете JavaScript, немного освежите свои знания или подготовьтесь к собеседованию! :muscle: :rocket: Я регулярно обновляю этот репозиторий новыми вопросами. Ответы находятся в **свернутой секции** под каждым вопросом. Просто нажми на "Ответ", чтобы развернуть. Удачи! :heart: -Ответы находятся в свернутой секции ниже вопросов. Просто нажми на "Ответ", чтобы развернуть. Удачи! :heart: +Не стесняйтесь обращаться ко мне (Lydia Hallie)! 😊
+Instagram || Twitter || LinkedIn || Blog +
-Хотите получать электронную почту всякий раз, когда я добавляю новые вопросы?
-✨✉Подпишитесь на обновления✉✨ +| Не стесняйтесь использовать эти примеры в проектах! 😃 Я (Lydia Hallie) была бы _действительно_ признателена за ссылку на этот репозиторий. Я добавляю вопросы и объяснения, и сообщество очень помогает мне поддерживать и улучшать все это! 💪🏼 Спасибо и приятного просмотра! | +|---| +--- -Список доступных переводов: -- [🇸🇦 العربية](../ar-AR/README_AR.md) -- [🇪🇬 اللغة العامية](../ar-EG/README_ar-EG.md) -- [🇧🇦 Bosanski](../bs-BS/README-bs_BS.md) -- [🇩🇪 Deutsch](../de-DE/README.md) +
See 18 Available Translations 🇸🇦🇪🇬🇧🇦🇩🇪🇪🇸🇫🇷🇮🇩🇯🇵🇰🇷🇳🇱🇧🇷🇷🇺🇹🇭🇹🇷🇺🇦🇻🇳🇨🇳🇹🇼 +

+ +- [🇸🇦 العربية](./ar-AR/README_AR.md) +- [🇪🇬 اللغة العامية](./ar-EG/README_ar-EG.md) +- [🇧🇦 Bosanski](./bs-BS/README-bs_BS.md) +- [🇩🇪 Deutsch](./de-DE/README.md) +- [🇪🇸 Español](./es-ES/README-ES.md) +- [🇫🇷 Français](./fr-FR/README_fr-FR.md) +- [🇮🇩 Indonesia](./id-ID/README.md) +- [🇮🇹 Italiano](./it-IT/README.md) +- [🇯🇵 日本語](./ja-JA/README-ja_JA.md) +- [🇰🇷 한국어](./ko-KR/README-ko_KR.md) +- [🇳🇱 Nederlands](./nl-NL/README.md) +- [🇧🇷 Português Brasil](./pt-BR/README_pt_BR.md) - [🇬🇧 English](../README.md) -- [🇪🇸 Español](../es-ES/README-ES.md) -- [🇫🇷 Français](../fr-FR/README_fr-FR.md) -- [🇮🇩 Indonesia](../id-ID/README.md) -- [🇮🇹 Italiano](../it-IT/README.md) -- [🇯🇵 日本語](../ja-JA/README-ja_JA.md) -- [🇰🇷 한국어](../ko-KR/README-ko_KR.md) -- [🇳🇱 Nederlands](../nl-NL/README.md) -- [🇧🇷 Português Brasil](../pt-BR/README_pt_BR.md) -- [🇹🇭 ไทย](../th-TH/README-th_TH.md) -- [🇹🇷 Türkçe](../tr-TR/README-tr_TR.md) -- [🇺🇦 Українська мова](../uk-UA/README.md) -- [🇻🇳 Tiếng Việt](../vi-VI/README-vi.md) -- [🇨🇳 简体中文](../zh-CN/README-zh_CN.md) -- [🇹🇼 繁體中文](../zh-TW/README_zh-TW.md) +- [🇹🇭 ไทย](./th-TH/README-th_TH.md) +- [🇹🇷 Türkçe](./tr-TR/README-tr_TR.md) +- [🇺🇦 Українська мова](./uk-UA/README.md) +- [🇻🇳 Tiếng Việt](./vi-VI/README-vi.md) +- [🇨🇳 简体中文](./zh-CN/README-zh_CN.md) +- [🇹🇼 繁體中文](./zh-TW/README_zh-TW.md) +

+
--- @@ -107,8 +118,8 @@ const shape = { perimeter: () => 2 * Math.PI * this.radius }; -shape.diameter(); -shape.perimeter(); +console.log(shape.diameter()); +console.log(shape.perimeter()); ``` - A: `20` и `62.83185307179586` @@ -121,7 +132,7 @@ shape.perimeter(); #### Ответ: B -Заметь, что `diameter` это обычная функция, в то время как `perimeter` это стрелочная функция. +Заметьте, что `diameter` это обычная функция, в то время как `perimeter` это стрелочная функция. У стрелочных функций значение `this` указывает на окружающую область видимости, в отличие от обычных функций! Это значит, что при вызове `perimeter` значение `this` у этой функции указывает не на объект `shape`, а на внешнюю область видимости (например, window). @@ -136,7 +147,7 @@ shape.perimeter(); ```javascript +true; -!"Lydia"; +!'Lydia'; ``` - A: `1` и `false` @@ -161,11 +172,11 @@ shape.perimeter(); ```javascript const bird = { - size: "small" + size: 'small' }; const mouse = { - name: "Mickey", + name: 'Mickey', small: true }; ``` @@ -193,15 +204,14 @@ JavaScript интерпретирует (или распаковывает) оп --- - ###### 6. Что будет в консоли? ```javascript -let c = { greeting: "Hey!" }; +let c = { greeting: 'Hey!' }; let d; d = c; -c.greeting = "Hello"; +c.greeting = 'Hello'; console.log(d.greeting); ``` @@ -222,7 +232,7 @@ console.log(d.greeting); -Когда ты изменяешь один объект, то изменяются значения всех ссылок, указывающих на этот объект. +Когда вы изменяете один объект, то изменяются значения всех ссылок, указывающих на этот объект.

@@ -251,7 +261,7 @@ console.log(b === c); #### Ответ: C -`new Number()` это встроенный конструктор функции. И хотя он выглядит как число, это не настоящее число: у него есть ряд дополнительных фич и это объект. +`new Number()` это встроенный конструктор функции. И хотя он выглядит как число, это не настоящее число: у него есть ряд дополнительных особеннстей, и это объект. Оператор `==` разрешает приведение типов, он проверяет равенство _значений_. Оба значения равны `3`, поэтому возвращается `true`. @@ -271,13 +281,13 @@ class Chameleon { return this.newColor; } - constructor({ newColor = "green" } = {}) { + constructor({ newColor = 'green' } = {}) { this.newColor = newColor; } } -const freddie = new Chameleon({ newColor: "purple" }); -freddie.colorChange("orange"); +const freddie = new Chameleon({ newColor: 'purple' }); +freddie.colorChange('orange'); ``` - A: `orange` @@ -290,7 +300,7 @@ freddie.colorChange("orange"); #### Ответ: D -Функция `colorChange` является статичной. Статичные методы не имеют доступа к экземплярам класса. Так как `freddie` это экземпляр, то статичный метод там не доступен. Поэтому выбрасывается ошибка `TypeError`. +Функция `colorChange` является статической. Статические методы предназначены для работы только в конструкторе, в котором они созданы, и не могут передаваться каким-либо дочерним элементам или вызываться в экземплярах класса. Так как `freddie` является экземпляром класса `Chameleon`, функция не может быть вызвана для него. Будет выдана ошибка `TypeError`.

@@ -327,10 +337,10 @@ console.log(greetign); ```javascript function bark() { - console.log("Woof!"); + console.log('Woof!'); } -bark.animal = "dog"; +bark.animal = 'dog'; ``` - A: Ничего, всё в порядке! @@ -360,7 +370,7 @@ function Person(firstName, lastName) { this.lastName = lastName; } -const member = new Person("Lydia", "Hallie"); +const member = new Person('Lydia', 'Hallie'); Person.getFullName = function () { return `${this.firstName} ${this.lastName}`; } @@ -378,7 +388,9 @@ console.log(member.getFullName()); #### Ответ: A -Нельзя добавлять свойства конструктору, как обычному объекту. Если нужно добавить фичу всем объектам, то необходимо использовать прототипы. В данном случае +В JavaScript функции являются объектами, поэтому метод `getFullName` добавляется к самому объекту функции-конструктора. По этой причине мы можем вызвать `Person.getFullName()`, но `member.getFullName` выдает `TypeError`. + +Если вы хотите, чтобы метод был доступен для всех экземпляров объекта, вы должны добавить его в свойство прототипа: ```js Person.prototype.getFullName = function () { @@ -386,8 +398,6 @@ Person.prototype.getFullName = function () { } ``` -сделает метод `member.getFullName()` рабочим. В чем тут преимущество? Предположим, что мы добавили этот метод к конструктору. Возможно, не каждому экземпляру `Person` нужен этот метод. Это приведет к большим потерям памяти, т.к. все экземпляры будут иметь это свойство. Напротив, если мы добавим этот метод только к прототипу, у нас будет только одно место в памяти, к которому смогут обращаться все экземпляры! -

@@ -401,8 +411,8 @@ function Person(firstName, lastName) { this.lastName = lastName; } -const lydia = new Person("Lydia", "Hallie"); -const sarah = Person("Sarah", "Smith"); +const lydia = new Person('Lydia', 'Hallie'); +const sarah = Person('Sarah', 'Smith'); console.log(lydia); console.log(sarah); @@ -458,7 +468,7 @@ console.log(sarah); #### Ответ: B -Все объекты имеют прототипы, кроме **базового объекта**. Базовый объект имеет доступ до некоторых методов и свойств, таких как `.toString`. Именно поэтому мы можем использовать встроенные методы JavaScript! Все эти методы доступны в прототипе. Если JavaScript не может найти метод непосредственно у объекта, он продолжает поиск по цепочке прототипов пока не найдет. +Все объекты имеют прототипы, кроме **базового объекта**. Базовый объект — это объект, созданный пользователем, или объект, созданный с использованием ключевого слова `new`. Базовый объект имеет доступ к некоторым методам и свойствам, таким как `.toString`. Вот почему вы можете использовать встроенные методы JavaScript! Все такие способы доступны в прототипе. Хотя JavaScript не может найти метод непосредственно в вашем объекте, он идет вниз по цепочке прототипов и находит его там, что делает его доступным.

@@ -472,7 +482,7 @@ function sum(a, b) { return a + b; } -sum(1, "2"); +sum(1, '2'); ``` - A: `NaN` @@ -539,7 +549,7 @@ function getPersonInfo(one, two, three) { console.log(three); } -const person = "Lydia"; +const person = 'Lydia'; const age = 21; getPersonInfo`${person} is ${age} years old`; @@ -554,7 +564,7 @@ getPersonInfo`${person} is ${age} years old`; #### Ответ: B -При использовании тегированных шаблонных литералов первым аргументом всегда будет массив строковых значений. Оставшимися аргументами будут значения переданных выражений! +При использовании [шаблонных строк](https://developer.mozilla.org/ru/docs/Web/JavaScript/Reference/Template_literals) первым аргументом всегда будет массив строковых значений. Оставшимися аргументами будут значения переданных выражений!

@@ -566,9 +576,9 @@ getPersonInfo`${person} is ${age} years old`; ```javascript function checkAge(data) { if (data === { age: 18 }) { - console.log("Ты взрослый!"); + console.log('Ты взрослый!'); } else if (data == { age: 18 }) { - console.log("Ты все еще взрослый."); + console.log('Ты все еще взрослый.'); } else { console.log(`Хмм.. Кажется, у тебя нет возраста.`); } @@ -628,7 +638,7 @@ getAge(21); ```javascript function getAge() { - "use strict"; + 'use strict'; age = 21; console.log(age); } @@ -656,7 +666,7 @@ getAge(); ###### 21. Чему будет равно `sum`? ```javascript -const sum = eval("10*10+5"); +const sum = eval('10*10+5'); ``` - A: `105` @@ -679,7 +689,7 @@ const sum = eval("10*10+5"); ###### 22. Как долго будет доступен cool_secret? ```javascript -sessionStorage.setItem("cool_secret", 123); +sessionStorage.setItem('cool_secret', 123); ``` - A: Всегда, данные не потеряются. @@ -732,12 +742,12 @@ console.log(num); ###### 24. Каким будет результат? ```javascript -const obj = { 1: "a", 2: "b", 3: "c" }; +const obj = { 1: 'a', 2: 'b', 3: 'c' }; const set = new Set([1, 2, 3, 4, 5]); -obj.hasOwnProperty("1"); +obj.hasOwnProperty('1'); obj.hasOwnProperty(1); -set.has("1"); +set.has('1'); set.has(1); ``` @@ -763,7 +773,7 @@ set.has(1); ###### 25. Что будет в консоли? ```javascript -const obj = { a: "one", b: "two", a: "three" }; +const obj = { a: 'one', b: 'two', a: 'three' }; console.log(obj); ``` @@ -788,7 +798,7 @@ console.log(obj); - A: Да - B: Нет -- C: Это зависит +- C: Это зависит от ...
Ответ

@@ -832,10 +842,10 @@ for (let i = 1; i < 5; i++) { ```javascript String.prototype.giveLydiaPizza = () => { - return "Just give Lydia pizza already!"; + return 'Just give Lydia pizza already!'; }; -const name = "Lydia"; +const name = 'Lydia'; console.log(name.giveLydiaPizza()) ``` @@ -861,8 +871,8 @@ console.log(name.giveLydiaPizza()) ```javascript const a = {}; -const b = { key: "b" }; -const c = { key: "c" }; +const b = { key: 'b' }; +const c = { key: 'c' }; a[b] = 123; a[c] = 456; @@ -894,9 +904,9 @@ console.log(a[b]); ###### 30. Каким будет результат? ```javascript -const foo = () => console.log("First"); -const bar = () => setTimeout(() => console.log("Second")); -const baz = () => console.log("Third"); +const foo = () => console.log('First'); +const bar = () => setTimeout(() => console.log('Second')); +const baz = () => console.log('Third'); bar(); foo(); @@ -1003,7 +1013,7 @@ WebAPI не может добавлять содержимое в стек ко ###### 33. Что будет в консоли? ```javascript -const person = { name: "Lydia" }; +const person = { name: 'Lydia' }; function sayHi(age) { console.log(`${this.name} is ${age}`); @@ -1039,7 +1049,7 @@ function sayHi() { return (() => 0)(); } -typeof sayHi(); +console.log(typeof sayHi()); ``` - A: `"object"` @@ -1055,6 +1065,7 @@ typeof sayHi(); Функция `sayHi` возвращает значение, возвращаемое из немедленно вызываемого функционального выражения (IIFE). Результатом является `0` типа `"number"`. Для информации: в JS 8 встроенных типов: `null`, `undefined`, `boolean`, `number`, `string`, `object`, `symbol` и `bigint`. `"function"` не является отдельным типом, т.к. функции являются объектами типа `"object"`. +

@@ -1081,14 +1092,16 @@ undefined; #### Ответ: A -Есть только шесть "ложных" значений: +Есть только восемь (8) "ложных" значений: - `undefined` - `null` - `NaN` -- `0` -- `''` (пустая строка) - `false` +- `''` (пустая строка) +- `0` +- `-0` +- `0n` (BigInt(0)) Конструкторы функций, такие как `new Number` и `new Boolean` являются "истинными". @@ -1187,7 +1200,7 @@ console.log(numbers); --- -###### 39. Всё в JavaScript это +###### 39. Всё в JavaScript это... - A: примитив или объект - B: функция или объект @@ -1244,7 +1257,7 @@ console.log(numbers); ```javascript !!null; -!!""; +!!''; !!1; ``` @@ -1269,10 +1282,10 @@ console.log(numbers); --- -###### 42. Что возвращает метод `setInterval`? +###### 42. Что возвращает метод `setInterval` в браузере? ```javascript -setInterval(() => console.log("Hi"), 1000); +setInterval(() => console.log('Hi'), 1000); ``` - A: уникальный id @@ -1295,7 +1308,7 @@ setInterval(() => console.log("Hi"), 1000); ###### 43. Каким будет результат? ```javascript -[..."Lydia"]; +[...'Lydia']; ``` - A: `["L", "y", "d", "i", "a"]` @@ -1354,11 +1367,11 @@ console.log(gen.next().value); ```javascript const firstPromise = new Promise((res, rej) => { - setTimeout(res, 500, "один"); + setTimeout(res, 500, 'один'); }); const secondPromise = new Promise((res, rej) => { - setTimeout(res, 100, "два"); + setTimeout(res, 100, 'два'); }); Promise.race([firstPromise, secondPromise]).then(res => console.log(res)); @@ -1384,7 +1397,7 @@ Promise.race([firstPromise, secondPromise]).then(res => console.log(res)); ###### 46. Каким будет результат? ```javascript -let person = { name: "Lydia" }; +let person = { name: 'Lydia' }; const members = [person]; person = null; @@ -1424,7 +1437,7 @@ console.log(members); ```javascript const person = { - name: "Lydia", + name: 'Lydia', age: 21 }; @@ -1453,7 +1466,7 @@ for (const item in person) { ###### 48. Каким будет результат? ```javascript -console.log(3 + 4 + "5"); +console.log(3 + 4 + '5'); ``` - A: `"345"` @@ -1506,7 +1519,7 @@ const num = parseInt("7*6", 10); ```javascript [1, 2, 3].map(num => { - if (typeof num === "number") return; + if (typeof num === 'number') return; return num * 2; }); ``` @@ -1534,12 +1547,12 @@ const num = parseInt("7*6", 10); ```javascript function getInfo(member, year) { - member.name = "Lydia"; + member.name = 'Lydia'; year = 1998; } -const person = { name: "Sarah" }; -const birthYear = "1997"; +const person = { name: 'Sarah' }; +const birthYear = '1997'; getInfo(person, birthYear); @@ -1571,15 +1584,15 @@ console.log(person, birthYear); ```javascript function greeting() { - throw "Hello world!"; + throw 'Hello world!'; } function sayHi() { try { const data = greeting(); - console.log("It worked!", data); + console.log('It worked!', data); } catch (e) { - console.log("Oh no an error:", e); + console.log('Oh no an error:', e); } } @@ -1609,8 +1622,8 @@ sayHi(); ```javascript function Car() { - this.make = "Lamborghini"; - return { make: "Maserati" }; + this.make = 'Lamborghini'; + return { make: 'Maserati' }; } const myCar = new Car(); @@ -1686,7 +1699,7 @@ Dog.prototype.bark = function() { console.log(`Woof I am ${this.name}`); }; -const pet = new Dog("Mara"); +const pet = new Dog('Mara'); pet.bark(); @@ -1751,7 +1764,7 @@ export default counter; ```javascript // index.js -import myCounter from "./counter"; +import myCounter from './counter'; myCounter += 1; @@ -1780,7 +1793,7 @@ console.log(myCounter); ###### 58. Какой будет вывод? ```javascript -const name = "Lydia"; +const name = 'Lydia'; age = 21; console.log(delete name); @@ -1851,7 +1864,7 @@ console.log(y); ###### 60. Какой будет вывод? ```javascript -const user = { name: "Lydia", age: 21 }; +const user = { name: 'Lydia', age: 21 }; const admin = { admin: true, ...user }; console.log(admin); @@ -1877,9 +1890,9 @@ console.log(admin); ###### 61. Какой будет вывод? ```javascript -const person = { name: "Lydia" }; +const person = { name: 'Lydia' }; -Object.defineProperty(person, "age", { value: 21 }); +Object.defineProperty(person, 'age', { value: 21 }); console.log(person); console.log(Object.keys(person)); @@ -1908,12 +1921,12 @@ console.log(Object.keys(person)); ```javascript const settings = { - username: "lydiahallie", + username: 'lydiahallie', level: 19, health: 90 }; -const data = JSON.stringify(settings, ["level", "health"]); +const data = JSON.stringify(settings, ['level', 'health']); console.log(data); ``` @@ -2037,6 +2050,7 @@ multiply(value); Если вы не возвращаете значение из функции, она возвращает значение `undefined`. При следующем вызове аккумулятор равен `undefined`, а текущее значение равно 3. `undefined` и `3` будут зарегистрированы. При четвертом вызове мы снова не возвращаемся из функции обратного вызова. Аккумулятор снова равен `undefined`, а текущее значение равно `4`. `undefined` и` 4` будут зарегистрированы. +

@@ -2090,6 +2104,7 @@ class Labrador extends Dog { С ключевым словом `super` мы вызываем конструктор родительского класса с заданными аргументами. Конструктор родителя получает аргумент `name`, поэтому нам нужно передать `name` в `super`. Класс `Labrador` получает два аргумента: `name`, поскольку он расширяет `Dog`, и `size` в качестве дополнительного свойства класса `Labrador`. Они оба должны быть переданы в функцию конструктора в `Labrador`, что делается правильно с помощью конструктора 2. +

@@ -2155,7 +2170,7 @@ console.log(Symbol('foo') === Symbol('foo')) ###### 69. Какой будет вывод? ```javascript -const name = "Lydia Hallie" +const name = 'Lydia Hallie' console.log(name.padStart(13)) console.log(name.padStart(2)) ``` @@ -2206,11 +2221,11 @@ console.log("🥑" + "💻"); ```javascript function* startGame() { - const answer = yield "Do you love JavaScript?"; - if (answer !== "Yes") { - return "Oh wow... Guess we're gone here"; + const answer = yield 'Do you love JavaScript?'; + if (answer !== 'Yes') { + return 'Oh wow... Guess we're gone here'; } - return "JavaScript loves you back ❤️"; + return 'JavaScript loves you back ❤️'; } const game = startGame(); @@ -2278,7 +2293,7 @@ console.log(String.raw`Hello\nworld`); ```javascript async function getData() { - return await Promise.resolve("I made it!"); + return await Promise.resolve('I made it!'); } const data = getData(); @@ -2315,7 +2330,7 @@ function addToList(item, list) { return list.push(item); } -const result = addToList("apple", ["banana"]); +const result = addToList('apple', ['banana']); console.log(result); ``` @@ -2375,7 +2390,7 @@ console.log(shape); ###### 76. Какой будет вывод? ```javascript -const { name: myName } = { name: "Lydia" }; +const { name: myName } = { name: 'Lydia' }; console.log(name); ``` @@ -2476,7 +2491,7 @@ console.log(addFunction(5 * 2)); ###### 79. Какой будет вывод? ```javascript -const myLifeSummedUp = ["☕", "💻", "🍷", "🍫"] +const myLifeSummedUp = ['☕', '💻', '🍷', '🍫'] for (let item in myLifeSummedUp) { console.log(item) @@ -2572,13 +2587,13 @@ console.log(sayHi()) ###### 82. Какой будет вывод? ```javascript -var status = "😎" +var status = '😎' setTimeout(() => { - const status = "😍" + const status = '😍' const data = { - status: "🥑", + status: '🥑', getStatus() { return this.status } @@ -2603,7 +2618,6 @@ setTimeout(() => { С помощью метода `call` мы можем изменить объект, на который ссылается ключевое слово `this`. В **функциях** ключевое слово `this` относится к _объекту, которому принадлежит функция_. Мы объявили функцию `setTimeout` для объекта _global_, поэтому в функции `setTimeout` ключевое слово `this` ссылается на объект _global_. В глобальном объекте есть переменная с именем _status_ со значением `"😎"`. При регистрации `this.status` выводится `"😎"`. -

@@ -2613,12 +2627,12 @@ setTimeout(() => { ```javascript const person = { - name: "Lydia", + name: 'Lydia', age: 21 } let city = person.city -city = "Amsterdam" +city = 'Amsterdam' console.log(person) ``` @@ -2738,7 +2752,7 @@ function getName(name) { ###### 87. Какой будет вывод? ```javascript -console.log("I want pizza"[0]) +console.log('I want pizza'[0]) ``` - A: `"""` @@ -2793,11 +2807,11 @@ sum(10) ```javascript // module.js -export default () => "Hello world" -export const name = "Lydia" +export default () => 'Hello world' +export const name = 'Lydia' // index.js -import * as data from "./module" +import * as data from './module' console.log(data) ``` @@ -2830,7 +2844,7 @@ class Person { } } -const member = new Person("John") +const member = new Person('John') console.log(typeof member) ``` @@ -2890,10 +2904,11 @@ console.log(newList.push(5)) ```javascript function giveLydiaPizza() { - return "Here is pizza!" + return 'Here is pizza!' } -const giveLydiaChocolate = () => "Here's chocolate... now go hit the gym already." +const giveLydiaChocolate = () => + "Here's chocolate... now go hit the gym already." console.log(giveLydiaPizza.prototype) console.log(giveLydiaChocolate.prototype) @@ -2920,7 +2935,7 @@ console.log(giveLydiaChocolate.prototype) ```javascript const person = { - name: "Lydia", + name: 'Lydia', age: 21 } @@ -2984,6 +2999,7 @@ getItems(["banana", "apple"], "pear", "orange") ``` Приведенный выше пример работает. Это возвращает массив `[ 'banana', 'apple', 'orange', 'pear' ]` +

@@ -2993,13 +3009,10 @@ getItems(["banana", "apple"], "pear", "orange") ```javascript function nums(a, b) { - if - (a > b) - console.log('a is bigger') - else - console.log('b is bigger') + if (a > b) console.log('a is bigger') + else console.log('b is bigger') return - a + b + a + b; } console.log(nums(4, 2)) @@ -3037,13 +3050,13 @@ console.log(nums(1, 2)) ```javascript class Person { constructor() { - this.name = "Lydia" + this.name = 'Lydia' } } Person = class AnotherPerson { constructor() { - this.name = "Sarah" + this.name = 'Sarah' } } @@ -3123,15 +3136,15 @@ console.log(getUser(user)) Функция `getList` получает массив в качестве аргумента. Между скобками функции `getList` мы сразу же деструктурируем этот массив. Вы можете увидеть это как: - `[x, ...y] = [1, 2, 3, 4]` +`[x, ...y] = [1, 2, 3, 4]` С помощью оставшихся параметров `... y` мы помещаем все "оставшиеся" аргументы в массив. Остальные аргументы - это `2`, `3` и `4` в этом случае. Значение `y` является массивом, содержащим все остальные параметры. В этом случае значение `x` равно `1`, поэтому, мы видим в логе `[x, y]`, `[1, [2, 3, 4]]`. -Функция `getUser` получает объект. В случае функций со стрелками мы не можем писать фигурные скобки, если мы просто возвращаем одно значение. Однако, если вы хотите вернуть _объект_ из стрелочной функции, вы должны написать его в скобках, в противном случае никакое значение не возвращается! Следующая функция вернула бы объект: +Функция `getUser` получает объект. В стрелочных функциях нам _не нужно_ писать фигурные скобки, если мы просто возвращаем одно значение. Однако, если вы хотите мгновенно вернуть _object_ из стрелочной функции, вы должны написать его между круглыми скобками, иначе все, что находится между двумя фигурными скобками, будет интерпретироваться как оператор блока. В этом случае код между фигурными скобками не является допустимым кодом JavaScript, поэтому выдается `SyntaxError`. -```const getUser = user => ({ name: user.name, age: user.age })``` +Следующая функция вернула бы объект: -Поскольку в этом случае значение не возвращается, функция возвращает значение `undefined`. +```const getUser = user => ({ name: user.name, age: user.age })```

@@ -3141,7 +3154,7 @@ console.log(getUser(user)) ###### 99. Какой будет вывод? ```javascript -const name = "Lydia" +const name = 'Lydia' console.log(name()) ``` @@ -3200,7 +3213,7 @@ You should${'' && `n't`} see a therapist after so much JavaScript lol` ```javascript const one = (false || {} || null) -const two = (null || false || "") +const two = (null || false || '') const three = ([] || 0 || true) console.log(one, two, three) @@ -3258,7 +3271,7 @@ secondFunction() #### Ответ: D -С обещанием мы в основном говорим: "Я хочу выполнить эту функцию и откладываю ее, пока она выполняется, поскольку это может занять некоторое время". Только когда определенное значение разрешено (или отклонено), и когда стек вызовов пуст, я хочу использовать это значение. +С обещанием мы в основном говорим: _"Я хочу выполнить эту функцию и откладываю ее, пока она выполняется, поскольку это может занять некоторое время. Только когда определенное значение разрешено (или отклонено), и когда стек вызовов пуст, я хочу использовать это значение_". Мы можем получить это значение с помощью ключевого слова `.then` и `await` в функции `async`. Хотя мы можем получить значение обещания с помощью `.then` и `await`, они работают немного по-разному. @@ -3279,8 +3292,8 @@ secondFunction() const set = new Set() set.add(1) -set.add("Lydia") -set.add({ name: "Lydia" }) +set.add('Lydia') +set.add({ name: 'Lydia' }) for (let item of set) { console.log(item + 2) @@ -3340,13 +3353,13 @@ Promise.resolve(5) ```javascript function compareMembers(person1, person2 = person) { if (person1 !== person2) { - console.log("Not the same!") + console.log('Not the same!') } else { - console.log("They are the same!") + console.log('They are the same!') } } -const person = { name: "Lydia" } +const person = { name: 'Lydia' } compareMembers(person) ``` @@ -3385,7 +3398,7 @@ const colorConfig = { yellow: false, } -const colors = ["pink", "red", "blue"] +const colors = ['pink', 'red', 'blue'] console.log(colorConfig.colors[1]) ``` @@ -3464,7 +3477,7 @@ emojis.splice(1, 2, '✨') --- -###### 109. Какое значение будет на выходе? +###### 109. Какое значение будет на выходе? ```javascript const food = ['🍕', '🍫', '🥑', '🍔'] @@ -3524,7 +3537,7 @@ const jsonArray = JSON.stringify([1, 2, 3]) // '[1, 2, 3]' JSON.parse(jsonArray) // [1, 2, 3] // Преобразование объекта в допустимый JSON, затем преобразование строки JSON в значение JavaScript: -const jsonArray = JSON.stringify({ name: "Lydia" }) // '{"name":"Lydia"}' +const jsonArray = JSON.stringify({ name: 'Lydia' }) // '{"name":"Lydia"}' JSON.parse(jsonArray) // { name: 'Lydia' } ``` @@ -3556,7 +3569,7 @@ getName() #### Ответ: D -Каждая функция имеет свой собственный _контекст исполнения_ (или _область действия_). Функция `getName` сначала ищет в своем собственном контексте (области действия), чтобы увидеть, содержит ли она переменную `name`, к которой мы пытаемся получить доступ. В этом случае функция `getName` содержит собственную переменную `name`: мы объявляем переменную `name` с ключевым словом `let` и значением `'Sarah'`. +Каждая функция имеет свой собственный _контекст исполнения_ (или _область видимости_). Функция `getName` сначала ищет в своем собственном контексте (области видимости), чтобы увидеть, содержит ли она переменную `name`, к которой мы пытаемся получить доступ. В этом случае функция `getName` содержит собственную переменную `name`: мы объявляем переменную `name` с ключевым словом `let` и значением `'Sarah'`. Переменные с ключевым словом `let` (и `const`) поднимаются в начало функции, в отличие от `var`, которые не инициализируется. Они недоступны до того, как мы объявим (инициализируем) их строку. Это называется "временной мертвой зоной". Когда мы пытаемся получить доступ к переменным до их объявления, JavaScript выдает `ReferenceError`. @@ -3673,7 +3686,11 @@ config = null #### Ответ: C -Обычно, когда мы устанавливаем объекты равными `null`, эти объекты получают метку _собрано в мусор_, так как больше нет ссылок на этот объект. Однако, поскольку функция обратного вызова в `setInterval` является стрелочной функцией (таким образом, привязанной к объекту `config`), функция обратного вызова все еще содержит ссылку на объект `config`. Пока есть ссылка, объект не будет собран в мусор. Поскольку сборщик мусора не отрабатывает, функция обратного вызова `setInterval` будет по-прежнему вызываться каждые 1000 мс (1с). +Обычно, когда мы устанавливаем объекты равными `null`, эти объекты получают статус _собрано в мусор_, так как больше нет ссылок на этот объект. Однако, поскольку функция обратного вызова внутри `setInterval` является стрелочной функцией (таким образом, привязанной к объекту `config`), функция обратного вызова по-прежнему содержит ссылку на объект `config`. +Пока есть ссылка, объект не будет собирать мусор. +Так как это интервал, установка `config` в `null` или `delete`-ing `config.alert` не приведет к сбору мусора для интервала, поэтому интервал все равно будет вызываться. +Его следует очистить с помощью `clearInterval(config.alert)`, чтобы удалить его из памяти. +Поскольку он не был очищен, функция обратного вызова `setInterval` будет по-прежнему вызываться каждые 1000мс (1с).

@@ -3720,14 +3737,14 @@ myMap.get(() => 'greeting') ```javascript const person = { - name: "Lydia", + name: 'Lydia', age: 21 } const changeAge = (x = { ...person }) => x.age += 1 const changeAgeAndName = (x = { ...person }) => { x.age += 1 - x.name = "Sarah" + x.name = 'Sarah' } changeAge(person) @@ -3757,7 +3774,7 @@ console.log(person) --- -###### 117. Какой из следующих наборов параметров вернет `6`? +###### 117. Какой из следующих наборов параметров вернет `6`? ```javascript function sumValues(x, y, z) { @@ -3812,11 +3829,11 @@ console.log(list[(num += 1)]); ```javascript const person = { - firstName: "Lydia", - lastName: "Hallie", + firstName: 'Lydia', + lastName: 'Hallie', pet: { - name: "Mara", - breed: "Dutch Tulip Hound" + name: 'Mara', + breed: 'Dutch Tulip Hound' }, getFullName() { return `${this.firstName} ${this.lastName}`; @@ -3854,10 +3871,10 @@ console.log(member.getLastName?.()); ###### 120. Что будет на выходе? ```javascript -const groceries = ["banana", "apple", "peanuts"]; +const groceries = ['banana', 'apple', 'peanuts']; -if (groceries.indexOf("banana")) { - console.log("We have to buy bananas!"); +if (groceries.indexOf('banana')) { + console.log('We have to buy bananas!'); } else { console.log(`We don't have to buy bananas!`); } @@ -3913,10 +3930,10 @@ console.log(config.language); ###### 122. Что будет на выходе? ```javascript -const name = "Lydia Hallie"; +const name = 'Lydia Hallie'; -console.log(!typeof name === "object"); -console.log(!typeof name === "string"); +console.log(!typeof name === 'object'); +console.log(!typeof name === 'string'); ``` - A: `false` `true` @@ -4129,7 +4146,7 @@ const randomValue = 21; function getInfo() { console.log(typeof randomValue); - const randomValue = "Lydia Hallie"; + const randomValue = 'Lydia Hallie'; } getInfo(); @@ -4155,7 +4172,7 @@ getInfo(); ###### 130. Что будет на выходе? ```javascript -const myPromise = Promise.resolve("Woah some cool data"); +const myPromise = Promise.resolve('Woah some cool data'); (async () => { try { @@ -4163,7 +4180,7 @@ const myPromise = Promise.resolve("Woah some cool data"); } catch { throw new Error(`Oops didn't work`); } finally { - console.log("Oh finally!"); + console.log('Oh finally!'); } })(); ``` @@ -4188,7 +4205,7 @@ const myPromise = Promise.resolve("Woah some cool data"); ###### 131. Что будет на выходе? ```javascript -const emojis = ["🥑", ["✨", "✨", ["🍕", "🍕"]]]; +const emojis = ['🥑', ['✨', '✨', ['🍕', '🍕']]]; console.log(emojis.flat(1)); ``` @@ -4290,15 +4307,19 @@ funcTwo(); #### Ответ: D -Сначала мы вызываем функцию `funcOne`. В первой строке `funcOne` происходит вызов обещания `myPromise`, которое является _асинхронной_ операцией. Пока движок занят обработкой обещания, он продолжает выполнение функции `funcOne`. Следующая строка является _асинхронной_ функцией `setTimeout`, поэтому её обратный вызов будет отправлен в Web API. (см. мою статью о цикле событий [здесь](https://dev.to/lydiahallie/javascript-visualized-event-loop-3dif).) +Сначала мы вызываем `funcOne`. В первой строке `funcOne` мы вызываем _асинхронную_ функцию `setTimeout`, из которой обратный вызов отправляется в веб-API. (см. мою статью о цикле событий здесь.) -Обещание, как и таймер, является асинхронной операцией, поэтому функция продолжит выполняться несмотря на обработку обещания и обратного вызова `setTimeout`. Выходит так, что `Last line!` попадет в консоль первой, т.к. не является асинхронной операцией. Далее, в следующей строке `funcOne`, обещание будет выполнено и `Promise!` выводится в консоль. Однако, т.к. далее мы вызываем `funcTwo()`, стэк вызывов не будет пустым, из-за чего обратный вызов функции `setTimeout` _пока_ не будет добавлен в стэк вызовов. +Затем мы вызываем обещание `myPromise`, которое является _асинхронной_ операцией. -В первой строке `funcTwo` мы _ожидаем_ выполнения обещания myPromise. С помощью ключевого слова `await` мы приостанавливаем выполнение функции пока обещание не будет выполнено (или отклонено). Затем выводим в консоль _ожидаемое_ значение `res` (т.к. предыдущее обещание вернуло обещание). После чего в консоль попадает `Promise!`. +И обещание, и тайм-аут являются асинхронными операциями, функция продолжает работать, пока она занята выполнением обещания и обработкой обратного вызова `setTimeout`. Это означает, что `Last line 1!` регистрируется первой, так как это не асинхронная операция. -Следующая строка является _асинхронной_ функцией `setTimeout`, которая отправляет обратный вызов в Web API. +Поскольку стек вызовов еще не пуст, функция `setTimeout` и обещание в `funcOne` еще не могут быть добавлены в стек вызовов. -Мы перешли к следующей строке функции `funcTwo` которая выводит в консоль `Last line!`. Теперь, когда стэк вызовов извлечен из `funcTwo`, он становится пустым. Обратные вызовы, которые ожидали очереди (`() => console.log("Timeout!")` из `funcOne`, и `() => console.log("Timeout!")` из `funcTwo`) добавлены в стэк вызовов один за другим. Первый вызов выведет в консоль `Timeout!` и будет извлечен из стэка. Следующий вызов также выведет `Timeout!` и тоже будет извлечен из стэка вызовов. Лог будет равен `Last line! Promise! Promise! Last line! Timeout! Timeout!` +В `funcTwo` переменная `res` получает `Promise`, потому что `Promise.resolve(Promise.resolve('Promise'))` эквивалентно `Promise.resolve('Promise')`, так как разрешение обещания просто разрешает его стоимость. `await` в этой строке останавливает выполнение функции до тех пор, пока она не получит разрешение промиса, а затем продолжает работать синхронно до завершения, поэтому `Promise 2!`, а затем `Last line 2!` регистрируются, а `setTimeout` отправляется в Web API. + +Тогда стек вызовов пуст. Промисы — это _микрозадачи_, поэтому они решаются первыми, когда стек вызовов пуст, поэтому `Promise 1!` регистрируется. + +Теперь, поскольку `funcTwo` выталкивается из стека вызовов, стек вызовов пуст. Обратные вызовы, ожидающие в очереди (`() => console.log("Timeout 1!")` из `funcOne`, и `() => console.log("Timeout 2!")` из `funcTwo`) добавляются в стек вызовов один за другим. Первый обратный вызов регистрирует `Timeout 1!` и удаляется из стека. Затем второй обратный вызов регистрирует `Timeout 2!` и удаляется из стека.

@@ -4344,8 +4365,8 @@ console.log(info); ```javascript { - default: "I love JavaScript", - name: "Lydia", + default: 'I love JavaScript', + name: 'Lydia', age: 21 } ``` @@ -4456,3 +4477,628 @@ Object.freeze(person);

+ +--- + +###### 138. Что будет на выходе? + +```javascript +const add = x => x + x; + +function myFunc(num = 2, value = add(num)) { + console.log(num, value); +} + +myFunc(); +myFunc(3); +``` + +- A: `2` `4` and `3` `6` +- B: `2` `NaN` and `3` `NaN` +- C: `2` `Error` and `3` `6` +- D: `2` `4` and `3` `Error` + +
Ответ +

+ +#### Ответ: A + +Во-первых, мы вызваем `myFunc()` без передачи каких-либо аргументов. Поскольку мы не передаем аргументы, `num` и `value` получают свои значения по умолчанию: `num` равно `2`, а `value` возвращаемое значение функции `add`. В функцию `add` мы передаем в качестве аргумента `num` со значением `2`. `add` возвращает `4`, что является значением `value`. + +Затем мы вызваем `myFunc(3)` и передаем значение `3` в качестве значения аргумента `num`. Мы не передаем аргумент для `value`. Поскольку мы не передаем значение для аргумента `value`, он получаеи значение по умолчанию: возвращаемое значение функции `add`. В `add` мы передаем `num`, значение которого равно `3`. `add` возвращает `6`, что является значением `value`. + +

+
+ +--- + +###### 139. Что будет на выходе? + +```javascript +class Counter { + #number = 10 + + increment() { + this.#number++ + } + + getNum() { + return this.#number + } +} + +const counter = new Counter() +counter.increment() + +console.log(counter.#number) +``` + +- A: `10` +- B: `11` +- C: `undefined` +- D: `SyntaxError` + +
Ответ +

+ +#### Ответ: D + +В ES2020 мы можем добавлять приватные переменные в классы с помощью символа `#`. Мы не можем получить доступ к этим переменным вне класса. Когда мы пытаемся записать `counter.#number`, выдается `SyntaxError`: мы не можем получить доступ вне класса `Counter`! + +

+
+ +--- + +###### 140. В каком случае не будет ошибки? + +```javascript +const teams = [ + { name: 'Team 1', members: ['Paul', 'Lisa'] }, + { name: 'Team 2', members: ['Laura', 'Tim'] }, +]; + +function* getMembers(members) { + for (let i = 0; i < members.length; i++) { + yield members[i]; + } +} + +function* getTeams(teams) { + for (let i = 0; i < teams.length; i++) { + // ✨ SOMETHING IS MISSING HERE ✨ + } +} + +const obj = getTeams(teams); +obj.next(); // { value: "Paul", done: false } +obj.next(); // { value: "Lisa", done: false } +``` + +- A: `yield getMembers(teams[i].members)` +- B: `yield* getMembers(teams[i].members)` +- C: `return getMembers(teams[i].members)` +- D: `return yield getMembers(teams[i].members)` + +
Ответ +

+ +#### Ответ: B + +Чтобы выполнить итерацию по `members` в каждом элементе массива `teams`, нам нужно передать `teams[i].members` в функцию генератора `getMembers`. Функция генератора возвращает объект генератора. Чтобы перебрать каждый элемент в этом объекте-генераторе, нам нужно использовать `yield*`. + +Если бы мы написали `yield`, `return yield` или `return`, вся функция генератора была бы возвращена при первом вызове метода `next`. + +

+
+ +--- + +###### 141. Что будет на выходе? + +```javascript +const person = { + name: 'Lydia Hallie', + hobbies: ['coding'], +}; + +function addHobby(hobby, hobbies = person.hobbies) { + hobbies.push(hobby); + return hobbies; +} + +addHobby('running', []); +addHobby('dancing'); +addHobby('baking', person.hobbies); + +console.log(person.hobbies); +``` + +- A: `["coding"]` +- B: `["coding", "dancing"]` +- C: `["coding", "dancing", "baking"]` +- D: `["coding", "running", "dancing", "baking"]` + +
Ответ +

+ +#### Ответ: C + +Функция `addHobby` получает два аргумента, `hobby` и `hobbies`, со значением по умолчанию массива `hobbies` в объекте `person`. + +Во-первых, мы вызываем функцию `addHobby` и передаем `"running"` в качестве значения для `hobby`, а пустой массив в качестве значения для `hobbies`. Так как мы передаем пустой массив в качестве значения для `hobbies`, `"running"` добавляется к этому пустому массиву. + +Затем мы вызываем функцию `addHobby` и передаем `dancing` в качестве значения для `hobby`. Мы не передавали значение для `hobbies`, поэтому оно получает значение по умолчанию, свойство `hobbies` объекта `person`. Мы помещаем хобби `dancing` в массив `person.hobbies`. + +Наконец, мы вызываем функцию `addHobby` и передаем `"baking"` в качестве значения для `hobby`, а массив `person.hobbies` в качестве значения для `hobbies`. Мы помещаем хобби `baking` в массив `person.hobbies`. + +После нажатия `танцы` и `выпечка`, значение `person.hobbies` равно `["coding", "dancing", "baking"]` + +

+
+ +--- + +###### 142. Что будет на выходе? + +```javascript +class Bird { + constructor() { + console.log("I'm a bird. 🦢"); + } +} + +class Flamingo extends Bird { + constructor() { + console.log("I'm pink. 🌸"); + super(); + } +} + +const pet = new Flamingo(); +``` + +- A: `I'm pink. 🌸` +- B: `I'm pink. 🌸` `I'm a bird. 🦢` +- C: `I'm a bird. 🦢` `I'm pink. 🌸` +- D: Nothing, we didn't call any method + +
Ответ +

+ +#### Ответ: B + +Мы создаем переменную `pet`, которая является экземпляром класса `Flamingo`. Когда мы создаем этот экземпляр, вызывается `constructor` для `Flamingo`. Сначала регистрируется `"I'm pink. 🌸"`, после чего мы вызываем `super()`. `super()` вызывает конструктор родительского класса `Bird`. Конструктор в `Bird` вызывается и регистрирует `"I'm a bird. 🦢"`. + +

+
+ +--- + +###### 143. Какой/какие из вариантов приведет к ошибке? + +```javascript +const emojis = ['🎄', '🎅🏼', '🎁', '⭐']; + +/* 1 */ emojis.push('🦌'); +/* 2 */ emojis.splice(0, 2); +/* 3 */ emojis = [...emojis, '🥂']; +/* 4 */ emojis.length = 0; +``` + +- A: 1 +- B: 1 и 2 +- C: 3 и 4 +- D: 3 + +
Ответ +

+ +#### Ответ: D + +Ключевое слово `const` просто означает, что мы не можем _повторно объявить_ значение этой переменной, оно доступно только для чтения. Однако само значение не является неизменным. Свойства массива `emojis` можно изменить, например, добавив новые значения, объединив их или установив длину массива на 0. + +

+
+ +--- + +###### 144. Что нам нужно добавить к объекту `person`, чтобы получить `["Lydia Hallie", 21]` в качестве вывода `[...person]`? + +```javascript +const person = { + name: "Lydia Hallie", + age: 21 +} + +[...person] // ["Lydia Hallie", 21] +``` + +- A: Ничего, объекты итерируется по умолчанию +- B: `*[Symbol.iterator]() { for (let x in this) yield* this[x] }` +- C: `*[Symbol.iterator]() { yield* Object.values(this) }` +- D: `*[Symbol.iterator]() { for (let x in this) yield this }` + +
Ответ +

+ +#### Ответ: C + +По умолчанию объекты не являются итерируемыми. Итерируемым объект становится, если присутствует протокол итератора. Мы можем добавить это вручную, добавив символ итератора `[Symbol.iterator]`, который должен возвращать объект-генератор, например, сделав его функцией-генератором `*[Symbol.iterator]() {}`. Эта функция-генератор должна возвращать `Object.values` объекта `person`, если мы хотим, чтобы он возвращал массив `["Lydia Hallie", 21]`: `yield* Object.values(this)`. + +

+
+ +--- + +###### 145. Что будет на выходе? + +```javascript +let count = 0; +const nums = [0, 1, 2, 3]; + +nums.forEach(num => { + if (num) count += 1 +}) + +console.log(count) +``` + +- A: 1 +- B: 2 +- C: 3 +- D: 4 + +
Ответ +

+ +#### Ответ: C + +Условие `if` внутри цикла `forEach` проверяет, является ли значение `num` истинным или ложным. Поскольку первое число в массиве `nums` равно `0`, то есть ложное значение, блок оператора `if` не будет выполнен. `count` увеличивается только для остальных 3 чисел в массиве `nums`: `1`, `2` и `3`. Поскольку `count` увеличивается на 1 3 раза, значение `count` равно `3`. + +

+
+ +--- + +###### 146. Что будет на выходе? + +```javascript +function getFruit(fruits) { + console.log(fruits?.[1]?.[1]) +} + +getFruit([['🍊', '🍌'], ['🍍']]) +getFruit() +getFruit([['🍍'], ['🍊', '🍌']]) +``` + +- A: `null`, `undefined`, 🍌 +- B: `[]`, `null`, 🍌 +- C: `[]`, `[]`, 🍌 +- D: `undefined`, `undefined`, 🍌 + +
Ответ +

+ +#### Ответ: D + +`?` позволяет нам дополнительно получить доступ к более глубоким вложенным свойствам внутри объектов. Мы пытаемся зарегистрировать элемент с индексом `1` в подмассиве с индексом `1` массива `fruits`. Если подмассив с индексом `1` в массиве `fruits` не существует, он просто вернет `undefined`. Если подмассив с индексом `1` в массиве `fruits` существует, но в этом подмассиве нет элемента с индексом `1`, он также вернет значение `undefined`. + +Во-первых, мы пытаемся зарегистрировать второй элемент в `['🍍']` подмассива `[['🍊', '🍌'], ['🍍']]`. Этот подмассив содержит только один элемент, что означает, что в индексе `1` нет элемента, и возвращает значение `undefined`. + +Затем мы вызываем функцию `getFruits` без передачи значения в качестве аргумента, что означает, что `fruits` по умолчанию имеет значение `undefined`. Поскольку мы условно связываем элемент с индексом `1` массива `fruits`, он возвращает значение `undefined`, поскольку этот элемент с индексом `1` не существует. + +Наконец, мы попытаемся зарегистрировать второй элемент в `['🍊', '🍌']` подмассива `['🍍'], ['🍊', '🍌']`. Элемент с индексом `1` в этом подмассиве — `🍌`, который регистрируется. + +

+
+ +--- + +###### 147. Что будет на выходе? + +```javascript +class Calc { + constructor() { + this.count = 0 + } + + increase() { + this.count ++ + } +} + +const calc = new Calc() +new Calc().increase() + +console.log(calc.count) +``` + +- A: `0` +- B: `1` +- C: `undefined` +- D: `ReferenceError` + +
Ответ +

+ +#### Ответ: A + +Мы устанавливаем переменную `calc` равной новому экземпляру класса `Calc`. Затем мы создаем экземпляр нового экземпляра `Calc` и вызываем метод увеличения для этого экземпляра. Поскольку свойство `count` находится в конструкторе класса `Calc`, свойство `count` не используется в прототипе `Calc`. Это означает, что значение `count` не было обновлено для экземпляра, на который указывает `calc`, `count` по-прежнему равен `0`. + +

+
+ +--- + +###### 148. Что будет на выходе? + +```javascript +const user = { + email: "e@mail.com", + password: "12345" +} + +const updateUser = ({ email, password }) => { + if (email) { + Object.assign(user, { email }) + } + + if (password) { + user.password = password + } + + return user +} + +const updatedUser = updateUser({ email: "new@email.com" }) + +console.log(updatedUser === user) +``` + +- A: `false` +- B: `true` +- C: `TypeError` +- D: `ReferenceError` + +
Ответ +

+ +#### Ответ: B + +Функция `updateUser` обновляет значения свойств `email` и `password` у пользователя, если их значения переданы в функцию, после чего функция возвращает объект `user`. Возвращаемое значение функции `updateUser` — это объект `user`, что означает, что значение `updatedUser` является ссылкой на тот же объект `user`, на который указывает `user`. `updatedUser === user` равно `true`. + +

+
+ +--- + +###### 149. Что будет на выходе? + +```javascript +const fruit = ['🍌', '🍊', '🍎'] + +fruit.slice(0, 1) +fruit.splice(0, 1) +fruit.unshift('🍇') + +console.log(fruit) +``` + +- A: `['🍌', '🍊', '🍎']` +- B: `['🍊', '🍎']` +- C: `['🍇', '🍊', '🍎']` +- D: `['🍇', '🍌', '🍊', '🍎']` + +
Ответ +

+ +#### Ответ: C + +Во-первых, мы вызываем метод `slice` для массива фруктов. Метод `slice` не изменяет исходный массив, а возвращает значение, которое было вырезано из массива: банановый смайлик. +Затем мы вызываем метод `splice` для массива фруктов. Метод `splice` изменяет исходный массив, что означает, что массив фруктов теперь состоит из `['🍊', '🍎']`. +Наконец, мы вызываем метод `unshift` для массива `fruit`, который изменяет исходный массив, добавляя предоставленное значение, в данном случае `🍇`, в качестве первого элемента в массиве. Массив фруктов теперь состоит из `['🍇', '🍊', '🍎']`. + +

+
+ +--- + +###### 150. Что будет на выходе? + +```javascript +const animals = {}; +let dog = { emoji: '🐶' } +let cat = { emoji: '🐈' } + +animals[dog] = { ...dog, name: "Mara" } +animals[cat] = { ...cat, name: "Sara" } + +console.log(animals[dog]) +``` + +- A: `{ emoji: "🐶", name: "Mara" }` +- B: `{ emoji: "🐈", name: "Sara" }` +- C: `undefined` +- D: `ReferenceError` + +
Ответ +

+ +#### Ответ: B + +Ключи объекта преобразуются в строки. + +Поскольку значение `dog` является объектом, `animals[dog]` на самом деле означает, что мы создаем новое свойство под названием `"object Object"`, равное новому объекту. `animals["object Object"]` теперь равно `{ emoji: "🐶", name: "Mara"}`. + +`cat` также является объектом, что означает, что `animals[cat]` на самом деле означает, что мы перезаписываем значение `animals["object Object"]` новыми свойствами кота. + +Регистрация `animals[dog]`, или фактически `animals["object Object"]`, поскольку преобразование объекта `dog` в строку приводит к `"object Object"`, возвращает `{ emoji: "🐈", name: " Сара"}`. + +

+
+ +--- + +###### 151. Что будет на выходе? + +```javascript +const user = { + email: "my@email.com", + updateEmail: email => { + this.email = email + } +} + +user.updateEmail("new@email.com") +console.log(user.email) +``` + +- A: `my@email.com` +- B: `new@email.com` +- C: `undefined` +- D: `ReferenceError` + +
Ответ +

+ +#### Ответ: A + +Функция `updateEmail` представляет собой стрелочную функцию и не привязана к объекту пользователя. Это означает, что ключевое слово `this` не относится к объекту `user`, а в данном случае относится к глобальной области видимости. Значение `email` в объекте `user` не обновляется. При регистрации значения `user.email` возвращается исходное значение `my@email.com`. + +

+
+ +--- + +###### 152. Что будет на выходе? + +```javascript +const promise1 = Promise.resolve('First') +const promise2 = Promise.resolve('Second') +const promise3 = Promise.reject('Third') +const promise4 = Promise.resolve('Fourth') + +const runPromises = async () => { + const res1 = await Promise.all([promise1, promise2]) + const res2 = await Promise.all([promise3, promise4]) + return [res1, res2] +} + +runPromises() + .then(res => console.log(res)) + .catch(err => console.log(err)) +``` + +- A: `[['First', 'Second'], ['Fourth']]` +- B: `[['First', 'Second'], ['Third', 'Fourth']]` +- C: `[['First', 'Second']]` +- D: `'Third'` + +
Ответ +

+ +#### Ответ: D + +Метод `Promise.all` выполняет переданные промисы параллельно. Если одно обещание не выполняется, метод `Promise.all` _отколняется_ со значением отклоненного обещания. В этом случае `promise3` отклонен со значением `"Third"`. Мы перехватываем отклоненное значение в цепочке методов `catch` при вызове `runPromises`, чтобы перехватывать любые ошибки внутри функции `runPromises`. Только `"Third"` регистрируется, так как `promise3` отклонено с этим значением. + +

+
+ +--- + +###### 153. Каким должно быть значение `method` для регистрации `{ name: "Lydia", age: 22 }`? + +```javascript +const keys = ["name", "age"] +const values = ["Lydia", 22] + +const method = /* ?? */ +Object[method](keys.map((_, i) => { + return [keys[i], values[i]] +})) // { name: "Lydia", age: 22 } +``` + +- A: `entries` +- B: `values` +- C: `fromEntries` +- D: `forEach` + +
Ответ +

+ +#### Ответ: C + +Метод `fromEntries` превращает двумерный массив в объект. Первый элемент в каждом подмассиве будет ключом, а второй элемент в каждом подмассиве будет значением. В этом случае мы сопоставляем массив `keys`, который возвращает массив, первый элемент которого является элементом массива ключей текущего индекса, а второй элемент является элементом массива значений текущего индекса. + +Это создает массив подмассивов, содержащих правильные ключи и значения, что приводит к `{ name: "Lydia", age: 22 }` + +

+
+ +--- + +###### 154. Что будет на выходе? + +```javascript +const createMember = ({ email, address = {}}) => { + const validEmail = /.+\@.+\..+/.test(email) + if (!validEmail) throw new Error("Valid email pls") + + return { + email, + address: address ? address : null + } +} + +const member = createMember({ email: "my@email.com" }) +console.log(member) +``` + +- A: `{ email: "my@email.com", address: null }` +- B: `{ email: "my@email.com" }` +- C: `{ email: "my@email.com", address: {} }` +- D: `{ email: "my@email.com", address: undefined }` + +
Ответ +

+ +#### Ответ: C + +Значением по умолчанию для `address` является пустой объект `{}`. Когда мы устанавливаем переменную `member` равной объекту, возвращаемому функцией `createMember`, мы не передаем значение для адреса, что означает, что значение адреса является пустым объектом по умолчанию `{}`. Пустой объект является истинным значением, что означает, что условие `address ? address : null` условно возвращает `true`. Значением адреса является пустой объект `{}`. + +

+
+ +--- + +###### 155. Что будет на выходе? + +```javascript +let randomValue = { name: "Lydia" } +randomValue = 23 + +if (!typeof randomValue === "string") { + console.log("It's not a string!") +} else { + console.log("Yay it's a string!") +} +``` + +- A: `It's not a string!` +- B: `Yay it's a string!` +- C: `TypeError` +- D: `undefined` + +
Ответ +

+ +#### Ответ: B + +Условие в операторе `if` проверяет, равно ли значение `!typeof randomValue` "строке". Оператор `!` преобразует значение в логическое значение. Если значение истинно, возвращаемое значение будет "ложным", если значение ложным, возвращаемое значение будет "истинным". В этом случае возвращаемое значение `typeof randomValue` является истинным значением `"number"`, что означает, что значение `!typeof randomValue` является логическим значением `false`. + +`!typeof randomValue === "string"` всегда возвращает `false`, поскольку на самом деле мы проверяем `false === "string"`. Поскольку условие вернуло `false`, запускается блок кода оператора `else`, и в журнал заносится сообщение `Yay it's a string!`. + +

+
From 7ddcc9f8522a7b1acbae83cd7d692a7619bf4b3d Mon Sep 17 00:00:00 2001 From: Alex Ivanov Date: Sat, 31 Dec 2022 22:17:47 +0300 Subject: [PATCH 131/193] fix: update available trans links Signed-off-by: Alex Ivanov --- ru-RU/README.md | 36 ++++++++++++++++++------------------ 1 file changed, 18 insertions(+), 18 deletions(-) diff --git a/ru-RU/README.md b/ru-RU/README.md index e2c68785..f9dbd536 100644 --- a/ru-RU/README.md +++ b/ru-RU/README.md @@ -20,25 +20,25 @@
See 18 Available Translations 🇸🇦🇪🇬🇧🇦🇩🇪🇪🇸🇫🇷🇮🇩🇯🇵🇰🇷🇳🇱🇧🇷🇷🇺🇹🇭🇹🇷🇺🇦🇻🇳🇨🇳🇹🇼

-- [🇸🇦 العربية](./ar-AR/README_AR.md) -- [🇪🇬 اللغة العامية](./ar-EG/README_ar-EG.md) -- [🇧🇦 Bosanski](./bs-BS/README-bs_BS.md) -- [🇩🇪 Deutsch](./de-DE/README.md) -- [🇪🇸 Español](./es-ES/README-ES.md) -- [🇫🇷 Français](./fr-FR/README_fr-FR.md) -- [🇮🇩 Indonesia](./id-ID/README.md) -- [🇮🇹 Italiano](./it-IT/README.md) -- [🇯🇵 日本語](./ja-JA/README-ja_JA.md) -- [🇰🇷 한국어](./ko-KR/README-ko_KR.md) -- [🇳🇱 Nederlands](./nl-NL/README.md) -- [🇧🇷 Português Brasil](./pt-BR/README_pt_BR.md) +- [🇸🇦 العربية](../ar-AR/README_AR.md) +- [🇪🇬 اللغة العامية](../ar-EG/README_ar-EG.md) +- [🇧🇦 Bosanski](../bs-BS/README-bs_BS.md) +- [🇩🇪 Deutsch](../de-DE/README.md) +- [🇪🇸 Español](../es-ES/README-ES.md) +- [🇫🇷 Français](../fr-FR/README_fr-FR.md) +- [🇮🇩 Indonesia](../id-ID/README.md) +- [🇮🇹 Italiano](../it-IT/README.md) +- [🇯🇵 日本語](../ja-JA/README-ja_JA.md) +- [🇰🇷 한국어](../ko-KR/README-ko_KR.md) +- [🇳🇱 Nederlands](../nl-NL/README.md) +- [🇧🇷 Português Brasil](../pt-BR/README_pt_BR.md) - [🇬🇧 English](../README.md) -- [🇹🇭 ไทย](./th-TH/README-th_TH.md) -- [🇹🇷 Türkçe](./tr-TR/README-tr_TR.md) -- [🇺🇦 Українська мова](./uk-UA/README.md) -- [🇻🇳 Tiếng Việt](./vi-VI/README-vi.md) -- [🇨🇳 简体中文](./zh-CN/README-zh_CN.md) -- [🇹🇼 繁體中文](./zh-TW/README_zh-TW.md) +- [🇹🇭 ไทย](../th-TH/README-th_TH.md) +- [🇹🇷 Türkçe](../tr-TR/README-tr_TR.md) +- [🇺🇦 Українська мова](../uk-UA/README.md) +- [🇻🇳 Tiếng Việt](../vi-VI/README-vi.md) +- [🇨🇳 简体中文](../zh-CN/README-zh_CN.md) +- [🇹🇼 繁體中文](../zh-TW/README_zh-TW.md)

From bcd6ec72ad41b1a7ade467170d1ff4f8c79f7042 Mon Sep 17 00:00:00 2001 From: Alex Ivanov Date: Sat, 31 Dec 2022 22:20:38 +0300 Subject: [PATCH 132/193] feat: add unar trans Signed-off-by: Alex Ivanov --- ru-RU/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ru-RU/README.md b/ru-RU/README.md index f9dbd536..b9b2e2e5 100644 --- a/ru-RU/README.md +++ b/ru-RU/README.md @@ -17,7 +17,7 @@ --- -
See 18 Available Translations 🇸🇦🇪🇬🇧🇦🇩🇪🇪🇸🇫🇷🇮🇩🇯🇵🇰🇷🇳🇱🇧🇷🇷🇺🇹🇭🇹🇷🇺🇦🇻🇳🇨🇳🇹🇼 +
Доступно в 18 переводах 🇸🇦🇪🇬🇧🇦🇩🇪🇪🇸🇫🇷🇮🇩🇯🇵🇰🇷🇳🇱🇧🇷🇷🇺🇹🇭🇹🇷🇺🇦🇻🇳🇨🇳🇹🇼

- [🇸🇦 العربية](../ar-AR/README_AR.md) From ca7e55e0ba4bde054aaafb7904217dce307d7b58 Mon Sep 17 00:00:00 2001 From: Alex Ivanov Date: Sat, 31 Dec 2022 22:21:57 +0300 Subject: [PATCH 133/193] feat: update count translations Signed-off-by: Alex Ivanov --- ru-RU/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ru-RU/README.md b/ru-RU/README.md index b9b2e2e5..78f8400d 100644 --- a/ru-RU/README.md +++ b/ru-RU/README.md @@ -17,7 +17,7 @@ --- -

Доступно в 18 переводах 🇸🇦🇪🇬🇧🇦🇩🇪🇪🇸🇫🇷🇮🇩🇯🇵🇰🇷🇳🇱🇧🇷🇷🇺🇹🇭🇹🇷🇺🇦🇻🇳🇨🇳🇹🇼 +
Доступно в 19 переводах 🇸🇦🇪🇬🇧🇦🇩🇪🇪🇸🇫🇷🇮🇩🇯🇵🇰🇷🇳🇱🇧🇷🇷🇺🇹🇭🇹🇷🇺🇦🇻🇳🇨🇳🇹🇼

- [🇸🇦 العربية](../ar-AR/README_AR.md) From 6b208652d062704ff91f72324b124a4a9d144a7e Mon Sep 17 00:00:00 2001 From: Alex Ivanov Date: Sat, 31 Dec 2022 22:23:35 +0300 Subject: [PATCH 134/193] fix: update count translations Signed-off-by: Alex Ivanov --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index c3083d3a..9c5b0895 100644 --- a/README.md +++ b/README.md @@ -17,7 +17,7 @@ Feel free to reach out to me! 😊
--- -

See 18 Available Translations 🇸🇦🇪🇬🇧🇦🇩🇪🇪🇸🇫🇷🇮🇩🇯🇵🇰🇷🇳🇱🇧🇷🇷🇺🇹🇭🇹🇷🇺🇦🇻🇳🇨🇳🇹🇼 +
See 19 Available Translations 🇸🇦🇪🇬🇧🇦🇩🇪🇪🇸🇫🇷🇮🇩🇯🇵🇰🇷🇳🇱🇧🇷🇷🇺🇹🇭🇹🇷🇺🇦🇻🇳🇨🇳🇹🇼

- [🇸🇦 العربية](./ar-AR/README_AR.md) From cf24491f48b91c0c2d2cee5b145dfa63495da475 Mon Sep 17 00:00:00 2001 From: Menai Ala Eddine Date: Mon, 9 Jan 2023 23:07:48 +0100 Subject: [PATCH 135/193] :microphone: Give a names for the equal operators. --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 7d89acd8..529644fc 100644 --- a/README.md +++ b/README.md @@ -263,9 +263,9 @@ console.log(b === c); `new Number()` is a built-in function constructor. Although it looks like a number, it's not really a number: it has a bunch of extra features and is an object. -When we use the `==` operator, it only checks whether it has the same _value_. They both have the value of `3`, so it returns `true`. +When we use the `==` operator (Equality operator), it only checks whether it has the same _value_. They both have the value of `3`, so it returns `true`. -However, when we use the `===` operator, both value _and_ type should be the same. It's not: `new Number()` is not a number, it's an **object**. Both return `false.` +However, when we use the `===` operator (Strict equality operator), both value _and_ type should be the same. It's not: `new Number()` is not a number, it's an **object**. Both return `false.`

From cdea09fe78a947a278bd7839a0844389549df164 Mon Sep 17 00:00:00 2001 From: Menai Ala Eddine Date: Tue, 10 Jan 2023 00:02:36 +0100 Subject: [PATCH 136/193] :information_desk_person: Provide the environment of each global variable MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Each environment has its own object model and provides a different syntax to access the global object. In the web browser, for example, the global object is accessible via window, self, or frames. In Node.js, however, these properties don’t exist, and you must use global instead. In Web Workers, only self is available. --- README.md | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 529644fc..960c958c 100644 --- a/README.md +++ b/README.md @@ -324,7 +324,12 @@ console.log(greetign); #### Answer: A -It logs the object, because we just created an empty object on the global object! When we mistyped `greeting` as `greetign`, the JS interpreter actually saw this as `global.greetign = {}` (or `window.greetign = {}` in a browser). +It logs the object, because we just created an empty object on the global object! When we mistyped `greeting` as `greetign`, the JS interpreter actually saw this as: + +1. `global.greetign = {}` in Node.js +2. `window.greetign = {}`, `frames.geetign = {}` and `self.greetign` in browsers. +3. `self.greetign` in web workers. +4. `globalThis.greetign` in all environments. In order to avoid this, we can use `"use strict"`. This makes sure that you have declared a variable before setting it equal to anything. From 72e0d7ca989d88cae13550363da653679cea2b99 Mon Sep 17 00:00:00 2001 From: Basel Rabia Date: Sun, 15 Jan 2023 08:24:29 +0200 Subject: [PATCH 137/193] add break line question 1 ar --- ar-AR/README_AR.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/ar-AR/README_AR.md b/ar-AR/README_AR.md index 962eedfe..33f0d8a0 100644 --- a/ar-AR/README_AR.md +++ b/ar-AR/README_AR.md @@ -63,7 +63,8 @@ sayHi(); الإجابة هي الخيار الرابع : D في داخل الدالة, قمنا أولا بتعريف المتغير `name` مع الكلمة المفتاحية `var`. و هذا يعني ان المتغير قد حصلت له عملية hoisting والتي تعني انه قد تم حجز مساحة لهذا المتغير في هذه اللحظة مع قيمة مبدئية و التي هي `undefined` إلى ان نقوم فعليا بتعريف قيمة له لاحقا. -لم نقم بتعريف المتغير `name` بعد عندما قمنا بطباعته في السطر الاول من الدالة, لهذا لايزال يحمل القيمة `undefined`. +لم نقم بتعريف المتغير `name` بعد عندما قمنا بطباعته في السطر الاول من الدالة, لهذا لايزال يحمل القيمة `undefined`. +
المتغيرات التي تم تعريفها بجانب الكلمات المفتاحية `let` و `const` يتم عمل عملية hoisting لها أيضا, ولكن على عكس المتغيرات التي يتم تعريفها بجانب الكلمة المفتاحية `var`, لا يتم تعريفها او الوصول اليها مالم نقم بإضافة قيمة لها فعليا. و يسمى هذا بال"temporal dead zone".عندما نحاول الوصول الى المتغيرات من النوع `var`قبل ان يتم تعريفها, نتحصل على الخطأ التالي `ReferenceError`.

From 16614a8eb50fa84627db7cc13b3950917fde69ba Mon Sep 17 00:00:00 2001 From: Basel Rabia Date: Sun, 15 Jan 2023 08:26:07 +0200 Subject: [PATCH 138/193] fix wrong description question 1 ar --- ar-AR/README_AR.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ar-AR/README_AR.md b/ar-AR/README_AR.md index 33f0d8a0..1535be4a 100644 --- a/ar-AR/README_AR.md +++ b/ar-AR/README_AR.md @@ -65,7 +65,7 @@ sayHi(); في داخل الدالة, قمنا أولا بتعريف المتغير `name` مع الكلمة المفتاحية `var`. و هذا يعني ان المتغير قد حصلت له عملية hoisting والتي تعني انه قد تم حجز مساحة لهذا المتغير في هذه اللحظة مع قيمة مبدئية و التي هي `undefined` إلى ان نقوم فعليا بتعريف قيمة له لاحقا. لم نقم بتعريف المتغير `name` بعد عندما قمنا بطباعته في السطر الاول من الدالة, لهذا لايزال يحمل القيمة `undefined`.
-المتغيرات التي تم تعريفها بجانب الكلمات المفتاحية `let` و `const` يتم عمل عملية hoisting لها أيضا, ولكن على عكس المتغيرات التي يتم تعريفها بجانب الكلمة المفتاحية `var`, لا يتم تعريفها او الوصول اليها مالم نقم بإضافة قيمة لها فعليا. و يسمى هذا بال"temporal dead zone".عندما نحاول الوصول الى المتغيرات من النوع `var`قبل ان يتم تعريفها, نتحصل على الخطأ التالي `ReferenceError`. +المتغيرات التي تم تعريفها بجانب الكلمات المفتاحية `let` و `const` يتم عمل عملية hoisting لها أيضا, ولكن على عكس المتغيرات التي يتم تعريفها بجانب الكلمة المفتاحية `var`, لا يتم تعريفها او الوصول اليها مالم نقم بإضافة قيمة لها فعليا. و يسمى هذا بال"temporal dead zone".عندما نحاول الوصول الى المتغيرات من النوع `let`قبل ان يتم تعريفها, نتحصل على الخطأ التالي `ReferenceError`.

From 7ce13f8bd5cdd1b7266ed5445147e12b9811d560 Mon Sep 17 00:00:00 2001 From: Alex Ivanov Date: Sun, 5 Feb 2023 23:43:07 +0300 Subject: [PATCH 139/193] feat: update translation regards scopes and globals Signed-off-by: Alex Ivanov --- ru-RU/README.md | 51 +++++++++++++++++++++++++++++++++++++++++++------ 1 file changed, 45 insertions(+), 6 deletions(-) diff --git a/ru-RU/README.md b/ru-RU/README.md index 78f8400d..77b2d167 100644 --- a/ru-RU/README.md +++ b/ru-RU/README.md @@ -324,7 +324,12 @@ console.log(greetign); #### Ответ: A -В консоли выведется объект, потому что мы только что создали пустой объект в глобальном объекте! Когда мы вместо `greeting` написали `greetign`, интерпретатор JS на самом деле выполнил `global.greetign = {}` (или `window.greetign = {}` в браузере). +В консоли выведется объект, потому что мы только что создали пустой объект в глобальном объекте! Когда мы вместо `greeting` написали `greetign`, интерпретатор JS на самом деле увидел: + +1. `global.greetign = {}` в Node.js +2. `window.greetign = {}`, `frames.geetign = {}` и `self.greetign` в браузерах. +3. `self.greetign` в веб-воркерах. +4. `globalThis.greetign` во всех окружениях. Нужно использовать `"use strict"`, чтобы избежать такого поведения. Эта запись поможет быть уверенным в том, что переменная была определена перед тем как ей присвоили значение. @@ -2390,9 +2395,9 @@ console.log(shape); ###### 76. Какой будет вывод? ```javascript -const { name: myName } = { name: 'Lydia' }; +const { firstName: myName } = { firstName: 'Lydia' }; -console.log(name); +console.log(firstName); ``` - A: `"Lydia"` @@ -2405,11 +2410,45 @@ console.log(name); #### Ответ: D -Когда мы распаковываем свойство `name` из правого объекта, мы присваиваем его значение `"Lydia"` переменной с именем `myName`. +Используя [деструктурирующее присваивание](https://developer.mozilla.org/ru/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment), мы можем распаковывать значения из массивов или свойства из объектов в отдельные переменные: + +```javascript +const { firstName } = { firstName: 'Lydia' }; +// Версия ES5: +// var firstName = { firstName: 'Lydia' }.firstName; + +console.log(firstName); // "Lydia" +``` + +Также свойство можно распаковать из объекта и присвоить переменной с именем, отличным от имени свойства объекта: + +```javascript +const { firstName: myName } = { firstName: 'Lydia' }; +// Версия ES5: +// var myName = { firstName: 'Lydia' }.firstName; + +console.log(myName); // "Lydia" +console.log(firstName); // Тут будет ошибка Uncaught ReferenceError: firstName is not defined +``` + +В этом случае `firstName` не существует как переменная, поэтому попытка доступа к ее значению вызовет `ReferenceError`. + +**Примечание.** Помните о свойствах глобальной области видимости: + +```javascript +const { name: myName } = { name: 'Lydia' }; + +console.log(myName); // "lydia" +console.log(name); // "" ----- Браузер, например, Chrome +console.log(name); // ReferenceError: name is not defined ----- NodeJS + +``` + +Всякий раз, когда Javascript не может найти переменную в _текущей области видимости_, то поднимается вверх по [цепочке областей видимости](https://developer.mozilla.org/ru/docs/Web/JavaScript/Closures#лексическая_область_видимости) и ищет ее на каждом уровне, и если достигает области верхнего уровня, также известной как **Глобальная область**, и все еще не находит нужной ссылки, то выдает `ReferenceError`. -С помощью `{name: myName}` мы сообщаем JavaScript, что хотим создать новую переменную с именем `myName` со значением свойства `name` в правой части. +- В **браузерах**, таких как _Chrome_, `name` является _устаревшим свойством глобальной области_. В этом примере код выполняется внутри _глобальной области_ и нет определяемой пользователем локальной переменной `name`, поэтому интерпретатор ищет предопределенные _переменные/свойства_ в глобальной области видимости, что в случае браузеров происходит через объект `window` и возвращается значение [window.name](https://developer.mozilla.org/en-US/docs/Web/API/Window/name), которое равно **пустой строке**. -Поскольку мы пытаемся зарегистрировать `name`, переменную, которая не определена, выдается ReferenceError. +- В **NodeJS** такого свойства в "глобальном" объекте нет, поэтому попытка доступа к несуществующей переменной вызовет [ReferenceError](https://developer.mozilla.org/ru/docs/Web/JavaScript/Reference/Errors/Not_defined).

From 153dc55460569bd2f82cb606e1d1791f53fb0ae2 Mon Sep 17 00:00:00 2001 From: Fiewor John Date: Tue, 23 May 2023 13:28:10 +0100 Subject: [PATCH 140/193] Fix typo --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 69f8ed47..4e4bf3ed 100644 --- a/README.md +++ b/README.md @@ -327,7 +327,7 @@ console.log(greetign); It logs the object, because we just created an empty object on the global object! When we mistyped `greeting` as `greetign`, the JS interpreter actually saw this as: 1. `global.greetign = {}` in Node.js -2. `window.greetign = {}`, `frames.geetign = {}` and `self.greetign` in browsers. +2. `window.greetign = {}`, `frames.greetign = {}` and `self.greetign` in browsers. 3. `self.greetign` in web workers. 4. `globalThis.greetign` in all environments. From 59bd1e4b95fdf78e692591fa5b1ddbe1660d8bb9 Mon Sep 17 00:00:00 2001 From: Amir Elemam Date: Sun, 4 Jun 2023 18:34:21 -0300 Subject: [PATCH 141/193] fix: correct spelling mistakes --- pt-BR/README_pt_BR.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/pt-BR/README_pt_BR.md b/pt-BR/README_pt_BR.md index cf0ff30e..9c2c7d6a 100644 --- a/pt-BR/README_pt_BR.md +++ b/pt-BR/README_pt_BR.md @@ -1097,7 +1097,7 @@ Funções construtoras, como `new Number` e `new Boolean` são truthy. --- -###### 36. Qual é a sáida? +###### 36. Qual é a saída? ```javascript console.log(typeof typeof 1); @@ -2202,11 +2202,11 @@ console.log(/* 2 */); // O JavaScript também ama você ❤️ #### Resposta: C -Uma função geradora "pausa" a sua execução quando encontra a palavra-chave `yield`. Primeiro, temos que deixar a função produzir a string "Você ama JavaScript?", o que pode ser feito chamando `game.next().value`. +Uma função geradora "pausa" a sua execução quando encontra a palavra-chave `yield`. Primeiro, temos que deixar a função produzir a string "Você ama JavaScript?", o que pode ser feito chamando `jogo.next().value`. Cada linha é executada, até encontrar a primeira palavra-chave `yield`. Há uma palavra-chave `yield` na primeira linha da função: a execução para com o primeiro retorno! _Isso significa que a variável `resposta` ainda não foi definida!_ -Quando chamamos `game.next("Sim").value`, o `yield` anterior é substituído pelo valor dos parâmetros passados para a função `next()`, `"Sim"` neste caso. O valor da variável `"resposta"` agora é igual a `"Sim"`. A condição da instrução if retorna `false` e `JavaScript também ama você ❤️` é registrada. +Quando chamamos `jogo.next("Sim").value`, o `yield` anterior é substituído pelo valor dos parâmetros passados para a função `next()`, `"Sim"` neste caso. O valor da variável `"resposta"` agora é igual a `"Sim"`. A condição da instrução if retorna `false` e `JavaScript também ama você ❤️` é registrada.

From 08884d3df433d9318238cc9eac3914da5f51beda Mon Sep 17 00:00:00 2001 From: Amir Elemam Date: Sun, 4 Jun 2023 18:35:22 -0300 Subject: [PATCH 142/193] fix: corrects answer for question 76, in line with the en-US version --- pt-BR/README_pt_BR.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pt-BR/README_pt_BR.md b/pt-BR/README_pt_BR.md index 9c2c7d6a..6335e458 100644 --- a/pt-BR/README_pt_BR.md +++ b/pt-BR/README_pt_BR.md @@ -2360,13 +2360,13 @@ console.log(name);
Answer

-#### Answer: C +#### Answer: D Quando descompactamos a propriedade `name` do objeto do lado direito, atribuímos seu valor `"Lydia"` a uma variável com o nome `myName`. Com `{ name: myName }`, informamos ao JavaScript que queremos criar uma nova variável chamada `myName` com o valor da propriedade `name` no lado direito. -Como tentamos registrar `name`, uma variável que não está definida, `undefined` é retornado na atribuição do lado esquerdo. Mais tarde, o valor de `Lydia` é armazenado através da atribuição de desestruturação. +Quando tentamos mostrar o conteúdo de `name`, uma variável que não está definida, recebemos o erro `ReferenceError`.

From 951f41c6922769686a45843c850310247b9aa428 Mon Sep 17 00:00:00 2001 From: Amir Elemam Date: Sun, 4 Jun 2023 18:34:21 -0300 Subject: [PATCH 143/193] fix: correct spelling mistakes --- pt-BR/README_pt_BR.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/pt-BR/README_pt_BR.md b/pt-BR/README_pt_BR.md index cf0ff30e..9c2c7d6a 100644 --- a/pt-BR/README_pt_BR.md +++ b/pt-BR/README_pt_BR.md @@ -1097,7 +1097,7 @@ Funções construtoras, como `new Number` e `new Boolean` são truthy. --- -###### 36. Qual é a sáida? +###### 36. Qual é a saída? ```javascript console.log(typeof typeof 1); @@ -2202,11 +2202,11 @@ console.log(/* 2 */); // O JavaScript também ama você ❤️ #### Resposta: C -Uma função geradora "pausa" a sua execução quando encontra a palavra-chave `yield`. Primeiro, temos que deixar a função produzir a string "Você ama JavaScript?", o que pode ser feito chamando `game.next().value`. +Uma função geradora "pausa" a sua execução quando encontra a palavra-chave `yield`. Primeiro, temos que deixar a função produzir a string "Você ama JavaScript?", o que pode ser feito chamando `jogo.next().value`. Cada linha é executada, até encontrar a primeira palavra-chave `yield`. Há uma palavra-chave `yield` na primeira linha da função: a execução para com o primeiro retorno! _Isso significa que a variável `resposta` ainda não foi definida!_ -Quando chamamos `game.next("Sim").value`, o `yield` anterior é substituído pelo valor dos parâmetros passados para a função `next()`, `"Sim"` neste caso. O valor da variável `"resposta"` agora é igual a `"Sim"`. A condição da instrução if retorna `false` e `JavaScript também ama você ❤️` é registrada. +Quando chamamos `jogo.next("Sim").value`, o `yield` anterior é substituído pelo valor dos parâmetros passados para a função `next()`, `"Sim"` neste caso. O valor da variável `"resposta"` agora é igual a `"Sim"`. A condição da instrução if retorna `false` e `JavaScript também ama você ❤️` é registrada.

From 3d6f16543c11e14f3b45ea6b3a71b111208fd11d Mon Sep 17 00:00:00 2001 From: Amir Elemam Date: Sun, 4 Jun 2023 18:35:22 -0300 Subject: [PATCH 144/193] fix: corrects answer for question 76, in line with the en-US version --- pt-BR/README_pt_BR.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pt-BR/README_pt_BR.md b/pt-BR/README_pt_BR.md index 9c2c7d6a..6335e458 100644 --- a/pt-BR/README_pt_BR.md +++ b/pt-BR/README_pt_BR.md @@ -2360,13 +2360,13 @@ console.log(name);
Answer

-#### Answer: C +#### Answer: D Quando descompactamos a propriedade `name` do objeto do lado direito, atribuímos seu valor `"Lydia"` a uma variável com o nome `myName`. Com `{ name: myName }`, informamos ao JavaScript que queremos criar uma nova variável chamada `myName` com o valor da propriedade `name` no lado direito. -Como tentamos registrar `name`, uma variável que não está definida, `undefined` é retornado na atribuição do lado esquerdo. Mais tarde, o valor de `Lydia` é armazenado através da atribuição de desestruturação. +Quando tentamos mostrar o conteúdo de `name`, uma variável que não está definida, recebemos o erro `ReferenceError`.

From 4259d32ef6378a58288fed69856cdb3d32ff9870 Mon Sep 17 00:00:00 2001 From: Amir Elemam Date: Sun, 11 Jun 2023 01:22:52 -0300 Subject: [PATCH 145/193] translates answers of question 77 --- pt-BR/README_pt_BR.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pt-BR/README_pt_BR.md b/pt-BR/README_pt_BR.md index 6335e458..c2bb00b9 100644 --- a/pt-BR/README_pt_BR.md +++ b/pt-BR/README_pt_BR.md @@ -2381,8 +2381,8 @@ function sum(a, b) { } ``` -- A: Yes -- B: No +- A: Sim +- B: Não
Answer

From 7329348eaa75fe257892f7d38aff174dcfc89ce1 Mon Sep 17 00:00:00 2001 From: Amir Elemam Date: Sun, 11 Jun 2023 01:23:45 -0300 Subject: [PATCH 146/193] appends explanation to answer of question 78 --- pt-BR/README_pt_BR.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pt-BR/README_pt_BR.md b/pt-BR/README_pt_BR.md index c2bb00b9..a89bca49 100644 --- a/pt-BR/README_pt_BR.md +++ b/pt-BR/README_pt_BR.md @@ -2430,7 +2430,7 @@ console.log(addFunction(5 * 2)); #### Answer: C -A função `add` é uma função _memoized_. Com a memorização, podemos armazenar em cache os resultados de uma função para acelerar sua execução. Nesse caso, criamos um objeto `cache` que armazena os valores retornados anteriormente. +A função `add` é uma função _memoized_ (memorizada). Com a memorização, podemos armazenar em cache os resultados de uma função para acelerar sua execução. Nesse caso, criamos um objeto `cache` que armazena os valores retornados anteriormente. Se chamarmos a função `addFunction` novamente com o mesmo argumento, ela primeiro verifica se já obteve esse valor em seu cache. Se for o caso, o valor dos caches será retornado, o que economiza tempo de execução. Caso contrário, se não estiver armazenado em cache, ele calculará o valor e o armazenará posteriormente. From e9111873607aaeba870600856a1eceae08cf2d8b Mon Sep 17 00:00:00 2001 From: duyvuxx Date: Fri, 16 Jun 2023 14:39:17 +0700 Subject: [PATCH 147/193] #726 - fix the additional information of Question 10 in Vietnamese --- vi-VI/README-vi.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/vi-VI/README-vi.md b/vi-VI/README-vi.md index 4a5ffa71..e790e9f7 100644 --- a/vi-VI/README-vi.md +++ b/vi-VI/README-vi.md @@ -338,7 +338,7 @@ bark.animal = "dog"; #### Đáp án: A -Điều này là có thể với Javascript, bởi vì `function` cũng chỉ là `object` mà thôi! (Mọi primitive types đều là object) +Điều này là có thể với Javascript, bởi vì `function` cũng chỉ là `object` mà thôi! (Các kiểu dữ liệu khác ngoài các kiểu nguyên thủy được gọi là kiểu dữ liệu tham chiếu) Function là một object đặc biệt. Phần code mà bạn viết không phải là function thực tế đâu. Function ở đây chính là một object với các thuộc tính. Và các thuộc tính này có thể gọi được. From bca92aa562154aff8f7a7c43508e83888069c961 Mon Sep 17 00:00:00 2001 From: Lukasz Jasionowski Date: Sun, 25 Jun 2023 21:13:58 +0200 Subject: [PATCH 148/193] Translation of the introduction & the first 10 Q&A --- pl-PL/README.md | 5143 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 5143 insertions(+) create mode 100644 pl-PL/README.md diff --git a/pl-PL/README.md b/pl-PL/README.md new file mode 100644 index 00000000..c00ec388 --- /dev/null +++ b/pl-PL/README.md @@ -0,0 +1,5143 @@ +

+ +

Pytania dotyczące JavaScript

+ +--- + +Publikuję pytania wielokrotnego wyboru dotyczące JavaScriptu na swoich [Instagram](https://www.instagram.com/theavocoder) **stories**, które również zamieszczę tutaj! Ostatnia aktualizacja:12 Czerwca + +Od podstawowych do zaawansowanych: sprawdź, jak dobrze znasz JavaScript, odśwież swoją wiedzę lub przygotuj się do rozmowy kwalifikacyjnej! :muscle: :rocket: Regularnie aktualizuję to repozytorium nowymi pytaniami. Odpowiedzi znajdują się w ukrytych zakładkach poniżej pytań - po prostu kliknij, aby je rozwinięć. To dla zabawy, powodzenia! :heart: + +Nie krępuj się ze mną kontaktować! 😊
+Instagram || Twitter || LinkedIn || Blog +
+ +| Śmiało używaj ich w projekcie! 😃 Byłabym _bardzo_ wdzięczna za referencje do tego repozytorium, tworzę pytania i wyjaśnienia (tak, jestem smutna lol) i społeczność bardzo mi pomaga w utrzymaniu i ulepszaniu go! 💪🏼 Dziękuję i baw się dobrze! | +|---| + +--- + +
Zobacz 19 dostępnych tłumaczeń 🇸🇦🇪🇬🇧🇦🇩🇪🇪🇸🇫🇷🇮🇩🇯🇵🇰🇷🇳🇱🇧🇷🇷🇺🇹🇭🇹🇷🇺🇦🇻🇳🇨🇳🇹🇼 +

+ +- [🇸🇦 العربية](./ar-AR/README_AR.md) +- [🇪🇬 اللغة العامية](./ar-EG/README_ar-EG.md) +- [🇧🇦 Bosanski](./bs-BS/README-bs_BS.md) +- [🇩🇪 Deutsch](./de-DE/README.md) +- [🇪🇸 Español](./es-ES/README-ES.md) +- [🇫🇷 Français](./fr-FR/README_fr-FR.md) +- [🇮🇩 Indonesia](./id-ID/README.md) +- [🇮🇹 Italiano](./it-IT/README.md) +- [🇯🇵 日本語](./ja-JA/README-ja_JA.md) +- [🇰🇷 한국어](./ko-KR/README-ko_KR.md) +- [🇳🇱 Nederlands](./nl-NL/README.md) +- [🇧🇷 Português Brasil](./pt-BR/README_pt_BR.md) +- [🇷🇺 Русский](./ru-RU/README.md) +- [🇹🇭 ไทย](./th-TH/README-th_TH.md) +- [🇹🇷 Türkçe](./tr-TR/README-tr_TR.md) +- [🇺🇦 Українська мова](./uk-UA/README.md) +- [🇻🇳 Tiếng Việt](./vi-VI/README-vi.md) +- [🇨🇳 简体中文](./zh-CN/README-zh_CN.md) +- [🇹🇼 繁體中文](./zh-TW/README_zh-TW.md) + +

+
+ +--- + +###### 1. Jaki jest wynik? + +```javascript +function sayHi() { + console.log(name); + console.log(age); + var name = 'Lydia'; + let age = 21; +} + +sayHi(); +``` + +- A: `Lydia` and `undefined` +- B: `Lydia` and `ReferenceError` +- C: `ReferenceError` and `21` +- D: `undefined` and `ReferenceError` + +
Odpowiedź +

+ +#### Odpowiedź: D + +Wewnątrz funkcji najpierw deklarujemy zmienną `name` za pomocą słowa kluczowego `var`. Oznacza to, że zmienna jest "wyciągana" (przestrzeń pamięci jest tworzona) z domyślną wartością `undefined` podczas fazy tworzenia, aż do momentu, gdy naprawdę definiujemy zmienną. W linii, w której próbujemy wyświetlić w konsoli zmienną `name`, jeszcze jej nie zdefiniowaliśmy, więc nadal przechowuje wartość `undefined`. + +Zmienne zadeklarowane za pomocą słowa kluczowego `let` (i `const`) są wyciągane, ale w przeciwieństwie do `var`, nie są inicjalizowane. Nie są dostępne przed linią, na której je deklarujemy (inicjalizujemy). Nazywa się to "czasową strefą martwą" (temporal dead zone). Gdy próbujemy uzyskać dostęp do zmiennych przed ich zadeklarowaniem, JavaScript generuje błąd `ReferenceError`. + +

+
+ +--- + +###### 2. Jaki jest wynik? + +```javascript +for (var i = 0; i < 3; i++) { + setTimeout(() => console.log(i), 1); +} + +for (let i = 0; i < 3; i++) { + setTimeout(() => console.log(i), 1); +} +``` + +- A: `0 1 2` and `0 1 2` +- B: `0 1 2` and `3 3 3` +- C: `3 3 3` and `0 1 2` + +
Odpowiedź +

+ +#### Odpowiedź: C + +Ze względu na kolejkę zdarzeń w JavaScript, funkcja zwrotna `setTimeout` jest wywoływana _po_ wykonaniu pętli. Ponieważ zmienna `i` w pierwszej pętli została zadeklarowana za pomocą słowa kluczowego `var`, jej wartość była globalna. Podczas pętli inkrementowaliśmy wartość `i` o `1` za każdym razem, używając operatora jednoargumentowego `++`. W momencie wywołania funkcji zwrotnej `setTimeout`, `i` miało wartość `3` w pierwszym przykładzie. + +W drugiej pętli zmienna `i` została zadeklarowana za pomocą słowa kluczowego `let`: zmienne zadeklarowane za pomocą słowa kluczowego `let` (i `const`) mają zakres blokowy (blokiem jest cokolwiek między `{ }`). Podczas każdej iteracji `i` będzie miało nową wartość, a każda wartość będzie miała zakres wewnątrz pętli. + +

+
+ +--- + +###### 3. Jaki jest wynik? + +```javascript +const shape = { + radius: 10, + diameter() { + return this.radius * 2; + }, + perimeter: () => 2 * Math.PI * this.radius, +}; + +console.log(shape.diameter()); +console.log(shape.perimeter()); +``` + +- A: `20` and `62.83185307179586` +- B: `20` and `NaN` +- C: `20` and `63` +- D: `NaN` and `63` + +
Odpowiedź +

+ +#### Odpowiedź: B + +Zwróć uwagę, że wartość `diameter` jest zwykłą funkcją, podczas gdy wartość `perimeter` jest funkcją strzałkową. + +W przypadku funkcji strzałkowych, słowo kluczowe `this` odnosi się do bieżącego otaczającego zakresu, w przeciwieństwie do zwykłych funkcji! Oznacza to, że gdy wywołujemy `perimeter`, nie odnosi się ono do obiektu shape, ale do swojego otaczającego zakresu (np. okna). + +Na tym obiekcie nie ma wartości `radius`, co powoduje zwrócenie `NaN` (Not a Number). + +

+
+ +--- + +###### 4. Jaki jest wynik? + +```javascript ++true; +!'Lydia'; +``` + +- A: `1` and `false` +- B: `false` and `NaN` +- C: `false` and `false` + +
Odpowiedź +

+ +#### Odpowiedź: A + +Operator jednoargumentowy plus próbuje przekonwertować operand na liczbę. `true` jest równoważne `1`, a `false` jest równoważne `0`. + +Łańcuch znaków `'Lydia'` jest wartością prawdziwą. Tak naprawdę pytamy, "czy ta wartość prawdziwa jest fałszywa?". To zwraca `false`. + +

+
+ +--- + +###### 5. Które jest prawdziwe? + +```javascript +const bird = { + size: 'small', +}; + +const mouse = { + name: 'Mickey', + small: true, +}; +``` + +- A: `mouse.bird.size` is not valid +- B: `mouse[bird.size]` is not valid +- C: `mouse[bird["size"]]` is not valid +- D: All of them are valid + +
Odpowiedź +

+ +#### Odpowiedź: A + +W JavaScript wszystkie klucze obiektów są stringami (chyba że są to symbole). Nawet jeśli nie wpisujemy ich jako stringi, zawsze są one konwertowane na stringi wewnątrz. + +JavaScript interpretuje (lub "odpakuowuje") instrukcje. Gdy używamy notacji nawiasów kwadratowych, interpreter widzi pierwszy otwierający nawias `[` i kontynuuje do momentu znalezienia zamykającego nawiasu `]`. Dopiero wtedy ocenia tę instrukcję. + +`mouse[bird.size]`: Najpierw ocenia `bird.size`, które wynosi `"small"`. `mouse["small"]` zwraca `true`. + +Jednakże, w przypadku notacji kropkowej, to się nie dzieje. `mouse` nie ma klucza o nazwie `bird`, co oznacza, że `mouse.bird` jest `undefined`. Następnie pytamy o `size` używając notacji kropkowej: `mouse.bird.size`. Ponieważ `mouse.bird` jest `undefined`, tak naprawdę pytamy o `undefined.size`. To nie jest poprawne i spowoduje błąd podobny do `Cannot read property "size" of undefined` (Nie można odczytać właściwości "size" z undefined). + +

+
+ +--- + +###### 6. Jaki jest wynik? + +```javascript +let c = { greeting: 'Hey!' }; +let d; + +d = c; +c.greeting = 'Hello'; +console.log(d.greeting); +``` + +- A: `Hello` +- B: `Hey!` +- C: `undefined` +- D: `ReferenceError` +- E: `TypeError` + +
Odpowiedź +

+ +#### Odpowiedź: A + +W JavaScript wszystkie obiekty komunikują się ze sobą przez _referencje_, gdy są sobie przypisywane. + +Na początku zmienna `c` przechowuje referencję do obiektu. Później przypisujemy zmiennej `d` tę samą referencję, którą ma `c`, do tego obiektu. + + + +Kiedy zmieniasz jeden obiekt, zmieniasz je wszystkie. + +

+
+ +--- + +###### 7. Jaki jest wynik? + +```javascript +let a = 3; +let b = new Number(3); +let c = 3; + +console.log(a == b); +console.log(a === b); +console.log(b === c); +``` + +- A: `true` `false` `true` +- B: `false` `false` `true` +- C: `true` `false` `false` +- D: `false` `true` `true` + +
Odpowiedź +

+ +#### Odpowiedź: C + +`new Number()` jest wbudowanym konstruktorem funkcji. Chociaż wygląda jak liczba, nie jest faktycznie liczbą: ma wiele dodatkowych funkcji i jest obiektem. + +Gdy używamy operatora `==` (operator równości), sprawdza on jedynie, czy mają tą samą _wartość_. Oba mają wartość `3`, więc zwraca `true`. + +Jednak gdy używamy operatora `===` (operator ścisłej równości), zarówno wartość, jak i typ powinny być takie same. Tutaj nie są: `new Number()` nie jest liczbą, lecz **obiektem**. Oba zwracają `false`. + +

+
+ +--- + +###### 8. Jaki jest wynik? + +```javascript +class Chameleon { + static colorChange(newColor) { + this.newColor = newColor; + return this.newColor; + } + + constructor({ newColor = 'green' } = {}) { + this.newColor = newColor; + } +} + +const freddie = new Chameleon({ newColor: 'purple' }); +console.log(freddie.colorChange('orange')); +``` + +- A: `orange` +- B: `purple` +- C: `green` +- D: `TypeError` + +
Odpowiedź +

+ +#### Odpowiedź: D + +Funkcja `colorChange` jest statyczna. Metody statyczne są zaprojektowane tak, aby istniały tylko w konstruktorze, w którym zostały utworzone, i nie mogą być przekazywane do żadnych potomków (children) ani wywoływane na instancjach klasy. Ponieważ `freddie` jest instancją klasy Chameleon, funkcja nie może być na niej wywołana. Otrzymujemy błąd `TypeError`. + +

+
+ +--- + +###### 9. Jaki jest wynik? + +```javascript +let greeting; +greetign = {}; // Celowa Literówka! +console.log(greetign); +``` + +- A: `{}` +- B: `ReferenceError: greetign is not defined` +- C: `undefined` + +
Odpowiedź +

+ +#### Odpowiedź: A + +Kod wypisuje w konsoli obiekt, ponieważ właśnie utworzyliśmy pusty obiekt w obiekcie globalnym! Gdy pomyłkowo wpisaliśmy `greeting` jako `greetign`, interpreter JavaScript faktycznie zobaczył to jako: + +1. `global.greetign = {}` w Node.js. +2. `window.greetign = {}`, `frames.greetign = {}` i `self.greetign` w przeglądarkach. +3. `self.greetign` w web workerach. +4. `globalThis.greetign` we wszystkich środowiskach. + +Aby temu zapobiec, możemy użyć `"use strict"`. Powoduje to, że musisz zadeklarować zmienną przed jej przypisaniem. + +

+
+ +--- + +###### 10. Co się dzieje, gdy to zrobimy? + +```javascript +function bark() { + console.log('Woof!'); +} + +bark.animal = 'dog'; +``` + +- A: Nothing, this is totally fine! +- B: `SyntaxError`. You cannot add properties to a function this way. +- C: `"Woof"` gets logged. +- D: `ReferenceError` + +
Odpowiedź +

+ +#### Odpowiedź: A + +Jest to możliwe w JavaScript, ponieważ funkcje są obiektami! (Wszystko oprócz typów prymitywnych jest obiektem) + +Funkcja jest specjalnym rodzajem obiektu. Kod, który sam piszesz, nie jest właściwą funkcją. Funkcja jest obiektem posiadającym właściwość, która jest wywoływalna. + +

+
+ +--- + +###### 11. Jaki jest wynik? + +```javascript +function Person(firstName, lastName) { + this.firstName = firstName; + this.lastName = lastName; +} + +const member = new Person('Lydia', 'Hallie'); +Person.getFullName = function() { + return `${this.firstName} ${this.lastName}`; +}; + +console.log(member.getFullName()); +``` + +- A: `TypeError` +- B: `SyntaxError` +- C: `Lydia Hallie` +- D: `undefined` `undefined` + +
Odpowiedź +

+ +#### Odpowiedź: A + +In JavaScript, functions are objects, and therefore, the method `getFullName` gets added to the constructor function object itself. For that reason, we can call `Person.getFullName()`, but `member.getFullName` throws a `TypeError`. + +If you want a method to be available to all object instances, you have to add it to the prototype property: + +```js +Person.prototype.getFullName = function() { + return `${this.firstName} ${this.lastName}`; +}; +``` + +

+
+ +--- + +###### 12. Jaki jest wynik? + +```javascript +function Person(firstName, lastName) { + this.firstName = firstName; + this.lastName = lastName; +} + +const lydia = new Person('Lydia', 'Hallie'); +const sarah = Person('Sarah', 'Smith'); + +console.log(lydia); +console.log(sarah); +``` + +- A: `Person {firstName: "Lydia", lastName: "Hallie"}` and `undefined` +- B: `Person {firstName: "Lydia", lastName: "Hallie"}` and `Person {firstName: "Sarah", lastName: "Smith"}` +- C: `Person {firstName: "Lydia", lastName: "Hallie"}` and `{}` +- D: `Person {firstName: "Lydia", lastName: "Hallie"}` and `ReferenceError` + +
Odpowiedź +

+ +#### Odpowiedź: A + +For `sarah`, we didn't use the `new` keyword. When using `new`, `this` refers to the new empty object we create. However, if you don't add `new`, `this` refers to the **global object**! + +We said that `this.firstName` equals `"Sarah"` and `this.lastName` equals `"Smith"`. What we actually did, is defining `global.firstName = 'Sarah'` and `global.lastName = 'Smith'`. `sarah` itself is left `undefined`, since we don't return a value from the `Person` function. + +

+
+ +--- + +###### 13. What are the three phases of event propagation? + +- A: Target > Capturing > Bubbling +- B: Bubbling > Target > Capturing +- C: Target > Bubbling > Capturing +- D: Capturing > Target > Bubbling + +
Odpowiedź +

+ +#### Odpowiedź: D + +During the **capturing** phase, the event goes through the ancestor elements down to the target element. It then reaches the **target** element, and **bubbling** begins. + + + +

+
+ +--- + +###### 14. All object have prototypes. + +- A: true +- B: false + +
Odpowiedź +

+ +#### Odpowiedź: B + +All objects have prototypes, except for the **base object**. The base object is the object created by the user, or an object that is created using the `new` keyword. The base object has access to some methods and properties, such as `.toString`. This is the reason why you can use built-in JavaScript methods! All of such methods are available on the prototype. Although JavaScript can't find it directly on your object, it goes down the prototype chain and finds it there, which makes it accessible for you. + +

+
+ +--- + +###### 15. Jaki jest wynik? + +```javascript +function sum(a, b) { + return a + b; +} + +sum(1, '2'); +``` + +- A: `NaN` +- B: `TypeError` +- C: `"12"` +- D: `3` + +
Odpowiedź +

+ +#### Odpowiedź: C + +JavaScript is a **dynamically typed language**: we don't specify what types certain variables are. Values can automatically be converted into another type without you knowing, which is called _implicit type coercion_. **Coercion** is converting from one type into another. + +In this example, JavaScript converts the number `1` into a string, in order for the function to make sense and return a value. During the addition of a numeric type (`1`) and a string type (`'2'`), the number is treated as a string. We can concatenate strings like `"Hello" + "World"`, so what's happening here is `"1" + "2"` which returns `"12"`. + +

+
+ +--- + +###### 16. Jaki jest wynik? + +```javascript +let number = 0; +console.log(number++); +console.log(++number); +console.log(number); +``` + +- A: `1` `1` `2` +- B: `1` `2` `2` +- C: `0` `2` `2` +- D: `0` `1` `2` + +
Odpowiedź +

+ +#### Odpowiedź: C + +The **postfix** unary operator `++`: + +1. Returns the value (this returns `0`) +2. Increments the value (number is now `1`) + +The **prefix** unary operator `++`: + +1. Increments the value (number is now `2`) +2. Returns the value (this returns `2`) + +This returns `0 2 2`. + +

+
+ +--- + +###### 17. Jaki jest wynik? + +```javascript +function getPersonInfo(one, two, three) { + console.log(one); + console.log(two); + console.log(three); +} + +const person = 'Lydia'; +const age = 21; + +getPersonInfo`${person} is ${age} years old`; +``` + +- A: `"Lydia"` `21` `["", " is ", " years old"]` +- B: `["", " is ", " years old"]` `"Lydia"` `21` +- C: `"Lydia"` `["", " is ", " years old"]` `21` + +
Odpowiedź +

+ +#### Odpowiedź: B + +If you use tagged template literals, the value of the first argument is always an array of the string values. The remaining arguments get the values of the passed expressions! + +

+
+ +--- + +###### 18. Jaki jest wynik? + +```javascript +function checkAge(data) { + if (data === { age: 18 }) { + console.log('You are an adult!'); + } else if (data == { age: 18 }) { + console.log('You are still an adult.'); + } else { + console.log(`Hmm.. You don't have an age I guess`); + } +} + +checkAge({ age: 18 }); +``` + +- A: `You are an adult!` +- B: `You are still an adult.` +- C: `Hmm.. You don't have an age I guess` + +
Odpowiedź +

+ +#### Odpowiedź: C + +When testing equality, primitives are compared by their _value_, while objects are compared by their _reference_. JavaScript checks if the objects have a reference to the same location in memory. + +The two objects that we are comparing don't have that: the object we passed as a parameter refers to a different location in memory than the object we used in order to check equality. + +This is why both `{ age: 18 } === { age: 18 }` and `{ age: 18 } == { age: 18 }` return `false`. + +

+
+ +--- + +###### 19. Jaki jest wynik? + +```javascript +function getAge(...args) { + console.log(typeof args); +} + +getAge(21); +``` + +- A: `"number"` +- B: `"array"` +- C: `"object"` +- D: `"NaN"` + +
Odpowiedź +

+ +#### Odpowiedź: C + +The rest parameter (`...args`) lets us "collect" all remaining arguments into an array. An array is an object, so `typeof args` returns `"object"` + +

+
+ +--- + +###### 20. Jaki jest wynik? + +```javascript +function getAge() { + 'use strict'; + age = 21; + console.log(age); +} + +getAge(); +``` + +- A: `21` +- B: `undefined` +- C: `ReferenceError` +- D: `TypeError` + +
Odpowiedź +

+ +#### Odpowiedź: C + +With `"use strict"`, you can make sure that you don't accidentally declare global variables. We never declared the variable `age`, and since we use `"use strict"`, it will throw a reference error. If we didn't use `"use strict"`, it would have worked, since the property `age` would have gotten added to the global object. + +

+
+ +--- + +###### 21. What's the value of `sum`? + +```javascript +const sum = eval('10*10+5'); +``` + +- A: `105` +- B: `"105"` +- C: `TypeError` +- D: `"10*10+5"` + +
Odpowiedź +

+ +#### Odpowiedź: A + +`eval` evaluates codes that's passed as a string. If it's an expression, like in this case, it evaluates the expression. The expression is `10 * 10 + 5`. This returns the number `105`. + +

+
+ +--- + +###### 22. How long is cool_secret accessible? + +```javascript +sessionStorage.setItem('cool_secret', 123); +``` + +- A: Forever, the data doesn't get lost. +- B: When the user closes the tab. +- C: When the user closes the entire browser, not only the tab. +- D: When the user shuts off their computer. + +
Odpowiedź +

+ +#### Odpowiedź: B + +The data stored in `sessionStorage` is removed after closing the _tab_. + +If you used `localStorage`, the data would've been there forever, unless for example `localStorage.clear()` is invoked. + +

+
+ +--- + +###### 23. Jaki jest wynik? + +```javascript +var num = 8; +var num = 10; + +console.log(num); +``` + +- A: `8` +- B: `10` +- C: `SyntaxError` +- D: `ReferenceError` + +
Odpowiedź +

+ +#### Odpowiedź: B + +With the `var` keyword, you can declare multiple variables with the same name. The variable will then hold the latest value. + +You cannot do this with `let` or `const` since they're block-scoped. + +

+
+ +--- + +###### 24. Jaki jest wynik? + +```javascript +const obj = { 1: 'a', 2: 'b', 3: 'c' }; +const set = new Set([1, 2, 3, 4, 5]); + +obj.hasOwnProperty('1'); +obj.hasOwnProperty(1); +set.has('1'); +set.has(1); +``` + +- A: `false` `true` `false` `true` +- B: `false` `true` `true` `true` +- C: `true` `true` `false` `true` +- D: `true` `true` `true` `true` + +
Odpowiedź +

+ +#### Odpowiedź: C + +All object keys (excluding Symbols) are strings under the hood, even if you don't type it yourself as a string. This is why `obj.hasOwnProperty('1')` also returns true. + +It doesn't work that way for a set. There is no `'1'` in our set: `set.has('1')` returns `false`. It has the numeric type `1`, `set.has(1)` returns `true`. + +

+
+ +--- + +###### 25. Jaki jest wynik? + +```javascript +const obj = { a: 'one', b: 'two', a: 'three' }; +console.log(obj); +``` + +- A: `{ a: "one", b: "two" }` +- B: `{ b: "two", a: "three" }` +- C: `{ a: "three", b: "two" }` +- D: `SyntaxError` + +
Odpowiedź +

+ +#### Odpowiedź: C + +If you have two keys with the same name, the key will be replaced. It will still be in its first position, but with the last specified value. + +

+
+ +--- + +###### 26. The JavaScript global execution context creates two things for you: the global object, and the "this" keyword. + +- A: true +- B: false +- C: it depends + +
Odpowiedź +

+ +#### Odpowiedź: A + +The base execution context is the global execution context: it's what's accessible everywhere in your code. + +

+
+ +--- + +###### 27. Jaki jest wynik? + +```javascript +for (let i = 1; i < 5; i++) { + if (i === 3) continue; + console.log(i); +} +``` + +- A: `1` `2` +- B: `1` `2` `3` +- C: `1` `2` `4` +- D: `1` `3` `4` + +
Odpowiedź +

+ +#### Odpowiedź: C + +The `continue` statement skips an iteration if a certain condition returns `true`. + +

+
+ +--- + +###### 28. Jaki jest wynik? + +```javascript +String.prototype.giveLydiaPizza = () => { + return 'Just give Lydia pizza already!'; +}; + +const name = 'Lydia'; + +console.log(name.giveLydiaPizza()) +``` + +- A: `"Just give Lydia pizza already!"` +- B: `TypeError: not a function` +- C: `SyntaxError` +- D: `undefined` + +
Odpowiedź +

+ +#### Odpowiedź: A + +`String` is a built-in constructor, which we can add properties to. I just added a method to its prototype. Primitive strings are automatically converted into a string object, generated by the string prototype function. So, all strings (string objects) have access to that method! + +

+
+ +--- + +###### 29. Jaki jest wynik? + +```javascript +const a = {}; +const b = { key: 'b' }; +const c = { key: 'c' }; + +a[b] = 123; +a[c] = 456; + +console.log(a[b]); +``` + +- A: `123` +- B: `456` +- C: `undefined` +- D: `ReferenceError` + +
Odpowiedź +

+ +#### Odpowiedź: B + +Object keys are automatically converted into strings. We are trying to set an object as a key to object `a`, with the value of `123`. + +However, when we stringify an object, it becomes `"[object Object]"`. So what we are saying here, is that `a["[object Object]"] = 123`. Then, we can try to do the same again. `c` is another object that we are implicitly stringifying. So then, `a["[object Object]"] = 456`. + +Then, we log `a[b]`, which is actually `a["[object Object]"]`. We just set that to `456`, so it returns `456`. + +

+
+ +--- + +###### 30. Jaki jest wynik? + +```javascript +const foo = () => console.log('First'); +const bar = () => setTimeout(() => console.log('Second')); +const baz = () => console.log('Third'); + +bar(); +foo(); +baz(); +``` + +- A: `First` `Second` `Third` +- B: `First` `Third` `Second` +- C: `Second` `First` `Third` +- D: `Second` `Third` `First` + +
Odpowiedź +

+ +#### Odpowiedź: B + +We have a `setTimeout` function and invoked it first. Yet, it was logged last. + +This is because in browsers, we don't just have the runtime engine, we also have something called a `WebAPI`. The `WebAPI` gives us the `setTimeout` function to start with, and for example the DOM. + +After the _callback_ is pushed to the WebAPI, the `setTimeout` function itself (but not the callback!) is popped off the stack. + + + +Now, `foo` gets invoked, and `"First"` is being logged. + + + +`foo` is popped off the stack, and `baz` gets invoked. `"Third"` gets logged. + + + +The WebAPI can't just add stuff to the stack whenever it's ready. Instead, it pushes the callback function to something called the _queue_. + + + +This is where an event loop starts to work. An **event loop** looks at the stack and task queue. If the stack is empty, it takes the first thing on the queue and pushes it onto the stack. + + + +`bar` gets invoked, `"Second"` gets logged, and it's popped off the stack. + +

+
+ +--- + +###### 31. What is the event.target when clicking the button? + +```html +
+
+ +
+
+``` + +- A: Outer `div` +- B: Inner `div` +- C: `button` +- D: An array of all nested elements. + +
Odpowiedź +

+ +#### Odpowiedź: C + +The deepest nested element that caused the event is the target of the event. You can stop bubbling by `event.stopPropagation` + +

+
+ +--- + +###### 32. When you click the paragraph, what's the logged output? + +```html +
+

+ Click here! +

+
+``` + +- A: `p` `div` +- B: `div` `p` +- C: `p` +- D: `div` + +
Odpowiedź +

+ +#### Odpowiedź: A + +If we click `p`, we see two logs: `p` and `div`. During event propagation, there are 3 phases: capturing, target, and bubbling. By default, event handlers are executed in the bubbling phase (unless you set `useCapture` to `true`). It goes from the deepest nested element outwards. + +

+
+ +--- + +###### 33. Jaki jest wynik? + +```javascript +const person = { name: 'Lydia' }; + +function sayHi(age) { + return `${this.name} is ${age}`; +} + +console.log(sayHi.call(person, 21)); +console.log(sayHi.bind(person, 21)); +``` + +- A: `undefined is 21` `Lydia is 21` +- B: `function` `function` +- C: `Lydia is 21` `Lydia is 21` +- D: `Lydia is 21` `function` + +
Odpowiedź +

+ +#### Odpowiedź: D + +With both, we can pass the object to which we want the `this` keyword to refer to. However, `.call` is also _executed immediately_! + +`.bind.` returns a _copy_ of the function, but with a bound context! It is not executed immediately. + +

+
+ +--- + +###### 34. Jaki jest wynik? + +```javascript +function sayHi() { + return (() => 0)(); +} + +console.log(typeof sayHi()); +``` + +- A: `"object"` +- B: `"number"` +- C: `"function"` +- D: `"undefined"` + +
Odpowiedź +

+ +#### Odpowiedź: B + +The `sayHi` function returns the returned value of the immediately invoked function expression (IIFE). This function returned `0`, which is type `"number"`. + +FYI: `typeof` can return the following list of values: `undefined`, `boolean`, `number`, `bigint`, `string`, `symbol`, `function` and `object`. Note that `typeof null` returns `"object"`. + +

+
+ +--- + +###### 35. Which of these values are falsy? + +```javascript +0; +new Number(0); +(''); +(' '); +new Boolean(false); +undefined; +``` + +- A: `0`, `''`, `undefined` +- B: `0`, `new Number(0)`, `''`, `new Boolean(false)`, `undefined` +- C: `0`, `''`, `new Boolean(false)`, `undefined` +- D: All of them are falsy + +
Odpowiedź +

+ +#### Odpowiedź: A + +There are 8 falsy values: + +- `undefined` +- `null` +- `NaN` +- `false` +- `''` (empty string) +- `0` +- `-0` +- `0n` (BigInt(0)) + +Function constructors, like `new Number` and `new Boolean` are truthy. + +

+
+ +--- + +###### 36. Jaki jest wynik? + +```javascript +console.log(typeof typeof 1); +``` + +- A: `"number"` +- B: `"string"` +- C: `"object"` +- D: `"undefined"` + +
Odpowiedź +

+ +#### Odpowiedź: B + +`typeof 1` returns `"number"`. +`typeof "number"` returns `"string"` + +

+
+ +--- + +###### 37. Jaki jest wynik? + +```javascript +const numbers = [1, 2, 3]; +numbers[10] = 11; +console.log(numbers); +``` + +- A: `[1, 2, 3, null x 7, 11]` +- B: `[1, 2, 3, 11]` +- C: `[1, 2, 3, empty x 7, 11]` +- D: `SyntaxError` + +
Odpowiedź +

+ +#### Odpowiedź: C + +When you set a value to an element in an array that exceeds the length of the array, JavaScript creates something called "empty slots". These actually have the value of `undefined`, but you will see something like: + +`[1, 2, 3, empty x 7, 11]` + +depending on where you run it (it's different for every browser, node, etc.) + +

+
+ +--- + +###### 38. Jaki jest wynik? + +```javascript +(() => { + let x, y; + try { + throw new Error(); + } catch (x) { + (x = 1), (y = 2); + console.log(x); + } + console.log(x); + console.log(y); +})(); +``` + +- A: `1` `undefined` `2` +- B: `undefined` `undefined` `undefined` +- C: `1` `1` `2` +- D: `1` `undefined` `undefined` + +
Odpowiedź +

+ +#### Odpowiedź: A + +The `catch` block receives the argument `x`. This is not the same `x` as the variable when we pass arguments. This variable `x` is block-scoped. + +Later, we set this block-scoped variable equal to `1`, and set the value of the variable `y`. Now, we log the block-scoped variable `x`, which is equal to `1`. + +Outside of the `catch` block, `x` is still `undefined`, and `y` is `2`. When we want to `console.log(x)` outside of the `catch` block, it returns `undefined`, and `y` returns `2`. + +

+
+ +--- + +###### 39. Everything in JavaScript is either a... + +- A: primitive or object +- B: function or object +- C: trick question! only objects +- D: number or object + +
Odpowiedź +

+ +#### Odpowiedź: A + +JavaScript only has primitive types and objects. + +Primitive types are `boolean`, `null`, `undefined`, `bigint`, `number`, `string`, and `symbol`. + +What differentiates a primitive from an object is that primitives do not have any properties or methods; however, you'll note that `'foo'.toUpperCase()` evaluates to `'FOO'` and does not result in a `TypeError`. This is because when you try to access a property or method on a primitive like a string, JavaScript will implicitly wrap the primitive type using one of the wrapper classes, i.e. `String`, and then immediately discard the wrapper after the expression evaluates. All primitives except for `null` and `undefined` exhibit this behaviour. + +

+
+ +--- + +###### 40. Jaki jest wynik? + +```javascript +[[0, 1], [2, 3]].reduce( + (acc, cur) => { + return acc.concat(cur); + }, + [1, 2], +); +``` + +- A: `[0, 1, 2, 3, 1, 2]` +- B: `[6, 1, 2]` +- C: `[1, 2, 0, 1, 2, 3]` +- D: `[1, 2, 6]` + +
Odpowiedź +

+ +#### Odpowiedź: C + +`[1, 2]` is our initial value. This is the value we start with, and the value of the very first `acc`. During the first round, `acc` is `[1,2]`, and `cur` is `[0, 1]`. We concatenate them, which results in `[1, 2, 0, 1]`. + +Then, `[1, 2, 0, 1]` is `acc` and `[2, 3]` is `cur`. We concatenate them, and get `[1, 2, 0, 1, 2, 3]` + +

+
+ +--- + +###### 41. Jaki jest wynik? + +```javascript +!!null; +!!''; +!!1; +``` + +- A: `false` `true` `false` +- B: `false` `false` `true` +- C: `false` `true` `true` +- D: `true` `true` `false` + +
Odpowiedź +

+ +#### Odpowiedź: B + +`null` is falsy. `!null` returns `true`. `!true` returns `false`. + +`""` is falsy. `!""` returns `true`. `!true` returns `false`. + +`1` is truthy. `!1` returns `false`. `!false` returns `true`. + +

+
+ +--- + +###### 42. What does the `setInterval` method return in the browser? + +```javascript +setInterval(() => console.log('Hi'), 1000); +``` + +- A: a unique id +- B: the amount of milliseconds specified +- C: the passed function +- D: `undefined` + +
Odpowiedź +

+ +#### Odpowiedź: A + +It returns a unique id. This id can be used to clear that interval with the `clearInterval()` function. + +

+
+ +--- + +###### 43. What does this return? + +```javascript +[...'Lydia']; +``` + +- A: `["L", "y", "d", "i", "a"]` +- B: `["Lydia"]` +- C: `[[], "Lydia"]` +- D: `[["L", "y", "d", "i", "a"]]` + +
Odpowiedź +

+ +#### Odpowiedź: A + +A string is an iterable. The spread operator maps every character of an iterable to one element. + +

+
+ +--- + +###### 44. Jaki jest wynik? + +```javascript +function* generator(i) { + yield i; + yield i * 2; +} + +const gen = generator(10); + +console.log(gen.next().value); +console.log(gen.next().value); +``` + +- A: `[0, 10], [10, 20]` +- B: `20, 20` +- C: `10, 20` +- D: `0, 10 and 10, 20` + +
Odpowiedź +

+ +#### Odpowiedź: C + +Regular functions cannot be stopped mid-way after invocation. However, a generator function can be "stopped" midway, and later continue from where it stopped. Every time a generator function encounters a `yield` keyword, the function yields the value specified after it. Note that the generator function in that case doesn’t _return_ the value, it _yields_ the value. + +First, we initialize the generator function with `i` equal to `10`. We invoke the generator function using the `next()` method. The first time we invoke the generator function, `i` is equal to `10`. It encounters the first `yield` keyword: it yields the value of `i`. The generator is now "paused", and `10` gets logged. + +Then, we invoke the function again with the `next()` method. It starts to continue where it stopped previously, still with `i` equal to `10`. Now, it encounters the next `yield` keyword, and yields `i * 2`. `i` is equal to `10`, so it returns `10 * 2`, which is `20`. This results in `10, 20`. + +

+
+ +--- + +###### 45. What does this return? + +```javascript +const firstPromise = new Promise((res, rej) => { + setTimeout(res, 500, 'one'); +}); + +const secondPromise = new Promise((res, rej) => { + setTimeout(res, 100, 'two'); +}); + +Promise.race([firstPromise, secondPromise]).then(res => console.log(res)); +``` + +- A: `"one"` +- B: `"two"` +- C: `"two" "one"` +- D: `"one" "two"` + +
Odpowiedź +

+ +#### Odpowiedź: B + +When we pass multiple promises to the `Promise.race` method, it resolves/rejects the _first_ promise that resolves/rejects. To the `setTimeout` method, we pass a timer: 500ms for the first promise (`firstPromise`), and 100ms for the second promise (`secondPromise`). This means that the `secondPromise` resolves first with the value of `'two'`. `res` now holds the value of `'two'`, which gets logged. + +

+
+ +--- + +###### 46. Jaki jest wynik? + +```javascript +let person = { name: 'Lydia' }; +const members = [person]; +person = null; + +console.log(members); +``` + +- A: `null` +- B: `[null]` +- C: `[{}]` +- D: `[{ name: "Lydia" }]` + +
Odpowiedź +

+ +#### Odpowiedź: D + +First, we declare a variable `person` with the value of an object that has a `name` property. + + + +Then, we declare a variable called `members`. We set the first element of that array equal to the value of the `person` variable. Objects interact by _reference_ when setting them equal to each other. When you assign a reference from one variable to another, you make a _copy_ of that reference. (note that they don't have the _same_ reference!) + + + +Then, we set the variable `person` equal to `null`. + + + +We are only modifying the value of the `person` variable, and not the first element in the array, since that element has a different (copied) reference to the object. The first element in `members` still holds its reference to the original object. When we log the `members` array, the first element still holds the value of the object, which gets logged. + +

+
+ +--- + +###### 47. Jaki jest wynik? + +```javascript +const person = { + name: 'Lydia', + age: 21, +}; + +for (const item in person) { + console.log(item); +} +``` + +- A: `{ name: "Lydia" }, { age: 21 }` +- B: `"name", "age"` +- C: `"Lydia", 21` +- D: `["name", "Lydia"], ["age", 21]` + +
Odpowiedź +

+ +#### Odpowiedź: B + +With a `for-in` loop, we can iterate through object keys, in this case `name` and `age`. Under the hood, object keys are strings (if they're not a Symbol). On every loop, we set the value of `item` equal to the current key it’s iterating over. First, `item` is equal to `name`, and gets logged. Then, `item` is equal to `age`, which gets logged. + +

+
+ +--- + +###### 48. Jaki jest wynik? + +```javascript +console.log(3 + 4 + '5'); +``` + +- A: `"345"` +- B: `"75"` +- C: `12` +- D: `"12"` + +
Odpowiedź +

+ +#### Odpowiedź: B + +Operator associativity is the order in which the compiler evaluates the expressions, either left-to-right or right-to-left. This only happens if all operators have the _same_ precedence. We only have one type of operator: `+`. For addition, the associativity is left-to-right. + +`3 + 4` gets evaluated first. This results in the number `7`. + +`7 + '5'` results in `"75"` because of coercion. JavaScript converts the number `7` into a string, see question 15. We can concatenate two strings using the `+`operator. `"7" + "5"` results in `"75"`. + +

+
+ +--- + +###### 49. What's the value of `num`? + +```javascript +const num = parseInt('7*6', 10); +``` + +- A: `42` +- B: `"42"` +- C: `7` +- D: `NaN` + +
Odpowiedź +

+ +#### Odpowiedź: C + +Only the first numbers in the string is returned. Based on the _radix_ (the second argument in order to specify what type of number we want to parse it to: base 10, hexadecimal, octal, binary, etc.), the `parseInt` checks whether the characters in the string are valid. Once it encounters a character that isn't a valid number in the radix, it stops parsing and ignores the following characters. + +`*` is not a valid number. It only parses `"7"` into the decimal `7`. `num` now holds the value of `7`. + +

+
+ +--- + +###### 50. Jaki jest wynik? + +```javascript +[1, 2, 3].map(num => { + if (typeof num === 'number') return; + return num * 2; +}); +``` + +- A: `[]` +- B: `[null, null, null]` +- C: `[undefined, undefined, undefined]` +- D: `[ 3 x empty ]` + +
Odpowiedź +

+ +#### Odpowiedź: C + +When mapping over the array, the value of `num` is equal to the element it’s currently looping over. In this case, the elements are numbers, so the condition of the if statement `typeof num === "number"` returns `true`. The map function creates a new array and inserts the values returned from the function. + +However, we don’t return a value. When we don’t return a value from the function, the function returns `undefined`. For every element in the array, the function block gets called, so for each element we return `undefined`. + +

+
+ +--- + +###### 51. Jaki jest wynik? + +```javascript +function getInfo(member, year) { + member.name = 'Lydia'; + year = '1998'; +} + +const person = { name: 'Sarah' }; +const birthYear = '1997'; + +getInfo(person, birthYear); + +console.log(person, birthYear); +``` + +- A: `{ name: "Lydia" }, "1997"` +- B: `{ name: "Sarah" }, "1998"` +- C: `{ name: "Lydia" }, "1998"` +- D: `{ name: "Sarah" }, "1997"` + +
Odpowiedź +

+ +#### Odpowiedź: A + +Arguments are passed by _value_, unless their value is an object, then they're passed by _reference_. `birthYear` is passed by value, since it's a string, not an object. When we pass arguments by value, a _copy_ of that value is created (see question 46). + +The variable `birthYear` has a reference to the value `"1997"`. The argument `year` also has a reference to the value `"1997"`, but it's not the same value as `birthYear` has a reference to. When we update the value of `year` by setting `year` equal to `"1998"`, we are only updating the value of `year`. `birthYear` is still equal to `"1997"`. + +The value of `person` is an object. The argument `member` has a (copied) reference to the _same_ object. When we modify a property of the object `member` has a reference to, the value of `person` will also be modified, since they both have a reference to the same object. `person`'s `name` property is now equal to the value `"Lydia"` + +

+
+ +--- + +###### 52. Jaki jest wynik? + +```javascript +function greeting() { + throw 'Hello world!'; +} + +function sayHi() { + try { + const data = greeting(); + console.log('It worked!', data); + } catch (e) { + console.log('Oh no an error:', e); + } +} + +sayHi(); +``` + +- A: `It worked! Hello world!` +- B: `Oh no an error: undefined` +- C: `SyntaxError: can only throw Error objects` +- D: `Oh no an error: Hello world!` + +
Odpowiedź +

+ +#### Odpowiedź: D + +With the `throw` statement, we can create custom errors. With this statement, you can throw exceptions. An exception can be a string, a number, a boolean or an object. In this case, our exception is the string `'Hello world!'`. + +With the `catch` statement, we can specify what to do if an exception is thrown in the `try` block. An exception is thrown: the string `'Hello world!'`. `e` is now equal to that string, which we log. This results in `'Oh an error: Hello world!'`. + +

+
+ +--- + +###### 53. Jaki jest wynik? + +```javascript +function Car() { + this.make = 'Lamborghini'; + return { make: 'Maserati' }; +} + +const myCar = new Car(); +console.log(myCar.make); +``` + +- A: `"Lamborghini"` +- B: `"Maserati"` +- C: `ReferenceError` +- D: `TypeError` + +
Odpowiedź +

+ +#### Odpowiedź: B + +When you return a property, the value of the property is equal to the _returned_ value, not the value set in the constructor function. We return the string `"Maserati"`, so `myCar.make` is equal to `"Maserati"`. + +

+
+ +--- + +###### 54. Jaki jest wynik? + +```javascript +(() => { + let x = (y = 10); +})(); + +console.log(typeof x); +console.log(typeof y); +``` + +- A: `"undefined", "number"` +- B: `"number", "number"` +- C: `"object", "number"` +- D: `"number", "undefined"` + +
Odpowiedź +

+ +#### Odpowiedź: A + +`let x = (y = 10);` is actually shorthand for: + +```javascript +y = 10; +let x = y; +``` + +When we set `y` equal to `10`, we actually add a property `y` to the global object (`window` in browser, `global` in Node). In a browser, `window.y` is now equal to `10`. + +Then, we declare a variable `x` with the value of `y`, which is `10`. Variables declared with the `let` keyword are _block scoped_, they are only defined within the block they're declared in; the immediately invoked function expression (IIFE) in this case. When we use the `typeof` operator, the operand `x` is not defined: we are trying to access `x` outside of the block it's declared in. This means that `x` is not defined. Values who haven't been assigned a value or declared are of type `"undefined"`. `console.log(typeof x)` returns `"undefined"`. + +However, we created a global variable `y` when setting `y` equal to `10`. This value is accessible anywhere in our code. `y` is defined, and holds a value of type `"number"`. `console.log(typeof y)` returns `"number"`. + +

+
+ +--- + +###### 55. Jaki jest wynik? + +```javascript +class Dog { + constructor(name) { + this.name = name; + } +} + +Dog.prototype.bark = function() { + console.log(`Woof I am ${this.name}`); +}; + +const pet = new Dog('Mara'); + +pet.bark(); + +delete Dog.prototype.bark; + +pet.bark(); +``` + +- A: `"Woof I am Mara"`, `TypeError` +- B: `"Woof I am Mara"`, `"Woof I am Mara"` +- C: `"Woof I am Mara"`, `undefined` +- D: `TypeError`, `TypeError` + +
Odpowiedź +

+ +#### Odpowiedź: A + +We can delete properties from objects using the `delete` keyword, also on the prototype. By deleting a property on the prototype, it is not available anymore in the prototype chain. In this case, the `bark` function is not available anymore on the prototype after `delete Dog.prototype.bark`, yet we still try to access it. + +When we try to invoke something that is not a function, a `TypeError` is thrown. In this case `TypeError: pet.bark is not a function`, since `pet.bark` is `undefined`. + +

+
+ +--- + +###### 56. Jaki jest wynik? + +```javascript +const set = new Set([1, 1, 2, 3, 4]); + +console.log(set); +``` + +- A: `[1, 1, 2, 3, 4]` +- B: `[1, 2, 3, 4]` +- C: `{1, 1, 2, 3, 4}` +- D: `{1, 2, 3, 4}` + +
Odpowiedź +

+ +#### Odpowiedź: D + +The `Set` object is a collection of _unique_ values: a value can only occur once in a set. + +We passed the iterable `[1, 1, 2, 3, 4]` with a duplicate value `1`. Since we cannot have two of the same values in a set, one of them is removed. This results in `{1, 2, 3, 4}`. + +

+
+ +--- + +###### 57. Jaki jest wynik? + +```javascript +// counter.js +let counter = 10; +export default counter; +``` + +```javascript +// index.js +import myCounter from './counter'; + +myCounter += 1; + +console.log(myCounter); +``` + +- A: `10` +- B: `11` +- C: `Error` +- D: `NaN` + +
Odpowiedź +

+ +#### Odpowiedź: C + +An imported module is _read-only_: you cannot modify the imported module. Only the module that exports them can change its value. + +When we try to increment the value of `myCounter`, it throws an error: `myCounter` is read-only and cannot be modified. + +

+
+ +--- + +###### 58. Jaki jest wynik? + +```javascript +const name = 'Lydia'; +age = 21; + +console.log(delete name); +console.log(delete age); +``` + +- A: `false`, `true` +- B: `"Lydia"`, `21` +- C: `true`, `true` +- D: `undefined`, `undefined` + +
Odpowiedź +

+ +#### Odpowiedź: A + +The `delete` operator returns a boolean value: `true` on a successful deletion, else it'll return `false`. However, variables declared with the `var`, `const` or `let` keyword cannot be deleted using the `delete` operator. + +The `name` variable was declared with a `const` keyword, so its deletion is not successful: `false` is returned. When we set `age` equal to `21`, we actually added a property called `age` to the global object. You can successfully delete properties from objects this way, also the global object, so `delete age` returns `true`. + +

+
+ +--- + +###### 59. Jaki jest wynik? + +```javascript +const numbers = [1, 2, 3, 4, 5]; +const [y] = numbers; + +console.log(y); +``` + +- A: `[[1, 2, 3, 4, 5]]` +- B: `[1, 2, 3, 4, 5]` +- C: `1` +- D: `[1]` + +
Odpowiedź +

+ +#### Odpowiedź: C + +We can unpack values from arrays or properties from objects through destructuring. For example: + +```javascript +[a, b] = [1, 2]; +``` + + + +The value of `a` is now `1`, and the value of `b` is now `2`. What we actually did in the question, is: + +```javascript +[y] = [1, 2, 3, 4, 5]; +``` + + + +This means that the value of `y` is equal to the first value in the array, which is the number `1`. When we log `y`, `1` is returned. + +

+
+ +--- + +###### 60. Jaki jest wynik? + +```javascript +const user = { name: 'Lydia', age: 21 }; +const admin = { admin: true, ...user }; + +console.log(admin); +``` + +- A: `{ admin: true, user: { name: "Lydia", age: 21 } }` +- B: `{ admin: true, name: "Lydia", age: 21 }` +- C: `{ admin: true, user: ["Lydia", 21] }` +- D: `{ admin: true }` + +
Odpowiedź +

+ +#### Odpowiedź: B + +It's possible to combine objects using the spread operator `...`. It lets you create copies of the key/value pairs of one object, and add them to another object. In this case, we create copies of the `user` object, and add them to the `admin` object. The `admin` object now contains the copied key/value pairs, which results in `{ admin: true, name: "Lydia", age: 21 }`. + +

+
+ +--- + +###### 61. Jaki jest wynik? + +```javascript +const person = { name: 'Lydia' }; + +Object.defineProperty(person, 'age', { value: 21 }); + +console.log(person); +console.log(Object.keys(person)); +``` + +- A: `{ name: "Lydia", age: 21 }`, `["name", "age"]` +- B: `{ name: "Lydia", age: 21 }`, `["name"]` +- C: `{ name: "Lydia"}`, `["name", "age"]` +- D: `{ name: "Lydia"}`, `["age"]` + +
Odpowiedź +

+ +#### Odpowiedź: B + +With the `defineProperty` method, we can add new properties to an object, or modify existing ones. When we add a property to an object using the `defineProperty` method, they are by default _not enumerable_. The `Object.keys` method returns all _enumerable_ property names from an object, in this case only `"name"`. + +Properties added using the `defineProperty` method are immutable by default. You can override this behavior using the `writable`, `configurable` and `enumerable` properties. This way, the `defineProperty` method gives you a lot more control over the properties you're adding to an object. + +

+
+ +--- + +###### 62. Jaki jest wynik? + +```javascript +const settings = { + username: 'lydiahallie', + level: 19, + health: 90, +}; + +const data = JSON.stringify(settings, ['level', 'health']); +console.log(data); +``` + +- A: `"{"level":19, "health":90}"` +- B: `"{"username": "lydiahallie"}"` +- C: `"["level", "health"]"` +- D: `"{"username": "lydiahallie", "level":19, "health":90}"` + +
Odpowiedź +

+ +#### Odpowiedź: A + +The second argument of `JSON.stringify` is the _replacer_. The replacer can either be a function or an array, and lets you control what and how the values should be stringified. + +If the replacer is an _array_, only the property names included in the array will be added to the JSON string. In this case, only the properties with the names `"level"` and `"health"` are included, `"username"` is excluded. `data` is now equal to `"{"level":19, "health":90}"`. + +If the replacer is a _function_, this function gets called on every property in the object you're stringifying. The value returned from this function will be the value of the property when it's added to the JSON string. If the value is `undefined`, this property is excluded from the JSON string. + +

+
+ +--- + +###### 63. Jaki jest wynik? + +```javascript +let num = 10; + +const increaseNumber = () => num++; +const increasePassedNumber = number => number++; + +const num1 = increaseNumber(); +const num2 = increasePassedNumber(num1); + +console.log(num1); +console.log(num2); +``` + +- A: `10`, `10` +- B: `10`, `11` +- C: `11`, `11` +- D: `11`, `12` + +
Odpowiedź +

+ +#### Odpowiedź: A + +The unary operator `++` _first returns_ the value of the operand, _then increments_ the value of the operand. The value of `num1` is `10`, since the `increaseNumber` function first returns the value of `num`, which is `10`, and only increments the value of `num` afterwards. + +`num2` is `10`, since we passed `num1` to the `increasePassedNumber`. `number` is equal to `10`(the value of `num1`. Again, the unary operator `++` _first returns_ the value of the operand, _then increments_ the value of the operand. The value of `number` is `10`, so `num2` is equal to `10`. + +

+
+ +--- + +###### 64. Jaki jest wynik? + +```javascript +const value = { number: 10 }; + +const multiply = (x = { ...value }) => { + console.log((x.number *= 2)); +}; + +multiply(); +multiply(); +multiply(value); +multiply(value); +``` + +- A: `20`, `40`, `80`, `160` +- B: `20`, `40`, `20`, `40` +- C: `20`, `20`, `20`, `40` +- D: `NaN`, `NaN`, `20`, `40` + +
Odpowiedź +

+ +#### Odpowiedź: C + +In ES6, we can initialize parameters with a default value. The value of the parameter will be the default value, if no other value has been passed to the function, or if the value of the parameter is `"undefined"`. In this case, we spread the properties of the `value` object into a new object, so `x` has the default value of `{ number: 10 }`. + +The default argument is evaluated at _call time_! Every time we call the function, a _new_ object is created. We invoke the `multiply` function the first two times without passing a value: `x` has the default value of `{ number: 10 }`. We then log the multiplied value of that number, which is `20`. + +The third time we invoke multiply, we do pass an argument: the object called `value`. The `*=` operator is actually shorthand for `x.number = x.number * 2`: we modify the value of `x.number`, and log the multiplied value `20`. + +The fourth time, we pass the `value` object again. `x.number` was previously modified to `20`, so `x.number *= 2` logs `40`. + +

+
+ +--- + +###### 65. Jaki jest wynik? + +```javascript +[1, 2, 3, 4].reduce((x, y) => console.log(x, y)); +``` + +- A: `1` `2` and `3` `3` and `6` `4` +- B: `1` `2` and `2` `3` and `3` `4` +- C: `1` `undefined` and `2` `undefined` and `3` `undefined` and `4` `undefined` +- D: `1` `2` and `undefined` `3` and `undefined` `4` + +
Odpowiedź +

+ +#### Odpowiedź: D + +The first argument that the `reduce` method receives is the _accumulator_, `x` in this case. The second argument is the _current value_, `y`. With the reduce method, we execute a callback function on every element in the array, which could ultimately result in one single value. + +In this example, we are not returning any values, we are simply logging the values of the accumulator and the current value. + +The value of the accumulator is equal to the previously returned value of the callback function. If you don't pass the optional `initialValue` argument to the `reduce` method, the accumulator is equal to the first element on the first call. + +On the first call, the accumulator (`x`) is `1`, and the current value (`y`) is `2`. We don't return from the callback function, we log the accumulator and current value: `1` and `2` get logged. + +If you don't return a value from a function, it returns `undefined`. On the next call, the accumulator is `undefined`, and the current value is `3`. `undefined` and `3` get logged. + +On the fourth call, we again don't return from the callback function. The accumulator is again `undefined`, and the current value is `4`. `undefined` and `4` get logged. + +

+
+ +--- + +###### 66. With which constructor can we successfully extend the `Dog` class? + +```javascript +class Dog { + constructor(name) { + this.name = name; + } +}; + +class Labrador extends Dog { + // 1 + constructor(name, size) { + this.size = size; + } + // 2 + constructor(name, size) { + super(name); + this.size = size; + } + // 3 + constructor(size) { + super(name); + this.size = size; + } + // 4 + constructor(name, size) { + this.name = name; + this.size = size; + } + +}; +``` + +- A: 1 +- B: 2 +- C: 3 +- D: 4 + +
Odpowiedź +

+ +#### Odpowiedź: B + +In a derived class, you cannot access the `this` keyword before calling `super`. If you try to do that, it will throw a ReferenceError: 1 and 4 would throw a reference error. + +With the `super` keyword, we call that parent class's constructor with the given arguments. The parent's constructor receives the `name` argument, so we need to pass `name` to `super`. + +The `Labrador` class receives two arguments, `name` since it extends `Dog`, and `size` as an extra property on the `Labrador` class. They both need to be passed to the constructor function on `Labrador`, which is done correctly using constructor 2. + +

+
+ +--- + +###### 67. Jaki jest wynik? + +```javascript +// index.js +console.log('running index.js'); +import { sum } from './sum.js'; +console.log(sum(1, 2)); + +// sum.js +console.log('running sum.js'); +export const sum = (a, b) => a + b; +``` + +- A: `running index.js`, `running sum.js`, `3` +- B: `running sum.js`, `running index.js`, `3` +- C: `running sum.js`, `3`, `running index.js` +- D: `running index.js`, `undefined`, `running sum.js` + +
Odpowiedź +

+ +#### Odpowiedź: B + +With the `import` keyword, all imported modules are _pre-parsed_. This means that the imported modules get run _first_, the code in the file which imports the module gets executed _after_. + +This is a difference between `require()` in CommonJS and `import`! With `require()`, you can load dependencies on demand while the code is being run. If we would have used `require` instead of `import`, `running index.js`, `running sum.js`, `3` would have been logged to the console. + +

+
+ +--- + +###### 68. Jaki jest wynik? + +```javascript +console.log(Number(2) === Number(2)); +console.log(Boolean(false) === Boolean(false)); +console.log(Symbol('foo') === Symbol('foo')); +``` + +- A: `true`, `true`, `false` +- B: `false`, `true`, `false` +- C: `true`, `false`, `true` +- D: `true`, `true`, `true` + +
Odpowiedź +

+ +#### Odpowiedź: A + +Every Symbol is entirely unique. The purpose of the argument passed to the Symbol is to give the Symbol a description. The value of the Symbol is not dependent on the passed argument. As we test equality, we are creating two entirely new symbols: the first `Symbol('foo')`, and the second `Symbol('foo')`. These two values are unique and not equal to each other, `Symbol('foo') === Symbol('foo')` returns `false`. + +

+
+ +--- + +###### 69. Jaki jest wynik? + +```javascript +const name = 'Lydia Hallie'; +console.log(name.padStart(13)); +console.log(name.padStart(2)); +``` + +- A: `"Lydia Hallie"`, `"Lydia Hallie"` +- B: `" Lydia Hallie"`, `" Lydia Hallie"` (`"[13x whitespace]Lydia Hallie"`, `"[2x whitespace]Lydia Hallie"`) +- C: `" Lydia Hallie"`, `"Lydia Hallie"` (`"[1x whitespace]Lydia Hallie"`, `"Lydia Hallie"`) +- D: `"Lydia Hallie"`, `"Lyd"`, + +
Odpowiedź +

+ +#### Odpowiedź: C + +With the `padStart` method, we can add padding to the beginning of a string. The value passed to this method is the _total_ length of the string together with the padding. The string `"Lydia Hallie"` has a length of `12`. `name.padStart(13)` inserts 1 space at the start of the string, because 12 + 1 is 13. + +If the argument passed to the `padStart` method is smaller than the length of the array, no padding will be added. + +

+
+ +--- + +###### 70. Jaki jest wynik? + +```javascript +console.log('🥑' + '💻'); +``` + +- A: `"🥑💻"` +- B: `257548` +- C: A string containing their code points +- D: Error + +
Odpowiedź +

+ +#### Odpowiedź: A + +With the `+` operator, you can concatenate strings. In this case, we are concatenating the string `"🥑"` with the string `"💻"`, resulting in `"🥑💻"`. + +

+
+ +--- + +###### 71. How can we log the values that are commented out after the console.log statement? + +```javascript +function* startGame() { + const answer = yield 'Do you love JavaScript?'; + if (answer !== 'Yes') { + return "Oh wow... Guess we're done here"; + } + return 'JavaScript loves you back ❤️'; +} + +const game = startGame(); +console.log(/* 1 */); // Do you love JavaScript? +console.log(/* 2 */); // JavaScript loves you back ❤️ +``` + +- A: `game.next("Yes").value` and `game.next().value` +- B: `game.next.value("Yes")` and `game.next.value()` +- C: `game.next().value` and `game.next("Yes").value` +- D: `game.next.value()` and `game.next.value("Yes")` + +
Odpowiedź +

+ +#### Odpowiedź: C + +A generator function "pauses" its execution when it sees the `yield` keyword. First, we have to let the function yield the string "Do you love JavaScript?", which can be done by calling `game.next().value`. + +Every line is executed, until it finds the first `yield` keyword. There is a `yield` keyword on the first line within the function: the execution stops with the first yield! _This means that the variable `answer` is not defined yet!_ + +When we call `game.next("Yes").value`, the previous `yield` is replaced with the value of the parameters passed to the `next()` function, `"Yes"` in this case. The value of the variable `answer` is now equal to `"Yes"`. The condition of the if-statement returns `false`, and `JavaScript loves you back ❤️` gets logged. + +

+
+ +--- + +###### 72. Jaki jest wynik? + +```javascript +console.log(String.raw`Hello\nworld`); +``` + +- A: `Hello world!` +- B: `Hello`
     `world` +- C: `Hello\nworld` +- D: `Hello\n`
     `world` + +
Odpowiedź +

+ +#### Odpowiedź: C + +`String.raw` returns a string where the escapes (`\n`, `\v`, `\t` etc.) are ignored! Backslashes can be an issue since you could end up with something like: + +`` const path = `C:\Documents\Projects\table.html` `` + +Which would result in: + +`"C:DocumentsProjects able.html"` + +With `String.raw`, it would simply ignore the escape and print: + +`C:\Documents\Projects\table.html` + +In this case, the string is `Hello\nworld`, which gets logged. + +

+
+ +--- + +###### 73. Jaki jest wynik? + +```javascript +async function getData() { + return await Promise.resolve('I made it!'); +} + +const data = getData(); +console.log(data); +``` + +- A: `"I made it!"` +- B: `Promise {: "I made it!"}` +- C: `Promise {}` +- D: `undefined` + +
Odpowiedź +

+ +#### Odpowiedź: C + +An async function always returns a promise. The `await` still has to wait for the promise to resolve: a pending promise gets returned when we call `getData()` in order to set `data` equal to it. + +If we wanted to get access to the resolved value `"I made it"`, we could have used the `.then()` method on `data`: + +`data.then(res => console.log(res))` + +This would've logged `"I made it!"` + +

+
+ +--- + +###### 74. Jaki jest wynik? + +```javascript +function addToList(item, list) { + return list.push(item); +} + +const result = addToList('apple', ['banana']); +console.log(result); +``` + +- A: `['apple', 'banana']` +- B: `2` +- C: `true` +- D: `undefined` + +
Odpowiedź +

+ +#### Odpowiedź: B + +The `.push()` method returns the _length_ of the new array! Previously, the array contained one element (the string `"banana"`) and had a length of `1`. After adding the string `"apple"` to the array, the array contains two elements, and has a length of `2`. This gets returned from the `addToList` function. + +The `push` method modifies the original array. If you wanted to return the _array_ from the function rather than the _length of the array_, you should have returned `list` after pushing `item` to it. + +

+
+ +--- + +###### 75. Jaki jest wynik? + +```javascript +const box = { x: 10, y: 20 }; + +Object.freeze(box); + +const shape = box; +shape.x = 100; + +console.log(shape); +``` + +- A: `{ x: 100, y: 20 }` +- B: `{ x: 10, y: 20 }` +- C: `{ x: 100 }` +- D: `ReferenceError` + +
Odpowiedź +

+ +#### Odpowiedź: B + +`Object.freeze` makes it impossible to add, remove, or modify properties of an object (unless the property's value is another object). + +When we create the variable `shape` and set it equal to the frozen object `box`, `shape` also refers to a frozen object. You can check whether an object is frozen by using `Object.isFrozen`. In this case, `Object.isFrozen(shape)` would return true, since the variable `shape` has a reference to a frozen object. + +Since `shape` is frozen, and since the value of `x` is not an object, we cannot modify the property `x`. `x` is still equal to `10`, and `{ x: 10, y: 20 }` gets logged. + +

+
+ +--- + +###### 76. Jaki jest wynik? + +```javascript +const { firstName: myName } = { firstName: 'Lydia' }; + +console.log(firstName); +``` + +- A: `"Lydia"` +- B: `"myName"` +- C: `undefined` +- D: `ReferenceError` + +
Odpowiedź +

+ +#### Odpowiedź: D + +By using [destructuring assignment](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment) syntax we can unpack values from arrays, or properties from objects, into distinct variables: + +```javascript +const { firstName } = { firstName: 'Lydia' }; +// ES5 version: +// var firstName = { firstName: 'Lydia' }.firstName; + +console.log(firstName); // "Lydia" +``` + +Also, a property can be unpacked from an object and assigned to a variable with a different name than the object property: + +```javascript +const { firstName: myName } = { firstName: 'Lydia' }; +// ES5 version: +// var myName = { firstName: 'Lydia' }.firstName; + +console.log(myName); // "Lydia" +console.log(firstName); // Uncaught ReferenceError: firstName is not defined +``` + +Therefore, `firstName` does not exist as a variable, thus attempting to access its value will raise a `ReferenceError`. + +**Note:** Be aware of the `global scope` properties: + +```javascript +const { name: myName } = { name: 'Lydia' }; + +console.log(myName); // "lydia" +console.log(name); // "" ----- Browser e.g. Chrome +console.log(name); // ReferenceError: name is not defined ----- NodeJS + +``` + +Whenever Javascript is unable to find a variable within the _current scope_, it climbs up the [Scope chain](https://github.com/getify/You-Dont-Know-JS/blob/2nd-ed/scope-closures/ch3.md) and searches for it and if it reaches the top-level scope, aka **Global scope**, and still doesn't find it, it will throw a `ReferenceError`. + +- In **Browsers** such as _Chrome_, `name` is a _deprecated global scope property_. In this example, the code is running inside _global scope_ and there is no user defined local variable for `name`, therefore it searches the predefined _variables/properties_ in the global scope which is in case of browsers, it searches through `window` object and it will extract the [window.name](https://developer.mozilla.org/en-US/docs/Web/API/Window/name) value which is equal to an **empty string**. + +- In **NodeJS**, there is no such property on the `global` object, thus attempting to access a non-existent variable will raise a [ReferenceError](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/Not_defined). + +

+
+ +--- + +###### 77. Is this a pure function? + +```javascript +function sum(a, b) { + return a + b; +} +``` + +- A: Yes +- B: No + +
Odpowiedź +

+ +#### Odpowiedź: A + +A pure function is a function that _always_ returns the same result, if the same arguments are passed. + +The `sum` function always returns the same result. If we pass `1` and `2`, it will _always_ return `3` without side effects. If we pass `5` and `10`, it will _always_ return `15`, and so on. This is the definition of a pure function. + +

+
+ +--- + +###### 78. What is the output? + +```javascript +const add = () => { + const cache = {}; + return num => { + if (num in cache) { + return `From cache! ${cache[num]}`; + } else { + const result = num + 10; + cache[num] = result; + return `Calculated! ${result}`; + } + }; +}; + +const addFunction = add(); +console.log(addFunction(10)); +console.log(addFunction(10)); +console.log(addFunction(5 * 2)); +``` + +- A: `Calculated! 20` `Calculated! 20` `Calculated! 20` +- B: `Calculated! 20` `From cache! 20` `Calculated! 20` +- C: `Calculated! 20` `From cache! 20` `From cache! 20` +- D: `Calculated! 20` `From cache! 20` `Error` + +
Odpowiedź +

+ +#### Odpowiedź: C + +The `add` function is a _memoized_ function. With memoization, we can cache the results of a function in order to speed up its execution. In this case, we create a `cache` object that stores the previously returned values. + +If we call the `addFunction` function again with the same argument, it first checks whether it has already gotten that value in its cache. If that's the case, the caches value will be returned, which saves on execution time. Else, if it's not cached, it will calculate the value and store it afterwards. + +We call the `addFunction` function three times with the same value: on the first invocation, the value of the function when `num` is equal to `10` isn't cached yet. The condition of the if-statement `num in cache` returns `false`, and the else block gets executed: `Calculated! 20` gets logged, and the value of the result gets added to the cache object. `cache` now looks like `{ 10: 20 }`. + +The second time, the `cache` object contains the value that gets returned for `10`. The condition of the if-statement `num in cache` returns `true`, and `'From cache! 20'` gets logged. + +The third time, we pass `5 * 2` to the function which gets evaluated to `10`. The `cache` object contains the value that gets returned for `10`. The condition of the if-statement `num in cache` returns `true`, and `'From cache! 20'` gets logged. + +

+
+ +--- + +###### 79. What is the output? + +```javascript +const myLifeSummedUp = ['☕', '💻', '🍷', '🍫']; + +for (let item in myLifeSummedUp) { + console.log(item); +} + +for (let item of myLifeSummedUp) { + console.log(item); +} +``` + +- A: `0` `1` `2` `3` and `"☕"` `"💻"` `"🍷"` `"🍫"` +- B: `"☕"` `"💻"` `"🍷"` `"🍫"` and `"☕"` `"💻"` `"🍷"` `"🍫"` +- C: `"☕"` `"💻"` `"🍷"` `"🍫"` and `0` `1` `2` `3` +- D: `0` `1` `2` `3` and `{0: "☕", 1: "💻", 2: "🍷", 3: "🍫"}` + +
Odpowiedź +

+ +#### Odpowiedź: A + +With a _for-in_ loop, we can iterate over **enumerable** properties. In an array, the enumerable properties are the "keys" of array elements, which are actually their indexes. You could see an array as: + +`{0: "☕", 1: "💻", 2: "🍷", 3: "🍫"}` + +Where the keys are the enumerable properties. `0` `1` `2` `3` get logged. + +With a _for-of_ loop, we can iterate over **iterables**. An array is an iterable. When we iterate over the array, the variable "item" is equal to the element it's currently iterating over, `"☕"` `"💻"` `"🍷"` `"🍫"` get logged. + +

+
+ +--- + +###### 80. What is the output? + +```javascript +const list = [1 + 2, 1 * 2, 1 / 2]; +console.log(list); +``` + +- A: `["1 + 2", "1 * 2", "1 / 2"]` +- B: `["12", 2, 0.5]` +- C: `[3, 2, 0.5]` +- D: `[1, 1, 1]` + +
Odpowiedź +

+ +#### Odpowiedź: C + +Array elements can hold any value. Numbers, strings, objects, other arrays, null, boolean values, undefined, and other expressions such as dates, functions, and calculations. + +The element will be equal to the returned value. `1 + 2` returns `3`, `1 * 2` returns `2`, and `1 / 2` returns `0.5`. + +

+
+ +--- + +###### 81. What is the output? + +```javascript +function sayHi(name) { + return `Hi there, ${name}`; +} + +console.log(sayHi()); +``` + +- A: `Hi there,` +- B: `Hi there, undefined` +- C: `Hi there, null` +- D: `ReferenceError` + +
Odpowiedź +

+ +#### Odpowiedź: B + +By default, arguments have the value of `undefined`, unless a value has been passed to the function. In this case, we didn't pass a value for the `name` argument. `name` is equal to `undefined` which gets logged. + +In ES6, we can overwrite this default `undefined` value with default parameters. For example: + +`function sayHi(name = "Lydia") { ... }` + +In this case, if we didn't pass a value or if we passed `undefined`, `name` would always be equal to the string `Lydia` + +

+
+ +--- + +###### 82. What is the output? + +```javascript +var status = '😎'; + +setTimeout(() => { + const status = '😍'; + + const data = { + status: '🥑', + getStatus() { + return this.status; + }, + }; + + console.log(data.getStatus()); + console.log(data.getStatus.call(this)); +}, 0); +``` + +- A: `"🥑"` and `"😍"` +- B: `"🥑"` and `"😎"` +- C: `"😍"` and `"😎"` +- D: `"😎"` and `"😎"` + +
Odpowiedź +

+ +#### Odpowiedź: B + +The value of the `this` keyword is dependent on where you use it. In a **method**, like the `getStatus` method, the `this` keyword refers to _the object that the method belongs to_. The method belongs to the `data` object, so `this` refers to the `data` object. When we log `this.status`, the `status` property on the `data` object gets logged, which is `"🥑"`. + +With the `call` method, we can change the object to which the `this` keyword refers. In **functions**, the `this` keyword refers to the _the object that the function belongs to_. We declared the `setTimeout` function on the _global object_, so within the `setTimeout` function, the `this` keyword refers to the _global object_. On the global object, there is a variable called _status_ with the value of `"😎"`. When logging `this.status`, `"😎"` gets logged. + +

+
+ +--- + +###### 83. What is the output? + +```javascript +const person = { + name: 'Lydia', + age: 21, +}; + +let city = person.city; +city = 'Amsterdam'; + +console.log(person); +``` + +- A: `{ name: "Lydia", age: 21 }` +- B: `{ name: "Lydia", age: 21, city: "Amsterdam" }` +- C: `{ name: "Lydia", age: 21, city: undefined }` +- D: `"Amsterdam"` + +
Odpowiedź +

+ +#### Odpowiedź: A + +We set the variable `city` equal to the value of the property called `city` on the `person` object. There is no property on this object called `city`, so the variable `city` has the value of `undefined`. + +Note that we are _not_ referencing the `person` object itself! We simply set the variable `city` equal to the current value of the `city` property on the `person` object. + +Then, we set `city` equal to the string `"Amsterdam"`. This doesn't change the person object: there is no reference to that object. + +When logging the `person` object, the unmodified object gets returned. + +

+
+ +--- + +###### 84. What is the output? + +```javascript +function checkAge(age) { + if (age < 18) { + const message = "Sorry, you're too young."; + } else { + const message = "Yay! You're old enough!"; + } + + return message; +} + +console.log(checkAge(21)); +``` + +- A: `"Sorry, you're too young."` +- B: `"Yay! You're old enough!"` +- C: `ReferenceError` +- D: `undefined` + +
Odpowiedź +

+ +#### Odpowiedź: C + +Variables with the `const` and `let` keyword are _block-scoped_. A block is anything between curly brackets (`{ }`). In this case, the curly brackets of the if/else statements. You cannot reference a variable outside of the block it's declared in, a ReferenceError gets thrown. + +

+
+ +--- + +###### 85. What kind of information would get logged? + +```javascript +fetch('https://www.website.com/api/user/1') + .then(res => res.json()) + .then(res => console.log(res)); +``` + +- A: The result of the `fetch` method. +- B: The result of the second invocation of the `fetch` method. +- C: The result of the callback in the previous `.then()`. +- D: It would always be undefined. + +
Odpowiedź +

+ +#### Odpowiedź: C + +The value of `res` in the second `.then` is equal to the returned value of the previous `.then`. You can keep chaining `.then`s like this, where the value is passed to the next handler. + +

+
+ +--- + +###### 86. Which option is a way to set `hasName` equal to `true`, provided you cannot pass `true` as an argument? + +```javascript +function getName(name) { + const hasName = // +} +``` + +- A: `!!name` +- B: `name` +- C: `new Boolean(name)` +- D: `name.length` + +
Odpowiedź +

+ +#### Odpowiedź: A + +With `!!name`, we determine whether the value of `name` is truthy or falsy. If name is truthy, which we want to test for, `!name` returns `false`. `!false` (which is what `!!name` practically is) returns `true`. + +By setting `hasName` equal to `name`, you set `hasName` equal to whatever value you passed to the `getName` function, not the boolean value `true`. + +`new Boolean(true)` returns an object wrapper, not the boolean value itself. + +`name.length` returns the length of the passed argument, not whether it's `true`. + +

+
+ +--- + +###### 87. Jaki jest wynik? + +```javascript +console.log('I want pizza'[0]); +``` + +- A: `"""` +- B: `"I"` +- C: `SyntaxError` +- D: `undefined` + +
Odpowiedź +

+ +#### Odpowiedź: B + +In order to get a character at a specific index of a string, you can use bracket notation. The first character in the string has index 0, and so on. In this case, we want to get the element with index 0, the character `"I'`, which gets logged. + +Note that this method is not supported in IE7 and below. In that case, use `.charAt()`. + +

+
+ +--- + +###### 88. Jaki jest wynik? + +```javascript +function sum(num1, num2 = num1) { + console.log(num1 + num2); +} + +sum(10); +``` + +- A: `NaN` +- B: `20` +- C: `ReferenceError` +- D: `undefined` + +
Odpowiedź +

+ +#### Odpowiedź: B + +You can set a default parameter's value equal to another parameter of the function, as long as they've been defined _before_ the default parameter. We pass the value `10` to the `sum` function. If the `sum` function only receives 1 argument, it means that the value for `num2` is not passed, and the value of `num1` is equal to the passed value `10` in this case. The default value of `num2` is the value of `num1`, which is `10`. `num1 + num2` returns `20`. + +If you're trying to set a default parameter's value equal to a parameter which is defined _after_ (to the right), the parameter's value hasn't been initialized yet, which will throw an error. + +

+
+ +--- + +###### 89. Jaki jest wynik? + +```javascript +// module.js +export default () => 'Hello world'; +export const name = 'Lydia'; + +// index.js +import * as data from './module'; + +console.log(data); +``` + +- A: `{ default: function default(), name: "Lydia" }` +- B: `{ default: function default() }` +- C: `{ default: "Hello world", name: "Lydia" }` +- D: Global object of `module.js` + +
Odpowiedź +

+ +#### Odpowiedź: A + +With the `import * as name` syntax, we import _all exports_ from the `module.js` file into the `index.js` file as a new object called `data` is created. In the `module.js` file, there are two exports: the default export, and a named export. The default export is a function which returns the string `"Hello World"`, and the named export is a variable called `name` which has the value of the string `"Lydia"`. + +The `data` object has a `default` property for the default export, other properties have the names of the named exports and their corresponding values. + +

+
+ +--- + +###### 90. Jaki jest wynik? + +```javascript +class Person { + constructor(name) { + this.name = name; + } +} + +const member = new Person('John'); +console.log(typeof member); +``` + +- A: `"class"` +- B: `"function"` +- C: `"object"` +- D: `"string"` + +
Odpowiedź +

+ +#### Odpowiedź: C + +Classes are syntactical sugar for function constructors. The equivalent of the `Person` class as a function constructor would be: + +```javascript +function Person(name) { + this.name = name; +} +``` + +Calling a function constructor with `new` results in the creation of an instance of `Person`, `typeof` keyword returns `"object"` for an instance. `typeof member` returns `"object"`. + +

+
+ +--- + +###### 91. Jaki jest wynik? + +```javascript +let newList = [1, 2, 3].push(4); + +console.log(newList.push(5)); +``` + +- A: `[1, 2, 3, 4, 5]` +- B: `[1, 2, 3, 5]` +- C: `[1, 2, 3, 4]` +- D: `Error` + +
Odpowiedź +

+ +#### Odpowiedź: D + +The `.push` method returns the _new length_ of the array, not the array itself! By setting `newList` equal to `[1, 2, 3].push(4)`, we set `newList` equal to the new length of the array: `4`. + +Then, we try to use the `.push` method on `newList`. Since `newList` is the numerical value `4`, we cannot use the `.push` method: a TypeError is thrown. + +

+
+ +--- + +###### 92. Jaki jest wynik? + +```javascript +function giveLydiaPizza() { + return 'Here is pizza!'; +} + +const giveLydiaChocolate = () => + "Here's chocolate... now go hit the gym already."; + +console.log(giveLydiaPizza.prototype); +console.log(giveLydiaChocolate.prototype); +``` + +- A: `{ constructor: ...}` `{ constructor: ...}` +- B: `{}` `{ constructor: ...}` +- C: `{ constructor: ...}` `{}` +- D: `{ constructor: ...}` `undefined` + +
Odpowiedź +

+ +#### Odpowiedź: D + +Regular functions, such as the `giveLydiaPizza` function, have a `prototype` property, which is an object (prototype object) with a `constructor` property. Arrow functions however, such as the `giveLydiaChocolate` function, do not have this `prototype` property. `undefined` gets returned when trying to access the `prototype` property using `giveLydiaChocolate.prototype`. + +

+
+ +--- + +###### 93. Jaki jest wynik? + +```javascript +const person = { + name: 'Lydia', + age: 21, +}; + +for (const [x, y] of Object.entries(person)) { + console.log(x, y); +} +``` + +- A: `name` `Lydia` and `age` `21` +- B: `["name", "Lydia"]` and `["age", 21]` +- C: `["name", "age"]` and `undefined` +- D: `Error` + +
Odpowiedź +

+ +#### Odpowiedź: A + +`Object.entries(person)` returns an array of nested arrays, containing the keys and objects: + +`[ [ 'name', 'Lydia' ], [ 'age', 21 ] ]` + +Using the `for-of` loop, we can iterate over each element in the array, the subarrays in this case. We can destructure the subarrays instantly in the for-of loop, using `const [x, y]`. `x` is equal to the first element in the subarray, `y` is equal to the second element in the subarray. + +The first subarray is `[ "name", "Lydia" ]`, with `x` equal to `"name"`, and `y` equal to `"Lydia"`, which get logged. +The second subarray is `[ "age", 21 ]`, with `x` equal to `"age"`, and `y` equal to `21`, which get logged. + +

+
+ +--- + +###### 94. Jaki jest wynik? + +```javascript +function getItems(fruitList, ...args, favoriteFruit) { + return [...fruitList, ...args, favoriteFruit] +} + +getItems(["banana", "apple"], "pear", "orange") +``` + +- A: `["banana", "apple", "pear", "orange"]` +- B: `[["banana", "apple"], "pear", "orange"]` +- C: `["banana", "apple", ["pear"], "orange"]` +- D: `SyntaxError` + +
Odpowiedź +

+ +#### Odpowiedź: D + +`...args` is a rest parameter. The rest parameter's value is an array containing all remaining arguments, **and can only be the last parameter**! In this example, the rest parameter was the second parameter. This is not possible, and will throw a syntax error. + +```javascript +function getItems(fruitList, favoriteFruit, ...args) { + return [...fruitList, ...args, favoriteFruit]; +} + +getItems(['banana', 'apple'], 'pear', 'orange'); +``` + +The above example works. This returns the array `[ 'banana', 'apple', 'orange', 'pear' ]` + +

+
+ +--- + +###### 95. Jaki jest wynik? + +```javascript +function nums(a, b) { + if (a > b) console.log('a is bigger'); + else console.log('b is bigger'); + return + a + b; +} + +console.log(nums(4, 2)); +console.log(nums(1, 2)); +``` + +- A: `a is bigger`, `6` and `b is bigger`, `3` +- B: `a is bigger`, `undefined` and `b is bigger`, `undefined` +- C: `undefined` and `undefined` +- D: `SyntaxError` + +
Odpowiedź +

+ +#### Odpowiedź: B + +In JavaScript, we don't _have_ to write the semicolon (`;`) explicitly, however the JavaScript engine still adds them after statements. This is called **Automatic Semicolon Insertion**. A statement can for example be variables, or keywords like `throw`, `return`, `break`, etc. + +Here, we wrote a `return` statement, and another value `a + b` on a _new line_. However, since it's a new line, the engine doesn't know that it's actually the value that we wanted to return. Instead, it automatically added a semicolon after `return`. You could see this as: + +```javascript +return; +a + b; +``` + +This means that `a + b` is never reached, since a function stops running after the `return` keyword. If no value gets returned, like here, the function returns `undefined`. Note that there is no automatic insertion after `if/else` statements! + +

+
+ +--- + +###### 96. Jaki jest wynik? + +```javascript +class Person { + constructor() { + this.name = 'Lydia'; + } +} + +Person = class AnotherPerson { + constructor() { + this.name = 'Sarah'; + } +}; + +const member = new Person(); +console.log(member.name); +``` + +- A: `"Lydia"` +- B: `"Sarah"` +- C: `Error: cannot redeclare Person` +- D: `SyntaxError` + +
Odpowiedź +

+ +#### Odpowiedź: B + +We can set classes equal to other classes/function constructors. In this case, we set `Person` equal to `AnotherPerson`. The name on this constructor is `Sarah`, so the name property on the new `Person` instance `member` is `"Sarah"`. + +

+
+ +--- + +###### 97. Jaki jest wynik? + +```javascript +const info = { + [Symbol('a')]: 'b', +}; + +console.log(info); +console.log(Object.keys(info)); +``` + +- A: `{Symbol('a'): 'b'}` and `["{Symbol('a')"]` +- B: `{}` and `[]` +- C: `{ a: "b" }` and `["a"]` +- D: `{Symbol('a'): 'b'}` and `[]` + +
Odpowiedź +

+ +#### Odpowiedź: D + +A Symbol is not _enumerable_. The Object.keys method returns all _enumerable_ key properties on an object. The Symbol won't be visible, and an empty array is returned. When logging the entire object, all properties will be visible, even non-enumerable ones. + +This is one of the many qualities of a symbol: besides representing an entirely unique value (which prevents accidental name collision on objects, for example when working with 2 libraries that want to add properties to the same object), you can also "hide" properties on objects this way (although not entirely. You can still access symbols using the `Object.getOwnPropertySymbols()` method). + +

+
+ +--- + +###### 98. Jaki jest wynik? + +```javascript +const getList = ([x, ...y]) => [x, y] +const getUser = user => { name: user.name, age: user.age } + +const list = [1, 2, 3, 4] +const user = { name: "Lydia", age: 21 } + +console.log(getList(list)) +console.log(getUser(user)) +``` + +- A: `[1, [2, 3, 4]]` and `SyntaxError` +- B: `[1, [2, 3, 4]]` and `{ name: "Lydia", age: 21 }` +- C: `[1, 2, 3, 4]` and `{ name: "Lydia", age: 21 }` +- D: `Error` and `{ name: "Lydia", age: 21 }` + +
Odpowiedź +

+ +#### Odpowiedź: A + +The `getList` function receives an array as its argument. Between the parentheses of the `getList` function, we destructure this array right away. You could see this as: + +`[x, ...y] = [1, 2, 3, 4]` + +With the rest parameter `...y`, we put all "remaining" arguments in an array. The remaining arguments are `2`, `3` and `4` in this case. The value of `y` is an array, containing all the rest parameters. The value of `x` is equal to `1` in this case, so when we log `[x, y]`, `[1, [2, 3, 4]]` gets logged. + +The `getUser` function receives an object. With arrow functions, we don't _have_ to write curly brackets if we just return one value. However, if you want to instantly return an _object_ from an arrow function, you have to write it between parentheses, otherwise everything between the two braces will be interpreted as a block statement. In this case the code between the braces is not a valid JavaScript code, so a `SyntaxError` gets thrown. + +The following function would have returned an object: + +`const getUser = user => ({ name: user.name, age: user.age })` + +

+
+ +--- + +###### 99. Jaki jest wynik? + +```javascript +const name = 'Lydia'; + +console.log(name()); +``` + +- A: `SyntaxError` +- B: `ReferenceError` +- C: `TypeError` +- D: `undefined` + +
Odpowiedź +

+ +#### Odpowiedź: C + +The variable `name` holds the value of a string, which is not a function, thus cannot invoke. + +TypeErrors get thrown when a value is not of the expected type. JavaScript expected `name` to be a function since we're trying to invoke it. It was a string however, so a TypeError gets thrown: name is not a function! + +SyntaxErrors get thrown when you've written something that isn't valid JavaScript, for example when you've written the word `return` as `retrun`. +ReferenceErrors get thrown when JavaScript isn't able to find a reference to a value that you're trying to access. + +

+
+ +--- + +###### 100. What's the value of output? + +```javascript +// 🎉✨ This is my 100th question! ✨🎉 + +const output = `${[] && 'Im'}possible! +You should${'' && `n't`} see a therapist after so much JavaScript lol`; +``` + +- A: `possible! You should see a therapist after so much JavaScript lol` +- B: `Impossible! You should see a therapist after so much JavaScript lol` +- C: `possible! You shouldn't see a therapist after so much JavaScript lol` +- D: `Impossible! You shouldn't see a therapist after so much JavaScript lol` + +
Odpowiedź +

+ +#### Odpowiedź: B + +`[]` is a truthy value. With the `&&` operator, the right-hand value will be returned if the left-hand value is a truthy value. In this case, the left-hand value `[]` is a truthy value, so `"Im'` gets returned. + +`""` is a falsy value. If the left-hand value is falsy, nothing gets returned. `n't` doesn't get returned. + +

+
+ +--- + +###### 101. What's the value of output? + +```javascript +const one = false || {} || null; +const two = null || false || ''; +const three = [] || 0 || true; + +console.log(one, two, three); +``` + +- A: `false` `null` `[]` +- B: `null` `""` `true` +- C: `{}` `""` `[]` +- D: `null` `null` `true` + +
Odpowiedź +

+ +#### Odpowiedź: C + +With the `||` operator, we can return the first truthy operand. If all values are falsy, the last operand gets returned. + +`(false || {} || null)`: the empty object `{}` is a truthy value. This is the first (and only) truthy value, which gets returned. `one` is equal to `{}`. + +`(null || false || "")`: all operands are falsy values. This means that the last operand, `""` gets returned. `two` is equal to `""`. + +`([] || 0 || "")`: the empty array`[]` is a truthy value. This is the first truthy value, which gets returned. `three` is equal to `[]`. + +

+
+ +--- + +###### 102. What's the value of output? + +```javascript +const myPromise = () => Promise.resolve('I have resolved!'); + +function firstFunction() { + myPromise().then(res => console.log(res)); + console.log('second'); +} + +async function secondFunction() { + console.log(await myPromise()); + console.log('second'); +} + +firstFunction(); +secondFunction(); +``` + +- A: `I have resolved!`, `second` and `I have resolved!`, `second` +- B: `second`, `I have resolved!` and `second`, `I have resolved!` +- C: `I have resolved!`, `second` and `second`, `I have resolved!` +- D: `second`, `I have resolved!` and `I have resolved!`, `second` + +
Odpowiedź +

+ +#### Odpowiedź: D + +With a promise, we basically say _I want to execute this function, but I'll put it aside for now while it's running since this might take a while. Only when a certain value is resolved (or rejected), and when the call stack is empty, I want to use this value._ + +We can get this value with both `.then` and the `await` keyword in an `async` function. Although we can get a promise's value with both `.then` and `await`, they work a bit differently. + +In the `firstFunction`, we (sort of) put the myPromise function aside while it was running, but continued running the other code, which is `console.log('second')` in this case. Then, the function resolved with the string `I have resolved`, which then got logged after it saw that the callstack was empty. + +With the await keyword in `secondFunction`, we literally pause the execution of an async function until the value has been resolved before moving to the next line. + +This means that it waited for the `myPromise` to resolve with the value `I have resolved`, and only once that happened, we moved to the next line: `second` got logged. + +

+
+ +--- + +###### 103. What's the value of output? + +```javascript +const set = new Set(); + +set.add(1); +set.add('Lydia'); +set.add({ name: 'Lydia' }); + +for (let item of set) { + console.log(item + 2); +} +``` + +- A: `3`, `NaN`, `NaN` +- B: `3`, `7`, `NaN` +- C: `3`, `Lydia2`, `[object Object]2` +- D: `"12"`, `Lydia2`, `[object Object]2` + +
Odpowiedź +

+ +#### Odpowiedź: C + +The `+` operator is not only used for adding numerical values, but we can also use it to concatenate strings. Whenever the JavaScript engine sees that one or more values are not a number, it coerces the number into a string. + +The first one is `1`, which is a numerical value. `1 + 2` returns the number 3. + +However, the second one is a string `"Lydia"`. `"Lydia"` is a string and `2` is a number: `2` gets coerced into a string. `"Lydia"` and `"2"` get concatenated, which results in the string `"Lydia2"`. + +`{ name: "Lydia" }` is an object. Neither a number nor an object is a string, so it stringifies both. Whenever we stringify a regular object, it becomes `"[object Object]"`. `"[object Object]"` concatenated with `"2"` becomes `"[object Object]2"`. + +

+
+ +--- + +###### 104. What's its value? + +```javascript +Promise.resolve(5); +``` + +- A: `5` +- B: `Promise {: 5}` +- C: `Promise {: 5}` +- D: `Error` + +
Odpowiedź +

+ +#### Odpowiedź: C + +We can pass any type of value we want to `Promise.resolve`, either a promise or a non-promise. The method itself returns a promise with the resolved value (``). If you pass a regular function, it'll be a resolved promise with a regular value. If you pass a promise, it'll be a resolved promise with the resolved value of that passed promise. + +In this case, we just passed the numerical value `5`. It returns a resolved promise with the value `5`. + +

+
+ +--- + +###### 105. What's its value? + +```javascript +function compareMembers(person1, person2 = person) { + if (person1 !== person2) { + console.log('Not the same!'); + } else { + console.log('They are the same!'); + } +} + +const person = { name: 'Lydia' }; + +compareMembers(person); +``` + +- A: `Not the same!` +- B: `They are the same!` +- C: `ReferenceError` +- D: `SyntaxError` + +
Odpowiedź +

+ +#### Odpowiedź: B + +Objects are passed by reference. When we check objects for strict equality (`===`), we're comparing their references. + +We set the default value for `person2` equal to the `person` object, and passed the `person` object as the value for `person1`. + +This means that both values have a reference to the same spot in memory, thus they are equal. + +The code block in the `else` statement gets run, and `They are the same!` gets logged. + +

+
+ +--- + +###### 106. What's its value? + +```javascript +const colorConfig = { + red: true, + blue: false, + green: true, + black: true, + yellow: false, +}; + +const colors = ['pink', 'red', 'blue']; + +console.log(colorConfig.colors[1]); +``` + +- A: `true` +- B: `false` +- C: `undefined` +- D: `TypeError` + +
Odpowiedź +

+ +#### Odpowiedź: D + +In JavaScript, we have two ways to access properties on an object: bracket notation, or dot notation. In this example, we use dot notation (`colorConfig.colors`) instead of bracket notation (`colorConfig["colors"]`). + +With dot notation, JavaScript tries to find the property on the object with that exact name. In this example, JavaScript tries to find a property called `colors` on the `colorConfig` object. There is no property called `colors`, so this returns `undefined`. Then, we try to access the value of the first element by using `[1]`. We cannot do this on a value that's `undefined`, so it throws a `TypeError`: `Cannot read property '1' of undefined`. + +JavaScript interprets (or unboxes) statements. When we use bracket notation, it sees the first opening bracket `[` and keeps going until it finds the closing bracket `]`. Only then, it will evaluate the statement. If we would've used `colorConfig[colors[1]]`, it would have returned the value of the `red` property on the `colorConfig` object. + +

+
+ +--- + +###### 107. What's its value? + +```javascript +console.log('❤️' === '❤️'); +``` + +- A: `true` +- B: `false` + +
Odpowiedź +

+ +#### Odpowiedź: A + +Under the hood, emojis are unicodes. The unicodes for the heart emoji is `"U+2764 U+FE0F"`. These are always the same for the same emojis, so we're comparing two equal strings to each other, which returns true. + +

+
+ +--- + +###### 108. Which of these methods modifies the original array? + +```javascript +const emojis = ['✨', '🥑', '😍']; + +emojis.map(x => x + '✨'); +emojis.filter(x => x !== '🥑'); +emojis.find(x => x !== '🥑'); +emojis.reduce((acc, cur) => acc + '✨'); +emojis.slice(1, 2, '✨'); +emojis.splice(1, 2, '✨'); +``` + +- A: `All of them` +- B: `map` `reduce` `slice` `splice` +- C: `map` `slice` `splice` +- D: `splice` + +
Odpowiedź +

+ +#### Odpowiedź: D + +With `splice` method, we modify the original array by deleting, replacing or adding elements. In this case, we removed 2 items from index 1 (we removed `'🥑'` and `'😍'`) and added the ✨ emoji instead. + +`map`, `filter` and `slice` return a new array, `find` returns an element, and `reduce` returns a reduced value. + +

+
+ +--- + +###### 109. Jaki jest wynik? + +```javascript +const food = ['🍕', '🍫', '🥑', '🍔']; +const info = { favoriteFood: food[0] }; + +info.favoriteFood = '🍝'; + +console.log(food); +``` + +- A: `['🍕', '🍫', '🥑', '🍔']` +- B: `['🍝', '🍫', '🥑', '🍔']` +- C: `['🍝', '🍕', '🍫', '🥑', '🍔']` +- D: `ReferenceError` + +
Odpowiedź +

+ +#### Odpowiedź: A + +We set the value of the `favoriteFood` property on the `info` object equal to the string with the pizza emoji, `'🍕'`. A string is a primitive data type. In JavaScript, primitive data types don't interact by reference. + +In JavaScript, primitive data types (everything that's not an object) interact by _value_. In this case, we set the value of the `favoriteFood` property on the `info` object equal to the value of the first element in the `food` array, the string with the pizza emoji in this case (`'🍕'`). A string is a primitive data type, and interact by value (see my [blogpost](https://www.theavocoder.com/complete-javascript/2018/12/21/by-value-vs-by-reference) if you're interested in learning more) + +Then, we change the value of the `favoriteFood` property on the `info` object. The `food` array hasn't changed, since the value of `favoriteFood` was merely a _copy_ of the value of the first element in the array, and doesn't have a reference to the same spot in memory as the element on `food[0]`. When we log food, it's still the original array, `['🍕', '🍫', '🥑', '🍔']`. + +

+
+ +--- + +###### 110. What does this method do? + +```javascript +JSON.parse(); +``` + +- A: Parses JSON to a JavaScript value +- B: Parses a JavaScript object to JSON +- C: Parses any JavaScript value to JSON +- D: Parses JSON to a JavaScript object only + +
Odpowiedź +

+ +#### Odpowiedź: A + +With the `JSON.parse()` method, we can parse JSON string to a JavaScript value. + +```javascript +// Stringifying a number into valid JSON, then parsing the JSON string to a JavaScript value: +const jsonNumber = JSON.stringify(4); // '4' +JSON.parse(jsonNumber); // 4 + +// Stringifying an array value into valid JSON, then parsing the JSON string to a JavaScript value: +const jsonArray = JSON.stringify([1, 2, 3]); // '[1, 2, 3]' +JSON.parse(jsonArray); // [1, 2, 3] + +// Stringifying an object into valid JSON, then parsing the JSON string to a JavaScript value: +const jsonArray = JSON.stringify({ name: 'Lydia' }); // '{"name":"Lydia"}' +JSON.parse(jsonArray); // { name: 'Lydia' } +``` + +

+
+ +--- + +###### 111. Jaki jest wynik? + +```javascript +let name = 'Lydia'; + +function getName() { + console.log(name); + let name = 'Sarah'; +} + +getName(); +``` + +- A: Lydia +- B: Sarah +- C: `undefined` +- D: `ReferenceError` + +
Odpowiedź +

+ +#### Odpowiedź: D + +Each function has its own _execution context_ (or _scope_). The `getName` function first looks within its own context (scope) to see if it contains the variable `name` we're trying to access. In this case, the `getName` function contains its own `name` variable: we declare the variable `name` with the `let` keyword, and with the value of `'Sarah'`. + +Variables with the `let` keyword (and `const`) are hoisted, but unlike `var`, don't get initialized. They are not accessible before the line we declare (initialize) them. This is called the "temporal dead zone". When we try to access the variables before they are declared, JavaScript throws a `ReferenceError`. + +If we wouldn't have declared the `name` variable within the `getName` function, the javascript engine would've looked down the _scope chain_. The outer scope has a variable called `name` with the value of `Lydia`. In that case, it would've logged `Lydia`. + +```javascript +let name = 'Lydia'; + +function getName() { + console.log(name); +} + +getName(); // Lydia +``` + +

+
+ +--- + +###### 112. Jaki jest wynik? + +```javascript +function* generatorOne() { + yield ['a', 'b', 'c']; +} + +function* generatorTwo() { + yield* ['a', 'b', 'c']; +} + +const one = generatorOne(); +const two = generatorTwo(); + +console.log(one.next().value); +console.log(two.next().value); +``` + +- A: `a` and `a` +- B: `a` and `undefined` +- C: `['a', 'b', 'c']` and `a` +- D: `a` and `['a', 'b', 'c']` + +
Odpowiedź +

+ +#### Odpowiedź: C + +With the `yield` keyword, we `yield` values in a generator function. With the `yield*` keyword, we can yield values from another generator function, or iterable object (for example an array). + +In `generatorOne`, we yield the entire array `['a', 'b', 'c']` using the `yield` keyword. The value of `value` property on the object returned by the `next` method on `one` (`one.next().value`) is equal to the entire array `['a', 'b', 'c']`. + +```javascript +console.log(one.next().value); // ['a', 'b', 'c'] +console.log(one.next().value); // undefined +``` + +In `generatorTwo`, we use the `yield*` keyword. This means that the first yielded value of `two`, is equal to the first yielded value in the iterator. The iterator is the array `['a', 'b', 'c']`. The first yielded value is `a`, so the first time we call `two.next().value`, `a` is returned. + +```javascript +console.log(two.next().value); // 'a' +console.log(two.next().value); // 'b' +console.log(two.next().value); // 'c' +console.log(two.next().value); // undefined +``` + +

+
+ +--- + +###### 113. Jaki jest wynik? + +```javascript +console.log(`${(x => x)('I love')} to program`); +``` + +- A: `I love to program` +- B: `undefined to program` +- C: `${(x => x)('I love') to program` +- D: `TypeError` + +
Odpowiedź +

+ +#### Odpowiedź: A + +Expressions within template literals are evaluated first. This means that the string will contain the returned value of the expression, the immediately invoked function `(x => x)('I love')` in this case. We pass the value `'I love'` as an argument to the `x => x` arrow function. `x` is equal to `'I love'`, which gets returned. This results in `I love to program`. + +

+
+ +--- + +###### 114. What will happen? + +```javascript +let config = { + alert: setInterval(() => { + console.log('Alert!'); + }, 1000), +}; + +config = null; +``` + +- A: The `setInterval` callback won't be invoked +- B: The `setInterval` callback gets invoked once +- C: The `setInterval` callback will still be called every second +- D: We never invoked `config.alert()`, config is `null` + +
Odpowiedź +

+ +#### Odpowiedź: C + +Normally when we set objects equal to `null`, those objects get _garbage collected_ as there is no reference anymore to that object. However, since the callback function within `setInterval` is an arrow function (thus bound to the `config` object), the callback function still holds a reference to the `config` object. +As long as there is a reference, the object won't get garbage collected. +Since this is an interval, setting `config` to `null` or `delete`-ing `config.alert` won't garbage-collect the interval, so the interval will still be called. +It should be cleared with `clearInterval(config.alert)` to remove it from memory. +Since it was not cleared, the `setInterval` callback function will still get invoked every 1000ms (1s). + +

+
+ +--- + +###### 115. Which method(s) will return the value `'Hello world!'`? + +```javascript +const myMap = new Map(); +const myFunc = () => 'greeting'; + +myMap.set(myFunc, 'Hello world!'); + +//1 +myMap.get('greeting'); +//2 +myMap.get(myFunc); +//3 +myMap.get(() => 'greeting'); +``` + +- A: 1 +- B: 2 +- C: 2 and 3 +- D: All of them + +
Odpowiedź +

+ +#### Odpowiedź: B + +When adding a key/value pair using the `set` method, the key will be the value of the first argument passed to the `set` function, and the value will be the second argument passed to the `set` function. The key is the _function_ `() => 'greeting'` in this case, and the value `'Hello world'`. `myMap` is now `{ () => 'greeting' => 'Hello world!' }`. + +1 is wrong, since the key is not `'greeting'` but `() => 'greeting'`. +3 is wrong, since we're creating a new function by passing it as a parameter to the `get` method. Object interact by _reference_. Functions are objects, which is why two functions are never strictly equal, even if they are identical: they have a reference to a different spot in memory. + +

+
+ +--- + +###### 116. Jaki jest wynik? + +```javascript +const person = { + name: 'Lydia', + age: 21, +}; + +const changeAge = (x = { ...person }) => (x.age += 1); +const changeAgeAndName = (x = { ...person }) => { + x.age += 1; + x.name = 'Sarah'; +}; + +changeAge(person); +changeAgeAndName(); + +console.log(person); +``` + +- A: `{name: "Sarah", age: 22}` +- B: `{name: "Sarah", age: 23}` +- C: `{name: "Lydia", age: 22}` +- D: `{name: "Lydia", age: 23}` + +
Odpowiedź +

+ +#### Odpowiedź: C + +Both the `changeAge` and `changeAgeAndName` functions have a default parameter, namely a _newly_ created object `{ ...person }`. This object has copies of all the key/values in the `person` object. + +First, we invoke the `changeAge` function and pass the `person` object as its argument. This function increases the value of the `age` property by 1. `person` is now `{ name: "Lydia", age: 22 }`. + +Then, we invoke the `changeAgeAndName` function, however we don't pass a parameter. Instead, the value of `x` is equal to a _new_ object: `{ ...person }`. Since it's a new object, it doesn't affect the values of the properties on the `person` object. `person` is still equal to `{ name: "Lydia", age: 22 }`. + +

+
+ +--- + +###### 117. Which of the following options will return `6`? + +```javascript +function sumValues(x, y, z) { + return x + y + z; +} +``` + +- A: `sumValues([...1, 2, 3])` +- B: `sumValues([...[1, 2, 3]])` +- C: `sumValues(...[1, 2, 3])` +- D: `sumValues([1, 2, 3])` + +
Odpowiedź +

+ +#### Odpowiedź: C + +With the spread operator `...`, we can _spread_ iterables to individual elements. The `sumValues` function receives three arguments: `x`, `y` and `z`. `...[1, 2, 3]` will result in `1, 2, 3`, which we pass to the `sumValues` function. + +

+
+ +--- + +###### 118. Jaki jest wynik? + +```javascript +let num = 1; +const list = ['🥳', '🤠', '🥰', '🤪']; + +console.log(list[(num += 1)]); +``` + +- A: `🤠` +- B: `🥰` +- C: `SyntaxError` +- D: `ReferenceError` + +
Odpowiedź +

+ +#### Odpowiedź: B + +With the `+=` operand, we're incrementing the value of `num` by `1`. `num` had the initial value `1`, so `1 + 1` is `2`. The item on the second index in the `list` array is 🥰, `console.log(list[2])` prints 🥰. + +

+
+ +--- + +###### 119. Jaki jest wynik? + +```javascript +const person = { + firstName: 'Lydia', + lastName: 'Hallie', + pet: { + name: 'Mara', + breed: 'Dutch Tulip Hound', + }, + getFullName() { + return `${this.firstName} ${this.lastName}`; + }, +}; + +console.log(person.pet?.name); +console.log(person.pet?.family?.name); +console.log(person.getFullName?.()); +console.log(member.getLastName?.()); +``` + +- A: `undefined` `undefined` `undefined` `undefined` +- B: `Mara` `undefined` `Lydia Hallie` `ReferenceError` +- C: `Mara` `null` `Lydia Hallie` `null` +- D: `null` `ReferenceError` `null` `ReferenceError` + +
Odpowiedź +

+ +#### Odpowiedź: B + +With the optional chaining operator `?.`, we no longer have to explicitly check whether the deeper nested values are valid or not. If we're trying to access a property on an `undefined` or `null` value (_nullish_), the expression short-circuits and returns `undefined`. + +`person.pet?.name`: `person` has a property named `pet`: `person.pet` is not nullish. It has a property called `name`, and returns `Mara`. +`person.pet?.family?.name`: `person` has a property named `pet`: `person.pet` is not nullish. `pet` does _not_ have a property called `family`, `person.pet.family` is nullish. The expression returns `undefined`. +`person.getFullName?.()`: `person` has a property named `getFullName`: `person.getFullName()` is not nullish and can get invoked, which returns `Lydia Hallie`. +`member.getLastName?.()`: variable `member` is non existent therefore a `ReferenceError` gets thrown! + +

+
+ +--- + +###### 120. Jaki jest wynik? + +```javascript +const groceries = ['banana', 'apple', 'peanuts']; + +if (groceries.indexOf('banana')) { + console.log('We have to buy bananas!'); +} else { + console.log(`We don't have to buy bananas!`); +} +``` + +- A: We have to buy bananas! +- B: We don't have to buy bananas +- C: `undefined` +- D: `1` + +
Odpowiedź +

+ +#### Odpowiedź: B + +We passed the condition `groceries.indexOf("banana")` to the if-statement. `groceries.indexOf("banana")` returns `0`, which is a falsy value. Since the condition in the if-statement is falsy, the code in the `else` block runs, and `We don't have to buy bananas!` gets logged. + +

+
+ +--- + +###### 121. Jaki jest wynik? + +```javascript +const config = { + languages: [], + set language(lang) { + return this.languages.push(lang); + }, +}; + +console.log(config.language); +``` + +- A: `function language(lang) { this.languages.push(lang }` +- B: `0` +- C: `[]` +- D: `undefined` + +
Odpowiedź +

+ +#### Odpowiedź: D + +The `language` method is a `setter`. Setters don't hold an actual value, their purpose is to _modify_ properties. When calling a `setter` method, `undefined` gets returned. + +

+
+ +--- + +###### 122. Jaki jest wynik? + +```javascript +const name = 'Lydia Hallie'; + +console.log(!typeof name === 'object'); +console.log(!typeof name === 'string'); +``` + +- A: `false` `true` +- B: `true` `false` +- C: `false` `false` +- D: `true` `true` + +
Odpowiedź +

+ +#### Odpowiedź: C + +`typeof name` returns `"string"`. The string `"string"` is a truthy value, so `!typeof name` returns the boolean value `false`. `false === "object"` and `false === "string"` both return`false`. + +(If we wanted to check whether the type was (un)equal to a certain type, we should've written `!==` instead of `!typeof`) + +

+
+ +--- + +###### 123. Jaki jest wynik? + +```javascript +const add = x => y => z => { + console.log(x, y, z); + return x + y + z; +}; + +add(4)(5)(6); +``` + +- A: `4` `5` `6` +- B: `6` `5` `4` +- C: `4` `function` `function` +- D: `undefined` `undefined` `6` + +
Odpowiedź +

+ +#### Odpowiedź: A + +The `add` function returns an arrow function, which returns an arrow function, which returns an arrow function (still with me?). The first function receives an argument `x` with the value of `4`. We invoke the second function, which receives an argument `y` with the value `5`. Then we invoke the third function, which receives an argument `z` with the value `6`. When we're trying to access the value `x`, `y` and `z` within the last arrow function, the JS engine goes up the scope chain in order to find the values for `x` and `y` accordingly. This returns `4` `5` `6`. + +

+
+ +--- + +###### 124. Jaki jest wynik? + +```javascript +async function* range(start, end) { + for (let i = start; i <= end; i++) { + yield Promise.resolve(i); + } +} + +(async () => { + const gen = range(1, 3); + for await (const item of gen) { + console.log(item); + } +})(); +``` + +- A: `Promise {1}` `Promise {2}` `Promise {3}` +- B: `Promise {}` `Promise {}` `Promise {}` +- C: `1` `2` `3` +- D: `undefined` `undefined` `undefined` + +
Odpowiedź +

+ +#### Odpowiedź: C + +The generator function `range` returns an async object with promises for each item in the range we pass: `Promise{1}`, `Promise{2}`, `Promise{3}`. We set the variable `gen` equal to the async object, after which we loop over it using a `for await ... of` loop. We set the variable `item` equal to the returned Promise values: first `Promise{1}`, then `Promise{2}`, then `Promise{3}`. Since we're _awaiting_ the value of `item`, the resolved promise, the resolved _values_ of the promises get returned: `1`, `2`, then `3`. + +

+
+ +--- + +###### 125. Jaki jest wynik? + +```javascript +const myFunc = ({ x, y, z }) => { + console.log(x, y, z); +}; + +myFunc(1, 2, 3); +``` + +- A: `1` `2` `3` +- B: `{1: 1}` `{2: 2}` `{3: 3}` +- C: `{ 1: undefined }` `undefined` `undefined` +- D: `undefined` `undefined` `undefined` + +
Odpowiedź +

+ +#### Odpowiedź: D + +`myFunc` expects an object with properties `x`, `y` and `z` as its argument. Since we're only passing three separate numeric values (1, 2, 3) instead of one object with properties `x`, `y` and `z` ({x: 1, y: 2, z: 3}), `x`, `y` and `z` have their default value of `undefined`. + +

+
+ +--- + +###### 126. Jaki jest wynik? + +```javascript +function getFine(speed, amount) { + const formattedSpeed = new Intl.NumberFormat('en-US', { + style: 'unit', + unit: 'mile-per-hour' + }).format(speed); + + const formattedAmount = new Intl.NumberFormat('en-US', { + style: 'currency', + currency: 'USD' + }).format(amount); + + return `The driver drove ${formattedSpeed} and has to pay ${formattedAmount}`; +} + +console.log(getFine(130, 300)) +``` + +- A: The driver drove 130 and has to pay 300 +- B: The driver drove 130 mph and has to pay \$300.00 +- C: The driver drove undefined and has to pay undefined +- D: The driver drove 130.00 and has to pay 300.00 + +
Odpowiedź +

+ +#### Odpowiedź: B + +With the `Intl.NumberFormat` method, we can format numeric values to any locale. We format the numeric value `130` to the `en-US` locale as a `unit` in `mile-per-hour`, which results in `130 mph`. The numeric value `300` to the `en-US` locale as a `currency` in `USD` results in `$300.00`. + +

+
+ +--- + +###### 127. Jaki jest wynik? + +```javascript +const spookyItems = ['👻', '🎃', '🕸']; +({ item: spookyItems[3] } = { item: '💀' }); + +console.log(spookyItems); +``` + +- A: `["👻", "🎃", "🕸"]` +- B: `["👻", "🎃", "🕸", "💀"]` +- C: `["👻", "🎃", "🕸", { item: "💀" }]` +- D: `["👻", "🎃", "🕸", "[object Object]"]` + +
Odpowiedź +

+ +#### Odpowiedź: B + +By destructuring objects, we can unpack values from the right-hand object, and assign the unpacked value to the value of the same property name on the left-hand object. In this case, we're assigning the value "💀" to `spookyItems[3]`. This means that we're modifying the `spookyItems` array, we're adding the "💀" to it. When logging `spookyItems`, `["👻", "🎃", "🕸", "💀"]` gets logged. + +

+
+ +--- + +###### 128. Jaki jest wynik? + +```javascript +const name = 'Lydia Hallie'; +const age = 21; + +console.log(Number.isNaN(name)); +console.log(Number.isNaN(age)); + +console.log(isNaN(name)); +console.log(isNaN(age)); +``` + +- A: `true` `false` `true` `false` +- B: `true` `false` `false` `false` +- C: `false` `false` `true` `false` +- D: `false` `true` `false` `true` + +
Odpowiedź +

+ +#### Odpowiedź: C + +With the `Number.isNaN` method, you can check if the value you pass is a _numeric value_ and equal to `NaN`. `name` is not a numeric value, so `Number.isNaN(name)` returns `false`. `age` is a numeric value, but is not equal to `NaN`, so `Number.isNaN(age)` returns `false`. + +With the `isNaN` method, you can check if the value you pass is not a number. `name` is not a number, so `isNaN(name)` returns true. `age` is a number, so `isNaN(age)` returns `false`. + +

+
+ +--- + +###### 129. Jaki jest wynik? + +```javascript +const randomValue = 21; + +function getInfo() { + console.log(typeof randomValue); + const randomValue = 'Lydia Hallie'; +} + +getInfo(); +``` + +- A: `"number"` +- B: `"string"` +- C: `undefined` +- D: `ReferenceError` + +
Odpowiedź +

+ +#### Odpowiedź: D + +Variables declared with the `const` keyword are not referenceable before their initialization: this is called the _temporal dead zone_. In the `getInfo` function, the variable `randomValue` is scoped in the functional scope of `getInfo`. On the line where we want to log the value of `typeof randomValue`, the variable `randomValue` isn't initialized yet: a `ReferenceError` gets thrown! The engine didn't go down the scope chain since we declared the variable `randomValue` in the `getInfo` function. + +

+
+ +--- + +###### 130. Jaki jest wynik? + +```javascript +const myPromise = Promise.resolve('Woah some cool data'); + +(async () => { + try { + console.log(await myPromise); + } catch { + throw new Error(`Oops didn't work`); + } finally { + console.log('Oh finally!'); + } +})(); +``` + +- A: `Woah some cool data` +- B: `Oh finally!` +- C: `Woah some cool data` `Oh finally!` +- D: `Oops didn't work` `Oh finally!` + +
Odpowiedź +

+ +#### Odpowiedź: C + +In the `try` block, we're logging the awaited value of the `myPromise` variable: `"Woah some cool data"`. Since no errors were thrown in the `try` block, the code in the `catch` block doesn't run. The code in the `finally` block _always_ runs, `"Oh finally!"` gets logged. + +

+
+ +--- + +###### 131. Jaki jest wynik? + +```javascript +const emojis = ['🥑', ['✨', '✨', ['🍕', '🍕']]]; + +console.log(emojis.flat(1)); +``` + +- A: `['🥑', ['✨', '✨', ['🍕', '🍕']]]` +- B: `['🥑', '✨', '✨', ['🍕', '🍕']]` +- C: `['🥑', ['✨', '✨', '🍕', '🍕']]` +- D: `['🥑', '✨', '✨', '🍕', '🍕']` + +
Odpowiedź +

+ +#### Odpowiedź: B + +With the `flat` method, we can create a new, flattened array. The depth of the flattened array depends on the value that we pass. In this case, we passed the value `1` (which we didn't have to, that's the default value), meaning that only the arrays on the first depth will be concatenated. `['🥑']` and `['✨', '✨', ['🍕', '🍕']]` in this case. Concatenating these two arrays results in `['🥑', '✨', '✨', ['🍕', '🍕']]`. + +

+
+ +--- + +###### 132. Jaki jest wynik? + +```javascript +class Counter { + constructor() { + this.count = 0; + } + + increment() { + this.count++; + } +} + +const counterOne = new Counter(); +counterOne.increment(); +counterOne.increment(); + +const counterTwo = counterOne; +counterTwo.increment(); + +console.log(counterOne.count); +``` + +- A: `0` +- B: `1` +- C: `2` +- D: `3` + +
Odpowiedź +

+ +#### Odpowiedź: D + +`counterOne` is an instance of the `Counter` class. The counter class contains a `count` property on its constructor, and an `increment` method. First, we invoked the `increment` method twice by calling `counterOne.increment()`. Currently, `counterOne.count` is `2`. + + + +Then, we create a new variable `counterTwo`, and set it equal to `counterOne`. Since objects interact by reference, we're just creating a new reference to the same spot in memory that `counterOne` points to. Since it has the same spot in memory, any changes made to the object that `counterTwo` has a reference to, also apply to `counterOne`. Currently, `counterTwo.count` is `2`. + +We invoke `counterTwo.increment()`, which sets `count` to `3`. Then, we log the count on `counterOne`, which logs `3`. + + + +

+
+ +--- + +###### 133. Jaki jest wynik? + +```javascript +const myPromise = Promise.resolve(Promise.resolve('Promise')); + +function funcOne() { + setTimeout(() => console.log('Timeout 1!'), 0); + myPromise.then(res => res).then(res => console.log(`${res} 1!`)); + console.log('Last line 1!'); +} + +async function funcTwo() { + const res = await myPromise; + console.log(`${res} 2!`) + setTimeout(() => console.log('Timeout 2!'), 0); + console.log('Last line 2!'); +} + +funcOne(); +funcTwo(); +``` + +- A: `Promise 1! Last line 1! Promise 2! Last line 2! Timeout 1! Timeout 2!` +- B: `Last line 1! Timeout 1! Promise 1! Last line 2! Promise2! Timeout 2! ` +- C: `Last line 1! Promise 2! Last line 2! Promise 1! Timeout 1! Timeout 2!` +- D: `Timeout 1! Promise 1! Last line 1! Promise 2! Timeout 2! Last line 2!` + +
Odpowiedź +

+ +#### Odpowiedź: C + +First, we invoke `funcOne`. On the first line of `funcOne`, we call the _asynchronous_ `setTimeout` function, from which the callback is sent to the Web API. (see my article on the event loop here.) + +Then we call the `myPromise` promise, which is an _asynchronous_ operation. + +Both the promise and the timeout are asynchronous operations, the function keeps on running while it's busy completing the promise and handling the `setTimeout` callback. This means that `Last line 1!` gets logged first, since this is not an asynchonous operation. + +Since the callstack is not empty yet, the `setTimeout` function and promise in `funcOne` cannot get added to the callstack yet. + +In `funcTwo`, the variable `res` gets `Promise` because `Promise.resolve(Promise.resolve('Promise'))` is equivalent to `Promise.resolve('Promise')` since resolving a promise just resolves it's value. The `await` in this line stops the execution of the function until it receives the resolution of the promise and then keeps on running synchronously until completion, so `Promise 2!` and then `Last line 2!` are logged and the `setTimeout` is sent to the Web API. + +Then the call stack is empty. Promises are _microtasks_ so they are resolved first when the call stack is empty so `Promise 1!` gets to be logged. + +Now, since `funcTwo` popped off the call stack, the call stack is empty. The callbacks waiting in the queue (`() => console.log("Timeout 1!")` from `funcOne`, and `() => console.log("Timeout 2!")` from `funcTwo`) get added to the call stack one by one. The first callback logs `Timeout 1!`, and gets popped off the stack. Then, the second callback logs `Timeout 2!`, and gets popped off the stack. + +

+
+ +--- + +###### 134. How can we invoke `sum` in `sum.js` from `index.js?` + +```javascript +// sum.js +export default function sum(x) { + return x + x; +} + +// index.js +import * as sum from './sum'; +``` + +- A: `sum(4)` +- B: `sum.sum(4)` +- C: `sum.default(4)` +- D: Default aren't imported with `*`, only named exports + +
Odpowiedź +

+ +#### Odpowiedź: C + +With the asterisk `*`, we import all exported values from that file, both default and named. If we had the following file: + +```javascript +// info.js +export const name = 'Lydia'; +export const age = 21; +export default 'I love JavaScript'; + +// index.js +import * as info from './info'; +console.log(info); +``` + +The following would get logged: + +```javascript +{ + default: "I love JavaScript", + name: "Lydia", + age: 21 +} +``` + +For the `sum` example, it means that the imported value `sum` looks like this: + +```javascript +{ default: function sum(x) { return x + x } } +``` + +We can invoke this function, by calling `sum.default` + +

+
+ +--- + +###### 135. Jaki jest wynik? + +```javascript +const handler = { + set: () => console.log('Added a new property!'), + get: () => console.log('Accessed a property!'), +}; + +const person = new Proxy({}, handler); + +person.name = 'Lydia'; +person.name; +``` + +- A: `Added a new property!` +- B: `Accessed a property!` +- C: `Added a new property!` `Accessed a property!` +- D: Nothing gets logged + +
Odpowiedź +

+ +#### Odpowiedź: C + +With a Proxy object, we can add custom behavior to an object that we pass to it as the second argument. In this case, we pass the `handler` object which contained two properties: `set` and `get`. `set` gets invoked whenever we _set_ property values, `get` gets invoked whenever we _get_ (access) property values. + +The first argument is an empty object `{}`, which is the value of `person`. To this object, the custom behavior specified in the `handler` object gets added. If we add a property to the `person` object, `set` will get invoked. If we access a property on the `person` object, `get` gets invoked. + +First, we added a new property `name` to the proxy object (`person.name = "Lydia"`). `set` gets invoked, and logs `"Added a new property!"`. + +Then, we access a property value on the proxy object, the `get` property on the handler object got invoked. `"Accessed a property!"` gets logged. + +

+
+ +--- + +###### 136. Which of the following will modify the `person` object? + +```javascript +const person = { name: 'Lydia Hallie' }; + +Object.seal(person); +``` + +- A: `person.name = "Evan Bacon"` +- B: `person.age = 21` +- C: `delete person.name` +- D: `Object.assign(person, { age: 21 })` + +
Odpowiedź +

+ +#### Odpowiedź: A + +With `Object.seal` we can prevent new properties from being _added_, or existing properties to be _removed_. + +However, you can still modify the value of existing properties. + +

+
+ +--- + +###### 137. Which of the following will modify the `person` object? + +```javascript +const person = { + name: 'Lydia Hallie', + address: { + street: '100 Main St', + }, +}; + +Object.freeze(person); +``` + +- A: `person.name = "Evan Bacon"` +- B: `delete person.address` +- C: `person.address.street = "101 Main St"` +- D: `person.pet = { name: "Mara" }` + +
Odpowiedź +

+ +#### Odpowiedź: C + +The `Object.freeze` method _freezes_ an object. No properties can be added, modified, or removed. + +However, it only _shallowly_ freezes the object, meaning that only _direct_ properties on the object are frozen. If the property is another object, like `address` in this case, the properties on that object aren't frozen, and can be modified. + +

+
+ +--- + +###### 138. Jaki jest wynik? + +```javascript +const add = x => x + x; + +function myFunc(num = 2, value = add(num)) { + console.log(num, value); +} + +myFunc(); +myFunc(3); +``` + +- A: `2` `4` and `3` `6` +- B: `2` `NaN` and `3` `NaN` +- C: `2` `Error` and `3` `6` +- D: `2` `4` and `3` `Error` + +
Odpowiedź +

+ +#### Odpowiedź: A + +First, we invoked `myFunc()` without passing any arguments. Since we didn't pass arguments, `num` and `value` got their default values: num is `2`, and `value` the returned value of the function `add`. To the `add` function, we pass `num` as an argument, which had the value of `2`. `add` returns `4`, which is the value of `value`. + +Then, we invoked `myFunc(3)` and passed the value `3` as the value for the argument `num`. We didn't pass an argument for `value`. Since we didn't pass a value for the `value` argument, it got the default value: the returned value of the `add` function. To `add`, we pass `num`, which has the value of `3`. `add` returns `6`, which is the value of `value`. + +

+
+ +--- + +###### 139. Jaki jest wynik? + +```javascript +class Counter { + #number = 10 + + increment() { + this.#number++ + } + + getNum() { + return this.#number + } +} + +const counter = new Counter() +counter.increment() + +console.log(counter.#number) +``` + +- A: `10` +- B: `11` +- C: `undefined` +- D: `SyntaxError` + +
Odpowiedź +

+ +#### Odpowiedź: D + +In ES2020, we can add private variables in classes by using the `#`. We cannot access these variables outside of the class. When we try to log `counter.#number`, a SyntaxError gets thrown: we cannot acccess it outside the `Counter` class! + +

+
+ +--- + +###### 140. What's missing? + +```javascript +const teams = [ + { name: 'Team 1', members: ['Paul', 'Lisa'] }, + { name: 'Team 2', members: ['Laura', 'Tim'] }, +]; + +function* getMembers(members) { + for (let i = 0; i < members.length; i++) { + yield members[i]; + } +} + +function* getTeams(teams) { + for (let i = 0; i < teams.length; i++) { + // ✨ SOMETHING IS MISSING HERE ✨ + } +} + +const obj = getTeams(teams); +obj.next(); // { value: "Paul", done: false } +obj.next(); // { value: "Lisa", done: false } +``` + +- A: `yield getMembers(teams[i].members)` +- B: `yield* getMembers(teams[i].members)` +- C: `return getMembers(teams[i].members)` +- D: `return yield getMembers(teams[i].members)` + +
Odpowiedź +

+ +#### Odpowiedź: B + +In order to iterate over the `members` in each element in the `teams` array, we need to pass `teams[i].members` to the `getMembers` generator function. The generator function returns a generator object. In order to iterate over each element in this generator object, we need to use `yield*`. + +If we would've written `yield`, `return yield`, or `return`, the entire generator function would've gotten returned the first time we called the `next` method. + +

+
+ +--- + +###### 141. Jaki jest wynik? + +```javascript +const person = { + name: 'Lydia Hallie', + hobbies: ['coding'], +}; + +function addHobby(hobby, hobbies = person.hobbies) { + hobbies.push(hobby); + return hobbies; +} + +addHobby('running', []); +addHobby('dancing'); +addHobby('baking', person.hobbies); + +console.log(person.hobbies); +``` + +- A: `["coding"]` +- B: `["coding", "dancing"]` +- C: `["coding", "dancing", "baking"]` +- D: `["coding", "running", "dancing", "baking"]` + +
Odpowiedź +

+ +#### Odpowiedź: C + +The `addHobby` function receives two arguments, `hobby` and `hobbies` with the default value of the `hobbies` array on the `person` object. + +First, we invoke the `addHobby` function, and pass `"running"` as the value for `hobby` and an empty array as the value for `hobbies`. Since we pass an empty array as the value for `hobbies`, `"running"` gets added to this empty array. + +Then, we invoke the `addHobby` function, and pass `"dancing"` as the value for `hobby`. We didn't pass a value for `hobbies`, so it gets the default value, the `hobbies` property on the `person` object. We push the hobby `dancing` to the `person.hobbies` array. + +Last, we invoke the `addHobby` function, and pass `"baking"` as the value for `hobby`, and the `person.hobbies` array as the value for `hobbies`. We push the hobby `baking` to the `person.hobbies` array. + +After pushing `dancing` and `baking`, the value of `person.hobbies` is `["coding", "dancing", "baking"]` + +

+
+ +--- + +###### 142. Jaki jest wynik? + +```javascript +class Bird { + constructor() { + console.log("I'm a bird. 🦢"); + } +} + +class Flamingo extends Bird { + constructor() { + console.log("I'm pink. 🌸"); + super(); + } +} + +const pet = new Flamingo(); +``` + +- A: `I'm pink. 🌸` +- B: `I'm pink. 🌸` `I'm a bird. 🦢` +- C: `I'm a bird. 🦢` `I'm pink. 🌸` +- D: Nothing, we didn't call any method + +
Odpowiedź +

+ +#### Odpowiedź: B + +We create the variable `pet` which is an instance of the `Flamingo` class. When we instantiate this instance, the `constructor` on `Flamingo` gets called. First, `"I'm pink. 🌸"` gets logged, after which we call `super()`. `super()` calls the constructor of the parent class, `Bird`. The constructor in `Bird` gets called, and logs `"I'm a bird. 🦢"`. + +

+
+ +--- + +###### 143. Which of the options result(s) in an error? + +```javascript +const emojis = ['🎄', '🎅🏼', '🎁', '⭐']; + +/* 1 */ emojis.push('🦌'); +/* 2 */ emojis.splice(0, 2); +/* 3 */ emojis = [...emojis, '🥂']; +/* 4 */ emojis.length = 0; +``` + +- A: 1 +- B: 1 and 2 +- C: 3 and 4 +- D: 3 + +
Odpowiedź +

+ +#### Odpowiedź: D + +The `const` keyword simply means we cannot _redeclare_ the value of that variable, it's _read-only_. However, the value itself isn't immutable. The properties on the `emojis` array can be modified, for example by pushing new values, splicing them, or setting the length of the array to 0. + +

+
+ +--- + +###### 144. What do we need to add to the `person` object to get `["Lydia Hallie", 21]` as the output of `[...person]`? + +```javascript +const person = { + name: "Lydia Hallie", + age: 21 +} + +[...person] // ["Lydia Hallie", 21] +``` + +- A: Nothing, object are iterable by default +- B: `*[Symbol.iterator]() { for (let x in this) yield* this[x] }` +- C: `*[Symbol.iterator]() { yield* Object.values(this) }` +- D: `*[Symbol.iterator]() { for (let x in this) yield this }` + +
Odpowiedź +

+ +#### Odpowiedź: C + +Objects aren't iterable by default. An iterable is an iterable if the iterator protocol is present. We can add this manually by adding the iterator symbol `[Symbol.iterator]`, which has to return a generator object, for example by making it a generator function `*[Symbol.iterator]() {}`. This generator function has to yield the `Object.values` of the `person` object if we want it to return the array `["Lydia Hallie", 21]`: `yield* Object.values(this)`. + +

+
+ +--- + +###### 145. Jaki jest wynik? + +```javascript +let count = 0; +const nums = [0, 1, 2, 3]; + +nums.forEach(num => { + if (num) count += 1 +}) + +console.log(count) +``` + +- A: 1 +- B: 2 +- C: 3 +- D: 4 + +
Odpowiedź +

+ +#### Odpowiedź: C + +The `if` condition within the `forEach` loop checks whether the value of `num` is truthy or falsy. Since the first number in the `nums` array is `0`, a falsy value, the `if` statement's code block won't be executed. `count` only gets incremented for the other 3 numbers in the `nums` array, `1`, `2` and `3`. Since `count` gets incremented by `1` 3 times, the value of `count` is `3`. + +

+
+ +--- + +###### 146. Jaki jest wynik? + +```javascript +function getFruit(fruits) { + console.log(fruits?.[1]?.[1]) +} + +getFruit([['🍊', '🍌'], ['🍍']]) +getFruit() +getFruit([['🍍'], ['🍊', '🍌']]) +``` + +- A: `null`, `undefined`, 🍌 +- B: `[]`, `null`, 🍌 +- C: `[]`, `[]`, 🍌 +- D: `undefined`, `undefined`, 🍌 + +
Odpowiedź +

+ +#### Odpowiedź: D + +The `?` allows us to optionally access deeper nested properties within objects. We're trying to log the item on index `1` within the subarray that's on index `1` of the `fruits` array. If the subarray on index `1` in the `fruits` array doesn't exist, it'll simply return `undefined`. If the subarray on index `1` in the `fruits` array exists, but this subarray doesn't have an item on its `1` index, it'll also return `undefined`. + +First, we're trying to log the second item in the `['🍍']` subarray of `[['🍊', '🍌'], ['🍍']]`. This subarray only contains one item, which means there is no item on index `1`, and returns `undefined`. + +Then, we're invoking the `getFruits` function without passing a value as an argument, which means that `fruits` has a value of `undefined` by default. Since we're conditionally chaining the item on index `1` of`fruits`, it returns `undefined` since this item on index `1` does not exist. + +Lastly, we're trying to log the second item in the `['🍊', '🍌']` subarray of `['🍍'], ['🍊', '🍌']`. The item on index `1` within this subarray is `🍌`, which gets logged. + +

+
+ +--- + +###### 147. Jaki jest wynik? + +```javascript +class Calc { + constructor() { + this.count = 0 + } + + increase() { + this.count ++ + } +} + +const calc = new Calc() +new Calc().increase() + +console.log(calc.count) +``` + +- A: `0` +- B: `1` +- C: `undefined` +- D: `ReferenceError` + +
Odpowiedź +

+ +#### Odpowiedź: A + +We set the variable `calc` equal to a new instance of the `Calc` class. Then, we instantiate a new instance of `Calc`, and invoke the `increase` method on this instance. Since the count property is within the constructor of the `Calc` class, the count property is not shared on the prototype of `Calc`. This means that the value of count has not been updated for the instance calc points to, count is still `0`. + +

+
+ +--- + +###### 148. Jaki jest wynik? + +```javascript +const user = { + email: "e@mail.com", + password: "12345" +} + +const updateUser = ({ email, password }) => { + if (email) { + Object.assign(user, { email }) + } + + if (password) { + user.password = password + } + + return user +} + +const updatedUser = updateUser({ email: "new@email.com" }) + +console.log(updatedUser === user) +``` + +- A: `false` +- B: `true` +- C: `TypeError` +- D: `ReferenceError` + +
Odpowiedź +

+ +#### Odpowiedź: B + +The `updateUser` function updates the values of the `email` and `password` properties on user, if their values are passed to the function, after which the function returns the `user` object. The returned value of the `updateUser` function is the `user` object, which means that the value of updatedUser is a reference to the same `user` object that `user` points to. `updatedUser === user` equals `true`. + +

+
+ +--- + +###### 149. Jaki jest wynik? + +```javascript +const fruit = ['🍌', '🍊', '🍎'] + +fruit.slice(0, 1) +fruit.splice(0, 1) +fruit.unshift('🍇') + +console.log(fruit) +``` + +- A: `['🍌', '🍊', '🍎']` +- B: `['🍊', '🍎']` +- C: `['🍇', '🍊', '🍎']` +- D: `['🍇', '🍌', '🍊', '🍎']` + +
Odpowiedź +

+ +#### Odpowiedź: C + +First, we invoke the `slice` method on the fruit array. The slice method does not modify the original array, but returns the value that it sliced off the array: the banana emoji. +Then, we invoke the `splice` method on the fruit array. The splice method does modify the original array, which means that the fruit array now consists of `['🍊', '🍎']`. +At last, we invoke the `unshift` method on the `fruit` array, which modifies the original array by adding the provided value, ‘🍇’ in this case, as the first element in the array. The fruit array now consists of `['🍇', '🍊', '🍎']`. + +

+
+ +--- + +###### 150. Jaki jest wynik? + +```javascript +const animals = {}; +let dog = { emoji: '🐶' } +let cat = { emoji: '🐈' } + +animals[dog] = { ...dog, name: "Mara" } +animals[cat] = { ...cat, name: "Sara" } + +console.log(animals[dog]) +``` + +- A: `{ emoji: "🐶", name: "Mara" }` +- B: `{ emoji: "🐈", name: "Sara" }` +- C: `undefined` +- D: `ReferenceError` + +
Odpowiedź +

+ +#### Odpowiedź: B + +Object keys are converted to strings. + +Since the value of `dog` is an object, `animals[dog]` actually means that we’re creating a new property called `"object Object"` equal to the new object. `animals["object Object"]` is now equal to `{ emoji: "🐶", name: "Mara"}`. + +`cat` is also an object, which means that `animals[cat]` actually means that we’re overwriting the value of `animals["object Object"]` with the new cat properties. + +Logging `animals[dog]`, or actually `animals["object Object"]` since converting the `dog` object to a string results `"object Object"`, returns the `{ emoji: "🐈", name: "Sara" }`. + +

+
+ +--- + +###### 151. Jaki jest wynik? + +```javascript +const user = { + email: "my@email.com", + updateEmail: email => { + this.email = email + } +} + +user.updateEmail("new@email.com") +console.log(user.email) +``` + +- A: `my@email.com` +- B: `new@email.com` +- C: `undefined` +- D: `ReferenceError` + +
Odpowiedź +

+ +#### Odpowiedź: A + +The `updateEmail` function is an arrow function, and is not bound to the `user` object. This means that the `this` keyword is not referring to the `user` object, but refers to the global scope in this case. The value of `email` within the `user` object does not get updated. When logging the value of `user.email`, the original value of `my@email.com` gets returned. + +

+
+ +--- + +###### 152. Jaki jest wynik? + +```javascript +const promise1 = Promise.resolve('First') +const promise2 = Promise.resolve('Second') +const promise3 = Promise.reject('Third') +const promise4 = Promise.resolve('Fourth') + +const runPromises = async () => { + const res1 = await Promise.all([promise1, promise2]) + const res2 = await Promise.all([promise3, promise4]) + return [res1, res2] +} + +runPromises() + .then(res => console.log(res)) + .catch(err => console.log(err)) +``` + +- A: `[['First', 'Second'], ['Fourth']]` +- B: `[['First', 'Second'], ['Third', 'Fourth']]` +- C: `[['First', 'Second']]` +- D: `'Third'` + +
Odpowiedź +

+ +#### Odpowiedź: D + +The `Promise.all` method runs the passed promises in parallel. If one promise fails, the `Promise.all` method _rejects_ with the value of the rejected promise. In this case, `promise3` rejected with the value `"Third"`. We’re catching the rejected value in the chained `catch` method on the `runPromises` invocation to catch any errors within the `runPromises` function. Only `"Third"` gets logged, since `promise3` rejected with this value. + +

+
+ +--- + +###### 153. What should the value of `method` be to log `{ name: "Lydia", age: 22 }`? + +```javascript +const keys = ["name", "age"] +const values = ["Lydia", 22] + +const method = /* ?? */ +Object[method](keys.map((_, i) => { + return [keys[i], values[i]] +})) // { name: "Lydia", age: 22 } +``` + +- A: `entries` +- B: `values` +- C: `fromEntries` +- D: `forEach` + +
Odpowiedź +

+ +#### Odpowiedź: C + +The `fromEntries` method turns a 2d array into an object. The first element in each subarray will be the key, and the second element in each subarray will be the value. In this case, we’re mapping over the `keys` array, which returns an array which first element is the item on the key array on the current index, and the second element is the item of the values array on the current index. + +This creates an array of subarrays containing the correct keys and values, which results in `{ name: "Lydia", age: 22 }` + +

+
+ +--- + +###### 154. Jaki jest wynik? + +```javascript +const createMember = ({ email, address = {}}) => { + const validEmail = /.+\@.+\..+/.test(email) + if (!validEmail) throw new Error("Valid email pls") + + return { + email, + address: address ? address : null + } +} + +const member = createMember({ email: "my@email.com" }) +console.log(member) +``` + +- A: `{ email: "my@email.com", address: null }` +- B: `{ email: "my@email.com" }` +- C: `{ email: "my@email.com", address: {} }` +- D: `{ email: "my@email.com", address: undefined }` + +
Odpowiedź +

+ +#### Odpowiedź: C + +The default value of `address` is an empty object `{}`. When we set the variable `member` equal to the object returned by the `createMember` function, we didn't pass a value for address, which means that the value of address is the default empty object `{}`. An empty object is a truthy value, which means that the condition of the `address ? address : null` conditional returns `true`. The value of address is the empty object `{}`. + +

+
+ +--- + +###### 155. Jaki jest wynik? + +```javascript +let randomValue = { name: "Lydia" } +randomValue = 23 + +if (!typeof randomValue === "string") { + console.log("It's not a string!") +} else { + console.log("Yay it's a string!") +} +``` + +- A: `It's not a string!` +- B: `Yay it's a string!` +- C: `TypeError` +- D: `undefined` + +
Odpowiedź +

+ +#### Odpowiedź: B + +The condition within the `if` statement checks whether the value of `!typeof randomValue` is equal to `"string"`. The `!` operator converts the value to a boolean value. If the value is truthy, the returned value will be `false`, if the value is falsy, the returned value will be `true`. In this case, the returned value of `typeof randomValue` is the truthy value `"number"`, meaning that the value of `!typeof randomValue` is the boolean value `false`. + +`!typeof randomValue === "string"` always returns false, since we're actually checking `false === "string"`. Since the condition returned `false`, the code block of the `else` statement gets run, and `Yay it's a string!` gets logged. + +

+
From 896b6c6c825672fa3d6290d3a9948e720a36f10a Mon Sep 17 00:00:00 2001 From: Lukasz Jasionowski Date: Sun, 25 Jun 2023 21:14:58 +0200 Subject: [PATCH 149/193] Add Polish to the list of available translations --- README.md | 1 + ar-AR/README_AR.md | 1 + bs-BS/README-bs_BS.md | 1 + de-DE/README.md | 1 + es-ES/README-ES.md | 1 + fr-FR/README_fr-FR.md | 1 + id-ID/README.md | 1 + it-IT/README.md | 1 + ja-JA/README-ja_JA.md | 1 + ko-KR/README-ko_KR.md | 1 + nl-NL/README.md | 1 + pt-BR/README_pt_BR.md | 1 + ru-RU/README.md | 1 + th-TH/README.md | 1 + tr-TR/README-tr_TR.md | 1 + uk-UA/README.md | 1 + vi-VI/README-vi.md | 1 + 17 files changed, 17 insertions(+) diff --git a/README.md b/README.md index 4e4bf3ed..a5e28d2c 100644 --- a/README.md +++ b/README.md @@ -31,6 +31,7 @@ Feel free to reach out to me! 😊
- [🇯🇵 日本語](./ja-JA/README-ja_JA.md) - [🇰🇷 한국어](./ko-KR/README-ko_KR.md) - [🇳🇱 Nederlands](./nl-NL/README.md) +- [🇵🇱 Polski](./pl_PL/README.md) - [🇧🇷 Português Brasil](./pt-BR/README_pt_BR.md) - [🇷🇺 Русский](./ru-RU/README.md) - [🇹🇭 ไทย](./th-TH/README-th_TH.md) diff --git a/ar-AR/README_AR.md b/ar-AR/README_AR.md index 1535be4a..be213a9b 100644 --- a/ar-AR/README_AR.md +++ b/ar-AR/README_AR.md @@ -25,6 +25,7 @@ - [🇯🇵 日本語](../ja-JA/README-ja_JA.md) - [🇰🇷 한국어](../ko-KR/README-ko_KR.md) - [🇳🇱 Nederlands](../nl-NL/README.md) +- [🇵🇱 Polski](../pl_PL/README.md) - [🇧🇷 Português Brasil](../pt-BR/README_pt_BR.md) - [🇷🇺 Русский](../ru-RU/README.md) - [🇹🇭 ไทย](../th-TH/README-th_TH.md) diff --git a/bs-BS/README-bs_BS.md b/bs-BS/README-bs_BS.md index 7e7f2398..39f3dee3 100644 --- a/bs-BS/README-bs_BS.md +++ b/bs-BS/README-bs_BS.md @@ -23,6 +23,7 @@ kliknite na njih da biste ih proširili. Sretno :heart: - [🇯🇵 日本語](../ja-JA/README-ja_JA.md) - [🇰🇷 한국어](../ko-KR/README-ko_KR.md) - [🇳🇱 Nederlands](../nl-NL/README.md) +- [🇵🇱 Polski](../pl_PL/README.md) - [🇧🇷 Português Brasil](../pt-BR/README_pt_BR.md) - [🇷🇺 Русский](../ru-RU/README.md) - [🇹🇭 ไทย](../th-TH/README-th_TH.md) diff --git a/de-DE/README.md b/de-DE/README.md index c45df9ad..59964041 100644 --- a/de-DE/README.md +++ b/de-DE/README.md @@ -33,6 +33,7 @@ Kontaktiert mich, wenn ihr möchtet! 😊
- [🇯🇵 日本語](../ja-JA/README-ja_JA.md) - [🇰🇷 한국어](../ko-KR/README-ko_KR.md) - [🇳🇱 Nederlands](../nl-NL/README.md) +- [🇵🇱 Polski](../pl_PL/README.md) - [🇧🇷 Português Brasil](../pt-BR/README_pt_BR.md) - [🇷🇺 Русский](../ru-RU/README.md) - [🇹🇭 ไทย](../th-TH/README-th_TH.md) diff --git a/es-ES/README-ES.md b/es-ES/README-ES.md index 16b94ec9..dbde4c4c 100644 --- a/es-ES/README-ES.md +++ b/es-ES/README-ES.md @@ -23,6 +23,7 @@ Lista de lenguajes disponibles: - [🇯🇵 日本語](../ja-JA/README-ja_JA.md) - [🇰🇷 한국어](../ko-KR/README-ko_KR.md) - [🇳🇱 Nederlands](../nl-NL/README.md) +- [🇵🇱 Polski](../pl_PL/README.md) - [🇧🇷 Português Brasil](../pt-BR/README_pt_BR.md) - [🇷🇺 Русский](../ru-RU/README.md) - [🇹🇭 ไทย](../th-TH/README-th_TH.md) diff --git a/fr-FR/README_fr-FR.md b/fr-FR/README_fr-FR.md index e88f19fe..ee2b9c0d 100644 --- a/fr-FR/README_fr-FR.md +++ b/fr-FR/README_fr-FR.md @@ -17,6 +17,7 @@ Les réponses se trouvent dans les sections repliées en dessous des questions, - [🇯🇵 日本語](../ja-JA/README-ja_JA.md) - [🇰🇷 한국어](../ko-KR/README-ko_KR.md) - [🇳🇱 Nederlands](../nl-NL/README.md) +- [🇵🇱 Polski](../pl_PL/README.md) - [🇧🇷 Português Brasil](../pt-BR/README_pt_BR.md) - [🇷🇺 Русский](../ru-RU/README.md) - [🇹🇭 ไทย](../th-TH/README-th_TH.md) diff --git a/id-ID/README.md b/id-ID/README.md index 82cc6e21..d1d126bd 100644 --- a/id-ID/README.md +++ b/id-ID/README.md @@ -27,6 +27,7 @@ Jangan sungkan untuk terhubung dengan saya! 😊
- [🇯🇵 日本語](../ja-JA/README-ja_JA.md) - [🇰🇷 한국어](../ko-KR/README-ko_KR.md) - [🇳🇱 Nederlands](../nl-NL/README.md) +- [🇵🇱 Polski](../pl_PL/README.md) - [🇧🇷 Português Brasil](../pt-BR/README_pt_BR.md) - [🇷🇺 Русский](../ru-RU/README.md) - [🇹🇭 ไทย](../th-TH/README-th_TH.md) diff --git a/it-IT/README.md b/it-IT/README.md index 1291c94a..09db4069 100644 --- a/it-IT/README.md +++ b/it-IT/README.md @@ -35,6 +35,7 @@ Traduzione a cura di: Lucia Cenetie - [🇯🇵 日本語](../ja-JA/README-ja_JA.md) - [🇰🇷 한국어](../ko-KR/README-ko_KR.md) - [🇳🇱 Nederlands](../nl-NL/README.md) +- [🇵🇱 Polski](../pl_PL/README.md) - [🇧🇷 Português Brasil](../pt-BR/README_pt_BR.md) - [🇷🇺 Русский](../ru-RU/README.md) - [🇹🇭 ไทย](../th-TH/README-th_TH.md) diff --git a/ja-JA/README-ja_JA.md b/ja-JA/README-ja_JA.md index 17dba18c..bd88f692 100644 --- a/ja-JA/README-ja_JA.md +++ b/ja-JA/README-ja_JA.md @@ -19,6 +19,7 @@ - [🇮🇹 Italiano](../it-IT/README.md) - [🇰🇷 한국어](../ko-KR/README-ko_KR.md) - [🇳🇱 Nederlands](../nl-NL/README.md) +- [🇵🇱 Polski](../pl_PL/README.md) - [🇧🇷 Português Brasil](../pt-BR/README_pt_BR.md) - [🇷🇺 Русский](../ru-RU/README.md) - [🇹🇭 ไทย](../th-TH/README-th_TH.md) diff --git a/ko-KR/README-ko_KR.md b/ko-KR/README-ko_KR.md index cdc08264..9651fd7d 100644 --- a/ko-KR/README-ko_KR.md +++ b/ko-KR/README-ko_KR.md @@ -32,6 +32,7 @@ - [🇮🇹 Italiano](../it-IT/README.md) - [🇯🇵 日本語](../ja-JA/README-ja_JA.md) - [🇳🇱 Nederlands](../nl-NL/README.md) +- [🇵🇱 Polski](../pl_PL/README.md) - [🇧🇷 Português Brasil](../pt-BR/README_pt_BR.md) - [🇷🇺 Русский](../ru-RU/README.md) - [🇹🇭 ไทย](../th-TH/README-th_TH.md) diff --git a/nl-NL/README.md b/nl-NL/README.md index 42fb2271..21339aa9 100644 --- a/nl-NL/README.md +++ b/nl-NL/README.md @@ -28,6 +28,7 @@ - [🇮🇹 Italiano](../it-IT/README.md) - [🇯🇵 日本語](../ja-JA/README-ja_JA.md) - [🇰🇷 한국어](../ko-KR/README-ko_KR.md) +- [🇵🇱 Polski](../pl_PL/README.md) - [🇧🇷 Português Brasil](../pt-BR/README_pt_BR.md) - [🇷🇺 Русский](../ru-RU/README.md) - [🇹🇭 ไทย](../th-TH/README-th_TH.md) diff --git a/pt-BR/README_pt_BR.md b/pt-BR/README_pt_BR.md index 6335e458..e9b1ef40 100644 --- a/pt-BR/README_pt_BR.md +++ b/pt-BR/README_pt_BR.md @@ -18,6 +18,7 @@ As respostas estão em seções recolhidas abaixo das questões, basta clicar ne - [🇯🇵 日本語](../ja-JA/README-ja_JA.md) - [🇰🇷 한국어](../ko-KR/README-ko_KR.md) - [🇳🇱 Nederlands](../nl-NL/README.md) +- [🇵🇱 Polski](../pl_PL/README.md) - [🇷🇺 Русский](../ru-RU/README.md) - [🇹🇭 ไทย](../th-TH/README-th_TH.md) - [🇹🇷 Türkçe](../tr-TR/README-tr_TR.md) diff --git a/ru-RU/README.md b/ru-RU/README.md index 77b2d167..382454e0 100644 --- a/ru-RU/README.md +++ b/ru-RU/README.md @@ -31,6 +31,7 @@ - [🇯🇵 日本語](../ja-JA/README-ja_JA.md) - [🇰🇷 한국어](../ko-KR/README-ko_KR.md) - [🇳🇱 Nederlands](../nl-NL/README.md) +- [🇵🇱 Polski](../pl_PL/README.md) - [🇧🇷 Português Brasil](../pt-BR/README_pt_BR.md) - [🇬🇧 English](../README.md) - [🇹🇭 ไทย](../th-TH/README-th_TH.md) diff --git a/th-TH/README.md b/th-TH/README.md index 287f3a01..8dd76df6 100644 --- a/th-TH/README.md +++ b/th-TH/README.md @@ -30,6 +30,7 @@ - [🇯🇵 日本語](../ja-JA/README-ja_JA.md) - [🇰🇷 한국어](../ko-KR/README-ko_KR.md) - [🇳🇱 Nederlands](../nl-NL/README.md) +- [🇵🇱 Polski](../pl_PL/README.md) - [🇧🇷 Português Brasil](../pt-BR/README_pt_BR.md) - [🇷🇺 Русский](../ru-RU/README.md) - [🇹🇷 Türkçe](../tr-TR/README-tr_TR.md) diff --git a/tr-TR/README-tr_TR.md b/tr-TR/README-tr_TR.md index 75cb7d6a..0eb88dd6 100644 --- a/tr-TR/README-tr_TR.md +++ b/tr-TR/README-tr_TR.md @@ -24,6 +24,7 @@ Mevcut dillerin listesi: - [🇯🇵 日本語](../ja-JA/README-ja_JA.md) - [🇰🇷 한국어](../ko-KR/README-ko_KR.md) - [🇳🇱 Nederlands](../nl-NL/README.md) +- [🇵🇱 Polski](../pl_PL/README.md) - [🇧🇷 Português Brasil](../pt-BR/README_pt_BR.md) - [🇷🇺 Русский](../ru-RU/README.md) - [🇹🇭 ไทย](../th-TH/README-th_TH.md) diff --git a/uk-UA/README.md b/uk-UA/README.md index 96157a23..f71a3f9c 100644 --- a/uk-UA/README.md +++ b/uk-UA/README.md @@ -18,6 +18,7 @@ - [🇯🇵 日本語](../ja-JA/README-ja_JA.md) - [🇰🇷 한국어](../ko-KR/README-ko_KR.md) - [🇳🇱 Nederlands](../nl-NL/README.md) +- [🇵🇱 Polski](../pl_PL/README.md) - [🇧🇷 Português Brasil](../pt-BR/README_pt_BR.md) - [🇷🇺 Русский](../ru-RU/README.md) - [🇹🇭 ไทย](../th-TH/README-th_TH.md) diff --git a/vi-VI/README-vi.md b/vi-VI/README-vi.md index 4a5ffa71..cbecac2a 100644 --- a/vi-VI/README-vi.md +++ b/vi-VI/README-vi.md @@ -19,6 +19,7 @@ Danh sách các ngôn ngữ khác: - [🇯🇵 日本語](../ja-JA/README-ja_JA.md) - [🇰🇷 한국어](../ko-KR/README-ko_KR.md) - [🇳🇱 Nederlands](../nl-NL/README.md) +- [🇵🇱 Polski](../pl_PL/README.md) - [🇧🇷 Português Brasil](../pt-BR/README_pt_BR.md) - [🇷🇺 Русский](../ru-RU/README.md) - [🇹🇭 ไทย](../th-TH/README-th_TH.md) From fc00df78aeef8fdaf12e2dffe636629d44290025 Mon Sep 17 00:00:00 2001 From: Lukasz Jasionowski Date: Sun, 25 Jun 2023 21:35:32 +0200 Subject: [PATCH 150/193] Remove English content and leave only translated one --- pl-PL/README.md | 4777 ----------------------------------------------- 1 file changed, 4777 deletions(-) diff --git a/pl-PL/README.md b/pl-PL/README.md index c00ec388..3dba610d 100644 --- a/pl-PL/README.md +++ b/pl-PL/README.md @@ -364,4780 +364,3 @@ Funkcja jest specjalnym rodzajem obiektu. Kod, który sam piszesz, nie jest wła

- ---- - -###### 11. Jaki jest wynik? - -```javascript -function Person(firstName, lastName) { - this.firstName = firstName; - this.lastName = lastName; -} - -const member = new Person('Lydia', 'Hallie'); -Person.getFullName = function() { - return `${this.firstName} ${this.lastName}`; -}; - -console.log(member.getFullName()); -``` - -- A: `TypeError` -- B: `SyntaxError` -- C: `Lydia Hallie` -- D: `undefined` `undefined` - -
Odpowiedź -

- -#### Odpowiedź: A - -In JavaScript, functions are objects, and therefore, the method `getFullName` gets added to the constructor function object itself. For that reason, we can call `Person.getFullName()`, but `member.getFullName` throws a `TypeError`. - -If you want a method to be available to all object instances, you have to add it to the prototype property: - -```js -Person.prototype.getFullName = function() { - return `${this.firstName} ${this.lastName}`; -}; -``` - -

-
- ---- - -###### 12. Jaki jest wynik? - -```javascript -function Person(firstName, lastName) { - this.firstName = firstName; - this.lastName = lastName; -} - -const lydia = new Person('Lydia', 'Hallie'); -const sarah = Person('Sarah', 'Smith'); - -console.log(lydia); -console.log(sarah); -``` - -- A: `Person {firstName: "Lydia", lastName: "Hallie"}` and `undefined` -- B: `Person {firstName: "Lydia", lastName: "Hallie"}` and `Person {firstName: "Sarah", lastName: "Smith"}` -- C: `Person {firstName: "Lydia", lastName: "Hallie"}` and `{}` -- D: `Person {firstName: "Lydia", lastName: "Hallie"}` and `ReferenceError` - -
Odpowiedź -

- -#### Odpowiedź: A - -For `sarah`, we didn't use the `new` keyword. When using `new`, `this` refers to the new empty object we create. However, if you don't add `new`, `this` refers to the **global object**! - -We said that `this.firstName` equals `"Sarah"` and `this.lastName` equals `"Smith"`. What we actually did, is defining `global.firstName = 'Sarah'` and `global.lastName = 'Smith'`. `sarah` itself is left `undefined`, since we don't return a value from the `Person` function. - -

-
- ---- - -###### 13. What are the three phases of event propagation? - -- A: Target > Capturing > Bubbling -- B: Bubbling > Target > Capturing -- C: Target > Bubbling > Capturing -- D: Capturing > Target > Bubbling - -
Odpowiedź -

- -#### Odpowiedź: D - -During the **capturing** phase, the event goes through the ancestor elements down to the target element. It then reaches the **target** element, and **bubbling** begins. - - - -

-
- ---- - -###### 14. All object have prototypes. - -- A: true -- B: false - -
Odpowiedź -

- -#### Odpowiedź: B - -All objects have prototypes, except for the **base object**. The base object is the object created by the user, or an object that is created using the `new` keyword. The base object has access to some methods and properties, such as `.toString`. This is the reason why you can use built-in JavaScript methods! All of such methods are available on the prototype. Although JavaScript can't find it directly on your object, it goes down the prototype chain and finds it there, which makes it accessible for you. - -

-
- ---- - -###### 15. Jaki jest wynik? - -```javascript -function sum(a, b) { - return a + b; -} - -sum(1, '2'); -``` - -- A: `NaN` -- B: `TypeError` -- C: `"12"` -- D: `3` - -
Odpowiedź -

- -#### Odpowiedź: C - -JavaScript is a **dynamically typed language**: we don't specify what types certain variables are. Values can automatically be converted into another type without you knowing, which is called _implicit type coercion_. **Coercion** is converting from one type into another. - -In this example, JavaScript converts the number `1` into a string, in order for the function to make sense and return a value. During the addition of a numeric type (`1`) and a string type (`'2'`), the number is treated as a string. We can concatenate strings like `"Hello" + "World"`, so what's happening here is `"1" + "2"` which returns `"12"`. - -

-
- ---- - -###### 16. Jaki jest wynik? - -```javascript -let number = 0; -console.log(number++); -console.log(++number); -console.log(number); -``` - -- A: `1` `1` `2` -- B: `1` `2` `2` -- C: `0` `2` `2` -- D: `0` `1` `2` - -
Odpowiedź -

- -#### Odpowiedź: C - -The **postfix** unary operator `++`: - -1. Returns the value (this returns `0`) -2. Increments the value (number is now `1`) - -The **prefix** unary operator `++`: - -1. Increments the value (number is now `2`) -2. Returns the value (this returns `2`) - -This returns `0 2 2`. - -

-
- ---- - -###### 17. Jaki jest wynik? - -```javascript -function getPersonInfo(one, two, three) { - console.log(one); - console.log(two); - console.log(three); -} - -const person = 'Lydia'; -const age = 21; - -getPersonInfo`${person} is ${age} years old`; -``` - -- A: `"Lydia"` `21` `["", " is ", " years old"]` -- B: `["", " is ", " years old"]` `"Lydia"` `21` -- C: `"Lydia"` `["", " is ", " years old"]` `21` - -
Odpowiedź -

- -#### Odpowiedź: B - -If you use tagged template literals, the value of the first argument is always an array of the string values. The remaining arguments get the values of the passed expressions! - -

-
- ---- - -###### 18. Jaki jest wynik? - -```javascript -function checkAge(data) { - if (data === { age: 18 }) { - console.log('You are an adult!'); - } else if (data == { age: 18 }) { - console.log('You are still an adult.'); - } else { - console.log(`Hmm.. You don't have an age I guess`); - } -} - -checkAge({ age: 18 }); -``` - -- A: `You are an adult!` -- B: `You are still an adult.` -- C: `Hmm.. You don't have an age I guess` - -
Odpowiedź -

- -#### Odpowiedź: C - -When testing equality, primitives are compared by their _value_, while objects are compared by their _reference_. JavaScript checks if the objects have a reference to the same location in memory. - -The two objects that we are comparing don't have that: the object we passed as a parameter refers to a different location in memory than the object we used in order to check equality. - -This is why both `{ age: 18 } === { age: 18 }` and `{ age: 18 } == { age: 18 }` return `false`. - -

-
- ---- - -###### 19. Jaki jest wynik? - -```javascript -function getAge(...args) { - console.log(typeof args); -} - -getAge(21); -``` - -- A: `"number"` -- B: `"array"` -- C: `"object"` -- D: `"NaN"` - -
Odpowiedź -

- -#### Odpowiedź: C - -The rest parameter (`...args`) lets us "collect" all remaining arguments into an array. An array is an object, so `typeof args` returns `"object"` - -

-
- ---- - -###### 20. Jaki jest wynik? - -```javascript -function getAge() { - 'use strict'; - age = 21; - console.log(age); -} - -getAge(); -``` - -- A: `21` -- B: `undefined` -- C: `ReferenceError` -- D: `TypeError` - -
Odpowiedź -

- -#### Odpowiedź: C - -With `"use strict"`, you can make sure that you don't accidentally declare global variables. We never declared the variable `age`, and since we use `"use strict"`, it will throw a reference error. If we didn't use `"use strict"`, it would have worked, since the property `age` would have gotten added to the global object. - -

-
- ---- - -###### 21. What's the value of `sum`? - -```javascript -const sum = eval('10*10+5'); -``` - -- A: `105` -- B: `"105"` -- C: `TypeError` -- D: `"10*10+5"` - -
Odpowiedź -

- -#### Odpowiedź: A - -`eval` evaluates codes that's passed as a string. If it's an expression, like in this case, it evaluates the expression. The expression is `10 * 10 + 5`. This returns the number `105`. - -

-
- ---- - -###### 22. How long is cool_secret accessible? - -```javascript -sessionStorage.setItem('cool_secret', 123); -``` - -- A: Forever, the data doesn't get lost. -- B: When the user closes the tab. -- C: When the user closes the entire browser, not only the tab. -- D: When the user shuts off their computer. - -
Odpowiedź -

- -#### Odpowiedź: B - -The data stored in `sessionStorage` is removed after closing the _tab_. - -If you used `localStorage`, the data would've been there forever, unless for example `localStorage.clear()` is invoked. - -

-
- ---- - -###### 23. Jaki jest wynik? - -```javascript -var num = 8; -var num = 10; - -console.log(num); -``` - -- A: `8` -- B: `10` -- C: `SyntaxError` -- D: `ReferenceError` - -
Odpowiedź -

- -#### Odpowiedź: B - -With the `var` keyword, you can declare multiple variables with the same name. The variable will then hold the latest value. - -You cannot do this with `let` or `const` since they're block-scoped. - -

-
- ---- - -###### 24. Jaki jest wynik? - -```javascript -const obj = { 1: 'a', 2: 'b', 3: 'c' }; -const set = new Set([1, 2, 3, 4, 5]); - -obj.hasOwnProperty('1'); -obj.hasOwnProperty(1); -set.has('1'); -set.has(1); -``` - -- A: `false` `true` `false` `true` -- B: `false` `true` `true` `true` -- C: `true` `true` `false` `true` -- D: `true` `true` `true` `true` - -
Odpowiedź -

- -#### Odpowiedź: C - -All object keys (excluding Symbols) are strings under the hood, even if you don't type it yourself as a string. This is why `obj.hasOwnProperty('1')` also returns true. - -It doesn't work that way for a set. There is no `'1'` in our set: `set.has('1')` returns `false`. It has the numeric type `1`, `set.has(1)` returns `true`. - -

-
- ---- - -###### 25. Jaki jest wynik? - -```javascript -const obj = { a: 'one', b: 'two', a: 'three' }; -console.log(obj); -``` - -- A: `{ a: "one", b: "two" }` -- B: `{ b: "two", a: "three" }` -- C: `{ a: "three", b: "two" }` -- D: `SyntaxError` - -
Odpowiedź -

- -#### Odpowiedź: C - -If you have two keys with the same name, the key will be replaced. It will still be in its first position, but with the last specified value. - -

-
- ---- - -###### 26. The JavaScript global execution context creates two things for you: the global object, and the "this" keyword. - -- A: true -- B: false -- C: it depends - -
Odpowiedź -

- -#### Odpowiedź: A - -The base execution context is the global execution context: it's what's accessible everywhere in your code. - -

-
- ---- - -###### 27. Jaki jest wynik? - -```javascript -for (let i = 1; i < 5; i++) { - if (i === 3) continue; - console.log(i); -} -``` - -- A: `1` `2` -- B: `1` `2` `3` -- C: `1` `2` `4` -- D: `1` `3` `4` - -
Odpowiedź -

- -#### Odpowiedź: C - -The `continue` statement skips an iteration if a certain condition returns `true`. - -

-
- ---- - -###### 28. Jaki jest wynik? - -```javascript -String.prototype.giveLydiaPizza = () => { - return 'Just give Lydia pizza already!'; -}; - -const name = 'Lydia'; - -console.log(name.giveLydiaPizza()) -``` - -- A: `"Just give Lydia pizza already!"` -- B: `TypeError: not a function` -- C: `SyntaxError` -- D: `undefined` - -
Odpowiedź -

- -#### Odpowiedź: A - -`String` is a built-in constructor, which we can add properties to. I just added a method to its prototype. Primitive strings are automatically converted into a string object, generated by the string prototype function. So, all strings (string objects) have access to that method! - -

-
- ---- - -###### 29. Jaki jest wynik? - -```javascript -const a = {}; -const b = { key: 'b' }; -const c = { key: 'c' }; - -a[b] = 123; -a[c] = 456; - -console.log(a[b]); -``` - -- A: `123` -- B: `456` -- C: `undefined` -- D: `ReferenceError` - -
Odpowiedź -

- -#### Odpowiedź: B - -Object keys are automatically converted into strings. We are trying to set an object as a key to object `a`, with the value of `123`. - -However, when we stringify an object, it becomes `"[object Object]"`. So what we are saying here, is that `a["[object Object]"] = 123`. Then, we can try to do the same again. `c` is another object that we are implicitly stringifying. So then, `a["[object Object]"] = 456`. - -Then, we log `a[b]`, which is actually `a["[object Object]"]`. We just set that to `456`, so it returns `456`. - -

-
- ---- - -###### 30. Jaki jest wynik? - -```javascript -const foo = () => console.log('First'); -const bar = () => setTimeout(() => console.log('Second')); -const baz = () => console.log('Third'); - -bar(); -foo(); -baz(); -``` - -- A: `First` `Second` `Third` -- B: `First` `Third` `Second` -- C: `Second` `First` `Third` -- D: `Second` `Third` `First` - -
Odpowiedź -

- -#### Odpowiedź: B - -We have a `setTimeout` function and invoked it first. Yet, it was logged last. - -This is because in browsers, we don't just have the runtime engine, we also have something called a `WebAPI`. The `WebAPI` gives us the `setTimeout` function to start with, and for example the DOM. - -After the _callback_ is pushed to the WebAPI, the `setTimeout` function itself (but not the callback!) is popped off the stack. - - - -Now, `foo` gets invoked, and `"First"` is being logged. - - - -`foo` is popped off the stack, and `baz` gets invoked. `"Third"` gets logged. - - - -The WebAPI can't just add stuff to the stack whenever it's ready. Instead, it pushes the callback function to something called the _queue_. - - - -This is where an event loop starts to work. An **event loop** looks at the stack and task queue. If the stack is empty, it takes the first thing on the queue and pushes it onto the stack. - - - -`bar` gets invoked, `"Second"` gets logged, and it's popped off the stack. - -

-
- ---- - -###### 31. What is the event.target when clicking the button? - -```html -
-
- -
-
-``` - -- A: Outer `div` -- B: Inner `div` -- C: `button` -- D: An array of all nested elements. - -
Odpowiedź -

- -#### Odpowiedź: C - -The deepest nested element that caused the event is the target of the event. You can stop bubbling by `event.stopPropagation` - -

-
- ---- - -###### 32. When you click the paragraph, what's the logged output? - -```html -
-

- Click here! -

-
-``` - -- A: `p` `div` -- B: `div` `p` -- C: `p` -- D: `div` - -
Odpowiedź -

- -#### Odpowiedź: A - -If we click `p`, we see two logs: `p` and `div`. During event propagation, there are 3 phases: capturing, target, and bubbling. By default, event handlers are executed in the bubbling phase (unless you set `useCapture` to `true`). It goes from the deepest nested element outwards. - -

-
- ---- - -###### 33. Jaki jest wynik? - -```javascript -const person = { name: 'Lydia' }; - -function sayHi(age) { - return `${this.name} is ${age}`; -} - -console.log(sayHi.call(person, 21)); -console.log(sayHi.bind(person, 21)); -``` - -- A: `undefined is 21` `Lydia is 21` -- B: `function` `function` -- C: `Lydia is 21` `Lydia is 21` -- D: `Lydia is 21` `function` - -
Odpowiedź -

- -#### Odpowiedź: D - -With both, we can pass the object to which we want the `this` keyword to refer to. However, `.call` is also _executed immediately_! - -`.bind.` returns a _copy_ of the function, but with a bound context! It is not executed immediately. - -

-
- ---- - -###### 34. Jaki jest wynik? - -```javascript -function sayHi() { - return (() => 0)(); -} - -console.log(typeof sayHi()); -``` - -- A: `"object"` -- B: `"number"` -- C: `"function"` -- D: `"undefined"` - -
Odpowiedź -

- -#### Odpowiedź: B - -The `sayHi` function returns the returned value of the immediately invoked function expression (IIFE). This function returned `0`, which is type `"number"`. - -FYI: `typeof` can return the following list of values: `undefined`, `boolean`, `number`, `bigint`, `string`, `symbol`, `function` and `object`. Note that `typeof null` returns `"object"`. - -

-
- ---- - -###### 35. Which of these values are falsy? - -```javascript -0; -new Number(0); -(''); -(' '); -new Boolean(false); -undefined; -``` - -- A: `0`, `''`, `undefined` -- B: `0`, `new Number(0)`, `''`, `new Boolean(false)`, `undefined` -- C: `0`, `''`, `new Boolean(false)`, `undefined` -- D: All of them are falsy - -
Odpowiedź -

- -#### Odpowiedź: A - -There are 8 falsy values: - -- `undefined` -- `null` -- `NaN` -- `false` -- `''` (empty string) -- `0` -- `-0` -- `0n` (BigInt(0)) - -Function constructors, like `new Number` and `new Boolean` are truthy. - -

-
- ---- - -###### 36. Jaki jest wynik? - -```javascript -console.log(typeof typeof 1); -``` - -- A: `"number"` -- B: `"string"` -- C: `"object"` -- D: `"undefined"` - -
Odpowiedź -

- -#### Odpowiedź: B - -`typeof 1` returns `"number"`. -`typeof "number"` returns `"string"` - -

-
- ---- - -###### 37. Jaki jest wynik? - -```javascript -const numbers = [1, 2, 3]; -numbers[10] = 11; -console.log(numbers); -``` - -- A: `[1, 2, 3, null x 7, 11]` -- B: `[1, 2, 3, 11]` -- C: `[1, 2, 3, empty x 7, 11]` -- D: `SyntaxError` - -
Odpowiedź -

- -#### Odpowiedź: C - -When you set a value to an element in an array that exceeds the length of the array, JavaScript creates something called "empty slots". These actually have the value of `undefined`, but you will see something like: - -`[1, 2, 3, empty x 7, 11]` - -depending on where you run it (it's different for every browser, node, etc.) - -

-
- ---- - -###### 38. Jaki jest wynik? - -```javascript -(() => { - let x, y; - try { - throw new Error(); - } catch (x) { - (x = 1), (y = 2); - console.log(x); - } - console.log(x); - console.log(y); -})(); -``` - -- A: `1` `undefined` `2` -- B: `undefined` `undefined` `undefined` -- C: `1` `1` `2` -- D: `1` `undefined` `undefined` - -
Odpowiedź -

- -#### Odpowiedź: A - -The `catch` block receives the argument `x`. This is not the same `x` as the variable when we pass arguments. This variable `x` is block-scoped. - -Later, we set this block-scoped variable equal to `1`, and set the value of the variable `y`. Now, we log the block-scoped variable `x`, which is equal to `1`. - -Outside of the `catch` block, `x` is still `undefined`, and `y` is `2`. When we want to `console.log(x)` outside of the `catch` block, it returns `undefined`, and `y` returns `2`. - -

-
- ---- - -###### 39. Everything in JavaScript is either a... - -- A: primitive or object -- B: function or object -- C: trick question! only objects -- D: number or object - -
Odpowiedź -

- -#### Odpowiedź: A - -JavaScript only has primitive types and objects. - -Primitive types are `boolean`, `null`, `undefined`, `bigint`, `number`, `string`, and `symbol`. - -What differentiates a primitive from an object is that primitives do not have any properties or methods; however, you'll note that `'foo'.toUpperCase()` evaluates to `'FOO'` and does not result in a `TypeError`. This is because when you try to access a property or method on a primitive like a string, JavaScript will implicitly wrap the primitive type using one of the wrapper classes, i.e. `String`, and then immediately discard the wrapper after the expression evaluates. All primitives except for `null` and `undefined` exhibit this behaviour. - -

-
- ---- - -###### 40. Jaki jest wynik? - -```javascript -[[0, 1], [2, 3]].reduce( - (acc, cur) => { - return acc.concat(cur); - }, - [1, 2], -); -``` - -- A: `[0, 1, 2, 3, 1, 2]` -- B: `[6, 1, 2]` -- C: `[1, 2, 0, 1, 2, 3]` -- D: `[1, 2, 6]` - -
Odpowiedź -

- -#### Odpowiedź: C - -`[1, 2]` is our initial value. This is the value we start with, and the value of the very first `acc`. During the first round, `acc` is `[1,2]`, and `cur` is `[0, 1]`. We concatenate them, which results in `[1, 2, 0, 1]`. - -Then, `[1, 2, 0, 1]` is `acc` and `[2, 3]` is `cur`. We concatenate them, and get `[1, 2, 0, 1, 2, 3]` - -

-
- ---- - -###### 41. Jaki jest wynik? - -```javascript -!!null; -!!''; -!!1; -``` - -- A: `false` `true` `false` -- B: `false` `false` `true` -- C: `false` `true` `true` -- D: `true` `true` `false` - -
Odpowiedź -

- -#### Odpowiedź: B - -`null` is falsy. `!null` returns `true`. `!true` returns `false`. - -`""` is falsy. `!""` returns `true`. `!true` returns `false`. - -`1` is truthy. `!1` returns `false`. `!false` returns `true`. - -

-
- ---- - -###### 42. What does the `setInterval` method return in the browser? - -```javascript -setInterval(() => console.log('Hi'), 1000); -``` - -- A: a unique id -- B: the amount of milliseconds specified -- C: the passed function -- D: `undefined` - -
Odpowiedź -

- -#### Odpowiedź: A - -It returns a unique id. This id can be used to clear that interval with the `clearInterval()` function. - -

-
- ---- - -###### 43. What does this return? - -```javascript -[...'Lydia']; -``` - -- A: `["L", "y", "d", "i", "a"]` -- B: `["Lydia"]` -- C: `[[], "Lydia"]` -- D: `[["L", "y", "d", "i", "a"]]` - -
Odpowiedź -

- -#### Odpowiedź: A - -A string is an iterable. The spread operator maps every character of an iterable to one element. - -

-
- ---- - -###### 44. Jaki jest wynik? - -```javascript -function* generator(i) { - yield i; - yield i * 2; -} - -const gen = generator(10); - -console.log(gen.next().value); -console.log(gen.next().value); -``` - -- A: `[0, 10], [10, 20]` -- B: `20, 20` -- C: `10, 20` -- D: `0, 10 and 10, 20` - -
Odpowiedź -

- -#### Odpowiedź: C - -Regular functions cannot be stopped mid-way after invocation. However, a generator function can be "stopped" midway, and later continue from where it stopped. Every time a generator function encounters a `yield` keyword, the function yields the value specified after it. Note that the generator function in that case doesn’t _return_ the value, it _yields_ the value. - -First, we initialize the generator function with `i` equal to `10`. We invoke the generator function using the `next()` method. The first time we invoke the generator function, `i` is equal to `10`. It encounters the first `yield` keyword: it yields the value of `i`. The generator is now "paused", and `10` gets logged. - -Then, we invoke the function again with the `next()` method. It starts to continue where it stopped previously, still with `i` equal to `10`. Now, it encounters the next `yield` keyword, and yields `i * 2`. `i` is equal to `10`, so it returns `10 * 2`, which is `20`. This results in `10, 20`. - -

-
- ---- - -###### 45. What does this return? - -```javascript -const firstPromise = new Promise((res, rej) => { - setTimeout(res, 500, 'one'); -}); - -const secondPromise = new Promise((res, rej) => { - setTimeout(res, 100, 'two'); -}); - -Promise.race([firstPromise, secondPromise]).then(res => console.log(res)); -``` - -- A: `"one"` -- B: `"two"` -- C: `"two" "one"` -- D: `"one" "two"` - -
Odpowiedź -

- -#### Odpowiedź: B - -When we pass multiple promises to the `Promise.race` method, it resolves/rejects the _first_ promise that resolves/rejects. To the `setTimeout` method, we pass a timer: 500ms for the first promise (`firstPromise`), and 100ms for the second promise (`secondPromise`). This means that the `secondPromise` resolves first with the value of `'two'`. `res` now holds the value of `'two'`, which gets logged. - -

-
- ---- - -###### 46. Jaki jest wynik? - -```javascript -let person = { name: 'Lydia' }; -const members = [person]; -person = null; - -console.log(members); -``` - -- A: `null` -- B: `[null]` -- C: `[{}]` -- D: `[{ name: "Lydia" }]` - -
Odpowiedź -

- -#### Odpowiedź: D - -First, we declare a variable `person` with the value of an object that has a `name` property. - - - -Then, we declare a variable called `members`. We set the first element of that array equal to the value of the `person` variable. Objects interact by _reference_ when setting them equal to each other. When you assign a reference from one variable to another, you make a _copy_ of that reference. (note that they don't have the _same_ reference!) - - - -Then, we set the variable `person` equal to `null`. - - - -We are only modifying the value of the `person` variable, and not the first element in the array, since that element has a different (copied) reference to the object. The first element in `members` still holds its reference to the original object. When we log the `members` array, the first element still holds the value of the object, which gets logged. - -

-
- ---- - -###### 47. Jaki jest wynik? - -```javascript -const person = { - name: 'Lydia', - age: 21, -}; - -for (const item in person) { - console.log(item); -} -``` - -- A: `{ name: "Lydia" }, { age: 21 }` -- B: `"name", "age"` -- C: `"Lydia", 21` -- D: `["name", "Lydia"], ["age", 21]` - -
Odpowiedź -

- -#### Odpowiedź: B - -With a `for-in` loop, we can iterate through object keys, in this case `name` and `age`. Under the hood, object keys are strings (if they're not a Symbol). On every loop, we set the value of `item` equal to the current key it’s iterating over. First, `item` is equal to `name`, and gets logged. Then, `item` is equal to `age`, which gets logged. - -

-
- ---- - -###### 48. Jaki jest wynik? - -```javascript -console.log(3 + 4 + '5'); -``` - -- A: `"345"` -- B: `"75"` -- C: `12` -- D: `"12"` - -
Odpowiedź -

- -#### Odpowiedź: B - -Operator associativity is the order in which the compiler evaluates the expressions, either left-to-right or right-to-left. This only happens if all operators have the _same_ precedence. We only have one type of operator: `+`. For addition, the associativity is left-to-right. - -`3 + 4` gets evaluated first. This results in the number `7`. - -`7 + '5'` results in `"75"` because of coercion. JavaScript converts the number `7` into a string, see question 15. We can concatenate two strings using the `+`operator. `"7" + "5"` results in `"75"`. - -

-
- ---- - -###### 49. What's the value of `num`? - -```javascript -const num = parseInt('7*6', 10); -``` - -- A: `42` -- B: `"42"` -- C: `7` -- D: `NaN` - -
Odpowiedź -

- -#### Odpowiedź: C - -Only the first numbers in the string is returned. Based on the _radix_ (the second argument in order to specify what type of number we want to parse it to: base 10, hexadecimal, octal, binary, etc.), the `parseInt` checks whether the characters in the string are valid. Once it encounters a character that isn't a valid number in the radix, it stops parsing and ignores the following characters. - -`*` is not a valid number. It only parses `"7"` into the decimal `7`. `num` now holds the value of `7`. - -

-
- ---- - -###### 50. Jaki jest wynik? - -```javascript -[1, 2, 3].map(num => { - if (typeof num === 'number') return; - return num * 2; -}); -``` - -- A: `[]` -- B: `[null, null, null]` -- C: `[undefined, undefined, undefined]` -- D: `[ 3 x empty ]` - -
Odpowiedź -

- -#### Odpowiedź: C - -When mapping over the array, the value of `num` is equal to the element it’s currently looping over. In this case, the elements are numbers, so the condition of the if statement `typeof num === "number"` returns `true`. The map function creates a new array and inserts the values returned from the function. - -However, we don’t return a value. When we don’t return a value from the function, the function returns `undefined`. For every element in the array, the function block gets called, so for each element we return `undefined`. - -

-
- ---- - -###### 51. Jaki jest wynik? - -```javascript -function getInfo(member, year) { - member.name = 'Lydia'; - year = '1998'; -} - -const person = { name: 'Sarah' }; -const birthYear = '1997'; - -getInfo(person, birthYear); - -console.log(person, birthYear); -``` - -- A: `{ name: "Lydia" }, "1997"` -- B: `{ name: "Sarah" }, "1998"` -- C: `{ name: "Lydia" }, "1998"` -- D: `{ name: "Sarah" }, "1997"` - -
Odpowiedź -

- -#### Odpowiedź: A - -Arguments are passed by _value_, unless their value is an object, then they're passed by _reference_. `birthYear` is passed by value, since it's a string, not an object. When we pass arguments by value, a _copy_ of that value is created (see question 46). - -The variable `birthYear` has a reference to the value `"1997"`. The argument `year` also has a reference to the value `"1997"`, but it's not the same value as `birthYear` has a reference to. When we update the value of `year` by setting `year` equal to `"1998"`, we are only updating the value of `year`. `birthYear` is still equal to `"1997"`. - -The value of `person` is an object. The argument `member` has a (copied) reference to the _same_ object. When we modify a property of the object `member` has a reference to, the value of `person` will also be modified, since they both have a reference to the same object. `person`'s `name` property is now equal to the value `"Lydia"` - -

-
- ---- - -###### 52. Jaki jest wynik? - -```javascript -function greeting() { - throw 'Hello world!'; -} - -function sayHi() { - try { - const data = greeting(); - console.log('It worked!', data); - } catch (e) { - console.log('Oh no an error:', e); - } -} - -sayHi(); -``` - -- A: `It worked! Hello world!` -- B: `Oh no an error: undefined` -- C: `SyntaxError: can only throw Error objects` -- D: `Oh no an error: Hello world!` - -
Odpowiedź -

- -#### Odpowiedź: D - -With the `throw` statement, we can create custom errors. With this statement, you can throw exceptions. An exception can be a string, a number, a boolean or an object. In this case, our exception is the string `'Hello world!'`. - -With the `catch` statement, we can specify what to do if an exception is thrown in the `try` block. An exception is thrown: the string `'Hello world!'`. `e` is now equal to that string, which we log. This results in `'Oh an error: Hello world!'`. - -

-
- ---- - -###### 53. Jaki jest wynik? - -```javascript -function Car() { - this.make = 'Lamborghini'; - return { make: 'Maserati' }; -} - -const myCar = new Car(); -console.log(myCar.make); -``` - -- A: `"Lamborghini"` -- B: `"Maserati"` -- C: `ReferenceError` -- D: `TypeError` - -
Odpowiedź -

- -#### Odpowiedź: B - -When you return a property, the value of the property is equal to the _returned_ value, not the value set in the constructor function. We return the string `"Maserati"`, so `myCar.make` is equal to `"Maserati"`. - -

-
- ---- - -###### 54. Jaki jest wynik? - -```javascript -(() => { - let x = (y = 10); -})(); - -console.log(typeof x); -console.log(typeof y); -``` - -- A: `"undefined", "number"` -- B: `"number", "number"` -- C: `"object", "number"` -- D: `"number", "undefined"` - -
Odpowiedź -

- -#### Odpowiedź: A - -`let x = (y = 10);` is actually shorthand for: - -```javascript -y = 10; -let x = y; -``` - -When we set `y` equal to `10`, we actually add a property `y` to the global object (`window` in browser, `global` in Node). In a browser, `window.y` is now equal to `10`. - -Then, we declare a variable `x` with the value of `y`, which is `10`. Variables declared with the `let` keyword are _block scoped_, they are only defined within the block they're declared in; the immediately invoked function expression (IIFE) in this case. When we use the `typeof` operator, the operand `x` is not defined: we are trying to access `x` outside of the block it's declared in. This means that `x` is not defined. Values who haven't been assigned a value or declared are of type `"undefined"`. `console.log(typeof x)` returns `"undefined"`. - -However, we created a global variable `y` when setting `y` equal to `10`. This value is accessible anywhere in our code. `y` is defined, and holds a value of type `"number"`. `console.log(typeof y)` returns `"number"`. - -

-
- ---- - -###### 55. Jaki jest wynik? - -```javascript -class Dog { - constructor(name) { - this.name = name; - } -} - -Dog.prototype.bark = function() { - console.log(`Woof I am ${this.name}`); -}; - -const pet = new Dog('Mara'); - -pet.bark(); - -delete Dog.prototype.bark; - -pet.bark(); -``` - -- A: `"Woof I am Mara"`, `TypeError` -- B: `"Woof I am Mara"`, `"Woof I am Mara"` -- C: `"Woof I am Mara"`, `undefined` -- D: `TypeError`, `TypeError` - -
Odpowiedź -

- -#### Odpowiedź: A - -We can delete properties from objects using the `delete` keyword, also on the prototype. By deleting a property on the prototype, it is not available anymore in the prototype chain. In this case, the `bark` function is not available anymore on the prototype after `delete Dog.prototype.bark`, yet we still try to access it. - -When we try to invoke something that is not a function, a `TypeError` is thrown. In this case `TypeError: pet.bark is not a function`, since `pet.bark` is `undefined`. - -

-
- ---- - -###### 56. Jaki jest wynik? - -```javascript -const set = new Set([1, 1, 2, 3, 4]); - -console.log(set); -``` - -- A: `[1, 1, 2, 3, 4]` -- B: `[1, 2, 3, 4]` -- C: `{1, 1, 2, 3, 4}` -- D: `{1, 2, 3, 4}` - -
Odpowiedź -

- -#### Odpowiedź: D - -The `Set` object is a collection of _unique_ values: a value can only occur once in a set. - -We passed the iterable `[1, 1, 2, 3, 4]` with a duplicate value `1`. Since we cannot have two of the same values in a set, one of them is removed. This results in `{1, 2, 3, 4}`. - -

-
- ---- - -###### 57. Jaki jest wynik? - -```javascript -// counter.js -let counter = 10; -export default counter; -``` - -```javascript -// index.js -import myCounter from './counter'; - -myCounter += 1; - -console.log(myCounter); -``` - -- A: `10` -- B: `11` -- C: `Error` -- D: `NaN` - -
Odpowiedź -

- -#### Odpowiedź: C - -An imported module is _read-only_: you cannot modify the imported module. Only the module that exports them can change its value. - -When we try to increment the value of `myCounter`, it throws an error: `myCounter` is read-only and cannot be modified. - -

-
- ---- - -###### 58. Jaki jest wynik? - -```javascript -const name = 'Lydia'; -age = 21; - -console.log(delete name); -console.log(delete age); -``` - -- A: `false`, `true` -- B: `"Lydia"`, `21` -- C: `true`, `true` -- D: `undefined`, `undefined` - -
Odpowiedź -

- -#### Odpowiedź: A - -The `delete` operator returns a boolean value: `true` on a successful deletion, else it'll return `false`. However, variables declared with the `var`, `const` or `let` keyword cannot be deleted using the `delete` operator. - -The `name` variable was declared with a `const` keyword, so its deletion is not successful: `false` is returned. When we set `age` equal to `21`, we actually added a property called `age` to the global object. You can successfully delete properties from objects this way, also the global object, so `delete age` returns `true`. - -

-
- ---- - -###### 59. Jaki jest wynik? - -```javascript -const numbers = [1, 2, 3, 4, 5]; -const [y] = numbers; - -console.log(y); -``` - -- A: `[[1, 2, 3, 4, 5]]` -- B: `[1, 2, 3, 4, 5]` -- C: `1` -- D: `[1]` - -
Odpowiedź -

- -#### Odpowiedź: C - -We can unpack values from arrays or properties from objects through destructuring. For example: - -```javascript -[a, b] = [1, 2]; -``` - - - -The value of `a` is now `1`, and the value of `b` is now `2`. What we actually did in the question, is: - -```javascript -[y] = [1, 2, 3, 4, 5]; -``` - - - -This means that the value of `y` is equal to the first value in the array, which is the number `1`. When we log `y`, `1` is returned. - -

-
- ---- - -###### 60. Jaki jest wynik? - -```javascript -const user = { name: 'Lydia', age: 21 }; -const admin = { admin: true, ...user }; - -console.log(admin); -``` - -- A: `{ admin: true, user: { name: "Lydia", age: 21 } }` -- B: `{ admin: true, name: "Lydia", age: 21 }` -- C: `{ admin: true, user: ["Lydia", 21] }` -- D: `{ admin: true }` - -
Odpowiedź -

- -#### Odpowiedź: B - -It's possible to combine objects using the spread operator `...`. It lets you create copies of the key/value pairs of one object, and add them to another object. In this case, we create copies of the `user` object, and add them to the `admin` object. The `admin` object now contains the copied key/value pairs, which results in `{ admin: true, name: "Lydia", age: 21 }`. - -

-
- ---- - -###### 61. Jaki jest wynik? - -```javascript -const person = { name: 'Lydia' }; - -Object.defineProperty(person, 'age', { value: 21 }); - -console.log(person); -console.log(Object.keys(person)); -``` - -- A: `{ name: "Lydia", age: 21 }`, `["name", "age"]` -- B: `{ name: "Lydia", age: 21 }`, `["name"]` -- C: `{ name: "Lydia"}`, `["name", "age"]` -- D: `{ name: "Lydia"}`, `["age"]` - -
Odpowiedź -

- -#### Odpowiedź: B - -With the `defineProperty` method, we can add new properties to an object, or modify existing ones. When we add a property to an object using the `defineProperty` method, they are by default _not enumerable_. The `Object.keys` method returns all _enumerable_ property names from an object, in this case only `"name"`. - -Properties added using the `defineProperty` method are immutable by default. You can override this behavior using the `writable`, `configurable` and `enumerable` properties. This way, the `defineProperty` method gives you a lot more control over the properties you're adding to an object. - -

-
- ---- - -###### 62. Jaki jest wynik? - -```javascript -const settings = { - username: 'lydiahallie', - level: 19, - health: 90, -}; - -const data = JSON.stringify(settings, ['level', 'health']); -console.log(data); -``` - -- A: `"{"level":19, "health":90}"` -- B: `"{"username": "lydiahallie"}"` -- C: `"["level", "health"]"` -- D: `"{"username": "lydiahallie", "level":19, "health":90}"` - -
Odpowiedź -

- -#### Odpowiedź: A - -The second argument of `JSON.stringify` is the _replacer_. The replacer can either be a function or an array, and lets you control what and how the values should be stringified. - -If the replacer is an _array_, only the property names included in the array will be added to the JSON string. In this case, only the properties with the names `"level"` and `"health"` are included, `"username"` is excluded. `data` is now equal to `"{"level":19, "health":90}"`. - -If the replacer is a _function_, this function gets called on every property in the object you're stringifying. The value returned from this function will be the value of the property when it's added to the JSON string. If the value is `undefined`, this property is excluded from the JSON string. - -

-
- ---- - -###### 63. Jaki jest wynik? - -```javascript -let num = 10; - -const increaseNumber = () => num++; -const increasePassedNumber = number => number++; - -const num1 = increaseNumber(); -const num2 = increasePassedNumber(num1); - -console.log(num1); -console.log(num2); -``` - -- A: `10`, `10` -- B: `10`, `11` -- C: `11`, `11` -- D: `11`, `12` - -
Odpowiedź -

- -#### Odpowiedź: A - -The unary operator `++` _first returns_ the value of the operand, _then increments_ the value of the operand. The value of `num1` is `10`, since the `increaseNumber` function first returns the value of `num`, which is `10`, and only increments the value of `num` afterwards. - -`num2` is `10`, since we passed `num1` to the `increasePassedNumber`. `number` is equal to `10`(the value of `num1`. Again, the unary operator `++` _first returns_ the value of the operand, _then increments_ the value of the operand. The value of `number` is `10`, so `num2` is equal to `10`. - -

-
- ---- - -###### 64. Jaki jest wynik? - -```javascript -const value = { number: 10 }; - -const multiply = (x = { ...value }) => { - console.log((x.number *= 2)); -}; - -multiply(); -multiply(); -multiply(value); -multiply(value); -``` - -- A: `20`, `40`, `80`, `160` -- B: `20`, `40`, `20`, `40` -- C: `20`, `20`, `20`, `40` -- D: `NaN`, `NaN`, `20`, `40` - -
Odpowiedź -

- -#### Odpowiedź: C - -In ES6, we can initialize parameters with a default value. The value of the parameter will be the default value, if no other value has been passed to the function, or if the value of the parameter is `"undefined"`. In this case, we spread the properties of the `value` object into a new object, so `x` has the default value of `{ number: 10 }`. - -The default argument is evaluated at _call time_! Every time we call the function, a _new_ object is created. We invoke the `multiply` function the first two times without passing a value: `x` has the default value of `{ number: 10 }`. We then log the multiplied value of that number, which is `20`. - -The third time we invoke multiply, we do pass an argument: the object called `value`. The `*=` operator is actually shorthand for `x.number = x.number * 2`: we modify the value of `x.number`, and log the multiplied value `20`. - -The fourth time, we pass the `value` object again. `x.number` was previously modified to `20`, so `x.number *= 2` logs `40`. - -

-
- ---- - -###### 65. Jaki jest wynik? - -```javascript -[1, 2, 3, 4].reduce((x, y) => console.log(x, y)); -``` - -- A: `1` `2` and `3` `3` and `6` `4` -- B: `1` `2` and `2` `3` and `3` `4` -- C: `1` `undefined` and `2` `undefined` and `3` `undefined` and `4` `undefined` -- D: `1` `2` and `undefined` `3` and `undefined` `4` - -
Odpowiedź -

- -#### Odpowiedź: D - -The first argument that the `reduce` method receives is the _accumulator_, `x` in this case. The second argument is the _current value_, `y`. With the reduce method, we execute a callback function on every element in the array, which could ultimately result in one single value. - -In this example, we are not returning any values, we are simply logging the values of the accumulator and the current value. - -The value of the accumulator is equal to the previously returned value of the callback function. If you don't pass the optional `initialValue` argument to the `reduce` method, the accumulator is equal to the first element on the first call. - -On the first call, the accumulator (`x`) is `1`, and the current value (`y`) is `2`. We don't return from the callback function, we log the accumulator and current value: `1` and `2` get logged. - -If you don't return a value from a function, it returns `undefined`. On the next call, the accumulator is `undefined`, and the current value is `3`. `undefined` and `3` get logged. - -On the fourth call, we again don't return from the callback function. The accumulator is again `undefined`, and the current value is `4`. `undefined` and `4` get logged. - -

-
- ---- - -###### 66. With which constructor can we successfully extend the `Dog` class? - -```javascript -class Dog { - constructor(name) { - this.name = name; - } -}; - -class Labrador extends Dog { - // 1 - constructor(name, size) { - this.size = size; - } - // 2 - constructor(name, size) { - super(name); - this.size = size; - } - // 3 - constructor(size) { - super(name); - this.size = size; - } - // 4 - constructor(name, size) { - this.name = name; - this.size = size; - } - -}; -``` - -- A: 1 -- B: 2 -- C: 3 -- D: 4 - -
Odpowiedź -

- -#### Odpowiedź: B - -In a derived class, you cannot access the `this` keyword before calling `super`. If you try to do that, it will throw a ReferenceError: 1 and 4 would throw a reference error. - -With the `super` keyword, we call that parent class's constructor with the given arguments. The parent's constructor receives the `name` argument, so we need to pass `name` to `super`. - -The `Labrador` class receives two arguments, `name` since it extends `Dog`, and `size` as an extra property on the `Labrador` class. They both need to be passed to the constructor function on `Labrador`, which is done correctly using constructor 2. - -

-
- ---- - -###### 67. Jaki jest wynik? - -```javascript -// index.js -console.log('running index.js'); -import { sum } from './sum.js'; -console.log(sum(1, 2)); - -// sum.js -console.log('running sum.js'); -export const sum = (a, b) => a + b; -``` - -- A: `running index.js`, `running sum.js`, `3` -- B: `running sum.js`, `running index.js`, `3` -- C: `running sum.js`, `3`, `running index.js` -- D: `running index.js`, `undefined`, `running sum.js` - -
Odpowiedź -

- -#### Odpowiedź: B - -With the `import` keyword, all imported modules are _pre-parsed_. This means that the imported modules get run _first_, the code in the file which imports the module gets executed _after_. - -This is a difference between `require()` in CommonJS and `import`! With `require()`, you can load dependencies on demand while the code is being run. If we would have used `require` instead of `import`, `running index.js`, `running sum.js`, `3` would have been logged to the console. - -

-
- ---- - -###### 68. Jaki jest wynik? - -```javascript -console.log(Number(2) === Number(2)); -console.log(Boolean(false) === Boolean(false)); -console.log(Symbol('foo') === Symbol('foo')); -``` - -- A: `true`, `true`, `false` -- B: `false`, `true`, `false` -- C: `true`, `false`, `true` -- D: `true`, `true`, `true` - -
Odpowiedź -

- -#### Odpowiedź: A - -Every Symbol is entirely unique. The purpose of the argument passed to the Symbol is to give the Symbol a description. The value of the Symbol is not dependent on the passed argument. As we test equality, we are creating two entirely new symbols: the first `Symbol('foo')`, and the second `Symbol('foo')`. These two values are unique and not equal to each other, `Symbol('foo') === Symbol('foo')` returns `false`. - -

-
- ---- - -###### 69. Jaki jest wynik? - -```javascript -const name = 'Lydia Hallie'; -console.log(name.padStart(13)); -console.log(name.padStart(2)); -``` - -- A: `"Lydia Hallie"`, `"Lydia Hallie"` -- B: `" Lydia Hallie"`, `" Lydia Hallie"` (`"[13x whitespace]Lydia Hallie"`, `"[2x whitespace]Lydia Hallie"`) -- C: `" Lydia Hallie"`, `"Lydia Hallie"` (`"[1x whitespace]Lydia Hallie"`, `"Lydia Hallie"`) -- D: `"Lydia Hallie"`, `"Lyd"`, - -
Odpowiedź -

- -#### Odpowiedź: C - -With the `padStart` method, we can add padding to the beginning of a string. The value passed to this method is the _total_ length of the string together with the padding. The string `"Lydia Hallie"` has a length of `12`. `name.padStart(13)` inserts 1 space at the start of the string, because 12 + 1 is 13. - -If the argument passed to the `padStart` method is smaller than the length of the array, no padding will be added. - -

-
- ---- - -###### 70. Jaki jest wynik? - -```javascript -console.log('🥑' + '💻'); -``` - -- A: `"🥑💻"` -- B: `257548` -- C: A string containing their code points -- D: Error - -
Odpowiedź -

- -#### Odpowiedź: A - -With the `+` operator, you can concatenate strings. In this case, we are concatenating the string `"🥑"` with the string `"💻"`, resulting in `"🥑💻"`. - -

-
- ---- - -###### 71. How can we log the values that are commented out after the console.log statement? - -```javascript -function* startGame() { - const answer = yield 'Do you love JavaScript?'; - if (answer !== 'Yes') { - return "Oh wow... Guess we're done here"; - } - return 'JavaScript loves you back ❤️'; -} - -const game = startGame(); -console.log(/* 1 */); // Do you love JavaScript? -console.log(/* 2 */); // JavaScript loves you back ❤️ -``` - -- A: `game.next("Yes").value` and `game.next().value` -- B: `game.next.value("Yes")` and `game.next.value()` -- C: `game.next().value` and `game.next("Yes").value` -- D: `game.next.value()` and `game.next.value("Yes")` - -
Odpowiedź -

- -#### Odpowiedź: C - -A generator function "pauses" its execution when it sees the `yield` keyword. First, we have to let the function yield the string "Do you love JavaScript?", which can be done by calling `game.next().value`. - -Every line is executed, until it finds the first `yield` keyword. There is a `yield` keyword on the first line within the function: the execution stops with the first yield! _This means that the variable `answer` is not defined yet!_ - -When we call `game.next("Yes").value`, the previous `yield` is replaced with the value of the parameters passed to the `next()` function, `"Yes"` in this case. The value of the variable `answer` is now equal to `"Yes"`. The condition of the if-statement returns `false`, and `JavaScript loves you back ❤️` gets logged. - -

-
- ---- - -###### 72. Jaki jest wynik? - -```javascript -console.log(String.raw`Hello\nworld`); -``` - -- A: `Hello world!` -- B: `Hello`
     `world` -- C: `Hello\nworld` -- D: `Hello\n`
     `world` - -
Odpowiedź -

- -#### Odpowiedź: C - -`String.raw` returns a string where the escapes (`\n`, `\v`, `\t` etc.) are ignored! Backslashes can be an issue since you could end up with something like: - -`` const path = `C:\Documents\Projects\table.html` `` - -Which would result in: - -`"C:DocumentsProjects able.html"` - -With `String.raw`, it would simply ignore the escape and print: - -`C:\Documents\Projects\table.html` - -In this case, the string is `Hello\nworld`, which gets logged. - -

-
- ---- - -###### 73. Jaki jest wynik? - -```javascript -async function getData() { - return await Promise.resolve('I made it!'); -} - -const data = getData(); -console.log(data); -``` - -- A: `"I made it!"` -- B: `Promise {: "I made it!"}` -- C: `Promise {}` -- D: `undefined` - -
Odpowiedź -

- -#### Odpowiedź: C - -An async function always returns a promise. The `await` still has to wait for the promise to resolve: a pending promise gets returned when we call `getData()` in order to set `data` equal to it. - -If we wanted to get access to the resolved value `"I made it"`, we could have used the `.then()` method on `data`: - -`data.then(res => console.log(res))` - -This would've logged `"I made it!"` - -

-
- ---- - -###### 74. Jaki jest wynik? - -```javascript -function addToList(item, list) { - return list.push(item); -} - -const result = addToList('apple', ['banana']); -console.log(result); -``` - -- A: `['apple', 'banana']` -- B: `2` -- C: `true` -- D: `undefined` - -
Odpowiedź -

- -#### Odpowiedź: B - -The `.push()` method returns the _length_ of the new array! Previously, the array contained one element (the string `"banana"`) and had a length of `1`. After adding the string `"apple"` to the array, the array contains two elements, and has a length of `2`. This gets returned from the `addToList` function. - -The `push` method modifies the original array. If you wanted to return the _array_ from the function rather than the _length of the array_, you should have returned `list` after pushing `item` to it. - -

-
- ---- - -###### 75. Jaki jest wynik? - -```javascript -const box = { x: 10, y: 20 }; - -Object.freeze(box); - -const shape = box; -shape.x = 100; - -console.log(shape); -``` - -- A: `{ x: 100, y: 20 }` -- B: `{ x: 10, y: 20 }` -- C: `{ x: 100 }` -- D: `ReferenceError` - -
Odpowiedź -

- -#### Odpowiedź: B - -`Object.freeze` makes it impossible to add, remove, or modify properties of an object (unless the property's value is another object). - -When we create the variable `shape` and set it equal to the frozen object `box`, `shape` also refers to a frozen object. You can check whether an object is frozen by using `Object.isFrozen`. In this case, `Object.isFrozen(shape)` would return true, since the variable `shape` has a reference to a frozen object. - -Since `shape` is frozen, and since the value of `x` is not an object, we cannot modify the property `x`. `x` is still equal to `10`, and `{ x: 10, y: 20 }` gets logged. - -

-
- ---- - -###### 76. Jaki jest wynik? - -```javascript -const { firstName: myName } = { firstName: 'Lydia' }; - -console.log(firstName); -``` - -- A: `"Lydia"` -- B: `"myName"` -- C: `undefined` -- D: `ReferenceError` - -
Odpowiedź -

- -#### Odpowiedź: D - -By using [destructuring assignment](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment) syntax we can unpack values from arrays, or properties from objects, into distinct variables: - -```javascript -const { firstName } = { firstName: 'Lydia' }; -// ES5 version: -// var firstName = { firstName: 'Lydia' }.firstName; - -console.log(firstName); // "Lydia" -``` - -Also, a property can be unpacked from an object and assigned to a variable with a different name than the object property: - -```javascript -const { firstName: myName } = { firstName: 'Lydia' }; -// ES5 version: -// var myName = { firstName: 'Lydia' }.firstName; - -console.log(myName); // "Lydia" -console.log(firstName); // Uncaught ReferenceError: firstName is not defined -``` - -Therefore, `firstName` does not exist as a variable, thus attempting to access its value will raise a `ReferenceError`. - -**Note:** Be aware of the `global scope` properties: - -```javascript -const { name: myName } = { name: 'Lydia' }; - -console.log(myName); // "lydia" -console.log(name); // "" ----- Browser e.g. Chrome -console.log(name); // ReferenceError: name is not defined ----- NodeJS - -``` - -Whenever Javascript is unable to find a variable within the _current scope_, it climbs up the [Scope chain](https://github.com/getify/You-Dont-Know-JS/blob/2nd-ed/scope-closures/ch3.md) and searches for it and if it reaches the top-level scope, aka **Global scope**, and still doesn't find it, it will throw a `ReferenceError`. - -- In **Browsers** such as _Chrome_, `name` is a _deprecated global scope property_. In this example, the code is running inside _global scope_ and there is no user defined local variable for `name`, therefore it searches the predefined _variables/properties_ in the global scope which is in case of browsers, it searches through `window` object and it will extract the [window.name](https://developer.mozilla.org/en-US/docs/Web/API/Window/name) value which is equal to an **empty string**. - -- In **NodeJS**, there is no such property on the `global` object, thus attempting to access a non-existent variable will raise a [ReferenceError](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/Not_defined). - -

-
- ---- - -###### 77. Is this a pure function? - -```javascript -function sum(a, b) { - return a + b; -} -``` - -- A: Yes -- B: No - -
Odpowiedź -

- -#### Odpowiedź: A - -A pure function is a function that _always_ returns the same result, if the same arguments are passed. - -The `sum` function always returns the same result. If we pass `1` and `2`, it will _always_ return `3` without side effects. If we pass `5` and `10`, it will _always_ return `15`, and so on. This is the definition of a pure function. - -

-
- ---- - -###### 78. What is the output? - -```javascript -const add = () => { - const cache = {}; - return num => { - if (num in cache) { - return `From cache! ${cache[num]}`; - } else { - const result = num + 10; - cache[num] = result; - return `Calculated! ${result}`; - } - }; -}; - -const addFunction = add(); -console.log(addFunction(10)); -console.log(addFunction(10)); -console.log(addFunction(5 * 2)); -``` - -- A: `Calculated! 20` `Calculated! 20` `Calculated! 20` -- B: `Calculated! 20` `From cache! 20` `Calculated! 20` -- C: `Calculated! 20` `From cache! 20` `From cache! 20` -- D: `Calculated! 20` `From cache! 20` `Error` - -
Odpowiedź -

- -#### Odpowiedź: C - -The `add` function is a _memoized_ function. With memoization, we can cache the results of a function in order to speed up its execution. In this case, we create a `cache` object that stores the previously returned values. - -If we call the `addFunction` function again with the same argument, it first checks whether it has already gotten that value in its cache. If that's the case, the caches value will be returned, which saves on execution time. Else, if it's not cached, it will calculate the value and store it afterwards. - -We call the `addFunction` function three times with the same value: on the first invocation, the value of the function when `num` is equal to `10` isn't cached yet. The condition of the if-statement `num in cache` returns `false`, and the else block gets executed: `Calculated! 20` gets logged, and the value of the result gets added to the cache object. `cache` now looks like `{ 10: 20 }`. - -The second time, the `cache` object contains the value that gets returned for `10`. The condition of the if-statement `num in cache` returns `true`, and `'From cache! 20'` gets logged. - -The third time, we pass `5 * 2` to the function which gets evaluated to `10`. The `cache` object contains the value that gets returned for `10`. The condition of the if-statement `num in cache` returns `true`, and `'From cache! 20'` gets logged. - -

-
- ---- - -###### 79. What is the output? - -```javascript -const myLifeSummedUp = ['☕', '💻', '🍷', '🍫']; - -for (let item in myLifeSummedUp) { - console.log(item); -} - -for (let item of myLifeSummedUp) { - console.log(item); -} -``` - -- A: `0` `1` `2` `3` and `"☕"` `"💻"` `"🍷"` `"🍫"` -- B: `"☕"` `"💻"` `"🍷"` `"🍫"` and `"☕"` `"💻"` `"🍷"` `"🍫"` -- C: `"☕"` `"💻"` `"🍷"` `"🍫"` and `0` `1` `2` `3` -- D: `0` `1` `2` `3` and `{0: "☕", 1: "💻", 2: "🍷", 3: "🍫"}` - -
Odpowiedź -

- -#### Odpowiedź: A - -With a _for-in_ loop, we can iterate over **enumerable** properties. In an array, the enumerable properties are the "keys" of array elements, which are actually their indexes. You could see an array as: - -`{0: "☕", 1: "💻", 2: "🍷", 3: "🍫"}` - -Where the keys are the enumerable properties. `0` `1` `2` `3` get logged. - -With a _for-of_ loop, we can iterate over **iterables**. An array is an iterable. When we iterate over the array, the variable "item" is equal to the element it's currently iterating over, `"☕"` `"💻"` `"🍷"` `"🍫"` get logged. - -

-
- ---- - -###### 80. What is the output? - -```javascript -const list = [1 + 2, 1 * 2, 1 / 2]; -console.log(list); -``` - -- A: `["1 + 2", "1 * 2", "1 / 2"]` -- B: `["12", 2, 0.5]` -- C: `[3, 2, 0.5]` -- D: `[1, 1, 1]` - -
Odpowiedź -

- -#### Odpowiedź: C - -Array elements can hold any value. Numbers, strings, objects, other arrays, null, boolean values, undefined, and other expressions such as dates, functions, and calculations. - -The element will be equal to the returned value. `1 + 2` returns `3`, `1 * 2` returns `2`, and `1 / 2` returns `0.5`. - -

-
- ---- - -###### 81. What is the output? - -```javascript -function sayHi(name) { - return `Hi there, ${name}`; -} - -console.log(sayHi()); -``` - -- A: `Hi there,` -- B: `Hi there, undefined` -- C: `Hi there, null` -- D: `ReferenceError` - -
Odpowiedź -

- -#### Odpowiedź: B - -By default, arguments have the value of `undefined`, unless a value has been passed to the function. In this case, we didn't pass a value for the `name` argument. `name` is equal to `undefined` which gets logged. - -In ES6, we can overwrite this default `undefined` value with default parameters. For example: - -`function sayHi(name = "Lydia") { ... }` - -In this case, if we didn't pass a value or if we passed `undefined`, `name` would always be equal to the string `Lydia` - -

-
- ---- - -###### 82. What is the output? - -```javascript -var status = '😎'; - -setTimeout(() => { - const status = '😍'; - - const data = { - status: '🥑', - getStatus() { - return this.status; - }, - }; - - console.log(data.getStatus()); - console.log(data.getStatus.call(this)); -}, 0); -``` - -- A: `"🥑"` and `"😍"` -- B: `"🥑"` and `"😎"` -- C: `"😍"` and `"😎"` -- D: `"😎"` and `"😎"` - -
Odpowiedź -

- -#### Odpowiedź: B - -The value of the `this` keyword is dependent on where you use it. In a **method**, like the `getStatus` method, the `this` keyword refers to _the object that the method belongs to_. The method belongs to the `data` object, so `this` refers to the `data` object. When we log `this.status`, the `status` property on the `data` object gets logged, which is `"🥑"`. - -With the `call` method, we can change the object to which the `this` keyword refers. In **functions**, the `this` keyword refers to the _the object that the function belongs to_. We declared the `setTimeout` function on the _global object_, so within the `setTimeout` function, the `this` keyword refers to the _global object_. On the global object, there is a variable called _status_ with the value of `"😎"`. When logging `this.status`, `"😎"` gets logged. - -

-
- ---- - -###### 83. What is the output? - -```javascript -const person = { - name: 'Lydia', - age: 21, -}; - -let city = person.city; -city = 'Amsterdam'; - -console.log(person); -``` - -- A: `{ name: "Lydia", age: 21 }` -- B: `{ name: "Lydia", age: 21, city: "Amsterdam" }` -- C: `{ name: "Lydia", age: 21, city: undefined }` -- D: `"Amsterdam"` - -
Odpowiedź -

- -#### Odpowiedź: A - -We set the variable `city` equal to the value of the property called `city` on the `person` object. There is no property on this object called `city`, so the variable `city` has the value of `undefined`. - -Note that we are _not_ referencing the `person` object itself! We simply set the variable `city` equal to the current value of the `city` property on the `person` object. - -Then, we set `city` equal to the string `"Amsterdam"`. This doesn't change the person object: there is no reference to that object. - -When logging the `person` object, the unmodified object gets returned. - -

-
- ---- - -###### 84. What is the output? - -```javascript -function checkAge(age) { - if (age < 18) { - const message = "Sorry, you're too young."; - } else { - const message = "Yay! You're old enough!"; - } - - return message; -} - -console.log(checkAge(21)); -``` - -- A: `"Sorry, you're too young."` -- B: `"Yay! You're old enough!"` -- C: `ReferenceError` -- D: `undefined` - -
Odpowiedź -

- -#### Odpowiedź: C - -Variables with the `const` and `let` keyword are _block-scoped_. A block is anything between curly brackets (`{ }`). In this case, the curly brackets of the if/else statements. You cannot reference a variable outside of the block it's declared in, a ReferenceError gets thrown. - -

-
- ---- - -###### 85. What kind of information would get logged? - -```javascript -fetch('https://www.website.com/api/user/1') - .then(res => res.json()) - .then(res => console.log(res)); -``` - -- A: The result of the `fetch` method. -- B: The result of the second invocation of the `fetch` method. -- C: The result of the callback in the previous `.then()`. -- D: It would always be undefined. - -
Odpowiedź -

- -#### Odpowiedź: C - -The value of `res` in the second `.then` is equal to the returned value of the previous `.then`. You can keep chaining `.then`s like this, where the value is passed to the next handler. - -

-
- ---- - -###### 86. Which option is a way to set `hasName` equal to `true`, provided you cannot pass `true` as an argument? - -```javascript -function getName(name) { - const hasName = // -} -``` - -- A: `!!name` -- B: `name` -- C: `new Boolean(name)` -- D: `name.length` - -
Odpowiedź -

- -#### Odpowiedź: A - -With `!!name`, we determine whether the value of `name` is truthy or falsy. If name is truthy, which we want to test for, `!name` returns `false`. `!false` (which is what `!!name` practically is) returns `true`. - -By setting `hasName` equal to `name`, you set `hasName` equal to whatever value you passed to the `getName` function, not the boolean value `true`. - -`new Boolean(true)` returns an object wrapper, not the boolean value itself. - -`name.length` returns the length of the passed argument, not whether it's `true`. - -

-
- ---- - -###### 87. Jaki jest wynik? - -```javascript -console.log('I want pizza'[0]); -``` - -- A: `"""` -- B: `"I"` -- C: `SyntaxError` -- D: `undefined` - -
Odpowiedź -

- -#### Odpowiedź: B - -In order to get a character at a specific index of a string, you can use bracket notation. The first character in the string has index 0, and so on. In this case, we want to get the element with index 0, the character `"I'`, which gets logged. - -Note that this method is not supported in IE7 and below. In that case, use `.charAt()`. - -

-
- ---- - -###### 88. Jaki jest wynik? - -```javascript -function sum(num1, num2 = num1) { - console.log(num1 + num2); -} - -sum(10); -``` - -- A: `NaN` -- B: `20` -- C: `ReferenceError` -- D: `undefined` - -
Odpowiedź -

- -#### Odpowiedź: B - -You can set a default parameter's value equal to another parameter of the function, as long as they've been defined _before_ the default parameter. We pass the value `10` to the `sum` function. If the `sum` function only receives 1 argument, it means that the value for `num2` is not passed, and the value of `num1` is equal to the passed value `10` in this case. The default value of `num2` is the value of `num1`, which is `10`. `num1 + num2` returns `20`. - -If you're trying to set a default parameter's value equal to a parameter which is defined _after_ (to the right), the parameter's value hasn't been initialized yet, which will throw an error. - -

-
- ---- - -###### 89. Jaki jest wynik? - -```javascript -// module.js -export default () => 'Hello world'; -export const name = 'Lydia'; - -// index.js -import * as data from './module'; - -console.log(data); -``` - -- A: `{ default: function default(), name: "Lydia" }` -- B: `{ default: function default() }` -- C: `{ default: "Hello world", name: "Lydia" }` -- D: Global object of `module.js` - -
Odpowiedź -

- -#### Odpowiedź: A - -With the `import * as name` syntax, we import _all exports_ from the `module.js` file into the `index.js` file as a new object called `data` is created. In the `module.js` file, there are two exports: the default export, and a named export. The default export is a function which returns the string `"Hello World"`, and the named export is a variable called `name` which has the value of the string `"Lydia"`. - -The `data` object has a `default` property for the default export, other properties have the names of the named exports and their corresponding values. - -

-
- ---- - -###### 90. Jaki jest wynik? - -```javascript -class Person { - constructor(name) { - this.name = name; - } -} - -const member = new Person('John'); -console.log(typeof member); -``` - -- A: `"class"` -- B: `"function"` -- C: `"object"` -- D: `"string"` - -
Odpowiedź -

- -#### Odpowiedź: C - -Classes are syntactical sugar for function constructors. The equivalent of the `Person` class as a function constructor would be: - -```javascript -function Person(name) { - this.name = name; -} -``` - -Calling a function constructor with `new` results in the creation of an instance of `Person`, `typeof` keyword returns `"object"` for an instance. `typeof member` returns `"object"`. - -

-
- ---- - -###### 91. Jaki jest wynik? - -```javascript -let newList = [1, 2, 3].push(4); - -console.log(newList.push(5)); -``` - -- A: `[1, 2, 3, 4, 5]` -- B: `[1, 2, 3, 5]` -- C: `[1, 2, 3, 4]` -- D: `Error` - -
Odpowiedź -

- -#### Odpowiedź: D - -The `.push` method returns the _new length_ of the array, not the array itself! By setting `newList` equal to `[1, 2, 3].push(4)`, we set `newList` equal to the new length of the array: `4`. - -Then, we try to use the `.push` method on `newList`. Since `newList` is the numerical value `4`, we cannot use the `.push` method: a TypeError is thrown. - -

-
- ---- - -###### 92. Jaki jest wynik? - -```javascript -function giveLydiaPizza() { - return 'Here is pizza!'; -} - -const giveLydiaChocolate = () => - "Here's chocolate... now go hit the gym already."; - -console.log(giveLydiaPizza.prototype); -console.log(giveLydiaChocolate.prototype); -``` - -- A: `{ constructor: ...}` `{ constructor: ...}` -- B: `{}` `{ constructor: ...}` -- C: `{ constructor: ...}` `{}` -- D: `{ constructor: ...}` `undefined` - -
Odpowiedź -

- -#### Odpowiedź: D - -Regular functions, such as the `giveLydiaPizza` function, have a `prototype` property, which is an object (prototype object) with a `constructor` property. Arrow functions however, such as the `giveLydiaChocolate` function, do not have this `prototype` property. `undefined` gets returned when trying to access the `prototype` property using `giveLydiaChocolate.prototype`. - -

-
- ---- - -###### 93. Jaki jest wynik? - -```javascript -const person = { - name: 'Lydia', - age: 21, -}; - -for (const [x, y] of Object.entries(person)) { - console.log(x, y); -} -``` - -- A: `name` `Lydia` and `age` `21` -- B: `["name", "Lydia"]` and `["age", 21]` -- C: `["name", "age"]` and `undefined` -- D: `Error` - -
Odpowiedź -

- -#### Odpowiedź: A - -`Object.entries(person)` returns an array of nested arrays, containing the keys and objects: - -`[ [ 'name', 'Lydia' ], [ 'age', 21 ] ]` - -Using the `for-of` loop, we can iterate over each element in the array, the subarrays in this case. We can destructure the subarrays instantly in the for-of loop, using `const [x, y]`. `x` is equal to the first element in the subarray, `y` is equal to the second element in the subarray. - -The first subarray is `[ "name", "Lydia" ]`, with `x` equal to `"name"`, and `y` equal to `"Lydia"`, which get logged. -The second subarray is `[ "age", 21 ]`, with `x` equal to `"age"`, and `y` equal to `21`, which get logged. - -

-
- ---- - -###### 94. Jaki jest wynik? - -```javascript -function getItems(fruitList, ...args, favoriteFruit) { - return [...fruitList, ...args, favoriteFruit] -} - -getItems(["banana", "apple"], "pear", "orange") -``` - -- A: `["banana", "apple", "pear", "orange"]` -- B: `[["banana", "apple"], "pear", "orange"]` -- C: `["banana", "apple", ["pear"], "orange"]` -- D: `SyntaxError` - -
Odpowiedź -

- -#### Odpowiedź: D - -`...args` is a rest parameter. The rest parameter's value is an array containing all remaining arguments, **and can only be the last parameter**! In this example, the rest parameter was the second parameter. This is not possible, and will throw a syntax error. - -```javascript -function getItems(fruitList, favoriteFruit, ...args) { - return [...fruitList, ...args, favoriteFruit]; -} - -getItems(['banana', 'apple'], 'pear', 'orange'); -``` - -The above example works. This returns the array `[ 'banana', 'apple', 'orange', 'pear' ]` - -

-
- ---- - -###### 95. Jaki jest wynik? - -```javascript -function nums(a, b) { - if (a > b) console.log('a is bigger'); - else console.log('b is bigger'); - return - a + b; -} - -console.log(nums(4, 2)); -console.log(nums(1, 2)); -``` - -- A: `a is bigger`, `6` and `b is bigger`, `3` -- B: `a is bigger`, `undefined` and `b is bigger`, `undefined` -- C: `undefined` and `undefined` -- D: `SyntaxError` - -
Odpowiedź -

- -#### Odpowiedź: B - -In JavaScript, we don't _have_ to write the semicolon (`;`) explicitly, however the JavaScript engine still adds them after statements. This is called **Automatic Semicolon Insertion**. A statement can for example be variables, or keywords like `throw`, `return`, `break`, etc. - -Here, we wrote a `return` statement, and another value `a + b` on a _new line_. However, since it's a new line, the engine doesn't know that it's actually the value that we wanted to return. Instead, it automatically added a semicolon after `return`. You could see this as: - -```javascript -return; -a + b; -``` - -This means that `a + b` is never reached, since a function stops running after the `return` keyword. If no value gets returned, like here, the function returns `undefined`. Note that there is no automatic insertion after `if/else` statements! - -

-
- ---- - -###### 96. Jaki jest wynik? - -```javascript -class Person { - constructor() { - this.name = 'Lydia'; - } -} - -Person = class AnotherPerson { - constructor() { - this.name = 'Sarah'; - } -}; - -const member = new Person(); -console.log(member.name); -``` - -- A: `"Lydia"` -- B: `"Sarah"` -- C: `Error: cannot redeclare Person` -- D: `SyntaxError` - -
Odpowiedź -

- -#### Odpowiedź: B - -We can set classes equal to other classes/function constructors. In this case, we set `Person` equal to `AnotherPerson`. The name on this constructor is `Sarah`, so the name property on the new `Person` instance `member` is `"Sarah"`. - -

-
- ---- - -###### 97. Jaki jest wynik? - -```javascript -const info = { - [Symbol('a')]: 'b', -}; - -console.log(info); -console.log(Object.keys(info)); -``` - -- A: `{Symbol('a'): 'b'}` and `["{Symbol('a')"]` -- B: `{}` and `[]` -- C: `{ a: "b" }` and `["a"]` -- D: `{Symbol('a'): 'b'}` and `[]` - -
Odpowiedź -

- -#### Odpowiedź: D - -A Symbol is not _enumerable_. The Object.keys method returns all _enumerable_ key properties on an object. The Symbol won't be visible, and an empty array is returned. When logging the entire object, all properties will be visible, even non-enumerable ones. - -This is one of the many qualities of a symbol: besides representing an entirely unique value (which prevents accidental name collision on objects, for example when working with 2 libraries that want to add properties to the same object), you can also "hide" properties on objects this way (although not entirely. You can still access symbols using the `Object.getOwnPropertySymbols()` method). - -

-
- ---- - -###### 98. Jaki jest wynik? - -```javascript -const getList = ([x, ...y]) => [x, y] -const getUser = user => { name: user.name, age: user.age } - -const list = [1, 2, 3, 4] -const user = { name: "Lydia", age: 21 } - -console.log(getList(list)) -console.log(getUser(user)) -``` - -- A: `[1, [2, 3, 4]]` and `SyntaxError` -- B: `[1, [2, 3, 4]]` and `{ name: "Lydia", age: 21 }` -- C: `[1, 2, 3, 4]` and `{ name: "Lydia", age: 21 }` -- D: `Error` and `{ name: "Lydia", age: 21 }` - -
Odpowiedź -

- -#### Odpowiedź: A - -The `getList` function receives an array as its argument. Between the parentheses of the `getList` function, we destructure this array right away. You could see this as: - -`[x, ...y] = [1, 2, 3, 4]` - -With the rest parameter `...y`, we put all "remaining" arguments in an array. The remaining arguments are `2`, `3` and `4` in this case. The value of `y` is an array, containing all the rest parameters. The value of `x` is equal to `1` in this case, so when we log `[x, y]`, `[1, [2, 3, 4]]` gets logged. - -The `getUser` function receives an object. With arrow functions, we don't _have_ to write curly brackets if we just return one value. However, if you want to instantly return an _object_ from an arrow function, you have to write it between parentheses, otherwise everything between the two braces will be interpreted as a block statement. In this case the code between the braces is not a valid JavaScript code, so a `SyntaxError` gets thrown. - -The following function would have returned an object: - -`const getUser = user => ({ name: user.name, age: user.age })` - -

-
- ---- - -###### 99. Jaki jest wynik? - -```javascript -const name = 'Lydia'; - -console.log(name()); -``` - -- A: `SyntaxError` -- B: `ReferenceError` -- C: `TypeError` -- D: `undefined` - -
Odpowiedź -

- -#### Odpowiedź: C - -The variable `name` holds the value of a string, which is not a function, thus cannot invoke. - -TypeErrors get thrown when a value is not of the expected type. JavaScript expected `name` to be a function since we're trying to invoke it. It was a string however, so a TypeError gets thrown: name is not a function! - -SyntaxErrors get thrown when you've written something that isn't valid JavaScript, for example when you've written the word `return` as `retrun`. -ReferenceErrors get thrown when JavaScript isn't able to find a reference to a value that you're trying to access. - -

-
- ---- - -###### 100. What's the value of output? - -```javascript -// 🎉✨ This is my 100th question! ✨🎉 - -const output = `${[] && 'Im'}possible! -You should${'' && `n't`} see a therapist after so much JavaScript lol`; -``` - -- A: `possible! You should see a therapist after so much JavaScript lol` -- B: `Impossible! You should see a therapist after so much JavaScript lol` -- C: `possible! You shouldn't see a therapist after so much JavaScript lol` -- D: `Impossible! You shouldn't see a therapist after so much JavaScript lol` - -
Odpowiedź -

- -#### Odpowiedź: B - -`[]` is a truthy value. With the `&&` operator, the right-hand value will be returned if the left-hand value is a truthy value. In this case, the left-hand value `[]` is a truthy value, so `"Im'` gets returned. - -`""` is a falsy value. If the left-hand value is falsy, nothing gets returned. `n't` doesn't get returned. - -

-
- ---- - -###### 101. What's the value of output? - -```javascript -const one = false || {} || null; -const two = null || false || ''; -const three = [] || 0 || true; - -console.log(one, two, three); -``` - -- A: `false` `null` `[]` -- B: `null` `""` `true` -- C: `{}` `""` `[]` -- D: `null` `null` `true` - -
Odpowiedź -

- -#### Odpowiedź: C - -With the `||` operator, we can return the first truthy operand. If all values are falsy, the last operand gets returned. - -`(false || {} || null)`: the empty object `{}` is a truthy value. This is the first (and only) truthy value, which gets returned. `one` is equal to `{}`. - -`(null || false || "")`: all operands are falsy values. This means that the last operand, `""` gets returned. `two` is equal to `""`. - -`([] || 0 || "")`: the empty array`[]` is a truthy value. This is the first truthy value, which gets returned. `three` is equal to `[]`. - -

-
- ---- - -###### 102. What's the value of output? - -```javascript -const myPromise = () => Promise.resolve('I have resolved!'); - -function firstFunction() { - myPromise().then(res => console.log(res)); - console.log('second'); -} - -async function secondFunction() { - console.log(await myPromise()); - console.log('second'); -} - -firstFunction(); -secondFunction(); -``` - -- A: `I have resolved!`, `second` and `I have resolved!`, `second` -- B: `second`, `I have resolved!` and `second`, `I have resolved!` -- C: `I have resolved!`, `second` and `second`, `I have resolved!` -- D: `second`, `I have resolved!` and `I have resolved!`, `second` - -
Odpowiedź -

- -#### Odpowiedź: D - -With a promise, we basically say _I want to execute this function, but I'll put it aside for now while it's running since this might take a while. Only when a certain value is resolved (or rejected), and when the call stack is empty, I want to use this value._ - -We can get this value with both `.then` and the `await` keyword in an `async` function. Although we can get a promise's value with both `.then` and `await`, they work a bit differently. - -In the `firstFunction`, we (sort of) put the myPromise function aside while it was running, but continued running the other code, which is `console.log('second')` in this case. Then, the function resolved with the string `I have resolved`, which then got logged after it saw that the callstack was empty. - -With the await keyword in `secondFunction`, we literally pause the execution of an async function until the value has been resolved before moving to the next line. - -This means that it waited for the `myPromise` to resolve with the value `I have resolved`, and only once that happened, we moved to the next line: `second` got logged. - -

-
- ---- - -###### 103. What's the value of output? - -```javascript -const set = new Set(); - -set.add(1); -set.add('Lydia'); -set.add({ name: 'Lydia' }); - -for (let item of set) { - console.log(item + 2); -} -``` - -- A: `3`, `NaN`, `NaN` -- B: `3`, `7`, `NaN` -- C: `3`, `Lydia2`, `[object Object]2` -- D: `"12"`, `Lydia2`, `[object Object]2` - -
Odpowiedź -

- -#### Odpowiedź: C - -The `+` operator is not only used for adding numerical values, but we can also use it to concatenate strings. Whenever the JavaScript engine sees that one or more values are not a number, it coerces the number into a string. - -The first one is `1`, which is a numerical value. `1 + 2` returns the number 3. - -However, the second one is a string `"Lydia"`. `"Lydia"` is a string and `2` is a number: `2` gets coerced into a string. `"Lydia"` and `"2"` get concatenated, which results in the string `"Lydia2"`. - -`{ name: "Lydia" }` is an object. Neither a number nor an object is a string, so it stringifies both. Whenever we stringify a regular object, it becomes `"[object Object]"`. `"[object Object]"` concatenated with `"2"` becomes `"[object Object]2"`. - -

-
- ---- - -###### 104. What's its value? - -```javascript -Promise.resolve(5); -``` - -- A: `5` -- B: `Promise {: 5}` -- C: `Promise {: 5}` -- D: `Error` - -
Odpowiedź -

- -#### Odpowiedź: C - -We can pass any type of value we want to `Promise.resolve`, either a promise or a non-promise. The method itself returns a promise with the resolved value (``). If you pass a regular function, it'll be a resolved promise with a regular value. If you pass a promise, it'll be a resolved promise with the resolved value of that passed promise. - -In this case, we just passed the numerical value `5`. It returns a resolved promise with the value `5`. - -

-
- ---- - -###### 105. What's its value? - -```javascript -function compareMembers(person1, person2 = person) { - if (person1 !== person2) { - console.log('Not the same!'); - } else { - console.log('They are the same!'); - } -} - -const person = { name: 'Lydia' }; - -compareMembers(person); -``` - -- A: `Not the same!` -- B: `They are the same!` -- C: `ReferenceError` -- D: `SyntaxError` - -
Odpowiedź -

- -#### Odpowiedź: B - -Objects are passed by reference. When we check objects for strict equality (`===`), we're comparing their references. - -We set the default value for `person2` equal to the `person` object, and passed the `person` object as the value for `person1`. - -This means that both values have a reference to the same spot in memory, thus they are equal. - -The code block in the `else` statement gets run, and `They are the same!` gets logged. - -

-
- ---- - -###### 106. What's its value? - -```javascript -const colorConfig = { - red: true, - blue: false, - green: true, - black: true, - yellow: false, -}; - -const colors = ['pink', 'red', 'blue']; - -console.log(colorConfig.colors[1]); -``` - -- A: `true` -- B: `false` -- C: `undefined` -- D: `TypeError` - -
Odpowiedź -

- -#### Odpowiedź: D - -In JavaScript, we have two ways to access properties on an object: bracket notation, or dot notation. In this example, we use dot notation (`colorConfig.colors`) instead of bracket notation (`colorConfig["colors"]`). - -With dot notation, JavaScript tries to find the property on the object with that exact name. In this example, JavaScript tries to find a property called `colors` on the `colorConfig` object. There is no property called `colors`, so this returns `undefined`. Then, we try to access the value of the first element by using `[1]`. We cannot do this on a value that's `undefined`, so it throws a `TypeError`: `Cannot read property '1' of undefined`. - -JavaScript interprets (or unboxes) statements. When we use bracket notation, it sees the first opening bracket `[` and keeps going until it finds the closing bracket `]`. Only then, it will evaluate the statement. If we would've used `colorConfig[colors[1]]`, it would have returned the value of the `red` property on the `colorConfig` object. - -

-
- ---- - -###### 107. What's its value? - -```javascript -console.log('❤️' === '❤️'); -``` - -- A: `true` -- B: `false` - -
Odpowiedź -

- -#### Odpowiedź: A - -Under the hood, emojis are unicodes. The unicodes for the heart emoji is `"U+2764 U+FE0F"`. These are always the same for the same emojis, so we're comparing two equal strings to each other, which returns true. - -

-
- ---- - -###### 108. Which of these methods modifies the original array? - -```javascript -const emojis = ['✨', '🥑', '😍']; - -emojis.map(x => x + '✨'); -emojis.filter(x => x !== '🥑'); -emojis.find(x => x !== '🥑'); -emojis.reduce((acc, cur) => acc + '✨'); -emojis.slice(1, 2, '✨'); -emojis.splice(1, 2, '✨'); -``` - -- A: `All of them` -- B: `map` `reduce` `slice` `splice` -- C: `map` `slice` `splice` -- D: `splice` - -
Odpowiedź -

- -#### Odpowiedź: D - -With `splice` method, we modify the original array by deleting, replacing or adding elements. In this case, we removed 2 items from index 1 (we removed `'🥑'` and `'😍'`) and added the ✨ emoji instead. - -`map`, `filter` and `slice` return a new array, `find` returns an element, and `reduce` returns a reduced value. - -

-
- ---- - -###### 109. Jaki jest wynik? - -```javascript -const food = ['🍕', '🍫', '🥑', '🍔']; -const info = { favoriteFood: food[0] }; - -info.favoriteFood = '🍝'; - -console.log(food); -``` - -- A: `['🍕', '🍫', '🥑', '🍔']` -- B: `['🍝', '🍫', '🥑', '🍔']` -- C: `['🍝', '🍕', '🍫', '🥑', '🍔']` -- D: `ReferenceError` - -
Odpowiedź -

- -#### Odpowiedź: A - -We set the value of the `favoriteFood` property on the `info` object equal to the string with the pizza emoji, `'🍕'`. A string is a primitive data type. In JavaScript, primitive data types don't interact by reference. - -In JavaScript, primitive data types (everything that's not an object) interact by _value_. In this case, we set the value of the `favoriteFood` property on the `info` object equal to the value of the first element in the `food` array, the string with the pizza emoji in this case (`'🍕'`). A string is a primitive data type, and interact by value (see my [blogpost](https://www.theavocoder.com/complete-javascript/2018/12/21/by-value-vs-by-reference) if you're interested in learning more) - -Then, we change the value of the `favoriteFood` property on the `info` object. The `food` array hasn't changed, since the value of `favoriteFood` was merely a _copy_ of the value of the first element in the array, and doesn't have a reference to the same spot in memory as the element on `food[0]`. When we log food, it's still the original array, `['🍕', '🍫', '🥑', '🍔']`. - -

-
- ---- - -###### 110. What does this method do? - -```javascript -JSON.parse(); -``` - -- A: Parses JSON to a JavaScript value -- B: Parses a JavaScript object to JSON -- C: Parses any JavaScript value to JSON -- D: Parses JSON to a JavaScript object only - -
Odpowiedź -

- -#### Odpowiedź: A - -With the `JSON.parse()` method, we can parse JSON string to a JavaScript value. - -```javascript -// Stringifying a number into valid JSON, then parsing the JSON string to a JavaScript value: -const jsonNumber = JSON.stringify(4); // '4' -JSON.parse(jsonNumber); // 4 - -// Stringifying an array value into valid JSON, then parsing the JSON string to a JavaScript value: -const jsonArray = JSON.stringify([1, 2, 3]); // '[1, 2, 3]' -JSON.parse(jsonArray); // [1, 2, 3] - -// Stringifying an object into valid JSON, then parsing the JSON string to a JavaScript value: -const jsonArray = JSON.stringify({ name: 'Lydia' }); // '{"name":"Lydia"}' -JSON.parse(jsonArray); // { name: 'Lydia' } -``` - -

-
- ---- - -###### 111. Jaki jest wynik? - -```javascript -let name = 'Lydia'; - -function getName() { - console.log(name); - let name = 'Sarah'; -} - -getName(); -``` - -- A: Lydia -- B: Sarah -- C: `undefined` -- D: `ReferenceError` - -
Odpowiedź -

- -#### Odpowiedź: D - -Each function has its own _execution context_ (or _scope_). The `getName` function first looks within its own context (scope) to see if it contains the variable `name` we're trying to access. In this case, the `getName` function contains its own `name` variable: we declare the variable `name` with the `let` keyword, and with the value of `'Sarah'`. - -Variables with the `let` keyword (and `const`) are hoisted, but unlike `var`, don't get initialized. They are not accessible before the line we declare (initialize) them. This is called the "temporal dead zone". When we try to access the variables before they are declared, JavaScript throws a `ReferenceError`. - -If we wouldn't have declared the `name` variable within the `getName` function, the javascript engine would've looked down the _scope chain_. The outer scope has a variable called `name` with the value of `Lydia`. In that case, it would've logged `Lydia`. - -```javascript -let name = 'Lydia'; - -function getName() { - console.log(name); -} - -getName(); // Lydia -``` - -

-
- ---- - -###### 112. Jaki jest wynik? - -```javascript -function* generatorOne() { - yield ['a', 'b', 'c']; -} - -function* generatorTwo() { - yield* ['a', 'b', 'c']; -} - -const one = generatorOne(); -const two = generatorTwo(); - -console.log(one.next().value); -console.log(two.next().value); -``` - -- A: `a` and `a` -- B: `a` and `undefined` -- C: `['a', 'b', 'c']` and `a` -- D: `a` and `['a', 'b', 'c']` - -
Odpowiedź -

- -#### Odpowiedź: C - -With the `yield` keyword, we `yield` values in a generator function. With the `yield*` keyword, we can yield values from another generator function, or iterable object (for example an array). - -In `generatorOne`, we yield the entire array `['a', 'b', 'c']` using the `yield` keyword. The value of `value` property on the object returned by the `next` method on `one` (`one.next().value`) is equal to the entire array `['a', 'b', 'c']`. - -```javascript -console.log(one.next().value); // ['a', 'b', 'c'] -console.log(one.next().value); // undefined -``` - -In `generatorTwo`, we use the `yield*` keyword. This means that the first yielded value of `two`, is equal to the first yielded value in the iterator. The iterator is the array `['a', 'b', 'c']`. The first yielded value is `a`, so the first time we call `two.next().value`, `a` is returned. - -```javascript -console.log(two.next().value); // 'a' -console.log(two.next().value); // 'b' -console.log(two.next().value); // 'c' -console.log(two.next().value); // undefined -``` - -

-
- ---- - -###### 113. Jaki jest wynik? - -```javascript -console.log(`${(x => x)('I love')} to program`); -``` - -- A: `I love to program` -- B: `undefined to program` -- C: `${(x => x)('I love') to program` -- D: `TypeError` - -
Odpowiedź -

- -#### Odpowiedź: A - -Expressions within template literals are evaluated first. This means that the string will contain the returned value of the expression, the immediately invoked function `(x => x)('I love')` in this case. We pass the value `'I love'` as an argument to the `x => x` arrow function. `x` is equal to `'I love'`, which gets returned. This results in `I love to program`. - -

-
- ---- - -###### 114. What will happen? - -```javascript -let config = { - alert: setInterval(() => { - console.log('Alert!'); - }, 1000), -}; - -config = null; -``` - -- A: The `setInterval` callback won't be invoked -- B: The `setInterval` callback gets invoked once -- C: The `setInterval` callback will still be called every second -- D: We never invoked `config.alert()`, config is `null` - -
Odpowiedź -

- -#### Odpowiedź: C - -Normally when we set objects equal to `null`, those objects get _garbage collected_ as there is no reference anymore to that object. However, since the callback function within `setInterval` is an arrow function (thus bound to the `config` object), the callback function still holds a reference to the `config` object. -As long as there is a reference, the object won't get garbage collected. -Since this is an interval, setting `config` to `null` or `delete`-ing `config.alert` won't garbage-collect the interval, so the interval will still be called. -It should be cleared with `clearInterval(config.alert)` to remove it from memory. -Since it was not cleared, the `setInterval` callback function will still get invoked every 1000ms (1s). - -

-
- ---- - -###### 115. Which method(s) will return the value `'Hello world!'`? - -```javascript -const myMap = new Map(); -const myFunc = () => 'greeting'; - -myMap.set(myFunc, 'Hello world!'); - -//1 -myMap.get('greeting'); -//2 -myMap.get(myFunc); -//3 -myMap.get(() => 'greeting'); -``` - -- A: 1 -- B: 2 -- C: 2 and 3 -- D: All of them - -
Odpowiedź -

- -#### Odpowiedź: B - -When adding a key/value pair using the `set` method, the key will be the value of the first argument passed to the `set` function, and the value will be the second argument passed to the `set` function. The key is the _function_ `() => 'greeting'` in this case, and the value `'Hello world'`. `myMap` is now `{ () => 'greeting' => 'Hello world!' }`. - -1 is wrong, since the key is not `'greeting'` but `() => 'greeting'`. -3 is wrong, since we're creating a new function by passing it as a parameter to the `get` method. Object interact by _reference_. Functions are objects, which is why two functions are never strictly equal, even if they are identical: they have a reference to a different spot in memory. - -

-
- ---- - -###### 116. Jaki jest wynik? - -```javascript -const person = { - name: 'Lydia', - age: 21, -}; - -const changeAge = (x = { ...person }) => (x.age += 1); -const changeAgeAndName = (x = { ...person }) => { - x.age += 1; - x.name = 'Sarah'; -}; - -changeAge(person); -changeAgeAndName(); - -console.log(person); -``` - -- A: `{name: "Sarah", age: 22}` -- B: `{name: "Sarah", age: 23}` -- C: `{name: "Lydia", age: 22}` -- D: `{name: "Lydia", age: 23}` - -
Odpowiedź -

- -#### Odpowiedź: C - -Both the `changeAge` and `changeAgeAndName` functions have a default parameter, namely a _newly_ created object `{ ...person }`. This object has copies of all the key/values in the `person` object. - -First, we invoke the `changeAge` function and pass the `person` object as its argument. This function increases the value of the `age` property by 1. `person` is now `{ name: "Lydia", age: 22 }`. - -Then, we invoke the `changeAgeAndName` function, however we don't pass a parameter. Instead, the value of `x` is equal to a _new_ object: `{ ...person }`. Since it's a new object, it doesn't affect the values of the properties on the `person` object. `person` is still equal to `{ name: "Lydia", age: 22 }`. - -

-
- ---- - -###### 117. Which of the following options will return `6`? - -```javascript -function sumValues(x, y, z) { - return x + y + z; -} -``` - -- A: `sumValues([...1, 2, 3])` -- B: `sumValues([...[1, 2, 3]])` -- C: `sumValues(...[1, 2, 3])` -- D: `sumValues([1, 2, 3])` - -
Odpowiedź -

- -#### Odpowiedź: C - -With the spread operator `...`, we can _spread_ iterables to individual elements. The `sumValues` function receives three arguments: `x`, `y` and `z`. `...[1, 2, 3]` will result in `1, 2, 3`, which we pass to the `sumValues` function. - -

-
- ---- - -###### 118. Jaki jest wynik? - -```javascript -let num = 1; -const list = ['🥳', '🤠', '🥰', '🤪']; - -console.log(list[(num += 1)]); -``` - -- A: `🤠` -- B: `🥰` -- C: `SyntaxError` -- D: `ReferenceError` - -
Odpowiedź -

- -#### Odpowiedź: B - -With the `+=` operand, we're incrementing the value of `num` by `1`. `num` had the initial value `1`, so `1 + 1` is `2`. The item on the second index in the `list` array is 🥰, `console.log(list[2])` prints 🥰. - -

-
- ---- - -###### 119. Jaki jest wynik? - -```javascript -const person = { - firstName: 'Lydia', - lastName: 'Hallie', - pet: { - name: 'Mara', - breed: 'Dutch Tulip Hound', - }, - getFullName() { - return `${this.firstName} ${this.lastName}`; - }, -}; - -console.log(person.pet?.name); -console.log(person.pet?.family?.name); -console.log(person.getFullName?.()); -console.log(member.getLastName?.()); -``` - -- A: `undefined` `undefined` `undefined` `undefined` -- B: `Mara` `undefined` `Lydia Hallie` `ReferenceError` -- C: `Mara` `null` `Lydia Hallie` `null` -- D: `null` `ReferenceError` `null` `ReferenceError` - -
Odpowiedź -

- -#### Odpowiedź: B - -With the optional chaining operator `?.`, we no longer have to explicitly check whether the deeper nested values are valid or not. If we're trying to access a property on an `undefined` or `null` value (_nullish_), the expression short-circuits and returns `undefined`. - -`person.pet?.name`: `person` has a property named `pet`: `person.pet` is not nullish. It has a property called `name`, and returns `Mara`. -`person.pet?.family?.name`: `person` has a property named `pet`: `person.pet` is not nullish. `pet` does _not_ have a property called `family`, `person.pet.family` is nullish. The expression returns `undefined`. -`person.getFullName?.()`: `person` has a property named `getFullName`: `person.getFullName()` is not nullish and can get invoked, which returns `Lydia Hallie`. -`member.getLastName?.()`: variable `member` is non existent therefore a `ReferenceError` gets thrown! - -

-
- ---- - -###### 120. Jaki jest wynik? - -```javascript -const groceries = ['banana', 'apple', 'peanuts']; - -if (groceries.indexOf('banana')) { - console.log('We have to buy bananas!'); -} else { - console.log(`We don't have to buy bananas!`); -} -``` - -- A: We have to buy bananas! -- B: We don't have to buy bananas -- C: `undefined` -- D: `1` - -
Odpowiedź -

- -#### Odpowiedź: B - -We passed the condition `groceries.indexOf("banana")` to the if-statement. `groceries.indexOf("banana")` returns `0`, which is a falsy value. Since the condition in the if-statement is falsy, the code in the `else` block runs, and `We don't have to buy bananas!` gets logged. - -

-
- ---- - -###### 121. Jaki jest wynik? - -```javascript -const config = { - languages: [], - set language(lang) { - return this.languages.push(lang); - }, -}; - -console.log(config.language); -``` - -- A: `function language(lang) { this.languages.push(lang }` -- B: `0` -- C: `[]` -- D: `undefined` - -
Odpowiedź -

- -#### Odpowiedź: D - -The `language` method is a `setter`. Setters don't hold an actual value, their purpose is to _modify_ properties. When calling a `setter` method, `undefined` gets returned. - -

-
- ---- - -###### 122. Jaki jest wynik? - -```javascript -const name = 'Lydia Hallie'; - -console.log(!typeof name === 'object'); -console.log(!typeof name === 'string'); -``` - -- A: `false` `true` -- B: `true` `false` -- C: `false` `false` -- D: `true` `true` - -
Odpowiedź -

- -#### Odpowiedź: C - -`typeof name` returns `"string"`. The string `"string"` is a truthy value, so `!typeof name` returns the boolean value `false`. `false === "object"` and `false === "string"` both return`false`. - -(If we wanted to check whether the type was (un)equal to a certain type, we should've written `!==` instead of `!typeof`) - -

-
- ---- - -###### 123. Jaki jest wynik? - -```javascript -const add = x => y => z => { - console.log(x, y, z); - return x + y + z; -}; - -add(4)(5)(6); -``` - -- A: `4` `5` `6` -- B: `6` `5` `4` -- C: `4` `function` `function` -- D: `undefined` `undefined` `6` - -
Odpowiedź -

- -#### Odpowiedź: A - -The `add` function returns an arrow function, which returns an arrow function, which returns an arrow function (still with me?). The first function receives an argument `x` with the value of `4`. We invoke the second function, which receives an argument `y` with the value `5`. Then we invoke the third function, which receives an argument `z` with the value `6`. When we're trying to access the value `x`, `y` and `z` within the last arrow function, the JS engine goes up the scope chain in order to find the values for `x` and `y` accordingly. This returns `4` `5` `6`. - -

-
- ---- - -###### 124. Jaki jest wynik? - -```javascript -async function* range(start, end) { - for (let i = start; i <= end; i++) { - yield Promise.resolve(i); - } -} - -(async () => { - const gen = range(1, 3); - for await (const item of gen) { - console.log(item); - } -})(); -``` - -- A: `Promise {1}` `Promise {2}` `Promise {3}` -- B: `Promise {}` `Promise {}` `Promise {}` -- C: `1` `2` `3` -- D: `undefined` `undefined` `undefined` - -
Odpowiedź -

- -#### Odpowiedź: C - -The generator function `range` returns an async object with promises for each item in the range we pass: `Promise{1}`, `Promise{2}`, `Promise{3}`. We set the variable `gen` equal to the async object, after which we loop over it using a `for await ... of` loop. We set the variable `item` equal to the returned Promise values: first `Promise{1}`, then `Promise{2}`, then `Promise{3}`. Since we're _awaiting_ the value of `item`, the resolved promise, the resolved _values_ of the promises get returned: `1`, `2`, then `3`. - -

-
- ---- - -###### 125. Jaki jest wynik? - -```javascript -const myFunc = ({ x, y, z }) => { - console.log(x, y, z); -}; - -myFunc(1, 2, 3); -``` - -- A: `1` `2` `3` -- B: `{1: 1}` `{2: 2}` `{3: 3}` -- C: `{ 1: undefined }` `undefined` `undefined` -- D: `undefined` `undefined` `undefined` - -
Odpowiedź -

- -#### Odpowiedź: D - -`myFunc` expects an object with properties `x`, `y` and `z` as its argument. Since we're only passing three separate numeric values (1, 2, 3) instead of one object with properties `x`, `y` and `z` ({x: 1, y: 2, z: 3}), `x`, `y` and `z` have their default value of `undefined`. - -

-
- ---- - -###### 126. Jaki jest wynik? - -```javascript -function getFine(speed, amount) { - const formattedSpeed = new Intl.NumberFormat('en-US', { - style: 'unit', - unit: 'mile-per-hour' - }).format(speed); - - const formattedAmount = new Intl.NumberFormat('en-US', { - style: 'currency', - currency: 'USD' - }).format(amount); - - return `The driver drove ${formattedSpeed} and has to pay ${formattedAmount}`; -} - -console.log(getFine(130, 300)) -``` - -- A: The driver drove 130 and has to pay 300 -- B: The driver drove 130 mph and has to pay \$300.00 -- C: The driver drove undefined and has to pay undefined -- D: The driver drove 130.00 and has to pay 300.00 - -
Odpowiedź -

- -#### Odpowiedź: B - -With the `Intl.NumberFormat` method, we can format numeric values to any locale. We format the numeric value `130` to the `en-US` locale as a `unit` in `mile-per-hour`, which results in `130 mph`. The numeric value `300` to the `en-US` locale as a `currency` in `USD` results in `$300.00`. - -

-
- ---- - -###### 127. Jaki jest wynik? - -```javascript -const spookyItems = ['👻', '🎃', '🕸']; -({ item: spookyItems[3] } = { item: '💀' }); - -console.log(spookyItems); -``` - -- A: `["👻", "🎃", "🕸"]` -- B: `["👻", "🎃", "🕸", "💀"]` -- C: `["👻", "🎃", "🕸", { item: "💀" }]` -- D: `["👻", "🎃", "🕸", "[object Object]"]` - -
Odpowiedź -

- -#### Odpowiedź: B - -By destructuring objects, we can unpack values from the right-hand object, and assign the unpacked value to the value of the same property name on the left-hand object. In this case, we're assigning the value "💀" to `spookyItems[3]`. This means that we're modifying the `spookyItems` array, we're adding the "💀" to it. When logging `spookyItems`, `["👻", "🎃", "🕸", "💀"]` gets logged. - -

-
- ---- - -###### 128. Jaki jest wynik? - -```javascript -const name = 'Lydia Hallie'; -const age = 21; - -console.log(Number.isNaN(name)); -console.log(Number.isNaN(age)); - -console.log(isNaN(name)); -console.log(isNaN(age)); -``` - -- A: `true` `false` `true` `false` -- B: `true` `false` `false` `false` -- C: `false` `false` `true` `false` -- D: `false` `true` `false` `true` - -
Odpowiedź -

- -#### Odpowiedź: C - -With the `Number.isNaN` method, you can check if the value you pass is a _numeric value_ and equal to `NaN`. `name` is not a numeric value, so `Number.isNaN(name)` returns `false`. `age` is a numeric value, but is not equal to `NaN`, so `Number.isNaN(age)` returns `false`. - -With the `isNaN` method, you can check if the value you pass is not a number. `name` is not a number, so `isNaN(name)` returns true. `age` is a number, so `isNaN(age)` returns `false`. - -

-
- ---- - -###### 129. Jaki jest wynik? - -```javascript -const randomValue = 21; - -function getInfo() { - console.log(typeof randomValue); - const randomValue = 'Lydia Hallie'; -} - -getInfo(); -``` - -- A: `"number"` -- B: `"string"` -- C: `undefined` -- D: `ReferenceError` - -
Odpowiedź -

- -#### Odpowiedź: D - -Variables declared with the `const` keyword are not referenceable before their initialization: this is called the _temporal dead zone_. In the `getInfo` function, the variable `randomValue` is scoped in the functional scope of `getInfo`. On the line where we want to log the value of `typeof randomValue`, the variable `randomValue` isn't initialized yet: a `ReferenceError` gets thrown! The engine didn't go down the scope chain since we declared the variable `randomValue` in the `getInfo` function. - -

-
- ---- - -###### 130. Jaki jest wynik? - -```javascript -const myPromise = Promise.resolve('Woah some cool data'); - -(async () => { - try { - console.log(await myPromise); - } catch { - throw new Error(`Oops didn't work`); - } finally { - console.log('Oh finally!'); - } -})(); -``` - -- A: `Woah some cool data` -- B: `Oh finally!` -- C: `Woah some cool data` `Oh finally!` -- D: `Oops didn't work` `Oh finally!` - -
Odpowiedź -

- -#### Odpowiedź: C - -In the `try` block, we're logging the awaited value of the `myPromise` variable: `"Woah some cool data"`. Since no errors were thrown in the `try` block, the code in the `catch` block doesn't run. The code in the `finally` block _always_ runs, `"Oh finally!"` gets logged. - -

-
- ---- - -###### 131. Jaki jest wynik? - -```javascript -const emojis = ['🥑', ['✨', '✨', ['🍕', '🍕']]]; - -console.log(emojis.flat(1)); -``` - -- A: `['🥑', ['✨', '✨', ['🍕', '🍕']]]` -- B: `['🥑', '✨', '✨', ['🍕', '🍕']]` -- C: `['🥑', ['✨', '✨', '🍕', '🍕']]` -- D: `['🥑', '✨', '✨', '🍕', '🍕']` - -
Odpowiedź -

- -#### Odpowiedź: B - -With the `flat` method, we can create a new, flattened array. The depth of the flattened array depends on the value that we pass. In this case, we passed the value `1` (which we didn't have to, that's the default value), meaning that only the arrays on the first depth will be concatenated. `['🥑']` and `['✨', '✨', ['🍕', '🍕']]` in this case. Concatenating these two arrays results in `['🥑', '✨', '✨', ['🍕', '🍕']]`. - -

-
- ---- - -###### 132. Jaki jest wynik? - -```javascript -class Counter { - constructor() { - this.count = 0; - } - - increment() { - this.count++; - } -} - -const counterOne = new Counter(); -counterOne.increment(); -counterOne.increment(); - -const counterTwo = counterOne; -counterTwo.increment(); - -console.log(counterOne.count); -``` - -- A: `0` -- B: `1` -- C: `2` -- D: `3` - -
Odpowiedź -

- -#### Odpowiedź: D - -`counterOne` is an instance of the `Counter` class. The counter class contains a `count` property on its constructor, and an `increment` method. First, we invoked the `increment` method twice by calling `counterOne.increment()`. Currently, `counterOne.count` is `2`. - - - -Then, we create a new variable `counterTwo`, and set it equal to `counterOne`. Since objects interact by reference, we're just creating a new reference to the same spot in memory that `counterOne` points to. Since it has the same spot in memory, any changes made to the object that `counterTwo` has a reference to, also apply to `counterOne`. Currently, `counterTwo.count` is `2`. - -We invoke `counterTwo.increment()`, which sets `count` to `3`. Then, we log the count on `counterOne`, which logs `3`. - - - -

-
- ---- - -###### 133. Jaki jest wynik? - -```javascript -const myPromise = Promise.resolve(Promise.resolve('Promise')); - -function funcOne() { - setTimeout(() => console.log('Timeout 1!'), 0); - myPromise.then(res => res).then(res => console.log(`${res} 1!`)); - console.log('Last line 1!'); -} - -async function funcTwo() { - const res = await myPromise; - console.log(`${res} 2!`) - setTimeout(() => console.log('Timeout 2!'), 0); - console.log('Last line 2!'); -} - -funcOne(); -funcTwo(); -``` - -- A: `Promise 1! Last line 1! Promise 2! Last line 2! Timeout 1! Timeout 2!` -- B: `Last line 1! Timeout 1! Promise 1! Last line 2! Promise2! Timeout 2! ` -- C: `Last line 1! Promise 2! Last line 2! Promise 1! Timeout 1! Timeout 2!` -- D: `Timeout 1! Promise 1! Last line 1! Promise 2! Timeout 2! Last line 2!` - -
Odpowiedź -

- -#### Odpowiedź: C - -First, we invoke `funcOne`. On the first line of `funcOne`, we call the _asynchronous_ `setTimeout` function, from which the callback is sent to the Web API. (see my article on the event loop here.) - -Then we call the `myPromise` promise, which is an _asynchronous_ operation. - -Both the promise and the timeout are asynchronous operations, the function keeps on running while it's busy completing the promise and handling the `setTimeout` callback. This means that `Last line 1!` gets logged first, since this is not an asynchonous operation. - -Since the callstack is not empty yet, the `setTimeout` function and promise in `funcOne` cannot get added to the callstack yet. - -In `funcTwo`, the variable `res` gets `Promise` because `Promise.resolve(Promise.resolve('Promise'))` is equivalent to `Promise.resolve('Promise')` since resolving a promise just resolves it's value. The `await` in this line stops the execution of the function until it receives the resolution of the promise and then keeps on running synchronously until completion, so `Promise 2!` and then `Last line 2!` are logged and the `setTimeout` is sent to the Web API. - -Then the call stack is empty. Promises are _microtasks_ so they are resolved first when the call stack is empty so `Promise 1!` gets to be logged. - -Now, since `funcTwo` popped off the call stack, the call stack is empty. The callbacks waiting in the queue (`() => console.log("Timeout 1!")` from `funcOne`, and `() => console.log("Timeout 2!")` from `funcTwo`) get added to the call stack one by one. The first callback logs `Timeout 1!`, and gets popped off the stack. Then, the second callback logs `Timeout 2!`, and gets popped off the stack. - -

-
- ---- - -###### 134. How can we invoke `sum` in `sum.js` from `index.js?` - -```javascript -// sum.js -export default function sum(x) { - return x + x; -} - -// index.js -import * as sum from './sum'; -``` - -- A: `sum(4)` -- B: `sum.sum(4)` -- C: `sum.default(4)` -- D: Default aren't imported with `*`, only named exports - -
Odpowiedź -

- -#### Odpowiedź: C - -With the asterisk `*`, we import all exported values from that file, both default and named. If we had the following file: - -```javascript -// info.js -export const name = 'Lydia'; -export const age = 21; -export default 'I love JavaScript'; - -// index.js -import * as info from './info'; -console.log(info); -``` - -The following would get logged: - -```javascript -{ - default: "I love JavaScript", - name: "Lydia", - age: 21 -} -``` - -For the `sum` example, it means that the imported value `sum` looks like this: - -```javascript -{ default: function sum(x) { return x + x } } -``` - -We can invoke this function, by calling `sum.default` - -

-
- ---- - -###### 135. Jaki jest wynik? - -```javascript -const handler = { - set: () => console.log('Added a new property!'), - get: () => console.log('Accessed a property!'), -}; - -const person = new Proxy({}, handler); - -person.name = 'Lydia'; -person.name; -``` - -- A: `Added a new property!` -- B: `Accessed a property!` -- C: `Added a new property!` `Accessed a property!` -- D: Nothing gets logged - -
Odpowiedź -

- -#### Odpowiedź: C - -With a Proxy object, we can add custom behavior to an object that we pass to it as the second argument. In this case, we pass the `handler` object which contained two properties: `set` and `get`. `set` gets invoked whenever we _set_ property values, `get` gets invoked whenever we _get_ (access) property values. - -The first argument is an empty object `{}`, which is the value of `person`. To this object, the custom behavior specified in the `handler` object gets added. If we add a property to the `person` object, `set` will get invoked. If we access a property on the `person` object, `get` gets invoked. - -First, we added a new property `name` to the proxy object (`person.name = "Lydia"`). `set` gets invoked, and logs `"Added a new property!"`. - -Then, we access a property value on the proxy object, the `get` property on the handler object got invoked. `"Accessed a property!"` gets logged. - -

-
- ---- - -###### 136. Which of the following will modify the `person` object? - -```javascript -const person = { name: 'Lydia Hallie' }; - -Object.seal(person); -``` - -- A: `person.name = "Evan Bacon"` -- B: `person.age = 21` -- C: `delete person.name` -- D: `Object.assign(person, { age: 21 })` - -
Odpowiedź -

- -#### Odpowiedź: A - -With `Object.seal` we can prevent new properties from being _added_, or existing properties to be _removed_. - -However, you can still modify the value of existing properties. - -

-
- ---- - -###### 137. Which of the following will modify the `person` object? - -```javascript -const person = { - name: 'Lydia Hallie', - address: { - street: '100 Main St', - }, -}; - -Object.freeze(person); -``` - -- A: `person.name = "Evan Bacon"` -- B: `delete person.address` -- C: `person.address.street = "101 Main St"` -- D: `person.pet = { name: "Mara" }` - -
Odpowiedź -

- -#### Odpowiedź: C - -The `Object.freeze` method _freezes_ an object. No properties can be added, modified, or removed. - -However, it only _shallowly_ freezes the object, meaning that only _direct_ properties on the object are frozen. If the property is another object, like `address` in this case, the properties on that object aren't frozen, and can be modified. - -

-
- ---- - -###### 138. Jaki jest wynik? - -```javascript -const add = x => x + x; - -function myFunc(num = 2, value = add(num)) { - console.log(num, value); -} - -myFunc(); -myFunc(3); -``` - -- A: `2` `4` and `3` `6` -- B: `2` `NaN` and `3` `NaN` -- C: `2` `Error` and `3` `6` -- D: `2` `4` and `3` `Error` - -
Odpowiedź -

- -#### Odpowiedź: A - -First, we invoked `myFunc()` without passing any arguments. Since we didn't pass arguments, `num` and `value` got their default values: num is `2`, and `value` the returned value of the function `add`. To the `add` function, we pass `num` as an argument, which had the value of `2`. `add` returns `4`, which is the value of `value`. - -Then, we invoked `myFunc(3)` and passed the value `3` as the value for the argument `num`. We didn't pass an argument for `value`. Since we didn't pass a value for the `value` argument, it got the default value: the returned value of the `add` function. To `add`, we pass `num`, which has the value of `3`. `add` returns `6`, which is the value of `value`. - -

-
- ---- - -###### 139. Jaki jest wynik? - -```javascript -class Counter { - #number = 10 - - increment() { - this.#number++ - } - - getNum() { - return this.#number - } -} - -const counter = new Counter() -counter.increment() - -console.log(counter.#number) -``` - -- A: `10` -- B: `11` -- C: `undefined` -- D: `SyntaxError` - -
Odpowiedź -

- -#### Odpowiedź: D - -In ES2020, we can add private variables in classes by using the `#`. We cannot access these variables outside of the class. When we try to log `counter.#number`, a SyntaxError gets thrown: we cannot acccess it outside the `Counter` class! - -

-
- ---- - -###### 140. What's missing? - -```javascript -const teams = [ - { name: 'Team 1', members: ['Paul', 'Lisa'] }, - { name: 'Team 2', members: ['Laura', 'Tim'] }, -]; - -function* getMembers(members) { - for (let i = 0; i < members.length; i++) { - yield members[i]; - } -} - -function* getTeams(teams) { - for (let i = 0; i < teams.length; i++) { - // ✨ SOMETHING IS MISSING HERE ✨ - } -} - -const obj = getTeams(teams); -obj.next(); // { value: "Paul", done: false } -obj.next(); // { value: "Lisa", done: false } -``` - -- A: `yield getMembers(teams[i].members)` -- B: `yield* getMembers(teams[i].members)` -- C: `return getMembers(teams[i].members)` -- D: `return yield getMembers(teams[i].members)` - -
Odpowiedź -

- -#### Odpowiedź: B - -In order to iterate over the `members` in each element in the `teams` array, we need to pass `teams[i].members` to the `getMembers` generator function. The generator function returns a generator object. In order to iterate over each element in this generator object, we need to use `yield*`. - -If we would've written `yield`, `return yield`, or `return`, the entire generator function would've gotten returned the first time we called the `next` method. - -

-
- ---- - -###### 141. Jaki jest wynik? - -```javascript -const person = { - name: 'Lydia Hallie', - hobbies: ['coding'], -}; - -function addHobby(hobby, hobbies = person.hobbies) { - hobbies.push(hobby); - return hobbies; -} - -addHobby('running', []); -addHobby('dancing'); -addHobby('baking', person.hobbies); - -console.log(person.hobbies); -``` - -- A: `["coding"]` -- B: `["coding", "dancing"]` -- C: `["coding", "dancing", "baking"]` -- D: `["coding", "running", "dancing", "baking"]` - -
Odpowiedź -

- -#### Odpowiedź: C - -The `addHobby` function receives two arguments, `hobby` and `hobbies` with the default value of the `hobbies` array on the `person` object. - -First, we invoke the `addHobby` function, and pass `"running"` as the value for `hobby` and an empty array as the value for `hobbies`. Since we pass an empty array as the value for `hobbies`, `"running"` gets added to this empty array. - -Then, we invoke the `addHobby` function, and pass `"dancing"` as the value for `hobby`. We didn't pass a value for `hobbies`, so it gets the default value, the `hobbies` property on the `person` object. We push the hobby `dancing` to the `person.hobbies` array. - -Last, we invoke the `addHobby` function, and pass `"baking"` as the value for `hobby`, and the `person.hobbies` array as the value for `hobbies`. We push the hobby `baking` to the `person.hobbies` array. - -After pushing `dancing` and `baking`, the value of `person.hobbies` is `["coding", "dancing", "baking"]` - -

-
- ---- - -###### 142. Jaki jest wynik? - -```javascript -class Bird { - constructor() { - console.log("I'm a bird. 🦢"); - } -} - -class Flamingo extends Bird { - constructor() { - console.log("I'm pink. 🌸"); - super(); - } -} - -const pet = new Flamingo(); -``` - -- A: `I'm pink. 🌸` -- B: `I'm pink. 🌸` `I'm a bird. 🦢` -- C: `I'm a bird. 🦢` `I'm pink. 🌸` -- D: Nothing, we didn't call any method - -
Odpowiedź -

- -#### Odpowiedź: B - -We create the variable `pet` which is an instance of the `Flamingo` class. When we instantiate this instance, the `constructor` on `Flamingo` gets called. First, `"I'm pink. 🌸"` gets logged, after which we call `super()`. `super()` calls the constructor of the parent class, `Bird`. The constructor in `Bird` gets called, and logs `"I'm a bird. 🦢"`. - -

-
- ---- - -###### 143. Which of the options result(s) in an error? - -```javascript -const emojis = ['🎄', '🎅🏼', '🎁', '⭐']; - -/* 1 */ emojis.push('🦌'); -/* 2 */ emojis.splice(0, 2); -/* 3 */ emojis = [...emojis, '🥂']; -/* 4 */ emojis.length = 0; -``` - -- A: 1 -- B: 1 and 2 -- C: 3 and 4 -- D: 3 - -
Odpowiedź -

- -#### Odpowiedź: D - -The `const` keyword simply means we cannot _redeclare_ the value of that variable, it's _read-only_. However, the value itself isn't immutable. The properties on the `emojis` array can be modified, for example by pushing new values, splicing them, or setting the length of the array to 0. - -

-
- ---- - -###### 144. What do we need to add to the `person` object to get `["Lydia Hallie", 21]` as the output of `[...person]`? - -```javascript -const person = { - name: "Lydia Hallie", - age: 21 -} - -[...person] // ["Lydia Hallie", 21] -``` - -- A: Nothing, object are iterable by default -- B: `*[Symbol.iterator]() { for (let x in this) yield* this[x] }` -- C: `*[Symbol.iterator]() { yield* Object.values(this) }` -- D: `*[Symbol.iterator]() { for (let x in this) yield this }` - -
Odpowiedź -

- -#### Odpowiedź: C - -Objects aren't iterable by default. An iterable is an iterable if the iterator protocol is present. We can add this manually by adding the iterator symbol `[Symbol.iterator]`, which has to return a generator object, for example by making it a generator function `*[Symbol.iterator]() {}`. This generator function has to yield the `Object.values` of the `person` object if we want it to return the array `["Lydia Hallie", 21]`: `yield* Object.values(this)`. - -

-
- ---- - -###### 145. Jaki jest wynik? - -```javascript -let count = 0; -const nums = [0, 1, 2, 3]; - -nums.forEach(num => { - if (num) count += 1 -}) - -console.log(count) -``` - -- A: 1 -- B: 2 -- C: 3 -- D: 4 - -
Odpowiedź -

- -#### Odpowiedź: C - -The `if` condition within the `forEach` loop checks whether the value of `num` is truthy or falsy. Since the first number in the `nums` array is `0`, a falsy value, the `if` statement's code block won't be executed. `count` only gets incremented for the other 3 numbers in the `nums` array, `1`, `2` and `3`. Since `count` gets incremented by `1` 3 times, the value of `count` is `3`. - -

-
- ---- - -###### 146. Jaki jest wynik? - -```javascript -function getFruit(fruits) { - console.log(fruits?.[1]?.[1]) -} - -getFruit([['🍊', '🍌'], ['🍍']]) -getFruit() -getFruit([['🍍'], ['🍊', '🍌']]) -``` - -- A: `null`, `undefined`, 🍌 -- B: `[]`, `null`, 🍌 -- C: `[]`, `[]`, 🍌 -- D: `undefined`, `undefined`, 🍌 - -
Odpowiedź -

- -#### Odpowiedź: D - -The `?` allows us to optionally access deeper nested properties within objects. We're trying to log the item on index `1` within the subarray that's on index `1` of the `fruits` array. If the subarray on index `1` in the `fruits` array doesn't exist, it'll simply return `undefined`. If the subarray on index `1` in the `fruits` array exists, but this subarray doesn't have an item on its `1` index, it'll also return `undefined`. - -First, we're trying to log the second item in the `['🍍']` subarray of `[['🍊', '🍌'], ['🍍']]`. This subarray only contains one item, which means there is no item on index `1`, and returns `undefined`. - -Then, we're invoking the `getFruits` function without passing a value as an argument, which means that `fruits` has a value of `undefined` by default. Since we're conditionally chaining the item on index `1` of`fruits`, it returns `undefined` since this item on index `1` does not exist. - -Lastly, we're trying to log the second item in the `['🍊', '🍌']` subarray of `['🍍'], ['🍊', '🍌']`. The item on index `1` within this subarray is `🍌`, which gets logged. - -

-
- ---- - -###### 147. Jaki jest wynik? - -```javascript -class Calc { - constructor() { - this.count = 0 - } - - increase() { - this.count ++ - } -} - -const calc = new Calc() -new Calc().increase() - -console.log(calc.count) -``` - -- A: `0` -- B: `1` -- C: `undefined` -- D: `ReferenceError` - -
Odpowiedź -

- -#### Odpowiedź: A - -We set the variable `calc` equal to a new instance of the `Calc` class. Then, we instantiate a new instance of `Calc`, and invoke the `increase` method on this instance. Since the count property is within the constructor of the `Calc` class, the count property is not shared on the prototype of `Calc`. This means that the value of count has not been updated for the instance calc points to, count is still `0`. - -

-
- ---- - -###### 148. Jaki jest wynik? - -```javascript -const user = { - email: "e@mail.com", - password: "12345" -} - -const updateUser = ({ email, password }) => { - if (email) { - Object.assign(user, { email }) - } - - if (password) { - user.password = password - } - - return user -} - -const updatedUser = updateUser({ email: "new@email.com" }) - -console.log(updatedUser === user) -``` - -- A: `false` -- B: `true` -- C: `TypeError` -- D: `ReferenceError` - -
Odpowiedź -

- -#### Odpowiedź: B - -The `updateUser` function updates the values of the `email` and `password` properties on user, if their values are passed to the function, after which the function returns the `user` object. The returned value of the `updateUser` function is the `user` object, which means that the value of updatedUser is a reference to the same `user` object that `user` points to. `updatedUser === user` equals `true`. - -

-
- ---- - -###### 149. Jaki jest wynik? - -```javascript -const fruit = ['🍌', '🍊', '🍎'] - -fruit.slice(0, 1) -fruit.splice(0, 1) -fruit.unshift('🍇') - -console.log(fruit) -``` - -- A: `['🍌', '🍊', '🍎']` -- B: `['🍊', '🍎']` -- C: `['🍇', '🍊', '🍎']` -- D: `['🍇', '🍌', '🍊', '🍎']` - -
Odpowiedź -

- -#### Odpowiedź: C - -First, we invoke the `slice` method on the fruit array. The slice method does not modify the original array, but returns the value that it sliced off the array: the banana emoji. -Then, we invoke the `splice` method on the fruit array. The splice method does modify the original array, which means that the fruit array now consists of `['🍊', '🍎']`. -At last, we invoke the `unshift` method on the `fruit` array, which modifies the original array by adding the provided value, ‘🍇’ in this case, as the first element in the array. The fruit array now consists of `['🍇', '🍊', '🍎']`. - -

-
- ---- - -###### 150. Jaki jest wynik? - -```javascript -const animals = {}; -let dog = { emoji: '🐶' } -let cat = { emoji: '🐈' } - -animals[dog] = { ...dog, name: "Mara" } -animals[cat] = { ...cat, name: "Sara" } - -console.log(animals[dog]) -``` - -- A: `{ emoji: "🐶", name: "Mara" }` -- B: `{ emoji: "🐈", name: "Sara" }` -- C: `undefined` -- D: `ReferenceError` - -
Odpowiedź -

- -#### Odpowiedź: B - -Object keys are converted to strings. - -Since the value of `dog` is an object, `animals[dog]` actually means that we’re creating a new property called `"object Object"` equal to the new object. `animals["object Object"]` is now equal to `{ emoji: "🐶", name: "Mara"}`. - -`cat` is also an object, which means that `animals[cat]` actually means that we’re overwriting the value of `animals["object Object"]` with the new cat properties. - -Logging `animals[dog]`, or actually `animals["object Object"]` since converting the `dog` object to a string results `"object Object"`, returns the `{ emoji: "🐈", name: "Sara" }`. - -

-
- ---- - -###### 151. Jaki jest wynik? - -```javascript -const user = { - email: "my@email.com", - updateEmail: email => { - this.email = email - } -} - -user.updateEmail("new@email.com") -console.log(user.email) -``` - -- A: `my@email.com` -- B: `new@email.com` -- C: `undefined` -- D: `ReferenceError` - -
Odpowiedź -

- -#### Odpowiedź: A - -The `updateEmail` function is an arrow function, and is not bound to the `user` object. This means that the `this` keyword is not referring to the `user` object, but refers to the global scope in this case. The value of `email` within the `user` object does not get updated. When logging the value of `user.email`, the original value of `my@email.com` gets returned. - -

-
- ---- - -###### 152. Jaki jest wynik? - -```javascript -const promise1 = Promise.resolve('First') -const promise2 = Promise.resolve('Second') -const promise3 = Promise.reject('Third') -const promise4 = Promise.resolve('Fourth') - -const runPromises = async () => { - const res1 = await Promise.all([promise1, promise2]) - const res2 = await Promise.all([promise3, promise4]) - return [res1, res2] -} - -runPromises() - .then(res => console.log(res)) - .catch(err => console.log(err)) -``` - -- A: `[['First', 'Second'], ['Fourth']]` -- B: `[['First', 'Second'], ['Third', 'Fourth']]` -- C: `[['First', 'Second']]` -- D: `'Third'` - -
Odpowiedź -

- -#### Odpowiedź: D - -The `Promise.all` method runs the passed promises in parallel. If one promise fails, the `Promise.all` method _rejects_ with the value of the rejected promise. In this case, `promise3` rejected with the value `"Third"`. We’re catching the rejected value in the chained `catch` method on the `runPromises` invocation to catch any errors within the `runPromises` function. Only `"Third"` gets logged, since `promise3` rejected with this value. - -

-
- ---- - -###### 153. What should the value of `method` be to log `{ name: "Lydia", age: 22 }`? - -```javascript -const keys = ["name", "age"] -const values = ["Lydia", 22] - -const method = /* ?? */ -Object[method](keys.map((_, i) => { - return [keys[i], values[i]] -})) // { name: "Lydia", age: 22 } -``` - -- A: `entries` -- B: `values` -- C: `fromEntries` -- D: `forEach` - -
Odpowiedź -

- -#### Odpowiedź: C - -The `fromEntries` method turns a 2d array into an object. The first element in each subarray will be the key, and the second element in each subarray will be the value. In this case, we’re mapping over the `keys` array, which returns an array which first element is the item on the key array on the current index, and the second element is the item of the values array on the current index. - -This creates an array of subarrays containing the correct keys and values, which results in `{ name: "Lydia", age: 22 }` - -

-
- ---- - -###### 154. Jaki jest wynik? - -```javascript -const createMember = ({ email, address = {}}) => { - const validEmail = /.+\@.+\..+/.test(email) - if (!validEmail) throw new Error("Valid email pls") - - return { - email, - address: address ? address : null - } -} - -const member = createMember({ email: "my@email.com" }) -console.log(member) -``` - -- A: `{ email: "my@email.com", address: null }` -- B: `{ email: "my@email.com" }` -- C: `{ email: "my@email.com", address: {} }` -- D: `{ email: "my@email.com", address: undefined }` - -
Odpowiedź -

- -#### Odpowiedź: C - -The default value of `address` is an empty object `{}`. When we set the variable `member` equal to the object returned by the `createMember` function, we didn't pass a value for address, which means that the value of address is the default empty object `{}`. An empty object is a truthy value, which means that the condition of the `address ? address : null` conditional returns `true`. The value of address is the empty object `{}`. - -

-
- ---- - -###### 155. Jaki jest wynik? - -```javascript -let randomValue = { name: "Lydia" } -randomValue = 23 - -if (!typeof randomValue === "string") { - console.log("It's not a string!") -} else { - console.log("Yay it's a string!") -} -``` - -- A: `It's not a string!` -- B: `Yay it's a string!` -- C: `TypeError` -- D: `undefined` - -
Odpowiedź -

- -#### Odpowiedź: B - -The condition within the `if` statement checks whether the value of `!typeof randomValue` is equal to `"string"`. The `!` operator converts the value to a boolean value. If the value is truthy, the returned value will be `false`, if the value is falsy, the returned value will be `true`. In this case, the returned value of `typeof randomValue` is the truthy value `"number"`, meaning that the value of `!typeof randomValue` is the boolean value `false`. - -`!typeof randomValue === "string"` always returns false, since we're actually checking `false === "string"`. Since the condition returned `false`, the code block of the `else` statement gets run, and `Yay it's a string!` gets logged. - -

-
From 71a26195d9e1043de2600f5ec5d8dc1dc9ae4bdd Mon Sep 17 00:00:00 2001 From: Lukasz Jasionowski Date: Mon, 26 Jun 2023 06:19:35 +0200 Subject: [PATCH 151/193] Fix typo from _ to - --- ar-AR/README_AR.md | 2 +- bs-BS/README-bs_BS.md | 2 +- de-DE/README.md | 2 +- es-ES/README-ES.md | 2 +- fr-FR/README_fr-FR.md | 2 +- id-ID/README.md | 2 +- it-IT/README.md | 2 +- ja-JA/README-ja_JA.md | 2 +- ko-KR/README-ko_KR.md | 2 +- nl-NL/README.md | 2 +- pt-BR/README_pt_BR.md | 2 +- ru-RU/README.md | 2 +- th-TH/README.md | 2 +- tr-TR/README-tr_TR.md | 2 +- uk-UA/README.md | 2 +- vi-VI/README-vi.md | 2 +- 16 files changed, 16 insertions(+), 16 deletions(-) diff --git a/ar-AR/README_AR.md b/ar-AR/README_AR.md index be213a9b..3e490cdd 100644 --- a/ar-AR/README_AR.md +++ b/ar-AR/README_AR.md @@ -25,7 +25,7 @@ - [🇯🇵 日本語](../ja-JA/README-ja_JA.md) - [🇰🇷 한국어](../ko-KR/README-ko_KR.md) - [🇳🇱 Nederlands](../nl-NL/README.md) -- [🇵🇱 Polski](../pl_PL/README.md) +- [🇵🇱 Polski](../pl-PL/README.md) - [🇧🇷 Português Brasil](../pt-BR/README_pt_BR.md) - [🇷🇺 Русский](../ru-RU/README.md) - [🇹🇭 ไทย](../th-TH/README-th_TH.md) diff --git a/bs-BS/README-bs_BS.md b/bs-BS/README-bs_BS.md index 39f3dee3..6e57f8c2 100644 --- a/bs-BS/README-bs_BS.md +++ b/bs-BS/README-bs_BS.md @@ -23,7 +23,7 @@ kliknite na njih da biste ih proširili. Sretno :heart: - [🇯🇵 日本語](../ja-JA/README-ja_JA.md) - [🇰🇷 한국어](../ko-KR/README-ko_KR.md) - [🇳🇱 Nederlands](../nl-NL/README.md) -- [🇵🇱 Polski](../pl_PL/README.md) +- [🇵🇱 Polski](../pl-PL/README.md) - [🇧🇷 Português Brasil](../pt-BR/README_pt_BR.md) - [🇷🇺 Русский](../ru-RU/README.md) - [🇹🇭 ไทย](../th-TH/README-th_TH.md) diff --git a/de-DE/README.md b/de-DE/README.md index 59964041..6111d8eb 100644 --- a/de-DE/README.md +++ b/de-DE/README.md @@ -33,7 +33,7 @@ Kontaktiert mich, wenn ihr möchtet! 😊
- [🇯🇵 日本語](../ja-JA/README-ja_JA.md) - [🇰🇷 한국어](../ko-KR/README-ko_KR.md) - [🇳🇱 Nederlands](../nl-NL/README.md) -- [🇵🇱 Polski](../pl_PL/README.md) +- [🇵🇱 Polski](../pl-PL/README.md) - [🇧🇷 Português Brasil](../pt-BR/README_pt_BR.md) - [🇷🇺 Русский](../ru-RU/README.md) - [🇹🇭 ไทย](../th-TH/README-th_TH.md) diff --git a/es-ES/README-ES.md b/es-ES/README-ES.md index dbde4c4c..aafe6fdc 100644 --- a/es-ES/README-ES.md +++ b/es-ES/README-ES.md @@ -23,7 +23,7 @@ Lista de lenguajes disponibles: - [🇯🇵 日本語](../ja-JA/README-ja_JA.md) - [🇰🇷 한국어](../ko-KR/README-ko_KR.md) - [🇳🇱 Nederlands](../nl-NL/README.md) -- [🇵🇱 Polski](../pl_PL/README.md) +- [🇵🇱 Polski](../pl-PL/README.md) - [🇧🇷 Português Brasil](../pt-BR/README_pt_BR.md) - [🇷🇺 Русский](../ru-RU/README.md) - [🇹🇭 ไทย](../th-TH/README-th_TH.md) diff --git a/fr-FR/README_fr-FR.md b/fr-FR/README_fr-FR.md index ee2b9c0d..eb695160 100644 --- a/fr-FR/README_fr-FR.md +++ b/fr-FR/README_fr-FR.md @@ -17,7 +17,7 @@ Les réponses se trouvent dans les sections repliées en dessous des questions, - [🇯🇵 日本語](../ja-JA/README-ja_JA.md) - [🇰🇷 한국어](../ko-KR/README-ko_KR.md) - [🇳🇱 Nederlands](../nl-NL/README.md) -- [🇵🇱 Polski](../pl_PL/README.md) +- [🇵🇱 Polski](../pl-PL/README.md) - [🇧🇷 Português Brasil](../pt-BR/README_pt_BR.md) - [🇷🇺 Русский](../ru-RU/README.md) - [🇹🇭 ไทย](../th-TH/README-th_TH.md) diff --git a/id-ID/README.md b/id-ID/README.md index d1d126bd..3e430594 100644 --- a/id-ID/README.md +++ b/id-ID/README.md @@ -27,7 +27,7 @@ Jangan sungkan untuk terhubung dengan saya! 😊
- [🇯🇵 日本語](../ja-JA/README-ja_JA.md) - [🇰🇷 한국어](../ko-KR/README-ko_KR.md) - [🇳🇱 Nederlands](../nl-NL/README.md) -- [🇵🇱 Polski](../pl_PL/README.md) +- [🇵🇱 Polski](../pl-PL/README.md) - [🇧🇷 Português Brasil](../pt-BR/README_pt_BR.md) - [🇷🇺 Русский](../ru-RU/README.md) - [🇹🇭 ไทย](../th-TH/README-th_TH.md) diff --git a/it-IT/README.md b/it-IT/README.md index 09db4069..bb0c13d7 100644 --- a/it-IT/README.md +++ b/it-IT/README.md @@ -35,7 +35,7 @@ Traduzione a cura di: Lucia Cenetie - [🇯🇵 日本語](../ja-JA/README-ja_JA.md) - [🇰🇷 한국어](../ko-KR/README-ko_KR.md) - [🇳🇱 Nederlands](../nl-NL/README.md) -- [🇵🇱 Polski](../pl_PL/README.md) +- [🇵🇱 Polski](../pl-PL/README.md) - [🇧🇷 Português Brasil](../pt-BR/README_pt_BR.md) - [🇷🇺 Русский](../ru-RU/README.md) - [🇹🇭 ไทย](../th-TH/README-th_TH.md) diff --git a/ja-JA/README-ja_JA.md b/ja-JA/README-ja_JA.md index bd88f692..ebd754c0 100644 --- a/ja-JA/README-ja_JA.md +++ b/ja-JA/README-ja_JA.md @@ -19,7 +19,7 @@ - [🇮🇹 Italiano](../it-IT/README.md) - [🇰🇷 한국어](../ko-KR/README-ko_KR.md) - [🇳🇱 Nederlands](../nl-NL/README.md) -- [🇵🇱 Polski](../pl_PL/README.md) +- [🇵🇱 Polski](../pl-PL/README.md) - [🇧🇷 Português Brasil](../pt-BR/README_pt_BR.md) - [🇷🇺 Русский](../ru-RU/README.md) - [🇹🇭 ไทย](../th-TH/README-th_TH.md) diff --git a/ko-KR/README-ko_KR.md b/ko-KR/README-ko_KR.md index 9651fd7d..aca2c534 100644 --- a/ko-KR/README-ko_KR.md +++ b/ko-KR/README-ko_KR.md @@ -32,7 +32,7 @@ - [🇮🇹 Italiano](../it-IT/README.md) - [🇯🇵 日本語](../ja-JA/README-ja_JA.md) - [🇳🇱 Nederlands](../nl-NL/README.md) -- [🇵🇱 Polski](../pl_PL/README.md) +- [🇵🇱 Polski](../pl-PL/README.md) - [🇧🇷 Português Brasil](../pt-BR/README_pt_BR.md) - [🇷🇺 Русский](../ru-RU/README.md) - [🇹🇭 ไทย](../th-TH/README-th_TH.md) diff --git a/nl-NL/README.md b/nl-NL/README.md index 21339aa9..ad13ed36 100644 --- a/nl-NL/README.md +++ b/nl-NL/README.md @@ -28,7 +28,7 @@ - [🇮🇹 Italiano](../it-IT/README.md) - [🇯🇵 日本語](../ja-JA/README-ja_JA.md) - [🇰🇷 한국어](../ko-KR/README-ko_KR.md) -- [🇵🇱 Polski](../pl_PL/README.md) +- [🇵🇱 Polski](../pl-PL/README.md) - [🇧🇷 Português Brasil](../pt-BR/README_pt_BR.md) - [🇷🇺 Русский](../ru-RU/README.md) - [🇹🇭 ไทย](../th-TH/README-th_TH.md) diff --git a/pt-BR/README_pt_BR.md b/pt-BR/README_pt_BR.md index 03695c1d..11995aaf 100644 --- a/pt-BR/README_pt_BR.md +++ b/pt-BR/README_pt_BR.md @@ -18,7 +18,7 @@ As respostas estão em seções recolhidas abaixo das questões, basta clicar ne - [🇯🇵 日本語](../ja-JA/README-ja_JA.md) - [🇰🇷 한국어](../ko-KR/README-ko_KR.md) - [🇳🇱 Nederlands](../nl-NL/README.md) -- [🇵🇱 Polski](../pl_PL/README.md) +- [🇵🇱 Polski](../pl-PL/README.md) - [🇷🇺 Русский](../ru-RU/README.md) - [🇹🇭 ไทย](../th-TH/README-th_TH.md) - [🇹🇷 Türkçe](../tr-TR/README-tr_TR.md) diff --git a/ru-RU/README.md b/ru-RU/README.md index 382454e0..d4236ed5 100644 --- a/ru-RU/README.md +++ b/ru-RU/README.md @@ -31,7 +31,7 @@ - [🇯🇵 日本語](../ja-JA/README-ja_JA.md) - [🇰🇷 한국어](../ko-KR/README-ko_KR.md) - [🇳🇱 Nederlands](../nl-NL/README.md) -- [🇵🇱 Polski](../pl_PL/README.md) +- [🇵🇱 Polski](../pl-PL/README.md) - [🇧🇷 Português Brasil](../pt-BR/README_pt_BR.md) - [🇬🇧 English](../README.md) - [🇹🇭 ไทย](../th-TH/README-th_TH.md) diff --git a/th-TH/README.md b/th-TH/README.md index 8dd76df6..1a16e65a 100644 --- a/th-TH/README.md +++ b/th-TH/README.md @@ -30,7 +30,7 @@ - [🇯🇵 日本語](../ja-JA/README-ja_JA.md) - [🇰🇷 한국어](../ko-KR/README-ko_KR.md) - [🇳🇱 Nederlands](../nl-NL/README.md) -- [🇵🇱 Polski](../pl_PL/README.md) +- [🇵🇱 Polski](../pl-PL/README.md) - [🇧🇷 Português Brasil](../pt-BR/README_pt_BR.md) - [🇷🇺 Русский](../ru-RU/README.md) - [🇹🇷 Türkçe](../tr-TR/README-tr_TR.md) diff --git a/tr-TR/README-tr_TR.md b/tr-TR/README-tr_TR.md index 0eb88dd6..4ca673e0 100644 --- a/tr-TR/README-tr_TR.md +++ b/tr-TR/README-tr_TR.md @@ -24,7 +24,7 @@ Mevcut dillerin listesi: - [🇯🇵 日本語](../ja-JA/README-ja_JA.md) - [🇰🇷 한국어](../ko-KR/README-ko_KR.md) - [🇳🇱 Nederlands](../nl-NL/README.md) -- [🇵🇱 Polski](../pl_PL/README.md) +- [🇵🇱 Polski](../pl-PL/README.md) - [🇧🇷 Português Brasil](../pt-BR/README_pt_BR.md) - [🇷🇺 Русский](../ru-RU/README.md) - [🇹🇭 ไทย](../th-TH/README-th_TH.md) diff --git a/uk-UA/README.md b/uk-UA/README.md index f71a3f9c..efa0329a 100644 --- a/uk-UA/README.md +++ b/uk-UA/README.md @@ -18,7 +18,7 @@ - [🇯🇵 日本語](../ja-JA/README-ja_JA.md) - [🇰🇷 한국어](../ko-KR/README-ko_KR.md) - [🇳🇱 Nederlands](../nl-NL/README.md) -- [🇵🇱 Polski](../pl_PL/README.md) +- [🇵🇱 Polski](../pl-PL/README.md) - [🇧🇷 Português Brasil](../pt-BR/README_pt_BR.md) - [🇷🇺 Русский](../ru-RU/README.md) - [🇹🇭 ไทย](../th-TH/README-th_TH.md) diff --git a/vi-VI/README-vi.md b/vi-VI/README-vi.md index 1f95bbef..e663ae96 100644 --- a/vi-VI/README-vi.md +++ b/vi-VI/README-vi.md @@ -19,7 +19,7 @@ Danh sách các ngôn ngữ khác: - [🇯🇵 日本語](../ja-JA/README-ja_JA.md) - [🇰🇷 한국어](../ko-KR/README-ko_KR.md) - [🇳🇱 Nederlands](../nl-NL/README.md) -- [🇵🇱 Polski](../pl_PL/README.md) +- [🇵🇱 Polski](../pl-PL/README.md) - [🇧🇷 Português Brasil](../pt-BR/README_pt_BR.md) - [🇷🇺 Русский](../ru-RU/README.md) - [🇹🇭 ไทย](../th-TH/README-th_TH.md) From a7959245587b76676d17409f3967aa97ebc5bbf9 Mon Sep 17 00:00:00 2001 From: Lukasz Jasionowski Date: Mon, 26 Jun 2023 06:22:13 +0200 Subject: [PATCH 152/193] Fix typo from _ to - --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index a5e28d2c..c5011bc9 100644 --- a/README.md +++ b/README.md @@ -31,7 +31,7 @@ Feel free to reach out to me! 😊
- [🇯🇵 日本語](./ja-JA/README-ja_JA.md) - [🇰🇷 한국어](./ko-KR/README-ko_KR.md) - [🇳🇱 Nederlands](./nl-NL/README.md) -- [🇵🇱 Polski](./pl_PL/README.md) +- [🇵🇱 Polski](./pl-PL/README.md) - [🇧🇷 Português Brasil](./pt-BR/README_pt_BR.md) - [🇷🇺 Русский](./ru-RU/README.md) - [🇹🇭 ไทย](./th-TH/README-th_TH.md) From f0574ed45d2ee3f72f5c4fa0520d184f4f75a3d3 Mon Sep 17 00:00:00 2001 From: Lukasz Jasionowski Date: Mon, 26 Jun 2023 21:45:25 +0200 Subject: [PATCH 153/193] Add another 10 translated questions and answers --- pl-PL/README.md | 303 +++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 302 insertions(+), 1 deletion(-) diff --git a/pl-PL/README.md b/pl-PL/README.md index 3dba610d..36c7f0c8 100644 --- a/pl-PL/README.md +++ b/pl-PL/README.md @@ -4,7 +4,7 @@ --- -Publikuję pytania wielokrotnego wyboru dotyczące JavaScriptu na swoich [Instagram](https://www.instagram.com/theavocoder) **stories**, które również zamieszczę tutaj! Ostatnia aktualizacja:
12 Czerwca +Publikuję pytania wielokrotnego wyboru dotyczące JavaScriptu na swoich [Instagram](https://www.instagram.com/theavocoder) **stories**, które również zamieszczę tutaj! Ostatnia aktualizacja: 26 Czerwca Od podstawowych do zaawansowanych: sprawdź, jak dobrze znasz JavaScript, odśwież swoją wiedzę lub przygotuj się do rozmowy kwalifikacyjnej! :muscle: :rocket: Regularnie aktualizuję to repozytorium nowymi pytaniami. Odpowiedzi znajdują się w ukrytych zakładkach poniżej pytań - po prostu kliknij, aby je rozwinięć. To dla zabawy, powodzenia! :heart: @@ -364,3 +364,304 @@ Funkcja jest specjalnym rodzajem obiektu. Kod, który sam piszesz, nie jest wła

+ +--- + +###### 11. Jaki jest wynik? + +```javascript +function Person(firstName, lastName) { + this.firstName = firstName; + this.lastName = lastName; +} + +const member = new Person('Lydia', 'Hallie'); +Person.getFullName = function() { + return `${this.firstName} ${this.lastName}`; +}; + +console.log(member.getFullName()); +``` + +- A: `TypeError` +- B: `SyntaxError` +- C: `Lydia Hallie` +- D: `undefined` `undefined` + +
Odpowiedź +

+ +#### Odpowiedź: A + +W JavaScript funkcje są obiektami, więc metoda `getFullName` jest dodawana do samego obiektu funkcji konstruktora. Dlatego możemy wywołać `Person.getFullName()`, ale `member.getFullName` zwraca błąd `TypeError`. + +Jeśli chcesz, aby metoda była dostępna dla wszystkich instancji obiektów, musisz dodać ją do właściwości prototype: + +```js +Person.prototype.getFullName = function() { + return `${this.firstName} ${this.lastName}`; +}; +``` + +

+
+ +--- + +###### 12. Jaki jest wynik? + +```javascript +function Person(firstName, lastName) { + this.firstName = firstName; + this.lastName = lastName; +} + +const lydia = new Person('Lydia', 'Hallie'); +const sarah = Person('Sarah', 'Smith'); + +console.log(lydia); +console.log(sarah); +``` + +- A: `Person {firstName: "Lydia", lastName: "Hallie"}` and `undefined` +- B: `Person {firstName: "Lydia", lastName: "Hallie"}` and `Person {firstName: "Sarah", lastName: "Smith"}` +- C: `Person {firstName: "Lydia", lastName: "Hallie"}` and `{}` +- D: `Person {firstName: "Lydia", lastName: "Hallie"}` and `ReferenceError` + +
Odpowiedź +

+ +#### Odpowiedź: A + +Dla `sarah`, nie użyliśmy słowa kluczowego `new`. Kiedy używamy `new`, `this` odwołuje się do nowego pustego obiektu, który tworzymy. Jednak jeśli nie dodajemy `new`, `this` odwołuje się do **globalnego obiektu**! + +Mówiliśmy, że `this.firstName` równa się `"Sarah"`, a `this.lastName` równa się `"Smith"`. Czyli faktycznie zdefiniowaliśmy `global.firstName = 'Sarah'` i `global.lastName = 'Smith'`. `sarah` pozostaje `undefined`, ponieważ nie zwracaliśmy żadnej wartości z funkcji `Person`. + +

+
+ +--- + +###### 13. Jakie są trzy fazy propagacji zdarzeń? + +- A: Target > Capturing > Bubbling +- B: Bubbling > Target > Capturing +- C: Target > Bubbling > Capturing +- D: Capturing > Target > Bubbling + +
Odpowiedź +

+ +#### Odpowiedź: D + +W fazie **capturing (przechwytywanie)**, zdarzenie przechodzi przez elementy nadrzędne w doł do elementu docelowego. Następnie dociera do elementu **target (cel)** i rozpoczyna się **bubbling (bąbelkowanie)**. + + + +

+
+ +--- + +###### 14. Wszystkie obiekty mają prototypy. + +- A: true +- B: false + +
Odpowiedź +

+ +#### Odpowiedź: B + +Wszystkie obiekty mają prototypy, z wyjątkiem **obiektu bazowego**. Obiekt bazowy jest obiektem utworzonym przez użytkownika lub obiektem utworzonym przy użyciu słowa kluczowego `new`. Obiekt bazowy ma dostęp do niektórych metod i właściwości, takich jak `.toString`. Jest to powód, dla którego można używać wbudowanych metod JavaScript! Wszystkie takie metody są dostępne w prototypie. Chociaż JavaScript nie może znaleźć ich bezpośrednio w twoim obiekcie, przechodzi w dół łańcucha prototypów i je tam znajduje, co czyni je dostępnymi dla ciebie. + +

+
+ +--- + +###### 15. Jaki jest wynik? + +```javascript +function sum(a, b) { + return a + b; +} + +sum(1, '2'); +``` + +- A: `NaN` +- B: `TypeError` +- C: `"12"` +- D: `3` + +
Odpowiedź +

+ +#### Odpowiedź: C + +JavaScript jest językiem **dynamicznie typowanym**: nie określamy typów niektórych zmiennych. Wartości mogą być automatycznie konwertowane na inny typ bez wiedzy użytkownika, co nazywa się _implicit type coercion_. **Koercja (Wymuszenie)** to konwersja z jednego typu na inny. + +W tym przykładzie JavaScript konwertuje liczbę `1` na string, aby funkcja miała sens i zwróciła wartość. Podczas dodawania typu liczbowego (`1`) i typu łańcuchowego (`'2'`), liczba traktowana jest jako string. Możemy łączyć stringi takie jak `"Hello" + "World"`, więc to co się tutaj dzieje to `"1" + "2"`, które zwraca `"12"`. + +

+
+ +--- + +###### 16. Jaki jest wynik? + +```javascript +let number = 0; +console.log(number++); +console.log(++number); +console.log(number); +``` + +- A: `1` `1` `2` +- B: `1` `2` `2` +- C: `0` `2` `2` +- D: `0` `1` `2` + +
Odpowiedź +

+ +#### Odpowiedź: C + +Operator jednoargumentowy **Postfix** `++`: + +1. Zwraca wartość (ten zwraca `0`) +2. Zwiększa wartość (liczba wynosi teraz `1`) + +Operator jednoargumentowy **Prefix** `++`: + +1. Zwiększa wartość (liczba wynosi teraz `2`) +2. Zwraca wartość (to zwraca `2`) + +number zwraca `0 2 2`. + +

+
+ +--- + +###### 17. Jaki jest wynik? + +```javascript +function getPersonInfo(one, two, three) { + console.log(one); + console.log(two); + console.log(three); +} + +const person = 'Lydia'; +const age = 21; + +getPersonInfo`${person} is ${age} years old`; +``` + +- A: `"Lydia"` `21` `["", " is ", " years old"]` +- B: `["", " is ", " years old"]` `"Lydia"` `21` +- C: `"Lydia"` `["", " is ", " years old"]` `21` + +
Odpowiedź +

+ +#### Odpowiedź: B + +W przypadku użycia `template strings`, wartością pierwszego argumentu jest zawsze tablica wartości łańcuchowych (string). Pozostałe argumenty otrzymują wartości przekazanych wyrażeń! + +

+
+ +--- + +###### 18. Jaki jest wynik? + +```javascript +function checkAge(data) { + if (data === { age: 18 }) { + console.log('You are an adult!'); + } else if (data == { age: 18 }) { + console.log('You are still an adult.'); + } else { + console.log(`Hmm.. You don't have an age I guess`); + } +} + +checkAge({ age: 18 }); +``` + +- A: `You are an adult!` +- B: `You are still an adult.` +- C: `Hmm.. You don't have an age I guess` + +
Odpowiedź +

+ +#### Odpowiedź: C + +Podczas testowania równości, liczby i ciągi znaków są porównywane przez ich _wartości_, a obiekty są porównywane przez ich _referencję_. JavaScript sprawdza, czy obiekty mają odwołanie do tej samej lokalizacji w pamięci. + +Dwa obiekty, które porównujemy, nie mają tej samej lokalizacji w pamięci: obiekt, który przekazujemy jako parametr, odwołuje się do innej lokalizacji w pamięci niż obiekt, którego użyliśmy do sprawdzenia równości. + +Dlatego też zarówno `{ age: 18 } == { age: 18 }` i `{ age: 18 } == { age: 18 }` zwracają `false`. + +

+
+ +--- + +###### 19. Jaki jest wynik? + +```javascript +function getAge(...args) { + console.log(typeof args); +} + +getAge(21); +``` + +- A: `"number"` +- B: `"array"` +- C: `"object"` +- D: `"NaN"` + +
Odpowiedź +

+ +#### Odpowiedź: C + +Parametr reszty (`...args`) pozwala nam "zbierać" wszystkie pozostałe argumenty do tablicy. Tablica to obiekt, więc `typeof args` zwraca `"object"`. + +

+
+ +--- + +###### 20. Jaki jest wynik? + +```javascript +function getAge() { + 'use strict'; + age = 21; + console.log(age); +} + +getAge(); +``` + +- A: `21` +- B: `undefined` +- C: `ReferenceError` +- D: `TypeError` + +
Odpowiedź +

+ +#### Odpowiedź: C + +Dzięki `"use strict"` możesz upewnić się, że przypadkowo nie zadeklarujesz zmiennych globalnych. Nigdy nie zadeklarowaliśmy zmiennej `age`, a ponieważ używamy `"use strict"`, zostanie zgłoszony błąd referencji. Gdybyśmy nie użyli `"use strict"`, to by zadziałało, ponieważ właściwość `age` zostałaby dodana do obiektu globalnego. + +

+
\ No newline at end of file From 37b5f334ff9f372f8f35ecf673ea9a8a81c52832 Mon Sep 17 00:00:00 2001 From: Gary Chen Date: Tue, 27 Jun 2023 14:57:45 +0800 Subject: [PATCH 154/193] fix: fix typos in Chinese docs --- zh-CN/README-zh_CN.md | 12 ++++++------ zh-TW/README_zh-TW.md | 16 ++++++++-------- 2 files changed, 14 insertions(+), 14 deletions(-) diff --git a/zh-CN/README-zh_CN.md b/zh-CN/README-zh_CN.md index 59ae585e..12b932e5 100644 --- a/zh-CN/README-zh_CN.md +++ b/zh-CN/README-zh_CN.md @@ -2519,7 +2519,7 @@ console.log(list) #### 答案: C -数组元素可以包含任何值。 数字,字符串,布尔值,对象,数组,`null`,`undeifned`,以及其他表达式,如日期,函数和计算。 +数组元素可以包含任何值。 数字,字符串,布尔值,对象,数组,`null`,`undefined`,以及其他表达式,如日期,函数和计算。 元素将等于返回的值。 `1 + 2`返回`3`,`1 * 2`返回'2`,'1 / 2`返回`0.5`。 @@ -3404,7 +3404,7 @@ console.log(colorConfig.colors[1]) 在 JavaScript 中,我们有两种访问对象属性的方法:括号表示法或点表示法。 在此示例中,我们使用点表示法(`colorConfig.colors`)代替括号表示法(`colorConfig [“ colors”]`)。 -使用点表示法,JavaScript 会尝试使用该确切名称在对象上查找属性。 在此示例中,JavaScript 尝试在 colorconfig 对象上找到名为 colors 的属性。 没有名为 “colors” 的属性,因此返回 “undefined”。 +使用点表示法,JavaScript 会尝试使用该确切名称在对象上查找属性。 在此示例中,JavaScript 尝试在 colorConfig 对象上找到名为 colors 的属性。 没有名为 “colors” 的属性,因此返回 “undefined”。 然后,我们尝试使用`[1]`访问第一个元素的值。 我们无法对未定义的值执行此操作,因此会抛出`Cannot read property '1' of undefined`。 JavaScript 解释(或取消装箱)语句。 当我们使用方括号表示法时,它会看到第一个左方括号`[`并一直进行下去,直到找到右方括号`]`。 只有这样,它才会评估该语句。 如果我们使用了 colorConfig [colors [1]],它将返回 colorConfig 对象上 red 属性的值。 @@ -3996,7 +3996,7 @@ async function* range(start, end) { #### 答案: C -我们给 函数 range 传递: `Promise{1}`, `Promise{2}`, `Promise{3}`,Generator 函数 `range` 返回一个全是 async object promise 数组。我们将 async object 赋值给变量 `gen`,之后我们使用`for await ... of` 进行循环遍历。我们将返回的 Promise 实例赋值给 `item`: 第一个返回 `Promise{1}`, 第二个返回 `Promise{2}`,之后是 `Promise{3}`。因为我们正 _awaiting_ `item` 的值,resolved 状态的 promsie,promise 数组的 resolved _值_ 以此为: `1`,`2`,`3`. +我们给 函数 range 传递: `Promise{1}`, `Promise{2}`, `Promise{3}`,Generator 函数 `range` 返回一个全是 async object promise 数组。我们将 async object 赋值给变量 `gen`,之后我们使用`for await ... of` 进行循环遍历。我们将返回的 Promise 实例赋值给 `item`: 第一个返回 `Promise{1}`, 第二个返回 `Promise{2}`,之后是 `Promise{3}`。因为我们正 _awaiting_ `item` 的值,resolved 状态的 promise,promise 数组的 resolved _值_ 以此为: `1`,`2`,`3`.

@@ -4060,7 +4060,7 @@ console.log(getFine(130, 300)) #### 答案: B -通过方法 `Intl.NumberFormat`,我们可以格式化任意区域的数字值。我们对数字值 `130` 进行 `mile-per-hour` 作为 `unit` 的 `en-US` 区域 格式化,结果为 `130 mph`。对数字值 `300` 进行 `USD` 作为 `currentcy` 的 `en-US` 区域格式化,结果为 `$300.00`. +通过方法 `Intl.NumberFormat`,我们可以格式化任意区域的数字值。我们对数字值 `130` 进行 `mile-per-hour` 作为 `unit` 的 `en-US` 区域 格式化,结果为 `130 mph`。对数字值 `300` 进行 `USD` 作为 `currency` 的 `en-US` 区域格式化,结果为 `$300.00`.

@@ -4612,7 +4612,7 @@ console.log(person.hobbies); 然后,我们调用函数 `addHobby`,并给 `hobby` 传递 `"dancing"`。我们不向 `hobbies` 传递值,因此它获取其默认值 —— 对象 `person` 的 属性 `hobbies`。我们向数组 `person.hobbies` push `dancing`。 -最后,我们调用函数 `addHobby`,并向 `hobby` 传递 值 `"bdaking"`,并且向 `hobbies` 传递 `person.hobbies`。我们向数组 `person.hobbies` push `dancing`。 +最后,我们调用函数 `addHobby`,并向 `hobby` 传递 值 `"baking"`,并且向 `hobbies` 传递 `person.hobbies`。我们向数组 `person.hobbies` push `dancing`。 pushing `dancing` 和 `baking` 之后,`person.hobbies` 的值为 `["coding", "dancing", "baking"]` @@ -4678,7 +4678,7 @@ const emojis = ["🎄", "🎅🏼", "🎁", "⭐"]; #### 答案: D -`const` 关键字意味着我们不能 _重定义_ 变量中的值,它 _仅可读_。而然,值本身不可修改。数组 `emojis` 中的值可被修改,如 push 新的值,拼接,又或者将数组的长度设置为 0。 +`const` 关键字意味着我们不能 _重定义_ 变量中的值,它 _仅可读_。然而,值本身不可修改。数组 `emojis` 中的值可被修改,如 push 新的值,拼接,又或者将数组的长度设置为 0。

diff --git a/zh-TW/README_zh-TW.md b/zh-TW/README_zh-TW.md index 5a2765a7..08c171df 100644 --- a/zh-TW/README_zh-TW.md +++ b/zh-TW/README_zh-TW.md @@ -1628,7 +1628,7 @@ console.log(myCar.make); #### 答案: B -當您回傳屬性(property) 時,該屬性的值等於 _returned_ 的值,而不是在函式建構式(constructor function)中設置的值。 我們回傳字串 `Maserati`,因此 `mycar.make` 等於 `Maserati`。 +當您回傳屬性(property) 時,該屬性的值等於 _returned_ 的值,而不是在函式建構式(constructor function)中設置的值。 我們回傳字串 `Maserati`,因此 `myCar.make` 等於 `Maserati`。

@@ -1803,7 +1803,7 @@ console.log(delete age); `delete` 運算子會回傳一個布林值: 成功刪除物件的情況下會回傳 `true`,反之則為 `false`。 但是經由 `var`,`const` 或是 `let` 關鍵字所宣告的變數是無法使用 `delete` 運算子刪除的。 -此處, `name` 無法成功刪除且會回傳 `fasle`,因為它是經由 `const` 所宣告。當我們宣告 `age` 的值為 `21` 時,實際上我們做的是將一個名為 `age` 的屬性為添加到了全球物件中,您可以透過 `delete` 來刪除物件中的屬性,因此您也能刪除全球物件中的屬性,故將回傳 `true`。 +此處, `name` 無法成功刪除且會回傳 `false`,因為它是經由 `const` 所宣告。當我們宣告 `age` 的值為 `21` 時,實際上我們做的是將一個名為 `age` 的屬性為添加到了全球物件中,您可以透過 `delete` 來刪除物件中的屬性,因此您也能刪除全球物件中的屬性,故將回傳 `true`。

@@ -2546,7 +2546,7 @@ console.log(list) #### 答案: C -陣列元素可以包含任何值。數字,字符,布林,物件,陣列,`null`,`undeifned`, 以及其他表達式,如日期,函數和計算式。 +陣列元素可以包含任何值。數字,字符,布林,物件,陣列,`null`,`undefined`, 以及其他表達式,如日期,函數和計算式。 元素將等於回傳的值。 `1 + 2`回傳`3`,`1 * 2`回傳'2`,'1 / 2`回傳`0.5`。 @@ -3407,7 +3407,7 @@ console.log(colorConfig.colors[1]) 在JavaScript中,我們有兩種存取物件屬性的方法:括號表示法或點表示法。在此範例中,我們使用點表示法(`colorConfig.colors`)代替括號表示法(`colorConfig [“ colors”]`)。 -使用點表示法,JavaScript會嘗試使用該確切名稱在物件上查找屬性。在此範例中,JavaScript嘗試在colorconfig物件上找到名為colors的屬性。沒有名為“colors”的屬性,因此得到“undefined”。 +使用點表示法,JavaScript會嘗試使用該確切名稱在物件上查找屬性。在此範例中,JavaScript嘗試在colorConfig物件上找到名為colors的屬性。沒有名為“colors”的屬性,因此得到“undefined”。 然後,我們嘗試使用`[1]`存取第一個元素的值。我們無法對未定義的值執行此操作,因此會拋出`Cannot read property '1' of undefined`。 JavaScript解釋(或取消裝箱)語句。當我們使用中括號表示法時,它會看到第一個左方括號`[`並一直進行下去,直到找到右方括號`]`。只有這樣,它才會評估該語句。如果我們使用了colorConfig [colors [1]],它將得到colorConfig物件上red屬性的值。 @@ -3982,7 +3982,7 @@ async function* range(start, end) { #### 答案: C -我們給 函數range 傳遞: `Promise{1}`, `Promise{2}`, `Promise{3}`,Generator 函數 `range` 回傳一個全是 async object promise 陣列。我們將 async object 賦值給變數 `gen`,之後我們使用`for await ... of` 進行循環遍歷。我們將回傳的 Promise 實例賦值給 `item`: 第一個回傳 `Promise{1}`, 第二個回傳 `Promise{2}`,之後是 `Promise{3}`。因為我們正 _awaiting_ `item` 的值,resolved 狀態的 promsie,promise陣列的resolved _值_ 以此為: `1`,`2`,`3`. +我們給 函數range 傳遞: `Promise{1}`, `Promise{2}`, `Promise{3}`,Generator 函數 `range` 回傳一個全是 async object promise 陣列。我們將 async object 賦值給變數 `gen`,之後我們使用`for await ... of` 進行循環遍歷。我們將回傳的 Promise 實例賦值給 `item`: 第一個回傳 `Promise{1}`, 第二個回傳 `Promise{2}`,之後是 `Promise{3}`。因為我們正 _awaiting_ `item` 的值,resolved 狀態的 promise,promise陣列的resolved _值_ 以此為: `1`,`2`,`3`.

@@ -4044,7 +4044,7 @@ console.log(getFine(130, 300)) #### 答案: B -通過函數 `Intl.NumberFormat`,我們可以格式化任意區域的數字值。我們對數字值 `130` 進行 `mile-per-hour` 作為 `unit` 的 `en-US` 區域 格式化,結果為 `130 mph`。對數字值 `300` 進行 `USD` 作為 `currentcy` 的 `en-US` 區域格式化,結果為 `$300.00`. +通過函數 `Intl.NumberFormat`,我們可以格式化任意區域的數字值。我們對數字值 `130` 進行 `mile-per-hour` 作為 `unit` 的 `en-US` 區域 格式化,結果為 `130 mph`。對數字值 `300` 進行 `USD` 作為 `currency` 的 `en-US` 區域格式化,結果為 `$300.00`.

@@ -4596,7 +4596,7 @@ console.log(person.hobbies); 然後,我們呼叫函數 `addHobby`,並給 `hobby` 傳遞 `"dancing"`。我們不向 `hobbies` 傳遞值,因此它獲取其預設值 —— 物件 `person` 的 屬性 `hobbies`。我們向陣列 `person.hobbies` push `dancing`。 -最後,我們呼叫函數 `addHobby`,並向 `hobby` 傳遞 值 `"bdaking"`,並且向 `hobbies` 傳遞 `person.hobbies`。我們向陣列 `person.hobbies` push `dancing`。 +最後,我們呼叫函數 `addHobby`,並向 `hobby` 傳遞 值 `"baking"`,並且向 `hobbies` 傳遞 `person.hobbies`。我們向陣列 `person.hobbies` push `dancing`。 pushing `dancing` 和 `baking` 之後,`person.hobbies` 的值為 `["coding", "dancing", "baking"]` @@ -4662,7 +4662,7 @@ const emojis = ["🎄", "🎅🏼", "🎁", "⭐"]; #### 答案: D -`const` 關鍵字意味著我們不能 _重定義_ 變數中的值,它 _僅可讀_。而然,值本身不可修改。陣列 `emojis` 中的值可被修改,如 push 新的值, 拼接,又或者將陣列的長度設置為0。 +`const` 關鍵字意味著我們不能 _重定義_ 變數中的值,它 _僅可讀_。然而,值本身不可修改。陣列 `emojis` 中的值可被修改,如 push 新的值, 拼接,又或者將陣列的長度設置為0。

From 85f95dcfb3a592193c684080d0f9a9da34f7aebb Mon Sep 17 00:00:00 2001 From: Lukasz Jasionowski Date: Tue, 27 Jun 2023 22:13:20 +0200 Subject: [PATCH 155/193] Add 10 translated questions | Total translated: 30 --- pl-PL/README.md | 293 +++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 292 insertions(+), 1 deletion(-) diff --git a/pl-PL/README.md b/pl-PL/README.md index 36c7f0c8..bb98fc6f 100644 --- a/pl-PL/README.md +++ b/pl-PL/README.md @@ -4,7 +4,7 @@ --- -Publikuję pytania wielokrotnego wyboru dotyczące JavaScriptu na swoich [Instagram](https://www.instagram.com/theavocoder) **stories**, które również zamieszczę tutaj! Ostatnia aktualizacja: 26 Czerwca +Publikuję pytania wielokrotnego wyboru dotyczące JavaScriptu na swoich [Instagram](https://www.instagram.com/theavocoder) **stories**, które również zamieszczę tutaj! Ostatnia aktualizacja: 27 Czerwca Od podstawowych do zaawansowanych: sprawdź, jak dobrze znasz JavaScript, odśwież swoją wiedzę lub przygotuj się do rozmowy kwalifikacyjnej! :muscle: :rocket: Regularnie aktualizuję to repozytorium nowymi pytaniami. Odpowiedzi znajdują się w ukrytych zakładkach poniżej pytań - po prostu kliknij, aby je rozwinięć. To dla zabawy, powodzenia! :heart: @@ -663,5 +663,296 @@ getAge(); Dzięki `"use strict"` możesz upewnić się, że przypadkowo nie zadeklarujesz zmiennych globalnych. Nigdy nie zadeklarowaliśmy zmiennej `age`, a ponieważ używamy `"use strict"`, zostanie zgłoszony błąd referencji. Gdybyśmy nie użyli `"use strict"`, to by zadziałało, ponieważ właściwość `age` zostałaby dodana do obiektu globalnego. +

+
+ +--- + +###### 21. Jaka jest wartość `sum`? + +```javascript +const sum = eval('10*10+5'); +``` + +- A: `105` +- B: `"105"` +- C: `TypeError` +- D: `"10*10+5"` + +
Odpowiedź +

+ +#### Odpowiedź: A + +`eval` oblicza kod, który przekazywany jest jako ciąg znaków. Jeśli jest to wyrażenie, tak jak w tym przypadku, oblicza ono wyrażenie. Wyrażenie to `10 * 10 + 5`. Zwraca liczbę `105`. + +

+
+ +--- + +###### 22. Jak długo cool_secret jest dostępny? + +```javascript +sessionStorage.setItem('cool_secret', 123); +``` + +- A: Dane nigdy nie zostaną utracone. +- B: Gdy użytkownik zamyka kartę. +- C: Gdy użytkownik zamyka cały przeglądarkę, a nie tylko kartę. +- D: Gdy użytkownik wyłącza swój komputer. + +
Odpowiedź +

+ +#### Odpowiedź: B + +Dane przechowywane w `sessionStorage` są usuwane po zamknięciu _zakładki_. + +Gdybyś użył `localStorage`, dane pozostałyby tam na zawsze, chyba że na przykład wywołano by `localStorage.clear()`. + +

+
+ +--- + +###### 23. Jaki jest wynik? + +```javascript +var num = 8; +var num = 10; + +console.log(num); +``` + +- A: `8` +- B: `10` +- C: `SyntaxError` +- D: `ReferenceError` + +
Odpowiedź +

+ +#### Odpowiedź: B + +Za pomocą słowa kluczowego `var` można zadeklarować wiele zmiennych o tej samej nazwie. Zmienna będzie wtedy przechowywać najnowszą wartość. + +Nie można tego zrobić za pomocą `let` lub `const`, ponieważ są one blokowe. + +

+
+ +--- + +###### 24. Jaki jest wynik? + +```javascript +const obj = { 1: 'a', 2: 'b', 3: 'c' }; +const set = new Set([1, 2, 3, 4, 5]); + +obj.hasOwnProperty('1'); +obj.hasOwnProperty(1); +set.has('1'); +set.has(1); +``` + +- A: `false` `true` `false` `true` +- B: `false` `true` `true` `true` +- C: `true` `true` `false` `true` +- D: `true` `true` `true` `true` + +
Odpowiedź +

+ +#### Odpowiedź: C + +Wszystkie klucze obiektów (z wyjątkiem symboli) są łańcuchami znaków pod względem samego obiektu, nawet jeśli nie napiszesz ich samodzielnie jako łańcucha znaków. Dlatego `obj.hasOwnProperty('1')` również zwraca true. + +Nie działa to w ten sam sposób dla zbioru. W zbiorze nie ma klucza `'1'`:`set.has('1')`, dlatego zwraca wartość false. Zawiera on liczbę całkowitą `1`, `set.has(1)` zwraca wartość true. + +

+
+ +--- + +###### 25. Jaki jest wynik? + +```javascript +const obj = { a: 'one', b: 'two', a: 'three' }; +console.log(obj); +``` + +- A: `{ a: "one", b: "two" }` +- B: `{ b: "two", a: "three" }` +- C: `{ a: "three", b: "two" }` +- D: `SyntaxError` + +
Odpowiedź +

+ +#### Odpowiedź: C + +Jeśli masz dwa klucze o takiej samej nazwie, zostanie on zastąpiony. Nadal będzie umieszczony na pierwszej pozycji, ale z ostatnią zdefiniowaną wartością. + +

+
+ +--- + +###### 26. Globalny kontekst wykonania JavaScript tworzy dwie rzeczy: obiekt globalny i słowo kluczowe "this". + +- A: true +- B: false +- C: it depends + +
Odpowiedź +

+ +#### Odpowiedź: A + +Globalny kontekst wykonania jest dostępny wszędzie w kodzie. + +

+
+ +--- + +###### 27. Jaki jest wynik? + +```javascript +for (let i = 1; i < 5; i++) { + if (i === 3) continue; + console.log(i); +} +``` + +- A: `1` `2` +- B: `1` `2` `3` +- C: `1` `2` `4` +- D: `1` `3` `4` + +
Odpowiedź +

+ +#### Odpowiedź: C + +Instrukcja `continue` pomija iterację, jeśli określony warunek zwróci `true`. + +

+
+ +--- + +###### 28. Jaki jest wynik? + +```javascript +String.prototype.giveLydiaPizza = () => { + return 'Just give Lydia pizza already!'; +}; + +const name = 'Lydia'; + +console.log(name.giveLydiaPizza()) +``` + +- A: `"Just give Lydia pizza already!"` +- B: `TypeError: not a function` +- C: `SyntaxError` +- D: `undefined` + +
Odpowiedź +

+ +#### Odpowiedź: A + +`String` jest wbudowanym konstruktorem, do którego możemy dodawać właściwości. Dodana została metoda do jego prototypu. Prymitywne ciągi znaków są automatycznie konwertowane na obiekt typu string, generowany przez funkcję prototypu ciągu znaków. Tak więc wszystkie ciągi (obiekty typu string) mają dostęp do tej metody! + +

+
+ +--- + +###### 29. Jaki jest wynik? + +```javascript +const a = {}; +const b = { key: 'b' }; +const c = { key: 'c' }; + +a[b] = 123; +a[c] = 456; + +console.log(a[b]); +``` + +- A: `123` +- B: `456` +- C: `undefined` +- D: `ReferenceError` + +
Odpowiedź +

+ +#### Odpowiedź: B + +Klucze obiektów są automatycznie konwertowane na ciągi znaków. Próbujemy ustawić obiekt jako klucz do obiektu `a`, z wartością `123`. + +Jednakże, kiedy stringujemy obiekt, staje się on `"[obiekt Object]"`. Mówimy więc, że `a["[obiekt Object]"] = 123`. Następnie próbujemy zrobić to samo. `c` jest kolejnym obiektem, który niejawnie stringujemy. Zatem `a["[obiekt Object]"] = 456`. + +Następnie wyświetlamy w konsoli `a[b]`, co w rzeczywistości jest `a["[obiekt Object]"]`, ustawiony wcześniej na `456`, więc zwraca `456`. + +

+
+ +--- + +###### 30. Jaki jest wynik? + +```javascript +const foo = () => console.log('First'); +const bar = () => setTimeout(() => console.log('Second')); +const baz = () => console.log('Third'); + +bar(); +foo(); +baz(); +``` + +- A: `First` `Second` `Third` +- B: `First` `Third` `Second` +- C: `Second` `First` `Third` +- D: `Second` `Third` `First` + +
Odpowiedź +

+ +#### Odpowiedź: B + +Mamy funkcję `setTimeout` i wywołaliśmy ją jako pierwszą. Została jednak wyświetlona jako ostatnia. + +Dzieje się tak, ponieważ w przeglądarkach mamy nie tylko silnik wykonawczy, ale także coś, co nazywa się `WebAPI`. Interfejs `WebAPI` daje nam na początek funkcję `setTimeout`. + +Po przesłaniu _callback_ do WebAPI, sama funkcja `setTimeout` (ale nie callback!) jest usuwana ze stosu. + + + +Teraz, `foo` jest wywoływane, a `"First"` jest wyświetlane. + + + +`foo` jest zdejmowane ze stosu, a `baz` jest wywoływane. "Third" zostaje wyświetlony. + + + +WebAPI nie może dodawać rzeczy do stosu, gdy jest gotowy. Zamiast tego przesuwa funkcję zwrotną do czegoś zwanego _kolejką_. + + + +W tym miejscu zaczyna działać pętla zdarzeń. **Pętla zdarzeń** patrzy na stos i kolejkę zadań. Jeśli stos jest pusty, pobiera pierwszą rzecz z kolejki i przesuwa ją na stos. + + + +`bar` zostaje wywołany, `"Second"` zostaje wyświetlony i zdjęty ze stosu. +

\ No newline at end of file From d696089b340143dc181e1f36850ecda709e2f6da Mon Sep 17 00:00:00 2001 From: Lukasz Jasionowski Date: Wed, 5 Jul 2023 19:56:27 +0200 Subject: [PATCH 156/193] Add 20 translated questions | Total translated: 50 --- pl-PL/README.md | 589 ++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 589 insertions(+) diff --git a/pl-PL/README.md b/pl-PL/README.md index bb98fc6f..9e4c01e7 100644 --- a/pl-PL/README.md +++ b/pl-PL/README.md @@ -954,5 +954,594 @@ W tym miejscu zaczyna działać pętla zdarzeń. **Pętla zdarzeń** patrzy na s `bar` zostaje wywołany, `"Second"` zostaje wyświetlony i zdjęty ze stosu. +

+
+ +--- + +###### 31. Co zostanie wyświetlone w konsoli po kliknięciu przycisku? + +```html +
+
+ +
+
+``` + +- A: Zewnętrzny `div` +- B: Wewnętrzny `div` +- C: `button` +- D: Tablica wszystkich zagnieżdżonych elementów. + +
Odpowiedź +

+ +#### Odpowiedź: C + +Najgłębiej zagnieżdżony element, który spowodował zdarzenie jest celem zdarzenia. Możesz zatrzymać bąbelkowanie poprzez `event.stopPropagation` + +

+
+ +--- + +###### 32. Co zostanie wyświetlone w konsoli po kliknięciu akapitu? + +```html +
+

+ Click here! +

+
+``` + +- A: `p` `div` +- B: `div` `p` +- C: `p` +- D: `div` + +
Odpowiedź +

+ +#### Odpowiedź: A + +Jeśli klikniemy `p`, zobaczymy dwa logi: `p` i `div`. Podczas propagacji zdarzeń istnieją 3 fazy: przechwytywanie, cel i bąbelkowanie (capturing, target, and bubbling). Domyślnie, event handlery są wykonywane w fazie bąbelkowania (chyba że ustawisz `useCapture` na `true`). Przebiega ona od najgłębiej zagnieżdżonego elementu na zewnątrz. + +

+
+ +--- + +###### 33. Jaki jest wynik? + +```javascript +const person = { name: 'Lydia' }; + +function sayHi(age) { + return `${this.name} is ${age}`; +} + +console.log(sayHi.call(person, 21)); +console.log(sayHi.bind(person, 21)); +``` + +- A: `undefined is 21` `Lydia is 21` +- B: `function` `function` +- C: `Lydia is 21` `Lydia is 21` +- D: `Lydia is 21` `function` + +
Odpowiedź +

+ +#### Odpowiedź: D + +W obu przypadkach możemy przekazać obiekt, do którego ma się odnosić słowo kluczowe `this`. Jednakże, `.call` jest _wykonywane natychmiast_! + +`.bind.` zwraca _kopię_ funkcji, ale z powiązanym kontekstem! Nie jest ona wykonywana natychmiast. + +

+
+ +--- + +###### 34. Jaki jest wynik? + +```javascript +function sayHi() { + return (() => 0)(); +} + +console.log(typeof sayHi()); +``` + +- A: `"object"` +- B: `"number"` +- C: `"function"` +- D: `"undefined"` + +
Odpowiedź +

+ +#### Odpowiedź: B + +Funkcja `sayHi` zwraca zwróconą wartość natychmiast wywołanego wyrażenia funkcyjnego (IIFE). Ta funkcja zwróciła wartość `0`, która jest typu `"number"`. + +FYI: `typeof` może zwrócić następującą listę wartości: `undefined`, `boolean`, `number`, `bigint`, `string`, `symbol`, `function` i `object`. Zauważ, że `typeof null` zwraca `"object"`. + +

+
+ +--- + +###### 35. Które z tych wartości są fałszywe? + +```javascript +0; +new Number(0); +(''); +(' '); +new Boolean(false); +undefined; +``` + +- A: `0`, `''`, `undefined` +- B: `0`, `new Number(0)`, `''`, `new Boolean(false)`, `undefined` +- C: `0`, `''`, `new Boolean(false)`, `undefined` +- D: Wszystkie są fałszywe + +
Odpowiedź +

+ +#### Odpowiedź: A + +Istnieje 8 fałszywych wartości: + +- `undefined` +- `null` +- `NaN` +- `false` +- `''` (pusty ciąg) +- `0` +- `-0` +- `0n` (BigInt(0)) + +Konstruktory funkcji, takie jak `new Number` i `new Boolean` są prawdziwe. + +

+
+ +--- + +###### 36. Jaki jest wynik? + +```javascript +console.log(typeof typeof 1); +``` + +- A: `"number"` +- B: `"string"` +- C: `"object"` +- D: `"undefined"` + +
Odpowiedź +

+ +#### Odpowiedź: B + +`typeof 1` zwraca `"number"`. +`typeof "number"` zwraca `"string"`. + +

+
+ +--- + +###### 37. Jaki jest wynik? + +```javascript +const numbers = [1, 2, 3]; +numbers[10] = 11; +console.log(numbers); +``` + +- A: `[1, 2, 3, null x 7, 11]` +- B: `[1, 2, 3, 11]` +- C: `[1, 2, 3, empty x 7, 11]` +- D: `SyntaxError` + +
Odpowiedź +

+ +#### Odpowiedź: C + +Po ustawieniu wartości elementu w tablicy, która przekracza długość tablicy, JavaScript tworzy coś, co nazywa się "pustymi slotami". W rzeczywistości mają one wartość `undefined`, ale zobaczysz coś takiego jak: + +`[1, 2, 3, puste x 7, 11]`. + +w zależności od tego, gdzie go uruchomisz (jest inny dla każdej przeglądarki, node itp.). + +

+
+ +--- + +###### 38. Jaki jest wynik? + +```javascript +(() => { + let x, y; + try { + throw new Error(); + } catch (x) { + (x = 1), (y = 2); + console.log(x); + } + console.log(x); + console.log(y); +})(); +``` + +- A: `1` `undefined` `2` +- B: `undefined` `undefined` `undefined` +- C: `1` `1` `2` +- D: `1` `undefined` `undefined` + +
Odpowiedź +

+ +#### Odpowiedź: A + +Blok `catch` otrzymuje argument `x`. Nie jest to ten sam `x` co zmienna, gdy przekazujemy argumenty. Ta zmienna `x` jest blokowa. + +Później, ustawiamy tę blokową zmienną równą `1` i ustawiamy wartość zmiennej `y`. Teraz wyświetlamy w konsoli zmienną blokową `x`, która jest równa `1`. + +Poza blokiem `catch`, `x` jest wciąż `undefined`, a `y` wynosi `2`. Gdy chcemy wykonać `console.log(x)` poza blokiem `catch`, zwraca on `undefined`, a `y` zwraca `2`. + +

+
+ +--- + +###### 39. Wszystko w JavaScript jest... + +- A: prymitywem lub obiektem +- B: funkcją lub obiektem +- C: podchwytliwe pytanie! tylko obiektem +- D: numerem lub obiektem + +
Odpowiedź +

+ +#### Odpowiedź: A + +JavaScript ma tylko prymitywne typy i obiekty. + +Typy prymitywne to `boolean`, `null`, `undefined`, `bigint`, `number`, `string` i `symbol`. + +To, co odróżnia prymityw od obiektu, to fakt, że prymitywy nie mają żadnych właściwości ani metod; zauważysz jednak, że `'foo'.toUpperCase()` wylicza `'FOO'` i nie powoduje `TypeError`. Dzieje się tak dlatego, że gdy próbujesz uzyskać dostęp do właściwości lub metody na prymitywie takim jak ciąg znaków, JavaScript niejawnie opakuje prymitywny typ za pomocą jednej z klas opakowujących, tj. `String`, a następnie natychmiast odrzuci opakowanie po ocenie wyrażenia. Wszystkie prymitywy z wyjątkiem `null` i `undefined` wykazują to zachowanie. + +

+
+ +--- + +###### 40. Jaki jest wynik? + +```javascript +[[0, 1], [2, 3]].reduce( + (acc, cur) => { + return acc.concat(cur); + }, + [1, 2], +); +``` + +- A: `[0, 1, 2, 3, 1, 2]` +- B: `[6, 1, 2]` +- C: `[1, 2, 0, 1, 2, 3]` +- D: `[1, 2, 6]` + +
Odpowiedź +

+ +#### Odpowiedź: C + +`[1, 2]` jest naszą wartością początkową. Jest to wartość, z którą zaczynamy i wartość pierwszego `acc`.Podczas pierwszej rundy, `acc` to `[1, 2]`, a `cur` to `[0, 1]`.Łączymy je, co daje `[1, 2, 0, 1]`. + +Następnie `[1, 2, 0, 1]` to `acc`, a `[2, 3]` to `cur`. Łączymy je i otrzymujemy `[1, 2, 0, 1, 2, 3]`. + +

+
+ +--- + +###### 41. Jaki jest wynik? + +```javascript +!!null; +!!''; +!!1; +``` + +- A: `false` `true` `false` +- B: `false` `false` `true` +- C: `false` `true` `true` +- D: `true` `true` `false` + +
Odpowiedź +

+ +#### Odpowiedź: B + +`null` jest fałszywe. `!null` zwraca `true`. `!true` zwraca `false`. + +`""` jest fałszywe. `!""` zwraca `true`. `!true` zwraca `false`. + +`1` jest prawdziwe. `!1` zwraca `false`. `!false` zwraca `true`. + +

+
+ +--- + +###### 42. Co zwraca metoda `setInterval` w przeglądarce? + +```javascript +setInterval(() => console.log('Hi'), 1000); +``` + +- A: unikalny identyfikator +- B: określona ilość milisekund +- C: przekazana funkcja +- D: `undefined` + +
Odpowiedź +

+ +#### Odpowiedź: A + +Zwraca unikalny identyfikator. Ten identyfikator może być użyty do wyczyszczenia tego interwału za pomocą funkcji `clearInterval()`. + +

+
+ +--- + +###### 43. Co to zwróci? + +```javascript +[...'Lydia']; +``` + +- A: `["L", "y", "d", "i", "a"]` +- B: `["Lydia"]` +- C: `[[], "Lydia"]` +- D: `[["L", "y", "d", "i", "a"]]` + +
Odpowiedź +

+ +#### Odpowiedź: A + +Łańcuch znaków jest iterowalny. Operator spread odwzorowuje każdy znak iterable na jeden element. + +

+
+ +--- + +###### 44. Jaki jest wynik? + +```javascript +function* generator(i) { + yield i; + yield i * 2; +} + +const gen = generator(10); + +console.log(gen.next().value); +console.log(gen.next().value); +``` + +- A: `[0, 10], [10, 20]` +- B: `20, 20` +- C: `10, 20` +- D: `0, 10 and 10, 20` + +
Odpowiedź +

+ +#### Odpowiedź: C + +Zwykłe funkcje nie mogą zostać zatrzymane w połowie wywoływania. Jednak funkcja generatora może zostać "zatrzymana" w połowie, a następnie kontynuować od miejsca, w którym się zatrzymała. Za każdym razem, gdy funkcja generująca napotka słowo kluczowe `yield`, funkcja zwraca wartość określoną po nim. + +Najpierw inicjalizujemy funkcję generatora z `i` równym `10`. Wywołujemy funkcję generatora za pomocą metody `next()`. Przy pierwszym wywołaniu funkcji generatora, `i` jest równe `10`. Funkcja napotyka pierwsze słowo kluczowe `yield`: zwraca wartość `i`. Generator jest teraz "wstrzymany", a wartość `10` zostaje zarejestrowana. + +Następnie ponownie wywołujemy funkcję za pomocą metody `next()`. Kontynuuje ona tam, gdzie zatrzymała się poprzednio, wciąż z `i` równym `10`. Teraz napotyka następne słowo kluczowe `yield` i zwraca `i * 2`. `i` jest równe `10`, więc zwraca `10 * 2`, czyli `20`. Wynikiem jest `10, 20`. + +

+
+ +--- + +###### 45. Co to zwróci? + +```javascript +const firstPromise = new Promise((res, rej) => { + setTimeout(res, 500, 'one'); +}); + +const secondPromise = new Promise((res, rej) => { + setTimeout(res, 100, 'two'); +}); + +Promise.race([firstPromise, secondPromise]).then(res => console.log(res)); +``` + +- A: `"one"` +- B: `"two"` +- C: `"two" "one"` +- D: `"one" "two"` + +
Odpowiedź +

+ +#### Odpowiedź: B + +Kiedy przekazujemy wiele 'promise' do metody `Promise.race`, rozwiązuje ona/odrzuca _pierwszą_ 'promise'. Do metody `setTimeout` przekazujemy timer: 500ms dla `firstPromise` i 100ms dla `secondPromise`. Oznacza to, że `secondPromise` zostanie rozwiązana jako pierwsza z wartością `'two'`. `res` przechowuje teraz wartość `'two'`, która jest wyświetlona w konsoli. + +

+
+ +--- + +###### 46. Jaki jest wynik? + +```javascript +let person = { name: 'Lydia' }; +const members = [person]; +person = null; + +console.log(members); +``` + +- A: `null` +- B: `[null]` +- C: `[{}]` +- D: `[{ name: "Lydia" }]` + +
Odpowiedź +

+ +#### Odpowiedź: D + +Najpierw deklarujemy zmienną `person` z wartością obiektu, który ma właściwość `name`. + + + +Następnie deklarujemy zmienną o nazwie `members`. Ustawiamy pierwszy element tej tablicy równy wartości zmiennej `person`. Obiekty oddziałują na siebie poprzez _referencję_, gdy ustawiamy je równe sobie. Kiedy przypisujesz referencję z jednej zmiennej do drugiej, tworzysz _kopię_ tej referencji. (Zauważ, że nie mają one _tej samej_ referencji!). + + + +Następnie ustawiamy zmienną `person` równą `null`. + + + +Modyfikujemy tylko wartość zmiennej `person`, a nie pierwszy element w tablicy, ponieważ ten element ma inną (skopiowaną) referencję do obiektu. Pierwszy element w `members` wciąż posiada referencję do oryginalnego obiektu. Kiedy wyświetlamy tablicę `members`, pierwszy element nadal przechowuje wartość obiektu, który jest wyświetlany. + +

+
+ +--- + +###### 47. Jaki jest wynik? + +```javascript +const person = { + name: 'Lydia', + age: 21, +}; + +for (const item in person) { + console.log(item); +} +``` + +- A: `{ name: "Lydia" }, { age: 21 }` +- B: `"name", "age"` +- C: `"Lydia", 21` +- D: `["name", "Lydia"], ["age", 21]` + +
Odpowiedź +

+ +#### Odpowiedź: B + +Za pomocą pętli `for-in` możemy iterować po kluczach obiektów, w tym przypadku `name` i `age`. Klucze obiektów są łańcuchami (jeśli nie są symbolami). W każdej pętli ustawiamy wartość `item` równą bieżącemu kluczowi, który iterujemy. Najpierw `item` jest równy `name`. Następnie, `item` jest równy `age`. + +

+
+ +--- + +###### 48. Jaki jest wynik? + +```javascript +console.log(3 + 4 + '5'); +``` + +- A: `"345"` +- B: `"75"` +- C: `12` +- D: `"12"` + +
Odpowiedź +

+ +#### Odpowiedź: B + +Asocjatywność operatorów to kolejność, w jakiej kompilator ocenia wyrażenia, od lewej do prawej lub od prawej do lewej. Dzieje się tak tylko wtedy, gdy wszystkie operatory mają _takie samo_ pierwszeństwo. Mamy tylko jeden typ operatora: `+`. Dla dodawania, asocjatywność jest od lewej do prawej. + +`3 + 4` jest obliczane jako pierwsze. Wynikiem jest liczba `7`. + +`7 + '5'` skutkuje `"75"` z powodu przymusu. JavaScript konwertuje liczbę `7` na ciąg znaków, patrz pytanie 15. Możemy połączyć dwa ciągi znaków za pomocą operatora `+`. "7" + "5"` daje w wyniku "75"`. + +

+
+ +--- + +###### 49. Jaka jest wartość `num`? + +```javascript +const num = parseInt('7*6', 10); +``` + +- A: `42` +- B: `"42"` +- C: `7` +- D: `NaN` + +
Odpowiedź +

+ +#### Odpowiedź: C + +Zwracana jest tylko pierwsza liczba w łańcuchu. W oparciu o _radix_ (drugi argument w celu określenia typu liczby, którą chcemy przetworzyć: podstawa 10, szesnastkowy, ósemkowy, binarny itp.), `parseInt` sprawdza, czy znaki w łańcuchu są prawidłowe. Gdy napotka znak, który nie jest prawidłową liczbą w radix, zatrzymuje parsowanie i ignoruje następujące znaki. + +`*` nie jest prawidłową liczbą. Przetwarza tylko `"7"` na dziesiętne `7`. `num` posiada teraz wartość `7`. + +

+
+ +--- + +###### 50. Jaki jest wynik? + +```javascript +[1, 2, 3].map(num => { + if (typeof num === 'number') return; + return num * 2; +}); +``` + +- A: `[]` +- B: `[null, null, null]` +- C: `[undefined, undefined, undefined]` +- D: `[ 3 x empty ]` + +
Odpowiedź +

+ +#### Odpowiedź: C + +Podczas mapowania tablicy, wartość `num` jest równa elementowi, nad którym aktualnie wykonywana jest pętla. W tym przypadku elementami są liczby, więc warunek instrukcji if `typeof num == "number"` zwraca `true`. Funkcja map tworzy nową tablicę i wstawia do niej wartości zwrócone przez funkcję. + +Nie zwracamy jednak żadnej wartości. Gdy nie zwracamy wartości z funkcji, funkcja zwraca `undefined`. Dla każdego elementu w tablicy wywoływany jest blok funkcji, więc dla każdego elementu zwracamy `undefined`. +

\ No newline at end of file From 05b485ff4fa20418abc813513b79c02721464b37 Mon Sep 17 00:00:00 2001 From: Aaditya Bhusal <46737849+aadityabhusal@users.noreply.github.com> Date: Sun, 9 Jul 2023 10:55:29 +0530 Subject: [PATCH 157/193] updates the answer reasoning of question 53 --- README.md | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index c5011bc9..80c8d584 100644 --- a/README.md +++ b/README.md @@ -1646,7 +1646,9 @@ console.log(myCar.make); #### Answer: B -When you return a property, the value of the property is equal to the _returned_ value, not the value set in the constructor function. We return the string `"Maserati"`, so `myCar.make` is equal to `"Maserati"`. +When a constructor function is called with the `new` keyword, it creates an object and sets the `this` keyword to refer to that object. By default, if the constructor function doesn't explicitly return anything, it will return the newly created object. + +In this case, the constructor function `Car` explicitly returns a new object with `make` set to `"Maserati"`, which overrides the default behavior. Therefore, when `new Car()` is called, the _returned_ object is assigned to `myCar`, resulting in the output being `"Maserati"` when `myCar.make` is accessed.

From 81b18decf8663ea29f73a6b6c5319530100dfbc1 Mon Sep 17 00:00:00 2001 From: Elasmai Elmehdi Date: Mon, 24 Jul 2023 14:27:22 +0100 Subject: [PATCH 158/193] Update README_fr-FR.md [Wording] Replace the word "and" with "et" --- fr-FR/README_fr-FR.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/fr-FR/README_fr-FR.md b/fr-FR/README_fr-FR.md index eb695160..1a15ee00 100644 --- a/fr-FR/README_fr-FR.md +++ b/fr-FR/README_fr-FR.md @@ -780,7 +780,7 @@ Si vous avez deux clés portant le même nom, la clé sera remplacée. Elle sera --- -###### 26. Le contexte global d'exécution de JavaScript crée 2 choses pour vous : l'objet global and le mot-clé `this`. +###### 26. Le contexte global d'exécution de JavaScript crée 2 choses pour vous : l'objet global et le mot-clé `this`. - A: Vrai - B: Faux From a03f41086c5de809c0b7b9b046f37c9103cf6990 Mon Sep 17 00:00:00 2001 From: Egzona Vllasaliu Date: Sun, 30 Jul 2023 01:47:08 +0200 Subject: [PATCH 159/193] Add support for Kosovar/Albanian localization SHQIP Hello, I hope this message finds you well. I'm excited to contribute to this amazing project. Being a native speaker of Albanian language called (SHQIP - sq), I've noticed that our language wasn't supported in the current version of the project. To make this project more inclusive and accessible to the speakers of Kosova/Albania, I've decided to add localization support for my native language. In this pull request, I have: 1. Added Shqip translation files to the directory. 2. Updated the documentation to reflect this new language addition. I believe that adding Shqip to the list of supported languages will make this project even more useful to a wider audience. I look forward to your feedback and hope for the successful merger of this contribution. Please feel free to suggest any changes or improvements. Thank you for considering this request. --- sq-KS/README_sq_KS.md | 5145 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 5145 insertions(+) create mode 100644 sq-KS/README_sq_KS.md diff --git a/sq-KS/README_sq_KS.md b/sq-KS/README_sq_KS.md new file mode 100644 index 00000000..5a0c05cc --- /dev/null +++ b/sq-KS/README_sq_KS.md @@ -0,0 +1,5145 @@ +
+ +

Pyetje Javascript

+ +--- + +Pyetjet të cilat mund të kenë më shumë se një përgjigje të saktë postohen në **storie** në këtë [Instagram](https://www.instagram.com/theavocoder), të cilat do të postohen edhe këtu! Përditësimi i fundit: 12 Qershor + +Nga konceptet bazike tek ato të avancuara: testo se sa mirë e njeh JavaScript-in, freskoni sado pak njohuritë e juaja ose edhe përgatitu për intervisten tuaj të ardhshme! 💪 🚀! Përgjigjet gjenden në **seksionet e mbyllura** përfundi pyetjeve, thjesht kliko mbi to për të hapur seksionin e përgjigjeve. Është vetëm për argëtim, paç fat! ❤️ + +Mos hezitoni të më kontaktoni! 😊 +Instagram || Twitter || LinkedIn || Blog + +
+ +| Ndjehuni të lirë të i përdorni në projektet e juaja |😃 Do të e vlerësoja shumë referencimin tuaj në ketë repositori, unë i krijoj pyetjet dhe poashtu edhe përgjigjet (lol) dhe komuniteti me ndihmon shumë të e përmirësoj dhe të mirëmbajë! 💪🏼 Faleminderit! + +--- + +
See 20 Available Translations 🇸🇦🇪🇬🇧🇦🇩🇪🇪🇸🇫🇷🇮🇩🇯🇵🇰🇷🇳🇱🇧🇷🇷🇺🇹🇭🇹🇷🇺🇦🇻🇳🇨🇳🇹🇼🇽🇰 +

+ +- [🇸🇦 العربية](./ar-AR/README_AR.md) +- [🇪🇬 اللغة العامية](./ar-EG/README_ar-EG.md) +- [🇧🇦 Bosanski](./bs-BS/README-bs_BS.md) +- [🇩🇪 Deutsch](./de-DE/README.md) +- [🇪🇸 Español](./es-ES/README-ES.md) +- [🇫🇷 Français](./fr-FR/README_fr-FR.md) +- [🇮🇩 Indonesia](./id-ID/README.md) +- [🇮🇹 Italiano](./it-IT/README.md) +- [🇯🇵 日本語](./ja-JA/README-ja_JA.md) +- [🇰🇷 한국어](./ko-KR/README-ko_KR.md) +- [🇳🇱 Nederlands](./nl-NL/README.md) +- [🇵🇱 Polski](./pl-PL/README.md) +- [🇧🇷 Português Brasil](./pt-BR/README_pt_BR.md) +- [🇷🇺 Русский](./ru-RU/README.md) +- [🇹🇭 ไทย](./th-TH/README-th_TH.md) +- [🇹🇷 Türkçe](./tr-TR/README-tr_TR.md) +- [🇺🇦 Українська мова](./uk-UA/README.md) +- [🇻🇳 Tiếng Việt](./vi-VI/README-vi.md) +- [🇨🇳 简体中文](./zh-CN/README-zh_CN.md) +- [🇹🇼 繁體中文](./zh-TW/README_zh-TW.md) +- [🇽🇰 Shqip](./sq-KS/README_sq_KS.md) + +

+
+ +--- + +###### 1. Cila është vlera e saj? + +```javascript +function sayHi() { + console.log(name); + console.log(age); + var name = 'Lydia'; + let age = 21; +} + +sayHi(); +``` + +- A: `Lydia` dhe `undefined` +- B: `Lydia` dhe `ReferenceError` +- C: `ReferenceError` dhe `21` +- D: `undefined` dhe `ReferenceError` + +
Përgjigja +

+ +#### Përgjigja: D + +Brenda funksionit, fillimisht deklarojmë variablën `name` me fjalën kyçe `var`. Kjo do të thotë se variabla ngrihet - hoistohet (hapësira e memories caktohet gjatë fazës së krijimit) me vlerën e paracaktuar `undefined`, deri sa të arrijmë në rreshtin ku e definojmë variablën. Nuk kemi definuar ende variablën në rreshtin ku përpiqemi të shfaqim variablën `name`, kështu që ajo ende mban vlerën `undefined`. + +Variablat me fjalën kyçe `let` (dhe `const`) hoistohen, por ndryshe nga `var`, nuk inicializohen. Ato nuk janë të qasshme para rreshtit ku i deklarojmë (inicializojmë) ato. Kjo quhet "zona e vdekur temporale". Kur përpiqemi të iu qasemi variablave para se ato të jenë të deklaruara, JavaScript hedh një `ReferenceError`. + +

+
+ +--- + +###### 2. Cila është vlera e saj? + +```javascript +for (var i = 0; i < 3; i++) { + setTimeout(() => console.log(i), 1); +} + +for (let i = 0; i < 3; i++) { + setTimeout(() => console.log(i), 1); +} +``` + +- A: `0 1 2` dhe `0 1 2` +- B: `0 1 2` dhe `3 3 3` +- C: `3 3 3` dhe `0 1 2` + +
Përgjigja +

+ +#### Përgjigja: C + +Për shkak të ***event queque*** në JavaScript, funksioni callback `setTimeout` thirret pas ekzekutimit të unazës. Pasi që variabla `i` në iterimin e parë u deklarua duke përdorur fjalën kyçe `var`, kjo vlerë ishte globale. Gjatë unazës, ne rritëm vlerën e `i` me `1` çdo herë, duke përdorur operatorin unar `++`. Deri në kohën që funksioni callback `setTimeout` u thirr, `i` ishte e barabartë me `3` në unazën e parë. + +Në unazën e dytë, variabla `i` u deklarua duke përdorur fjalën kyçe `let`: variablat e deklaruara me fjalën kyçe `let` (dhe `const`) janë të qasshme në bllok (një bllok është çdo gjë mes `{ }`). Gjatë çdo iteracioni, `i` do të ketë një vlerë të re, dhe çdo vlerë është e qasshme brenda unazës. + +

+
+ +--- + +###### 3. Cila është vlera e saj? + +```javascript +const shape = { + radius: 10, + diameter() { + return this.radius * 2; + }, + perimeter: () => 2 * Math.PI * this.radius, +}; + +console.log(shape.diameter()); +console.log(shape.perimeter()); +``` + +- A: `20` and `62.83185307179586` +- B: `20` and `NaN` +- C: `20` and `63` +- D: `NaN` and `63` + +
Përgjigja +

+ +#### Përgjigja: B + +Vini re se vlera e `diameter` është një funksion i zakonshëm, ndërsa vlera e `perimeter` është një funksion shigjete (arrow function). + +Në funksionet shigjeta, fjala kyçe `this` referohet në qasjen në rrethinën aktuale përreth saj, ndryshe nga funksionet e zakonshme! Kjo do të thotë se kur ne e thërrasim `perimeter`, ajo nuk referohet tek objekti shape, por tek rrethina e saj (për shembull "window"). + +`radius` nuk ka ndonjë vlerë të caktuar në atë objekt, prandaj do të kemi si rezultat `NaN`. + +

+
+ +--- + +###### 4. Cila është vlera e saj? + +```javascript ++true; +!'Lydia'; +``` + +- A: `1` and `false` +- B: `false` and `NaN` +- C: `false` and `false` + +
Përgjigja +

+ +#### Përgjigja: A + +Operatori unar `+` provon të e konvertojë operandin në numër. `true` është `1`, dhe `false` është `0`. + +Vargu i karaktereve (stringu) `'Lydia'` konsiderohet si vlerë `true`. Çfarë ne realisht po pyesim është "a është kjo vlerë e vërtetë e pavërtetë?". Kjo do të kthejë vlerën `false`. + +

+
+ +--- + +###### 5. Cila përgjigje është e saktë? + +```javascript +const bird = { + size: 'small', +}; + +const mouse = { + name: 'Mickey', + small: true, +}; +``` + +- A: `mouse.bird.size` nuk është sintaksë valide +- B: `mouse[bird.size]` nuk është sintaksë valide +- C: `mouse[bird["size"]]` nuk është sintaksë valide +- D: Të gjitha sintaksat janë valide + +
Përgjigja +

+ +#### Përgjigja: A + +Në JavaScript, të gjithë çelësat (keys) e objektit janë stringje (përveç nëse është Symbol). Edhe nëse nuk i _shkruajmë_ si stringje, ato gjithmonë konvertohen në stringje në prapavijë. + +JavaScript interpreton deklarimet. Kur përdorim notacionin e kllapave, ai shikon kllapën e parë hapëse `[` dhe vazhdon derisa të gjejë kllapën mbyllëse `]`. Vetëm atëherë do të vlerësohet deklarata (kthehet vlera e caktuar për atë deklarim). + +`mouse[bird.size]`: Fillimisht gjendet vlera e `bird.size`, e cila është `"small"`. `mouse["small"]` kthen `true` + +Megjithatë, me notacionin pikë, kjo nuk ndodh. `mouse` nuk ka një çelës të quajtur `bird`, që do të thotë se `mouse.bird` është `undefined`. Pastaj, ne kërkojmë "size" duke përdorur notacionin pikë: "mouse.bird.size". Meqenëse `mouse.bird` është `undefined`, ne në fakt po pyesim 'undefined.size'. Kjo nuk është valide dhe do të marrim një gabim të ngjashëm me `Cannot read property "size" of undefined`. + +

+
+ +--- + +###### 6. Cila është vlera e saj? + +```javascript +let c = { greeting: 'Hey!' }; +let d; + +d = c; +c.greeting = 'Hello'; +console.log(d.greeting); +``` + +- A: `Hello` +- B: `Hey!` +- C: `undefined` +- D: `ReferenceError` +- E: `TypeError` + +
Përgjigja +

+ +#### Përgjigja: A + +Në JavaScript, të gjitha objektet ndërveprojnë me _referencë_ kur i vendosin me vlera të barabarta me njëri-tjetrin. + +Fillimisht, variabla `c` mbanë vlerën për një objekt. Më vonë, ne e caktojmë `d` me të njejtën reference të cilën `c` ka tek objekti. + + + +Kur e ndryshoni një objekt, i ndryshoni të gjitha objektet. + +

+
+ +--- + +###### 7. Cila është vlera e saj? + +```javascript +let a = 3; +let b = new Number(3); +let c = 3; + +console.log(a == b); +console.log(a === b); +console.log(b === c); +``` + +- A: `true` `false` `true` +- B: `false` `false` `true` +- C: `true` `false` `false` +- D: `false` `true` `true` + +
Përgjigja +

+ +#### Përgjigja: C + +`new Number()` është konstruktor i integruar (built-in function). Edhe pse duket si një numër, nuk është në të vërtetë një numër: ai ka një mori karakteristikash shtesë dhe si rrjedhojë është një objekt. + +Kur përdorim operatorin `==` (operatorin i barazimit), ai kontrollon vetëm nëse ka të njëjtën _vlerë_. Të dy kanë vlerën `3`, kështu që kthen `true`. + +Megjithatë, kur përdorim operatorin `===` (operatori i barazisë strikte), të dy vlerat dhe tipi i tyre duhet të jenë të njëjta. Nuk është: `new Number()` nuk është një numër, është një __objekt__. Të dy kthejnë `false`. + +

+
+ +--- + +###### 8. Cila është vlera e saj? + +```javascript +class Chameleon { + static colorChange(newColor) { + this.newColor = newColor; + return this.newColor; + } + + constructor({ newColor = 'green' } = {}) { + this.newColor = newColor; + } +} + +const freddie = new Chameleon({ newColor: 'purple' }); +console.log(freddie.colorChange('orange')); +``` + +- A: `orange` +- B: `purple` +- C: `green` +- D: `TypeError` + +
Përgjigja +

+ +#### Përgjigja: D + +Funksioni `colorChange` është statik. Metodat statike janë krijuar për të "jetuar" vetëm në konstruktorin në të cilin janë krijuar dhe nuk mund t'i kalohen asnjë fëmije ose të thirren në instancat e klasës. Meqenëse `freddie` është një instancë e klasës Chameleon, funksioni nuk mund të thirret. Në këtë rast do të kthehet `TypeError`. + +

+
+ +--- + +###### 9. Cila është vlera e saj? + +```javascript +let greeting; +greetign = {}; // Typo - gabim drejtëshkrimor! +console.log(greetign); +``` + +- A: `{}` +- B: `ReferenceError: greetign is not defined` +- C: `undefined` + +
Përgjigja +

+ +#### Përgjigja: A + +Do të printojë objekt, sepse ne sapo krijuam një objekt bosh në objektin global! Kur e shkruajtëm gabim `greeting` si `greetign`, interpretuesi i JS në fakt e pa këtë si: + +1. `global.greetign = {}` në Node.js +2. `window.greetign = {}`, `frames.greetign = {}` dhe `self.greetign` në shfletues (browser). +3. `self.greetign` në web workers. +4. `globalThis.greetign` në të gjitha mjediset. + +Për të shmangur këtë, ne mund të përdorim `"use strict"`. Kjo siguron që ju të keni deklaruar një variabël përpara se ta vendosni atë të barabartë (inicializoni ndonjë variabël tjetër me vlerën e saj) me ndonjë gjë. + +

+
+ +--- + +###### 10. Çfarë do të ndodh kur e bëjmë këtë veprim? + +```javascript +function bark() { + console.log('Woof!'); +} + +bark.animal = 'dog'; +``` + +- A: Asgjë, gjithçka është në rregull! +- B: `SyntaxError`. Nuk mund të shtoni veti te një funksion në këtë mënyrë. +- C: `"Woof"` do të printohet. +- D: `ReferenceError` + +
Përgjigja +

+ +#### Përgjigja: A + +Kjo është e mundshme në JavaScript, spese funksionet janë objekte! (Gjithçka, përveç tipeve primitive janë objekte) + +Një funksion është një lloj i veçantë objekti. Kodi që shkruani vetë nuk është funksioni aktual. Funksioni është një objekt me veti. Kjo veti është e pavokueshme. + +

+
+ +--- + +###### 11. Cila është vlera e saj? + +```javascript +function Person(firstName, lastName) { + this.firstName = firstName; + this.lastName = lastName; +} + +const member = new Person('Lydia', 'Hallie'); +Person.getFullName = function() { + return `${this.firstName} ${this.lastName}`; +}; + +console.log(member.getFullName()); +``` + +- A: `TypeError` +- B: `SyntaxError` +- C: `Lydia Hallie` +- D: `undefined` `undefined` + +
Përgjigja +

+ +#### Përgjigja: A + +Në JavaScript, funksionet janë objekte dhe për këtë arsye metoda `getFullName` i shtohet vetë objektit të funksionit të konstruktorit. Për këtë arsye, ne mund të thërrasim `Person.getFullName()`, por `member.getFullName` do të kthejë `TypeError`. + +Nëse dëshironi që një metodë të jetë e qasshme për të gjitha instancat e objektit, duhet ta shtoni atë në vetinë e quajtur "prototype": + +```js +Person.prototype.getFullName = function() { + return `${this.firstName} ${this.lastName}`; +}; +``` + +

+
+ +--- + +###### 12. Cila është vlera e saj? + +```javascript +function Person(firstName, lastName) { + this.firstName = firstName; + this.lastName = lastName; +} + +const lydia = new Person('Lydia', 'Hallie'); +const sarah = Person('Sarah', 'Smith'); + +console.log(lydia); +console.log(sarah); +``` + +- A: `Person {firstName: "Lydia", lastName: "Hallie"}` and `undefined` +- B: `Person {firstName: "Lydia", lastName: "Hallie"}` and `Person {firstName: "Sarah", lastName: "Smith"}` +- C: `Person {firstName: "Lydia", lastName: "Hallie"}` and `{}` +- D: `Person {firstName: "Lydia", lastName: "Hallie"}` and `ReferenceError` + +
Përgjigja +

+ +#### Përgjigja: A + +Për `sarah`, ne nuk përdorëm fjalën kyçe `new`. Kur përdorim `new`, `this` i referohet objektit të ri bosh që krijojmë. Megjithatë, nëse nuk shtoni `new`, `this` i referohet **objektit global**! + +E cekëm se `this.firstName` është `"Sarah"` dhe `this.lastName` është `"Smith"`. Çfarë bëmë realisht është se ne e definuam `global.firstName = 'Sarah'` dhe `global.lastName = 'Smith'`. `sarah` vetë mbetet `undefined`, pasi ne nuk kthejmë ndonjë vlerë nga funksioni `Person`. + +

+
+ +--- + +###### 13. Cilat janë tri fazat e "event propagation"? + +- A: Target > Capturing > Bubbling +- B: Bubbling > Target > Capturing +- C: Target > Bubbling > Capturing +- D: Capturing > Target > Bubbling + +
Përgjigja +

+ +#### Përgjigja: D + +Gjatë fazës **capturing** (kapjes), eventi kalon nëpër elementet paraardhëse deri te elementi i synuar. Më pas arrin në elementin **target** (e synuar) dhe fillon **bubbling**. + + + +

+
+ +--- + +###### 14. Të gjitha objektet kanë prototipe. + +- A: e vërtetë +- B: e pavërtetë + +
Përgjigja +

+ +#### Përgjigja: B + +Të gjitha objektet kanë prototipe, me përjashtim të **objektit bazë**. Objekti bazë është objekti i krijuar nga përdoruesi, ose një objekt që krijohet duke përdorur fjalën kyçe "new". Objekti bazë ka qasje në disa metoda dhe veti, të tilla si `.toString`. Kjo është arsyeja pse ju mund të përdorni metoda të integruara të JavaScript! Të gjitha këto metoda janë të disponueshme në prototip. Megjithëse JavaScript nuk mund ta gjejë atë drejtpërdrejt në objektin tuaj, ai zbret në zinxhirin e prototipit dhe e gjen atje, gjë që e bën atë të qasshëm për ju. + +

+
+ +--- + +###### 15. Cila është vlera e saj? + +```javascript +function sum(a, b) { + return a + b; +} + +sum(1, '2'); +``` + +- A: `NaN` +- B: `TypeError` +- C: `"12"` +- D: `3` + +
Përgjigja +

+ +#### Përgjigja: C + +JavaScript është gjuhë e shkruar në mënyrë dinamike __dynamically typed language__: ne nuk specifikojmë se çfarë tipe janë variablat e caktuara. Vlerat mund të konvertohen automatikisht në një tip tjetër pa e ditur ju dhe ky proces quhet _implicit type coercion_ (shndërrimi i tipit në mënyrë të nënkuptuar). __Coercion__ është shndërrimi nga një tip në një tjetër. + +Në këtë shembull, JavaScript konverton numrin `1` në string, në mënyrë që për funksionin të ketë kuptim dhe të kthejë një vlerë. Përgjatë mbledhjes të një tipi number (`1`) dhe një tipi string (`'2'`), numri trajtohet si string. Ne mund ti bashkojmë stringjet si `"Hello" + "World"`, kështu që ajo që po ndodh këtu është `"1" + "2"` e cila kthen "12"`. + +

+
+ +--- + +###### 16. Cila është vlera e saj? + +```javascript +let number = 0; +console.log(number++); +console.log(++number); +console.log(number); +``` + +- A: `1` `1` `2` +- B: `1` `2` `2` +- C: `0` `2` `2` +- D: `0` `1` `2` + +
Përgjigja +

+ +#### Përgjigja: C + +**postfiks** operatori unar `++`: + +1. Kthen vlerën (kthen `0`) +2. Rrit vleren (numri tani është `1`) + +**prefiks** operatori unar `++`: + +1. Rrit vlerën (numri tani është `2`) +2. Kthen vlerën (kthen `2`) + +Prandaj rezultati që kthehet është `0 2 2`. + +

+
+ +--- + +###### 17. Cila është vlera e saj? + +```javascript +function getPersonInfo(one, two, three) { + console.log(one); + console.log(two); + console.log(three); +} + +const person = 'Lydia'; +const age = 21; + +getPersonInfo`${person} is ${age} years old`; +``` + +- A: `"Lydia"` `21` `["", " is ", " years old"]` +- B: `["", " is ", " years old"]` `"Lydia"` `21` +- C: `"Lydia"` `["", " is ", " years old"]` `21` + +
Përgjigja +

+ +#### Përgjigja: B + +Nëse përdorni literale të shabllonit (template literals) të etiketuar, vlera e argumentit të parë është gjithmonë një array vlerash stringu. Argumentet e mbetura marrin vlerat e shprehjeve të vendosura në variablat e dhëna! + +

+
+ +--- + +###### 18. Cila është vlera e saj? + +```javascript +function checkAge(data) { + if (data === { age: 18 }) { + console.log('You are an adult!'); + } else if (data == { age: 18 }) { + console.log('You are still an adult.'); + } else { + console.log(`Hmm.. You don't have an age I guess`); + } +} + +checkAge({ age: 18 }); +``` + +- A: `You are an adult!` +- B: `You are still an adult.` +- C: `Hmm.. You don't have an age I guess` + +
Përgjigja +

+ +#### Përgjigja: C + +Kur testojmë barazinë, primitivet krahasohen me _vlerën_ e tyre, ndërsa objektet krahasohen me _referencën_ e tyre. JavaScript kontrollon nëse objektet kanë një referencë në të njëjtin vend në memorie. + +Dy objektet që po krahasojmë nuk e kanë këtë: objekti që kemi vendosur si parametër i referohet një vendndodhjeje të ndryshme në memorie nga objekti që kemi përdorur për të kontrolluar barazinë. + +Kjo tregon pse të dyja: `{ age: 18 } === { age: 18 }` dhe `{ age: 18 } == { age: 18 }` kthen `false`. + +

+
+ +--- + +###### 19. Cila është vlera e saj? + +```javascript +function getAge(...args) { + console.log(typeof args); +} + +getAge(21); +``` + +- A: `"number"` +- B: `"array"` +- C: `"object"` +- D: `"NaN"` + +
Përgjigja +

+ +#### Përgjigja: C + +Parametri "rest" (`...args`) na lejon të "mbledhim" të gjitha argumentet e mbetura në një array. Një array është një objekt, kështu që `typeof args` kthen `“objekt”` + +

+
+ +--- + +###### 20. Cila është vlera e saj? + +```javascript +function getAge() { + 'use strict'; + age = 21; + console.log(age); +} + +getAge(); +``` + +- A: `21` +- B: `undefined` +- C: `ReferenceError` +- D: `TypeError` + +
Përgjigja +

+ +#### Përgjigja: C + +Me `"use strict"`, mund të siguroheni se nuk do të deklaroni variabla globale pa qëllim. Ne asnjëherë nuk e kemi deklaruar variablen `age`, dhe pasi ne e përdorim `"use strict"`, do të na kthehet një error reference. Në qoftesë nuk përdorim `"use strict"`, do të kishte funksionuar pasi vetia `age` do të ishte shtuar në objektin global. + +

+
+ +--- + +###### 21. Sa do të jetë vlera e `sum`? + +```javascript +const sum = eval('10*10+5'); +``` + +- A: `105` +- B: `"105"` +- C: `TypeError` +- D: `"10*10+5"` + +
Përgjigja +

+ +#### Përgjigja: A + +`eval` vlerëson kodet që i pasohen si string. Nëse është një shprehje, si në këtë rast, ajo vlerëson shprehjen. Shprehja është `10 * 10 + 5`. Kjo kthen numrin '105'. + +

+
+ +--- + +###### 22. Sa kohë është e qasshme cool_secret? + +```javascript +sessionStorage.setItem('cool_secret', 123); +``` + +- A: Përgjithmonë, e dhëna nuk humb. +- B: Kur përdoruesi mbyll dritaren. +- C: Kur përdoruesi mbyll browser-in në tërësi, jo vetëm dritaren. +- D: Kur përdoruesi ndal kompjuterin e tyre. + +
Përgjigja +

+ +#### Përgjigja: B + +Të dhënat e ruajtura në `sessionStorage` largohen pasi të mbyllet _dritarja_. + +Nëse keni përdorur 'localStorage', të dhënat do të kishin mbetur aty përgjithmonë, përveç nëse për shembull thirret 'localStorage.clear()'. + +

+
+ +--- + +###### 23. Cila është vlera e saj? + +```javascript +var num = 8; +var num = 10; + +console.log(num); +``` + +- A: `8` +- B: `10` +- C: `SyntaxError` +- D: `ReferenceError` + +
Përgjigja +

+ +#### Përgjigja: B + +Me fjalën kyçe `var`, mund të deklaroni shumë variabla me të njëjtin emër. Më pas variabla do të mbajë vlerën e fundit të inicializuar në të. + +Ju nuk mund ta bëni këtë me 'let' ose 'const' pasi ato kanë qasje në bllok (block-scoped). + +

+
+ +--- + +###### 24. Cila është vlera e saj? + +```javascript +const obj = { 1: 'a', 2: 'b', 3: 'c' }; +const set = new Set([1, 2, 3, 4, 5]); + +obj.hasOwnProperty('1'); +obj.hasOwnProperty(1); +set.has('1'); +set.has(1); +``` + +- A: `false` `true` `false` `true` +- B: `false` `true` `true` `true` +- C: `true` `true` `false` `true` +- D: `true` `true` `true` `true` + +
Përgjigja +

+ +#### Përgjigja: C + +Të gjitha çelësat e objektit (përjashto Simbolet) janë stringje në prapavijë, edhe nëse ju vetë nuk e shkruani atë si string. Kjo është arsyeja pse `obj.hasOwnProperty('1')` gjithashtu kthen vlerën true. + +Nuk funksionon në këtë mënyrë për një "set". Nuk ka asnjë `'1'` në set-in tonë: `set.has('1')` kthen `false`. Nëse ka tipin numër `1`, `set.has(1)` kthen `true`. + +

+
+ +--- + +###### 25. Cila është vlera e saj? + +```javascript +const obj = { a: 'one', b: 'two', a: 'three' }; +console.log(obj); +``` + +- A: `{ a: "one", b: "two" }` +- B: `{ b: "two", a: "three" }` +- C: `{ a: "three", b: "two" }` +- D: `SyntaxError` + +
Përgjigja +

+ +#### Përgjigja: C + +Nëse keni dy çelësa me të njëjtin emër, çelësi do të zëvendësohet. Do të jetë ende në pozitën e parë, por me vlerën e fundit të specifikuar. + +

+
+ +--- + +###### 26. Konteksti global i ekzekutimit në JavaScript krijon dy gjëra për ju: objektin global, dhe fjalën kyçe "this". + +- A: e vërtetë +- B: e pavërtetë +- C: varet + +
Përgjigja +

+ +#### Përgjigja: A + +Konteksti bazë i ekzekutimit është konteksti global i ekzekutimit: është ajo që është e qasshme kudo në kodin tuaj. + +

+
+ +--- + +###### 27. Cila është vlera e saj? + +```javascript +for (let i = 1; i < 5; i++) { + if (i === 3) continue; + console.log(i); +} +``` + +- A: `1` `2` +- B: `1` `2` `3` +- C: `1` `2` `4` +- D: `1` `3` `4` + +
Përgjigja +

+ +#### Përgjigja: C + +Deklarata `continue` kalon një iterim nëse një kusht i caktuar kthen `true`. + +

+
+ +--- + +###### 28. Cila është vlera e saj? + +```javascript +String.prototype.giveLydiaPizza = () => { + return 'Just give Lydia pizza already!'; +}; + +const name = 'Lydia'; + +console.log(name.giveLydiaPizza()) +``` + +- A: `"Just give Lydia pizza already!"` +- B: `TypeError: not a function` +- C: `SyntaxError` +- D: `undefined` + +
Përgjigja +

+ +#### Përgjigja: A + +`String` është një konstruktor i integruar, të cilit mund t'i shtojmë veti. Sapo shtuam një metodë në prototipin e saj. Stringjet primitive konvertohen automatikisht në një objekt string, të gjeneruara nga funksioni i prototipit të stringut. Pra, të gjitha vargjet (objektet e stringut) kanë qasje në atë metodë! + +

+
+ +--- + +###### 29. Cila është vlera e saj? + +```javascript +const a = {}; +const b = { key: 'b' }; +const c = { key: 'c' }; + +a[b] = 123; +a[c] = 456; + +console.log(a[b]); +``` + +- A: `123` +- B: `456` +- C: `undefined` +- D: `ReferenceError` + +
Përgjigja +

+ +#### Përgjigja: B + +Çelësat e objekteve konvertohen automatikisht në stringje. Ne po provojmë të vendosim një objekt si çelës për objektin 'a', me vlerën '123'. + +Megjithatë, kur e përdorim "stringify" në një objekt, ai bëhet `"[object Object]"`. Pra, ajo që po themi këtu, është se `a["[object Object]"] = 123`. Pastaj, ne mund të provojmë të bëjmë të njëjtën gjë përsëri. `c` është një objekt tjetër që ne po e "stringify" në mënyrë implicite. Pra, atëherë, `a["[object Object]"] = 456`. + +Pastaj ne e printojmë `a[b]` e cila është `a["[object Object]"]`. We sapo e vendosëm `456` në të, prandaj edhe do të kthejë `456` + +

+
+ +--- + +###### 30. Cila është vlera e saj? + +```javascript +const foo = () => console.log('First'); +const bar = () => setTimeout(() => console.log('Second')); +const baz = () => console.log('Third'); + +bar(); +foo(); +baz(); +``` + +- A: `First` `Second` `Third` +- B: `First` `Third` `Second` +- C: `Second` `First` `Third` +- D: `Second` `Third` `First` + +
Përgjigja +

+ +#### Përgjigja: B + +Ne kemi një funksion "setTimeout" të cilin e thirrëm së pari. Megjithatë, ai u printua i fundit. + +Kjo është për shkak se në browser-a, ne nuk kemi vetëm "runtime" funksionalitet, ne gjithashtu kemi diçka që quhet `WebAPI`. `WebAPI` na jep funksionin `setTimeout` dhe poashtu për shembull DOM. + +Pasi _callback_ të vendoset në WebAPI, vetë funksioni "setTimeout" (por jo callback!) del nga pirgu (stack). + + + +Tani `foo` thirret dhe `"First"` do të printohet. + + + +`foo` del nga stack, dhe `baz` thirret. `"Third"` do të printohet. + + + +WebAPI nuk mund të shtojë gjëra në stack sa herë që është gati. Në vend të kësaj, ai vendos callback në diçka që quhet _queue_. + + + +Këtu fillon të funksionojë event loop. Një **event loop** shikon "stack" dhe "task queue". Nëse "stack" është bosh, ai merr gjënë e parë në radhë dhe e vendos atë në stack. + + + +`bar` thirret, `"Second"` do të printohet dhe do të largohet nga stack. + +

+
+ +--- + +###### 31. Çfarë do të jetë event.target kur e klikojmë butonin? + +```html +
+
+ +
+
+``` + +- A: `div` i jashtëm +- B: `div` i brendshëm +- C: `button` +- D: Një array i elementeve të ndërthurura. + +
Përgjigja +

+ +#### Përgjigja: C + +Elementi më thellë i mbivendosur që shkaktoi ngjarjen është objektivi i ngjarjes. Ju mund të ndaloni bubbling me "event.stopPropagation". + +

+
+ +--- + +###### 32. Kur klikoni paragrafin, çfarë do të printohet në dalje? + +```html +
+

+ Click here! +

+
+``` + +- A: `p` `div` +- B: `div` `p` +- C: `p` +- D: `div` + +
Përgjigja +

+ +#### Përgjigja: A + +Nëse klikojmë `p`, shohim dy dalje: `p` dhe `div`. Gjatë "event propagation", ekzistojnë 3 faza: kapja, objektivi dhe flluska. Si parazgjedhje, mbajtësit e ngjarjeve (event handlers) ekzekutohen në fazën e flluskimit (përveç nëse e vendosni "useCapture" në "true"). Ai shkon nga elementi më i thellë i mbivendosur jashtë. + +

+
+ +--- + +###### 33. Cila është vlera e saj? + +```javascript +const person = { name: 'Lydia' }; + +function sayHi(age) { + return `${this.name} is ${age}`; +} + +console.log(sayHi.call(person, 21)); +console.log(sayHi.bind(person, 21)); +``` + +- A: `undefined is 21` `Lydia is 21` +- B: `function` `function` +- C: `Lydia is 21` `Lydia is 21` +- D: `Lydia is 21` `function` + +
Përgjigja +

+ +#### Përgjigja: D + +Në të dy rastet, ne mund të e vendosim objektin si argument varësisht në cilin funksion dëshirojmë të referohemi me fjalën kyçe `this`. Megjithatë, `.call` gjithashtu ekzekutohet menjëherë! + +`.bind.` kthen një _kopje_ të funksionit, por me një kontekst të lidhur! Nuk ekzekutohet menjëherë. + +

+
+ +--- + +###### 34. Cila është vlera e saj? + +```javascript +function sayHi() { + return (() => 0)(); +} + +console.log(typeof sayHi()); +``` + +- A: `"object"` +- B: `"number"` +- C: `"function"` +- D: `"undefined"` + +
Përgjigja +

+ +#### Përgjigja: B + +Funksioni `sayHi` kthen vlerën e kthyer të shprehjes së funksionit të thirrur menjëherë (IIFE). Ky funksion ktheu `0`, që është i tipit `“numër”`. + +FYI: `typeof` mund të kthejë listën e mëposhtme të vlerave: `undefined`, `boolean`, `number`, `bigint`, `string`, `symbol`, `function` dhe `object`. Vini re se `typeof null` kthen `“object”`. + +

+
+ +--- + +###### 35. Cilat nga këto vlera janë false? + +```javascript +0; +new Number(0); +(''); +(' '); +new Boolean(false); +undefined; +``` + +- A: `0`, `''`, `undefined` +- B: `0`, `new Number(0)`, `''`, `new Boolean(false)`, `undefined` +- C: `0`, `''`, `new Boolean(false)`, `undefined` +- D: Të gjitha paraqesin vlerë false + +
Përgjigja +

+ +#### Përgjigja: A + +Ekzistojnë këto 8 vlera të cilat paraqesin false: + +- `undefined` +- `null` +- `NaN` +- `false` +- `''` (string i zbrazët) +- `0` +- `-0` +- `0n` (BigInt(0)) + +Konstruktorët e funksioneve, si `new Number` dhe `new Boolean` kthejnë vlerë të vërtetë (truthy). + +

+
+ +--- + +###### 36. Cila është vlera e saj? + +```javascript +console.log(typeof typeof 1); +``` + +- A: `"number"` +- B: `"string"` +- C: `"object"` +- D: `"undefined"` + +
Përgjigja +

+ +#### Përgjigja: B + +`typeof 1` kthen `"number"`. +`typeof "number"` kthen `"string"` + +

+
+ +--- + +###### 37. Cila është vlera e saj? + +```javascript +const numbers = [1, 2, 3]; +numbers[10] = 11; +console.log(numbers); +``` + +- A: `[1, 2, 3, null x 7, 11]` +- B: `[1, 2, 3, 11]` +- C: `[1, 2, 3, empty x 7, 11]` +- D: `SyntaxError` + +
Përgjigja +

+ +#### Përgjigja: C + +Kur inicializoni një vlerë për një element të vargut (array) i cili e kalon gjatësinë e tij, Javascript-i krijon diçka që quhet "empty slots (vende të zbrazëta)". Këto realisht e kanë vlerën `undefined`, por ju do të shihni diçka si: + +`[1, 2, 3, empty x 7, 11]` + +varësisht ku e ekzekutoni kodin tuaj (dallon për çdo browser, node, etj.) + +

+
+ +--- + +###### 38. Cila është vlera e saj? + +```javascript +(() => { + let x, y; + try { + throw new Error(); + } catch (x) { + (x = 1), (y = 2); + console.log(x); + } + console.log(x); + console.log(y); +})(); +``` + +- A: `1` `undefined` `2` +- B: `undefined` `undefined` `undefined` +- C: `1` `1` `2` +- D: `1` `undefined` `undefined` + +
Përgjigja +

+ +#### Përgjigja: A + +Blloku `catch` merr argumentin `x`. Kjo nuk është e njëjta `x` si variabla kur ne japim argumente. Variabla `x` (në bllokun `catch`) ka shtrirje blloku (është block-scoped). + +Më vonë, ne e inicializojmë këtë variabël me shtrirje blloku të barabartë me `1` dhe inicializojmë vlerën e ndryshores `y`. Tani, ne printojmë ndryshoren me shtrirje blloku `x`, e cila është e barabartë me `1`. + +Jashtë bllokut `catch`, `x` është ende `undefined`, dhe `y` është `2`. Kur dëshirojmë të bëjmë `console.log(x)` jashtë bllokut `catch`, do të kthejë `undefined`, dhe `y` kthen `2`. + +

+
+ +--- + +###### 39. Çdo gjë në JavaScript është ose... + +- A: primitive ose objekt +- B: funksion ose objekt +- C: pyetje me trik! vetëm objekt +- D: numër ose objekt + +
Përgjigja +

+ +#### Përgjigja: A + +JavaScript ka vetëm tipe primitive dhe objekte. + +Tipet primitive janë `boolean`, `null`, `undefined`, `bigint`, `number`, `string`, dhe `symbol`. + +Ajo që e dallon një tip primitiv nga një objekt është se primitivët nuk kanë asnjë veti ose metodë; megjithatë, do të vini re se `foo.toUpperCase()` vlerësohet në `'FOO'` dhe nuk rezulton në `TypeError`. Kjo ndodh sepse kur përpiqeni të qasni një veçori ose metodë në një primitive si një string, JavaScript do të mbështjellë në mënyrë implicite tipin primitiv duke përdorur një nga klasat e mbështjellësit, d.m.th. `String`, dhe më pas do ta heqë menjëherë mbështjellësin pasi të vlerësohet shprehja. Të gjithë primitivët përveç `null` dhe `undefined` e shfaqin këtë sjellje. + +

+
+ +--- + +###### 40. Cila është vlera e saj? + +```javascript +[[0, 1], [2, 3]].reduce( + (acc, cur) => { + return acc.concat(cur); + }, + [1, 2], +); +``` + +- A: `[0, 1, 2, 3, 1, 2]` +- B: `[6, 1, 2]` +- C: `[1, 2, 0, 1, 2, 3]` +- D: `[1, 2, 6]` + +
Përgjigja +

+ +#### Përgjigja: C + +`[1, 2]` është vlera jonë fillestare. Kjo është vlera me të cilën fillojmë, dhe vlera e parë e `acc`. Gjatë iterimit të parë, `acc` është `[1,2]`, dhe `cur` është `[0, 1]`. Ne i bashkojmë ato dhe kjo rezulton në `[1, 2, 0, 1]`. + +Pastaj, `[1, 2, 0, 1]` është `acc` dhe `[2, 3]` është `cur`. I bashkojmë ato dhe marrim `[1, 2, 0, 1, 2, 3]` + +

+
+ +--- + +###### 41. Cila është vlera e saj? + +```javascript +!!null; +!!''; +!!1; +``` + +- A: `false` `true` `false` +- B: `false` `false` `true` +- C: `false` `true` `true` +- D: `true` `true` `false` + +
Përgjigja +

+ +#### Përgjigja: B + +`null` është false. `!null` kthen `true`. `!true` kthen `false`. + +`""` është false. `!""` kthen `true`. `!true` kthen `false`. + +`1` është e vërtetë (truthy). `!1` kthen `false`. `!false` kthen `true`. + +

+
+ +--- + +###### 42. Çfarë do të kthejë në browser funksioni `setInterval`? + +```javascript +setInterval(() => console.log('Hi'), 1000); +``` + +- A: një id unike +- B: numrin e milisekondave të specifikuara +- C: funksionin të cilin e kemi kaluar si argument +- D: `undefined` + +
Përgjigja +

+ +#### Përgjigja: A + +Kthen një id unike. Kjo id mund të përdoret për të pastruar intervalin me funksionin `clearInterval()`. + +

+
+ +--- + +###### 43. Çfarë do të kthehet si rezultat? + +```javascript +[...'Lydia']; +``` + +- A: `["L", "y", "d", "i", "a"]` +- B: `["Lydia"]` +- C: `[[], "Lydia"]` +- D: `[["L", "y", "d", "i", "a"]]` + +
Përgjigja +

+ +#### Përgjigja: A + +Stringu është i iterueshëm. Operatori i përhapjes (spread operator) iteron çdo karakter të një elementi të iterueshëm në një element (në këtë rast array []). + +

+
+ +--- + +###### 44. Cila është vlera e saj? + +```javascript +function* generator(i) { + yield i; + yield i * 2; +} + +const gen = generator(10); + +console.log(gen.next().value); +console.log(gen.next().value); +``` + +- A: `[0, 10], [10, 20]` +- B: `20, 20` +- C: `10, 20` +- D: `0, 10 and 10, 20` + +
Përgjigja +

+ +#### Përgjigja: C + +Funksionet e rregullta nuk mund të ndalen në mes të ekzekutimit pas thirrjes. Sidoqoftë, funksioni i gjeneratorit (generator function) mund të "ndalohet" në mes të rrugës dhe më vonë të vazhdojë nga vendi ku ndaloi. Sa herë që një funksion gjenerues ndeshet me fjalën kyçe `yield`, funksioni jep vlerën e specifikuar pas saj. Vini re se funksioni i gjeneratorit në atë rast nuk e _kthen_ (return) vlerën, por e _jep_ (yield) vlerën. + +Së pari, ne inicializojmë funksionin e gjeneratorit me `i` të barabartë me `10`. Ne thërrasim funksionin e gjeneratorit duke përdorur metodën `next()`. Herën e parë që thërrasim funksionin e gjeneratorit, `i` është i barabartë me `10`. Ai ndeshet me fjalën kyçe të parë `yield`: jep vlerën e `i`. Gjeneratori tani është `në pauzë` dhe `10` regjistrohet. + +Pastaj, ne e thirrim funksionin përsëri me metodën `next()`. Fillon dhe vazhdon aty ku ka ndaluar më parë, ende me `i` të barabartë me `10`. Tani, ai ndeshet me fjalën kyçe tjetër "yield" dhe jep `i * 2`. `i` është e barabartë me `10`, kështu që kthen `10 * 2`, që është `20`. Kjo rezulton në `10, 20`. + +

+
+ +--- + +###### 45. Çfarë do të kthehet si rezultat? + +```javascript +const firstPromise = new Promise((res, rej) => { + setTimeout(res, 500, 'one'); +}); + +const secondPromise = new Promise((res, rej) => { + setTimeout(res, 100, 'two'); +}); + +Promise.race([firstPromise, secondPromise]).then(res => console.log(res)); +``` + +- A: `"one"` +- B: `"two"` +- C: `"two" "one"` +- D: `"one" "two"` + +
Përgjigja +

+ +#### Përgjigja: B + +Kur i kalojmë premtime (promises) të shumta metodës `Promise.race`, ajo zgjidh/refuzon premtimin _e parë_ që do të zgjidhet/refuzohet. Me metodën `setTimeout`, kalojmë një kohëmatës: 500 ms për premtimin e parë (`firstPromise`) dhe 100 ms për premtimin e dytë (`secondPromise`). Kjo do të thotë se `secondPromise`zgjidhet fillimisht me vlerën `'two'`. `res` tani mban vlerën e `'two'`, e cila printohet. + +

+
+ +--- + +###### 46. Cila është vlera e saj? + +```javascript +let person = { name: 'Lydia' }; +const members = [person]; +person = null; + +console.log(members); +``` + +- A: `null` +- B: `[null]` +- C: `[{}]` +- D: `[{ name: "Lydia" }]` + +
Përgjigja +

+ +#### Përgjigja: D + +Së pari, deklarojmë variablën `person` me vlerën e objektit i cili e ka vetinë `name`. + + + +Më pas, ne deklarojmë një variabël të quajtur `members`. E caktojmë elementin e parë të atij array të barabartë me vlerën e variablës `person`. Objektet ndërveprojnë me _referencë_ kur i vendosin të barabartë me njëri-tjetrin. Kur caktoni një referencë nga një ndryshore në tjetrën, ju bëni një _kopje_ të asaj reference. (vini re se ato nuk kanë të njëjtën referencë!) + + + +Pastaj e ri-inicializojmë variablën `person` të barabartë me `null` + + + +Ne po e modifikojmë vetëm vlerën e variblës `person`, dhe jo të elementit të parë ne array, meqenëse ai element ka një referencë të ndryshme (të kopjuar) për objektin. Elementi i parë në `members` ende mban referencën e tij ndaj objektit origjinal. Kur printojmë array `members`, elementi i parë ende mban vlerën e objektit, i cili printohet. + +

+
+ +--- + +###### 47. Cila është vlera e saj? + +```javascript +const person = { + name: 'Lydia', + age: 21, +}; + +for (const item in person) { + console.log(item); +} +``` + +- A: `{ name: "Lydia" }, { age: 21 }` +- B: `"name", "age"` +- C: `"Lydia", 21` +- D: `["name", "Lydia"], ["age", 21]` + +
Përgjigja +

+ +#### Përgjigja: B + +Me unazën `for-in`, ne mund të iterojmë përgjatë çelësave të objektit, në këtë rast `name` dhe `age`. Në prapavijë, çelësat e objektit janë stringje (në qoftesë nuk janë Symbol). Në çdo unazë, ne vendosim vlerën e `item` të barabartë me çelësin aktual në të cilin po iterohet. Së pari, `item` është i barabartë me `name`, dhe printohet. Pastaj, `item` është e barabartë me `age` dhe printohet. + +

+
+ +--- + +###### 48. Cila është vlera e saj? + +```javascript +console.log(3 + 4 + '5'); +``` + +- A: `"345"` +- B: `"75"` +- C: `12` +- D: `"12"` + +
Përgjigja +

+ +#### Përgjigja: B + +Radha e veprimeve matematikore të operatorit është rendi në të cilin përpiluesi (kompajleri) vlerëson shprehjet, qoftë nga e majta në të djathtë ose nga e djathta në të majtë. Kjo ndodh vetëm nëse të gjithë operatorët kanë përparësinë _të njejtë_. Ne kemi vetëm një lloj operatori: `+`. Për më tepër, radha e veprimeve matematikore është nga e majta në të djathtë. + +`3 + 4` llogaritet së pari. Kjo rezulton në numrin `7`. + +`7 + '5'` rezulton në `"75"` për shkak të shndërrimit të tipit (coercion). JavaScript-i e konverton numrin `7` ne një string, shiko pyetjen 15. Ne mund të i bashkojmë dy stringje duke e përdorur operatorin `+`. `"7"` + `"5"` rezulton në `"75"` + +

+
+ +--- + +###### 49. What's the value of `num`? + +```javascript +const num = parseInt('7*6', 10); +``` + +- A: `42` +- B: `"42"` +- C: `7` +- D: `NaN` + +
Përgjigja +

+ +#### Përgjigja: C + +Kthehen vetëm numrat e parë në string. Bazuar në _radix (bazë)_ (argumenti i dytë për të specifikuar se në çfarë tipi duam ta parsojmë atë: bazën 10, heksadecimal, oktal, binar, etj.), `parseInt` kontrollon nëse karakteret në string janë të vlefshme. Pasi të ndeshet me një karakter që nuk është një numër i vlefshëm në bazë, ai ndalon parsimin dhe injoron karakteret e ardhshme. + +`*` nuk është numër valid. Parson vetëm `"7"` në decimal `7`. `num` tani mban vlerën `7`. + +

+
+ +--- + +###### 50. Cila është vlera e saj? + +```javascript +[1, 2, 3].map(num => { + if (typeof num === 'number') return; + return num * 2; +}); +``` + +- A: `[]` +- B: `[null, null, null]` +- C: `[undefined, undefined, undefined]` +- D: `[ 3 x empty ]` + +
Përgjigja +

+ +#### Përgjigja: C + +Kur iterojmë (map-ojmë) një array, vlera e `num` është e barabartë me elementin që është duke u iteruar aktualisht. Në këtë rast, elementet janë numra, kështu që kushti i deklaratës if `typeof num === "number"` kthen `true`. Funksioni map krijon një grup të ri dhe fut vlerat e kthyera nga funksioni. + +Megjithatë, ne nuk kthejmë një vlerë. Kur nuk kthejmë një vlerë nga funksioni, funksioni kthen `undefined`. Për çdo element në array, blloku i funksionit thirret, kështu që për secilin element ne kthejmë `undefined`. + +

+
+ +--- + +###### 51. Cila është vlera e saj? + +```javascript +function getInfo(member, year) { + member.name = 'Lydia'; + year = '1998'; +} + +const person = { name: 'Sarah' }; +const birthYear = '1997'; + +getInfo(person, birthYear); + +console.log(person, birthYear); +``` + +- A: `{ name: "Lydia" }, "1997"` +- B: `{ name: "Sarah" }, "1998"` +- C: `{ name: "Lydia" }, "1998"` +- D: `{ name: "Sarah" }, "1997"` + +
Përgjigja +

+ +#### Përgjigja: A + +Argumentet kalohen si _vlerë_, përveç nëse vlera e tyre është një objekt, atëherë ato kalohen si _referencë_. `birthYear` kalohet sipas vlerës, pasi është një string, jo një objekt. Kur kalojmë argumente sipas vlerës, krijohet një _kopje_ e asaj vlere (shih pyetjen 46). + +Variabla `birthYear` ka referencë në vlerën `“1997”`. Argumenti `year` gjithashtu ka referencë në vlerën `"1997"`, por nuk është e njëjta vlerë si `birthYear`. Kur përditësojmë vlerën e `year` duke vendosur `year` të barabartë me `"1998"`, ne po përditësojmë vetëm vlerën e `year`. `birthYear` është ende i barabartë me `"1997"`. + +Vlera e `person` është objekt. Argumenti `member` ka referencë (të kopjuar) për objektin e njejtë. Kur modifikojmë një veti të objektit që `member` ka një referencë, vlera e `person` gjithashtu do të modifikohet, pasi të dy kanë një referencë për të njëjtin objekt. Vetia `name` e `person` tani është e barabartë me vlerën `"Lydia"`. + +

+
+ +--- + +###### 52. Cila është vlera e saj? + +```javascript +function greeting() { + throw 'Hello world!'; +} + +function sayHi() { + try { + const data = greeting(); + console.log('It worked!', data); + } catch (e) { + console.log('Oh no an error:', e); + } +} + +sayHi(); +``` + +- A: `It worked! Hello world!` +- B: `Oh no an error: undefined` +- C: `SyntaxError: can only throw Error objects` +- D: `Oh no an error: Hello world!` + +
Përgjigja +

+ +#### Përgjigja: D + +Me deklaratën `throw`, ne mund të krijojmë gabime (error) të personalizuara. Me këtë deklaratë, ju mund të bëni përjashtime. Një përjashtim mund të jetë një string, një numër, një boolean ose një objekt. Në këtë rast, përjashtimi ynë është stringy `'Hello world!'`. + +Me deklaratën `catch`, ne mund të specifikojmë se çfarë të bëjmë nëse një përjashtim hidhet në bllokun `try`. Bëhet një përjashtim: stringu `'Hello world!'`. `e` tani është e barabartë me atë string, të cilin e regjistrojmë. Kjo rezulton në `'Oh an error: Hello world!'`. + +

+
+ +--- + +###### 53. Cila është vlera e saj? + +```javascript +function Car() { + this.make = 'Lamborghini'; + return { make: 'Maserati' }; +} + +const myCar = new Car(); +console.log(myCar.make); +``` + +- A: `"Lamborghini"` +- B: `"Maserati"` +- C: `ReferenceError` +- D: `TypeError` + +
Përgjigja +

+ +#### Përgjigja: B + +Kur një konstruktor thirret me fjalën kyçe `new`, ai krijon një objekt dhe vendos fjalën kyçe `this` për t'iu referuar atij objekti. Si parazgjedhje, nëse konstruktori nuk kthen asgjë në mënyrë të qartë, ai do të kthejë objektin e krijuar së fundi. + +Në këtë rast, konstruktori `Car` kthen në mënyrë eksplicite një objekt të ri me `make` të vendosur në `"Maserati"`, i cili mbishkruan sjelljen e paracaktuar. Prandaj, kur thirret `New Car()`, objekti i kthyer i caktohet `myCar`, duke rezultuar në daljen `“Maserati”` kur qaset `myCar.make`. + +

+
+ +--- + +###### 54. Cila është vlera e saj? + +```javascript +(() => { + let x = (y = 10); +})(); + +console.log(typeof x); +console.log(typeof y); +``` + +- A: `"undefined", "number"` +- B: `"number", "number"` +- C: `"object", "number"` +- D: `"number", "undefined"` + +
Përgjigja +

+ +#### Përgjigja: A + +`let x = (y = 10);` është shkurtesë për: + +```javascript +y = 10; +let x = y; +``` + +Kur e vendosim `y` të barabartë me `10`, ne në të vërtetë e shtojmë vetinë `y` në objektin global (`window` në browser, `global` në Node). Në browser, `window.y` është tani e barabartë me `10`. + +Më pas, ne deklarojmë variablën `x` me vlerën `y`, e cila është `10`. Variablat e deklaruara me fjalën kyçe 'let' janë _block scoped_, ato përcaktohen vetëm brenda bllokut ku janë deklaruar; shprehja e funksionit të thirrur menjëherë (IIFE) në këtë rast. Kur përdorim operatorin `typeof`, operandi `x` nuk është i përcaktuar: ne po përpiqemi të qasim `x` jashtë bllokut ku ai është deklaruar. Kjo do të thotë se `x` nuk është përcaktuar. Vlerat e të cilave nuk u është caktuar një vlerë ose nuk janë deklaruar janë të tipit `"undefined"`. `console.log(typeof x)` kthen `"undefined"`. + +Megjithatë, ne krijuam një variabël globale `y` kur vendosëm `y` të barabartë me `10`. Kjo vlerë është e qasshme kudo në kodin tonë. `y` është përcaktuar dhe mban vlerën e tipit `"number"`. `console.log(typeof y)` kthen `"number"`. + +

+
+ +--- + +###### 55. Cila është vlera e saj? + +```javascript +class Dog { + constructor(name) { + this.name = name; + } +} + +Dog.prototype.bark = function() { + console.log(`Woof I am ${this.name}`); +}; + +const pet = new Dog('Mara'); + +pet.bark(); + +delete Dog.prototype.bark; + +pet.bark(); +``` + +- A: `"Woof I am Mara"`, `TypeError` +- B: `"Woof I am Mara"`, `"Woof I am Mara"` +- C: `"Woof I am Mara"`, `undefined` +- D: `TypeError`, `TypeError` + +
Përgjigja +

+ +#### Përgjigja: A + +Ne mund të fshijmë veti nga objektet duke përdorur fjalën kyçe `delete`, gjithashtu në prototip. Duke fshirë një veti në prototip, ajo nuk është më e qasshme në zinxhirin e prototipit. Në këtë rast, funksioni `bark` nuk është më i qasshëm në prototip pas `delete Dog.prototype.bark`, por ne ende provojmë të i qasemi. + +Kur përpiqemi të thërrasim diçka që nuk është funksion, hidhet një 'TypeError'. Në këtë rast `TypeError: pet.bark is not a function`, pasi `pet.bark` është `undefined`. + +

+
+ +--- + +###### 56. Cila është vlera e saj? + +```javascript +const set = new Set([1, 1, 2, 3, 4]); + +console.log(set); +``` + +- A: `[1, 1, 2, 3, 4]` +- B: `[1, 2, 3, 4]` +- C: `{1, 1, 2, 3, 4}` +- D: `{1, 2, 3, 4}` + +
Përgjigja +

+ +#### Përgjigja: D + +Objekti `Set` është një koleksion vlerash _unike_: një vlerë mund të paraqitet vetëm një herë në një grup (set). + +Vendosëm `[1, 1, 2, 3, 4]` me një vlerë dublikate `1`. Meqenëse nuk mund të kemi dy vlera të njëjta në një "set", njëra prej tyre largohet. Kjo rezulton në `{1, 2, 3, 4}`. + +

+
+ +--- + +###### 57. Cila është vlera e saj? + +```javascript +// counter.js +let counter = 10; +export default counter; +``` + +```javascript +// index.js +import myCounter from './counter'; + +myCounter += 1; + +console.log(myCounter); +``` + +- A: `10` +- B: `11` +- C: `Error` +- D: `NaN` + +
Përgjigja +

+ +#### Përgjigja: C + +Një modul i importuar mund vetëm të i lexohet vlera (_read-only_): nuk mund të modifikohet. Vetëm moduli i cili i importon ato mund të ndërrojë atë vlerë. + +Kur tentojmë të rrisim vlerën e `myCounter`, do të marrim një error: `myCounter` mundet vetëm të lexohet dhe nuk mund të modifikohet. + +

+
+ +--- + +###### 58. Cila është vlera e saj? + +```javascript +const name = 'Lydia'; +age = 21; + +console.log(delete name); +console.log(delete age); +``` + +- A: `false`, `true` +- B: `"Lydia"`, `21` +- C: `true`, `true` +- D: `undefined`, `undefined` + +
Përgjigja +

+ +#### Përgjigja: A + +Operatori "delete" kthen një vlerë booleane: `true` në fshirje të suksesshme, përndryshe do të kthejë `false`. Megjithatë, variablat e deklaruara me fjalën kyçe `var`, `const` ose `let` nuk mund të fshihen duke përdorur operatorin `delete`. + +Variabla `name` u deklarua me fjalën kyçe `const`, kështu që fshirja e saj nuk ishte e suksesshme: u kthye `false`. Kur vendosëm `age` të barabartë me `21`, ne në fakt shtuam një veti të quajtur `age` në objektin global. Ju mund të fshini me sukses vetitë nga objektet në këtë mënyrë, gjithashtu edhe objektin global, kështu që `delete age` kthen `true`. + +

+
+ +--- + +###### 59. Cila është vlera e saj? + +```javascript +const numbers = [1, 2, 3, 4, 5]; +const [y] = numbers; + +console.log(y); +``` + +- A: `[[1, 2, 3, 4, 5]]` +- B: `[1, 2, 3, 4, 5]` +- C: `1` +- D: `[1]` + +
Përgjigja +

+ +#### Përgjigja: C + +Ne mund të targetojmë vlerat nga vargjet ose vetitë nga objektet përmes destrukturimit. Për shembull: + +```javascript +[a, b] = [1, 2]; +``` + + + +Vlera `a` tani është `1`, dhe vlera `b` tani është `2`. Çfarë ne bëmë në të vërtetë në pyetje, është: + +```javascript +[y] = [1, 2, 3, 4, 5]; +``` + + + +Kjo do të thotë se vlera e `y` është e barabartë me vlerën e parë në array, që është numri `1`. Kur printojmë `y`, do të kthehet `1`. + +

+
+ +--- + +###### 60. Cila është vlera e saj? + +```javascript +const user = { name: 'Lydia', age: 21 }; +const admin = { admin: true, ...user }; + +console.log(admin); +``` + +- A: `{ admin: true, user: { name: "Lydia", age: 21 } }` +- B: `{ admin: true, name: "Lydia", age: 21 }` +- C: `{ admin: true, user: ["Lydia", 21] }` +- D: `{ admin: true }` + +
Përgjigja +

+ +#### Përgjigja: B + +Është e mundur të kombinohen objektet duke përdorur operatorin e përhapjes (spread) `...`. Kjo ju lejon të krijoni kopje të çifteve çelës/vlerë të një objekti dhe t'i shtoni ato në një objekt tjetër. Në këtë rast, ne krijojmë kopje të objektit `user` dhe i shtojmë ato në objektin `admin`. Objekti `admin` tani përmban çiftet e kopjuara të çelësit/vlerës, që rezulton në `{ admin: true, emri: "Lydia", mosha: 21 }`. + +

+
+ +--- + +###### 61. Cila është vlera e saj? + +```javascript +const person = { name: 'Lydia' }; + +Object.defineProperty(person, 'age', { value: 21 }); + +console.log(person); +console.log(Object.keys(person)); +``` + +- A: `{ name: "Lydia", age: 21 }`, `["name", "age"]` +- B: `{ name: "Lydia", age: 21 }`, `["name"]` +- C: `{ name: "Lydia"}`, `["name", "age"]` +- D: `{ name: "Lydia"}`, `["age"]` + +
Përgjigja +

+ +#### Përgjigja: B + +Me metodën `defineProperty`, ne mund të shtojmë veti të reja në një objekt, ose të modifikojmë ato ekzistuese. Kur shtojmë një veti në një objekt duke përdorur metodën `defineProperty`, ato janë si parazgjedhje _not enumerable_. Metoda `Object.keys` kthen të gjithë emrat e vetive _numerable_ nga një objekt, në këtë rast vetëm `"name"`. + +Vetitë e shtuara duke përdorur metodën `defineProperty` janë të pandryshueshme si parazgjedhje. Ju mund ta mbishkruani këtë sjellje duke përdorur veçoritë `writable`, `configurable` dhe `enumerable`. Në këtë mënyrë, metoda `defineProperty` ju jep shumë më tepër kontroll mbi vetitë që po i shtoni një objekti. + +

+
+ +--- + +###### 62. Cila është vlera e saj? + +```javascript +const settings = { + username: 'lydiahallie', + level: 19, + health: 90, +}; + +const data = JSON.stringify(settings, ['level', 'health']); +console.log(data); +``` + +- A: `"{"level":19, "health":90}"` +- B: `"{"username": "lydiahallie"}"` +- C: `"["level", "health"]"` +- D: `"{"username": "lydiahallie", "level":19, "health":90}"` + +
Përgjigja +

+ +#### Përgjigja: A + +Argumenti i dytë i "JSON.stringify" është _zëvendësuesi_. Zëvendësuesi mund të jetë ose një funksion ose një array, dhe ju lejon të kontrolloni se çfarë dhe si duhet të konvertohet një vlerë e JavaScript në JSON string. + +Nëse zëvendësuesi është një _array_, vetëm emrat e vetive të përfshira në array do të shtohen në stringun JSON. Në këtë rast, përfshihen vetëm vetitë me emrat `"level"` dhe `"health"`, përjashtohet `"username"`. `data` tani është e barabartë me `"{"level":19, "health":90}"`. + +Nëse zëvendësuesi është një _funksion_, ky funksion thirret në çdo veti në objektin që po e përdorni metodën 'stringify'. Vlera e kthyer nga ky funksion do të jetë vlera e vetive kur të shtohet në vargun JSON. Nëse vlera është `undefined`, kjo veti përjashtohet nga vargu JSON. + +

+
+ +--- + +###### 63. Cila është vlera e saj? + +```javascript +let num = 10; + +const increaseNumber = () => num++; +const increasePassedNumber = number => number++; + +const num1 = increaseNumber(); +const num2 = increasePassedNumber(num1); + +console.log(num1); +console.log(num2); +``` + +- A: `10`, `10` +- B: `10`, `11` +- C: `11`, `11` +- D: `11`, `12` + +
Përgjigja +

+ +#### Përgjigja: A + +Operatori unar `++` fillimisht kthen vlerën e operandit, pastaj e rrit vlerën e tij. Vlera e `num1` është `10`, meqenëse funksioni `increaseNumber` fillimisht kthen vlerën e `num`, e cila është `10`, dhe vetëm pastaj e rrit vlerën e `num`. + +`num2` është `10`, pasi ne e kaluam `num1` si argument tek `increasePassedNumber`. `number` është i barabartë me `10`(vlera e `num1`). Përsëri, operatori unar `++` _së pari kthen_ vlerën e operandit, dhe pastaj rrit vlerën e tij. Vlera e `number` është `10`, kështu që `num2` është e barabartë me `10`. + +

+
+ +--- + +###### 64. Cila është vlera e saj? + +```javascript +const value = { number: 10 }; + +const multiply = (x = { ...value }) => { + console.log((x.number *= 2)); +}; + +multiply(); +multiply(); +multiply(value); +multiply(value); +``` + +- A: `20`, `40`, `80`, `160` +- B: `20`, `40`, `20`, `40` +- C: `20`, `20`, `20`, `40` +- D: `NaN`, `NaN`, `20`, `40` + +
Përgjigja +

+ +#### Përgjigja: C + +Në ES6, ne mund të inicializojmë parametrat me një vlerë të paracaktuar (default). Vlera e parametrit do të jetë vlera e paracaktuar, nëse asnjë vlerë tjetër nuk i është kaluar funksionit, ose nëse vlera e parametrit është `"undefined"`. Në këtë rast, ne i shpërndajmë vetitë e objektit `value` në një objekt të ri, kështu që `x` ka vlerën e paracaktuar të `{ number: 10 }`. + +Argumenti i paracaktuar vlerësohet (llogaritet) në _kohën e thirrjes_! Sa herë që thërrasim funksionin, krijohet një objekt i ri. Ne e thërrasim funksionin `multiply` dy herët e para pa kaluar vlerën: `x` ka vlerën e paracaktuar të `{ number: 10 }`. Më pas printojmë vlerën e shumëzuar të atij numri, që është `20`. + +Herën e tretë që thërrasim funksionin `multiply`, kalojmë një argument: objektin e quajtur `value`. Operatori `*=` është në fakt shkurtesë për `x.number = x.number * 2`: ne e modifikojmë vlerën e `x.number` dhe printojmë vlerën e shumëzuar `20`. + +Herën e katërt, ne e kalojmë përsëri objektin `value`. `x.number` është modifikuar më parë në `20`, kështu që `x.number *= 2` printon `40`. + +

+
+ +--- + +###### 65. Cila është vlera e saj? + +```javascript +[1, 2, 3, 4].reduce((x, y) => console.log(x, y)); +``` + +- A: `1` `2` dhe `3` `3` dhe `6` `4` +- B: `1` `2` dhe `2` `3` dhe `3` `4` +- C: `1` `undefined` dhe `2` `undefined` dhe `3` `undefined` dhe `4` `undefined` +- D: `1` `2` dhe `undefined` `3` dhe `undefined` `4` + +
Përgjigja +

+ +#### Përgjigja: D + +Argumenti i parë që merr metoda `reduce` është _akumulatori_, në këtë rast `x`. Argumenti i dytë është _vlera aktuale_, `y`. Me metodën e reduktimit, ne ekzekutojmë një funksion të kthimit (callback) në çdo element në array, i cili përfundimisht mund të rezultojë në një vlerë të vetme. + +Në këtë shembull, ne nuk jemi duke kthyer ndonjë vlerë, jemi vetëm duke printuar vlerat e akumulatorit dhe vlerën aktuale. + +Vlera e akumulatorit është e barabartë me vlerën e kthyer më parë të funksionit të kthimit (callback). Nëse nuk e kaloni argumentin opsional `initialValue` në metodën `reduce`, akumuluesi është i barabartë me elementin e parë në thirrjen e parë. + +Në thirrjen e parë, akumuluesi (`x`) është `1`, dhe vlera aktuale (`y`) është `2`. Ne nuk kthehemi nga callback, ne printojmë akumuluesin dhe vlerën aktuale: `1` dhe `2` printohen. + +Nëse nuk ktheni një vlerë nga një funksion, ai kthen `undefined`. Në thirrjen tjetër, akumuluesi është `undefined` dhe vlera aktuale është `3`. `undefined` dhe `3` printohet. + +Në thirrjen e katërt, ne përsëri nuk kthehemi nga callback. Akumulatori është përsëri `undefined` dhe vlera aktuale është `4`. `undefined` dhe `4` printohen. + +

+
+ +--- + +###### 66. Me cilin konstruktor mund të zgjerojmë me sukses klasën 'Dog'? + +```javascript +class Dog { + constructor(name) { + this.name = name; + } +}; + +class Labrador extends Dog { + // 1 + constructor(name, size) { + this.size = size; + } + // 2 + constructor(name, size) { + super(name); + this.size = size; + } + // 3 + constructor(size) { + super(name); + this.size = size; + } + // 4 + constructor(name, size) { + this.name = name; + this.size = size; + } + +}; +``` + +- A: 1 +- B: 2 +- C: 3 +- D: 4 + +
Përgjigja +

+ +#### Përgjigja: B + +Në një klasë të derivuar, ju nuk mund të përdorni fjalën kyçe `this` përpara se të e thirrni `super`. Nëse provoni ta bëni këtë, do të jap `ReferenceError`: 1 dhe 4 do të hedhin një gabim referimi. + +Me fjalën kyçe `super`, ne e thërrasim konstruktorin e asaj klase mëmë me argumentet e dhëna. Konstruktori i prindit merr argumentin `name`, kështu që ne duhet të kalojmë `name` në `super`. + +Klasa `Labrador` merr dy argumente, `name` meqenëse trashëgon klasën 'Dog', dhe `size` si një veti shtesë në klasën `Labrador`. Ata të dy duhet t'i kalojnë konstruktorit në `Labrador`, i cili implementohet saktë duke përdorur konstruktorin 2. + +

+
+ +--- + +###### 67. Cila është vlera e saj? + +```javascript +// index.js +console.log('running index.js'); +import { sum } from './sum.js'; +console.log(sum(1, 2)); + +// sum.js +console.log('running sum.js'); +export const sum = (a, b) => a + b; +``` + +- A: `running index.js`, `running sum.js`, `3` +- B: `running sum.js`, `running index.js`, `3` +- C: `running sum.js`, `3`, `running index.js` +- D: `running index.js`, `undefined`, `running sum.js` + +
Përgjigja +

+ +#### Përgjigja: B + +Me fjalën kyçe `import`, të gjitha modulet e importuara parsohen fillimisht (_para-parsed_). Kjo do të thotë që modulet e importuara ekzekutohen _të parat_, kodi në file që importon modulin ekzekutohet _më pas_. + +Ky është një dallimi në mes `require()` në CommonJS dhe `import`! Me `require()`, mund të ngarkoni varësitë sipas kërkesës gjatë ekzekutimit të kodit. Nëse do të kishim përdorur `require` në vend të `import`, `running index.js`, `running sum.js`, `3` do të ishte printuar në tastierë. + +

+
+ +--- + +###### 68. Cila është vlera e saj? + +```javascript +console.log(Number(2) === Number(2)); +console.log(Boolean(false) === Boolean(false)); +console.log(Symbol('foo') === Symbol('foo')); +``` + +- A: `true`, `true`, `false` +- B: `false`, `true`, `false` +- C: `true`, `false`, `true` +- D: `true`, `true`, `true` + +
Përgjigja +

+ +#### Përgjigja: A + +Çdo Symbol është tërësisht unik. Arsyeja e jepjes të argumentit në Symbol është të i jap përshkrim Symbol. Vlera e Symbol nuk është e varur nga argumenti i cili i ipet. Meqenëse po testojmë barazueshmërinë, ne jemi duke krijuar dy Symbol tërësisht të reja: `Symbol('foo')` i parë dhe `Symbol('foo)` i dytë. Të dy janë vlera unike dhe jo të barabarta me njëra tjetrën, `Symbol('foo') === Symbol('foo')` kthen `false`. + +

+
+ +--- + +###### 69. Cila është vlera e saj? + +```javascript +const name = 'Lydia Hallie'; +console.log(name.padStart(13)); +console.log(name.padStart(2)); +``` + +- A: `"Lydia Hallie"`, `"Lydia Hallie"` +- B: `" Lydia Hallie"`, `" Lydia Hallie"` (`"[13x whitespace]Lydia Hallie"`, `"[2x whitespace]Lydia Hallie"`) +- C: `" Lydia Hallie"`, `"Lydia Hallie"` (`"[1x whitespace]Lydia Hallie"`, `"Lydia Hallie"`) +- D: `"Lydia Hallie"`, `"Lyd"`, + +
Përgjigja +

+ +#### Përgjigja: C + +Me metodën `padStart`, mund të shtojmë mbushje (padding) në fillim të një stringu. Vlera e kaluar në këtë metodë është gjatësia totale e stringut së bashku me mbushjen. Vargu "Lydia Hallie" ka një gjatësi prej `12` karakteresh. `name.padStart(13)` vendos 1 hapësirë në fillim të vargut, sepse 12 + 1 është 13. + +Nëse argumenti i kaluar në metodën `padStart` është më i vogël se gjatësia e array, nuk do të shtohet asnjë mbushje. + +

+
+ +--- + +###### 70. Cila është vlera e saj? + +```javascript +console.log('🥑' + '💻'); +``` + +- A: `"🥑💻"` +- B: `257548` +- C: Një varg që përmban kodin për t'i shfaqur këto simbole +- D: Error + +
Përgjigja +

+ +#### Përgjigja: A + +Me operatorin `+`, ju mund të bashkoni vargjet. Në këtë rast, ne po bashkojmë stringun `"🥑"` me stringun `"💻"`, duke rezultuar në `"🥑💻"`. + +

+
+ +--- + +###### 71. How can we log the values that are commented out after the console.log statement? + +```javascript +function* startGame() { + const Përgjigja = yield 'Do you love JavaScript?'; + if (Përgjigja !== 'Yes') { + return "Oh wow... Guess we're done here"; + } + return 'JavaScript loves you back ❤️'; +} + +const game = startGame(); +console.log(/* 1 */); // Do you love JavaScript? +console.log(/* 2 */); // JavaScript loves you back ❤️ +``` + +- A: `game.next("Yes").value` dhe `game.next().value` +- B: `game.next.value("Yes")` dhe `game.next.value()` +- C: `game.next().value` dhe `game.next("Yes").value` +- D: `game.next.value()` dhe `game.next.value("Yes")` + +
Përgjigja +

+ +#### Përgjigja: C + +Një funksion gjenerues (generator function) "pauzon" ekzekutimin e tij kur sheh fjalën kyçe `yield`. Së pari, duhet ta lëmë funksionin të japë vargun "A ju pëlqen JavaScript?", i cili mund të bëhet duke thirrur `game.next().value`. + +Çdo rresht ekzekutohet derisa të gjejë fjalën kyçe të parë "yield". Ekziston një fjalë kyçe `yield` në rreshtin e parë brenda funksionit: ekzekutimi ndalon me yield-in e parë! _Kjo do të thotë se variabla `Përgjigja` nuk është përcaktuar ende!_ + +Kur e thërrasim `game.next("Po").value`, `yield` i mëparshëm zëvendësohet me vlerën e parametrave të kaluar në funksionin `next()`, `"Yes"` në këtë rast. Vlera e ndryshores `Përgjigja` tani është e barabartë me `"Yes"`. Kushti i deklaratës if kthehet `false`, dhe `JavaScript loves you back ❤️` printohet. + +

+
+ +--- + +###### 72. Cila është vlera e saj? + +```javascript +console.log(String.raw`Hello\nworld`); +``` + +- A: `Hello world!` +- B: `Hello`      `world` +- C: `Hello\nworld` +- D: `Hello\n`      `world` + +
Përgjigja +

+ +#### Përgjigja: C + +`String.raw` kthen një varg ku karakteret speciale (`\n`, `\v`, `\t` etj.) injorohen! Vizat e pasme mund të jenë një problem pasi mund të përfundoni me diçka si: + +`const path = `C:\Documents\Projects\table.html`` + +E cila do të rezultonte në: + +`"C:DocumentsProjects able.html"` + +Me `String.raw`, vetëm do e injoronte karakterin special dhe do të printonte: + +`C:\Documents\Projects\table.html` + +Në këtë rast, `Hello\nworld` do të printohet. + +

+
+ +--- + +###### 73. Cila është vlera e saj? + +```javascript +async function getData() { + return await Promise.resolve('I made it!'); +} + +const data = getData(); +console.log(data); +``` + +- A: `"I made it!"` +- B: `Promise {: "I made it!"}` +- C: `Promise {}` +- D: `undefined` + +
Përgjigja +

+ +#### Përgjigja: C + +Një funksion asinkron gjithmonë kthen një "promise". `await` duhet të pres për funksionin "promise" te zgjidhjet: një "promise" në pritje do të kthehet kur e thirrim `getData()` në mënyrë që të vendosim `data` në të. + +Nëse do të dëshironim të kemi qasje në vlerën e zgjidhur `"I made it"` do të kishim përdorur metodën `.then()` në `data`: + +`data.then(res => console.log(res))` + +Kjo do të printonte `"I made it!"` + +

+
+ +--- + +###### 74. Cila është vlera e saj? + +```javascript +function addToList(item, list) { + return list.push(item); +} + +const result = addToList('apple', ['banana']); +console.log(result); +``` + +- A: `['apple', 'banana']` +- B: `2` +- C: `true` +- D: `undefined` + +
Përgjigja +

+ +#### Përgjigja: B + +Metoda `.push()` kthen _gjatësinë_ e vargut "array" të ri! Më parë, array përmbante një element (stringun `"banana"`) dhe kishte gjatësinë `1`. Pasi shtuam stringun `"apple"` në array, ai do të përmbajë dy elemente dhe do të ketë gjatësinë `2`. Kjo kthehet nga funksioni `addToList`. + +Metoda `push` modifikon array origjinal. Në qoftëse ju dëshironi të ktheni _array_ nga funksioni në vend të _gjatësisë së vargut_, ateherë ju duhet të ktheni `list` pasi e vendosni `item` në të. + +

+
+ +--- + +###### 75. Cila është vlera e saj? + +```javascript +const box = { x: 10, y: 20 }; + +Object.freeze(box); + +const shape = box; +shape.x = 100; + +console.log(shape); +``` + +- A: `{ x: 100, y: 20 }` +- B: `{ x: 10, y: 20 }` +- C: `{ x: 100 }` +- D: `ReferenceError` + +
Përgjigja +

+ +#### Përgjigja: B + +`Object.freeze` e bën të pamundur shtimin, largimin ose modifikimin e vetive në një objekt (përveç nëse vlera e një vetie është një objekt tjetër). + +Kur krijojmë ndryshoren `shape` dhe e vendosim të barabartë me objektin e ngrirë `box`, `shape` i referohet gjithashtu një objekti të ngrirë. Ju mund të kontrolloni nëse një objekt është i ngrirë duke përdorur `Object.isFrozen`. Në këtë rast, `Object.isFrozen(shape)` do të kthehej e vërtetë, pasi variabla `shape` ka një referencë për një objekt të ngrirë. + +Meqenëse `shape` është e ngrirë dhe meqenëse vlera e `x` nuk është një objekt, ne nuk mund të modifikojmë vetinë `x`. `x` është ende e barabartë me `10` dhe `{ x: 10, y: 20 }` do të printohet. + +

+
+ +--- + +###### 76. Cila është vlera e saj? + +```javascript +const { firstName: myName } = { firstName: 'Lydia' }; + +console.log(firstName); +``` + +- A: `"Lydia"` +- B: `"myName"` +- C: `undefined` +- D: `ReferenceError` + +
Përgjigja +

+ +#### Përgjigja: D + +Duke përdorur [sintaksen e funksioneve destruktuese](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment) ne mund të targetojmë vlerat nga vargjet, ose vetitë nga objektet, në variabla të veçanta: + +```javascript +const { firstName } = { firstName: 'Lydia' }; +// versioni i ES5: +// var firstName = { firstName: 'Lydia' }.firstName; + +console.log(firstName); // "Lydia" +``` + +Gjithashtu, një veti mund të targetohet nga një objekt dhe t'i caktohet një variableje me një emër të ndryshëm nga vetia e objektit: + +```javascript +const { firstName: myName } = { firstName: 'Lydia' }; +// versioni i ES5: +// var myName = { firstName: 'Lydia' }.firstName; + +console.log(myName); // "Lydia" +console.log(firstName); // Uncaught ReferenceError: firstName is not defined +``` + +Prandaj, `firstName` nuk ekziston si variabël, kështu që tentimi për të qasur vlerën e saj do të ngrejë një `ReferenceError`. + +**Shënim:** Kujdes nga vetitë e `global scope`: + +```javascript +const { name: myName } = { name: 'Lydia' }; + +console.log(myName); // "lydia" +console.log(name); // "" ----- Browser psh. Chrome +console.log(name); // ReferenceError: name is not defined ----- NodeJS + +``` + +Kurdo që JavaScript nuk mundet të gjejë një varibël në _current scope_, ngrihet në [Scope chain](https://github.com/getify/You-Dont-Know-JS/blob/2nd-ed/scope-closures/ch3.md) dhe kërkon për të dhe në qoftëse e arrin nivelin më të lartë të shtrirjes (the top-level scope), të quajtur __Global scope__, dhe ende nuk e gjen do të ngrejë `ReferenceError`. + +- Në __Browsers__ si _Chrome_, `name` është _vetia e shtrirjes globale e vjetëruar_. Në këtë shembull, kodi funksionon brenda _global scope_ dhe nuk ka asnjë variabël lokale të përcaktuar nga përdoruesi për `name`, prandaj ai kërkon _variables/properties_ të paracaktuara në shtrirjen globale, në këtë rast shfletuesve, ai kërkon përmes objektit `window`, dhe do të nxjerrë vlerën [window.name](https://developer.mozilla.org/en-US/docs/Web/API/Window/name) e cila është e barabartë me një varg __bosh__. +- Në __NodeJS__, nuk ka një veçori të tillë në objektin `global`, kështu që përpjekja për të iu qasur një variable joekzistente do të ngrejë një [ReferenceError](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/Not_defined). + +

+
+ +--- + +###### 77. A është ky një funksion i pastër? + +```javascript +function sum(a, b) { + return a + b; +} +``` + +- A: Po +- B: Jo + +
Përgjigja +

+ +#### Përgjigja: A + +Një funksion është gjithmonë funksion i pastër nëse sa herë që i kalojmë argumente të njëjta gjithmonë kthen rezultatin e njëjtë. + +Funksioni `sum` _gjithmonë_ kthen të njëjtin rezultat. Nëse i kalojmë `1` dhe `2`, gjithmonë do të kthejë `3` pa ndonjë efekt anësorë. Nëse i kalojmë `5` dhe `10`, gjithmonë do të kthejë `15`, e kështu me radhë. Ky është definicioni i një funksioni të pastër. + +

+
+ +--- + +###### 78. Cila është vlera e saj? + +```javascript +const add = () => { + const cache = {}; + return num => { + if (num in cache) { + return `From cache! ${cache[num]}`; + } else { + const result = num + 10; + cache[num] = result; + return `Calculated! ${result}`; + } + }; +}; + +const addFunction = add(); +console.log(addFunction(10)); +console.log(addFunction(10)); +console.log(addFunction(5 * 2)); +``` + +- A: `Calculated! 20` `Calculated! 20` `Calculated! 20` +- B: `Calculated! 20` `From cache! 20` `Calculated! 20` +- C: `Calculated! 20` `From cache! 20` `From cache! 20` +- D: `Calculated! 20` `From cache! 20` `Error` + +
Përgjigja +

+ +#### Përgjigja: C + +Funksioni `add` është një funksion _memoized_. Me memoizim, ne mund të ruajmë rezultatet e një funksioni në mënyrë që të përshpejtojmë ekzekutimin e tij. Në këtë rast, ne krijojmë një objekt `cache` që ruan vlerat e kthyera më parë. + +Nëse e thirrim sërish funksionin `addFunction` me të njëjtin argument, ai fillimisht kontrollon nëse e ka marrë tashmë atë vlerë në cache-in e tij. Nëse është kështu, vlera e caches do të kthehet, e cila kursen kohën e ekzekutimit. Përndryshe, nëse nuk është i ruajtur në memorie, ai do të llogarisë vlerën dhe do ta ruajë atë më pas. + +Ne e thirrim funksionin `addFunction` tre herë me të njëjtën vlerë: në thirrjen e parë, vlera e funksionit kur `num`" është e barabartë me `10` nuk është ruajtur ende në memorie. Kushtëzimi if `num in cache` kthen `false`, dhe blloku else ekzekutohet: `Calculated! 20` printohet dhe vlera e rezultatit i shtohet objektit të cache-it. `cache` tani duket si `{ 10: 20 }`. + +Herën e dytë, objekti `cache` përmban vlerën që kthehet për `10`. Kushtëzimi if `num in cache` kthen `true`, dhe `'From cache! 20'` printohet. + +Herën e tretë, ne kalojmë `5 * 2` te funksioni i cili llogaritet si `10`. Objekti `cache` përmban vlerën që kthehet për `10`. Kushtëzimi if `num in cache` kthen `true`, dhe `'From cache! 20' printohet. + +

+
+ +--- + +###### 79. Cila është vlera e saj? + +```javascript +const myLifeSummedUp = ['☕', '💻', '🍷', '🍫']; + +for (let item in myLifeSummedUp) { + console.log(item); +} + +for (let item of myLifeSummedUp) { + console.log(item); +} +``` + +- A: `0` `1` `2` `3` dhe `"☕"` `"💻"` `"🍷"` `"🍫"` +- B: `"☕"` `"💻"` `"🍷"` `"🍫"` dhe `"☕"` `"💻"` `"🍷"` `"🍫"` +- C: `"☕"` `"💻"` `"🍷"` `"🍫"` dhe `0` `1` `2` `3` +- D: `0` `1` `2` `3` dhe `{0: "☕", 1: "💻", 2: "🍷", 3: "🍫"}` + +
Përgjigja +

+ +#### Përgjigja: A + +Me unazën _for-in_, ne mund të iterojmë në vetitë _e numërueshme_. Në një array, vetitë e numërueshmë janë "çelësat" e elementeve të array, të cilët janë në të vërtetë indekset e tij. Mund të shikoni array si: + +`{0: "☕", 1: "💻", 2: "🍷", 3: "🍫"}` + +Ku çelësat janë vetitë e numërueshme. `0` `1` `2` `3` printohet. + +Me unazën _for-of_, ne mund të iterojmë mbi __iterables__. Një array është një "iterable". Kur iterojmë mbi array, variabla "item" është e barabartë me elementin mbi të cilin po iterojmë aktualisht, "☕"` `"💻"` `"🍷"` `"🍫"` printohet. + +

+
+ +--- + +###### 80. Cila është vlera e saj? + +```javascript +const list = [1 + 2, 1 * 2, 1 / 2]; +console.log(list); +``` + +- A: `["1 + 2", "1 * 2", "1 / 2"]` +- B: `["12", 2, 0.5]` +- C: `[3, 2, 0.5]` +- D: `[1, 1, 1]` + +
Përgjigja +

+ +#### Përgjigja: C + +Elementet e array mund të mbajnë çfarë vlere. Numra, stringje, objekte, array të tjerë, null, vlera boolean-e, undefined, dhe shprehje të tjera si data, funksione dhe kalkulime. + +Elementi do të jetë i barabartë me vlerën e kthyer. `1 + 2` kthen `3`, `1 * 2` kthen `2` dhe `1 / 2` kthen `0.5`. + +

+
+ +--- + +###### 81. Cila është vlera e saj? + +```javascript +function sayHi(name) { + return `Hi there, ${name}`; +} + +console.log(sayHi()); +``` + +- A: `Hi there,` +- B: `Hi there, undefined` +- C: `Hi there, null` +- D: `ReferenceError` + +
Përgjigja +

+ +#### Përgjigja: B + +Paraprakisht, argumentet kane vlerën `undefined`, përveç në qoftëse ndonjë vlerë i kalohet në funksion. Në këtë rast, ne nuk e kaluam ndonjë vlerë për argumentin `name`. `name` është e barabartë me `undefined` e cila edhe printohet. + +Në ES6, ne mund të mbishkruajmë këtë vlerë paraprake `undefined` me parametër të definuar paraprakisht. Për shembull: + +`function sayHi(name = "Lydia") { ... }` + +Në këtë rast, nëse ne nuk kalojmë ndonjë vlerë ose e kalojmë `undefined`, `name` do të ishte gjithmonë i barabartë me stringun `Lydia`. + +

+
+ +--- + +###### 82. Cila është vlera e saj? + +```javascript +var status = '😎'; + +setTimeout(() => { + const status = '😍'; + + const data = { + status: '🥑', + getStatus() { + return this.status; + }, + }; + + console.log(data.getStatus()); + console.log(data.getStatus.call(this)); +}, 0); +``` + +- A: `"🥑"` and `"😍"` +- B: `"🥑"` and `"😎"` +- C: `"😍"` and `"😎"` +- D: `"😎"` and `"😎"` + +
Përgjigja +

+ +#### Përgjigja: B + +Vlera e fjalës kyçe `this` varet nga vendi ku e përdorni. Në një __metodë__, si metoda `getStatus`, fjala kyçe `this` i referohet _objektit që i përket metoda_. Metoda i përket objektit `data`, kështu që `this` i referohet objektit `data`. Kur printojmë `this.status`, vetia `status` në objektin `data` printohet, që është `"🥑"`. + +Me metodën `call`, ne mund të ndryshojmë objektin të cilit i referohet fjala kyçe `this`. Në __funksione__, fjala kyçe `this` i referohet _objektit të cilit i përket funksioni_. Ne deklaruam funksionin `setTimeout` në objektin _global_, kështu që brenda funksionit `setTimeout`, fjala kyçe `this` i referohet objektit _global_. Në objektin global, ekziston një variabël e quajtur _status_ me vlerën `"😎"`. Kur printoni `this.status`, `"😎"` printohet. + +

+
+ +--- + +###### 83. Cila është vlera e saj? + +```javascript +const person = { + name: 'Lydia', + age: 21, +}; + +let city = person.city; +city = 'Amsterdam'; + +console.log(person); +``` + +- A: `{ name: "Lydia", age: 21 }` +- B: `{ name: "Lydia", age: 21, city: "Amsterdam" }` +- C: `{ name: "Lydia", age: 21, city: undefined }` +- D: `"Amsterdam"` + +
Përgjigja +

+ +#### Përgjigja: A + +0Vendosëm variablën `city` të barabartë me vlerën e vetisë të quajtur `city` në objektin `person.`. Në objekt nuk ka ndonjë veti e cila quhet `city`, kështu që variabla `city` ka vlerën `undefined`. + +Vini re, ne _nuk_ jemi duke iu referuar objektit `person`! Ne vetëm e vendosëm variablën `city` të barabartë me vlerën aktuale të vetisë `city` në objektin `person`. + +Pastaj, ne vendosëm `city` të barabartë me stringun `"Amsterdam"`. Kjo nuk e ndryshon objektin person: nuk ka ndonjë referencë tek ai objekt. + +Kur printojmë objektin `person`. objekti i pamodifikuar kthehet. + +

+
+ +--- + +###### 84. Cila është vlera e saj? + +```javascript +function checkAge(age) { + if (age < 18) { + const message = "Sorry, you're too young."; + } else { + const message = "Yay! You're old enough!"; + } + + return message; +} + +console.log(checkAge(21)); +``` + +- A: `"Sorry, you're too young."` +- B: `"Yay! You're old enough!"` +- C: `ReferenceError` +- D: `undefined` + +
Përgjigja +

+ +#### Përgjigja: C + +Variablat e deklaruara me fjalët kyçe `const` dhe `let` janë të qasshme vetëm në bllokun ku shtrihen (_block-scoped_). Një bllok quhet gjithçka që gjendet brenda kllapave gjarpërore (`{ }`). Në këtë rast, kllapat gjarpërore e deklarimeve if/else. Nuk mund të i referencohemi një variable jashtë bllokut ku është deklaruar, sepse do të ngrihet ReferenceError. + +

+
+ +--- + +###### 85. Çfarë lloj informacioni do të printohet? + +```javascript +fetch('https://www.website.com/api/user/1') + .then(res => res.json()) + .then(res => console.log(res)); +``` + +- A: Rezultati i metodës `fetch`. +- B: Rezultati i thirrjes së dytë së metodës `fetch`. +- C: Rezultati i callback paraprak `.then()` +- D: Do të jetë gjithmonë undefined. + +
Përgjigja +

+ +#### Përgjigja: C + +Vlera e `res` në `.then` të dytë do të jetë e barabartë me vlerën e kthyer në `.then` paraprak. You mund të bëni `.then`-ë të tjerë si në shembull, ku vlera do të kalohet në trajtuesin tjetër. + +

+
+ +--- + +###### 86. Cili opsion do të mundësojë që të vendosim `hasName` të barabartë me `true`, nuk mund të kaloni si argument vlerën `true`? + +```javascript +function getName(name) { + const hasName = // +} +``` + +- A: `!!name` +- B: `name` +- C: `new Boolean(name)` +- D: `name.length` + +
Përgjigja +

+ +#### Përgjigja: A + +Me `!!name`, ne vendosim në qoftëse vlera e `name` është e vërtetë osë false. Nëse "name" është e vërtetë, për të cilën duam të testojmë, `!name` kthen `false`. `!false` (e cila është vlera të cilën `!!name` ka) kthen `true`. + +Kur vendosim `hasName` të barabartë me `name`, ju vendosni `hasName` të barabartë me çdo vlerë të cilën e kaloni si arguemnt tek funksioni `getName`, jo vlera boolean-e `true`. + +`new Boolean(true)` kthen një mbështjellës së objektit, jo vetë vlerën boolean-e. + +`name.length` kthen gjatësinë e argumentit të kaluar, jo në qoftëse është `true` ose jo. + +

+
+ +--- + +###### 87. Cila është vlera e saj? + +```javascript +console.log('I want pizza'[0]); +``` + +- A: `"""` +- B: `"I"` +- C: `SyntaxError` +- D: `undefined` + +
Përgjigja +

+ +#### Përgjigja: B + +Në mënyrë që të marrim karakterin në një indeks specifik në string, mund të përdorimin notacionin e kllapave të mëdha "[]". Karakteri i parë në string ka indeksin 0, dhe kështu me rradhë. Në këtë rast, ne duam të marrim elementin me indeks 0, karakterin `"I"`, i cili printohet. + +Vini re se kjo metodë nuk suportohet në IE7 e më poshtë. Në këtë rast përdorni `.charAt()`. + +

+
+ +--- + +###### 88. Cila është vlera e saj? + +```javascript +function sum(num1, num2 = num1) { + console.log(num1 + num2); +} + +sum(10); +``` + +- A: `NaN` +- B: `20` +- C: `ReferenceError` +- D: `undefined` + +
Përgjigja +

+ +#### Përgjigja: B + +Ne mund të përcaktojmë një vlerë paraprakisht të barabartë me ndonjë parametër tjetër të funksionit, përderisa ato janë të deinuara përpara vlerës së paradefinuar. Ne e kalojmë vlerën `10` tek funksioni `sum`. Nëse funksioni `sum` pranon vetëm një argument, do të thotë se vlera për `num2` nuk është kaluar, dhe vlera e `num1` është e barabartë me vlerën `10` e cila ka kaluar si argument në këtë rast. Vlera e paradefinuar e `num2` është vlera e `num1`, e cila është `10`. `num1 + num2` kthen `20`. + +Në qoftëse provoni të vendosni një vlerë të paradefinuar të barabartë me një parametër i cili definohet _pastaj_ (në të djathë), vlera e parametrit nuk do të jetë e inicializuar ende, e cila do të kthejë një error. + +

+
+ +--- + +###### 89. Cila është vlera e saj? + +```javascript +// module.js +export default () => 'Hello world'; +export const name = 'Lydia'; + +// index.js +import * as data from './module'; + +console.log(data); +``` + +- A: `{ default: function default(), name: "Lydia" }` +- B: `{ default: function default() }` +- C: `{ default: "Hello world", name: "Lydia" }` +- D: Global object of `module.js` + +
Përgjigja +

+ +#### Përgjigja: A + +Me sintaksën `import * as name`, ne importojmë _të gjithë eksportet_ nga fajlli `module.js` në `index.js` si një objekt i ri i cili quhet `data` i cili krijohet. Në `module.js`, gjenden dy eksporta: eksporti i paracaktuar dhe një eksport i emërtuar. Eksporti i paracaktuar është funksion i cili kthen stringun `Hello World`, dhe esksporti i emëruar është variabla e quajtur `name` e cila ka vlerën e stringut `"Lydia"`. + +Objekti `data` ka një veti `default` për eksportin e paracaktuar, vetitë e tjera kanë emrat e eksporteve të emëruara dhe vlerat e tyre korrespoduese. + +

+
+ +--- + +###### 90. Cila është vlera e saj? + +```javascript +class Person { + constructor(name) { + this.name = name; + } +} + +const member = new Person('John'); +console.log(typeof member); +``` + +- A: `"class"` +- B: `"function"` +- C: `"object"` +- D: `"string"` + +
Përgjigja +

+ +#### Përgjigja: C + +Klasat janë si sintaksë që është krijuar për t'i bërë gjërat më të lehta për t'u lexuar ose për t'u shprehur për funksionet e konstruktorëve. Ekuivante e klasës `Person` si funksion kontruktorë do të ishte: + +```javascript +function Person(name) { + this.name = name; +} +``` + +Thirrja e një konstruktori me `new` rezulton në krijimin e një instance të `Person`, `typeof` do të kthejë `"object"` për një instancë. `typeof member` kthen `"object"`. + +

+
+ +--- + +###### 91. Cila është vlera e saj? + +```javascript +let newList = [1, 2, 3].push(4); + +console.log(newList.push(5)); +``` + +- A: `[1, 2, 3, 4, 5]` +- B: `[1, 2, 3, 5]` +- C: `[1, 2, 3, 4]` +- D: `Error` + +
Përgjigja +

+ +#### Përgjigja: D + +Metoda `.push` kthen _gjatësinë e re_ të array, jo vetë array! Duke vendosur `newList` të barabartë me `[1, 2, 3].push(4)`, e vendosim `newList` të barabartë me gjatësinë e re të array: `4`. + +Pastaj, ne provojmë të përdorim metodën `.push` në `newList`. Meqenëse `newList` është vlera numerike e `4` ne nuk mund të përdorim metodën `.push`: do të ngrihet TypeError. + +

+
+ +--- + +###### 92. Cila është vlera e saj? + +```javascript +function giveLydiaPizza() { + return 'Here is pizza!'; +} + +const giveLydiaChocolate = () => + "Here's chocolate... now go hit the gym already."; + +console.log(giveLydiaPizza.prototype); +console.log(giveLydiaChocolate.prototype); +``` + +- A: `{ constructor: ...}` `{ constructor: ...}` +- B: `{}` `{ constructor: ...}` +- C: `{ constructor: ...}` `{}` +- D: `{ constructor: ...}` `undefined` + +
Përgjigja +

+ +#### Përgjigja: D + +Funskionet e rregullta, të tillë si funksioni `giveLydiaPizza`, kanë vetinë `prototype`, e cila është një objekt (veti e objektit) me veti `constructor`. Funksionet shigjetë (arrow functions) sidoqoftë, të tilla si funskioni `giveLydiaChocolate`, nuk e kanë këtë veti `prototype`. Kur tentojmë të i qasemi vetisë `prototype` duke pëdorur `giveLydiaChocolate.prototype` do të na kthehet `undefined`. + +

+
+ +--- + +###### 93. Cila është vlera e saj? + +```javascript +const person = { + name: 'Lydia', + age: 21, +}; + +for (const [x, y] of Object.entries(person)) { + console.log(x, y); +} +``` + +- A: `name` `Lydia` and `age` `21` +- B: `["name", "Lydia"]` and `["age", 21]` +- C: `["name", "age"]` and `undefined` +- D: `Error` + +
Përgjigja +

+ +#### Përgjigja: A + +`Object.entries(person)` kthen një array me array të ndërthurur, i cili përmban çelësat dhe objektet: + +`[ [ 'name', 'Lydia' ], [ 'age', 21 ] ]` + +Përdorimi i unazës `for-of`, na mundëson iterimin në secilin element në array, dhe nën array në këtë rast. Ne mund të destrukturojmë nën array menjëherë në unazën for-of, duke përdorur `const [x, y]`. `x` është e barabartë me elementin e parë në nën array, `y` është e barabartë me elementin e dytë në nën array. + +Nën array i parë është `["name", "Lydia"]`, me `x` të barabartë me `"name"`, dhe `y` të barabartë me `"Lydia"`, e cila printohet. Nën array i dytë është `["age", 21 ]`, me `x` të barabartë me `"age"`, dhe `y` të barabartë me `21`, e cila printohet. + +

+
+ +--- + +###### 94. Cila është vlera e saj? + +```javascript +function getItems(fruitList, ...args, favoriteFruit) { + return [...fruitList, ...args, favoriteFruit] +} + +getItems(["banana", "apple"], "pear", "orange") +``` + +- A: `["banana", "apple", "pear", "orange"]` +- B: `[["banana", "apple"], "pear", "orange"]` +- C: `["banana", "apple", ["pear"], "orange"]` +- D: `SyntaxError` + +
Përgjigja +

+ +#### Përgjigja: D + +`...args` është "rest" parametër. Vlera e "rest" parametrit është një array i cili përmban të gjitha argumentet e mbetura, **dhe mund të jetë vetëm parametri i fundit**! Në këtë shembull, "rest" parametri ishte parametri i dytë. Kjo nuk është e mundur, dhe do të ngrisë gabim sintaksorë. + +```javascript +function getItems(fruitList, favoriteFruit, ...args) { + return [...fruitList, ...args, favoriteFruit]; +} + +getItems(['banana', 'apple'], 'pear', 'orange'); +``` + +Shembulli i mësipërm funskionon. Do të kthejë array `[ 'banana', 'apple', 'orange', 'pear' ]` + +

+
+ +--- + +###### 95. Cila është vlera e saj? + +```javascript +function nums(a, b) { + if (a > b) console.log('a is bigger'); + else console.log('b is bigger'); + return + a + b; +} + +console.log(nums(4, 2)); +console.log(nums(1, 2)); +``` + +- A: `a is bigger`, `6` dhe `b is bigger`, `3` +- B: `a is bigger`, `undefined` dhe `b is bigger`, `undefined` +- C: `undefined` dhe `undefined` +- D: `SyntaxError` + +
Përgjigja +

+ +#### Përgjigja: B + +Në JavaScript, nuk e duhet të e shkruajmë pikëpresjen `;` në mënyrë eksplicite, sidoqoftë makina e JavaScript prapë i vendos ato pas deklarimeve. Kjo quhet __Automatic Semicolon Insertion__ (vendosja e pikëpresjes automatikisht). Një deklaratë për shembull mund të jetë variabla, ose fjalët kyçe si `throw`, `return`, `break` etj. + +Në këtë rast, ne shkruajtëm deklaratën `return`, dhe vlerën tjetër `a + b` në rresht të ri. Sidoqoftë, meqenëse është rresht i ri, makina nuk e di se në të vërtetë ajo është vlera që ne po dëshirojmë të kthejmë. Në vend se të e llogarisë në atë mënyrë, në mënyrë automatike vendoset `return`. Kjo mund të shikohet edhe si kjo sintaksë: + +```javascript +return; +a + b; +``` + +Kjo do të thotë se `a + b` nuk arrihet asnjëherë, meqenëse funksioni ndalon ekzekutimin pas fjalës kyçe `return`. Nëse asnjë vlerë nuk kthehet si në këtë rast, funksioni kthen `undefined`. Vini re se nuk ka ndonjë përfshirje automatike pas deklarimit `if/else` + +

+
+ +--- + +###### 96. Cila është vlera e saj? + +```javascript +class Person { + constructor() { + this.name = 'Lydia'; + } +} + +Person = class AnotherPerson { + constructor() { + this.name = 'Sarah'; + } +}; + +const member = new Person(); +console.log(member.name); +``` + +- A: `"Lydia"` +- B: `"Sarah"` +- C: `Error: cannot redeclare Person` +- D: `SyntaxError` + +
Përgjigja +

+ +#### Përgjigja: B + +Ne mund të iu shoqërojmë klasave konstruktorët e tjerë të klasave/funksioneve. Në këtë rast, ne vendosim `Person` të barabartë me `AnotherPerson`. Emri në këtë konstruktor është `Sarah`, kështu që vetia e emrit në instancën e re `Person`, `member` është `“Sarah”`. + +

+
+ +--- + +###### 97. Cila është vlera e saj? + +```javascript +const info = { + [Symbol('a')]: 'b', +}; + +console.log(info); +console.log(Object.keys(info)); +``` + +- A: `{Symbol('a'): 'b'}` dhe `["{Symbol('a')"]` +- B: `{}` dhe `[]` +- C: `{ a: "b" }` dhe `["a"]` +- D: `{Symbol('a'): 'b'}` dhe `[]` + +
Përgjigja +

+ +#### Përgjigja: D + +Një Symbol nuk është i _numërueshëm_. Metoda Object.keys kthen të gjithë çelësat e _numërueshëm në një objekt. Symbol nuk do të jetë i dukshëm, dhe një array i zbrazët do të kthehet. Kur e printojmë objektin në tërësi, të gjitha vetitë janë të dukshme, edhe ato të cilat nuk janë te numërueshme. + +Kjo është vetëm një nga shumë vetitë e symbol, përveç përfaqësimit të një vlere krejtësisht unike (e cila parandalon konflikt në emërtim të objekteve, për shembull kur punoni me 2 librari që duan të shtojnë vetitë në të njëjtin objekt), ju gjithashtu mund të "fshehni" vetitë e objekteve në këtë mënyrë (edhe pse jo plotësisht. Ju mund t'i qaseni simboleve duke përdorur metodën `Object.getOwnPropertySymbols()`). + +

+
+ +--- + +###### 98. Cila është vlera e saj? + +```javascript +const getList = ([x, ...y]) => [x, y] +const getUser = user => { name: user.name, age: user.age } + +const list = [1, 2, 3, 4] +const user = { name: "Lydia", age: 21 } + +console.log(getList(list)) +console.log(getUser(user)) +``` + +- A: `[1, [2, 3, 4]]` and `SyntaxError` +- B: `[1, [2, 3, 4]]` and `{ name: "Lydia", age: 21 }` +- C: `[1, 2, 3, 4]` and `{ name: "Lydia", age: 21 }` +- D: `Error` and `{ name: "Lydia", age: 21 }` + +
Përgjigja +

+ +#### Përgjigja: A + +Funksioni `getList` merr një array si argument. Brenda kllapave të funksionit `getList`, ne e destrukturojmë ketë array në mënyrën e duhur. Kjo mund të shihet edhe si: + +`[x, ...y] = [1, 2, 3, 4]` + +Me "rest" parametrin `...y`, ne i vendosim argumentet "e mbetura" në një array. Argumentet e mbetura janë `2`, `3` dhe `4` në këtë rast. Vlera e `y` është një array, i cili i përmban të gjithë parametrat e mbetur. Vlera e `x` është e barabartë me `1` në këtë rast kur e printojmë `[x, y]`, printohet `[1, [2, 3, 4]]`. + +Funskioni `getUser` merr një objekt. Me funksionet shigjetë (arrow function), ne nuk kemi nevojë të shkruajmë kllapat gjarpërore nëse vetëm dëshirojmë të kthejmë një vlerë. Sidoqoftë, nëse dëshironi që në mënyrë instante të ktheni një objekt nga një arrow funksion, mund të e shkruani brenda kllapave të vogla "()", përndryshe çdo gjë mes dy kllapave do të interpretohet si një deklaratë blloku. Në këtë rast kodi në mes të kllapave nuk është kod valid i JavaScript, kështu që do të ngrihet `SyntaxError`. + +Funskioni i meposhtëm do të kthente një objekt: + +`const getUser = user => ({ name: user.name, age: user.age })` + +

+
+ +--- + +###### 99. Cila është vlera e saj? + +```javascript +const name = 'Lydia'; + +console.log(name()); +``` + +- A: `SyntaxError` +- B: `ReferenceError` +- C: `TypeError` +- D: `undefined` + +
Përgjigja +

+ +#### Përgjigja: C + +Variabla `name` mban vlerën e një stringu, i cili nuk është funksion, prandaj nuk mund të thirret si i tillë. + +TypeErrors do të ngrihen kur një vlerë nuk është e tipit që pritet. JavaScript pret që `name` të jetë një funksion meqenëse po provojmë të e thirrim atë. Sidoqoftë është një string, prandaj do të marrim TypeError: "name" nuk është një funksion. + +SyntaxErrors do të ngrihen kur ne shënojmë diçka e cila nuk është valide në JavaScript, për shembull kur e shënojmë fjalën `return` si `retrun`. +ReferenceErrors ngrihen kur Javascript-i nuk është në gjendje të gjejë referencë tek një vlerë të cilën ne provojmë të i qasemi. + +

+
+ +--- + +###### 100. Cila është vlera në dalje? + +```javascript +// 🎉✨ Kjo është pytja jonë e 100! ✨🎉 + +const output = `${[] && 'Im'}possible! +You should${'' && `n't`} see a therapist after so much JavaScript lol`; +``` + +- A: `possible! You should see a therapist after so much JavaScript lol` +- B: `Impossible! You should see a therapist after so much JavaScript lol` +- C: `possible! You shouldn't see a therapist after so much JavaScript lol` +- D: `Impossible! You shouldn't see a therapist after so much JavaScript lol` + +
Përgjigja +

+ +#### Përgjigja: B + +`[]` është vlerë "truthy". Me operatorin `&&`, vlera në anën e djathtë do të kthehet nëse vlera në anën e majtë është vlerë "truthy". Në këtë rast, vlera në anën e majtë `[]` është vlerë "truthy" prandaj `"Im"` do të kthehet. + +`""` është vlerë "falsy". Nësë ana e majtë është falsy, asgjë nuk kthehet. `n't` nuk do të kthehet. + +

+
+ +--- + +###### 101. Cila është vlera në dalje? + +```javascript +const one = false || {} || null; +const two = null || false || ''; +const three = [] || 0 || true; + +console.log(one, two, three); +``` + +- A: `false` `null` `[]` +- B: `null` `""` `true` +- C: `{}` `""` `[]` +- D: `null` `null` `true` + +
Përgjigja +

+ +#### Përgjigja: C + +Me operatorin `||`, ne mund të kthejmë vlerën e parë "truthy" të operandit. Nëse të gjitha vlerat janë "falsy", operandi i fundit do të kthehet. + +`(false || {} || null)`: objekti i zbrazët `{}` është vlerë "truthy". Ky është i pari dhe i vetmi vlerë "truthy", i cili kthehet. `one` është i barabartë me `{}`. + +`(null || false || "")`: të gjithë operandët janë vlera "falsy". Kjo do të thotë se operandi i fundit, `""` do të kthehet. `two` është i barabartë me `""`. + +`([] || 0 || "")`: array i zbrazët `[]` është vlerë "truthy". Kjo është vlera e parë "truthy" e cila kthehet. `three` është e barabartë me `[]`. + +

+
+ +--- + +###### 102. Cila është vlera në dalje? + +```javascript +const myPromise = () => Promise.resolve('I have resolved!'); + +function firstFunction() { + myPromise().then(res => console.log(res)); + console.log('second'); +} + +async function secondFunction() { + console.log(await myPromise()); + console.log('second'); +} + +firstFunction(); +secondFunction(); +``` + +- A: `I have resolved!`, `second` and `I have resolved!`, `second` +- B: `second`, `I have resolved!` and `second`, `I have resolved!` +- C: `I have resolved!`, `second` and `second`, `I have resolved!` +- D: `second`, `I have resolved!` and `I have resolved!`, `second` + +
Përgjigja +

+ +#### Përgjigja: D + +Me një premtim, në thelb themi _Dëshiroj ta ekzekutoj këtë funksion, por do të e lë mënjanë për momentin ndërsa është duke u ekzekutuar pasi kjo mund të marrë pak kohë. Vetëm kur një vlerë e caktuar zgjidhet (ose refuzohet) dhe kur "call stack" është bosh, unë dua ta përdor këtë vlerë._ + +Ne mund të marrim këtë rezultat me të dy: `.then` dhe fjalën kyçe `await` në `async` funksione. Edhe pse mund të marrim vlerën e 'promise' me të dy `.then` dhe `await` ato funksionojnë pak më ndryshe. + +Në funksionin e parë `firstFunction`, në një mënyrë e vendosim funksionin 'myPromise' mënjanë përgjatë ekzekutimit, por ne e vazhdojmë ekzekutimin e kodit tjetër, i cili në këtë rast është `console.log('second')`. Pastaj, funksioni zgjidhet me stringun `I have resolved`, i cili pastaj printohet pasi që e sheh se call stack është i zbrazët. + +Me fjalën kyçe `secondFunction`, në të vërtetë e pauzojmë ekzekutimin e funksionit async derisa vlera të zgjidhet përpara se të vazhdojmë tek rreshti tjetër. + +Kjo do të thotë se pret për `myPromise` të zgjidhet me vlerën `I have resolved`, dhe pasi ajo të ndodhë ne vazhdojmë ne rreshtin e ardhshëm: `second` do të printohet. + +

+
+ +--- + +###### 103. Cila është vlera në dalje? + +```javascript +const set = new Set(); + +set.add(1); +set.add('Lydia'); +set.add({ name: 'Lydia' }); + +for (let item of set) { + console.log(item + 2); +} +``` + +- A: `3`, `NaN`, `NaN` +- B: `3`, `7`, `NaN` +- C: `3`, `Lydia2`, `[object Object]2` +- D: `"12"`, `Lydia2`, `[object Object]2` + +
Përgjigja +

+ +#### Përgjigja: C + +Operatori `+` nuk përdoret vetëm vetëm për të mbledhur vlerat numberike, por mund të e përdorim për bashkimin e stringjeve. Sa herë që makina e JavaScript e vëren se një ose më shumë vlera nuk janë numra, e shndërron numrin në string. + +Ne fillim është `1` i cili është vlerë numerike. `1 + 2` kthen numrin 3. + +Megjithatë, vlera e dytë është string `"Lydia"`. `"Lydia"` është string dhe `2` është numër: `2` shndërrohet në string. `"Lydia"` dhe `"2"` bashkohen, dhe kjo rezulton në stringun `"Lydia2"`. + +`{ name: "Lydia"}` është objekt. Nuk është as numër as objekt është string, prandaj i konsideron si stringje të dyja. Sa herë që i konsiderojmë si stringje objektet e zakonshme, behet `"[object Object"]`.`"[object Object"]` bashkohet me `"2"` dhe bëhet `"[object Object]2"`. + +

+
+ +--- + +###### 104. Cila është vlera e saj? + +```javascript +Promise.resolve(5); +``` + +- A: `5` +- B: `Promise {: 5}` +- C: `Promise {: 5}` +- D: `Error` + +
Përgjigja +

+ +#### Përgjigja: C + +Ne mund të kalojmë qfarëdo vlere që duam te `Promise.resolve`, 'promise' ose 'jo-promise'. Metoda vetë kthen një 'promise' e cila zgjidhet me vlerën (`fulfilled`). Nëse i kaloni një funksion të zakonshëm, do të zgjidhet një promise me një vlerë të zakonshme. Nëse i kaloni një 'promise' si argument, do të zgjidhjet një promise me vlerën e zgjidhur me vlerën që i kalohet si promise. + +Në këtë rast, ne vetëm i kaluam si argument vlerën numerike `5`. Kthen promise të zgjidhur me vlerë `5`. + +

+
+ +--- + +###### 105. Cila është vlera e saj? + +```javascript +function compareMembers(person1, person2 = person) { + if (person1 !== person2) { + console.log('Not the same!'); + } else { + console.log('They are the same!'); + } +} + +const person = { name: 'Lydia' }; + +compareMembers(person); +``` + +- A: `Not the same!` +- B: `They are the same!` +- C: `ReferenceError` +- D: `SyntaxError` + +
Përgjigja +

+ +#### Përgjigja: B + +Objektet vendosen si argumente në bazë të referencës së tyre. Kur i kontrollojmë objektet me operatorin për barazim strikt (`===`), ne po kontorllojmë referencën e tyre. + +Ne e paracaktuam vlerën e `person2` të barabartë me objektin `person`, dhe e kaluam objektin `person` si vlerë të `person1`. + +Kjo do të thotë që të dy vlerat kanë referencë të e njejta hapësirë memorike, dhe kështu ato janë të barabarta. + +Blloku i kodit në deklarimin `else` ekzekutohet dhe `They are the same!` printohet. + +

+
+ +--- + +###### 106. Cila është vlera e saj? + +```javascript +const colorConfig = { + red: true, + blue: false, + green: true, + black: true, + yellow: false, +}; + +const colors = ['pink', 'red', 'blue']; + +console.log(colorConfig.colors[1]); +``` + +- A: `true` +- B: `false` +- C: `undefined` +- D: `TypeError` + +
Përgjigja +

+ +#### Përgjigja: D + +Në JavaScript, kemi dy mënyra për të iu qasur vetive të një objekti: notacioni me kllapa të mëdha "[]" ose notacioni me pikë ".". Në këtë shembull ne po e perdorim notacionin (`colorConfig.colors`) në vend të notacionit me kllapë (`colorConfig["colors"]`). + +Me notacionin me pikë, JavaScript provon të gjejë veti në objekt me saktësisht të njejtin emër. Në këtë shembull, JavaScript provon të gjejë një veti e cila quhet `colors` në objektin `colorConfig`. Nuk ka ndonjë veti të quajtur `colors`, prandaj kjo do të kthejë `undefined`. Pastaj ne provojmë të i qasemi vlerës së elementit të parë ne array duke përdorur `[1]`. Nuk mund të e bëjmë këtë në vlerën e cila është `undefined`, prandaj do të ngrihet `TypeError`: `Cannot read property '1' of undefined`. + +JavaScript i interpreton deklarimet. Kur përdorim notacionin me kllapa të mëdha, e sheh kllapën hapëse `[` dhe vazhdon kërkon derisa të gjen kllapën mbyllëse `]`. Vetëm atëherë, e llogarit deklarimin. Nëse do të përdornim `colorConfig[colors[1]]`, do të kishte kthyer vlerën e vetisë `red` në objektin `colorConfig`. + +

+
+ +--- + +###### 107. Cila është vlera e saj? + +```javascript +console.log('❤️' === '❤️'); +``` + +- A: `true` +- B: `false` + +
Përgjigja +

+ +#### Përgjigja: A + +Në prapavijë, emoji-t janë kode të veçanta. Unikodet për emoji-t e zemrës janë `"U+2764 U+FE0F"`. Këto janë gjithmonë të njëjta për të njëjtat emoji, kështu që ne po krahasojmë dy stringje të barabarta me njëri-tjetrin, gjë që ktheh 'e vërtetë'. + +

+
+ +--- + +###### 108. Cila nga këto metoda e modifikon array origjinal? + +```javascript +const emojis = ['✨', '🥑', '😍']; + +emojis.map(x => x + '✨'); +emojis.filter(x => x !== '🥑'); +emojis.find(x => x !== '🥑'); +emojis.reduce((acc, cur) => acc + '✨'); +emojis.slice(1, 2, '✨'); +emojis.splice(1, 2, '✨'); +``` + +- A: `All of them` +- B: `map` `reduce` `slice` `splice` +- C: `map` `slice` `splice` +- D: `splice` + +
Përgjigja +

+ +#### Përgjigja: D + +Me motodën `splice`, ne modifikojmë array origjinal duke fshirë, zëvendësuar ose shtuar elemente. Në këtë rast, ne larguam 2 gjëra duke filluar nga indeksi 1 ( larguam `'🥑'` dhe `'😍'`) dhe shtuam ✨ në vend të tyre. + +`map`, `filter` dhe `slide` kthen array të ri, `find` kthen një element dhe `reduce` kthen një vlerë të reduktuar. + +

+
+ +--- + +###### 109. Cila është vlera e saj? + +```javascript +const food = ['🍕', '🍫', '🥑', '🍔']; +const info = { favoriteFood: food[0] }; + +info.favoriteFood = '🍝'; + +console.log(food); +``` + +- A: `['🍕', '🍫', '🥑', '🍔']` +- B: `['🍝', '🍫', '🥑', '🍔']` +- C: `['🍝', '🍕', '🍫', '🥑', '🍔']` +- D: `ReferenceError` + +
Përgjigja +

+ +#### Përgjigja: A + +Ne vendosëm vlerën e vetisë `favoriteFood` në objektin `info` të barabartë me stringun me emoji-n e picës, `'🍕'`. Një string është një tip i të dhënave primitive. Në JavaScript, tipet primitive të të dhënave nuk ndërveprojnë me referencë. + +Në JavaScript, tipet primitive të të dhënave (gjithçka që nuk është objekt) ndërveprojnë me _vlerë_. Në këtë rast, ne vendosim vlerën e vetisë `favoriteFood` në objektin `info` të barabartë me vlerën e elementit të parë në array `food`, stringu me emoji-n e picës në këtë rast (`'🍕'`). Një string është një tip i të dhënave primitive dhe ndërvepron sipas vlerës (shikoni [blogpost](https://www.theavocoder.com/complete-javascript/2018/12/21/by-value-vs-by-reference) nëse jeni të interesuar të mësoni më shumë) + +Më pas, ne ndryshojmë vlerën e vetisë `favoriteFood` në objektin `info`. Vargu `food` nuk ka ndryshuar, pasi vlera e `favoriteFood` ishte thjesht një _kopje_ e vlerës së elementit të parë në grup dhe nuk ka një referencë për të njëjtin vend në memorie si elementi në `food[0]`. Kur printojmë 'food', është ende array origjinal, "['🍕", "🍫", "🥑", "🍔"]". + +

+
+ +--- + +###### 110. Çfarë bën kjo metodë? + +```javascript +JSON.parse(); +``` + +- A: Parson JSON në një vlerë të JavaScript. +- B: Parson një objekt të JavaScript në JSON. +- C: Parson çfarëdo vlere të JavaScript në JSON. +- D: Parson JSON vetëm në objekt të JavaScript + +
Përgjigja +

+ +#### Përgjigja: A + +Me metodën `JSON.parse()`, ne mund të parsojmë JSON stringun në një vlerë JavaScript-i. + +```javascript +// Stringifimi i një numri në një JSON valid, pastaj parsimi i nje4 stringu në vlerë të JavaScript: +const jsonNumber = JSON.stringify(4); // '4' +JSON.parse(jsonNumber); // 4 + +// Stringifimi i një array në JSON valid, pastaj parsimi i JSON stringut ne një vlerë të JavaScript: +const jsonArray = JSON.stringify([1, 2, 3]); // '[1, 2, 3]' +JSON.parse(jsonArray); // [1, 2, 3] + +// Stringifimi i një objekti në JSON valid, pastaj parsimi i JSON stringut në një vlerë të JavaScript: +const jsonArray = JSON.stringify({ name: 'Lydia' }); // '{"name":"Lydia"}' +JSON.parse(jsonArray); // { name: 'Lydia' } +``` + +

+
+ +--- + +###### 111. Cila është vlera e saj? + +```javascript +let name = 'Lydia'; + +function getName() { + console.log(name); + let name = 'Sarah'; +} + +getName(); +``` + +- A: Lydia +- B: Sarah +- C: `undefined` +- D: `ReferenceError` + +
Përgjigja +

+ +#### Përgjigja: D + +Secili funksion ka _kontekstin e vetë të ekzekutimit_. Funksioni `getName` së pari shikon brenda kontekstit të tij në qoftëse përmban variablën `name` të cilën po provojmë të i qasemi. Në këtë rast, funksioni `getName` përmban variablën e tij `name`: e deklaruam variablën `name` me fjalën kyçe `let`m dhe i inicializuam vlerën `'Sarah'`. + +Variablat me fjalën kyçe `let` (dhe `const`) ngriten (hoistoh-en), por për dallim nga `var` nuk inicializohen. Ato nuk janë të qasshme më herët se rreshti në të cilin janë deklaruar (i kemi deklaruar). Kjo quhet "zona e vdekur e përkohshme" (temporal dead zone). Kur tentojmë të i qasemi variablave përpara se ato të deklarohen, JavaScript hedh `ReferenceError`. + +Nëse nuk do të kishim deklaruar `name` brenda funksionit `getName`, makina e JavaScript do të kishte shikuar poshtë _zingjirit të shtrirjes_. Fusha e jashtme ka variabël të quajtur `name` me vlerë `Lydia`. Në këtë rast, do të kishte printuat `Lydia`. + +```javascript +let name = 'Lydia'; + +function getName() { + console.log(name); +} + +getName(); // Lydia +``` + +

+
+ +--- + +###### 112. Cila është vlera e saj? + +```javascript +function* generatorOne() { + yield ['a', 'b', 'c']; +} + +function* generatorTwo() { + yield* ['a', 'b', 'c']; +} + +const one = generatorOne(); +const two = generatorTwo(); + +console.log(one.next().value); +console.log(two.next().value); +``` + +- A: `a` dhe `a` +- B: `a` dhe `undefined` +- C: `['a', 'b', 'c']` dhe `a` +- D: `a` dhe `['a', 'b', 'c']` + +
Përgjigja +

+ +#### Përgjigja: C + +Me fjalën kyçe `yield`, ne i japim vlerat në një funksion gjenerator. Me fjalën kyçe `yield*`, ne mund të nxjerrim vlera nga një funksion tjetër gjenerues, ose objekt i iterueshëm (për shembull një array). + +Në `generatorOne`, ne japim të gjithë array `['a', 'b', 'c']'` duke përdorur fjalën kyçe `yield`. Vlera e vetisë `value` në objektin e kthyer me metodën `next` në `one` (`one.next().value`) është e barabartë me të gjithë grupin `['a', 'b', 'c']`. + +```javascript +console.log(one.next().value); // ['a', 'b', 'c'] +console.log(one.next().value); // undefined +``` + +Në `generatorTwo`, ne përdorim fjalën kyçe `yield*`. Kjo do të thotë se vlera e parë e dhënë e `two`, është e barabartë me vlerën e dhënë në iterimin e parë. Iteratori është grupi `['a', 'b', 'c']`. Vlera e parë e dhënë është `a`, kështu që herën e parë që thërrasim `two.next().value`, kthehet `a`. + +```javascript +console.log(two.next().value); // 'a' +console.log(two.next().value); // 'b' +console.log(two.next().value); // 'c' +console.log(two.next().value); // undefined +``` + +

+
+ +--- + +###### 113. Cila është vlera e saj? + +```javascript +console.log(`${(x => x)('I love')} to program`); +``` + +- A: `I love to program` +- B: `undefined to program` +- C: `${(x => x)('I love') to program` +- D: `TypeError` + +
Përgjigja +

+ +#### Përgjigja: A + +Shprehjet brenda shablloneve literale vlerësohen së pari. Kjo do të thotë që stringu do të përmbajë vlerën e kthyer të shprehjes, funksionin e thirrur menjëherë `(x => x)('I love')` në këtë rast. Ne e kalojmë vlerën `'I love'` si argument në funksionin e shigjetës `x => x`. `x` është e barabartë me `'I love'`, e cila kthehet. Kjo rezulton në `I love to program`. + +

+
+ +--- + +###### 114. Çfarë do të ndodhë? + +```javascript +let config = { + alert: setInterval(() => { + console.log('Alert!'); + }, 1000), +}; + +config = null; +``` + +- A: Callback `setInterval` nuk do të thirret. +- B: Callback `setInterval` do të thirret një herë. +- C: Callback `setInterval` do të thirret çdo sekond. +- D: Nuk e kemi thirrur asnjëherë `config.alert()`, config është `null`. + +
Përgjigja +

+ +#### Përgjigja: C + +Zakonisht kur i vendosim objektet të barabarta me `null`, ato objekte mirren nga _garbage collector_ pasi nuk ka më referencë për ato objekte. Megjithatë, meqenëse funksioni callback brenda `setInterval` është një funksion me shigjetë (pra i lidhur me objektin `config`), funksioni callback ende mban një referencë për objektin `config`. +Për sa kohë ka një referencë, objekti nuk do të merret nga 'garbage collector' (menaxhuesi i memories për të u larguar). +Meqenëse ky është një interval, vendosja e `config` në '`null` ose `delete` `config.alert` nuk do të mbledhet nga garbage-collector për intervalin, kështu që intervali do të vazhdojë të thirret. +Për ta hequr nga memoria duhet të e pastrojmë me `clearInterval(config.alert)`. +Meqenëse nuk u fshi, funksioni `setInterval` callback do të vazhdojë të thirret çdo 1000ms (1s). + +

+
+ +--- + +###### 115. Cila metodë do të kthejë vlerën `'Hello world!'`? + +```javascript +const myMap = new Map(); +const myFunc = () => 'greeting'; + +myMap.set(myFunc, 'Hello world!'); + +//1 +myMap.get('greeting'); +//2 +myMap.get(myFunc); +//3 +myMap.get(() => 'greeting'); +``` + +- A: 1 +- B: 2 +- C: 2 dhe 3 +- D: Të gjitha + +
Përgjigja +

+ +#### Përgjigja: B + +Kur shtoni një çift çelës/vlerë duke përdorur metodën `set`, çelësi do të jetë vlera e argumentit të parë që i kalohet funksionit `set`, dhe vlera do të jetë argumenti i dytë që i kalohet funksionit `set`. Çelësi është _functioni_ `() => 'greeting'` në këtë rast, dhe vlera `'Hello world'`. `myMap` tani është `{ () => 'greeting' => 'Hello world!' }`. + +1 është gabim, pasi çelësi nuk është `'greeting'` por `() => 'greeting'`. +3 është gabim, pasi ne po krijojmë një funksion të ri duke e kaluar atë si parametër në metodën `get`. Objekti ndërvepron me _referencë_. Funksionet janë objekte, prandaj dy funksione nuk janë kurrë rreptësisht të barabarta, edhe nëse janë identike: ato kanë një referencë në një vend të ndryshëm në memorie. + +

+
+ +--- + +###### 116. Cila është vlera e saj? + +```javascript +const person = { + name: 'Lydia', + age: 21, +}; + +const changeAge = (x = { ...person }) => (x.age += 1); +const changeAgeAndName = (x = { ...person }) => { + x.age += 1; + x.name = 'Sarah'; +}; + +changeAge(person); +changeAgeAndName(); + +console.log(person); +``` + +- A: `{name: "Sarah", age: 22}` +- B: `{name: "Sarah", age: 23}` +- C: `{name: "Lydia", age: 22}` +- D: `{name: "Lydia", age: 23}` + +
Përgjigja +

+ +#### Përgjigja: C + +Të dy funksionet `changeAge` dhe `changeAgeAndName` kanë një parametër të paracaktuar, përkatësisht një objekt të krijuar rishtazi `{...person}`. Ky objekt ka kopje të të gjithë çelësave/vlerave në objektin `person`. + +Së pari, e thirrim funksionin `changeAge` dhe e kalojmë objektin `person` si argument. Ky funksion rrit vlerën e vetisë `age` për 1. `person` tani është `{ name: "Lydia", age: 22 }`. + +Pastaj, e thirrim funksionin `changeAgeAndName`, sidoqoftë ne nuk e kalojmë një parametër. Në vend të kësaj, vlera e `x` është e barabartë me objektin e ri `{ ...person }`. Meqenëse është një objekt i ri, nuk do të afektojë vlerën e vetive në objektin `person`. `person` ende është e barabartë me `{ name: "Lydia", age: 22 }`. + +

+
+ +--- + +###### 117. Cili nga funksionet e mëposhtme do të kthejë `6`? + +```javascript +function sumValues(x, y, z) { + return x + y + z; +} +``` + +- A: `sumValues([...1, 2, 3])` +- B: `sumValues([...[1, 2, 3]])` +- C: `sumValues(...[1, 2, 3])` +- D: `sumValues([1, 2, 3])` + +
Përgjigja +

+ +#### Përgjigja: C + +Me operatorin spread `...`, me mund të _përhapim_ iteruesit në elemente individuale. Funksioni `sumValues` merr tre argumente: `x`, `y` dhe `z`. `...[1, 2, 3]` do të rezultojë në `1, 2, 3`, të cilin ia kalojmë funksionit `sumValues`. + +

+
+ +--- + +###### 118. Cila është vlera e saj? + +```javascript +let num = 1; +const list = ['🥳', '🤠', '🥰', '🤪']; + +console.log(list[(num += 1)]); +``` + +- A: `🤠` +- B: `🥰` +- C: `SyntaxError` +- D: `ReferenceError` + +
Përgjigja +

+ +#### Përgjigja: B + +Me operandin `+=`, ne po rrisim vlerën e `sum` për `1`. `num` kishte vlerën iniciale `1`, kështu `1 + 1` është `2`. Elementi në indeksin e dytë në `list` është 🥰, `console.log(list[2])` printon 🥰. + +

+
+ +--- + +###### 119. Cila është vlera e saj? + +```javascript +const person = { + firstName: 'Lydia', + lastName: 'Hallie', + pet: { + name: 'Mara', + breed: 'Dutch Tulip Hound', + }, + getFullName() { + return `${this.firstName} ${this.lastName}`; + }, +}; + +console.log(person.pet?.name); +console.log(person.pet?.family?.name); +console.log(person.getFullName?.()); +console.log(member.getLastName?.()); +``` + +- A: `undefined` `undefined` `undefined` `undefined` +- B: `Mara` `undefined` `Lydia Hallie` `ReferenceError` +- C: `Mara` `null` `Lydia Hallie` `null` +- D: `null` `ReferenceError` `null` `ReferenceError` + +
Përgjigja +

+ +#### Përgjigja: B + +Me operatorin opsional të zinxhirit `?.`, nuk duhet të kontrollojmë më në mënyrë eksplicite nëse vlerat më të thella të ndërthurura janë të vlefshme apo jo. Nëse po provojmë ti qasemi një vetie me një vlerë `undefined` ose `null` (_nullish_), shprehja lidhet me qark të shkurtër dhe kthen `undefined`. + +`person.pet?.name`: `person` ka një veti të quajtur `pet`: `person.pet` nuk është vlerë null. Ka një veti të quajtur `name`, dhe kthen `Mara`. +`person.pet?.family?.name`: `person` ka një veti të quajtur `pet`: `person.pet` nuk është vlerë null. `pet` nuk ka një veti të quajtur `family`, `person.pet.family` është vlerë null. Shprehja kthen `undefined`. +`person.getFullName?.()`: `person` ka një veti të quajtur `getFullName`: `person.getFullName()` nuk është vlerë null dhe mund të thirret, dhe do të kthejë `Lydia Hallie`. +`member.getLastName?.()`: variabla `member` nuk ekziston prandaj `ReferenceError` do të hedhet! + +

+
+ +--- + +###### 120. Cila është vlera e saj? + +```javascript +const groceries = ['banana', 'apple', 'peanuts']; + +if (groceries.indexOf('banana')) { + console.log('We have to buy bananas!'); +} else { + console.log(`We don't have to buy bananas!`); +} +``` + +- A: We have to buy bananas! +- B: We don't have to buy bananas +- C: `undefined` +- D: `1` + +
Përgjigja +

+ +#### Përgjigja: B + +Ne e kaluam kushtëzimin `groceries.indexOf("banana")` tek deklarimi if. `groceries.indexOf("banana")` kthen `0`, e cila është vlerë false. Përderisa deklarimi i kushtëzimit if është falsy, kodi në bllokun `else` ekzekutohet, dhe `We don't have to buy bananas!` do të printohet. + +

+
+ +--- + +###### 121. Cila është vlera e saj? + +```javascript +const config = { + languages: [], + set language(lang) { + return this.languages.push(lang); + }, +}; + +console.log(config.language); +``` + +- A: `function language(lang) { this.languages.push(lang }` +- B: `0` +- C: `[]` +- D: `undefined` + +
Përgjigja +

+ +#### Përgjigja: D + +Metoda `language` është metodë `setter` (vendosëse). Vendosësit nuk mbajë një vlerë aktuale, qêllimi i tyre është të _modifikojnë_ vetitë. Kur e thirrim metodën `setter`, do të kthehet `undefined`. + +

+
+ +--- + +###### 122. Cila është vlera e saj? + +```javascript +const name = 'Lydia Hallie'; + +console.log(!typeof name === 'object'); +console.log(!typeof name === 'string'); +``` + +- A: `false` `true` +- B: `true` `false` +- C: `false` `false` +- D: `true` `true` + +
Përgjigja +

+ +#### Përgjigja: C + +`typeof name` kthen `"string"`. Stringu `"string"` është vlerë truthy, kështu që `!typeof name` kthen vlerën booleane `false`. `false === "object"` dhe `false === "string"` të dy kthejnë `false`. + +(Nëse do të dëshironim të shikojmë në qoftëse tipi ishtë (jo) i barabartë në një tip të caktuar, do të kishim shkruar `!==` në vend të `!typeof`) + +

+
+ +--- + +###### 123. Cila është vlera e saj? + +```javascript +const add = x => y => z => { + console.log(x, y, z); + return x + y + z; +}; + +add(4)(5)(6); +``` + +- A: `4` `5` `6` +- B: `6` `5` `4` +- C: `4` `function` `function` +- D: `undefined` `undefined` `6` + +
Përgjigja +

+ +#### Përgjigja: A + +Funksioni `add` kthen një funksion shigjete, i cili kthen një funksion shigjete, i cili kthen një funksion shigjete. Funksioni i parë merr një argument `x` me vlerën `4`. Ne e thërrasim funksionin e dytë, i cili merr një argument `y` me vlerën `5`. Pastaj thërrasim funksionin e tretë, i cili merr një argument `z` me vlerën `6`. Kur po provojmë të qasemi në vlerën `x`, `y` dhe `z` brenda funksionit të fundit të shigjetës, makina JS shkon lart në zinxhirin e shtrirjes për të gjetur vlerat për `x` dhe `y` përkatësisht. Kjo kthen `4` `5` `6`. + +

+
+ +--- + +###### 124. Cila është vlera e saj? + +```javascript +async function* range(start, end) { + for (let i = start; i <= end; i++) { + yield Promise.resolve(i); + } +} + +(async () => { + const gen = range(1, 3); + for await (const item of gen) { + console.log(item); + } +})(); +``` + +- A: `Promise {1}` `Promise {2}` `Promise {3}` +- B: `Promise {}` `Promise {}` `Promise {}` +- C: `1` `2` `3` +- D: `undefined` `undefined` `undefined` + +
Përgjigja +

+ +#### Përgjigja: C + +Funksioni gjenerator `range` kthen një objekt asinkron me premtimet për çdo elemnt në rangun që ne japim: `Promise{1}`, `Promise{2}`, `Promise{3}`. Ne vendosim variablën `gen` të jetë e barabartë me objektin asinkron, pas të cilit ne e iterojmë mbi të nëpërmjet unazës `for await ... of`. Ne vendosim variablën `item` të jetë e barabartë me vlerat e kthyera të Promise: së pari `Promise{1}`, pastaj `Promise{2}`, pastaj `Promise{3}`. Pasi që po _presim_ vlerën e `item`, premtimet e zgjidhura, vlerat e zgjidhura të premtimit kthehen: `1`, `2`, pastaj `3`. + +

+
+ +--- + +###### 125. Cila është vlera e saj? + +```javascript +const myFunc = ({ x, y, z }) => { + console.log(x, y, z); +}; + +myFunc(1, 2, 3); +``` + +- A: `1` `2` `3` +- B: `{1: 1}` `{2: 2}` `{3: 3}` +- C: `{ 1: undefined }` `undefined` `undefined` +- D: `undefined` `undefined` `undefined` + +
Përgjigja +

+ +#### Përgjigja: D + +`myFunc` pret një objekt me vetitë `x`, `y` dhe `z` si argumente të tij. Pasi që po japim vetëm tre vlera numerike të ndara (1, 2, 3) në vend të një objekti me vetitë `x`, `y` dhe `z` ({x: 1, y: 2, z: 3}), `x`, `y` dhe `z` kanë vlerën e tyre të parazgjedhur si `undefined`. + +

+
+ +--- + +###### 126. Cila është vlera e saj? + +```javascript +function getFine(speed, amount) { + const formattedSpeed = new Intl.NumberFormat('en-US', { + style: 'unit', + unit: 'mile-per-hour' + }).format(speed); + + const formattedAmount = new Intl.NumberFormat('en-US', { + style: 'currency', + currency: 'USD' + }).format(amount); + + return `The driver drove ${formattedSpeed} and has to pay ${formattedAmount}`; +} + +console.log(getFine(130, 300)) +``` + +- A: The driver drove 130 and has to pay 300 +- B: The driver drove 130 mph and has to pay \$300.00 +- C: The driver drove undefined and has to pay undefined +- D: The driver drove 130.00 and has to pay 300.00 + +
Përgjigja +

+ +#### Përgjigja: B + +Me metoden `Intl.NumberFormat`, ne mund të formatojmë vlerat numerike në çdo vend. Ne formatojmë vlerën numerike `130` në vendin `en-US` si një `unit` në `mile-per-hour`, që rezulton në `130 mph`. Vlera numerike `300` në vendin `en-US` si një `currency` në `USD` rezulton në `$300.00`. + +

+
+ +--- + +###### 127. Cila është vlera e saj? + +```javascript +const spookyItems = ['👻', '🎃', '🕸']; +({ item: spookyItems[3] } = { item: '💀' }); + +console.log(spookyItems); +``` + +- A: `["👻", "🎃", "🕸"]` +- B: `["👻", "🎃", "🕸", "💀"]` +- C: `["👻", "🎃", "🕸", { item: "💀" }]` +- D: `["👻", "🎃", "🕸", "[object Object]"]` + +
Përgjigja +

+ +#### Përgjigja: B + +Duke destrukturuar objektet, ne mund të targetojmë vlerat nga objekti i djathtë, dhe të caktojmë vlerën e targetuar në vlerën e emrit të njëjtë të vetisë në objektin në anën e majtë. Në këtë rast, ne po caktojmë vlerën "💀" në `spookyItems[3]`. Kjo do të thotë se ne po ndryshojmë vargun `spookyItems`, po i shtojmë "💀". Kur printojmë `spookyItems`, `["👻", "🎃", "🕸", "💀"]` printohet. + +

+
+ +--- + +###### 128. Cila është vlera e saj? + +```javascript +const name = 'Lydia Hallie'; +const age = 21; + +console.log(Number.isNaN(name)); +console.log(Number.isNaN(age)); + +console.log(isNaN(name)); +console.log(isNaN(age)); +``` + +- A: `true` `false` `true` `false` +- B: `true` `false` `false` `false` +- C: `false` `false` `true` `false` +- D: `false` `true` `false` `true` + +
Përgjigja +

+ +#### Përgjigja: C + +Me metoden `Number.isNaN`, ju mund të kontrolloni nëse vlera që ju jepni është një _vlerë numerike_ dhe e barabartë me `NaN`. `name` nuk është një vlerë numerike, kështu që `Number.isNaN(name)` kthen `false`. `age` është një vlerë numerike, por nuk është e barabartë me `NaN`, kështu që `Number.isNaN(age)` kthen `false`. + +Me metoden `isNaN`, ju mund të kontrolloni nëse vlera që ju jepni nuk është numër. `name` nuk është numër, kështu që `isNaN(name)` kthen true. `age` është numër, kështu që `isNaN(age)` kthen `false`. + +

+
+ +--- + +###### 129. Cila është vlera e saj? + +```javascript +const randomValue = 21; + +function getInfo() { + console.log(typeof randomValue); + const randomValue = 'Lydia Hallie'; +} + +getInfo(); +``` + +- A: `"number"` +- B: `"string"` +- C: `undefined` +- D: `ReferenceError` + +
Përgjigja +

+ +#### Përgjigja: D + +Variablat e deklaruara me fjalën kyçe `const` nuk janë të referueshme para inicializimit të tyre: kjo quhet _zona e vdekjes së përkohshme_. Në funksionin `getInfo`, variabla `randomValue` është me shtrirje në fushën e funksionit `getInfo`. Në rreshtin ku ne duam të printojmë vlerën e `typeof randomValue`, variabla `randomValue` nuk është inicializuar ende: një `ReferenceError` hidhet! Makina e JS nuk shkoi poshtë në zinxhirin e fushës pasi ne deklaruam variablën `randomValue` në funksionin `getInfo`. + +

+
+ +--- + +###### 130. Cila është vlera e saj? + +```javascript +const myPromise = Promise.resolve('Woah some cool data'); + +(async () => { + try { + console.log(await myPromise); + } catch { + throw new Error(`Oops didn't work`); + } finally { + console.log('Oh finally!'); + } +})(); +``` + +- A: `Woah some cool data` +- B: `Oh finally!` +- C: `Woah some cool data` `Oh finally!` +- D: `Oops didn't work` `Oh finally!` + +
Përgjigja +

+ +#### Përgjigja: C + +Në bllokun `try`, ne jemi duke printuar vlerën e pritur të variablës `myPromise`: `"Woah some cool data"`. Pasi që nuk u hodhën gabime në bllokun `try`, kodi në bllokun `catch` nuk ekzekutohet. Kodi në bllokun `finally` _gjithmonë_ ekzekutohet, `"Oh finally!"` printohet. + +

+
+ +--- + +###### 131. Cila është vlera e saj? + +```javascript +const emojis = ['🥑', ['✨', '✨', ['🍕', '🍕']]]; + +console.log(emojis.flat(1)); +``` + +- A: `['🥑', ['✨', '✨', ['🍕', '🍕']]]` +- B: `['🥑', '✨', '✨', ['🍕', '🍕']]` +- C: `['🥑', ['✨', '✨', '🍕', '🍕']]` +- D: `['🥑', '✨', '✨', '🍕', '🍕']` + +
Përgjigja +

+ +#### Përgjigja: B + +Me metodën flat, ne mund të krijojmë një varg të ri, të rrafshët. Thellësia e vargut të rrafshët varet nga vlera që ne japim. Në këtë rast, ne dhamë vlerën 1 (e cila nuk ishte e nevojshme, ajo është vlera e paracaktuar), që do të thotë se vetëm vargjet në thellësinë e parë do të bashkohen. ['🥑'] dhe ['✨', '✨', ['🍕', '🍕']] në këtë rast. Bashkimi i këtyre dy vargjeve rezulton në ['🥑', '✨', '✨', ['🍕', '🍕']]. + +

+
+ +--- + +###### 132. Cila është vlera e saj? + +```javascript +class Counter { + constructor() { + this.count = 0; + } + + increment() { + this.count++; + } +} + +const counterOne = new Counter(); +counterOne.increment(); +counterOne.increment(); + +const counterTwo = counterOne; +counterTwo.increment(); + +console.log(counterOne.count); +``` + +- A: `0` +- B: `1` +- C: `2` +- D: `3` + +
Përgjigja +

+ +#### Përgjigja: D + +`counterOne` është një instancë e klasës `Counter`. Klasa Counter përmban një veti `count` në konstruktorin e saj, dhe një metodë `increment`. Së pari, ne thirrëm metodën `increment` dy herë duke thirrur `counterOne.increment()`. Aktualisht, `counterOne.count` është `2`. + + + +Më pas, ne krijojmë një variabël të re `counterTwo`, dhe e vendosim të barabartë me `counterOne`. Pasi objektet ndërveprojnë me referencë, ne thjesht po krijojmë një referencë të re për të njëjtin vend në memorie ku `counterOne` tregon. Meqenëse po tregon në të njëjtin vend në memorie, çdo ndryshim i bërë në objektin që `counterTwo` ka një referencë, gjithashtu vlen edhe për `counterOne`. Aktualisht, `counterTwo.count` është `2`. + +Ne thërrasim `counterTwo.increment()`, i cili vendos `count` në `3`. Pastaj, printojmë numëruesin `counterOne`, i cili printon `3`. + + + +

+
+ +--- + +###### 133. Cila është vlera e saj? + +```javascript +const myPromise = Promise.resolve(Promise.resolve('Promise')); + +function funcOne() { + setTimeout(() => console.log('Timeout 1!'), 0); + myPromise.then(res => res).then(res => console.log(`${res} 1!`)); + console.log('Last line 1!'); +} + +async function funcTwo() { + const res = await myPromise; + console.log(`${res} 2!`) + setTimeout(() => console.log('Timeout 2!'), 0); + console.log('Last line 2!'); +} + +funcOne(); +funcTwo(); +``` + +- A: `Promise 1! Last line 1! Promise 2! Last line 2! Timeout 1! Timeout 2!` +- B: `Last line 1! Timeout 1! Promise 1! Last line 2! Promise2! Timeout 2! ` +- C: `Last line 1! Promise 2! Last line 2! Promise 1! Timeout 1! Timeout 2!` +- D: `Timeout 1! Promise 1! Last line 1! Promise 2! Timeout 2! Last line 2!` + +
Përgjigja +

+ +#### Përgjigja: C + +Së pari, ne thirrim `funcOne`. Në rreshtin e parë të `funcOne`, ne thirrim funksionin _asinkron_ `setTimeout`, nga i cili callback është dërguar tek API-ja e Web-it. (shih artikullin tim mbi ciklin e ngjarjeve këtu.) + +Pastaj e thirrim premtimin `myPromise`, e cila është një operacion _asinkron_. + +Edhe premtimi dhe koha e pritjes janë operacione asinkrone, funksioni vazhdon të ekzekutohet ndërsa është i zënë në plotësimin e premtimeve dhe trajtimin e callback-ut `setTimeout`. Kjo do të thotë se `Last line 1!` printohet së pari, pasi kjo nuk është një operacion asinkron. + +Meqenëse callstack nuk është bosh ende, funksioni `setTimeout` dhe premtimi në `funcOne` nuk mund të shtohen ende në callstack. + +Në `funcTwo`, variabla `res` merr `Promise` sepse `Promise.resolve(Promise.resolve('Promise'))` është ekuivalente me `Promise.resolve('Promise')` pasi plotësimi i një premtimi thjesht i plotëson vlerat e tij. `await` në këtë rresht ndalon ekzekutimin e funksionit derisa të marrë zgjidhjen e premtimit dhe pastaj vazhdon të ekzekutohet sinkronisht deri në përfundim, kështu që `Promise 2!` dhe pastaj `Last line 2!` janë regjistruar dhe `setTimeout` është dërguar tek API-ja e Web-it. + +Pastaj call stack është bosh. Premtimet janë _mikrodetyra_ (microtasks) prandaj ato zgjidhen së pari kur call stack është bosh, kështu që `Promise 1!` printohet. + +Tani, pasi që `funcTwo` është larguar nga call stack, call stack është bosh. Callback-et që po presin në radhë (`() => console.log("Timeout 1!")` nga `funcOne`, dhe `() => console.log("Timeout 2!")` nga `funcTwo`) shtohen në call stack një nga një. Callback-i i parë printon `Timeout 1!`, dhe largohet nga stack. Më pas, callback-i i dytë printon `Timeout 2!`, dhe largohet nga stack. + +

+
+ +--- + +###### 134. Si mund të thërrasim funksionin `sum` nga `sum.js` në `index.js`? + +```javascript +// sum.js +export default function sum(x) { + return x + x; +} + +// index.js +import * as sum from './sum'; +``` + +- A: `sum(4)` +- B: `sum.sum(4)` +- C: `sum.default(4)` +- D: Eksportimet e paracaktuar nuk importohen me `*`, vetëm eksportimet e emëruara. + +
Përgjigja +

+ +#### Përgjigja: C + +Me yllin `*`, ne importojmë të gjitha vlerat e eksportuara nga ai fajll, si ato të paracaktuara dhe ato të emëruara. Nëse kemi fajllin e mëposhtëm: + +```javascript +// info.js +export const name = 'Lydia'; +export const age = 21; +export default 'I love JavaScript'; + +// index.js +import * as info from './info'; +console.log(info); +``` + +The following would get logged: + +```javascript +{ + default: "I love JavaScript", + name: "Lydia", + age: 21 +} +``` + +Për shembullin `sum`, do të thotë se vlera e importuar e `sum` do të dukej kështu: + +```javascript +{ default: function sum(x) { return x + x } } +``` + +Mund të e thërrasim këtë funksion, duke thirrur `sum.default` + +

+
+ +--- + +###### 135. Cila është vlera e saj? + +```javascript +const handler = { + set: () => console.log('Added a new property!'), + get: () => console.log('Accessed a property!'), +}; + +const person = new Proxy({}, handler); + +person.name = 'Lydia'; +person.name; +``` + +- A: `Added a new property!` +- B: `Accessed a property!` +- C: `Added a new property!` `Accessed a property!` +- D: Asgjë nuk printohet + +
Përgjigja +

+ +#### Përgjigja: C + +Me një objekt Proxy, ne mund të shtojmë sjellje të personalizuara për një objekt të cilit i kalohet si argumenti i dytë. Në këtë rast, ne i kalojmë objektin `handler` i cili përmban dy veti: `set` dhe `get`. `set` thirret çdo herë kur ne _caktojmë_ vlerat e vetisë, `get` thirret çdo herë kur ne _marrim_ (i qasemi) vlerave të vetisë. + +Argumenti i parë është një objekt i zbrazët `{}`, i cili është vlera e `person`. Tek ky objekt, shtohet sjellja e personalizuar e specifikuar në objektin `handler`. Nëse shtojmë një veti tek objekti `person`, `set` do të thirret. Nëse i qasemi një vetie në objektin `person`, `get` do të thirret. + +Së pari, ne shtuam një veti të re `name` tek objekti proxy (`person.name = "Lydia"`). `set` thirret, dhe printon `"Added a new property!"`. + +Pastaj, ne i qasemi një vlerë të vetisë në objektin proxy, vetia `get` në objektin handler thirret. `"Accessed a property!"` printohet. + +

+
+ +--- + +###### 136. Cili nga opsionet e mëposhtme do të modifikojë objektin `person`? + +```javascript +const person = { name: 'Lydia Hallie' }; + +Object.seal(person); +``` + +- A: `person.name = "Evan Bacon"` +- B: `person.age = 21` +- C: `delete person.name` +- D: `Object.assign(person, { age: 21 })` + +
Përgjigja +

+ +#### Përgjigja: A + +Me `Object.seal` ne mund të parandalojmë shtimin e vetive të reja, ose fshirjen e vetive ekzistuese. + +Megjithatë, ju ende mund të modifikoni vlerën e vetive ekzistuese. + +

+
+ +--- + +###### 137. Cili nga opsionet e mëposhtme do të modifikojë objektin `person`? + +```javascript +const person = { + name: 'Lydia Hallie', + address: { + street: '100 Main St', + }, +}; + +Object.freeze(person); +``` + +- A: `person.name = "Evan Bacon"` +- B: `delete person.address` +- C: `person.address.street = "101 Main St"` +- D: `person.pet = { name: "Mara" }` + +
Përgjigja +

+ +#### Përgjigja: C + +Metoda `Object.freeze` _ngrin_ një objekt. Asnjë veti nuk mund të shtohet, të modifikohet, ose të hiqet. + +Megjithatë, ajo vetëm _ngrin sipërfaqësisht_ objektin, që do të thotë se vetëm vetitë _e drejtpërdrejta_ në objekt janë të ngrira. Nëse vetia është një tjetër objekt, si `address` në këtë rast, vetitë në atë objekt nuk janë të ngrira, dhe mund të modifikohen. + +

+
+ +--- + +###### 138. Cila është vlera e saj? + +```javascript +const add = x => x + x; + +function myFunc(num = 2, value = add(num)) { + console.log(num, value); +} + +myFunc(); +myFunc(3); +``` + +- A: `2` `4` and `3` `6` +- B: `2` `NaN` and `3` `NaN` +- C: `2` `Error` and `3` `6` +- D: `2` `4` and `3` `Error` + +
Përgjigja +

+ +#### Përgjigja: A + +Së pari, ne thirrëm `myFunc()` pa kaluar asnjë argument. Pasi që nuk kaluam argumente, `num` dhe `value` morën vlerat e tyre të paracaktuara: num është `2`, dhe `value` është vlera e kthyer nga funksioni `add`. Tek funksioni `add`, ne i japim si argument `num`, i cili ka vlerën `2`. `Add` kthen `4`, e cila është vlera e `value`. + +Më pas, ne thirrëm `myFunc(3)` dhe kaluam vlerën `3` si vlerë për argumentin `num`. Nuk kaluam një argument për `value`. Pasi nuk kaluam një vlerë për argumentin `value`, ai mori vlerën e paracaktuar: vlerën e kthyer nga funksioni `add`. Tek `add`, ne i japim si argument `num`, i cili ka vlerën `3`. `Add` kthen `6`, e cila është vlera e `value`. + +

+
+ +--- + +###### 139. Cila është vlera e saj? + +```javascript +class Counter { + #number = 10 + + increment() { + this.#number++ + } + + getNum() { + return this.#number + } +} + +const counter = new Counter() +counter.increment() + +console.log(counter.#number) +``` + +- A: `10` +- B: `11` +- C: `undefined` +- D: `SyntaxError` + +
Përgjigja +

+ +#### Përgjigja: D + +Në ES2020, mund të shtojmë variabla private në klasa duke përdorur `#`. Nuk mund t'i qasemi këtyre variablave jashtë klasës. Kur provojmë të printojmë `counter.#number`, hidhet një SyntaxError: nuk mund t'i qaseni jashtë klasës `Counter`! + +

+
+ +--- + +###### 140. Çfarë po mungon? + +```javascript +const teams = [ + { name: 'Team 1', members: ['Paul', 'Lisa'] }, + { name: 'Team 2', members: ['Laura', 'Tim'] }, +]; + +function* getMembers(members) { + for (let i = 0; i < members.length; i++) { + yield members[i]; + } +} + +function* getTeams(teams) { + for (let i = 0; i < teams.length; i++) { + // ✨ SOMETHING IS MISSING HERE ✨ + } +} + +const obj = getTeams(teams); +obj.next(); // { value: "Paul", done: false } +obj.next(); // { value: "Lisa", done: false } +``` + +- A: `yield getMembers(teams[i].members)` +- B: `yield* getMembers(teams[i].members)` +- C: `return getMembers(teams[i].members)` +- D: `return yield getMembers(teams[i].members)` + +
Përgjigja +

+ +#### Përgjigja: B + +Për të iteruar mbi `members` në çdo element në array `teams`, duhet të kaloni `teams[i].members` në funksionin gjenerator `getMembers`. Funksioni gjenerator kthen një objekt gjenerator. Për të iteruar mbi çdo element në këtë objekt gjenerator, duhet të përdorim `yield*`. + +Nëse do të shkruanim `yield`, `return yield`, ose `return`, gjithë funksioni gjenerator do të kthehej herën e parë që do e thirrim metodën `next`. + +

+
+ +--- + +###### 141. Cila është vlera e saj? + +```javascript +const person = { + name: 'Lydia Hallie', + hobbies: ['coding'], +}; + +function addHobby(hobby, hobbies = person.hobbies) { + hobbies.push(hobby); + return hobbies; +} + +addHobby('running', []); +addHobby('dancing'); +addHobby('baking', person.hobbies); + +console.log(person.hobbies); +``` + +- A: `["coding"]` +- B: `["coding", "dancing"]` +- C: `["coding", "dancing", "baking"]` +- D: `["coding", "running", "dancing", "baking"]` + +
Përgjigja +

+ +#### Përgjigja: C + +Funksioni `addHobby` merr dy argumente, `hobby` dhe `hobbies` me vlerën e paracaktuar të array `hobbies` në objektin `person`. + +Së pari, ne thirrim funksionin `addHobby`, dhe japim `"running"` si vlerë për `hobby` dhe një array bosh si vlerë për `hobbies`. Pasi japim një varg bosh si vlerë për `hobbies`, `"running"` shtohet në këtë varg bosh. + +Pastaj, ne thirrim funksionin `addHobby`, dhe japim `"dancing"` si vlerë për `hobby`. Nuk kemi dhënë vlerë për `hobbies`, kështu që ajo merr vlerën e paracaktuar, vetinë `hobbies` në objektin `person`. Ne shtojmë hobi `dancing` në array `person.hobbies`. + +Në fund, ne thirrim funksionin `addHobby`, dhe japim `"baking"` si vlerë për `hobby`, dhe array `person.hobbies` si vlerë për `hobbies`. Ne shtojmë hobi `baking` në array `person.hobbies`. + +Pas shtimit të `dancing` dhe `baking`, vlera e `person.hobbies` është `["coding", "dancing", "baking"]` + +

+
+ +--- + +###### 142. Cila është vlera e saj? + +```javascript +class Bird { + constructor() { + console.log("I'm a bird. 🦢"); + } +} + +class Flamingo extends Bird { + constructor() { + console.log("I'm pink. 🌸"); + super(); + } +} + +const pet = new Flamingo(); +``` + +- A: `I'm pink. 🌸` +- B: `I'm pink. 🌸` `I'm a bird. 🦢` +- C: `I'm a bird. 🦢` `I'm pink. 🌸` +- D: Asgjë, ne nuk kemi thirrur ndonjë metodë. + +
Përgjigja +

+ +#### Përgjigja: B + +Krijojmë variablën `pet` që është një instancë e klasës `Flamingo`. Kur ne e instantojmë këtë instancë, thirret `constructor` në `Flamingo`. Së pari, `"I'm pink. 🌸"` printohet, pas të cilit thirrim `super()`. `super()` thirr constructorin e klasës prind, `Bird`. Thirret constructori në `Bird`, dhe printon `"I'm a bird. 🦢"`. + +

+
+ +--- + +###### 143. Cila nga opsionet rezulton me gabim? + +```javascript +const emojis = ['🎄', '🎅🏼', '🎁', '⭐']; + +/* 1 */ emojis.push('🦌'); +/* 2 */ emojis.splice(0, 2); +/* 3 */ emojis = [...emojis, '🥂']; +/* 4 */ emojis.length = 0; +``` + +- A: 1 +- B: 1 and 2 +- C: 3 and 4 +- D: 3 + +
Përgjigja +

+ +#### Përgjigja: D + +Fjala kyçe `const` thjesht do të thotë se nuk mund të _ri-deklarojmë_ vlerën e asaj ndryshore, është _vetëm për lexim_. Megjithatë, vlera e elementeve të array nuk është e pandryshueshme. Vetitë në vargun `emojis` mund të modifikohen, për shembull duke shtuar vlera të reja, duke i shpërndarë ato, ose duke caktuar gjatësinë e vargut në 0. + +

+
+ +--- + +###### 144. Çfarë duhet të shtojmë në objektin `person` për të marrë `["Lydia Hallie", 21]` si rezultat të `[...person]`? + +```javascript +const person = { + name: "Lydia Hallie", + age: 21 +} + +[...person] // ["Lydia Hallie", 21] +``` + +- A: Asgjë, objektet janë të iterueshme paraprakisht. +- B: `*[Symbol.iterator]() { for (let x in this) yield* this[x] }` +- C: `*[Symbol.iterator]() { yield* Object.values(this) }` +- D: `*[Symbol.iterator]() { for (let x in this) yield this }` + +
Përgjigja +

+ +#### Përgjigja: C + +Objektet nuk janë të paraprakisht të iterueshme. Një objekt është i iterueshëm nëse protokolli i iteratorëve është prezent. Ne mund ta shtojmë këtë manualisht duke shtuar simbolin e iteratorit `[Symbol.iterator]`, i cili duhet të kthejë një objekt gjenerator, për shembull duke e bërë atë një funksion gjenerator `*[Symbol.iterator]() {}`. Ky funksion gjenerator duhet të prodhojë `Object.values` e objektit `person` nëse dëshirojmë që të kthejë array `["Lydia Hallie", 21]`: `yield* Object.values(this)`. + +

+
+ +--- + +###### 145. Cila është vlera e saj? + +```javascript +let count = 0; +const nums = [0, 1, 2, 3]; + +nums.forEach(num => { + if (num) count += 1 +}) + +console.log(count) +``` + +- A: 1 +- B: 2 +- C: 3 +- D: 4 + +
Përgjigja +

+ +#### Përgjigja: C + +Kushti `if` brenda ciklit `forEach` kontrollon nëse vlera e `num` është e vërtetë apo false. Meqenëse numri i parë në array `nums` është `0`, një vlerë false, blloku i kodit të deklaratës `if` nuk do të ekzekutohet. `count` rritet vetëm për 3 numrat e tjerë në array `nums`, `1`, `2` dhe `3`. Meqenëse `count` rritet për `1` 3 herë, vlera e `count` është `3`. + +

+
+ +--- + +###### 146. Cila është vlera e saj? + +```javascript +function getFruit(fruits) { + console.log(fruits?.[1]?.[1]) +} + +getFruit([['🍊', '🍌'], ['🍍']]) +getFruit() +getFruit([['🍍'], ['🍊', '🍌']]) +``` + +- A: `null`, `undefined`, 🍌 +- B: `[]`, `null`, 🍌 +- C: `[]`, `[]`, 🍌 +- D: `undefined`, `undefined`, 🍌 + +
Përgjigja +

+ +#### Përgjigja: D + +Simboli ? na lejon të i qasemi opsionalisht vetive më të thella brenda objekteve. Ne po provojmë të shfaqim elementin në indeksin 1 brenda në nën-array që është në indeksin 1 të array fruits. Nëse nën-array në indeksin 1 në array fruits nuk ekziston, thjesht do të kthejë undefined. Nëse nën-array në indeksin 1 në vargun fruits ekziston, por ky nën-array nuk ka një artikull në indeksin e tij 1, gjithashtu do të kthejë undefined. + +Së pari, ne po përpiqemi të printojmë artikullin e dytë në nën-array `['🍍']` të `[['🍊', '🍌'], ['🍍']]`. Ky nën-array përmban vetëm një element, që do të thotë se nuk ka element në indeksin `1`, dhe kthen `undefined`. + +Më pas, ne po thërrasim funksionin `getFruits` pa kaluar një vlerë si argument, që do të thotë se `fruits` ka vlerë `undefined` të paracaktuar. Pasi që po lidhim në mënyrë kushtëzuese elementin në indeksin `1` të `fruits`, kthen `undefined` pasi ky element në indeksin `1` nuk ekziston. + +Së fundmi, po përpiqemi të shfaqim artikullin e dytë në nën-array `['🍊', '🍌']` të `['🍍'], ['🍊', '🍌']`. Elementi në indeksin `1` brenda këtij nën-array është `🍌` që printohet. + +

+
+ +--- + +###### 147. Cila është vlera e saj? + +```javascript +class Calc { + constructor() { + this.count = 0 + } + + increase() { + this.count ++ + } +} + +const calc = new Calc() +new Calc().increase() + +console.log(calc.count) +``` + +- A: `0` +- B: `1` +- C: `undefined` +- D: `ReferenceError` + +
Përgjigja +

+ +#### Përgjigja: A + +Ne i caktojmë variablës `calc` të jetë e barabartë me një instancë të re të klasës `Calc`. Më pas, ne krijojmë një instancë të re të `Calc`, dhe thërrasim metodën `increase` në këtë instancë. Pasi që vetia 'count' është brenda konstruktorit të klasës `Calc`, vetia 'calc' nuk është e përbashkët në prototipin e `Calc`. Kjo do të thotë se vlera 'calc' nuk është përditësuar për instancën që tregon calc, numërimi është ende `0`. + +

+
+ +--- + +###### 148. Cila është vlera e saj? + +```javascript +const user = { + email: "e@mail.com", + password: "12345" +} + +const updateUser = ({ email, password }) => { + if (email) { + Object.assign(user, { email }) + } + + if (password) { + user.password = password + } + + return user +} + +const updatedUser = updateUser({ email: "new@email.com" }) + +console.log(updatedUser === user) +``` + +- A: `false` +- B: `true` +- C: `TypeError` +- D: `ReferenceError` + +
Përgjigja +

+ +#### Përgjigja: B + +Funksioni `updateUser` përditëson vlerat e vetive `email` dhe `password` në user, nëse vlerat e tyre i janë kaluar funksionit, pas së cilës funksioni kthen objektin `user`. Vlera e kthyer e funksionit `updateUser` është objekti `user`, që do të thotë se vlera e updatedUser është një referencë për të njëjtin objekt `user` që tregon `user`. `updatedUser === user` është e barabartë me `true`. + +

+
+ +--- + +###### 149. Cila është vlera e saj? + +```javascript +const fruit = ['🍌', '🍊', '🍎'] + +fruit.slice(0, 1) +fruit.splice(0, 1) +fruit.unshift('🍇') + +console.log(fruit) +``` + +- A: `['🍌', '🍊', '🍎']` +- B: `['🍊', '🍎']` +- C: `['🍇', '🍊', '🍎']` +- D: `['🍇', '🍌', '🍊', '🍎']` + +
Përgjigja +

+ +#### Përgjigja: C + +Së pari, ne thirrim metodën `slice` në array e frutave. Metoda slice nuk modifikon array origjinal, por kthen vlerën që e ka 'prerë (slice)' nga array: emoji e bananes. +Më pas, ne thirrim metodën `splice` në array e frutave. Metoda splice modifikon array origjinal, që do të thotë se array i frutave tani përbëhet nga `['🍊', '🍎']`. +Në fund, ne thirrim metodën `unshift` në array e frutave, e cila modifikon array origjinal duke shtuar vlerën e dhënë, në këtë rast ‘🍇’, si elementin e parë në varg. Array i frutave tani përbëhet nga `['🍇', '🍊', '🍎']`. + +

+
+ +--- + +###### 150. Cila është vlera e saj? + +```javascript +const animals = {}; +let dog = { emoji: '🐶' } +let cat = { emoji: '🐈' } + +animals[dog] = { ...dog, name: "Mara" } +animals[cat] = { ...cat, name: "Sara" } + +console.log(animals[dog]) +``` + +- A: `{ emoji: "🐶", name: "Mara" }` +- B: `{ emoji: "🐈", name: "Sara" }` +- C: `undefined` +- D: `ReferenceError` + +
Përgjigja +

+ +#### Përgjigja: B + +Çelësat e objektit konvertohen në stringje. + +Pasi që vlera e `dog` është një objekt, `animals[dog]` në fakt do të thotë që ne po krijojmë një veti të re të quajtur `"object Object"` të barabartë me objektin e ri. Tani `animals["object Object"]` është i barabartë me `{ emoji: "🐶", name: "Mara"}`. + +`cat` është gjithashtu një objekt, që do të thotë që `animals[cat]` në fakt do të thotë se ne po mbishkruajmë vlerën e `animals["object Object"]` me vetitë e reja të macës. + +Duke printuar `animals[dog]`, ose në fakt `animals["object Object"]` pasi që konvertimi i objektit `dog` në string rezulton në `"object Object"`, kthen `{ emoji: "🐈", name: "Sara" }`. + +

+
+ +--- + +###### 151. Cila është vlera e saj? + +```javascript +const user = { + email: "my@email.com", + updateEmail: email => { + this.email = email + } +} + +user.updateEmail("new@email.com") +console.log(user.email) +``` + +- A: `my@email.com` +- B: `new@email.com` +- C: `undefined` +- D: `ReferenceError` + +
Përgjigja +

+ +#### Përgjigja: A + +Funksioni `updateEmail` është një funksion shigjetë dhe nuk është i lidhur me objektin `user`. Kjo do të thotë se fjalë kyçe `this` nuk i referohet objektit `user`, por i referohet shtrirjes globale në këtë rast. Vlera e `email` brenda objektit `user` nuk përditësohet. Kur printohet vlera e `user.email`, kthehet vlera origjinale e `my@email.com`. + +

+
+ +--- + +###### 152. Cila është vlera e saj? + +```javascript +const promise1 = Promise.resolve('First') +const promise2 = Promise.resolve('Second') +const promise3 = Promise.reject('Third') +const promise4 = Promise.resolve('Fourth') + +const runPromises = async () => { + const res1 = await Promise.all([promise1, promise2]) + const res2 = await Promise.all([promise3, promise4]) + return [res1, res2] +} + +runPromises() + .then(res => console.log(res)) + .catch(err => console.log(err)) +``` + +- A: `[['First', 'Second'], ['Fourth']]` +- B: `[['First', 'Second'], ['Third', 'Fourth']]` +- C: `[['First', 'Second']]` +- D: `'Third'` + +
Përgjigja +

+ +#### Përgjigja: D + +Metoda `Promise.all` ekzekuton premtimet e dhëna si argumente paralelisht. Nëse një premtim dështon, metoda 'Promise.all' _refuzon_ me vlerën e premtimit të refuzuar. Në këtë rast, `promise3` u refuzua me vlerën `"Third"`. Ne po kapim vlerën e refuzuar në metodën `catch` në thirrjen `runPromises` për të kapur çdo gabim brenda funksionit `runPromises`. Vetëm `"Third"` printohet, pasi `promise3` u refuzua me këtë vlerë. + +

+
+ +--- + +###### 153. Cila duhet të jetë vlera e `method` për të printuar `{ name: "Lydia", age: 22 }`? + +```javascript +const keys = ["name", "age"] +const values = ["Lydia", 22] + +const method = /* ?? */ +Object[method](keys.map((_, i) => { + return [keys[i], values[i]] +})) // { name: "Lydia", age: 22 } +``` + +- A: `entries` +- B: `values` +- C: `fromEntries` +- D: `forEach` + +
Përgjigja +

+ +#### Përgjigja: C + +Metoda `fromEntries` transformon një array 2d në një objekt. Elementi i parë në çdo nën-array do të jetë çelësi, dhe elementi i dytë në çdo nën-array do të jetë vlera. Në këtë rast, ne jemi duke mapuar mbi array `keys`, i cili kthen një array ku elementi i parë është elementi në array të çelësave në indeksin aktual, dhe elementi i dytë është elementi i vlerave të array në indeksin aktual. + +Kjo krijon një array të nën-arrays që përmbajnë çelësat dhe vlerat e duhura, të cilat rezultojnë në `{ name: "Lydia", age: 22 }` + +

+
+ +--- + +###### 154. Cila është vlera e saj? + +```javascript +const createMember = ({ email, address = {}}) => { + const validEmail = /.+\@.+\..+/.test(email) + if (!validEmail) throw new Error("Valid email pls") + + return { + email, + address: address ? address : null + } +} + +const member = createMember({ email: "my@email.com" }) +console.log(member) +``` + +- A: `{ email: "my@email.com", address: null }` +- B: `{ email: "my@email.com" }` +- C: `{ email: "my@email.com", address: {} }` +- D: `{ email: "my@email.com", address: undefined }` + +
Përgjigja +

+ +#### Përgjigja: C + +Vlera e paracaktuar e `address` është një objekt i zbrazët `{}`. Kur vendosëm variablën `member` të barabartë me objektin që kthehet nga funksioni `createMember`, ne nuk kaluam një vlerë për adresën, që do të thotë se vlera e adresës është objekti i zbrazët parazgjedhur `{}`. Një objekt i zbrazët është një vlerë e vërtetë, që do të thotë se gjendja e `address ? address : null` kushtëzuese kthehet `true`. Vlera e adresës është objekti i zbrazët `{}`. + +

+
+ +--- + +###### 155. Cila është vlera e saj? + +```javascript +let randomValue = { name: "Lydia" } +randomValue = 23 + +if (!typeof randomValue === "string") { + console.log("It's not a string!") +} else { + console.log("Yay it's a string!") +} +``` + +- A: `It's not a string!` +- B: `Yay it's a string!` +- C: `TypeError` +- D: `undefined` + +
Përgjigja +

+ +#### Përgjigja: B + +Kushti brenda deklaratës `if` kontrollon nëse vlera e `!typeof randomValue` është e barabartë me `"string"`. Operatori `!` e shndërron vlerën në një vlerë booleane. Nëse vlera është e vërtetë, vlera e kthyer do të jetë `false`, nëse vlera është e pavërtetë, vlera e kthyer do të jetë `true`. Në këtë rast, vlera e kthyer e `typeof randomValue` është vlera e vërtetë `"number"`, që do të thotë se vlera e `!typeof randomValue` është vlera booleane `false`. + +`!typeof randomValue === "string"` gjithmonë kthen false, pasi në fakt po kontrollojmë `false === "string"`. Pasi që kushtëzimi ktheu `false`, blloku i kodit të deklaratës `else` ekzekutohet, dhe `Yay it's a string!` printohet. + +

+
From a2da426359113149ec7dc4a821d5f2c81a5b28fa Mon Sep 17 00:00:00 2001 From: Egzona Vllasaliu Date: Sun, 30 Jul 2023 02:05:56 +0200 Subject: [PATCH 160/193] Modify main READMe.md --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index 80c8d584..1cd5bd33 100644 --- a/README.md +++ b/README.md @@ -40,6 +40,7 @@ Feel free to reach out to me! 😊
- [🇻🇳 Tiếng Việt](./vi-VI/README-vi.md) - [🇨🇳 简体中文](./zh-CN/README-zh_CN.md) - [🇹🇼 繁體中文](./zh-TW/README_zh-TW.md) +- [🇽🇰 Shqip](./sq-KS/README_sq_KS.md)

From 03e434f844a68f618a637f2f21017570ece9be35 Mon Sep 17 00:00:00 2001 From: EgzonaVllasaliu <44296118+EgzonaVllasaliu@users.noreply.github.com> Date: Tue, 1 Aug 2023 07:29:22 +0000 Subject: [PATCH 161/193] Link all languages in the same way for consistentcy --- README.md | 2 +- ar-AR/README_AR.md | 1 + bs-BS/README-bs_BS.md | 1 + de-DE/README.md | 3 ++- es-ES/README-ES.md | 1 + fr-FR/README_fr-FR.md | 1 + id-ID/README.md | 3 ++- it-IT/README.md | 3 ++- ja-JA/README-ja_JA.md | 1 + ko-KR/README-ko_KR.md | 3 ++- nl-NL/README.md | 1 + pl-PL/README.md | 3 ++- pt-BR/README_pt_BR.md | 1 + ru-RU/README.md | 3 ++- sq-KS/README_sq_KS.md | 43 +++++++++++++++++++++---------------------- th-TH/README.md | 1 + tr-TR/README-tr_TR.md | 1 + uk-UA/README.md | 1 + vi-VI/README-vi.md | 1 + 19 files changed, 45 insertions(+), 29 deletions(-) diff --git a/README.md b/README.md index 1cd5bd33..bf0e1d7e 100644 --- a/README.md +++ b/README.md @@ -17,7 +17,7 @@ Feel free to reach out to me! 😊
--- -
See 19 Available Translations 🇸🇦🇪🇬🇧🇦🇩🇪🇪🇸🇫🇷🇮🇩🇯🇵🇰🇷🇳🇱🇧🇷🇷🇺🇹🇭🇹🇷🇺🇦🇻🇳🇨🇳🇹🇼 +
See 20 Available Translations 🇸🇦🇪🇬🇧🇦🇩🇪🇪🇸🇫🇷🇮🇩🇯🇵🇰🇷🇳🇱🇧🇷🇷🇺🇹🇭🇹🇷🇺🇦🇻🇳🇨🇳🇹🇼🇽🇰

- [🇸🇦 العربية](./ar-AR/README_AR.md) diff --git a/ar-AR/README_AR.md b/ar-AR/README_AR.md index 3e490cdd..88e7f550 100644 --- a/ar-AR/README_AR.md +++ b/ar-AR/README_AR.md @@ -34,6 +34,7 @@ - [🇻🇳 Tiếng Việt](../vi-VI/README-vi.md) - [🇨🇳 简体中文](../zh-CN/README-zh_CN.md) - [🇹🇼 繁體中文](../zh-TW/README_zh-TW.md) +- [🇽🇰 Shqip](../sq-KS/README_sq_KS.md) ____________ diff --git a/bs-BS/README-bs_BS.md b/bs-BS/README-bs_BS.md index 6e57f8c2..3df71853 100644 --- a/bs-BS/README-bs_BS.md +++ b/bs-BS/README-bs_BS.md @@ -32,6 +32,7 @@ kliknite na njih da biste ih proširili. Sretno :heart: - [🇻🇳 Tiếng Việt](../vi-VI/README-vi.md) - [🇨🇳 简体中文](../zh-CN/README-zh_CN.md) - [🇹🇼 繁體中文](../zh-TW/README_zh-TW.md) +- [🇽🇰 Shqip](../sq-KS/README_sq_KS.md) * * * * * diff --git a/de-DE/README.md b/de-DE/README.md index 6111d8eb..dde4a461 100644 --- a/de-DE/README.md +++ b/de-DE/README.md @@ -19,7 +19,7 @@ Kontaktiert mich, wenn ihr möchtet! 😊
--- -

Alle 18 Übersetzungen anzeigen 🇸🇦🇪🇬🇧🇦🇩🇪🇪🇸🇫🇷🇮🇩🇯🇵🇰🇷🇳🇱🇧🇷🇷🇺🇹🇭🇹🇷🇺🇦🇻🇳🇨🇳🇹🇼 +
Alle 20 Übersetzungen anzeigen 🇸🇦🇪🇬🇧🇦🇩🇪🇪🇸🇫🇷🇮🇩🇯🇵🇰🇷🇳🇱🇧🇷🇷🇺🇹🇭🇹🇷🇺🇦🇻🇳🇨🇳🇹🇼🇽🇰

- [🇸🇦 العربية](../ar-AR/README_AR.md) @@ -42,6 +42,7 @@ Kontaktiert mich, wenn ihr möchtet! 😊
- [🇻🇳 Tiếng Việt](../vi-VI/README-vi.md) - [🇨🇳 简体中文](../zh-CN/README-zh_CN.md) - [🇹🇼 繁體中文](../zh-TW/README_zh-TW.md) +- [🇽🇰 Shqip](../sq-KS/README_sq_KS.md)

diff --git a/es-ES/README-ES.md b/es-ES/README-ES.md index aafe6fdc..88b2e285 100644 --- a/es-ES/README-ES.md +++ b/es-ES/README-ES.md @@ -32,6 +32,7 @@ Lista de lenguajes disponibles: - [🇻🇳 Tiếng Việt](../vi-VI/README-vi.md) - [🇨🇳 简体中文](../zh-CN/README-zh_CN.md) - [🇹🇼 繁體中文](../zh-TW/README_zh-TW.md) +- [🇽🇰 Shqip](../sq-KS/README_sq_KS.md) --- diff --git a/fr-FR/README_fr-FR.md b/fr-FR/README_fr-FR.md index 1a15ee00..e8ea9154 100644 --- a/fr-FR/README_fr-FR.md +++ b/fr-FR/README_fr-FR.md @@ -26,6 +26,7 @@ Les réponses se trouvent dans les sections repliées en dessous des questions, - [🇻🇳 Tiếng Việt](../vi-VI/README-vi.md) - [🇨🇳 简体中文](../zh-CN/README-zh_CN.md) - [🇹🇼 繁體中文](../zh-TW/README_zh-TW.md) +- [🇽🇰 Shqip](../sq-KS/README_sq_KS.md) --- diff --git a/id-ID/README.md b/id-ID/README.md index 3e430594..22b329a9 100644 --- a/id-ID/README.md +++ b/id-ID/README.md @@ -13,7 +13,7 @@ Jangan sungkan untuk terhubung dengan saya! 😊
--- -
Lihat 17 Terjemahan yang tersedia 🇪🇸🇮🇹🇩🇪 🇫🇷🇷🇺🇨🇳🇵🇹 +
Lihat 20 Terjemahan yang tersedia 🇪🇸🇮🇹🇩🇪 🇫🇷🇷🇺🇨🇳🇵🇹🇽🇰

- [🇸🇦 العربية](../ar-AR/README_AR.md) @@ -36,6 +36,7 @@ Jangan sungkan untuk terhubung dengan saya! 😊
- [🇻🇳 Tiếng Việt](../vi-VI/README-vi.md) - [🇨🇳 简体中文](../zh-CN/README-zh_CN.md) - [🇹🇼 繁體中文](../zh-TW/README_zh-TW.md) +- [🇽🇰 Shqip](../sq-KS/README_sq_KS.md)

diff --git a/it-IT/README.md b/it-IT/README.md index bb0c13d7..797db159 100644 --- a/it-IT/README.md +++ b/it-IT/README.md @@ -21,7 +21,7 @@ Traduzione a cura di: Lucia Cenetie --- -
Vedi le 18 traduzioni disponibili 🇸🇦🇪🇬🇧🇦🇩🇪🇪🇸🇫🇷🇮🇩🇯🇵🇰🇷🇳🇱🇧🇷🇷🇺🇹🇭🇹🇷🇺🇦🇻🇳🇨🇳🇹🇼 +
Vedi le 20 traduzioni disponibili 🇸🇦🇪🇬🇧🇦🇩🇪🇪🇸🇫🇷🇮🇩🇯🇵🇰🇷🇳🇱🇧🇷🇷🇺🇹🇭🇹🇷🇺🇦🇻🇳🇨🇳🇹🇼🇽🇰

- [🇸🇦 العربية](../ar-AR/README_AR.md) @@ -44,6 +44,7 @@ Traduzione a cura di: Lucia Cenetie - [🇻🇳 Tiếng Việt](../vi-VI/README-vi.md) - [🇨🇳 简体中文](../zh-CN/README-zh_CN.md) - [🇹🇼 繁體中文](../zh-TW/README_zh-TW.md) +- [🇽🇰 Shqip](../sq-KS/README_sq_KS.md)

diff --git a/ja-JA/README-ja_JA.md b/ja-JA/README-ja_JA.md index ebd754c0..18b50630 100644 --- a/ja-JA/README-ja_JA.md +++ b/ja-JA/README-ja_JA.md @@ -28,6 +28,7 @@ - [🇻🇳 Tiếng Việt](../vi-VI/README-vi.md) - [🇨🇳 简体中文](../zh-CN/README-zh_CN.md) - [🇹🇼 繁體中文](../zh-TW/README_zh-TW.md) +- [🇽🇰 Shqip](../sq-KS/README_sq_KS.md) --- ###### 1. 何が出力されるでしょうか? diff --git a/ko-KR/README-ko_KR.md b/ko-KR/README-ko_KR.md index aca2c534..f3ff436e 100644 --- a/ko-KR/README-ko_KR.md +++ b/ko-KR/README-ko_KR.md @@ -18,7 +18,7 @@ --- -
사용 가능한 번역 18개 🇸🇦🇪🇬🇧🇦🇬🇧🇩🇪🇪🇸🇫🇷🇮🇩🇯🇵🇳🇱🇧🇷🇷🇺🇹🇭🇹🇷🇺🇦🇻🇳🇨🇳🇹🇼 +
사용 가능한 번역 20개 🇸🇦🇪🇬🇧🇦🇬🇧🇩🇪🇪🇸🇫🇷🇮🇩🇯🇵🇳🇱🇧🇷🇷🇺🇹🇭🇹🇷🇺🇦🇻🇳🇨🇳🇹🇼🇽🇰

- [🇸🇦 العربية](../ar-AR/README_AR.md) @@ -41,6 +41,7 @@ - [🇻🇳 Tiếng Việt](../vi-VI/README-vi.md) - [🇨🇳 简体中文](../zh-CN/README-zh_CN.md) - [🇹🇼 繁體中文](../zh-TW/README_zh-TW.md) +- [🇽🇰 Shqip](../sq-KS/README_sq_KS.md)

diff --git a/nl-NL/README.md b/nl-NL/README.md index ad13ed36..9e03c08a 100644 --- a/nl-NL/README.md +++ b/nl-NL/README.md @@ -37,6 +37,7 @@ - [🇻🇳 Tiếng Việt](../vi-VI/README-vi.md) - [🇨🇳 简体中文](../zh-CN/README-zh_CN.md) - [🇹🇼 繁體中文](../zh-TW/README_zh-TW.md) +- [🇽🇰 Shqip](../sq-KS/README_sq_KS.md)

diff --git a/pl-PL/README.md b/pl-PL/README.md index 9e4c01e7..5517cde7 100644 --- a/pl-PL/README.md +++ b/pl-PL/README.md @@ -17,7 +17,7 @@ Nie krępuj się ze mną kontaktować! 😊
--- -
Zobacz 19 dostępnych tłumaczeń 🇸🇦🇪🇬🇧🇦🇩🇪🇪🇸🇫🇷🇮🇩🇯🇵🇰🇷🇳🇱🇧🇷🇷🇺🇹🇭🇹🇷🇺🇦🇻🇳🇨🇳🇹🇼 +
Zobacz 20 dostępnych tłumaczeń 🇸🇦🇪🇬🇧🇦🇩🇪🇪🇸🇫🇷🇮🇩🇯🇵🇰🇷🇳🇱🇧🇷🇷🇺🇹🇭🇹🇷🇺🇦🇻🇳🇨🇳🇹🇼🇽🇰

- [🇸🇦 العربية](./ar-AR/README_AR.md) @@ -39,6 +39,7 @@ Nie krępuj się ze mną kontaktować! 😊
- [🇻🇳 Tiếng Việt](./vi-VI/README-vi.md) - [🇨🇳 简体中文](./zh-CN/README-zh_CN.md) - [🇹🇼 繁體中文](./zh-TW/README_zh-TW.md) +- [🇽🇰 Shqip](../sq-KS/README_sq_KS.md)

diff --git a/pt-BR/README_pt_BR.md b/pt-BR/README_pt_BR.md index 11995aaf..4485d523 100644 --- a/pt-BR/README_pt_BR.md +++ b/pt-BR/README_pt_BR.md @@ -26,6 +26,7 @@ As respostas estão em seções recolhidas abaixo das questões, basta clicar ne - [🇻🇳 Tiếng Việt](../vi-VI/README-vi.md) - [🇨🇳 简体中文](../zh-CN/README-zh_CN.md) - [🇹🇼 繁體中文](../zh-TW/README_zh-TW.md) +- [🇽🇰 Shqip](../sq-KS/README_sq_KS.md) --- diff --git a/ru-RU/README.md b/ru-RU/README.md index d4236ed5..276428f6 100644 --- a/ru-RU/README.md +++ b/ru-RU/README.md @@ -17,7 +17,7 @@ --- -
Доступно в 19 переводах 🇸🇦🇪🇬🇧🇦🇩🇪🇪🇸🇫🇷🇮🇩🇯🇵🇰🇷🇳🇱🇧🇷🇷🇺🇹🇭🇹🇷🇺🇦🇻🇳🇨🇳🇹🇼 +
Доступно в 20 переводах 🇸🇦🇪🇬🇧🇦🇩🇪🇪🇸🇫🇷🇮🇩🇯🇵🇰🇷🇳🇱🇧🇷🇷🇺🇹🇭🇹🇷🇺🇦🇻🇳🇨🇳🇹🇼🇽🇰

- [🇸🇦 العربية](../ar-AR/README_AR.md) @@ -40,6 +40,7 @@ - [🇻🇳 Tiếng Việt](../vi-VI/README-vi.md) - [🇨🇳 简体中文](../zh-CN/README-zh_CN.md) - [🇹🇼 繁體中文](../zh-TW/README_zh-TW.md) +- [🇽🇰 Shqip](../sq-KS/README_sq_KS.md)

diff --git a/sq-KS/README_sq_KS.md b/sq-KS/README_sq_KS.md index 5a0c05cc..79e2c41d 100644 --- a/sq-KS/README_sq_KS.md +++ b/sq-KS/README_sq_KS.md @@ -9,8 +9,7 @@ Pyetjet të cilat mund të kenë më shumë se një përgjigje të saktë postoh Nga konceptet bazike tek ato të avancuara: testo se sa mirë e njeh JavaScript-in, freskoni sado pak njohuritë e juaja ose edhe përgatitu për intervisten tuaj të ardhshme! 💪 🚀! Përgjigjet gjenden në **seksionet e mbyllura** përfundi pyetjeve, thjesht kliko mbi to për të hapur seksionin e përgjigjeve. Është vetëm për argëtim, paç fat! ❤️ Mos hezitoni të më kontaktoni! 😊 -Instagram || Twitter || LinkedIn || Blog - +
Instagram || Twitter || LinkedIn || Blog | Ndjehuni të lirë të i përdorni në projektet e juaja |😃 Do të e vlerësoja shumë referencimin tuaj në ketë repositori, unë i krijoj pyetjet dhe poashtu edhe përgjigjet (lol) dhe komuniteti me ndihmon shumë të e përmirësoj dhe të mirëmbajë! 💪🏼 Faleminderit! @@ -20,26 +19,26 @@ Instagram || Twitter || LinkedIn || Blog
See 20 Available Translations 🇸🇦🇪🇬🇧🇦🇩🇪🇪🇸🇫🇷🇮🇩🇯🇵🇰🇷🇳🇱🇧🇷🇷🇺🇹🇭🇹🇷🇺🇦🇻🇳🇨🇳🇹🇼🇽🇰

-- [🇸🇦 العربية](./ar-AR/README_AR.md) -- [🇪🇬 اللغة العامية](./ar-EG/README_ar-EG.md) -- [🇧🇦 Bosanski](./bs-BS/README-bs_BS.md) -- [🇩🇪 Deutsch](./de-DE/README.md) -- [🇪🇸 Español](./es-ES/README-ES.md) -- [🇫🇷 Français](./fr-FR/README_fr-FR.md) -- [🇮🇩 Indonesia](./id-ID/README.md) -- [🇮🇹 Italiano](./it-IT/README.md) -- [🇯🇵 日本語](./ja-JA/README-ja_JA.md) -- [🇰🇷 한국어](./ko-KR/README-ko_KR.md) -- [🇳🇱 Nederlands](./nl-NL/README.md) -- [🇵🇱 Polski](./pl-PL/README.md) -- [🇧🇷 Português Brasil](./pt-BR/README_pt_BR.md) -- [🇷🇺 Русский](./ru-RU/README.md) -- [🇹🇭 ไทย](./th-TH/README-th_TH.md) -- [🇹🇷 Türkçe](./tr-TR/README-tr_TR.md) -- [🇺🇦 Українська мова](./uk-UA/README.md) -- [🇻🇳 Tiếng Việt](./vi-VI/README-vi.md) -- [🇨🇳 简体中文](./zh-CN/README-zh_CN.md) -- [🇹🇼 繁體中文](./zh-TW/README_zh-TW.md) +- [🇸🇦 العربية](../ar-AR/README_AR.md) +- [🇪🇬 اللغة العامية](../ar-EG/README_ar-EG.md) +- [🇧🇦 Bosanski](../bs-BS/README-bs_BS.md) +- [🇩🇪 Deutsch](../de-DE/README.md) +- [🇪🇸 Español](../es-ES/README-ES.md) +- [🇫🇷 Français](../fr-FR/README_fr-FR.md) +- [🇮🇩 Indonesia](../id-ID/README.md) +- [🇮🇹 Italiano](../it-IT/README.md) +- [🇯🇵 日本語](../ja-JA/README-ja_JA.md) +- [🇰🇷 한국어](../ko-KR/README-ko_KR.md) +- [🇳🇱 Nederlands](../nl-NL/README.md) +- [🇵🇱 Polski](../pl-PL/README.md) +- [🇧🇷 Português Brasil](../pt-BR/README_pt_BR.md) +- [🇷🇺 Русский](../ru-RU/README.md) +- [🇹🇭 ไทย](../th-TH/README-th_TH.md) +- [🇹🇷 Türkçe](../tr-TR/README-tr_TR.md) +- [🇺🇦 Українська мова](../uk-UA/README.md) +- [🇻🇳 Tiếng Việt](../vi-VI/README-vi.md) +- [🇨🇳 简体中文](../zh-CN/README-zh_CN.md) +- [🇹🇼 繁體中文](../zh-TW/README_zh-TW.md) - [🇽🇰 Shqip](./sq-KS/README_sq_KS.md)

diff --git a/th-TH/README.md b/th-TH/README.md index 1a16e65a..86d6a513 100644 --- a/th-TH/README.md +++ b/th-TH/README.md @@ -38,6 +38,7 @@ - [🇻🇳 Tiếng Việt](../vi-VI/README-vi.md) - [🇨🇳 简体中文](../zh-CN/README-zh_CN.md) - [🇹🇼 繁體中文](../zh-TW/README_zh-TW.md) +- [🇽🇰 Shqip](../sq-KS/README_sq_KS.md) --- diff --git a/tr-TR/README-tr_TR.md b/tr-TR/README-tr_TR.md index 4ca673e0..5f0aea48 100644 --- a/tr-TR/README-tr_TR.md +++ b/tr-TR/README-tr_TR.md @@ -32,6 +32,7 @@ Mevcut dillerin listesi: - [🇻🇳 Tiếng Việt](../vi-VI/README-vi.md) - [🇨🇳 简体中文](../zh-CN/README-zh_CN.md) - [🇹🇼 繁體中文](../zh-TW/README_zh-TW.md) +- [🇽🇰 Shqip](../sq-KS/README_sq_KS.md) --- diff --git a/uk-UA/README.md b/uk-UA/README.md index efa0329a..e3b7533c 100644 --- a/uk-UA/README.md +++ b/uk-UA/README.md @@ -26,6 +26,7 @@ - [🇻🇳 Tiếng Việt](../vi-VI/README-vi.md) - [🇨🇳 简体中文](../zh-CN/README-zh_CN.md) - [🇹🇼 繁體中文](../zh-TW/README_zh-TW.md) +- [🇽🇰 Shqip](../sq-KS/README_sq_KS.md) --- diff --git a/vi-VI/README-vi.md b/vi-VI/README-vi.md index e663ae96..5e187647 100644 --- a/vi-VI/README-vi.md +++ b/vi-VI/README-vi.md @@ -27,6 +27,7 @@ Danh sách các ngôn ngữ khác: - [🇺🇦 Українська мова](../uk-UA/README.md) - [🇨🇳 简体中文](../zh-CN/README-zh_CN.md) - [🇹🇼 繁體中文](../zh-TW/README_zh-TW.md) +- [🇽🇰 Shqip](../sq-KS/README_sq_KS.md) --- From 7a387cd695ae9f0133be28282e05d3aa66cb08f5 Mon Sep 17 00:00:00 2001 From: EgzonaVllasaliu <44296118+EgzonaVllasaliu@users.noreply.github.com> Date: Tue, 1 Aug 2023 08:44:47 +0000 Subject: [PATCH 162/193] Modify languages order in README's alphabetically --- README.md | 2 +- ar-AR/README_AR.md | 2 +- bs-BS/README-bs_BS.md | 2 +- de-DE/README.md | 2 +- es-ES/README-ES.md | 2 +- fr-FR/README_fr-FR.md | 2 +- id-ID/README.md | 2 +- it-IT/README.md | 2 +- ja-JA/README-ja_JA.md | 3 ++- ko-KR/README-ko_KR.md | 2 +- nl-NL/README.md | 2 +- pl-PL/README.md | 2 +- pt-BR/README_pt_BR.md | 2 +- ru-RU/README.md | 2 +- sq-KS/README_sq_KS.md | 2 +- th-TH/README.md | 2 +- tr-TR/README-tr_TR.md | 2 +- uk-UA/README.md | 2 +- vi-VI/README-vi.md | 2 +- 19 files changed, 20 insertions(+), 19 deletions(-) diff --git a/README.md b/README.md index bf0e1d7e..97cde89e 100644 --- a/README.md +++ b/README.md @@ -34,13 +34,13 @@ Feel free to reach out to me! 😊
- [🇵🇱 Polski](./pl-PL/README.md) - [🇧🇷 Português Brasil](./pt-BR/README_pt_BR.md) - [🇷🇺 Русский](./ru-RU/README.md) +- [🇽🇰 Shqip](./sq-KS/README_sq_KS.md) - [🇹🇭 ไทย](./th-TH/README-th_TH.md) - [🇹🇷 Türkçe](./tr-TR/README-tr_TR.md) - [🇺🇦 Українська мова](./uk-UA/README.md) - [🇻🇳 Tiếng Việt](./vi-VI/README-vi.md) - [🇨🇳 简体中文](./zh-CN/README-zh_CN.md) - [🇹🇼 繁體中文](./zh-TW/README_zh-TW.md) -- [🇽🇰 Shqip](./sq-KS/README_sq_KS.md)

diff --git a/ar-AR/README_AR.md b/ar-AR/README_AR.md index 88e7f550..6d5638e7 100644 --- a/ar-AR/README_AR.md +++ b/ar-AR/README_AR.md @@ -28,13 +28,13 @@ - [🇵🇱 Polski](../pl-PL/README.md) - [🇧🇷 Português Brasil](../pt-BR/README_pt_BR.md) - [🇷🇺 Русский](../ru-RU/README.md) +- [🇽🇰 Shqip](../sq-KS/README_sq_KS.md) - [🇹🇭 ไทย](../th-TH/README-th_TH.md) - [🇹🇷 Türkçe](../tr-TR/README-tr_TR.md) - [🇺🇦 Українська мова](../uk-UA/README.md) - [🇻🇳 Tiếng Việt](../vi-VI/README-vi.md) - [🇨🇳 简体中文](../zh-CN/README-zh_CN.md) - [🇹🇼 繁體中文](../zh-TW/README_zh-TW.md) -- [🇽🇰 Shqip](../sq-KS/README_sq_KS.md) ____________ diff --git a/bs-BS/README-bs_BS.md b/bs-BS/README-bs_BS.md index 3df71853..5c63bb02 100644 --- a/bs-BS/README-bs_BS.md +++ b/bs-BS/README-bs_BS.md @@ -26,13 +26,13 @@ kliknite na njih da biste ih proširili. Sretno :heart: - [🇵🇱 Polski](../pl-PL/README.md) - [🇧🇷 Português Brasil](../pt-BR/README_pt_BR.md) - [🇷🇺 Русский](../ru-RU/README.md) +- [🇽🇰 Shqip](../sq-KS/README_sq_KS.md) - [🇹🇭 ไทย](../th-TH/README-th_TH.md) - [🇹🇷 Türkçe](../tr-TR/README-tr_TR.md) - [🇺🇦 Українська мова](../uk-UA/README.md) - [🇻🇳 Tiếng Việt](../vi-VI/README-vi.md) - [🇨🇳 简体中文](../zh-CN/README-zh_CN.md) - [🇹🇼 繁體中文](../zh-TW/README_zh-TW.md) -- [🇽🇰 Shqip](../sq-KS/README_sq_KS.md) * * * * * diff --git a/de-DE/README.md b/de-DE/README.md index dde4a461..10145050 100644 --- a/de-DE/README.md +++ b/de-DE/README.md @@ -36,13 +36,13 @@ Kontaktiert mich, wenn ihr möchtet! 😊
- [🇵🇱 Polski](../pl-PL/README.md) - [🇧🇷 Português Brasil](../pt-BR/README_pt_BR.md) - [🇷🇺 Русский](../ru-RU/README.md) +- [🇽🇰 Shqip](../sq-KS/README_sq_KS.md) - [🇹🇭 ไทย](../th-TH/README-th_TH.md) - [🇹🇷 Türkçe](../tr-TR/README-tr_TR.md) - [🇺🇦 Українська мова](../uk-UA/README.md) - [🇻🇳 Tiếng Việt](../vi-VI/README-vi.md) - [🇨🇳 简体中文](../zh-CN/README-zh_CN.md) - [🇹🇼 繁體中文](../zh-TW/README_zh-TW.md) -- [🇽🇰 Shqip](../sq-KS/README_sq_KS.md)

diff --git a/es-ES/README-ES.md b/es-ES/README-ES.md index 88b2e285..5c3ddc40 100644 --- a/es-ES/README-ES.md +++ b/es-ES/README-ES.md @@ -26,13 +26,13 @@ Lista de lenguajes disponibles: - [🇵🇱 Polski](../pl-PL/README.md) - [🇧🇷 Português Brasil](../pt-BR/README_pt_BR.md) - [🇷🇺 Русский](../ru-RU/README.md) +- [🇽🇰 Shqip](../sq-KS/README_sq_KS.md) - [🇹🇭 ไทย](../th-TH/README-th_TH.md) - [🇹🇷 Türkçe](../tr-TR/README-tr_TR.md) - [🇺🇦 Українська мова](../uk-UA/README.md) - [🇻🇳 Tiếng Việt](../vi-VI/README-vi.md) - [🇨🇳 简体中文](../zh-CN/README-zh_CN.md) - [🇹🇼 繁體中文](../zh-TW/README_zh-TW.md) -- [🇽🇰 Shqip](../sq-KS/README_sq_KS.md) --- diff --git a/fr-FR/README_fr-FR.md b/fr-FR/README_fr-FR.md index e8ea9154..cce10323 100644 --- a/fr-FR/README_fr-FR.md +++ b/fr-FR/README_fr-FR.md @@ -20,13 +20,13 @@ Les réponses se trouvent dans les sections repliées en dessous des questions, - [🇵🇱 Polski](../pl-PL/README.md) - [🇧🇷 Português Brasil](../pt-BR/README_pt_BR.md) - [🇷🇺 Русский](../ru-RU/README.md) +- [🇽🇰 Shqip](../sq-KS/README_sq_KS.md) - [🇹🇭 ไทย](../th-TH/README-th_TH.md) - [🇹🇷 Türkçe](../tr-TR/README-tr_TR.md) - [🇺🇦 Українська мова](../uk-UA/README.md) - [🇻🇳 Tiếng Việt](../vi-VI/README-vi.md) - [🇨🇳 简体中文](../zh-CN/README-zh_CN.md) - [🇹🇼 繁體中文](../zh-TW/README_zh-TW.md) -- [🇽🇰 Shqip](../sq-KS/README_sq_KS.md) --- diff --git a/id-ID/README.md b/id-ID/README.md index 22b329a9..26a566cc 100644 --- a/id-ID/README.md +++ b/id-ID/README.md @@ -30,13 +30,13 @@ Jangan sungkan untuk terhubung dengan saya! 😊
- [🇵🇱 Polski](../pl-PL/README.md) - [🇧🇷 Português Brasil](../pt-BR/README_pt_BR.md) - [🇷🇺 Русский](../ru-RU/README.md) +- [🇽🇰 Shqip](../sq-KS/README_sq_KS.md) - [🇹🇭 ไทย](../th-TH/README-th_TH.md) - [🇹🇷 Türkçe](../tr-TR/README-tr_TR.md) - [🇺🇦 Українська мова](../uk-UA/README.md) - [🇻🇳 Tiếng Việt](../vi-VI/README-vi.md) - [🇨🇳 简体中文](../zh-CN/README-zh_CN.md) - [🇹🇼 繁體中文](../zh-TW/README_zh-TW.md) -- [🇽🇰 Shqip](../sq-KS/README_sq_KS.md)

diff --git a/it-IT/README.md b/it-IT/README.md index 797db159..71b71ca5 100644 --- a/it-IT/README.md +++ b/it-IT/README.md @@ -38,13 +38,13 @@ Traduzione a cura di: Lucia Cenetie - [🇵🇱 Polski](../pl-PL/README.md) - [🇧🇷 Português Brasil](../pt-BR/README_pt_BR.md) - [🇷🇺 Русский](../ru-RU/README.md) +- [🇽🇰 Shqip](../sq-KS/README_sq_KS.md) - [🇹🇭 ไทย](../th-TH/README-th_TH.md) - [🇹🇷 Türkçe](../tr-TR/README-tr_TR.md) - [🇺🇦 Українська мова](../uk-UA/README.md) - [🇻🇳 Tiếng Việt](../vi-VI/README-vi.md) - [🇨🇳 简体中文](../zh-CN/README-zh_CN.md) - [🇹🇼 繁體中文](../zh-TW/README_zh-TW.md) -- [🇽🇰 Shqip](../sq-KS/README_sq_KS.md)

diff --git a/ja-JA/README-ja_JA.md b/ja-JA/README-ja_JA.md index 18b50630..1cc85d76 100644 --- a/ja-JA/README-ja_JA.md +++ b/ja-JA/README-ja_JA.md @@ -22,13 +22,14 @@ - [🇵🇱 Polski](../pl-PL/README.md) - [🇧🇷 Português Brasil](../pt-BR/README_pt_BR.md) - [🇷🇺 Русский](../ru-RU/README.md) +- [🇽🇰 Shqip](../sq-KS/README_sq_KS.md) - [🇹🇭 ไทย](../th-TH/README-th_TH.md) - [🇹🇷 Türkçe](../tr-TR/README-tr_TR.md) - [🇺🇦 Українська мова](../uk-UA/README.md) - [🇻🇳 Tiếng Việt](../vi-VI/README-vi.md) - [🇨🇳 简体中文](../zh-CN/README-zh_CN.md) - [🇹🇼 繁體中文](../zh-TW/README_zh-TW.md) -- [🇽🇰 Shqip](../sq-KS/README_sq_KS.md) + --- ###### 1. 何が出力されるでしょうか? diff --git a/ko-KR/README-ko_KR.md b/ko-KR/README-ko_KR.md index f3ff436e..13651a7c 100644 --- a/ko-KR/README-ko_KR.md +++ b/ko-KR/README-ko_KR.md @@ -35,13 +35,13 @@ - [🇵🇱 Polski](../pl-PL/README.md) - [🇧🇷 Português Brasil](../pt-BR/README_pt_BR.md) - [🇷🇺 Русский](../ru-RU/README.md) +- [🇽🇰 Shqip](../sq-KS/README_sq_KS.md) - [🇹🇭 ไทย](../th-TH/README-th_TH.md) - [🇹🇷 Türkçe](../tr-TR/README-tr_TR.md) - [🇺🇦 Українська мова](../uk-UA/README.md) - [🇻🇳 Tiếng Việt](../vi-VI/README-vi.md) - [🇨🇳 简体中文](../zh-CN/README-zh_CN.md) - [🇹🇼 繁體中文](../zh-TW/README_zh-TW.md) -- [🇽🇰 Shqip](../sq-KS/README_sq_KS.md)

diff --git a/nl-NL/README.md b/nl-NL/README.md index 9e03c08a..0400e8ed 100644 --- a/nl-NL/README.md +++ b/nl-NL/README.md @@ -31,13 +31,13 @@ - [🇵🇱 Polski](../pl-PL/README.md) - [🇧🇷 Português Brasil](../pt-BR/README_pt_BR.md) - [🇷🇺 Русский](../ru-RU/README.md) +- [🇽🇰 Shqip](../sq-KS/README_sq_KS.md) - [🇹🇭 ไทย](../th-TH/README-th_TH.md) - [🇹🇷 Türkçe](../tr-TR/README-tr_TR.md) - [🇺🇦 Українська мова](../uk-UA/README.md) - [🇻🇳 Tiếng Việt](../vi-VI/README-vi.md) - [🇨🇳 简体中文](../zh-CN/README-zh_CN.md) - [🇹🇼 繁體中文](../zh-TW/README_zh-TW.md) -- [🇽🇰 Shqip](../sq-KS/README_sq_KS.md)

diff --git a/pl-PL/README.md b/pl-PL/README.md index 5517cde7..866f4458 100644 --- a/pl-PL/README.md +++ b/pl-PL/README.md @@ -33,13 +33,13 @@ Nie krępuj się ze mną kontaktować! 😊
- [🇳🇱 Nederlands](./nl-NL/README.md) - [🇧🇷 Português Brasil](./pt-BR/README_pt_BR.md) - [🇷🇺 Русский](./ru-RU/README.md) +- [🇽🇰 Shqip](../sq-KS/README_sq_KS.md) - [🇹🇭 ไทย](./th-TH/README-th_TH.md) - [🇹🇷 Türkçe](./tr-TR/README-tr_TR.md) - [🇺🇦 Українська мова](./uk-UA/README.md) - [🇻🇳 Tiếng Việt](./vi-VI/README-vi.md) - [🇨🇳 简体中文](./zh-CN/README-zh_CN.md) - [🇹🇼 繁體中文](./zh-TW/README_zh-TW.md) -- [🇽🇰 Shqip](../sq-KS/README_sq_KS.md)

diff --git a/pt-BR/README_pt_BR.md b/pt-BR/README_pt_BR.md index 4485d523..e59c6a6f 100644 --- a/pt-BR/README_pt_BR.md +++ b/pt-BR/README_pt_BR.md @@ -20,13 +20,13 @@ As respostas estão em seções recolhidas abaixo das questões, basta clicar ne - [🇳🇱 Nederlands](../nl-NL/README.md) - [🇵🇱 Polski](../pl-PL/README.md) - [🇷🇺 Русский](../ru-RU/README.md) +- [🇽🇰 Shqip](../sq-KS/README_sq_KS.md) - [🇹🇭 ไทย](../th-TH/README-th_TH.md) - [🇹🇷 Türkçe](../tr-TR/README-tr_TR.md) - [🇺🇦 Українська мова](../uk-UA/README.md) - [🇻🇳 Tiếng Việt](../vi-VI/README-vi.md) - [🇨🇳 简体中文](../zh-CN/README-zh_CN.md) - [🇹🇼 繁體中文](../zh-TW/README_zh-TW.md) -- [🇽🇰 Shqip](../sq-KS/README_sq_KS.md) --- diff --git a/ru-RU/README.md b/ru-RU/README.md index 276428f6..17a083ab 100644 --- a/ru-RU/README.md +++ b/ru-RU/README.md @@ -34,13 +34,13 @@ - [🇵🇱 Polski](../pl-PL/README.md) - [🇧🇷 Português Brasil](../pt-BR/README_pt_BR.md) - [🇬🇧 English](../README.md) +- [🇽🇰 Shqip](../sq-KS/README_sq_KS.md) - [🇹🇭 ไทย](../th-TH/README-th_TH.md) - [🇹🇷 Türkçe](../tr-TR/README-tr_TR.md) - [🇺🇦 Українська мова](../uk-UA/README.md) - [🇻🇳 Tiếng Việt](../vi-VI/README-vi.md) - [🇨🇳 简体中文](../zh-CN/README-zh_CN.md) - [🇹🇼 繁體中文](../zh-TW/README_zh-TW.md) -- [🇽🇰 Shqip](../sq-KS/README_sq_KS.md)

diff --git a/sq-KS/README_sq_KS.md b/sq-KS/README_sq_KS.md index 79e2c41d..aa1eb9dc 100644 --- a/sq-KS/README_sq_KS.md +++ b/sq-KS/README_sq_KS.md @@ -33,13 +33,13 @@ Mos hezitoni të më kontaktoni! 😊 - [🇵🇱 Polski](../pl-PL/README.md) - [🇧🇷 Português Brasil](../pt-BR/README_pt_BR.md) - [🇷🇺 Русский](../ru-RU/README.md) +- [🇽🇰 Shqip](./sq-KS/README_sq_KS.md) - [🇹🇭 ไทย](../th-TH/README-th_TH.md) - [🇹🇷 Türkçe](../tr-TR/README-tr_TR.md) - [🇺🇦 Українська мова](../uk-UA/README.md) - [🇻🇳 Tiếng Việt](../vi-VI/README-vi.md) - [🇨🇳 简体中文](../zh-CN/README-zh_CN.md) - [🇹🇼 繁體中文](../zh-TW/README_zh-TW.md) -- [🇽🇰 Shqip](./sq-KS/README_sq_KS.md)

diff --git a/th-TH/README.md b/th-TH/README.md index 86d6a513..22550eb2 100644 --- a/th-TH/README.md +++ b/th-TH/README.md @@ -33,12 +33,12 @@ - [🇵🇱 Polski](../pl-PL/README.md) - [🇧🇷 Português Brasil](../pt-BR/README_pt_BR.md) - [🇷🇺 Русский](../ru-RU/README.md) +- [🇽🇰 Shqip](../sq-KS/README_sq_KS.md) - [🇹🇷 Türkçe](../tr-TR/README-tr_TR.md) - [🇺🇦 Українська мова](../uk-UA/README.md) - [🇻🇳 Tiếng Việt](../vi-VI/README-vi.md) - [🇨🇳 简体中文](../zh-CN/README-zh_CN.md) - [🇹🇼 繁體中文](../zh-TW/README_zh-TW.md) -- [🇽🇰 Shqip](../sq-KS/README_sq_KS.md) --- diff --git a/tr-TR/README-tr_TR.md b/tr-TR/README-tr_TR.md index 5f0aea48..e34ae66b 100644 --- a/tr-TR/README-tr_TR.md +++ b/tr-TR/README-tr_TR.md @@ -27,12 +27,12 @@ Mevcut dillerin listesi: - [🇵🇱 Polski](../pl-PL/README.md) - [🇧🇷 Português Brasil](../pt-BR/README_pt_BR.md) - [🇷🇺 Русский](../ru-RU/README.md) +- [🇽🇰 Shqip](../sq-KS/README_sq_KS.md) - [🇹🇭 ไทย](../th-TH/README-th_TH.md) - [🇺🇦 Українська мова](../uk-UA/README.md) - [🇻🇳 Tiếng Việt](../vi-VI/README-vi.md) - [🇨🇳 简体中文](../zh-CN/README-zh_CN.md) - [🇹🇼 繁體中文](../zh-TW/README_zh-TW.md) -- [🇽🇰 Shqip](../sq-KS/README_sq_KS.md) --- diff --git a/uk-UA/README.md b/uk-UA/README.md index e3b7533c..3b38c921 100644 --- a/uk-UA/README.md +++ b/uk-UA/README.md @@ -21,12 +21,12 @@ - [🇵🇱 Polski](../pl-PL/README.md) - [🇧🇷 Português Brasil](../pt-BR/README_pt_BR.md) - [🇷🇺 Русский](../ru-RU/README.md) +- [🇽🇰 Shqip](../sq-KS/README_sq_KS.md) - [🇹🇭 ไทย](../th-TH/README-th_TH.md) - [🇹🇷 Türkçe](../tr-TR/README-tr_TR.md) - [🇻🇳 Tiếng Việt](../vi-VI/README-vi.md) - [🇨🇳 简体中文](../zh-CN/README-zh_CN.md) - [🇹🇼 繁體中文](../zh-TW/README_zh-TW.md) -- [🇽🇰 Shqip](../sq-KS/README_sq_KS.md) --- diff --git a/vi-VI/README-vi.md b/vi-VI/README-vi.md index 5e187647..8750b2d6 100644 --- a/vi-VI/README-vi.md +++ b/vi-VI/README-vi.md @@ -22,12 +22,12 @@ Danh sách các ngôn ngữ khác: - [🇵🇱 Polski](../pl-PL/README.md) - [🇧🇷 Português Brasil](../pt-BR/README_pt_BR.md) - [🇷🇺 Русский](../ru-RU/README.md) +- [🇽🇰 Shqip](../sq-KS/README_sq_KS.md) - [🇹🇭 ไทย](../th-TH/README-th_TH.md) - [🇹🇷 Türkçe](../tr-TR/README-tr_TR.md) - [🇺🇦 Українська мова](../uk-UA/README.md) - [🇨🇳 简体中文](../zh-CN/README-zh_CN.md) - [🇹🇼 繁體中文](../zh-TW/README_zh-TW.md) -- [🇽🇰 Shqip](../sq-KS/README_sq_KS.md) --- From 051904af27ec92120a65b8dbb58e349c191ea016 Mon Sep 17 00:00:00 2001 From: May Kittens Devour Your Soul Date: Wed, 2 Aug 2023 20:22:42 +0200 Subject: [PATCH 163/193] Update README-bs_BS.md --- bs-BS/README-bs_BS.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/bs-BS/README-bs_BS.md b/bs-BS/README-bs_BS.md index 5c63bb02..3bbd0e0b 100644 --- a/bs-BS/README-bs_BS.md +++ b/bs-BS/README-bs_BS.md @@ -67,10 +67,10 @@ još nismo definirali varijablu na liniji gdje pokušavamo prijaviti varijabla `name`, tako da još uvijek sadrži vrijednost` undefined`. Varijable s ključnom riječi `let` (i` const`) su podignute, ali za razliku od njih -`var`, ne bivaju inicijalizirane . Nisu dostupni prije -linije na kojo ih proglašavamo (inicijaliziramo). To se naziva "temporal dead zone". +`var`, ne bivaju inicijalizirane . Nisu dostupne prije +linije na kojoj ih proglašavamo (inicijaliziramo). To se naziva "temporal dead zone". Kada pokušamo pristupiti varijablama prije nego što budu deklarirane, -JavaScript iz bacuje `ReferenceError`. +JavaScript izbacuje `ReferenceError`.

From c6086e1179fa153f2cb82706a5f198ed3beeadbb Mon Sep 17 00:00:00 2001 From: May Kittens Devour Your Soul Date: Wed, 2 Aug 2023 20:34:49 +0200 Subject: [PATCH 164/193] Update README-bs_BS.md --- bs-BS/README-bs_BS.md | 20 ++++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/bs-BS/README-bs_BS.md b/bs-BS/README-bs_BS.md index 3bbd0e0b..65ee11f7 100644 --- a/bs-BS/README-bs_BS.md +++ b/bs-BS/README-bs_BS.md @@ -253,7 +253,7 @@ console.log(d.greeting); #### Odgovor: A -U JavaScriptu, svi objekti međusobno djeluju * referencom * kada ih postavljaju +U JavaScriptu, svi objekti međusobno djeluju *referencom* kada ih postavljaju jednaki. Prvo, varijabla `c` sadrži vrijednost objekta. Kasnije dodijelimo `d` @@ -290,15 +290,15 @@ console.log(b === c); #### Odgovor: C -`new Number ()` je ugrađeni konstruktor function. Iako izgleda +`new Number ()` je ugrađena konstruktor funkcija. Iako izgleda kao broj, to zapravo nije broj: ima gomilu ekstra dodataka pa je zbog toga objekt. -Kada koristimo `==` operatora, on samo provjerava ima li isti +Kada koristimo `==` operator, on samo provjerava ima li isti *vrijednost*. Obje imaju vrijednost `3`, pa se vraća 'true'. Međutim, kada koristimo `===` operator, obje vrijednosti * i * trebaju biti -isto. To nije: `new Number ()` nije broj, to je ** objekt **. +iste. To nije: `new Number ()` nije broj, to je ** objekt **. Oba vraćaju "false"

@@ -376,7 +376,7 @@ da ste deklarirali varijablu prije nego je postavite na bilo što. * * * * * -###### 10. Što se događa kada to učinimo? +###### 10. Što se događa kada učinimo ovo? ```javascript function bark() { @@ -396,11 +396,11 @@ bark.animal = "dog"; #### Odgovor: A -To je moguće u JavaScriptu, jer su funkcije objekti! +Ovo je moguće u JavaScriptu, jer su funkcije objekti! (Sve osim primitivnih tipova su objekti) function je posebna vrsta objekta. Kod koji sami napišete -nije stvarna function. function je objekt sa svojstvima. +nije stvarna funkcija. function je objekt sa svojstvima. Ova nekretnina je nepovratna.

@@ -435,7 +435,7 @@ console.log(member.getFullName()); #### Odgovor: A Ne možete dodati svojstva konstruktoru kao što možete s uobičajenim -objekti. Ako želite dodati značajku svim objektima odjednom, imate +objektima. Ako želite dodati značajku svim objektima odjednom, imate umjesto toga koristiti prototip. Dakle, u ovom slučaju, ```{.js} @@ -444,12 +444,12 @@ Person.prototype.getFullName = function () { }; ``` -bi učinio `member.getFullName ()`. Zašto je to korisno? Reći će mo +bi učinio `member.getFullName ()`. Zašto je to korisno? Reći ćemo da smo tu metodu dodali samom konstruktoru. Možda ne svaki Primjer "Person" trebao je ovu metodu. To bi trošilo puno memorije scopa (prostora), jer bi oni još uvijek imali tu svojinu, koja uzima memoriju scopa za svaku instancu. Umjesto toga, ako ga samo dodamo prototipu, mi -će mo je imati na jednom mjestu u memoriji, ali svi imaju pristup! +ćemo je imati na jednom mjestu u memoriji, ali svi imaju pristup!

From 133e907093ba5bf447f25aab44d831f6694825ce Mon Sep 17 00:00:00 2001 From: Mohammed Nasif <99568326+Mohammed-Nasif@users.noreply.github.com> Date: Fri, 11 Aug 2023 11:46:12 -0700 Subject: [PATCH 165/193] Update README.md ###### 23. What's the output? The Answer description was not clear as the reason is that the variable declared with let couldn't be redeclared. --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 97cde89e..7627f92e 100644 --- a/README.md +++ b/README.md @@ -739,7 +739,7 @@ console.log(num); With the `var` keyword, you can declare multiple variables with the same name. The variable will then hold the latest value. -You cannot do this with `let` or `const` since they're block-scoped. +You cannot do this with `let` or `const` since they couldn't be redeclared.

From d8f096396becd18256123479e42c7a0290b52771 Mon Sep 17 00:00:00 2001 From: alexb017 Date: Mon, 21 Aug 2023 00:06:22 +0300 Subject: [PATCH 166/193] Add romanian translation --- README.md | 624 ++++++++++++++-------------- ar-AR/README_AR.md | 362 ++++++++++------- bs-BS/README-bs_BS.md | 249 ++++++------ de-DE/README.md | 925 +++++++++++++++++++++--------------------- es-ES/README-ES.md | 495 +++++++++++----------- fr-FR/README_fr-FR.md | 44 +- id-ID/README.md | 546 ++++++++++++------------- it-IT/README.md | 654 ++++++++++++++--------------- ja-JA/README-ja_JA.md | 375 +++++++++-------- ko-KR/README-ko_KR.md | 514 +++++++++++------------ nl-NL/README.md | 619 ++++++++++++++-------------- pl-PL/README.md | 126 +++--- pt-BR/README_pt_BR.md | 116 +++--- ro-RO/README.ro.md | 49 +++ ru-RU/README.md | 825 ++++++++++++++++++------------------- sq-KS/README_sq_KS.md | 653 ++++++++++++++--------------- th-TH/README.md | 385 +++++++++--------- tr-TR/README-tr_TR.md | 316 ++++++++------- uk-UA/README.md | 35 +- vi-VI/README-vi.md | 829 ++++++++++++++++++------------------- 20 files changed, 4441 insertions(+), 4300 deletions(-) create mode 100644 ro-RO/README.ro.md diff --git a/README.md b/README.md index 97cde89e..031b0f72 100644 --- a/README.md +++ b/README.md @@ -10,10 +10,11 @@ From basic to advanced: test how well you know JavaScript, refresh your knowledg Feel free to reach out to me! 😊
Instagram || Twitter || LinkedIn || Blog + -| Feel free to use them in a project! 😃 I would _really_ appreciate a reference to this repo, I create the questions and explanations (yes I'm sad lol) and the community helps me so much to maintain and improve it! 💪🏼 Thank you and have fun! | -|---| +| Feel free to use them in a project! 😃 I would _really_ appreciate a reference to this repo, I create the questions and explanations (yes I'm sad lol) and the community helps me so much to maintain and improve it! 💪🏼 Thank you and have fun! | +| ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | --- @@ -33,6 +34,7 @@ Feel free to reach out to me! 😊
- [🇳🇱 Nederlands](./nl-NL/README.md) - [🇵🇱 Polski](./pl-PL/README.md) - [🇧🇷 Português Brasil](./pt-BR/README_pt_BR.md) +- [🇷o Română](./ro-RO/README.ro.md) - [🇷🇺 Русский](./ru-RU/README.md) - [🇽🇰 Shqip](./sq-KS/README_sq_KS.md) - [🇹🇭 ไทย](./th-TH/README-th_TH.md) @@ -53,7 +55,7 @@ Feel free to reach out to me! 😊
function sayHi() { console.log(name); console.log(age); - var name = 'Lydia'; + var name = "Lydia"; let age = 21; } @@ -149,7 +151,7 @@ There is no value `radius` on that object, which returns `NaN`. ```javascript +true; -!'Lydia'; +!"Lydia"; ``` - A: `1` and `false` @@ -174,11 +176,11 @@ The string `'Lydia'` is a truthy value. What we're actually asking, is "is this ```javascript const bird = { - size: 'small', + size: "small", }; const mouse = { - name: 'Mickey', + name: "Mickey", small: true, }; ``` @@ -209,11 +211,11 @@ However, with dot notation, this doesn't happen. `mouse` does not have a key cal ###### 6. What's the output? ```javascript -let c = { greeting: 'Hey!' }; +let c = { greeting: "Hey!" }; let d; d = c; -c.greeting = 'Hello'; +c.greeting = "Hello"; console.log(d.greeting); ``` @@ -283,13 +285,13 @@ class Chameleon { return this.newColor; } - constructor({ newColor = 'green' } = {}) { + constructor({ newColor = "green" } = {}) { this.newColor = newColor; } } -const freddie = new Chameleon({ newColor: 'purple' }); -console.log(freddie.colorChange('orange')); +const freddie = new Chameleon({ newColor: "purple" }); +console.log(freddie.colorChange("orange")); ``` - A: `orange` @@ -344,10 +346,10 @@ In order to avoid this, we can use `"use strict"`. This makes sure that you have ```javascript function bark() { - console.log('Woof!'); + console.log("Woof!"); } -bark.animal = 'dog'; +bark.animal = "dog"; ``` - A: Nothing, this is totally fine! @@ -377,8 +379,8 @@ function Person(firstName, lastName) { this.lastName = lastName; } -const member = new Person('Lydia', 'Hallie'); -Person.getFullName = function() { +const member = new Person("Lydia", "Hallie"); +Person.getFullName = function () { return `${this.firstName} ${this.lastName}`; }; @@ -395,12 +397,12 @@ console.log(member.getFullName()); #### Answer: A -In JavaScript, functions are objects, and therefore, the method `getFullName` gets added to the constructor function object itself. For that reason, we can call `Person.getFullName()`, but `member.getFullName` throws a `TypeError`. +In JavaScript, functions are objects, and therefore, the method `getFullName` gets added to the constructor function object itself. For that reason, we can call `Person.getFullName()`, but `member.getFullName` throws a `TypeError`. If you want a method to be available to all object instances, you have to add it to the prototype property: ```js -Person.prototype.getFullName = function() { +Person.prototype.getFullName = function () { return `${this.firstName} ${this.lastName}`; }; ``` @@ -418,8 +420,8 @@ function Person(firstName, lastName) { this.lastName = lastName; } -const lydia = new Person('Lydia', 'Hallie'); -const sarah = Person('Sarah', 'Smith'); +const lydia = new Person("Lydia", "Hallie"); +const sarah = Person("Sarah", "Smith"); console.log(lydia); console.log(sarah); @@ -489,7 +491,7 @@ function sum(a, b) { return a + b; } -sum(1, '2'); +sum(1, "2"); ``` - A: `NaN` @@ -556,7 +558,7 @@ function getPersonInfo(one, two, three) { console.log(three); } -const person = 'Lydia'; +const person = "Lydia"; const age = 21; getPersonInfo`${person} is ${age} years old`; @@ -583,9 +585,9 @@ If you use tagged template literals, the value of the first argument is always a ```javascript function checkAge(data) { if (data === { age: 18 }) { - console.log('You are an adult!'); + console.log("You are an adult!"); } else if (data == { age: 18 }) { - console.log('You are still an adult.'); + console.log("You are still an adult."); } else { console.log(`Hmm.. You don't have an age I guess`); } @@ -645,7 +647,7 @@ The rest parameter (`...args`) lets us "collect" all remaining arguments into an ```javascript function getAge() { - 'use strict'; + "use strict"; age = 21; console.log(age); } @@ -673,7 +675,7 @@ With `"use strict"`, you can make sure that you don't accidentally declare globa ###### 21. What's the value of `sum`? ```javascript -const sum = eval('10*10+5'); +const sum = eval("10*10+5"); ``` - A: `105` @@ -696,7 +698,7 @@ const sum = eval('10*10+5'); ###### 22. How long is cool_secret accessible? ```javascript -sessionStorage.setItem('cool_secret', 123); +sessionStorage.setItem("cool_secret", 123); ``` - A: Forever, the data doesn't get lost. @@ -749,12 +751,12 @@ You cannot do this with `let` or `const` since they're block-scoped. ###### 24. What's the output? ```javascript -const obj = { 1: 'a', 2: 'b', 3: 'c' }; +const obj = { 1: "a", 2: "b", 3: "c" }; const set = new Set([1, 2, 3, 4, 5]); -obj.hasOwnProperty('1'); +obj.hasOwnProperty("1"); obj.hasOwnProperty(1); -set.has('1'); +set.has("1"); set.has(1); ``` @@ -780,7 +782,7 @@ It doesn't work that way for a set. There is no `'1'` in our set: `set.has('1')` ###### 25. What's the output? ```javascript -const obj = { a: 'one', b: 'two', a: 'three' }; +const obj = { a: "one", b: "two", a: "three" }; console.log(obj); ``` @@ -849,12 +851,12 @@ The `continue` statement skips an iteration if a certain condition returns `true ```javascript String.prototype.giveLydiaPizza = () => { - return 'Just give Lydia pizza already!'; + return "Just give Lydia pizza already!"; }; -const name = 'Lydia'; +const name = "Lydia"; -console.log(name.giveLydiaPizza()) +console.log(name.giveLydiaPizza()); ``` - A: `"Just give Lydia pizza already!"` @@ -878,8 +880,8 @@ console.log(name.giveLydiaPizza()) ```javascript const a = {}; -const b = { key: 'b' }; -const c = { key: 'c' }; +const b = { key: "b" }; +const c = { key: "c" }; a[b] = 123; a[c] = 456; @@ -911,9 +913,9 @@ Then, we log `a[b]`, which is actually `a["[object Object]"]`. We just set that ###### 30. What's the output? ```javascript -const foo = () => console.log('First'); -const bar = () => setTimeout(() => console.log('Second')); -const baz = () => console.log('Third'); +const foo = () => console.log("First"); +const bar = () => setTimeout(() => console.log("Second")); +const baz = () => console.log("Third"); bar(); foo(); @@ -966,9 +968,7 @@ This is where an event loop starts to work. An **event loop** looks at the stack ```html
- +
``` @@ -994,9 +994,7 @@ The deepest nested element that caused the event is the target of the event. You ```html
-

- Click here! -

+

Click here!

``` @@ -1020,7 +1018,7 @@ If we click `p`, we see two logs: `p` and `div`. During event propagation, there ###### 33. What's the output? ```javascript -const person = { name: 'Lydia' }; +const person = { name: "Lydia" }; function sayHi(age) { return `${this.name} is ${age}`; @@ -1070,7 +1068,6 @@ console.log(typeof sayHi()); #### Answer: B The `sayHi` function returns the returned value of the immediately invoked function expression (IIFE). This function returned `0`, which is type `"number"`. - FYI: `typeof` can return the following list of values: `undefined`, `boolean`, `number`, `bigint`, `string`, `symbol`, `function` and `object`. Note that `typeof null` returns `"object"`.

@@ -1083,8 +1080,8 @@ FYI: `typeof` can return the following list of values: `undefined`, `boolean`, ` ```javascript 0; new Number(0); -(''); -(' '); +(""); +(" "); new Boolean(false); undefined; ``` @@ -1233,11 +1230,14 @@ What differentiates a primitive from an object is that primitives do not have an ###### 40. What's the output? ```javascript -[[0, 1], [2, 3]].reduce( +[ + [0, 1], + [2, 3], +].reduce( (acc, cur) => { return acc.concat(cur); }, - [1, 2], + [1, 2] ); ``` @@ -1264,7 +1264,7 @@ Then, `[1, 2, 0, 1]` is `acc` and `[2, 3]` is `cur`. We concatenate them, and ge ```javascript !!null; -!!''; +!!""; !!1; ``` @@ -1292,7 +1292,7 @@ Then, `[1, 2, 0, 1]` is `acc` and `[2, 3]` is `cur`. We concatenate them, and ge ###### 42. What does the `setInterval` method return in the browser? ```javascript -setInterval(() => console.log('Hi'), 1000); +setInterval(() => console.log("Hi"), 1000); ``` - A: a unique id @@ -1315,7 +1315,7 @@ It returns a unique id. This id can be used to clear that interval with the `cle ###### 43. What does this return? ```javascript -[...'Lydia']; +[..."Lydia"]; ``` - A: `["L", "y", "d", "i", "a"]` @@ -1374,14 +1374,14 @@ Then, we invoke the function again with the `next()` method. It starts to contin ```javascript const firstPromise = new Promise((res, rej) => { - setTimeout(res, 500, 'one'); + setTimeout(res, 500, "one"); }); const secondPromise = new Promise((res, rej) => { - setTimeout(res, 100, 'two'); + setTimeout(res, 100, "two"); }); -Promise.race([firstPromise, secondPromise]).then(res => console.log(res)); +Promise.race([firstPromise, secondPromise]).then((res) => console.log(res)); ``` - A: `"one"` @@ -1404,7 +1404,7 @@ When we pass multiple promises to the `Promise.race` method, it resolves/rejects ###### 46. What's the output? ```javascript -let person = { name: 'Lydia' }; +let person = { name: "Lydia" }; const members = [person]; person = null; @@ -1444,7 +1444,7 @@ We are only modifying the value of the `person` variable, and not the first elem ```javascript const person = { - name: 'Lydia', + name: "Lydia", age: 21, }; @@ -1473,7 +1473,7 @@ With a `for-in` loop, we can iterate through object keys, in this case `name` an ###### 48. What's the output? ```javascript -console.log(3 + 4 + '5'); +console.log(3 + 4 + "5"); ``` - A: `"345"` @@ -1500,7 +1500,7 @@ Operator associativity is the order in which the compiler evaluates the expressi ###### 49. What's the value of `num`? ```javascript -const num = parseInt('7*6', 10); +const num = parseInt("7*6", 10); ``` - A: `42` @@ -1525,8 +1525,8 @@ Only the first numbers in the string is returned. Based on the _radix_ (the seco ###### 50. What's the output? ```javascript -[1, 2, 3].map(num => { - if (typeof num === 'number') return; +[1, 2, 3].map((num) => { + if (typeof num === "number") return; return num * 2; }); ``` @@ -1554,12 +1554,12 @@ However, we don’t return a value. When we don’t return a value from the func ```javascript function getInfo(member, year) { - member.name = 'Lydia'; - year = '1998'; + member.name = "Lydia"; + year = "1998"; } -const person = { name: 'Sarah' }; -const birthYear = '1997'; +const person = { name: "Sarah" }; +const birthYear = "1997"; getInfo(person, birthYear); @@ -1591,15 +1591,15 @@ The value of `person` is an object. The argument `member` has a (copied) referen ```javascript function greeting() { - throw 'Hello world!'; + throw "Hello world!"; } function sayHi() { try { const data = greeting(); - console.log('It worked!', data); + console.log("It worked!", data); } catch (e) { - console.log('Oh no an error:', e); + console.log("Oh no an error:", e); } } @@ -1629,8 +1629,8 @@ With the `catch` statement, we can specify what to do if an exception is thrown ```javascript function Car() { - this.make = 'Lamborghini'; - return { make: 'Maserati' }; + this.make = "Lamborghini"; + return { make: "Maserati" }; } const myCar = new Car(); @@ -1704,11 +1704,11 @@ class Dog { } } -Dog.prototype.bark = function() { +Dog.prototype.bark = function () { console.log(`Woof I am ${this.name}`); }; -const pet = new Dog('Mara'); +const pet = new Dog("Mara"); pet.bark(); @@ -1773,7 +1773,7 @@ export default counter; ```javascript // index.js -import myCounter from './counter'; +import myCounter from "./counter"; myCounter += 1; @@ -1802,7 +1802,7 @@ When we try to increment the value of `myCounter`, it throws an error: `myCounte ###### 58. What's the output? ```javascript -const name = 'Lydia'; +const name = "Lydia"; age = 21; console.log(delete name); @@ -1873,7 +1873,7 @@ This means that the value of `y` is equal to the first value in the array, which ###### 60. What's the output? ```javascript -const user = { name: 'Lydia', age: 21 }; +const user = { name: "Lydia", age: 21 }; const admin = { admin: true, ...user }; console.log(admin); @@ -1899,9 +1899,9 @@ It's possible to combine objects using the spread operator `...`. It lets you cr ###### 61. What's the output? ```javascript -const person = { name: 'Lydia' }; +const person = { name: "Lydia" }; -Object.defineProperty(person, 'age', { value: 21 }); +Object.defineProperty(person, "age", { value: 21 }); console.log(person); console.log(Object.keys(person)); @@ -1930,12 +1930,12 @@ Properties added using the `defineProperty` method are immutable by default. You ```javascript const settings = { - username: 'lydiahallie', + username: "lydiahallie", level: 19, health: 90, }; -const data = JSON.stringify(settings, ['level', 'health']); +const data = JSON.stringify(settings, ["level", "health"]); console.log(data); ``` @@ -1966,7 +1966,7 @@ If the replacer is a _function_, this function gets called on every property in let num = 10; const increaseNumber = () => num++; -const increasePassedNumber = number => number++; +const increasePassedNumber = (number) => number++; const num1 = increaseNumber(); const num2 = increasePassedNumber(num1); @@ -2123,12 +2123,12 @@ The `Labrador` class receives two arguments, `name` since it extends `Dog`, and ```javascript // index.js -console.log('running index.js'); -import { sum } from './sum.js'; +console.log("running index.js"); +import { sum } from "./sum.js"; console.log(sum(1, 2)); // sum.js -console.log('running sum.js'); +console.log("running sum.js"); export const sum = (a, b) => a + b; ``` @@ -2156,7 +2156,7 @@ This is a difference between `require()` in CommonJS and `import`! With `require ```javascript console.log(Number(2) === Number(2)); console.log(Boolean(false) === Boolean(false)); -console.log(Symbol('foo') === Symbol('foo')); +console.log(Symbol("foo") === Symbol("foo")); ``` - A: `true`, `true`, `false` @@ -2179,7 +2179,7 @@ Every Symbol is entirely unique. The purpose of the argument passed to the Symbo ###### 69. What's the output? ```javascript -const name = 'Lydia Hallie'; +const name = "Lydia Hallie"; console.log(name.padStart(13)); console.log(name.padStart(2)); ``` @@ -2206,7 +2206,7 @@ If the argument passed to the `padStart` method is smaller than the length of th ###### 70. What's the output? ```javascript -console.log('🥑' + '💻'); +console.log("🥑" + "💻"); ``` - A: `"🥑💻"` @@ -2230,11 +2230,11 @@ With the `+` operator, you can concatenate strings. In this case, we are concate ```javascript function* startGame() { - const answer = yield 'Do you love JavaScript?'; - if (answer !== 'Yes') { + const answer = yield "Do you love JavaScript?"; + if (answer !== "Yes") { return "Oh wow... Guess we're done here"; } - return 'JavaScript loves you back ❤️'; + return "JavaScript loves you back ❤️"; } const game = startGame(); @@ -2302,7 +2302,7 @@ In this case, the string is `Hello\nworld`, which gets logged. ```javascript async function getData() { - return await Promise.resolve('I made it!'); + return await Promise.resolve("I made it!"); } const data = getData(); @@ -2339,7 +2339,7 @@ function addToList(item, list) { return list.push(item); } -const result = addToList('apple', ['banana']); +const result = addToList("apple", ["banana"]); console.log(result); ``` @@ -2399,7 +2399,7 @@ Since `shape` is frozen, and since the value of `x` is not an object, we cannot ###### 76. What's the output? ```javascript -const { firstName: myName } = { firstName: 'Lydia' }; +const { firstName: myName } = { firstName: "Lydia" }; console.log(firstName); ``` @@ -2417,7 +2417,7 @@ console.log(firstName); By using [destructuring assignment](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment) syntax we can unpack values from arrays, or properties from objects, into distinct variables: ```javascript -const { firstName } = { firstName: 'Lydia' }; +const { firstName } = { firstName: "Lydia" }; // ES5 version: // var firstName = { firstName: 'Lydia' }.firstName; @@ -2427,7 +2427,7 @@ console.log(firstName); // "Lydia" Also, a property can be unpacked from an object and assigned to a variable with a different name than the object property: ```javascript -const { firstName: myName } = { firstName: 'Lydia' }; +const { firstName: myName } = { firstName: "Lydia" }; // ES5 version: // var myName = { firstName: 'Lydia' }.firstName; @@ -2440,12 +2440,11 @@ Therefore, `firstName` does not exist as a variable, thus attempting to access i **Note:** Be aware of the `global scope` properties: ```javascript -const { name: myName } = { name: 'Lydia' }; +const { name: myName } = { name: "Lydia" }; console.log(myName); // "lydia" console.log(name); // "" ----- Browser e.g. Chrome console.log(name); // ReferenceError: name is not defined ----- NodeJS - ``` Whenever Javascript is unable to find a variable within the _current scope_, it climbs up the [Scope chain](https://github.com/getify/You-Dont-Know-JS/blob/2nd-ed/scope-closures/ch3.md) and searches for it and if it reaches the top-level scope, aka **Global scope**, and still doesn't find it, it will throw a `ReferenceError`. @@ -2489,7 +2488,7 @@ The `sum` function always returns the same result. If we pass `1` and `2`, it wi ```javascript const add = () => { const cache = {}; - return num => { + return (num) => { if (num in cache) { return `From cache! ${cache[num]}`; } else { @@ -2534,7 +2533,7 @@ The third time, we pass `5 * 2` to the function which gets evaluated to `10`. Th ###### 79. What is the output? ```javascript -const myLifeSummedUp = ['☕', '💻', '🍷', '🍫']; +const myLifeSummedUp = ["☕", "💻", "🍷", "🍫"]; for (let item in myLifeSummedUp) { console.log(item); @@ -2630,13 +2629,13 @@ In this case, if we didn't pass a value or if we passed `undefined`, `name` woul ###### 82. What is the output? ```javascript -var status = '😎'; +var status = "😎"; setTimeout(() => { - const status = '😍'; + const status = "😍"; const data = { - status: '🥑', + status: "🥑", getStatus() { return this.status; }, @@ -2670,12 +2669,12 @@ With the `call` method, we can change the object to which the `this` keyword ref ```javascript const person = { - name: 'Lydia', + name: "Lydia", age: 21, }; let city = person.city; -city = 'Amsterdam'; +city = "Amsterdam"; console.log(person); ``` @@ -2739,9 +2738,9 @@ Variables with the `const` and `let` keyword are _block-scoped_. A block is anyt ###### 85. What kind of information would get logged? ```javascript -fetch('https://www.website.com/api/user/1') - .then(res => res.json()) - .then(res => console.log(res)); +fetch("https://www.website.com/api/user/1") + .then((res) => res.json()) + .then((res) => console.log(res)); ``` - A: The result of the `fetch` method. @@ -2795,7 +2794,7 @@ By setting `hasName` equal to `name`, you set `hasName` equal to whatever value ###### 87. What's the output? ```javascript -console.log('I want pizza'[0]); +console.log("I want pizza"[0]); ``` - A: `"""` @@ -2850,11 +2849,11 @@ If you're trying to set a default parameter's value equal to a parameter which i ```javascript // module.js -export default () => 'Hello world'; -export const name = 'Lydia'; +export default () => "Hello world"; +export const name = "Lydia"; // index.js -import * as data from './module'; +import * as data from "./module"; console.log(data); ``` @@ -2887,7 +2886,7 @@ class Person { } } -const member = new Person('John'); +const member = new Person("John"); console.log(typeof member); ``` @@ -2947,7 +2946,7 @@ Then, we try to use the `.push` method on `newList`. Since `newList` is the nume ```javascript function giveLydiaPizza() { - return 'Here is pizza!'; + return "Here is pizza!"; } const giveLydiaChocolate = () => @@ -2978,7 +2977,7 @@ Regular functions, such as the `giveLydiaPizza` function, have a `prototype` pro ```javascript const person = { - name: 'Lydia', + name: "Lydia", age: 21, }; @@ -3038,7 +3037,7 @@ function getItems(fruitList, favoriteFruit, ...args) { return [...fruitList, ...args, favoriteFruit]; } -getItems(['banana', 'apple'], 'pear', 'orange'); +getItems(["banana", "apple"], "pear", "orange"); ``` The above example works. This returns the array `[ 'banana', 'apple', 'orange', 'pear' ]` @@ -3052,9 +3051,9 @@ The above example works. This returns the array `[ 'banana', 'apple', 'orange', ```javascript function nums(a, b) { - if (a > b) console.log('a is bigger'); - else console.log('b is bigger'); - return + if (a > b) console.log("a is bigger"); + else console.log("b is bigger"); + return; a + b; } @@ -3093,13 +3092,13 @@ This means that `a + b` is never reached, since a function stops running after t ```javascript class Person { constructor() { - this.name = 'Lydia'; + this.name = "Lydia"; } } Person = class AnotherPerson { constructor() { - this.name = 'Sarah'; + this.name = "Sarah"; } }; @@ -3128,7 +3127,7 @@ We can set classes equal to other classes/function constructors. In this case, w ```javascript const info = { - [Symbol('a')]: 'b', + [Symbol("a")]: "b", }; console.log(info); @@ -3183,7 +3182,7 @@ The `getList` function receives an array as its argument. Between the parenthese With the rest parameter `...y`, we put all "remaining" arguments in an array. The remaining arguments are `2`, `3` and `4` in this case. The value of `y` is an array, containing all the rest parameters. The value of `x` is equal to `1` in this case, so when we log `[x, y]`, `[1, [2, 3, 4]]` gets logged. -The `getUser` function receives an object. With arrow functions, we don't _have_ to write curly brackets if we just return one value. However, if you want to instantly return an _object_ from an arrow function, you have to write it between parentheses, otherwise everything between the two braces will be interpreted as a block statement. In this case the code between the braces is not a valid JavaScript code, so a `SyntaxError` gets thrown. +The `getUser` function receives an object. With arrow functions, we don't _have_ to write curly brackets if we just return one value. However, if you want to instantly return an _object_ from an arrow function, you have to write it between parentheses, otherwise everything between the two braces will be interpreted as a block statement. In this case the code between the braces is not a valid JavaScript code, so a `SyntaxError` gets thrown. The following function would have returned an object: @@ -3197,7 +3196,7 @@ The following function would have returned an object: ###### 99. What's the output? ```javascript -const name = 'Lydia'; +const name = "Lydia"; console.log(name()); ``` @@ -3229,8 +3228,8 @@ ReferenceErrors get thrown when JavaScript isn't able to find a reference to a v ```javascript // 🎉✨ This is my 100th question! ✨🎉 -const output = `${[] && 'Im'}possible! -You should${'' && `n't`} see a therapist after so much JavaScript lol`; +const output = `${[] && "Im"}possible! +You should${"" && `n't`} see a therapist after so much JavaScript lol`; ``` - A: `possible! You should see a therapist after so much JavaScript lol` @@ -3256,7 +3255,7 @@ You should${'' && `n't`} see a therapist after so much JavaScript lol`; ```javascript const one = false || {} || null; -const two = null || false || ''; +const two = null || false || ""; const three = [] || 0 || true; console.log(one, two, three); @@ -3288,16 +3287,16 @@ With the `||` operator, we can return the first truthy operand. If all values ar ###### 102. What's the value of output? ```javascript -const myPromise = () => Promise.resolve('I have resolved!'); +const myPromise = () => Promise.resolve("I have resolved!"); function firstFunction() { - myPromise().then(res => console.log(res)); - console.log('second'); + myPromise().then((res) => console.log(res)); + console.log("second"); } async function secondFunction() { console.log(await myPromise()); - console.log('second'); + console.log("second"); } firstFunction(); @@ -3335,8 +3334,8 @@ This means that it waited for the `myPromise` to resolve with the value `I have const set = new Set(); set.add(1); -set.add('Lydia'); -set.add({ name: 'Lydia' }); +set.add("Lydia"); +set.add({ name: "Lydia" }); for (let item of set) { console.log(item + 2); @@ -3396,13 +3395,13 @@ In this case, we just passed the numerical value `5`. It returns a resolved prom ```javascript function compareMembers(person1, person2 = person) { if (person1 !== person2) { - console.log('Not the same!'); + console.log("Not the same!"); } else { - console.log('They are the same!'); + console.log("They are the same!"); } } -const person = { name: 'Lydia' }; +const person = { name: "Lydia" }; compareMembers(person); ``` @@ -3441,7 +3440,7 @@ const colorConfig = { yellow: false, }; -const colors = ['pink', 'red', 'blue']; +const colors = ["pink", "red", "blue"]; console.log(colorConfig.colors[1]); ``` @@ -3470,7 +3469,7 @@ JavaScript interprets (or unboxes) statements. When we use bracket notation, it ###### 107. What's its value? ```javascript -console.log('❤️' === '❤️'); +console.log("❤️" === "❤️"); ``` - A: `true` @@ -3491,14 +3490,14 @@ Under the hood, emojis are unicodes. The unicodes for the heart emoji is `"U+276 ###### 108. Which of these methods modifies the original array? ```javascript -const emojis = ['✨', '🥑', '😍']; +const emojis = ["✨", "🥑", "😍"]; -emojis.map(x => x + '✨'); -emojis.filter(x => x !== '🥑'); -emojis.find(x => x !== '🥑'); -emojis.reduce((acc, cur) => acc + '✨'); -emojis.slice(1, 2, '✨'); -emojis.splice(1, 2, '✨'); +emojis.map((x) => x + "✨"); +emojis.filter((x) => x !== "🥑"); +emojis.find((x) => x !== "🥑"); +emojis.reduce((acc, cur) => acc + "✨"); +emojis.slice(1, 2, "✨"); +emojis.splice(1, 2, "✨"); ``` - A: `All of them` @@ -3523,10 +3522,10 @@ With `splice` method, we modify the original array by deleting, replacing or add ###### 109. What's the output? ```javascript -const food = ['🍕', '🍫', '🥑', '🍔']; +const food = ["🍕", "🍫", "🥑", "🍔"]; const info = { favoriteFood: food[0] }; -info.favoriteFood = '🍝'; +info.favoriteFood = "🍝"; console.log(food); ``` @@ -3580,7 +3579,7 @@ const jsonArray = JSON.stringify([1, 2, 3]); // '[1, 2, 3]' JSON.parse(jsonArray); // [1, 2, 3] // Stringifying an object into valid JSON, then parsing the JSON string to a JavaScript value: -const jsonArray = JSON.stringify({ name: 'Lydia' }); // '{"name":"Lydia"}' +const jsonArray = JSON.stringify({ name: "Lydia" }); // '{"name":"Lydia"}' JSON.parse(jsonArray); // { name: 'Lydia' } ``` @@ -3592,11 +3591,11 @@ JSON.parse(jsonArray); // { name: 'Lydia' } ###### 111. What's the output? ```javascript -let name = 'Lydia'; +let name = "Lydia"; function getName() { console.log(name); - let name = 'Sarah'; + let name = "Sarah"; } getName(); @@ -3619,7 +3618,7 @@ Variables with the `let` keyword (and `const`) are hoisted, but unlike `var`, do If we wouldn't have declared the `name` variable within the `getName` function, the javascript engine would've looked down the _scope chain_. The outer scope has a variable called `name` with the value of `Lydia`. In that case, it would've logged `Lydia`. ```javascript -let name = 'Lydia'; +let name = "Lydia"; function getName() { console.log(name); @@ -3637,11 +3636,11 @@ getName(); // Lydia ```javascript function* generatorOne() { - yield ['a', 'b', 'c']; + yield ["a", "b", "c"]; } function* generatorTwo() { - yield* ['a', 'b', 'c']; + yield* ["a", "b", "c"]; } const one = generatorOne(); @@ -3687,7 +3686,7 @@ console.log(two.next().value); // undefined ###### 113. What's the output? ```javascript -console.log(`${(x => x)('I love')} to program`); +console.log(`${((x) => x)("I love")} to program`); ``` - A: `I love to program` @@ -3712,7 +3711,7 @@ Expressions within template literals are evaluated first. This means that the st ```javascript let config = { alert: setInterval(() => { - console.log('Alert!'); + console.log("Alert!"); }, 1000), }; @@ -3729,9 +3728,9 @@ config = null; #### Answer: C -Normally when we set objects equal to `null`, those objects get _garbage collected_ as there is no reference anymore to that object. However, since the callback function within `setInterval` is an arrow function (thus bound to the `config` object), the callback function still holds a reference to the `config` object. -As long as there is a reference, the object won't get garbage collected. -Since this is an interval, setting `config` to `null` or `delete`-ing `config.alert` won't garbage-collect the interval, so the interval will still be called. +Normally when we set objects equal to `null`, those objects get _garbage collected_ as there is no reference anymore to that object. However, since the callback function within `setInterval` is an arrow function (thus bound to the `config` object), the callback function still holds a reference to the `config` object. +As long as there is a reference, the object won't get garbage collected. +Since this is an interval, setting `config` to `null` or `delete`-ing `config.alert` won't garbage-collect the interval, so the interval will still be called. It should be cleared with `clearInterval(config.alert)` to remove it from memory. Since it was not cleared, the `setInterval` callback function will still get invoked every 1000ms (1s). @@ -3744,16 +3743,16 @@ Since it was not cleared, the `setInterval` callback function will still get inv ```javascript const myMap = new Map(); -const myFunc = () => 'greeting'; +const myFunc = () => "greeting"; -myMap.set(myFunc, 'Hello world!'); +myMap.set(myFunc, "Hello world!"); //1 -myMap.get('greeting'); +myMap.get("greeting"); //2 myMap.get(myFunc); //3 -myMap.get(() => 'greeting'); +myMap.get(() => "greeting"); ``` - A: 1 @@ -3780,14 +3779,14 @@ When adding a key/value pair using the `set` method, the key will be the value o ```javascript const person = { - name: 'Lydia', + name: "Lydia", age: 21, }; const changeAge = (x = { ...person }) => (x.age += 1); const changeAgeAndName = (x = { ...person }) => { x.age += 1; - x.name = 'Sarah'; + x.name = "Sarah"; }; changeAge(person); @@ -3846,7 +3845,7 @@ With the spread operator `...`, we can _spread_ iterables to individual elements ```javascript let num = 1; -const list = ['🥳', '🤠', '🥰', '🤪']; +const list = ["🥳", "🤠", "🥰", "🤪"]; console.log(list[(num += 1)]); ``` @@ -3872,11 +3871,11 @@ With the `+=` operand, we're incrementing the value of `num` by `1`. `num` had t ```javascript const person = { - firstName: 'Lydia', - lastName: 'Hallie', + firstName: "Lydia", + lastName: "Hallie", pet: { - name: 'Mara', - breed: 'Dutch Tulip Hound', + name: "Mara", + breed: "Dutch Tulip Hound", }, getFullName() { return `${this.firstName} ${this.lastName}`; @@ -3914,10 +3913,10 @@ With the optional chaining operator `?.`, we no longer have to explicitly check ###### 120. What's the output? ```javascript -const groceries = ['banana', 'apple', 'peanuts']; +const groceries = ["banana", "apple", "peanuts"]; -if (groceries.indexOf('banana')) { - console.log('We have to buy bananas!'); +if (groceries.indexOf("banana")) { + console.log("We have to buy bananas!"); } else { console.log(`We don't have to buy bananas!`); } @@ -3973,10 +3972,10 @@ The `language` method is a `setter`. Setters don't hold an actual value, their p ###### 122. What's the output? ```javascript -const name = 'Lydia Hallie'; +const name = "Lydia Hallie"; -console.log(!typeof name === 'object'); -console.log(!typeof name === 'string'); +console.log(!typeof name === "object"); +console.log(!typeof name === "string"); ``` - A: `false` `true` @@ -4001,7 +4000,7 @@ console.log(!typeof name === 'string'); ###### 123. What's the output? ```javascript -const add = x => y => z => { +const add = (x) => (y) => (z) => { console.log(x, y, z); return x + y + z; }; @@ -4091,20 +4090,20 @@ myFunc(1, 2, 3); ```javascript function getFine(speed, amount) { - const formattedSpeed = new Intl.NumberFormat('en-US', { - style: 'unit', - unit: 'mile-per-hour' + const formattedSpeed = new Intl.NumberFormat("en-US", { + style: "unit", + unit: "mile-per-hour", }).format(speed); - const formattedAmount = new Intl.NumberFormat('en-US', { - style: 'currency', - currency: 'USD' + const formattedAmount = new Intl.NumberFormat("en-US", { + style: "currency", + currency: "USD", }).format(amount); return `The driver drove ${formattedSpeed} and has to pay ${formattedAmount}`; } -console.log(getFine(130, 300)) +console.log(getFine(130, 300)); ``` - A: The driver drove 130 and has to pay 300 @@ -4127,8 +4126,8 @@ With the `Intl.NumberFormat` method, we can format numeric values to any locale. ###### 127. What's the output? ```javascript -const spookyItems = ['👻', '🎃', '🕸']; -({ item: spookyItems[3] } = { item: '💀' }); +const spookyItems = ["👻", "🎃", "🕸"]; +({ item: spookyItems[3] } = { item: "💀" }); console.log(spookyItems); ``` @@ -4153,7 +4152,7 @@ By destructuring objects, we can unpack values from the right-hand object, and a ###### 128. What's the output? ```javascript -const name = 'Lydia Hallie'; +const name = "Lydia Hallie"; const age = 21; console.log(Number.isNaN(name)); @@ -4189,7 +4188,7 @@ const randomValue = 21; function getInfo() { console.log(typeof randomValue); - const randomValue = 'Lydia Hallie'; + const randomValue = "Lydia Hallie"; } getInfo(); @@ -4215,7 +4214,7 @@ Variables declared with the `const` keyword are not referenceable before their i ###### 130. What's the output? ```javascript -const myPromise = Promise.resolve('Woah some cool data'); +const myPromise = Promise.resolve("Woah some cool data"); (async () => { try { @@ -4223,7 +4222,7 @@ const myPromise = Promise.resolve('Woah some cool data'); } catch { throw new Error(`Oops didn't work`); } finally { - console.log('Oh finally!'); + console.log("Oh finally!"); } })(); ``` @@ -4248,7 +4247,7 @@ In the `try` block, we're logging the awaited value of the `myPromise` variable: ###### 131. What's the output? ```javascript -const emojis = ['🥑', ['✨', '✨', ['🍕', '🍕']]]; +const emojis = ["🥑", ["✨", "✨", ["🍕", "🍕"]]]; console.log(emojis.flat(1)); ``` @@ -4321,19 +4320,19 @@ We invoke `counterTwo.increment()`, which sets `count` to `3`. Then, we log the ###### 133. What's the output? ```javascript -const myPromise = Promise.resolve(Promise.resolve('Promise')); +const myPromise = Promise.resolve(Promise.resolve("Promise")); function funcOne() { - setTimeout(() => console.log('Timeout 1!'), 0); - myPromise.then(res => res).then(res => console.log(`${res} 1!`)); - console.log('Last line 1!'); + setTimeout(() => console.log("Timeout 1!"), 0); + myPromise.then((res) => res).then((res) => console.log(`${res} 1!`)); + console.log("Last line 1!"); } async function funcTwo() { const res = await myPromise; - console.log(`${res} 2!`) - setTimeout(() => console.log('Timeout 2!'), 0); - console.log('Last line 2!'); + console.log(`${res} 2!`); + setTimeout(() => console.log("Timeout 2!"), 0); + console.log("Last line 2!"); } funcOne(); @@ -4354,7 +4353,7 @@ First, we invoke `funcOne`. On the first line of `funcOne`, we call the _asynchr Then we call the `myPromise` promise, which is an _asynchronous_ operation. -Both the promise and the timeout are asynchronous operations, the function keeps on running while it's busy completing the promise and handling the `setTimeout` callback. This means that `Last line 1!` gets logged first, since this is not an asynchonous operation. +Both the promise and the timeout are asynchronous operations, the function keeps on running while it's busy completing the promise and handling the `setTimeout` callback. This means that `Last line 1!` gets logged first, since this is not an asynchonous operation. Since the callstack is not empty yet, the `setTimeout` function and promise in `funcOne` cannot get added to the callstack yet. @@ -4378,7 +4377,7 @@ export default function sum(x) { } // index.js -import * as sum from './sum'; +import * as sum from "./sum"; ``` - A: `sum(4)` @@ -4395,12 +4394,12 @@ With the asterisk `*`, we import all exported values from that file, both defaul ```javascript // info.js -export const name = 'Lydia'; +export const name = "Lydia"; export const age = 21; -export default 'I love JavaScript'; +export default "I love JavaScript"; // index.js -import * as info from './info'; +import * as info from "./info"; console.log(info); ``` @@ -4431,13 +4430,13 @@ We can invoke this function, by calling `sum.default` ```javascript const handler = { - set: () => console.log('Added a new property!'), - get: () => console.log('Accessed a property!'), + set: () => console.log("Added a new property!"), + get: () => console.log("Accessed a property!"), }; const person = new Proxy({}, handler); -person.name = 'Lydia'; +person.name = "Lydia"; person.name; ``` @@ -4467,7 +4466,7 @@ Then, we access a property value on the proxy object, the `get` property on the ###### 136. Which of the following will modify the `person` object? ```javascript -const person = { name: 'Lydia Hallie' }; +const person = { name: "Lydia Hallie" }; Object.seal(person); ``` @@ -4495,9 +4494,9 @@ However, you can still modify the value of existing properties. ```javascript const person = { - name: 'Lydia Hallie', + name: "Lydia Hallie", address: { - street: '100 Main St', + street: "100 Main St", }, }; @@ -4526,7 +4525,7 @@ However, it only _shallowly_ freezes the object, meaning that only _direct_ prop ###### 138. What's the output? ```javascript -const add = x => x + x; +const add = (x) => x + x; function myFunc(num = 2, value = add(num)) { console.log(num, value); @@ -4559,21 +4558,21 @@ Then, we invoked `myFunc(3)` and passed the value `3` as the value for the argum ```javascript class Counter { - #number = 10 + #number = 10; increment() { - this.#number++ + this.#number++; } getNum() { - return this.#number + return this.#number; } } -const counter = new Counter() -counter.increment() +const counter = new Counter(); +counter.increment(); -console.log(counter.#number) +console.log(counter.#number); ``` - A: `10` @@ -4597,8 +4596,8 @@ In ES2020, we can add private variables in classes by using the `#`. We cannot a ```javascript const teams = [ - { name: 'Team 1', members: ['Paul', 'Lisa'] }, - { name: 'Team 2', members: ['Laura', 'Tim'] }, + { name: "Team 1", members: ["Paul", "Lisa"] }, + { name: "Team 2", members: ["Laura", "Tim"] }, ]; function* getMembers(members) { @@ -4641,8 +4640,8 @@ If we would've written `yield`, `return yield`, or `return`, the entire generato ```javascript const person = { - name: 'Lydia Hallie', - hobbies: ['coding'], + name: "Lydia Hallie", + hobbies: ["coding"], }; function addHobby(hobby, hobbies = person.hobbies) { @@ -4650,9 +4649,9 @@ function addHobby(hobby, hobbies = person.hobbies) { return hobbies; } -addHobby('running', []); -addHobby('dancing'); -addHobby('baking', person.hobbies); +addHobby("running", []); +addHobby("dancing"); +addHobby("baking", person.hobbies); console.log(person.hobbies); ``` @@ -4721,11 +4720,11 @@ We create the variable `pet` which is an instance of the `Flamingo` class. When ###### 143. Which of the options result(s) in an error? ```javascript -const emojis = ['🎄', '🎅🏼', '🎁', '⭐']; +const emojis = ["🎄", "🎅🏼", "🎁", "⭐"]; -/* 1 */ emojis.push('🦌'); +/* 1 */ emojis.push("🦌"); /* 2 */ emojis.splice(0, 2); -/* 3 */ emojis = [...emojis, '🥂']; +/* 3 */ emojis = [...emojis, "🥂"]; /* 4 */ emojis.length = 0; ``` @@ -4780,11 +4779,11 @@ Objects aren't iterable by default. An iterable is an iterable if the iterator p let count = 0; const nums = [0, 1, 2, 3]; -nums.forEach(num => { - if (num) count += 1 -}) +nums.forEach((num) => { + if (num) count += 1; +}); -console.log(count) +console.log(count); ``` - A: 1 @@ -4808,12 +4807,12 @@ The `if` condition within the `forEach` loop checks whether the value of `num` i ```javascript function getFruit(fruits) { - console.log(fruits?.[1]?.[1]) + console.log(fruits?.[1]?.[1]); } -getFruit([['🍊', '🍌'], ['🍍']]) -getFruit() -getFruit([['🍍'], ['🍊', '🍌']]) +getFruit([["🍊", "🍌"], ["🍍"]]); +getFruit(); +getFruit([["🍍"], ["🍊", "🍌"]]); ``` - A: `null`, `undefined`, 🍌 @@ -4826,11 +4825,11 @@ getFruit([['🍍'], ['🍊', '🍌']]) #### Answer: D -The `?` allows us to optionally access deeper nested properties within objects. We're trying to log the item on index `1` within the subarray that's on index `1` of the `fruits` array. If the subarray on index `1` in the `fruits` array doesn't exist, it'll simply return `undefined`. If the subarray on index `1` in the `fruits` array exists, but this subarray doesn't have an item on its `1` index, it'll also return `undefined`. +The `?` allows us to optionally access deeper nested properties within objects. We're trying to log the item on index `1` within the subarray that's on index `1` of the `fruits` array. If the subarray on index `1` in the `fruits` array doesn't exist, it'll simply return `undefined`. If the subarray on index `1` in the `fruits` array exists, but this subarray doesn't have an item on its `1` index, it'll also return `undefined`. First, we're trying to log the second item in the `['🍍']` subarray of `[['🍊', '🍌'], ['🍍']]`. This subarray only contains one item, which means there is no item on index `1`, and returns `undefined`. -Then, we're invoking the `getFruits` function without passing a value as an argument, which means that `fruits` has a value of `undefined` by default. Since we're conditionally chaining the item on index `1` of`fruits`, it returns `undefined` since this item on index `1` does not exist. +Then, we're invoking the `getFruits` function without passing a value as an argument, which means that `fruits` has a value of `undefined` by default. Since we're conditionally chaining the item on index `1` of`fruits`, it returns `undefined` since this item on index `1` does not exist. Lastly, we're trying to log the second item in the `['🍊', '🍌']` subarray of `['🍍'], ['🍊', '🍌']`. The item on index `1` within this subarray is `🍌`, which gets logged. @@ -4843,19 +4842,19 @@ Lastly, we're trying to log the second item in the `['🍊', '🍌']` subarray o ```javascript class Calc { - constructor() { - this.count = 0 - } + constructor() { + this.count = 0; + } - increase() { - this.count ++ - } + increase() { + this.count++; + } } -const calc = new Calc() -new Calc().increase() +const calc = new Calc(); +new Calc().increase(); -console.log(calc.count) +console.log(calc.count); ``` - A: `0` @@ -4879,25 +4878,25 @@ We set the variable `calc` equal to a new instance of the `Calc` class. Then, we ```javascript const user = { - email: "e@mail.com", - password: "12345" -} + email: "e@mail.com", + password: "12345", +}; const updateUser = ({ email, password }) => { - if (email) { - Object.assign(user, { email }) - } + if (email) { + Object.assign(user, { email }); + } - if (password) { - user.password = password - } + if (password) { + user.password = password; + } - return user -} + return user; +}; -const updatedUser = updateUser({ email: "new@email.com" }) +const updatedUser = updateUser({ email: "new@email.com" }); -console.log(updatedUser === user) +console.log(updatedUser === user); ``` - A: `false` @@ -4920,13 +4919,13 @@ The `updateUser` function updates the values of the `email` and `password` prope ###### 149. What's the output? ```javascript -const fruit = ['🍌', '🍊', '🍎'] +const fruit = ["🍌", "🍊", "🍎"]; -fruit.slice(0, 1) -fruit.splice(0, 1) -fruit.unshift('🍇') +fruit.slice(0, 1); +fruit.splice(0, 1); +fruit.unshift("🍇"); -console.log(fruit) +console.log(fruit); ``` - A: `['🍌', '🍊', '🍎']` @@ -4941,7 +4940,7 @@ console.log(fruit) First, we invoke the `slice` method on the fruit array. The slice method does not modify the original array, but returns the value that it sliced off the array: the banana emoji. Then, we invoke the `splice` method on the fruit array. The splice method does modify the original array, which means that the fruit array now consists of `['🍊', '🍎']`. -At last, we invoke the `unshift` method on the `fruit` array, which modifies the original array by adding the provided value, ‘🍇’ in this case, as the first element in the array. The fruit array now consists of `['🍇', '🍊', '🍎']`. +At last, we invoke the `unshift` method on the `fruit` array, which modifies the original array by adding the provided value, ‘🍇’ in this case, as the first element in the array. The fruit array now consists of `['🍇', '🍊', '🍎']`.

@@ -4952,13 +4951,13 @@ At last, we invoke the `unshift` method on the `fruit` array, which modifies the ```javascript const animals = {}; -let dog = { emoji: '🐶' } -let cat = { emoji: '🐈' } +let dog = { emoji: "🐶" }; +let cat = { emoji: "🐈" }; -animals[dog] = { ...dog, name: "Mara" } -animals[cat] = { ...cat, name: "Sara" } +animals[dog] = { ...dog, name: "Mara" }; +animals[cat] = { ...cat, name: "Sara" }; -console.log(animals[dog]) +console.log(animals[dog]); ``` - A: `{ emoji: "🐶", name: "Mara" }` @@ -4971,11 +4970,11 @@ console.log(animals[dog]) #### Answer: B -Object keys are converted to strings. +Object keys are converted to strings. -Since the value of `dog` is an object, `animals[dog]` actually means that we’re creating a new property called `"object Object"` equal to the new object. `animals["object Object"]` is now equal to `{ emoji: "🐶", name: "Mara"}`. +Since the value of `dog` is an object, `animals[dog]` actually means that we’re creating a new property called `"object Object"` equal to the new object. `animals["object Object"]` is now equal to `{ emoji: "🐶", name: "Mara"}`. -`cat` is also an object, which means that `animals[cat]` actually means that we’re overwriting the value of `animals["object Object"]` with the new cat properties. +`cat` is also an object, which means that `animals[cat]` actually means that we’re overwriting the value of `animals["object Object"]` with the new cat properties. Logging `animals[dog]`, or actually `animals["object Object"]` since converting the `dog` object to a string results `"object Object"`, returns the `{ emoji: "🐈", name: "Sara" }`. @@ -4988,14 +4987,14 @@ Logging `animals[dog]`, or actually `animals["object Object"]` since converting ```javascript const user = { - email: "my@email.com", - updateEmail: email => { - this.email = email - } -} + email: "my@email.com", + updateEmail: (email) => { + this.email = email; + }, +}; -user.updateEmail("new@email.com") -console.log(user.email) +user.updateEmail("new@email.com"); +console.log(user.email); ``` - A: `my@email.com` @@ -5008,7 +5007,7 @@ console.log(user.email) #### Answer: A -The `updateEmail` function is an arrow function, and is not bound to the `user` object. This means that the `this` keyword is not referring to the `user` object, but refers to the global scope in this case. The value of `email` within the `user` object does not get updated. When logging the value of `user.email`, the original value of `my@email.com` gets returned. +The `updateEmail` function is an arrow function, and is not bound to the `user` object. This means that the `this` keyword is not referring to the `user` object, but refers to the global scope in this case. The value of `email` within the `user` object does not get updated. When logging the value of `user.email`, the original value of `my@email.com` gets returned.

@@ -5018,20 +5017,20 @@ The `updateEmail` function is an arrow function, and is not bound to the `user` ###### 152. What's the output? ```javascript -const promise1 = Promise.resolve('First') -const promise2 = Promise.resolve('Second') -const promise3 = Promise.reject('Third') -const promise4 = Promise.resolve('Fourth') +const promise1 = Promise.resolve("First"); +const promise2 = Promise.resolve("Second"); +const promise3 = Promise.reject("Third"); +const promise4 = Promise.resolve("Fourth"); const runPromises = async () => { - const res1 = await Promise.all([promise1, promise2]) - const res2 = await Promise.all([promise3, promise4]) - return [res1, res2] -} + const res1 = await Promise.all([promise1, promise2]); + const res2 = await Promise.all([promise3, promise4]); + return [res1, res2]; +}; runPromises() - .then(res => console.log(res)) - .catch(err => console.log(err)) + .then((res) => console.log(res)) + .catch((err) => console.log(err)); ``` - A: `[['First', 'Second'], ['Fourth']]` @@ -5044,23 +5043,26 @@ runPromises() #### Answer: D -The `Promise.all` method runs the passed promises in parallel. If one promise fails, the `Promise.all` method _rejects_ with the value of the rejected promise. In this case, `promise3` rejected with the value `"Third"`. We’re catching the rejected value in the chained `catch` method on the `runPromises` invocation to catch any errors within the `runPromises` function. Only `"Third"` gets logged, since `promise3` rejected with this value. +The `Promise.all` method runs the passed promises in parallel. If one promise fails, the `Promise.all` method _rejects_ with the value of the rejected promise. In this case, `promise3` rejected with the value `"Third"`. We’re catching the rejected value in the chained `catch` method on the `runPromises` invocation to catch any errors within the `runPromises` function. Only `"Third"` gets logged, since `promise3` rejected with this value.

--- -###### 153. What should the value of `method` be to log `{ name: "Lydia", age: 22 }`? +###### 153. What should the value of `method` be to log `{ name: "Lydia", age: 22 }`? ```javascript -const keys = ["name", "age"] -const values = ["Lydia", 22] +const keys = ["name", "age"]; +const values = ["Lydia", 22]; -const method = /* ?? */ -Object[method](keys.map((_, i) => { - return [keys[i], values[i]] -})) // { name: "Lydia", age: 22 } +const method = + /* ?? */ + Object[method]( + keys.map((_, i) => { + return [keys[i], values[i]]; + }) + ); // { name: "Lydia", age: 22 } ``` - A: `entries` @@ -5073,7 +5075,7 @@ Object[method](keys.map((_, i) => { #### Answer: C -The `fromEntries` method turns a 2d array into an object. The first element in each subarray will be the key, and the second element in each subarray will be the value. In this case, we’re mapping over the `keys` array, which returns an array which first element is the item on the key array on the current index, and the second element is the item of the values array on the current index. +The `fromEntries` method turns a 2d array into an object. The first element in each subarray will be the key, and the second element in each subarray will be the value. In this case, we’re mapping over the `keys` array, which returns an array which first element is the item on the key array on the current index, and the second element is the item of the values array on the current index. This creates an array of subarrays containing the correct keys and values, which results in `{ name: "Lydia", age: 22 }` @@ -5085,18 +5087,18 @@ This creates an array of subarrays containing the correct keys and values, which ###### 154. What's the output? ```javascript -const createMember = ({ email, address = {}}) => { - const validEmail = /.+\@.+\..+/.test(email) - if (!validEmail) throw new Error("Valid email pls") +const createMember = ({ email, address = {} }) => { + const validEmail = /.+\@.+\..+/.test(email); + if (!validEmail) throw new Error("Valid email pls"); - return { - email, - address: address ? address : null - } -} + return { + email, + address: address ? address : null, + }; +}; -const member = createMember({ email: "my@email.com" }) -console.log(member) +const member = createMember({ email: "my@email.com" }); +console.log(member); ``` - A: `{ email: "my@email.com", address: null }` @@ -5119,13 +5121,13 @@ The default value of `address` is an empty object `{}`. When we set the variable ###### 155. What's the output? ```javascript -let randomValue = { name: "Lydia" } -randomValue = 23 +let randomValue = { name: "Lydia" }; +randomValue = 23; if (!typeof randomValue === "string") { - console.log("It's not a string!") + console.log("It's not a string!"); } else { - console.log("Yay it's a string!") + console.log("Yay it's a string!"); } ``` diff --git a/ar-AR/README_AR.md b/ar-AR/README_AR.md index 6d5638e7..9c1210e2 100644 --- a/ar-AR/README_AR.md +++ b/ar-AR/README_AR.md @@ -1,16 +1,14 @@ - -
# قائــمة أسئلة جافا سكريبت (مستوى متقدم) + أقوم بنشر عدة أسئلة جافاسكريبت بصورة يومية على حسابي في [انستغرام](https://www.instagram.com/theavocoder/). تتدرج الأسئلة إبتداءا من المستوى الأساسي أو البسيط الى المستوى المتقدم لإختبار مدى معرفتك بلغة الجافا سكريبت, قم بمراجعة و إنعاش معرفتك باللغة قليلا, أو قم بالتجهيز لمقابلة عمل لوظيفة مبرمج عن طريق هذه الأسئلة! أقوم بتحديث هذا المستودع أسبوعيا بإضافة المزيد من الأسئلة. :muscle: :rocket: - -الأجوبة توجد في الجزء المطوي بالأسفل أدناه تحت كل سؤال على حدة, فقط قم بالضغط على كلمة الإجابة لكي تحصل على الإجابة, حظا موفقا :heart: +الأجوبة توجد في الجزء المطوي بالأسفل أدناه تحت كل سؤال على حدة, فقط قم بالضغط على كلمة الإجابة لكي تحصل على الإجابة, حظا موفقا :heart: اللغات المتوفرة: @@ -27,6 +25,7 @@ - [🇳🇱 Nederlands](../nl-NL/README.md) - [🇵🇱 Polski](../pl-PL/README.md) - [🇧🇷 Português Brasil](../pt-BR/README_pt_BR.md) +- [🇷o Română](../ro-RO/README.ro.md) - [🇷🇺 Русский](../ru-RU/README.md) - [🇽🇰 Shqip](../sq-KS/README_sq_KS.md) - [🇹🇭 ไทย](../th-TH/README-th_TH.md) @@ -37,8 +36,7 @@ - [🇹🇼 繁體中文](../zh-TW/README_zh-TW.md)
-____________ - +--- 1. ماهو الناتج ؟ @@ -64,10 +62,10 @@ sayHi();
الإجابة هي الخيار الرابع : D -في داخل الدالة, قمنا أولا بتعريف المتغير `name` مع الكلمة المفتاحية `var`. و هذا يعني ان المتغير قد حصلت له عملية hoisting والتي تعني انه قد تم حجز مساحة لهذا المتغير في هذه اللحظة مع قيمة مبدئية و التي هي `undefined` إلى ان نقوم فعليا بتعريف قيمة له لاحقا. +في داخل الدالة, قمنا أولا بتعريف المتغير `name` مع الكلمة المفتاحية `var`. و هذا يعني ان المتغير قد حصلت له عملية hoisting والتي تعني انه قد تم حجز مساحة لهذا المتغير في هذه اللحظة مع قيمة مبدئية و التي هي `undefined` إلى ان نقوم فعليا بتعريف قيمة له لاحقا. لم نقم بتعريف المتغير `name` بعد عندما قمنا بطباعته في السطر الاول من الدالة, لهذا لايزال يحمل القيمة `undefined`. -
-المتغيرات التي تم تعريفها بجانب الكلمات المفتاحية `let` و `const` يتم عمل عملية hoisting لها أيضا, ولكن على عكس المتغيرات التي يتم تعريفها بجانب الكلمة المفتاحية `var`, لا يتم تعريفها او الوصول اليها مالم نقم بإضافة قيمة لها فعليا. و يسمى هذا بال"temporal dead zone".عندما نحاول الوصول الى المتغيرات من النوع `let`قبل ان يتم تعريفها, نتحصل على الخطأ التالي `ReferenceError`. +
+المتغيرات التي تم تعريفها بجانب الكلمات المفتاحية `let` و `const` يتم عمل عملية hoisting لها أيضا, ولكن على عكس المتغيرات التي يتم تعريفها بجانب الكلمة المفتاحية `var`, لا يتم تعريفها او الوصول اليها مالم نقم بإضافة قيمة لها فعليا. و يسمى هذا بال"temporal dead zone".عندما نحاول الوصول الى المتغيرات من النوع `let`قبل ان يتم تعريفها, نتحصل على الخطأ التالي `ReferenceError`.

@@ -97,8 +95,8 @@ for (let i = 0; i < 3; i++) {
الإجابة هي الخيار الثالث: C -بسبب ترتيب تسلسل الأحداث في الجافا سكريبت, دالة `setTimeout` والتي هي دالة من نوع callbackقد تم استدعائها بعد ان تم تنفيذ ال loop. بماأن المتغير `i` في الloop الاولى قد تم تعريفه عن طريق الكلمة المفتاحية `var` فإن هذه القيمة هي global. أثناء تنفيذ هذه ال loop قد تم إضافة 1 الى المتغير `var` في كل دورة باستخدام العملية `++`. بنهاية الدورة و عندما تم استدعاء الدالة `setTimeout` كانت قيمة المتغير `i` قد أصبحت تساوي `3` في المثال الأول. -في الloop الثانية ,تم تعريف المتغير `i` باستخدام الكلمة المفتاحية `let` المتغيرات التي يتم تعريفها باستخدام الكلمات المفتاحية `let` و `const` هي متغيرات تنتمي فقط للBlock الذي تم تعريفها بداخله, والذي هو بين القوسين, أثناءتنفيذ الloop, سنقوم بالتحصل على قيمة جديدة للمتغير `i` في نهاية كل دورة , وأي قيمة تكون منتمية للScope بداخل الloop. +بسبب ترتيب تسلسل الأحداث في الجافا سكريبت, دالة `setTimeout` والتي هي دالة من نوع callbackقد تم استدعائها بعد ان تم تنفيذ ال loop. بماأن المتغير `i` في الloop الاولى قد تم تعريفه عن طريق الكلمة المفتاحية `var` فإن هذه القيمة هي global. أثناء تنفيذ هذه ال loop قد تم إضافة 1 الى المتغير `var` في كل دورة باستخدام العملية `++`. بنهاية الدورة و عندما تم استدعاء الدالة `setTimeout` كانت قيمة المتغير `i` قد أصبحت تساوي `3` في المثال الأول. +في الloop الثانية ,تم تعريف المتغير `i` باستخدام الكلمة المفتاحية `let` المتغيرات التي يتم تعريفها باستخدام الكلمات المفتاحية `let` و `const` هي متغيرات تنتمي فقط للBlock الذي تم تعريفها بداخله, والذي هو بين القوسين, أثناءتنفيذ الloop, سنقوم بالتحصل على قيمة جديدة للمتغير `i` في نهاية كل دورة , وأي قيمة تكون منتمية للScope بداخل الloop.

@@ -114,7 +112,7 @@ const shape = { diameter() { return this.radius * 2; }, - perimeter: () => 2 * Math.PI * this.radius + perimeter: () => 2 * Math.PI * this.radius, }; shape.diameter(); @@ -136,14 +134,13 @@ shape.perimeter(); لا توجد قيمة `radius` في ذلك ال object لهذا يقوم بإرجاع القيمة `undefined`. -

--- -4. ماهو الناتج؟ +4. ماهو الناتج؟ ```javascript +true; @@ -160,23 +157,24 @@ shape.perimeter(); الجواب هو الخيار الأول : A عملية الزيادة الأحادية هنا وجدت لكي تقوم بتحويل المعامل الى رقم, `true` هي `1` , و `false` هي `0`. - المتغير من نوع string `'Lydia'` هو قيمة صدقية أو حقيقية, بمعنى أنها تساوي `true` . السؤال الذي نقوم بطرحه هنا, هو هل هذه القيمة الصدقية هي قيمة غير صدقية؟ اي تساوي `false`؟ لهذا نتحصل على الجواب `false`. + المتغير من نوع string `'Lydia'` هو قيمة صدقية أو حقيقية, بمعنى أنها تساوي `true` . السؤال الذي نقوم بطرحه هنا, هو هل هذه القيمة الصدقية هي قيمة غير صدقية؟ اي تساوي `false`؟ لهذا نتحصل على الجواب `false`. +

--- -5. أي الإجابات هو إجابة صحيحة؟ +5. أي الإجابات هو إجابة صحيحة؟ ```javascript const bird = { - size: "small" + size: "small", }; const mouse = { name: "Mickey", - small: true + small: true, }; ``` @@ -190,20 +188,21 @@ const mouse = {
الجواب هو الخيار الأول: A -في لغة الجافا سكريبت, جميع مفاتيح الobjects هي من النوع string. الا اذا كانت عبارة عن symbol. حتى ولو أننا في بعض المرات لانقوم بوضع نوعها على انها string بصورة صريحة, ولكنها دائما يتم تحويلها الى نوع string وراء الكواليس. +في لغة الجافا سكريبت, جميع مفاتيح الobjects هي من النوع string. الا اذا كانت عبارة عن symbol. حتى ولو أننا في بعض المرات لانقوم بوضع نوعها على انها string بصورة صريحة, ولكنها دائما يتم تحويلها الى نوع string وراء الكواليس. -لغة الجافاسكريبت تقوم بترجمةال statements.عندما نقوم باستعمال ال bracket notation, تقوم الجافا سكريبت اولا برؤية أول فتحة للقوس `[` و تقوم بالمتابعة الى ان تجد قفلة هذا القوس `]`.فقط عندما تصل الى قفلة القوس حتى تقوم بتقييم ال statement و من ثم معالجتها. +لغة الجافاسكريبت تقوم بترجمةال statements.عندما نقوم باستعمال ال bracket notation, تقوم الجافا سكريبت اولا برؤية أول فتحة للقوس `[` و تقوم بالمتابعة الى ان تجد قفلة هذا القوس `]`.فقط عندما تصل الى قفلة القوس حتى تقوم بتقييم ال statement و من ثم معالجتها. `mouse[bird.size]`: اولا تقوم بتقييم`bird.size`, والتي هي تساوي `"small"`. `mouse["small"]` تقوم بإرجاع`true` -ولكن في المقابل, عندما نقوم بإستخدام ال dot notation,لا يتم معالجة الأمر هكذا. `mouse` ليس لديها مفتاح يسمى `bird`, و هذا يعني أن `mouse.bird` هي قيمة `undefined`. بالتالي نقوم بالسؤال عن ال`size` بإستخدام ال dot notation: للسؤال عن قيمة `mouse.bird.size`. -وبما أن `mouse.bird`قيمتها `undefined` ف نحن فعليا نقوم بالسؤال عن `undefined.size` و التي هي بالتأكيد غير صحيحة و غير صالحة و ستقوم بإرجاع error مشابه ل `Cannot read property "size" of undefined`. +ولكن في المقابل, عندما نقوم بإستخدام ال dot notation,لا يتم معالجة الأمر هكذا. `mouse` ليس لديها مفتاح يسمى `bird`, و هذا يعني أن `mouse.bird` هي قيمة `undefined`. بالتالي نقوم بالسؤال عن ال`size` بإستخدام ال dot notation: للسؤال عن قيمة `mouse.bird.size`. +وبما أن `mouse.bird`قيمتها `undefined` ف نحن فعليا نقوم بالسؤال عن `undefined.size` و التي هي بالتأكيد غير صحيحة و غير صالحة و ستقوم بإرجاع error مشابه ل `Cannot read property "size" of undefined`. +

--- -6. ماهو الناتج؟ +6. ماهو الناتج؟ ```javascript let c = { greeting: "Hey!" }; @@ -231,7 +230,7 @@ console.log(d.greeting); -لذا, عندما تقوم بتغيير object واحد , انت فعليا تقوم بتغيير جميع الobjects. +لذا, عندما تقوم بتغيير object واحد , انت فعليا تقوم بتغيير جميع الobjects.

@@ -261,13 +260,13 @@ console.log(b === c);
الجواب هو الخيار الثالث: C -`new Number()` هي دالة من نوع built-in function constructer. على الرغم من أنها تبدو كرقم, ولكنها في الحقيقة ليس رقم, هي عبارة عن object ولديها العديد العديد من المميزات. - +`new Number()` هي دالة من نوع built-in function constructer. على الرغم من أنها تبدو كرقم, ولكنها في الحقيقة ليس رقم, هي عبارة عن object ولديها العديد العديد من المميزات. + عندما نقوم بإستخدام العلامة او العامل `==`, هي تقوم فقط بالتحقق من إذا ماكان لديها same _value_.كلا الطرفين قيمتهم تساوي `3` لهذا تقوم بإرجاع `true`. -و لكن على الرغم من هذا, عندما نقوم بإستخدام العملية أو المعامل `===`, كلا القيمة _and_ النوع يجب ان يكونا نفس الشيء. +و لكن على الرغم من هذا, عندما نقوم بإستخدام العملية أو المعامل `===`, كلا القيمة _and_ النوع يجب ان يكونا نفس الشيء. -هي ليست `new Number()` هي ليست عبارة عن رقم, هي عبارة عن **object** , وكلاهما سيقومان بإرجاع `false.` +هي ليست `new Number()` هي ليست عبارة عن رقم, هي عبارة عن **object** , وكلاهما سيقومان بإرجاع `false.`

@@ -275,7 +274,7 @@ console.log(b === c); --- -8. ماهو الناتج؟ +8. ماهو الناتج؟ ```javascript class Chameleon { @@ -303,7 +302,8 @@ console.log(freddie.colorChange("orange"));
الجواب هو الخيار الرابع: D -الدالة `colorChange` هي دالة static, و الدوال التي هي من نوع static هي دوال صممت لكي يتم استخدامها فقط في الconstructor الذي تم تعريفها به, و ليس من الممكن ان يتم تمريرها او استخدامها من قبل اي مكون children. بما أن `freddie` هي متغير children فإن الدالة لم يتم تمريرها اليه و هي غير متوفرة في ال instant من `freddie` لذا نتحصل على الخطأ `TypeError` . +الدالة `colorChange` هي دالة static, و الدوال التي هي من نوع static هي دوال صممت لكي يتم استخدامها فقط في الconstructor الذي تم تعريفها به, و ليس من الممكن ان يتم تمريرها او استخدامها من قبل اي مكون children. بما أن `freddie` هي متغير children فإن الدالة لم يتم تمريرها اليه و هي غير متوفرة في ال instant من `freddie` لذا نتحصل على الخطأ `TypeError` . +

@@ -327,16 +327,17 @@ console.log(greetign);
الجواب هو الخيار الأول : A -تقوم بعمل log على الconsole ل object. و لأننا قمنا بإنشاء object فارغ في global object! عندما قمنا بالخطأ بطباعة `greetign` بدل ان نقوم بطباعتها بصورة صحيحة هكذا `greeting`, هنا قام مترجم الجافاسكريبت بترجمة الآتي `global.greetign = {}` أو `window.greetign = {}` في المتصفح. +تقوم بعمل log على الconsole ل object. و لأننا قمنا بإنشاء object فارغ في global object! عندما قمنا بالخطأ بطباعة `greetign` بدل ان نقوم بطباعتها بصورة صحيحة هكذا `greeting`, هنا قام مترجم الجافاسكريبت بترجمة الآتي `global.greetign = {}` أو `window.greetign = {}` في المتصفح. + +لكي نتجنب حدوث مثل هذه الحالة, بإمكاننا إستخدام `"use strict"`. بفعل هذه الخطوة ستتأكد من أنك قد عرفت المتغير قبل ان تساويه بأي شي آخر. -لكي نتجنب حدوث مثل هذه الحالة, بإمكاننا إستخدام `"use strict"`. بفعل هذه الخطوة ستتأكد من أنك قد عرفت المتغير قبل ان تساويه بأي شي آخر.

--- - 10. ما الذي يحدث عندما نقوم بعمل الآتي؟ +10. ما الذي يحدث عندما نقوم بعمل الآتي؟ ```javascript function bark() { @@ -359,6 +360,7 @@ bark.animal = "dog"; هذا ممكن في لغة الجافاسكريبت, لأن الدوال هي عبارة عن objects, (كل شيء بداخل الأنواع التي هي primitive هو عبارة عن object) الدالة هي عبارة عن نوع خاص من الobjects, الكود الذي تقوم بكتابته بنفسك هو ليس بالدالة الفعلية, الدالة هي object لديه خصائص. و هذه الخاصية قابلة للمناداة +

@@ -374,7 +376,7 @@ function Person(firstName, lastName) { } const member = new Person("Lydia", "Hallie"); -Person.getFullName = function() { +Person.getFullName = function () { return `${this.firstName} ${this.lastName}`; }; @@ -392,10 +394,11 @@ console.log(member.getFullName()); الجواب هو الخيار الأول: A ليس بإمكانك اضافة الخصائص ل constructor كما تقوم بإضافة الخصائص للobjects. إذا أردت أن تضيف مميزات لكل الobjects مرة واحدة, سيجب عليك أن تقوم بإستخدام الprototype. لذا في هذه الحالة, + ```js -Person.prototype.getFullName = function() { +Person.prototype.getFullName = function () { return `${this.firstName} ${this.lastName}`; }; ``` @@ -434,9 +437,10 @@ console.log(sarah);
الجواب هو الخيار الأول: A -للمتغير `sarah` لم نقم بإستخدام الكلمة المفتاحية `new`, عندإستخدام الكلمة المفتاحية `new` ف هي تشير الى ال object الخالي او الفارغ الذي قمنا بإنشاءه, و لكن اذا لم تقم بإضافة`new` ف هي ستشير الى ال **global object**!. +للمتغير `sarah` لم نقم بإستخدام الكلمة المفتاحية `new`, عندإستخدام الكلمة المفتاحية `new` ف هي تشير الى ال object الخالي او الفارغ الذي قمنا بإنشاءه, و لكن اذا لم تقم بإضافة`new` ف هي ستشير الى ال **global object**!. + +نحن نقول بأن `this.firstName` تساوي `"Sarah"` و `this.lastName` تساوي `"Smith"`. ماقمنا بفعله حقا هنا, هو أنه قمنا بتعريف `global.firstName = 'Sarah'` و `global.lastName = 'Smith'`. المتغير `sarah` لا يظل `undefined`. -نحن نقول بأن `this.firstName` تساوي `"Sarah"` و `this.lastName` تساوي `"Smith"`. ماقمنا بفعله حقا هنا, هو أنه قمنا بتعريف `global.firstName = 'Sarah'` و `global.lastName = 'Smith'`. المتغير `sarah` لا يظل `undefined`.

@@ -457,7 +461,7 @@ console.log(sarah);
الجواب هو الخيار الرابع: D -أثناء مرحلة ال**capturing**, الevent تمر عبر العناصر العليا, أي العناصر الآباء إلى أن تصل الى العنصر المقصود أو المراد, حينها تتمكن من الوصول الى العنصر **target** , و حينها تبدأ عملية ال **bubbling**. +أثناء مرحلة ال**capturing**, الevent تمر عبر العناصر العليا, أي العناصر الآباء إلى أن تصل الى العنصر المقصود أو المراد, حينها تتمكن من الوصول الى العنصر **target** , و حينها تبدأ عملية ال **bubbling**. @@ -479,7 +483,8 @@ console.log(sarah);
الجواب هو الخيار الثاني: B -جميع الobjects لديها prototypes, عدا ال objects من نوع **base object**. الobject من نوع base object هو عبارة عن object تم إنشاءه من قبل المستخدم, أو تم إنشاءه عن طريق إستخدام الكلمة المفتاحية `new`. الbase object لديه حق الوصول الى بعض ال methods و الخصائص. مثال: `.toString`. هذا هو السبب الذي يمكنك من إستخدام built-in JavaScript methods, مثل هذه ال methods جميعها متاحة في ال ptototype, على الرغم من أن لغة الجافا سكريبت ليس بإمكانها أن تجدها بصورة مباشرة من الobject الذي قمت أنت بإنشاءه, و لكنها تذهب الى سلسلة الprototype حيث بإمكانها ان تجده هناك, مما يجعله قابل للوصول من قبلك, أي بإمكانك أن تصل إليه. +جميع الobjects لديها prototypes, عدا ال objects من نوع **base object**. الobject من نوع base object هو عبارة عن object تم إنشاءه من قبل المستخدم, أو تم إنشاءه عن طريق إستخدام الكلمة المفتاحية `new`. الbase object لديه حق الوصول الى بعض ال methods و الخصائص. مثال: `.toString`. هذا هو السبب الذي يمكنك من إستخدام built-in JavaScript methods, مثل هذه ال methods جميعها متاحة في ال ptototype, على الرغم من أن لغة الجافا سكريبت ليس بإمكانها أن تجدها بصورة مباشرة من الobject الذي قمت أنت بإنشاءه, و لكنها تذهب الى سلسلة الprototype حيث بإمكانها ان تجده هناك, مما يجعله قابل للوصول من قبلك, أي بإمكانك أن تصل إليه. +

@@ -506,9 +511,10 @@ sum(1, "2");
الجواب هو الخيار الثالث: C -لغة الجافاسكريبت هي لغة **dynamically typed language** بمعنى أننا لا نقوم بتعريف نوع معين للمتغيرات, المتغيرات بصورة أوتوماتيكية يتم تحويلها الى أنواع أخرى بدون أن تعرف أنت ذلك, وهذا يسمى ب _implicit type coercion_. **Coercion** تعني بأنك تقوم بالتحويل من نوع الى آخر. +لغة الجافاسكريبت هي لغة **dynamically typed language** بمعنى أننا لا نقوم بتعريف نوع معين للمتغيرات, المتغيرات بصورة أوتوماتيكية يتم تحويلها الى أنواع أخرى بدون أن تعرف أنت ذلك, وهذا يسمى ب _implicit type coercion_. **Coercion** تعني بأنك تقوم بالتحويل من نوع الى آخر. + +في هذا المثال, لغة الجافاسكريبت تقوم بتحويل الرقم `1` الى string, لكي تستطيع الدالةأن تقوم بعملها و تتمكن من إرجاع قيمة. أثناء قيام عملية إضافةالمتغير من النوع number و الذي هو (`1`) و المتغير من النوع string والذي هو (`'2'`), الرقم تم التعامل معه ك string, بهذه الطريقة سنتمكن من عمل عملية concatenate للمتغيرين من نوع string ك مثال `"Hello" + "World"`, لهذا مايحدث هنا هو عبارة عن `"1" + "2"` و الذي بدوره يقوم بإرجاع `"12"`. -في هذا المثال, لغة الجافاسكريبت تقوم بتحويل الرقم `1` الى string, لكي تستطيع الدالةأن تقوم بعملها و تتمكن من إرجاع قيمة. أثناء قيام عملية إضافةالمتغير من النوع number و الذي هو (`1`) و المتغير من النوع string والذي هو (`'2'`), الرقم تم التعامل معه ك string, بهذه الطريقة سنتمكن من عمل عملية concatenate للمتغيرين من نوع string ك مثال `"Hello" + "World"`, لهذا مايحدث هنا هو عبارة عن `"1" + "2"` و الذي بدوره يقوم بإرجاع `"12"`.

@@ -541,8 +547,8 @@ console.log(number); ال **prefix** العامل الأحادي `++`: -1. تقوم بزيادة القيمة(number الآن تساوي `2`) -2. تقوم بإٍرجاع القيمة (هذه ترجع `2`) +1. تقوم بزيادة القيمة(number الآن تساوي `2`) +2. تقوم بإٍرجاع القيمة (هذه ترجع `2`) هذا يقوم بإرجاع `0 2 2`. @@ -552,7 +558,7 @@ console.log(number); --- -17.ماهو الناتج؟ +17.ماهو الناتج؟ ```javascript function getPersonInfo(one, two, three) { @@ -576,7 +582,8 @@ getPersonInfo`${person} is ${age} years old`;
الجواب هو الخيار الثاني: B -اذا قمت بإستخدام tagged template literals, فإن قيمة ال argument الأول هي دائما عبارة عن array والذي نوع قيمها عبارة عن string, ماتبقى من الarguments تتحصل على القيم من الpassed expressions. +اذا قمت بإستخدام tagged template literals, فإن قيمة ال argument الأول هي دائما عبارة عن array والذي نوع قيمها عبارة عن string, ماتبقى من الarguments تتحصل على القيم من الpassed expressions. +

@@ -608,11 +615,11 @@ checkAge({ age: 18 });
الجواب هو الخيار الثالث: C -عندما نقوم بإختبار المساواة أو التساوي بين طرفين, ال primitives يتم مقارنتها عن طريق قيمها, بينما ال objects يتم مقارنتها عن طريق الreference الذي يتبع لها, لغة الجافاسكريبت تتحقق عن إذا ماكان الrefrence الذي يتبع لobject يشير الى نفس الموقع في الذاكرة. +عندما نقوم بإختبار المساواة أو التساوي بين طرفين, ال primitives يتم مقارنتها عن طريق قيمها, بينما ال objects يتم مقارنتها عن طريق الreference الذي يتبع لها, لغة الجافاسكريبت تتحقق عن إذا ماكان الrefrence الذي يتبع لobject يشير الى نفس الموقع في الذاكرة. -لدينا هنا اثنان من ال objects والتي نقوم بعمل مقارنة بينهما, واللذان بدورهما ليس لديهما ذلك, الobject الذي قمنا بتمريره ك parameter يشير الى موقع مختلف في الذاكرة من الموقع الذي يشير اليه الobject الثاني و الذي تم استخدامه للتحق من شرط المساواة. +لدينا هنا اثنان من ال objects والتي نقوم بعمل مقارنة بينهما, واللذان بدورهما ليس لديهما ذلك, الobject الذي قمنا بتمريره ك parameter يشير الى موقع مختلف في الذاكرة من الموقع الذي يشير اليه الobject الثاني و الذي تم استخدامه للتحق من شرط المساواة. -لهذا كلا من `{ age: 18 } === { age: 18 }` و `{ age: 18 } == { age: 18 }` يرجعان `false`. +لهذا كلا من `{ age: 18 } === { age: 18 }` و `{ age: 18 } == { age: 18 }` يرجعان `false`.

@@ -640,14 +647,15 @@ getAge(21);
الجواب هو الخيار الثالث: C -العامل spread `...args` يقوم بإرجاع array مع arguments. الarray هي object, لذا فإن `typeof args` تقوم بإرجاع `"object"`. +العامل spread `...args` يقوم بإرجاع array مع arguments. الarray هي object, لذا فإن `typeof args` تقوم بإرجاع `"object"`. +

--- -20. ماهو الناتج؟ +20. ماهو الناتج؟ ```javascript function getAge() { @@ -669,7 +677,8 @@ getAge();
الجواب هو الخيار الثالث: C -بإستخدام `"use strict"`, يمكنك التأكد بأنك لن تقوم عن طريق الخطأ بتعريف global variables. نحن لم نقم قط بتعريف المتغير `age`, و بما أننا قمنا بإستخدام `"use strict"` ستقوم بإرجاع reference error. اذا لم نقم بإستخدام `"use strict"` لكانت قد أدت المطلوب, بما أن الخاصية `age` تم إضافتها لل global object. +بإستخدام `"use strict"`, يمكنك التأكد بأنك لن تقوم عن طريق الخطأ بتعريف global variables. نحن لم نقم قط بتعريف المتغير `age`, و بما أننا قمنا بإستخدام `"use strict"` ستقوم بإرجاع reference error. اذا لم نقم بإستخدام `"use strict"` لكانت قد أدت المطلوب, بما أن الخاصية `age` تم إضافتها لل global object. +

@@ -678,7 +687,7 @@ getAge();
21. ماهي القيمة التي تحملها `sum`؟ -
+ ```javascript const sum = eval("10*10+5"); @@ -694,7 +703,8 @@ const sum = eval("10*10+5");
الجواب هو الخيار الأول : A -`eval` تقوم بتقييم الكود الذي تم تمريره ك string. إذا كان عبارة عن expression كما في هذه الحالة, فإنها تقوم بتقييم ال expression. ال expression هو `10 * 10 + 5`. و هذا بدوره يقوم بإرجاع الرقم `105`. +`eval` تقوم بتقييم الكود الذي تم تمريره ك string. إذا كان عبارة عن expression كما في هذه الحالة, فإنها تقوم بتقييم ال expression. ال expression هو `10 * 10 + 5`. و هذا بدوره يقوم بإرجاع الرقم `105`. +

@@ -708,6 +718,7 @@ const sum = eval("10*10+5"); ```javascript sessionStorage.setItem("cool_secret", 123); ``` +
A - الى الأبد, فالبيانات لايمكن أن تفقد. @@ -717,6 +728,7 @@ B - عندما يقوم المستخدم بقفل ال tab. C - عندما يقوم المستخدم بقفل نافذه المتصفح , ليس فقط الtab. D - عندما يقوم المستخدم بقفل جهاز الكمبيوتر. +
الإجابة @@ -724,16 +736,17 @@ D - عندما يقوم المستخدم بقفل جهاز الكمبيوتر.
الجواب هو الخيار الثاني: B -البيانات التي يتم تخزينها في `sessionStorage` يتم فقدها بعد قفل ال tab. +البيانات التي يتم تخزينها في `sessionStorage` يتم فقدها بعد قفل ال tab. + +إذا قمت بإستخدام `localStorage`, البيانات ستكون مخزنة هناك الى الأبد, و لكن اذا قمت بإستثناء ان تقوم بمناداة الدالة Clear كما في التالي `localStorage.clear()` عندها ستفقد هذه البيانات.: -إذا قمت بإستخدام `localStorage`, البيانات ستكون مخزنة هناك الى الأبد, و لكن اذا قمت بإستثناء ان تقوم بمناداة الدالة Clear كما في التالي `localStorage.clear()` عندها ستفقد هذه البيانات.:

--- -23. ماهو الناتج؟ +23. ماهو الناتج؟ ```javascript var num = 8; @@ -752,9 +765,10 @@ console.log(num);
الجواب هو الخيار الثاني: B -مع الكلمة المفتاحية `var` بإمكانك تريف عدد من المتغيرات تحمل نفس الإسم, و المتغير سيقوم بأخذ آخر قيمة تمت إضافتها اليه. +مع الكلمة المفتاحية `var` بإمكانك تريف عدد من المتغيرات تحمل نفس الإسم, و المتغير سيقوم بأخذ آخر قيمة تمت إضافتها اليه. + +ليس بإمكانك أن تفعل هذا مع `let` أو `const` بما أن الكلمتان المفتاحيتان عبارة عن block-scoped, بمعنى أن القيمة ستكون متاحة في نطاق الBlock الذي تم تعريفها به. -ليس بإمكانك أن تفعل هذا مع `let` أو `const` بما أن الكلمتان المفتاحيتان عبارة عن block-scoped, بمعنى أن القيمة ستكون متاحة في نطاق الBlock الذي تم تعريفها به.

@@ -783,16 +797,17 @@ set.has(1);
الجواب هو الخيار الثالث: C -كل مفاتيح ال object (عدا الSymbols)هي عبارة عن strings وراء الكواليس, حتى لو لم تقم بكتابة ذلك صراحة بنفسك ك string, لهذا دائما `obj.hasOwnProperty('1')` تقوم بإرجاع القيمة true. +كل مفاتيح ال object (عدا الSymbols)هي عبارة عن strings وراء الكواليس, حتى لو لم تقم بكتابة ذلك صراحة بنفسك ك string, لهذا دائما `obj.hasOwnProperty('1')` تقوم بإرجاع القيمة true. + +ولكنها لا تعمل بهذا الشكل مع set, ليس هنالك `'1'` من ضمن set, لهذا `set.has('1')` تقوم بإرجاع `false`, لديها القيمة الرقمية `1` أي من النوع number, `set.has(1)` تقوم بإرجاع `true`. -ولكنها لا تعمل بهذا الشكل مع set, ليس هنالك `'1'` من ضمن set, لهذا `set.has('1')` تقوم بإرجاع `false`, لديها القيمة الرقمية `1` أي من النوع number, `set.has(1)` تقوم بإرجاع `true`.

--- -25. ماهو الناتج؟ +25. ماهو الناتج؟ ```javascript const obj = { a: "one", b: "two", a: "three" }; @@ -822,7 +837,7 @@ console.log(obj); - A: true - B: false -- C: تعتمد على +- C: تعتمد على
الإجابة

@@ -830,9 +845,10 @@ console.log(obj); الجواب هو الخيارالأول: A سياق التنفيذ الأساسي هو سياق تنفيذ الglobal, وهي الشيء الذي يمكن الوصول إليه من أي مكان في الكود الذي ببرنامجك. +

- + --- @@ -855,7 +871,8 @@ for (let i = 1; i < 5; i++) {
الجواب هو الخيار الثالث: C -العبارة `continue` تقوم بتخطي دورة التكرار إذا وجد شرط معين يقوم بإرجاع `true`. +العبارة `continue` تقوم بتخطي دورة التكرار إذا وجد شرط معين يقوم بإرجاع `true`. +

@@ -871,7 +888,7 @@ String.prototype.giveLydiaPizza = () => { const name = "Lydia"; -console.log(name.giveLydiaPizza()) +console.log(name.giveLydiaPizza()); ``` - A: `"Just give Lydia pizza already!"` @@ -884,14 +901,15 @@ console.log(name.giveLydiaPizza())
الجواب هو الخيار الأول : A -`String` هي built-in constructor, و لهذا سنتمكن من إضافة خصائص لها. لقد قمت بإضافة method للprototype الخاص ب `String`. Primitive strings يتمتحويلهم بصورة اوتوماتيكية الى objects من نوع string, و التي بدورها تم انشائها عن طريق دالة ال string prototype, لهذا جميع الstrings و التي هي string objects لديها حق الوصول الى الmethod. +`String` هي built-in constructor, و لهذا سنتمكن من إضافة خصائص لها. لقد قمت بإضافة method للprototype الخاص ب `String`. Primitive strings يتمتحويلهم بصورة اوتوماتيكية الى objects من نوع string, و التي بدورها تم انشائها عن طريق دالة ال string prototype, لهذا جميع الstrings و التي هي string objects لديها حق الوصول الى الmethod. +

--- -29. ماهو الناتج؟ +29. ماهو الناتج؟ ```javascript const a = {}; @@ -914,12 +932,13 @@ console.log(a[b]);
الجواب هو الخيار الثاني : B -مفاتيح ال object يتم تحويلها اوتوماتيكيا الى strings. نحن نحاول أن نقوم بجعل object عبارة عن مفتاح للobject `a`, و الذي يحمل القيمة `123`. +مفاتيح ال object يتم تحويلها اوتوماتيكيا الى strings. نحن نحاول أن نقوم بجعل object عبارة عن مفتاح للobject `a`, و الذي يحمل القيمة `123`. و لكن, عندما نقوم بمحاول جعل object الى نوع string, سيصبح `"[object Object]"`. لذا ما نحاول أن نقوله هنا, هو أن `a["object Object"] = 123`. -إذا, سنحاول أن نفعل هذا مرة أخرى , `c` هو object آخر سنقوم بتحويله الى string بصورة صريحة, لذا `a["object Object"] = 456`. +إذا, سنحاول أن نفعل هذا مرة أخرى , `c` هو object آخر سنقوم بتحويله الى string بصورة صريحة, لذا `a["object Object"] = 456`. + +إذاَ, نحن نقوم بعمل log ل `a[b]`, و التي هي في الحقيقة `a["object Object"]`. و نحن قبل قليل قمنا بوضع قيمتها التي تساوي `456`, لذا ستقوم بإرجاع `456`. -إذاَ, نحن نقوم بعمل log ل `a[b]`, و التي هي في الحقيقة `a["object Object"]`. و نحن قبل قليل قمنا بوضع قيمتها التي تساوي `456`, لذا ستقوم بإرجاع `456`.

@@ -950,17 +969,17 @@ baz(); لدينا الدالة `setTimeout` والتي تم استدعائها أولا, و لكن تم الخروج منها آخراً. -هذا لأن في المتصفح, ليس لدينا محرَك من نوع runtime, أيضا لدينا مايعرف ب `WebAPI`. هذا ال`WebAPI` يقوم بإعطائنا الدالة `setTimeout` لكي نبدأ بها, على سبيل المثال: DOM. +هذا لأن في المتصفح, ليس لدينا محرَك من نوع runtime, أيضا لدينا مايعرف ب `WebAPI`. هذا ال`WebAPI` يقوم بإعطائنا الدالة `setTimeout` لكي نبدأ بها, على سبيل المثال: DOM. بعد ان يتم ارسال و البدء بتنفيذ ال _callback_ الى الWebAPI, الدالة `setTimeout` نفسها (ليس ال callback!) يتم اخراجها من الstack. -الآن, `foo` يتم إدخالها و البدء بتنفيذها, بينما `"First"` يتم تسجيل دخولها. +الآن, `foo` يتم إدخالها و البدء بتنفيذها, بينما `"First"` يتم تسجيل دخولها. -`foo` يتم إخراجها من ال stack, بينما `baz` يتم إدخالها و البدأ بتنفيذها. `"Third"` يتم تسجيل دخولها. +`foo` يتم إخراجها من ال stack, بينما `baz` يتم إدخالها و البدأ بتنفيذها. `"Third"` يتم تسجيل دخولها. @@ -968,17 +987,19 @@ baz(); -هنا تحديدا المكان الذي تبدأ فيه الloop بالعمل. +هنا تحديدا المكان الذي تبدأ فيه الloop بالعمل. ال **event loop** تنظر الى الstack و ال task queue, إذا كانت الstack خاوية, فهي تقوم بأخذ أول شيء في الqueue. و تقوم بإدخاله الى stack. -`bar` يتم إدخالها و البدأ بتنفيذها, `"Second"` يتم تسجيل دخولها, و من ثم إخراجها من الstack. +`bar` يتم إدخالها و البدأ بتنفيذها, `"Second"` يتم تسجيل دخولها, و من ثم إخراجها من الstack. +

--- +
31. ماهو ال event.target عندما نقوم بالضغط على الزر
@@ -986,14 +1007,12 @@ baz(); ```html
- +
``` -- A: الخارجي `div` +- A: الخارجي `div` - B: الداخلي `div` - C: `button` - D: array تحتوي على جميع العناصرالمتداخلة. @@ -1003,7 +1022,8 @@ baz();
الجواب هو الخيار الثالث: C -العنصر المتداخل الأعمق الذي تسبب بتنفيذ الevent هو العنصر الذي يستهدفه هذا الevent, بإمكانك إيقاف ال bubbling عن طريق `event.stopPropagation`. +العنصر المتداخل الأعمق الذي تسبب بتنفيذ الevent هو العنصر الذي يستهدفه هذا الevent, بإمكانك إيقاف ال bubbling عن طريق `event.stopPropagation`. +

@@ -1016,9 +1036,7 @@ baz(); ```html
-

- Click here! -

+

Click here!

``` @@ -1032,7 +1050,8 @@ baz();
الجواب هو الخيار الأول: A -إذا قمنا بالضغط على `p` سنرى إثنان من الlogs, ألا و هما `p` و `div`, أثناء عملية event propagation, هنالك ثلاث مراحل: الا وهي capturing, target و bubbling. بصورة افتراضية, الevent handlers يتم تنفيذهم في مرحلة الbubbling (إلا في حال أنك قمت بضبط قيمة `useCapture` ل `true` ). هي تتسلسل ابتداءا من أعمق عنصر متداخل تصاعدا الى الأقل عمقاً. +إذا قمنا بالضغط على `p` سنرى إثنان من الlogs, ألا و هما `p` و `div`, أثناء عملية event propagation, هنالك ثلاث مراحل: الا وهي capturing, target و bubbling. بصورة افتراضية, الevent handlers يتم تنفيذهم في مرحلة الbubbling (إلا في حال أنك قمت بضبط قيمة `useCapture` ل `true` ). هي تتسلسل ابتداءا من أعمق عنصر متداخل تصاعدا الى الأقل عمقاً. +

@@ -1062,9 +1081,10 @@ sayHi.bind(person, 21);
الجواب هو الخيار الرابع: D -في الحالتين, بإمكاننا تمرير ال object الذي نود أن تشير اليه الكلمة المفتاحية `this`, ولكن, `.call` هي أيضا تم تنفيذها حالا. +في الحالتين, بإمكاننا تمرير ال object الذي نود أن تشير اليه الكلمة المفتاحية `this`, ولكن, `.call` هي أيضا تم تنفيذها حالا. `.bind.` تقوم بإرجاع نسخة من الدالة, ولكن مع سياق محدد, لذا هي لا يتم تنفيذها حالاً. +

@@ -1091,9 +1111,10 @@ console.log(typeof sayHi());
الجواب هو الخيار الثاني: B -دالة `sayHi` تقوم بإرجاع القيمة المرجعة من الدالة المناداة في اللحظة (IIFE). هذه الدالة تقوم بإرجاع `0`, و الذي نوعه عبارة عن `"number"`. +دالة `sayHi` تقوم بإرجاع القيمة المرجعة من الدالة المناداة في اللحظة (IIFE). هذه الدالة تقوم بإرجاع `0`, و الذي نوعه عبارة عن `"number"`. + +لمعلوماتك: لدينا فقط سبعة أنواع من ال built-in و هي : `null`, `undefined`, `boolean`, `number`, `string`, `object`, و `symbol`, و `bigint`.`"function"` هي ليست نوع, وبما أن الدوال عبارة عن objects, ف هي ليست من النوع `"object"`. -لمعلوماتك: لدينا فقط سبعة أنواع من ال built-in و هي : `null`, `undefined`, `boolean`, `number`, `string`, `object`, و `symbol`, و `bigint`.`"function"` هي ليست نوع, وبما أن الدوال عبارة عن objects, ف هي ليست من النوع `"object"`.

@@ -1130,7 +1151,7 @@ undefined; - `''` (empty string) - `false` -Function constructors, مثل `new Number` و `new Boolean` هي قيم صحيحية. +Function constructors, مثل `new Number` و `new Boolean` هي قيم صحيحية.

@@ -1186,6 +1207,7 @@ console.log(numbers); `[1, 2, 3, 7 x empty, 11]` وذلك يعتمد على المكان الذي قمت فيه بتشغيل البرنامج ( هو مختلف لكل متصفح, node, ...الخ) +

@@ -1220,9 +1242,10 @@ console.log(numbers); النطاق أو الblock `catch`يستقبل ال arguemnt الذي يساوي `x`, هذا ليس نفس القيمة `x` عندما قمنا بتمرير الarguments, هذا المتغير `x` هو متغير block-scoped, أي يتم التعامل معه أو مناداته فقط بداخل الblock الذي تم تعريفه به. -لاحقا, قمنا بضبط القيمة `1` لهذا المتغير من نوع block-scoped, وقمنا أيضا بضبط قيمة للمتغير `y`. الآن نحن نقوم بطباعة قيمة المتغير الذي من نوع block-scoped و الذي هو `x` عن طريق الlog, و الذي هو يساوي `1`. +لاحقا, قمنا بضبط القيمة `1` لهذا المتغير من نوع block-scoped, وقمنا أيضا بضبط قيمة للمتغير `y`. الآن نحن نقوم بطباعة قيمة المتغير الذي من نوع block-scoped و الذي هو `x` عن طريق الlog, و الذي هو يساوي `1`. + +بخارج نطاق ال`catch` block, `x` هي لاتزال `undefined`, و قيمة ال `y` تساوي `2`. عندما نريد طباعة قيمة ال x عن طريق الlog خارج نطاق ال `catch` block, فهي تقوم بإرجاع `undefined`, و ال `y` تقوم بإرجاع `2`. -بخارج نطاق ال`catch` block, `x` هي لاتزال `undefined`, و قيمة ال `y` تساوي `2`. عندما نريد طباعة قيمة ال x عن طريق الlog خارج نطاق ال `catch` block, فهي تقوم بإرجاع `undefined`, و ال `y` تقوم بإرجاع `2`.

@@ -1243,19 +1266,23 @@ console.log(numbers); لغة الجافاسكريبت لديها فقط primitive types و objects. -نقصد بال Primitive types: `boolean`, `null`, `undefined`, `bigint`, `number`, `string`, و `symbol`. +نقصد بال Primitive types: `boolean`, `null`, `undefined`, `bigint`, `number`, `string`, و `symbol`. + +مايميز ال primitive من ال object هو أن ال primitives ليس لديها أي خصائص أو methods; ولكنك ستلاحظ أن `'foo'.toUpperCase()`يتم تقييمها ومعالجتها الى `'FOO'`و لا نتحصل على الخطأ `TypeError`. هذا لأنه عندما تحاول الوصول الى خاصية أو method لمتغير من من نوع primitive مثل ال string, فإن لغة الجافاسكريبت ستقوم بشكل ضمني بعمل wrap لل object بإستخدام واحدة من ال wrapper Classes, أي مانعنيه `String`, و لاحقا بصورة مباشرة يقوم بالتخلص من الwrapper, بعد أن يتم تقييم و تنفيذ الexpression. جميع الprimitives, ماعدا `null` و `undefined` تقوم بعمل هذه العملية. -مايميز ال primitive من ال object هو أن ال primitives ليس لديها أي خصائص أو methods; ولكنك ستلاحظ أن `'foo'.toUpperCase()`يتم تقييمها ومعالجتها الى `'FOO'`و لا نتحصل على الخطأ `TypeError`. هذا لأنه عندما تحاول الوصول الى خاصية أو method لمتغير من من نوع primitive مثل ال string, فإن لغة الجافاسكريبت ستقوم بشكل ضمني بعمل wrap لل object بإستخدام واحدة من ال wrapper Classes, أي مانعنيه `String`, و لاحقا بصورة مباشرة يقوم بالتخلص من الwrapper, بعد أن يتم تقييم و تنفيذ الexpression. جميع الprimitives, ماعدا `null` و `undefined` تقوم بعمل هذه العملية.

--- -40. ماهو الناتج؟ +40. ماهو الناتج؟ ```javascript -[[0, 1], [2, 3]].reduce( +[ + [0, 1], + [2, 3], +].reduce( (acc, cur) => { return acc.concat(cur); }, @@ -1275,7 +1302,8 @@ console.log(numbers); `[1, 2]` هي القيمة المبدئية.هذه القيمة هي التي بدأنا بها, و هي القيمة الأولى ل `acc`. أثناء الدورة الأولى`acc` تساوي `[1,2]` و `cur` تساوي `[0, 1]`, عندما نقوم بدمجهما سويا عن طريق concat يصبح لدينا الناتج `[1, 2, 0, 1]`. -إذاً, `[1, 2, 0, 1]` هي `acc` و `[2, 3]` هي `cur`. نقوم بدمجهما سوية و نتحصل على `[1, 2, 0, 1, 2, 3]`. +إذاً, `[1, 2, 0, 1]` هي `acc` و `[2, 3]` هي `cur`. نقوم بدمجهما سوية و نتحصل على `[1, 2, 0, 1, 2, 3]`. +

@@ -1302,27 +1330,29 @@ console.log(numbers); `null` قيمة خطئية. -`!null` تقوم بإرجاع `true`. +`!null` تقوم بإرجاع `true`. `!true` تقوم بإرجاع `false`. -********* - + +--- + `""` قيمة خطئية. -`!""`تقوم بإرجاع `true`. +`!""`تقوم بإرجاع `true`. `!true` تقوم بإرجاع `false`. -********* - + +--- + `1` قيمة صحيحية. `!1` تقوم بإرجاع `false`. -`!false` تقوم بإرجاع `true`. +`!false` تقوم بإرجاع `true`.

- + --- @@ -1338,11 +1368,10 @@ setInterval(() => console.log("Hi"), 1000);
A - رقم فريد أو متفرد id - - - B - قيمة محددة لل milliseconds - C - الدالة التي تم تمريرها +B - قيمة محددة لل milliseconds + +C - الدالة التي تم تمريرها `undefined` - D @@ -1353,14 +1382,15 @@ A - رقم فريد أو متفرد id
الجواب هو الخيار الأول: A -تقوم بإرجاع ال id الفريد, هذا الid يمكن استخدامه لكي يقوم بتصفير عداد الفترات المفصلة أي الinterval عن طريق استخدام الدالة `clearInterval()` +تقوم بإرجاع ال id الفريد, هذا الid يمكن استخدامه لكي يقوم بتصفير عداد الفترات المفصلة أي الinterval عن طريق استخدام الدالة `clearInterval()` +

--- -43. مالذي يتم ارجاعه بعد تنفيذ الكود أدناه؟ +43. مالذي يتم ارجاعه بعد تنفيذ الكود أدناه؟ ```javascript [..."Lydia"]; @@ -1377,6 +1407,7 @@ A - رقم فريد أو متفرد id الجواب هو الخيار الأول: A الstring هي تكرارية, و عملية الspread (...) تقوم بتحويل اي حرف تم فيه تنفيذ فئة تكرارية الى عنصر منفرد واحد. +

@@ -1407,11 +1438,12 @@ console.log(gen.next().value);
الجواب هو الخيار الثالث: C -الدوال العادية ليس بإمكانها ان تتوقف في وسط التنفيذ بعد أن يتم مناداتها, و لكن الدوال من نوع generator من الممكن أن يتم ايقافها وسط التنفيذ, و لاحقا يتم مواصلة تنفيذها من حيث المكان الذي توقفت به. في كل مرة تواجه فيها الدالة من نوع generator الكلمة المفتاحية `yield`, فإن الدالة تخضع أو تستسلم للقيمة المحددة بعدها. مع ملاحظة أن الدالة من نوع generator في هذه الحالة, لاتقوم بإرجاع القيمة, بل تخضع لتلك القيمة. +الدوال العادية ليس بإمكانها ان تتوقف في وسط التنفيذ بعد أن يتم مناداتها, و لكن الدوال من نوع generator من الممكن أن يتم ايقافها وسط التنفيذ, و لاحقا يتم مواصلة تنفيذها من حيث المكان الذي توقفت به. في كل مرة تواجه فيها الدالة من نوع generator الكلمة المفتاحية `yield`, فإن الدالة تخضع أو تستسلم للقيمة المحددة بعدها. مع ملاحظة أن الدالة من نوع generator في هذه الحالة, لاتقوم بإرجاع القيمة, بل تخضع لتلك القيمة. أولا, نقوم بإنشاء الدالة من نوع generator مع وجود المتغير `i` مساوي ل `10`. نقوم بمناداة الدالةمن نوع generator باستخدام الدالة `next()`. في المرة الأولى التي ننادي فيها الدالة من نوع generator, فإن ال `i` تساوي `10`. هي تواجه الكلمة المفتاحية `yield`, فتخضع لقيمة ال `i`. الدالة generator في هذه اللحظة تم توقيفها مؤقتا, و القيمة `10` تم طباعتها عن طريق log. -اذاً, نقوم بمناداة الدالة مرة أخرى عن طريق الدالة `next()`, هي تبدأ لتواصل من المكان الذي تم توقفيها فيه مؤقتا سابقاً, و ماتزال قيمة `i` تساوي `10`. الآن هي تواجه الكلمة المفتاحية `yield` التالية, و تواجه `i * 2`. `i` تساوي `10`,لهذا تقوم بإرجاع `10 * 2` و التي هي تساوي `20`, و هذا سيوصلنا للنتيجة `10, 20`. +اذاً, نقوم بمناداة الدالة مرة أخرى عن طريق الدالة `next()`, هي تبدأ لتواصل من المكان الذي تم توقفيها فيه مؤقتا سابقاً, و ماتزال قيمة `i` تساوي `10`. الآن هي تواجه الكلمة المفتاحية `yield` التالية, و تواجه `i * 2`. `i` تساوي `10`,لهذا تقوم بإرجاع `10 * 2` و التي هي تساوي `20`, و هذا سيوصلنا للنتيجة `10, 20`. +

@@ -1429,7 +1461,7 @@ const secondPromise = new Promise((res, rej) => { setTimeout(res, 100, "two"); }); -Promise.race([firstPromise, secondPromise]).then(res => console.log(res)); +Promise.race([firstPromise, secondPromise]).then((res) => console.log(res)); ``` - A: `"one"` @@ -1442,7 +1474,8 @@ Promise.race([firstPromise, secondPromise]).then(res => console.log(res));
الجواب هو الخيار الثاني: B -عندما نقوم بتمرير عدد من الpromises للدالة `Promise.race`. فهي تقوم برفض أو فصل الpromise الاولى. للدالة `setTimeout` نحن نقوم بتمرير timer: 500ms لل promise الأولى و التي هي (`firstPromise`), و 100ms اي 100ملي ثانية للpromise الثانية والتي هي (`secondPromise`) هذا يعني ان ال `secondPromise` يتم فصلها اولاً مع القيمة `'two'`. `res` الآن تحمل قيمة `'two'`, وهي التي تم طباعتها عن طريق الlog. +عندما نقوم بتمرير عدد من الpromises للدالة `Promise.race`. فهي تقوم برفض أو فصل الpromise الاولى. للدالة `setTimeout` نحن نقوم بتمرير timer: 500ms لل promise الأولى و التي هي (`firstPromise`), و 100ms اي 100ملي ثانية للpromise الثانية والتي هي (`secondPromise`) هذا يعني ان ال `secondPromise` يتم فصلها اولاً مع القيمة `'two'`. `res` الآن تحمل قيمة `'two'`, وهي التي تم طباعتها عن طريق الlog. +

@@ -1469,7 +1502,7 @@ console.log(members);
الجواب هو الخيار الرابع: D -أولا, نقوم بتعريف المتغير `person` مع قيمة عبارة عن object لديه الخاصية `name`. +أولا, نقوم بتعريف المتغير `person` مع قيمة عبارة عن object لديه الخاصية `name`. @@ -1478,11 +1511,12 @@ console.log(members); -ثم , نقوم بضبط قمية المتغير `person` بقيمة تساوي `null`. +ثم , نقوم بضبط قمية المتغير `person` بقيمة تساوي `null`. -نحن فقط نقوم بتعديل قيمة المتغير `person`, وليس أول عنصر في ال array, بما أن ذلك العنصر لديه refrence منسوخ من ال object. أول عنصر في `members` لا يزال لديه refrence للobject الأصلي. و عندما نقوم بطباع الarray `members` عن طريق الlog, فإن العنصر الأول لايزال يحمل قيمة الobject, و التي سيتم طباعتها عن طريق log. +نحن فقط نقوم بتعديل قيمة المتغير `person`, وليس أول عنصر في ال array, بما أن ذلك العنصر لديه refrence منسوخ من ال object. أول عنصر في `members` لا يزال لديه refrence للobject الأصلي. و عندما نقوم بطباع الarray `members` عن طريق الlog, فإن العنصر الأول لايزال يحمل قيمة الobject, و التي سيتم طباعتها عن طريق log. +

@@ -1494,7 +1528,7 @@ console.log(members); ```javascript const person = { name: "Lydia", - age: 21 + age: 21, }; for (const item in person) { @@ -1512,7 +1546,8 @@ for (const item in person) {
الجواب هو الخيار الثاني: B -بإستخدام `for-in` التكرارية, بامكاننا أن نصل الى جميع المفاتيح التي تخص object معين. في هذه الحالة `name` و `age`. ماوراء الكواليس, مفاتيح ال objects هي عبارة عن strings (إذا لم تكن هذه المفاتيح عبارة عن symbol), في أي حلقة من الحلقات التكرارية, نقوم بضبط القيمة `item`مساوية للمفتاح الحالي الذي هي تتكرر فيه اوعنده. أولا `item` تساوي `name`, و يتم طباعتها عن طريق الlog, ثم `item` تساوي `age` و التي ايضا تم طباعتها عن طريق الlog. +بإستخدام `for-in` التكرارية, بامكاننا أن نصل الى جميع المفاتيح التي تخص object معين. في هذه الحالة `name` و `age`. ماوراء الكواليس, مفاتيح ال objects هي عبارة عن strings (إذا لم تكن هذه المفاتيح عبارة عن symbol), في أي حلقة من الحلقات التكرارية, نقوم بضبط القيمة `item`مساوية للمفتاح الحالي الذي هي تتكرر فيه اوعنده. أولا `item` تساوي `name`, و يتم طباعتها عن طريق الlog, ثم `item` تساوي `age` و التي ايضا تم طباعتها عن طريق الlog. +

@@ -1535,11 +1570,12 @@ console.log(3 + 4 + "5");
الجواب هو الخيار الثاني: B -Operator associativity او ترابطية العامل هي الترتيب أو التسلسل الذي يقيم به الcompiler ال expressions, ف هو إما أن يكون من اليسار الى اليمين أو من اليمين الى اليسار. هذا يحدث فقط إذا كان جميع الoperators لديها نفس الأسبقية. لدينا فقط نوع واحد من الoperator ألا و هو `+`. بالإضافة الى التالي, الترابطية هي من اليسار الى اليمين. +Operator associativity او ترابطية العامل هي الترتيب أو التسلسل الذي يقيم به الcompiler ال expressions, ف هو إما أن يكون من اليسار الى اليمين أو من اليمين الى اليسار. هذا يحدث فقط إذا كان جميع الoperators لديها نفس الأسبقية. لدينا فقط نوع واحد من الoperator ألا و هو `+`. بالإضافة الى التالي, الترابطية هي من اليسار الى اليمين. `3 + 4` يتم تقييمها أولا. هذا مايعطينا الناتج الذي هو عبارة عن الرقم `7`. -`7 + '5'` تقوم بإرجاع الناتج `"75"` بسبب عملية ال coercion وهي العمليةالتي تقوم بالتحويل من نوع الى آخر, لغة الجافاسكريبت تقوم بتحويل الرقم `7` الى النوع string, أنظرالى السؤال رقم 15 في الأعلى. بإمكاننا عمل concatenate لمتغيرين من النوع string بإستخدام العملية `+`. `"7" + "5"` سترجع الناتج `"75"`. +`7 + '5'` تقوم بإرجاع الناتج `"75"` بسبب عملية ال coercion وهي العمليةالتي تقوم بالتحويل من نوع الى آخر, لغة الجافاسكريبت تقوم بتحويل الرقم `7` الى النوع string, أنظرالى السؤال رقم 15 في الأعلى. بإمكاننا عمل concatenate لمتغيرين من النوع string بإستخدام العملية `+`. `"7" + "5"` سترجع الناتج `"75"`. +

@@ -1564,9 +1600,10 @@ const num = parseInt("7*6", 10);
الجواب هو الخيار الثالث: C -فقط الأرقام الأولى في الstring يتم إرجاعها. بناءاً على _radix_ (الargument الثاني لكي يتم تحديدنوعية الرقم الذي نود أن نقوم بعمل parse له الى: base 10, hexadecimal, octal, binary, الخ. ). تقوم `parseInt` بالتحقق عن إذا ماكانت الحروف في الstring صالحة. و بمجرد أن تجد حرف غير صالح في ال radix, ف هي تقوم بإيقاف عملية الparsing مباشرة و تتجاهل الحروف التي تليه. +فقط الأرقام الأولى في الstring يتم إرجاعها. بناءاً على _radix_ (الargument الثاني لكي يتم تحديدنوعية الرقم الذي نود أن نقوم بعمل parse له الى: base 10, hexadecimal, octal, binary, الخ. ). تقوم `parseInt` بالتحقق عن إذا ماكانت الحروف في الstring صالحة. و بمجرد أن تجد حرف غير صالح في ال radix, ف هي تقوم بإيقاف عملية الparsing مباشرة و تتجاهل الحروف التي تليه. + +`*` ليست رقم صالح. هي فقط تقوم بعمل parse ل `"7"` الى عدد عشري `7`. `num` الآن تحمل القيمة `7`. -`*` ليست رقم صالح. هي فقط تقوم بعمل parse ل `"7"` الى عدد عشري `7`. `num` الآن تحمل القيمة `7`.

@@ -1576,7 +1613,7 @@ const num = parseInt("7*6", 10); 50. ماهو الناتج؟ ```javascript -[1, 2, 3].map(num => { +[1, 2, 3].map((num) => { if (typeof num === "number") return; return num * 2; }); @@ -1592,9 +1629,10 @@ const num = parseInt("7*6", 10);
الجواب هو الخيار الثالث: C -عندما يتم عمل mapping لل array, فإن قيمة `num` ستساوي قيمة العنصر الذي يتم حاليا المرور به, فكما نعرف أن الmapping يدور على جميع عناصر الarray. في هذه الحالة, العناصر عبارة عن أرقام, لهذا فإن شرط ال if statement `typeof num === "number"` يقوم بإرجاع `true`. دالة map تقوم بإنشاء array جديدة, و إدخال القيم المرجعة من الدالة في هذه الarray. +عندما يتم عمل mapping لل array, فإن قيمة `num` ستساوي قيمة العنصر الذي يتم حاليا المرور به, فكما نعرف أن الmapping يدور على جميع عناصر الarray. في هذه الحالة, العناصر عبارة عن أرقام, لهذا فإن شرط ال if statement `typeof num === "number"` يقوم بإرجاع `true`. دالة map تقوم بإنشاء array جديدة, و إدخال القيم المرجعة من الدالة في هذه الarray. + +ولكن, لا نقوم بإرجاع قيمة. عندما لا نقوم بإرجاع قيمة من الدالة, فإن الدالة تقوم بإرجاع `undefined`. لكل عنصرٍ في الarray, فإن نطاق الدالة او نعني الfunction block يتم مناداته, لهذا لأي عنصر نقوم بإرجاع `undefined`. -ولكن, لا نقوم بإرجاع قيمة. عندما لا نقوم بإرجاع قيمة من الدالة, فإن الدالة تقوم بإرجاع `undefined`. لكل عنصرٍ في الarray, فإن نطاق الدالة او نعني الfunction block يتم مناداته, لهذا لأي عنصر نقوم بإرجاع `undefined`.

@@ -1631,7 +1669,8 @@ console.log(person, birthYear); المتغير `birthYear` لديه refrence للقيمة `"1997"`. الargument `year` أيضا لديه refrence للقيمة `"1997"`, لكنها ليست نفس القيمة التي `birthYear` لديها refrence لها. عندما نقوم بتحديث قيمة `year` عن طريق ضبط `year` تساوي ل `"1998"`, نحن فقط نقوم بتحديث قيمة `year`. `birthYear` لا تزال تساوي `"1997"`. -قيمة `person` هي object. الargument `member` لديه نسخة refrence لنفس الobject. عندما نقوم بتعديل او تحديث خاصية للobject `member`و الذي لديه refrence لها, فإن قيمة `person` ستتعدل و تتغير أيضا,بما أن كلاهما لديهما refrence لنفس الobject. الخصائص `person` و `name` هما الأىن مساويان للقيمة `"Lydia"`. +قيمة `person` هي object. الargument `member` لديه نسخة refrence لنفس الobject. عندما نقوم بتعديل او تحديث خاصية للobject `member`و الذي لديه refrence لها, فإن قيمة `person` ستتعدل و تتغير أيضا,بما أن كلاهما لديهما refrence لنفس الobject. الخصائص `person` و `name` هما الأىن مساويان للقيمة `"Lydia"`. +

@@ -1667,16 +1706,17 @@ sayHi();
الجواب هو الخيار الرابع: D -مع عبارة `throw` , بإمكاننا إنشاء errors حسب الطلب, أي ليست كا الإخطاء العامة في اللغة, بإستخدام هذه العبارة بإمكانك أن تضع exception, الexception يمكن أن يكون : string, number, boolean أو object. في هذه الحالة, الexcption لدينا هو ال string `'Hello world'`. +مع عبارة `throw` , بإمكاننا إنشاء errors حسب الطلب, أي ليست كا الإخطاء العامة في اللغة, بإستخدام هذه العبارة بإمكانك أن تضع exception, الexception يمكن أن يكون : string, number, boolean أو object. في هذه الحالة, الexcption لدينا هو ال string `'Hello world'`. + +مع عبارة `catch`, بإمكاننا ان نحدد ما الذي يتوجب فعله عندما يتم وضع أو إلقاء الexception في نطاق ال `try`. تم إلقاء أو وضع exception: الstring `'Hello world'`. `e` الآن تساوي تلك الstring,log. هذا سيعطينا النتيجة `'Oh an error: Hello world'`. -مع عبارة `catch`, بإمكاننا ان نحدد ما الذي يتوجب فعله عندما يتم وضع أو إلقاء الexception في نطاق ال `try`. تم إلقاء أو وضع exception: الstring `'Hello world'`. `e` الآن تساوي تلك الstring,log. هذا سيعطينا النتيجة `'Oh an error: Hello world'`.

--- -53. ماهو الناتج؟ +53. ماهو الناتج؟ ```javascript function Car() { @@ -1698,7 +1738,8 @@ console.log(myCar.make);
الجواب هو الخيار الثاني: B -عندما تقوم بإرجاع خاصية, فإن قيمة هذه الخاصية هي تساوي القيمة المرجعة, ليس القيمة التي تم ضبطها في دالة الconstructor. نقوم بإرجاع ال string `"Maserati"`, لذا فإن `myCar.make` تساوي `"Maserati"`. +عندما تقوم بإرجاع خاصية, فإن قيمة هذه الخاصية هي تساوي القيمة المرجعة, ليس القيمة التي تم ضبطها في دالة الconstructor. نقوم بإرجاع ال string `"Maserati"`, لذا فإن `myCar.make` تساوي `"Maserati"`. +

@@ -1726,7 +1767,8 @@ console.log(typeof y);
الجواب هو الخيار الأول : A -`let x = y = 10;` هي في الحقيقة إختصار ل: +`let x = y = 10;` هي في الحقيقة إختصار ل: +
```javascript @@ -1736,11 +1778,12 @@ let x = y;
-عندما نقوم بضبط قيمة`y` لكي تساوي `10`, فنحن فعليا نقوم بإضافة الخاصية `y` للglobal object. (`window` في المتصفح, `global` في Node). في المتصفح, `window.y` الآن تساوي `10`. +عندما نقوم بضبط قيمة`y` لكي تساوي `10`, فنحن فعليا نقوم بإضافة الخاصية `y` للglobal object. (`window` في المتصفح, `global` في Node). في المتصفح, `window.y` الآن تساوي `10`. ثم, عندما نقوم بتعريف المتغير `x` بالقيمة `y` و التي هي في الحقيقة تساوي `10`. المتغيرات التي يتم تعريفها بالكلمة المفتاحية `let`هي متغيرات block scoped, أي يتم التعامل معها في النطاق الذي تم تعريفها فيه فقط, الدالة المناداة حاليا في هذه الحالة أي immediately-invoked function (IIFE). عندما نقوم بإستخدام العملية `typeof`, فإن المعامل `x` ليس معرف, نحن نحاول الوصول الى `x` خارج النطاق الذي تم تعريفه بها. هذا يعني أن `x` ليست معرفة. المتغيرات التي لم يتم وضع قيمة لها أو لم يتم تعريفها هي من النوع `"undefined"`. `console.log(typeof x)` تقوم بإرجاع `"undefined"`. -ولكن, نحن قمنا بإنشاء و تعريف global variable `y` عندما قمنا بضبط قيمة `y` لتساوي `10`. هذه القيمة يمكن الوصول إليها من أي مكان في البرنامج. `y` هي معرفة, و لديها قيمة من النوع `"number"`. `console.log(typeof y)` تقوم بإرجاع `"number"`. +ولكن, نحن قمنا بإنشاء و تعريف global variable `y` عندما قمنا بضبط قيمة `y` لتساوي `10`. هذه القيمة يمكن الوصول إليها من أي مكان في البرنامج. `y` هي معرفة, و لديها قيمة من النوع `"number"`. `console.log(typeof y)` تقوم بإرجاع `"number"`. +

@@ -1756,7 +1799,7 @@ class Dog { } } -Dog.prototype.bark = function() { +Dog.prototype.bark = function () { console.log(`Woof I am ${this.name}`); }; @@ -1779,9 +1822,10 @@ pet.bark();
الجواب هو الخيار الأول: A -بإمكاننا مسح خصائص object معين عن طريق استخدام الكلمة المفتاحية `delete`, أيضا يمكن فعل هذا في ال prototype. بمسح خاصية معينة من الprototype, فهي سيتم مسحها وبالتالي لن تكون موجودة في سلسلة الprototype. في هذه الحالة فإن الدالة `bark` لن تكون موجودة بعد الآن في الprototype بعد `delete Dog.prototype.bark`, ولكن بالرغم من هذا فنحن نحاول الوصول إليها. +بإمكاننا مسح خصائص object معين عن طريق استخدام الكلمة المفتاحية `delete`, أيضا يمكن فعل هذا في ال prototype. بمسح خاصية معينة من الprototype, فهي سيتم مسحها وبالتالي لن تكون موجودة في سلسلة الprototype. في هذه الحالة فإن الدالة `bark` لن تكون موجودة بعد الآن في الprototype بعد `delete Dog.prototype.bark`, ولكن بالرغم من هذا فنحن نحاول الوصول إليها. + +عندما نحاول أن ننادي شيئا ما في دالة و هو ليس موجود في هذه الدالة, فإننا سنتحصل على الخطأ `TypeError`, و في هذه الحالة `TypeError: pet.bark is not a function` بما أن `pet.bark` هي `undefined`. -عندما نحاول أن ننادي شيئا ما في دالة و هو ليس موجود في هذه الدالة, فإننا سنتحصل على الخطأ `TypeError`, و في هذه الحالة `TypeError: pet.bark is not a function` بما أن `pet.bark` هي `undefined`.

@@ -1806,9 +1850,10 @@ console.log(set);
الجواب هو الخيار الرابع: D -ال object `Set` هو مجموعة من القيم الفريدة, أي القيمة بإمكانها أن تتواجد مرة واحدة فقط في المجموعة. +ال object `Set` هو مجموعة من القيم الفريدة, أي القيمة بإمكانها أن تتواجد مرة واحدة فقط في المجموعة. + +نقوم بتمرير التكراري أي نعني الiterable `[1, 1, 2, 3, 4]` بوجود قيمة مكررة ألا وهي `1` . بما أننا لا يمكن أن نضع قيمة واحدة مرتين في مجموعة, فإن واحدة من القيم المكررة سيتم إزالتها, و سيكون الناتج: `{1, 2, 3, 4}`. -نقوم بتمرير التكراري أي نعني الiterable `[1, 1, 2, 3, 4]` بوجود قيمة مكررة ألا وهي `1` . بما أننا لا يمكن أن نضع قيمة واحدة مرتين في مجموعة, فإن واحدة من القيم المكررة سيتم إزالتها, و سيكون الناتج: `{1, 2, 3, 4}`.

@@ -1844,7 +1889,8 @@ console.log(myCounter); هنا يوجد لدينا module مستورد وهو قابل للقراءة فقط, ليس بإمكانك تعديل او تحديث الmodule المستورد, أي imported module. فقط الmodule الذي قام بتصديره هو القادر على تغيير قيمته. -عندما نحاول أن نزيد قيمة المتغير `myCounter`, سنتحصل على الخطأ `myCounter` هو قابل للقراءة فقط و ليس من الممكن تعديله. +عندما نحاول أن نزيد قيمة المتغير `myCounter`, سنتحصل على الخطأ `myCounter` هو قابل للقراءة فقط و ليس من الممكن تعديله. +

@@ -1871,9 +1917,10 @@ console.log(delete age);
الجواب هو الخيار الأول: A -العامل `delete` تقوم بإرجاع قيمة boolen و هي `true` عندما تتم عملية المسح بنجاح, خلاف ذلك ستقوم بإرجاع `false`, ولكن المتغيرات المعرفة بالكلمات المفتاحية `var`, `const` أو `let` ليس بالإمكان مسحها بإستخدام العامل `delete`. +العامل `delete` تقوم بإرجاع قيمة boolen و هي `true` عندما تتم عملية المسح بنجاح, خلاف ذلك ستقوم بإرجاع `false`, ولكن المتغيرات المعرفة بالكلمات المفتاحية `var`, `const` أو `let` ليس بالإمكان مسحها بإستخدام العامل `delete`. + +المتغير `name` تم تعريفه باستخدام الكلمة المفتاحية `const`, لهذا فإن عملية مسحه لم تتم بنجاح, وتم إرجاع القيمة `false`, عندما نقوم بضبط المتغير `age` ليساوي القيمة `21` فإننا فعليا نقوم بإضافة خاصية تسمى `age` للglobal object. بإمكانك أن تمسح خصائص من الobjects بنجاح بإستخدام هذه الطريقة , أيضا الglobal objects, لذا فإن `delete age` تقوم بإرجاع `true`. -المتغير `name` تم تعريفه باستخدام الكلمة المفتاحية `const`, لهذا فإن عملية مسحه لم تتم بنجاح, وتم إرجاع القيمة `false`, عندما نقوم بضبط المتغير `age` ليساوي القيمة `21` فإننا فعليا نقوم بإضافة خاصية تسمى `age` للglobal object. بإمكانك أن تمسح خصائص من الobjects بنجاح بإستخدام هذه الطريقة , أيضا الglobal objects, لذا فإن `delete age` تقوم بإرجاع `true`.

@@ -1898,7 +1945,8 @@ console.log(y);
الجواب هو الخيار الثالث: C -بإمكاننا إستخراج أو استخلاص القيم من arrays أو من objects عن طريق إستخدام الdestructing, على سبيل المثال: +بإمكاننا إستخراج أو استخلاص القيم من arrays أو من objects عن طريق إستخدام الdestructing, على سبيل المثال: +
```javascript @@ -1908,7 +1956,8 @@ console.log(y);
-قيمة `a` الآن تساوي `1`, و قيمة `b` الآن تساوي `2`. ماقمنا بفعله حقاً في هذا السؤال هو: +قيمة `a` الآن تساوي `1`, و قيمة `b` الآن تساوي `2`. ماقمنا بفعله حقاً في هذا السؤال هو: +
```javascript @@ -1918,7 +1967,8 @@ console.log(y);
-هذا يعني أن قيمة `y` هي مساوية للقيمة الأولى في الarray, والتي هي عبارة عن نوع رقم يساوي `1`, عندما نقوم بطباعة `y` عن طريق الlog, فإن القيمة `1` هي التي يتم إرجاعها. +هذا يعني أن قيمة `y` هي مساوية للقيمة الأولى في الarray, والتي هي عبارة عن نوع رقم يساوي `1`, عندما نقوم بطباعة `y` عن طريق الlog, فإن القيمة `1` هي التي يتم إرجاعها. +

@@ -1944,7 +1994,8 @@ console.log(admin);
الجواب هو الخيار الثاني: B -من الممكن دمج الobjects بإستخدام العامل spread `...`. هي تمكنك من إنشاء نسخ من أزواج ال key/value أي أزواج المفاتيح و القيم التي تنتمي الى object معين, و إضافتهم الى object آخر. في هذه الحالة, نحن نقوم بعمل نسخ من الobject `user`, و من ثم إضافتهم الى ال obejct `admin`. ال object `admin` الآن يتضمن نسخ عبارة عن أزواج مفاتيح و قيم, و هذا ما سبب في إعطاء النتيجة `{ admin: true, name: "Lydia", age: 21 }`. +من الممكن دمج الobjects بإستخدام العامل spread `...`. هي تمكنك من إنشاء نسخ من أزواج ال key/value أي أزواج المفاتيح و القيم التي تنتمي الى object معين, و إضافتهم الى object آخر. في هذه الحالة, نحن نقوم بعمل نسخ من الobject `user`, و من ثم إضافتهم الى ال obejct `admin`. ال object `admin` الآن يتضمن نسخ عبارة عن أزواج مفاتيح و قيم, و هذا ما سبب في إعطاء النتيجة `{ admin: true, name: "Lydia", age: 21 }`. +

@@ -1972,9 +2023,10 @@ console.log(Object.keys(person));
الجواب هو الخيار الثاني: B -مع إستخدام `defineProperty` method, بإمكاننا إضافة خصائص جديدة لobject معين,أو تعديل خصائصه الحالية,. عندما نقوم بإضافة خاصية لobject بإستخدام `defineProperty` method, ف هي بطبيعة الحال ليست enumerable. ال `Object.keys` method تقوم بإرجاع جميع أسامي الخصائص من object معين و التي هي جميعها enumerable, في هذه الحالة `"name"` فقط. +مع إستخدام `defineProperty` method, بإمكاننا إضافة خصائص جديدة لobject معين,أو تعديل خصائصه الحالية,. عندما نقوم بإضافة خاصية لobject بإستخدام `defineProperty` method, ف هي بطبيعة الحال ليست enumerable. ال `Object.keys` method تقوم بإرجاع جميع أسامي الخصائص من object معين و التي هي جميعها enumerable, في هذه الحالة `"name"` فقط. + +الخصائص التي تم إضافتها بإستخدام `defineProperty` method هي بطبيعة الحال غير قابلة للتغيير أو التعديل. بإمكانك عمل override بإستخدام الخصائص `writable`, `configurable` و `enumerable`. بهذه الطريقة, ال `defineProperty` method ستعطيك تحكم أكثر بكثير على الخصائص التي قمت بإضافتها الى object معين. -الخصائص التي تم إضافتها بإستخدام `defineProperty` method هي بطبيعة الحال غير قابلة للتغيير أو التعديل. بإمكانك عمل override بإستخدام الخصائص `writable`, `configurable` و `enumerable`. بهذه الطريقة, ال `defineProperty` method ستعطيك تحكم أكثر بكثير على الخصائص التي قمت بإضافتها الى object معين.

@@ -1987,7 +2039,7 @@ console.log(Object.keys(person)); const settings = { username: "lydiahallie", level: 19, - health: 90 + health: 90, }; const data = JSON.stringify(settings, ["level", "health"]); @@ -2004,11 +2056,12 @@ console.log(data);
الجواب هو الخيار الأول : A -ال argument الثاني من `JSON.stringify` هو replacer أي حالٍ محل شيء آخر, الreplacer إما أن يكون دالة أو يكون array, و سيمكنك من التحكم في كيفية و ماهية امكانية عمل stringified للقيم, أي تحويلها الى string. +ال argument الثاني من `JSON.stringify` هو replacer أي حالٍ محل شيء آخر, الreplacer إما أن يكون دالة أو يكون array, و سيمكنك من التحكم في كيفية و ماهية امكانية عمل stringified للقيم, أي تحويلها الى string. -إذا كان الreplacer هو عبارة عن array, فإن الخصائص التي أساميها مضمنة في الarray هي فقط التي يمكن إضافتها الى ال JSON string. في هذه الحالة, الخصائص التي تحمل الأسامي `"level"` و `"health"` فقط هي المضمنة, `"username"` غير مضمنة. `data` الآن تساوي `"{"level":19, "health":90}"`. +إذا كان الreplacer هو عبارة عن array, فإن الخصائص التي أساميها مضمنة في الarray هي فقط التي يمكن إضافتها الى ال JSON string. في هذه الحالة, الخصائص التي تحمل الأسامي `"level"` و `"health"` فقط هي المضمنة, `"username"` غير مضمنة. `data` الآن تساوي `"{"level":19, "health":90}"`. + +إذا كان الreplacer عبارة عن دالة, فإن هذه الدالة يتم مناداتها عند أي خاصية في الobject أنت تقوم بعمل stringifying لها.القيمة المرجعة من هذه الدالة ستكون قيمة الخاصية عندما تم إضافتها ل JSON string. إذا كانت القيمة `undefined`, فإن هذه الخاصية سيتم إستبعادها من الJSON string. -إذا كان الreplacer عبارة عن دالة, فإن هذه الدالة يتم مناداتها عند أي خاصية في الobject أنت تقوم بعمل stringifying لها.القيمة المرجعة من هذه الدالة ستكون قيمة الخاصية عندما تم إضافتها ل JSON string. إذا كانت القيمة `undefined`, فإن هذه الخاصية سيتم إستبعادها من الJSON string.

@@ -2021,7 +2074,7 @@ console.log(data); let num = 10; const increaseNumber = () => num++; -const increasePassedNumber = number => number++; +const increasePassedNumber = (number) => number++; const num1 = increaseNumber(); const num2 = increasePassedNumber(num1); @@ -2040,9 +2093,10 @@ console.log(num2);
الجواب هو الخيار الأول : A -العامل الأحادي `++` يقوم أولا بإرجاع قيمة المعامل, ثم يقوم بزيادة قيمة هذا المعامل. قيمة `num1` تساوي `10`, و بما أن دالة `increaseNumber` أولا تقوم بإرجاع قيمة `num` و التي هي تساوي `10`, و تقوم بزيادة قيمة `num` لاحقاً فقط. +العامل الأحادي `++` يقوم أولا بإرجاع قيمة المعامل, ثم يقوم بزيادة قيمة هذا المعامل. قيمة `num1` تساوي `10`, و بما أن دالة `increaseNumber` أولا تقوم بإرجاع قيمة `num` و التي هي تساوي `10`, و تقوم بزيادة قيمة `num` لاحقاً فقط. + +`num2` تساوي`10`, وبما أننا نقوم بتمرير `num1` ل `increasePassedNumber`. فإن `number` تساوي `10` والتي هي قيمة`num1`. مجدداً, العامل الأحادي `++`, أولاً يقوم بإرجاع قيمة المعامل, و من ثم زيادة قيمة المعامل. قيمة `number` تساوي`10`, إذاً `num2` تساوي `10`. -`num2` تساوي`10`, وبما أننا نقوم بتمرير `num1` ل `increasePassedNumber`. فإن `number` تساوي `10` والتي هي قيمة`num1`. مجدداً, العامل الأحادي `++`, أولاً يقوم بإرجاع قيمة المعامل, و من ثم زيادة قيمة المعامل. قيمة `number` تساوي`10`, إذاً `num2` تساوي `10`.

diff --git a/bs-BS/README-bs_BS.md b/bs-BS/README-bs_BS.md index 65ee11f7..2ff41568 100644 --- a/bs-BS/README-bs_BS.md +++ b/bs-BS/README-bs_BS.md @@ -1,8 +1,9 @@ # Popis (naprednih) JavaScript pitanja + ======================================= Svakodnevno postavljam JavaScript pitanja s višestrukim izborom na moj -[Instagram](https://www.instagram.com/theavocoder), koja također objavljujem +[Instagram](https://www.instagram.com/theavocoder), koja također objavljujem ovdje! Od osnovnog do naprednog: testirajte koliko dobro znate JavaScript, osvježite svoj @@ -25,6 +26,7 @@ kliknite na njih da biste ih proširili. Sretno :heart: - [🇳🇱 Nederlands](../nl-NL/README.md) - [🇵🇱 Polski](../pl-PL/README.md) - [🇧🇷 Português Brasil](../pt-BR/README_pt_BR.md) +- [🇷o Română](../ro-RO/README.ro.md) - [🇷🇺 Русский](../ru-RU/README.md) - [🇽🇰 Shqip](../sq-KS/README_sq_KS.md) - [🇹🇭 ไทย](../th-TH/README-th_TH.md) @@ -34,7 +36,7 @@ kliknite na njih da biste ih proširili. Sretno :heart: - [🇨🇳 简体中文](../zh-CN/README-zh_CN.md) - [🇹🇼 繁體中文](../zh-TW/README_zh-TW.md) -* * * * * +--- ###### 1. Što je izlaz? @@ -75,7 +77,7 @@ JavaScript izbacuje `ReferenceError`.

-* * * * * +--- ###### 2. Što je izlaz? @@ -99,7 +101,7 @@ for (let i = 0; i < 3; i++) { #### Odgovor: C Zbog reda događaja u JavaScriptu, povratni poziv `setTimeout` -function se zove * nakon što je izvršena petlja. Od +function se zove \* nakon što je izvršena petlja. Od varijabla `i` u prvoj petlji je deklarirana pomoću ključne riječi` var`, ta je vrijednost bila globalna. Tijekom petlje povećavamo vrijednost `i` svaki put '1', koristeći unarni operator `++`. Do vremena @@ -114,7 +116,7 @@ block-scoped (blok je sve između `{}`). Tijekom svake iteracije,

-* * * * * +--- ###### 3. Što je izlaz? @@ -124,7 +126,7 @@ const shape = { diameter() { return this.radius * 2; }, - perimeter: () => 2 * Math.PI * this.radius + perimeter: () => 2 * Math.PI * this.radius, }; shape.diameter(); @@ -154,7 +156,7 @@ Na tom objektu nema vrijednosti `radius` koja vraća` undefined`.

-* * * * * +--- ###### 4. Što je izlaz? @@ -181,18 +183,18 @@ Niz '' Lydia '' je istinita vrijednost. Ono što zapravo tražimo jest

-* * * * * +--- ###### 5. Koja je istina? ```javascript const bird = { - size: "small" + size: "small", }; const mouse = { name: "Mickey", - small: true + small: true, }; ``` @@ -207,7 +209,7 @@ const mouse = { #### Odgovor: A U JavaScriptu su svi key-evi objekta stringovi (osim ako to nije simbol). Čak -iako ih možda ne * upisujemo kao * nizove, oni se uvijek pretvaraju +iako ih možda ne _ upisujemo kao _ nizove, oni se uvijek pretvaraju u String ispod "haube". JavaScript tumači (ili odlaže) izjave. Kada koristimo zagradu @@ -228,8 +230,7 @@ To nije valjano, a bit će u pitanju pogreška slična onoj

-* * * * * - +--- ###### 6. Što je izlaz? @@ -253,7 +254,7 @@ console.log(d.greeting); #### Odgovor: A -U JavaScriptu, svi objekti međusobno djeluju *referencom* kada ih postavljaju +U JavaScriptu, svi objekti međusobno djeluju _referencom_ kada ih postavljaju jednaki. Prvo, varijabla `c` sadrži vrijednost objekta. Kasnije dodijelimo `d` @@ -266,7 +267,7 @@ Kada promijenite jedan objekt, mijenjate ih sve.

-* * * * * +--- ###### 7. Što je izlaz? @@ -280,10 +281,10 @@ console.log(a === b); console.log(b === c); ``` -- A: `true`` false` `true` -- B: `false`` false` `true` -- C: `true`` false` `false` -- D: `false`` true` `true` +- A: ` true`` false ` `true` +- B: ` false`` false ` `true` +- C: ` true`` false ` `false` +- D: ` false`` true ` `true`
Odgovor

@@ -295,16 +296,16 @@ kao broj, to zapravo nije broj: ima gomilu ekstra dodataka pa je zbog toga objekt. Kada koristimo `==` operator, on samo provjerava ima li isti -*vrijednost*. Obje imaju vrijednost `3`, pa se vraća 'true'. +_vrijednost_. Obje imaju vrijednost `3`, pa se vraća 'true'. -Međutim, kada koristimo `===` operator, obje vrijednosti * i * trebaju biti +Međutim, kada koristimo `===` operator, obje vrijednosti _ i _ trebaju biti iste. To nije: `new Number ()` nije broj, to je ** objekt **. Oba vraćaju "false"

-* * * * * +--- ###### 8. Što je izlaz? @@ -335,7 +336,7 @@ freddie.colorChange("orange"); #### Odgovor: D function `colorChange` je statična. Namijenjene su statičkim metodama -žive samo na konstruktoru u kojem su stvoreni i ne mogu biti proslijeđeni +žive samo na konstruktoru u kojem su stvoreni i ne mogu biti proslijeđeni bilo kojem childu. Budući da je `freddie` child, function je nije proslijeđena, i nije dostupan na `freddie` instanci: a Izbačen je `TypeError`. @@ -343,7 +344,7 @@ Izbačen je `TypeError`.

-* * * * * +--- ###### 9. Što je izlaz? @@ -351,7 +352,6 @@ Izbačen je `TypeError`. let greeting; greetign = {}; // Typo! console.log(greetign); - ``` - A: `{}` @@ -374,7 +374,7 @@ da ste deklarirali varijablu prije nego je postavite na bilo što.

-* * * * * +--- ###### 10. Što se događa kada učinimo ovo? @@ -406,7 +406,7 @@ Ova nekretnina je nepovratna.

-* * * * * +--- ###### 11. Kakav je rezultat? @@ -417,7 +417,7 @@ function Person(firstName, lastName) { } const member = new Person("Lydia", "Hallie"); -Person.getFullName = function() { +Person.getFullName = function () { return `${this.firstName} ${this.lastName}`; }; @@ -427,7 +427,7 @@ console.log(member.getFullName()); - A: `TypeError` - B: `SyntaxError` - C: "Lydia Hallie" -- D: `undefined`` undefined` +- D: ` undefined`` undefined `
Odgovor

@@ -454,7 +454,7 @@ scopa za svaku instancu. Umjesto toga, ako ga samo dodamo prototipu, mi

-* * * * * +--- ###### 12. Što je izlaz? @@ -473,10 +473,10 @@ console.log(sarah); - A: `Person {ime:" Lydia ", prezime:" Hallie "} i` undefined` - B: `Person {ime:" Lydia ", prezime:" Hallie "} i - `Person {ime:" Sarah ", prezime:" Smith "}` + `Person {ime:" Sarah ", prezime:" Smith "}` - C: `Person {ime:" Lydia ", prezime:" Hallie "}` i `{}` - D: `Person {ime:" Lydia ", prezime:" Hallie "} i - `ReferenceError` + `ReferenceError`
Odgovor

@@ -495,7 +495,7 @@ sam je ostavljen 'undefined'.

-* * * * * +--- ###### 13. Koje su tri faze propagiranja događaja? @@ -504,7 +504,6 @@ sam je ostavljen 'undefined'. - C: Target > Bubbling > Capturing - D: Capturing > Target > Bubbling -
Odgovor

@@ -519,11 +518,11 @@ i ** bubbling **.

-* * * * * +--- ###### 14. Svi objekti imaju prototipove. -- Istinito +- Istinito - B: lažno
Odgovor @@ -541,7 +540,7 @@ nalazi ga tamo, što ga čini dostupnim.

-* * * * * +--- ###### 15. Što je izlaz? @@ -565,20 +564,20 @@ sum(1, "2"); JavaScript je ** dinamički upisani jezik **: ne navodimo što vrste su određene varijable. Vrijednosti se mogu automatski pretvoriti u -drugi tip bez vašeg znanja, koji se zove * implicitni tip -prisila *. ** Prisila ** pretvara iz jednog tipa u drugi. +drugi tip bez vašeg znanja, koji se zove _ implicitni tip +prisila _. ** Prisila ** pretvara iz jednog tipa u drugi. U ovom primjeru JavaScript pretvara broj `1` u niz, u kako bi function imala smisla i vratila vrijednost. Tijekom dodavanje numeričkog tipa (`1`) i tipa niza (` '2'`), broja se tretira kao niz. Možemo slično spojiti -"" Zdravo "+" Svijet "`, tako da se ovdje događa `````````````````` -vraća `" 12 "`. +"" Zdravo "+" Svijet "` , tako da se ovdje događa `````````````````` +vraća `" 12 "`.

-* * * * * +--- ###### 16. Što je izlaz? @@ -589,10 +588,10 @@ console.log(++number); console.log(number); ``` -- A: `1`` 1` `2` -- B: `1`` 2` `2` -- C: `0`` 2` `2` -- D: `0`` 1` `2` +- A: ` 1`` 1 ` `2` +- B: ` 1`` 2 ` `2` +- C: ` 0`` 2 ` `2` +- D: ` 0`` 1 ` `2`
Odgovor

@@ -614,7 +613,7 @@ Ovo vraća `0 2 2`.

-* * * * * +--- ###### 17. Što je izlaz? @@ -647,7 +646,7 @@ vrijednosti prošlih izraza!

-* * * * * +--- ###### 18. Što je izlaz? @@ -674,8 +673,8 @@ checkAge({ age: 18 }); #### Odgovor: C -Prilikom ispitivanja jednakosti, primitivi se uspoređuju prema njihovoj * vrijednosti *, dok -objekti se uspoređuju prema njihovoj * referenci *. JavaScript provjerava ako +Prilikom ispitivanja jednakosti, primitivi se uspoređuju prema njihovoj _ vrijednosti _, dok +objekti se uspoređuju prema njihovoj _ referenci _. JavaScript provjerava ako objekti imaju referencu na isto mjesto u memoriji. Dva predmeta koje uspoređujemo nemaju: objekt mi @@ -688,12 +687,11 @@ Zato i `{age: 18} === {age: 18}` i

-* * * * * +--- ###### 19. Što je izlaz? ```javascript - function getAge(...args) { console.log(typeof args); } @@ -717,7 +715,7 @@ array je objekt, pa `typeof args` vraća` `objekt '`

-* * * * * +--- ###### 20. Što je izlaz? @@ -741,16 +739,16 @@ getAge(); #### Odgovor: C -Sa `` use strict '', možete se uvjeriti da nije slučajno +Sa `use strict '', možete se uvjeriti da nije slučajno deklarisana globalna varijabla. Nikada nismo objavili varijablu "age" i -budući da koristimo `` use strict '', ona će načiniti referentnu pogrešku. Ako mi +budući da koristimo` use strict '', ona će načiniti referentnu pogrešku. Ako mi nije koristio "" strict ", to bi išlo od vlasništva `age` bi se dodao u globalni objekt.

-* * * * * +--- ###### 21. Što je vrijednost `suma '? @@ -775,15 +773,16 @@ kao u ovom slučaju, on ocjenjuje izraz. Izraz je

-* * * * * +--- -###### 22. Koliko dugo je cool \ _secret dostupan? +###### 22. Koliko dugo je cool \ \_secret dostupan? ```javascript sessionStorage.setItem("cool_secret", 123); ``` O: Podaci se zauvijek ne gube. + - B: Kada korisnik zatvori karticu. - C: Kada korisnik zatvori cijeli preglednik, ne samo karticu. - D: Kada korisnik isključi svoje računalo. @@ -793,7 +792,7 @@ O: Podaci se zauvijek ne gube. #### Odgovor: B -Podaci spremljeni u `sessionStorage` se uklanjaju nakon zatvaranja * tab *. +Podaci spremljeni u `sessionStorage` se uklanjaju nakon zatvaranja _ tab _. Ako ste koristili `localStorage`, podaci bi bili tamo zauvijek, osim ako na primjer, `localStorage.clear ()` je pozvan. @@ -801,7 +800,7 @@ na primjer, `localStorage.clear ()` je pozvan.

-* * * * * +--- ###### 23. Što je izlaz? @@ -830,7 +829,7 @@ To ne možete učiniti s `let` ili` const` jer su blokirani.

-* * * * * +--- ###### 24. Što je izlaz? @@ -844,10 +843,10 @@ set.has("1"); set.has(1); ``` -- A: `false`` true` `false`` true` -- B: `false`` true` `true`` true` -- C: `true`` true` `false`` true` -- D: `true`` true` `true`` true` +- A: ` false`` true ` ` false`` true ` +- B: ` false`` true ` ` true`` true ` +- C: ` true`` true ` ` false`` true ` +- D: ` true`` true ` ` true`` true `
Odgovor

@@ -865,7 +864,7 @@ To ne radi tako za skup. U našem setu ne postoji "1":

-* * * * * +--- ###### 25. Što je izlaz? @@ -890,11 +889,11 @@ i dalje će biti na prvom mjestu, ali s posljednjom navedenom vrijednošću.

-* * * * * +--- ###### 26. Globalni kontekst izvođenja JavaScripta za vas stvara dvije stvari: globalni objekt i "ovu" ključnu riječ. -- Istina +- Istina - B: lažno - C: to ovisi @@ -909,7 +908,7 @@ dostupno svugdje u vašem kodu.

-* * * * * +--- ###### 27. Što je izlaz? @@ -918,13 +917,12 @@ for (let i = 1; i < 5; i++) { if (i === 3) continue; console.log(i); } - ``` -- A: `1`` 2` -- B: `1`` 2` `3` -- C: `1`` 2` `4` -- D: `1`` 3` `4` +- A: ` 1`` 2 ` +- B: ` 1`` 2 ` `3` +- C: ` 1`` 2 ` `4` +- D: ` 1`` 3 ` `4`
Odgovor

@@ -937,7 +935,7 @@ vraća "true".

-* * * * * +--- ###### 28. Što je izlaz? @@ -948,10 +946,10 @@ String.prototype.giveLydiaPizza = () => { const name = "Lydia"; -console.log(name.giveLydiaPizza()) +console.log(name.giveLydiaPizza()); ``` -- A: `` Već daj Lizijinu pizzu! `` +- A: `Već daj Lizijinu pizzu!` - B: `TypeError: nije function` - C: `SyntaxError` - D: `undefined` @@ -970,7 +968,7 @@ način!

-* * * * * +--- ###### 29. Što je izlaz? @@ -1009,7 +1007,7 @@ da na `456`, tako da se vraća` 456`.

-* * * * * +--- ###### 30. Što je izlaz? @@ -1023,10 +1021,10 @@ foo(); baz(); ``` -- A: `Prvi`` Drugi` `Treći` -- B: `Prvi`` Treći` `Drugi` -- C: `Drugi`` Prvi` `Treći` -- D: `Drugi`` Treći` `Prvi` +- A: ` Prvi`` Drugi ` `Treći` +- B: ` Prvi`` Treći ` `Drugi` +- C: ` Drugi`` Prvi ` `Treći` +- D: ` Drugi`` Treći ` `Prvi`
Odgovor

@@ -1040,7 +1038,7 @@ To je zato što u preglednicima nemamo samo runtime engine, mi također imaju nešto što se zove "WebAPI". "WebAPI" nam daje `setTimeout` function za početak, i na primjer DOM. -Nakon što je * callback * preusmjeren na WebAPI, function `setTimeout` +Nakon što je _ callback _ preusmjeren na WebAPI, function `setTimeout` sam (ali ne i povratni poziv!) iskače iz stog. @@ -1056,11 +1054,11 @@ prijavljeni. WebAPI ne može jednostavno dodati stvari u stog kad god je spreman. Umjesto toga, on povlači funkciju povratnog poziva u nešto što se zove -*red*. +_red_. -Ovo je mjesto gdje petlja događaja počinje raditi. ** ** krug događaja ** gleda +Ovo je mjesto gdje petlja događaja počinje raditi. \*\* ** krug događaja ** gleda red i red za zadatke. Ako je stog prazan, uzima prvi stvar u redu i gura je u stog. @@ -1072,7 +1070,7 @@ stog.

-* * * * * +--- ###### 31. Što je event.target kada kliknete na gumb? @@ -1104,7 +1102,7 @@ događaj. Možete zaustaviti mjehuriće 'event.stopPropagation'

-* * * * * +--- ###### 32. Kada kliknete na paragraf, što je zapisani izlaz? @@ -1116,8 +1114,8 @@ događaj. Možete zaustaviti mjehuriće 'event.stopPropagation'
``` -- A: `p`` div` -- B: `div`` p` +- A: ` p`` div ` +- B: ` div`` p ` - C: p - D: "div" @@ -1135,7 +1133,7 @@ van.

-* * * * * +--- ###### 33. Što je izlaz? @@ -1150,10 +1148,10 @@ sayHi.call(person, 21); sayHi.bind(person, 21); ``` -- A: `undefined is 21`` Lydia je 21` +- A: ` undefined is 21`` Lydia je 21 ` - B: function funkcije -- C: `Lydia je 21`` Lydia je 21` -- D: `Lydia je 21`` function` +- C: ` Lydia je 21`` Lydia je 21 ` +- D: ` Lydia je 21`` function `
Odgovor

@@ -1161,15 +1159,15 @@ sayHi.bind(person, 21); #### Odgovor: D S oba, možemo proslijediti objekt kojem želimo ključnu riječ "this" -odnosi se na. Međutim, `.call` se također * izvršava odmah *! +odnosi se na. Međutim, `.call` se također _ izvršava odmah _! -`.bind.` vraća * copy * funkcije, ali s vezanim kontekstom! To +`.bind.` vraća _ copy _ funkcije, ali s vezanim kontekstom! To se ne izvršava odmah.

-* * * * * +--- ###### 34. Što je izlaz? @@ -1196,13 +1194,13 @@ pozvana function (IIFE). Ova function vratila je `0`, što je tip ` "Broj"`. FYI: postoji samo 7 ugrađenih tipova: `null`,` undefined`, `boolean`, -"broj", "niz", "objekt" i "simbol". `` function '' nije tip, -budući da su funkcije objekti, to je tipa `` objekta '`. +"broj", "niz", "objekt" i "simbol". `function '' nije tip, +budući da su funkcije objekti, to je tipa` objekta '`.

-* * * * * +--- ###### 35. Koja od ovih vrijednosti su neistinite? @@ -1216,8 +1214,8 @@ undefined; ``` - A: `0`,` ```,` undefined` -- B: `0`,` new Number (0) `,` '' `,` new Boolean (false) `,` undefined ' -- C: `0`,` '' `,` new Boolean (false) `,` undefined` +- B: `0`,`new Number (0)`,`''`,`new Boolean (false)`,` undefined ' +- C: `0`,`''`,`new Boolean (false)`,` undefined` - D: Svi su oni lažni
Odgovor @@ -1239,13 +1237,12 @@ Konstruktori function, kao što su 'new Number' i 'new Boolean' su istiniti.

-* * * * * +--- ###### 36. Što je izlaz? ```javascript console.log(typeof typeof 1); - ``` - A: `" broj " @@ -1263,7 +1260,7 @@ console.log(typeof typeof 1);

-* * * * * +--- ###### 37. Što je izlaz? @@ -1295,7 +1292,7 @@ itd)

-* * * * * +--- ###### 38. Što je izlaz? @@ -1313,10 +1310,10 @@ itd) })(); ``` -- A: `1`` undefined `` 2` -- B: `undefined`` undefined` `undefined` -- C: `1`` 1` `2` -- D: `1`` undefined` `undefined` +- A: ` 1`` undefined `` 2 ` +- B: ` undefined`` undefined ` `undefined` +- C: ` 1`` 1 ` `2` +- D: ` 1`` undefined ` `undefined`
Odgovor

@@ -1331,13 +1328,13 @@ varijable `y '. Sada, zapisujemo blok-scoped varijablu `x`, koja je jednako "1". Izvan 'catch' bloka, `x 'je i dalje` undefined`, a `y` je` 2`. -Kada želimo `console.log (x)` izvan `catch` bloka, to -vraća `undefined` i` y` vraća `2`. +Kada želimo `console.log (x)`izvan`catch`bloka, to +vraća`undefined` i` y`vraća`2`.

-* * * * * +--- ###### 39. Sve u JavaScriptu je ili ... @@ -1358,8 +1355,7 @@ Primitivni tipovi su "boolean", "null", "undefined", "bigint", "number", Ono što razlikuje primitiv od objekta je to što primitivci to ne čine imaju bilo kakva svojstva ili metode; međutim, to ćete primijetiti -`'foo'.toUpperCase ()` vrednuje za' 'FOO'` i ne rezultira a -`TypeError`. To je zato što kada pokušate pristupiti svojstvu ili metodi +`'foo'.toUpperCase ()` vrednuje za' 'FOO'`i ne rezultira a`TypeError`. To je zato što kada pokušate pristupiti svojstvu ili metodi na primitivnom poput stringa, JavaScript će implicitet omotati objekt koristeći jednu od klasa omotača, tj. `String ', a zatim odmah odbacite omotač nakon što se izraz procijeni. Svi primitivci @@ -1368,12 +1364,15 @@ osim "null" i "undefined" pokazuju ovo ponašanje.

-* * * * * +--- ###### 40. Što je izlaz? ```javascript -[[0, 1], [2, 3]].reduce( +[ + [0, 1], + [2, 3], +].reduce( (acc, cur) => { return acc.concat(cur); }, @@ -1393,7 +1392,7 @@ osim "null" i "undefined" pokazuju ovo ponašanje. "[1, 2]" je naša početna vrijednost. To je vrijednost s kojom počinjemo i vrijednost prvog `acc`. Tijekom prvog kruga, "acc" je "[1,2]", -i `cur` je` [0, 1] `. Spojimo ih, što rezultira +i `cur` je`[0, 1]`. Spojimo ih, što rezultira `[1, 2, 0, 1]`. Tada je `[1, 2, 0, 1]` `acc` i` [2, 3] `````. Ulančavamo se @@ -1402,7 +1401,7 @@ i dobiti `[1, 2, 0, 1, 2, 3]`

-* * * * * +--- ###### 41. Što je izlaz? @@ -1412,10 +1411,10 @@ i dobiti `[1, 2, 0, 1, 2, 3]` !!1; ``` -- A: `false`` true` `false` -- B: `false`` false` `true` -- C: `false`` true` `true` -- D: `true`` true` `false` +- A: ` false`` true ` `false` +- B: ` false`` false ` `true` +- C: ` false`` true ` `true` +- D: ` true`` true ` `false`
Odgovor

@@ -1431,7 +1430,7 @@ i dobiti `[1, 2, 0, 1, 2, 3]`

-* * * * * +--- ###### 42. Što se vraća metoda `setInterval`? @@ -1455,7 +1454,7 @@ Vraća jedinstveni ID. Taj se ID može koristiti za brisanje tog intervala

-* * * * * +--- ###### 43. Što se to vraća? diff --git a/de-DE/README.md b/de-DE/README.md index 10145050..a9dbd381 100644 --- a/de-DE/README.md +++ b/de-DE/README.md @@ -10,10 +10,11 @@ Von einfach bis fortgeschritten: teste, wie gut du JavaScript kennst, frische de Kontaktiert mich, wenn ihr möchtet! 😊
Instagram || Twitter || LinkedIn || Blog + -| Benutzt die Fragen und Lösungen in einem Projekt! 😃 Ich würde mich _sehr_ freuen, wenn ihr dieses Repo verlinkt. Ich erstelle die Fragen und antworten (ja, ich bin traurig, lol) und die Community hilft mir unglaublich dabei, das ganze zu pflegen und verbessern! 💪🏼 Danke und habt Spaß! | -|---| +| Benutzt die Fragen und Lösungen in einem Projekt! 😃 Ich würde mich _sehr_ freuen, wenn ihr dieses Repo verlinkt. Ich erstelle die Fragen und antworten (ja, ich bin traurig, lol) und die Community hilft mir unglaublich dabei, das ganze zu pflegen und verbessern! 💪🏼 Danke und habt Spaß! | +| ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | @@ -35,6 +36,7 @@ Kontaktiert mich, wenn ihr möchtet! 😊
- [🇳🇱 Nederlands](../nl-NL/README.md) - [🇵🇱 Polski](../pl-PL/README.md) - [🇧🇷 Português Brasil](../pt-BR/README_pt_BR.md) +- [🇷o Română](../ro-RO/README.ro.md) - [🇷🇺 Русский](../ru-RU/README.md) - [🇽🇰 Shqip](../sq-KS/README_sq_KS.md) - [🇹🇭 ไทย](../th-TH/README-th_TH.md) @@ -53,19 +55,19 @@ Kontaktiert mich, wenn ihr möchtet! 😊
```javascript function sayHi() { - console.log(name); - console.log(age); - var name = "Lydia"; - let age = 21; + console.log(name); + console.log(age); + var name = "Lydia"; + let age = 21; } sayHi(); ``` -- A: `Lydia` und `undefined` -- B: `Lydia` und `ReferenceError` -- C: `ReferenceError` und `21` -- D: `undefined` und `ReferenceError` +- A: `Lydia` und `undefined` +- B: `Lydia` und `ReferenceError` +- C: `ReferenceError` und `21` +- D: `undefined` und `ReferenceError`
Antwort

@@ -85,17 +87,17 @@ Variablen mit dem `let` (oder `const`) Keyword werden ebenfalls gehoisted, aber ```javascript for (var i = 0; i < 3; i++) { - setTimeout(() => console.log(i), 1); + setTimeout(() => console.log(i), 1); } for (let i = 0; i < 3; i++) { - setTimeout(() => console.log(i), 1); + setTimeout(() => console.log(i), 1); } ``` -- A: `0 1 2` und `0 1 2` -- B: `0 1 2` und `3 3 3` -- C: `3 3 3` und `0 1 2` +- A: `0 1 2` und `0 1 2` +- B: `0 1 2` und `3 3 3` +- C: `3 3 3` und `0 1 2`

Antwort

@@ -115,21 +117,21 @@ In der zweiten Schleife wurde die Variable `i` mit dem `let` Keyword definiert: ```javascript const shape = { - radius: 10, - diameter() { - return this.radius * 2; - }, - perimeter: () => 2 * Math.PI * this.radius, + radius: 10, + diameter() { + return this.radius * 2; + }, + perimeter: () => 2 * Math.PI * this.radius, }; shape.diameter(); shape.perimeter(); ``` -- A: `20` und `62.83185307179586` -- B: `20` und `NaN` -- C: `20` und `63` -- D: `NaN` und `63` +- A: `20` und `62.83185307179586` +- B: `20` und `NaN` +- C: `20` und `63` +- D: `NaN` und `63`

Antwort

@@ -154,9 +156,9 @@ Es gibt keinen Wert `radius` in dem Object, daher wird `undefined` zurückgegebe !"Lydia"; ``` -- A: `1` und `false` -- B: `false` und `NaN` -- C: `false` und `false` +- A: `1` und `false` +- B: `false` und `NaN` +- C: `false` und `false`

Antwort

@@ -176,19 +178,19 @@ Der String `'Lydia'` ist truthy. Was wir eigentlich fragen ist: "ist dieser trut ```javascript const bird = { - size: "small", + size: "small", }; const mouse = { - name: "Mickey", - small: true, + name: "Mickey", + small: true, }; ``` -- A: `mouse.bird.size` ist nicht korrekt -- B: `mouse[bird.size]` ist nicht korrekt -- C: `mouse[bird["size"]]` ist nicht korrekt -- D: Keine der Antworten ist korrekt. +- A: `mouse.bird.size` ist nicht korrekt +- B: `mouse[bird.size]` ist nicht korrekt +- C: `mouse[bird["size"]]` ist nicht korrekt +- D: Keine der Antworten ist korrekt.

Antwort

@@ -219,11 +221,11 @@ c.greeting = "Hello"; console.log(d.greeting); ``` -- A: `Hello` -- B: `Hey` -- C: `undefined` -- D: `ReferenceError` -- E: `TypeError` +- A: `Hello` +- B: `Hey` +- C: `undefined` +- D: `ReferenceError` +- E: `TypeError`

Antwort

@@ -255,10 +257,10 @@ console.log(a === b); console.log(b === c); ``` -- A: `true` `false` `true` -- B: `false` `false` `true` -- C: `true` `false` `false` -- D: `false` `true` `true` +- A: `true` `false` `true` +- B: `false` `false` `true` +- C: `true` `false` `false` +- D: `false` `true` `true`

Antwort

@@ -280,24 +282,24 @@ Wenn wir aber `===` nutzen müssen sowohl der Wert _als auch_ der Typ übereinst ```javascript class Chameleon { - static colorChange(newColor) { - this.newColor = newColor; - return this.newColor; - } - - constructor({ newColor = "green" } = {}) { - this.newColor = newColor; - } + static colorChange(newColor) { + this.newColor = newColor; + return this.newColor; + } + + constructor({ newColor = "green" } = {}) { + this.newColor = newColor; + } } const freddie = new Chameleon({ newColor: "purple" }); freddie.colorChange("orange"); ``` -- A: `orange` -- B: `purple` -- C: `green` -- D: `TypeError` +- A: `orange` +- B: `purple` +- C: `green` +- D: `TypeError`

Antwort

@@ -319,9 +321,9 @@ greetign = {}; // Typo! console.log(greetign); ``` -- A: `{}` -- B: `ReferenceError: greetign is not defined` -- C: `undefined` +- A: `{}` +- B: `ReferenceError: greetign is not defined` +- C: `undefined`

Antwort

@@ -341,16 +343,16 @@ Um das zu verhindern, können wir `"use strict"` verwenden. Das stellt sicher, d ```javascript function bark() { - console.log("Woof!"); + console.log("Woof!"); } bark.animal = "dog"; ``` -- A: Nichts, das ist absolut in Ordnung. -- B: `SyntaxError`. Man kann einer Funktion keine Properties in der Form zuweisen. -- C: `undefined` -- D: `ReferenceError` +- A: Nichts, das ist absolut in Ordnung. +- B: `SyntaxError`. Man kann einer Funktion keine Properties in der Form zuweisen. +- C: `undefined` +- D: `ReferenceError`

Antwort

@@ -370,22 +372,22 @@ Eine Funktion ist ein spezieller Typ eines Objekts. Der Code, den wir schreiben ```javascript function Person(firstName, lastName) { - this.firstName = firstName; - this.lastName = lastName; + this.firstName = firstName; + this.lastName = lastName; } const member = new Person("Lydia", "Hallie"); -Person.getFullName = function() { - return `${this.firstName} ${this.lastName}`; +Person.getFullName = function () { + return `${this.firstName} ${this.lastName}`; }; console.log(member.getFullName()); ``` -- A: `TypeError` -- B: `SyntaxError` -- C: `Lydia Hallie` -- D: `undefined` `undefined` +- A: `TypeError` +- B: `SyntaxError` +- C: `Lydia Hallie` +- D: `undefined` `undefined`

Antwort

@@ -395,8 +397,8 @@ console.log(member.getFullName()); Man kann keine Properties einem Constructor zuweisen, wie es bei normalen Objects der Fall ist. Wenn man ein Feature allen Objects zugleich zuweisen möchte, muss man den Prototype verwenden. In diesem Fall also: ```js -Person.prototype.getFullName = function() { - return `${this.firstName} ${this.lastName}`; +Person.prototype.getFullName = function () { + return `${this.firstName} ${this.lastName}`; }; ``` @@ -412,8 +414,8 @@ Stattdessen haben wir sie nur dem Prototype zugewiesen, sodass sie nur an einer ```javascript function Person(firstName, lastName) { - this.firstName = firstName; - this.lastName = lastName; + this.firstName = firstName; + this.lastName = lastName; } const lydia = new Person("Lydia", "Hallie"); @@ -423,10 +425,10 @@ console.log(lydia); console.log(sarah); ``` -- A: `Person {firstName: "Lydia", lastName: "Hallie"}` und `undefined` -- B: `Person {firstName: "Lydia", lastName: "Hallie"}` und `Person {firstName: "Sarah", lastName: "Smith"}` -- C: `Person {firstName: "Lydia", lastName: "Hallie"}` und `{}` -- D:`Person {firstName: "Lydia", lastName: "Hallie"}` und `ReferenceError` +- A: `Person {firstName: "Lydia", lastName: "Hallie"}` und `undefined` +- B: `Person {firstName: "Lydia", lastName: "Hallie"}` und `Person {firstName: "Sarah", lastName: "Smith"}` +- C: `Person {firstName: "Lydia", lastName: "Hallie"}` und `{}` +- D:`Person {firstName: "Lydia", lastName: "Hallie"}` und `ReferenceError`

Antwort

@@ -444,10 +446,10 @@ Wir haben `this.firstName` den Wert `"Sarah"` zugewiesen und `this.lastName` den ###### 13. Was sind die drei Phasen der Event Propagation? -- A: Target > Capturing > Bubbling -- B: Bubbling > Target > Capturing -- C: Target > Bubbling > Capturing -- D: Capturing > Target > Bubbling +- A: Target > Capturing > Bubbling +- B: Bubbling > Target > Capturing +- C: Target > Bubbling > Capturing +- D: Capturing > Target > Bubbling

Antwort

@@ -465,8 +467,8 @@ Während der **capturing** Phase geht das Event durch die Elternelemente bis hin ###### 14. Alle Objekte haben Prototypes. -- A: wahr -- B: falsch +- A: wahr +- B: falsch

Antwort

@@ -484,16 +486,16 @@ Alle Objekte haben Prototypes, außer dem **Basis Objekt**. Das Basis Objekt hat ```javascript function sum(a, b) { - return a + b; + return a + b; } sum(1, "2"); ``` -- A: `NaN` -- B: `TypeError` -- C: `"12"` -- D: `3` +- A: `NaN` +- B: `TypeError` +- C: `"12"` +- D: `3`

Antwort

@@ -518,10 +520,10 @@ console.log(++number); console.log(number); ``` -- A: `1` `1` `2` -- B: `1` `2` `2` -- C: `0` `2` `2` -- D: `0` `1` `2` +- A: `1` `1` `2` +- B: `1` `2` `2` +- C: `0` `2` `2` +- D: `0` `1` `2`

Antwort

@@ -549,9 +551,9 @@ Der Output ist daher `0 2 2`. ```javascript function getPersonInfo(one, two, three) { - console.log(one); - console.log(two); - console.log(three); + console.log(one); + console.log(two); + console.log(three); } const person = "Lydia"; @@ -560,9 +562,9 @@ const age = 21; getPersonInfo`${person} is ${age} years old`; ``` -- A: `"Lydia"` `21` `["", " is ", " years old"]` -- B: `["", " is ", " years old"]` `"Lydia"` `21` -- C: `"Lydia"` `["", " is ", " years old"]` `21` +- A: `"Lydia"` `21` `["", " is ", " years old"]` +- B: `["", " is ", " years old"]` `"Lydia"` `21` +- C: `"Lydia"` `["", " is ", " years old"]` `21`

Antwort

@@ -580,21 +582,21 @@ Wenn man Template Literals verwendet ist das erste Argument immer ein Array der ```javascript function checkAge(data) { - if (data === { age: 18 }) { - console.log("You are an adult!"); - } else if (data == { age: 18 }) { - console.log("You are still an adult."); - } else { - console.log(`Hmm.. You don't have an age I guess`); - } + if (data === { age: 18 }) { + console.log("You are an adult!"); + } else if (data == { age: 18 }) { + console.log("You are still an adult."); + } else { + console.log(`Hmm.. You don't have an age I guess`); + } } checkAge({ age: 18 }); ``` -- A: `You are an adult!` -- B: `You are still an adult.` -- C: `Hmm.. You don't have an age I guess` +- A: `You are an adult!` +- B: `You are still an adult.` +- C: `Hmm.. You don't have an age I guess`

Antwort

@@ -616,16 +618,16 @@ Deshalb werfen sowohl `{ age: 18 } === { age: 18 }` als auch `{ age: 18 } == { a ```javascript function getAge(...args) { - console.log(typeof args); + console.log(typeof args); } getAge(21); ``` -- A: `"number"` -- B: `"array"` -- C: `"object"` -- D: `"NaN"` +- A: `"number"` +- B: `"array"` +- C: `"object"` +- D: `"NaN"`

Antwort

@@ -643,18 +645,18 @@ Der Spread Operator (`...args`) gibt ein Array mit Argumenten zurück. Ein Array ```javascript function getAge() { - "use strict"; - age = 21; - console.log(age); + "use strict"; + age = 21; + console.log(age); } getAge(); ``` -- A: `21` -- B: `undefined` -- C: `ReferenceError` -- D: `TypeError` +- A: `21` +- B: `undefined` +- C: `ReferenceError` +- D: `TypeError`

Antwort

@@ -674,10 +676,10 @@ Durch `"use strict"` kann man sicher stellen, dass man nicht versehentlich globa const sum = eval("10*10+5"); ``` -- A: `105` -- B: `"105"` -- C: `TypeError` -- D: `"10*10+5"` +- A: `105` +- B: `"105"` +- C: `TypeError` +- D: `"10*10+5"`

Antwort

@@ -697,10 +699,10 @@ const sum = eval("10*10+5"); sessionStorage.setItem("cool_secret", 123); ``` -- A: Für immer, der Wert geht nicht verloren. -- B: Wenn der User den Tab schließt. -- C: Wenn der User den Browser schließt, nicht nur den Tab. -- D: Wenn der User den Computer neu startet. +- A: Für immer, der Wert geht nicht verloren. +- B: Wenn der User den Tab schließt. +- C: Wenn der User den Browser schließt, nicht nur den Tab. +- D: Wenn der User den Computer neu startet.

Antwort

@@ -725,10 +727,10 @@ var num = 10; console.log(num); ``` -- A: `8` -- B: `10` -- C: `SyntaxError` -- D: `ReferenceError` +- A: `8` +- B: `10` +- C: `SyntaxError` +- D: `ReferenceError`

Antwort

@@ -756,10 +758,10 @@ set.has("1"); set.has(1); ``` -- A: `false` `true` `false` `true` -- B: `false` `true` `true` `true` -- C: `true` `true` `false` `true` -- D: `true` `true` `true` `true` +- A: `false` `true` `false` `true` +- B: `false` `true` `true` `true` +- C: `true` `true` `false` `true` +- D: `true` `true` `true` `true`

Antwort

@@ -782,10 +784,10 @@ const obj = { a: "one", b: "two", a: "three" }; console.log(obj); ``` -- A: `{ a: "one", b: "two" }` -- B: `{ b: "two", a: "three" }` -- C: `{ a: "three", b: "two" }` -- D: `SyntaxError` +- A: `{ a: "one", b: "two" }` +- B: `{ b: "two", a: "three" }` +- C: `{ a: "three", b: "two" }` +- D: `SyntaxError`

Antwort

@@ -801,9 +803,9 @@ Wenn man zwei Keys mit dem selben Namen hat, wird der erste Key ersetzt. Er wird ###### 26. Der JavaScript Global Execution Context erstellt zwei Dinge: das globale Objekt und das "this" Keyword. -- A: wahr -- B: falsch -- C: kommt darauf an +- A: wahr +- B: falsch +- C: kommt darauf an

Antwort

@@ -821,15 +823,15 @@ Der Base Execution Context entspricht dem Global Execution Context und ist über ```javascript for (let i = 1; i < 5; i++) { - if (i === 3) continue; - console.log(i); + if (i === 3) continue; + console.log(i); } ``` -- A: `1` `2` -- B: `1` `2` `3` -- C: `1` `2` `4` -- D: `1` `3` `4` +- A: `1` `2` +- B: `1` `2` `3` +- C: `1` `2` `4` +- D: `1` `3` `4`

Antwort

@@ -847,18 +849,18 @@ for (let i = 1; i < 5; i++) { ```javascript String.prototype.giveLydiaPizza = () => { - return "Just give Lydia pizza already!"; + return "Just give Lydia pizza already!"; }; const name = "Lydia"; -console.log(name.giveLydiaPizza()) +console.log(name.giveLydiaPizza()); ``` -- A: `"Just give Lydia pizza already!"` -- B: `TypeError: not a function` -- C: `SyntaxError` -- D: `undefined` +- A: `"Just give Lydia pizza already!"` +- B: `TypeError: not a function` +- C: `SyntaxError` +- D: `undefined`

Antwort

@@ -885,10 +887,10 @@ a[c] = 456; console.log(a[b]); ``` -- A: `123` -- B: `456` -- C: `undefined` -- D: `ReferenceError` +- A: `123` +- B: `456` +- C: `undefined` +- D: `ReferenceError`

Antwort

@@ -918,10 +920,10 @@ foo(); baz(); ``` -- A: `First` `Second` `Third` -- B: `First` `Third` `Second` -- C: `Second` `First` `Third` -- D: `Second` `Third` `First` +- A: `First` `Second` `Third` +- B: `First` `Third` `Second` +- C: `Second` `First` `Third` +- D: `Second` `Third` `First`

Antwort

@@ -963,18 +965,16 @@ Das ist, wo die Event Loop ins Spiel kommt. Die **Event Loop** betrachtet den St ```html

-
- -
+
+ +
``` -- A: Äußerer `div` -- B: Innerer `div` -- C: `button` -- D: Ein Array mit allen genesteten Elementen +- A: Äußerer `div` +- B: Innerer `div` +- C: `button` +- D: Ein Array mit allen genesteten Elementen
Antwort

@@ -992,16 +992,14 @@ Das am tiefsten genestete Element, welches das Event auslöst ist das Event Targ ```html

-

- Click here! -

+

Click here!

``` -- A: `p` `div` -- B: `div` `p` -- C: `p` -- D: `div` +- A: `p` `div` +- B: `div` `p` +- C: `p` +- D: `div`
Antwort

@@ -1021,17 +1019,17 @@ Wenn wir auf den Paragraph klicken, sehen wir zwei logs: `p` und `div`. Während const person = { name: "Lydia" }; function sayHi(age) { - console.log(`${this.name} is ${age}`); + console.log(`${this.name} is ${age}`); } sayHi.call(person, 21); sayHi.bind(person, 21); ``` -- A: `undefined is 21` `Lydia is 21` -- B: `function` `function` -- C: `Lydia is 21` `Lydia is 21` -- D: `Lydia is 21` `function` +- A: `undefined is 21` `Lydia is 21` +- B: `function` `function` +- C: `Lydia is 21` `Lydia is 21` +- D: `Lydia is 21` `function`

Antwort

@@ -1051,16 +1049,16 @@ In beiden Fällen können wir das Objekt weiter reichen, auf welches sich das `t ```javascript function sayHi() { - return (() => 0)(); + return (() => 0)(); } typeof sayHi(); ``` -- A: `"object"` -- B: `"number"` -- C: `"function"` -- D: `"undefined"` +- A: `"object"` +- B: `"number"` +- C: `"function"` +- D: `"undefined"`

Antwort

@@ -1087,10 +1085,10 @@ new Boolean(false); undefined; ``` -- A: `0`, `''`, `undefined` -- B: `0`, `new Number(0)`, `''`, `new Boolean(false)`, `undefined` -- C: `0`, `''`, `new Boolean(false)`, `undefined` -- D: Alle sind falsy +- A: `0`, `''`, `undefined` +- B: `0`, `new Number(0)`, `''`, `new Boolean(false)`, `undefined` +- C: `0`, `''`, `new Boolean(false)`, `undefined` +- D: Alle sind falsy

Antwort

@@ -1099,12 +1097,12 @@ undefined; Es gibt nur 6 falsy typen: -- `undefined` -- `null` -- `NaN` -- `0` -- `''` (leerer String) -- `false` +- `undefined` +- `null` +- `NaN` +- `0` +- `''` (leerer String) +- `false` Funktions-Constructor, wie `new Number` und `new Boolean` sind truthy. @@ -1119,10 +1117,10 @@ Funktions-Constructor, wie `new Number` und `new Boolean` sind truthy. console.log(typeof typeof 1); ``` -- A: `"number"` -- B: `"string"` -- C: `"object"` -- D: `"undefined"` +- A: `"number"` +- B: `"string"` +- C: `"object"` +- D: `"undefined"`

Antwort

@@ -1145,10 +1143,10 @@ numbers[10] = 11; console.log(numbers); ``` -- A: `[1, 2, 3, 7 x null, 11]` -- B: `[1, 2, 3, 11]` -- C: `[1, 2, 3, 7 x empty, 11]` -- D: `SyntaxError` +- A: `[1, 2, 3, 7 x null, 11]` +- B: `[1, 2, 3, 11]` +- C: `[1, 2, 3, 7 x empty, 11]` +- D: `SyntaxError`

Antwort

@@ -1170,22 +1168,22 @@ abhängig davon wo das Array ausgeführt wird (die Ausgabe ist unterschiedlich f ```javascript (() => { - let x, y; - try { - throw new Error(); - } catch (x) { - (x = 1), (y = 2); - console.log(x); - } - console.log(x); - console.log(y); + let x, y; + try { + throw new Error(); + } catch (x) { + (x = 1), (y = 2); + console.log(x); + } + console.log(x); + console.log(y); })(); ``` -- A: `1` `undefined` `2` -- B: `undefined` `undefined` `undefined` -- C: `1` `1` `2` -- D: `1` `undefined` `undefined` +- A: `1` `undefined` `2` +- B: `undefined` `undefined` `undefined` +- C: `1` `1` `2` +- D: `1` `undefined` `undefined`

Antwort

@@ -1205,10 +1203,10 @@ Außerhalb des `catch` Blocks ist `x` noch immer `undefined` und `y` ist `2`. We ###### 39. Alles in JavaScript ist entweder ein ... -- A: Primitive oder Object -- B: Function oder Object -- C: Fangfrage: nur Objects! -- D: Number oder Object +- A: Primitive oder Object +- B: Function oder Object +- C: Fangfrage: nur Objects! +- D: Number oder Object

Antwort

@@ -1229,18 +1227,21 @@ Was einen primitiven Typ von einem Objekt unterscheidet ist, dass Primitive kein ###### 40. Was wird ausgegeben? ```javascript -[[0, 1], [2, 3]].reduce( - (acc, cur) => { - return acc.concat(cur); - }, - [1, 2], +[ + [0, 1], + [2, 3], +].reduce( + (acc, cur) => { + return acc.concat(cur); + }, + [1, 2] ); ``` -- A: `[0, 1, 2, 3, 1, 2]` -- B: `[6, 1, 2]` -- C: `[1, 2, 0, 1, 2, 3]` -- D: `[1, 2, 6]` +- A: `[0, 1, 2, 3, 1, 2]` +- B: `[6, 1, 2]` +- C: `[1, 2, 0, 1, 2, 3]` +- D: `[1, 2, 6]`

Antwort

@@ -1264,10 +1265,10 @@ Dann entspricht `acc` gleich `[1, 2, 0, 1]` und `cur` ist gleich `[2, 3]`. Wir v !!1; ``` -- A: `false` `true` `false` -- B: `false` `false` `true` -- C: `false` `true` `true` -- D: `true` `true` `false` +- A: `false` `true` `false` +- B: `false` `false` `true` +- C: `false` `true` `true` +- D: `true` `true` `false`

Antwort

@@ -1291,10 +1292,10 @@ Dann entspricht `acc` gleich `[1, 2, 0, 1]` und `cur` ist gleich `[2, 3]`. Wir v setInterval(() => console.log("Hi"), 1000); ``` -- A: Eine unique id -- B: Die definierte Anzahl von Millisekunden -- C: Die Callback Function -- D: `undefined` +- A: Eine unique id +- B: Die definierte Anzahl von Millisekunden +- C: Die Callback Function +- D: `undefined`

Antwort

@@ -1314,10 +1315,10 @@ Es gibt eine unique id zurück. Diese id kann zum Beispiel verwendet werden um d [..."Lydia"]; ``` -- A: `["L", "y", "d", "i", "a"]` -- B: `["Lydia"]` -- C: `[[], "Lydia"]` -- D: `[["L", "y", "d", "i", "a"]]` +- A: `["L", "y", "d", "i", "a"]` +- B: `["Lydia"]` +- C: `[[], "Lydia"]` +- D: `[["L", "y", "d", "i", "a"]]`

Antwort

@@ -1377,7 +1378,7 @@ const secondPromise = new Promise((res, rej) => { setTimeout(res, 100, "two"); }); -Promise.race([firstPromise, secondPromise]).then(res => console.log(res)); +Promise.race([firstPromise, secondPromise]).then((res) => console.log(res)); ``` - A: `"one"` @@ -1441,7 +1442,7 @@ Wir ändern nur den Wert der Variable `person` und nicht das erste Element im Ar ```javascript const person = { name: "Lydia", - age: 21 + age: 21, }; for (const item in person) { @@ -1521,7 +1522,7 @@ Nur die erste Zahl im String wird ausgegeben. Aufgrund des _radix_ (das zweite A ###### 50. Was wird ausgegeben? ```javascript -[1, 2, 3].map(num => { +[1, 2, 3].map((num) => { if (typeof num === "number") return; return num * 2; }); @@ -1687,7 +1688,6 @@ Da wir die Variable `y` aber global erstellt haben ist ihr Wert `10` auch hier v

- --- ###### 55. Was wird ausgegeben? @@ -1699,7 +1699,7 @@ class Dog { } } -Dog.prototype.bark = function() { +Dog.prototype.bark = function () { console.log(`Woof I am ${this.name}`); }; @@ -1814,7 +1814,7 @@ console.log(delete age); #### Antwort: A -Der `delete` Operator gibt einen Boolean Wert zurück: `true` bei erfolgreichem entfernen, oder andernfalls `false`. Variablen, die mit `var`, `let` oder `const` deklariert werden, können andererseits nicht mit `delete` entfernt werden. +Der `delete` Operator gibt einen Boolean Wert zurück: `true` bei erfolgreichem entfernen, oder andernfalls `false`. Variablen, die mit `var`, `let` oder `const` deklariert werden, können andererseits nicht mit `delete` entfernt werden. Der Wert von `name` wurde mit `const` deklariert, weshalb `delete` nicht möglich ist und `false` zurückgegeben wird. Als wir `age` den Wert `21` zugewiesen haben, haben wir eine Property `age` zum globalen Objekt hinzugefügt. Diese Properties kann man mit `delete` entfernen, sodass `delete age` `true` zurückgibt. @@ -1927,7 +1927,7 @@ Properties, die mit `defineProperty` erstellt wurden sind standardmäßig unver const settings = { username: "lydiahallie", level: 19, - health: 90 + health: 90, }; const data = JSON.stringify(settings, ["level", "health"]); @@ -1961,7 +1961,7 @@ Wenn der Replacer eine _Funktion_ ist, so wird diese Funktion für jede Property let num = 10; const increaseNumber = () => num++; -const increasePassedNumber = number => number++; +const increasePassedNumber = (number) => number++; const num1 = increaseNumber(); const num2 = increasePassedNumber(num1); @@ -1987,8 +1987,6 @@ Der unäre Operator `++` _gibt zuerst_ den Wert des Operanden aus und _erhöht d

- - --- ###### 64. Was wird ausgegeben? @@ -2056,6 +2054,7 @@ Beim ersten Call ist der Akkumulator (`x`) gleich `1` und der aktuelle Wert (`y` Wenn wir keinen Wert einer Funktion ausgeben wird `undefined` ausgegeben. Beim nächsten Call ist der Akkumulator daher `undefined` und der aktuelle Wert ist `3`. `undefined` und `3` werden geloggt. Beim vierten Call geben wir wieder nichts aus, sodass der Akkumulator wieder `undefined` ist und der aktuelle Wert `4`. `undefined` und `4` werden geloggt. +

@@ -2109,6 +2108,7 @@ In einer abgeleiteten Klasse kann das `this` Keyword nicht aufgerufen werden, be Mit dem `super` Keyword können wir den Constructor der Elternklasse mit gegebenen Argumenten aufrufen. Der Constructor der Elternklasse erhält das `name` Argument, sodass wir `name` an `super` übergeben müssen. Die `Dog` Klasse erhält zwei Argumente, `name` da es `Animal` erweitert und `size` als extra Property der `Dog` Klasse. Beide müssen an die Constructor Funktion von `Dog` übergeben werden, was nur bei Constructor 2 richtig ist. +

@@ -2149,9 +2149,9 @@ Das ist der große Unterschied zwischen `require()` in CommonJS und `import`. Mi ###### 68. Was wird ausgegeben? ```javascript -console.log(Number(2) === Number(2)) -console.log(Boolean(false) === Boolean(false)) -console.log(Symbol('foo') === Symbol('foo')) +console.log(Number(2) === Number(2)); +console.log(Boolean(false) === Boolean(false)); +console.log(Symbol("foo") === Symbol("foo")); ``` - A: `true`, `true`, `false` @@ -2174,9 +2174,9 @@ Jedes Symbol ist eindeutig. Der Sinn des Argumentes, welches an das Symbol weite ###### 69. Was wird ausgegeben? ```javascript -const name = "Lydia Hallie" -console.log(name.padStart(13)) -console.log(name.padStart(2)) +const name = "Lydia Hallie"; +console.log(name.padStart(13)); +console.log(name.padStart(2)); ``` - A: `"Lydia Hallie"`, `"Lydia Hallie"` @@ -2451,7 +2451,7 @@ Die `sum` Funktion gibt daher immer das gleiche Ergebnis aus. Wenn wir `1` und ` ```javascript const add = () => { const cache = {}; - return num => { + return (num) => { if (num in cache) { return `From cache! ${cache[num]}`; } else { @@ -2496,21 +2496,21 @@ Beim dritten Mal geben wir `5 * 2` als Argument in die Funktion ein, was `10` er ###### 79. Was wird ausgegeben? ```javascript -const myLifeSummedUp = ["☕", "💻", "🍷", "🍫"] +const myLifeSummedUp = ["☕", "💻", "🍷", "🍫"]; for (let item in myLifeSummedUp) { - console.log(item) + console.log(item); } for (let item of myLifeSummedUp) { - console.log(item) + console.log(item); } ``` - A: `0` `1` `2` `3` und `"☕"` ` "💻"` `"🍷"` `"🍫"` - B: `"☕"` ` "💻"` `"🍷"` `"🍫"` und `"☕"` ` "💻"` `"🍷"` `"🍫"` - C: `"☕"` ` "💻"` `"🍷"` `"🍫"` und `0` `1` `2` `3` -- D: `0` `1` `2` `3` und `{0: "☕", 1: "💻", 2: "🍷", 3: "🍫"}` +- D: `0` `1` `2` `3` und `{0: "☕", 1: "💻", 2: "🍷", 3: "🍫"}`
Antwort

@@ -2533,14 +2533,14 @@ Mit einer _for-of_ Schleife können wir über **wiederholbare** Elemente iterier ###### 80. Was wird ausgegeben? ```javascript -const list = [1 + 2, 1 * 2, 1 / 2] -console.log(list) +const list = [1 + 2, 1 * 2, 1 / 2]; +console.log(list); ``` - A: `["1 + 2", "1 * 2", "1 / 2"]` - B: `["12", 2, 0.5]` - C: `[3, 2, 0.5]` -- D: `[1, 1, 1]` +- D: `[1, 1, 1]`

Antwort

@@ -2560,16 +2560,16 @@ Das Element ist gleich dem ausgegebenen Wert. `1 + 2` ergibt `3`, `1 * 2` ergibt ```javascript function sayHi(name) { - return `Hi there, ${name}` + return `Hi there, ${name}`; } -console.log(sayHi()) +console.log(sayHi()); ``` - A: `Hi there, ` - B: `Hi there, undefined` - C: `Hi there, null` -- D: `ReferenceError` +- D: `ReferenceError`

Antwort

@@ -2592,21 +2592,21 @@ In diesem Fall, falls wir kein Argument oder `undefined` eingeben ist `name` imm ###### 82. Was wird ausgegeben? ```javascript -var status = "😎" +var status = "😎"; setTimeout(() => { - const status = "😍" + const status = "😍"; const data = { status: "🥑", getStatus() { - return this.status - } - } + return this.status; + }, + }; - console.log(data.getStatus()) - console.log(data.getStatus.call(this)) -}, 0) + console.log(data.getStatus()); + console.log(data.getStatus.call(this)); +}, 0); ``` - A: `"🥑"` und `"😍"` @@ -2623,7 +2623,6 @@ Der Wert des `this` Keywords hängt davon ab, wo es verwendet wird. In einer **M Mit der `call` Methode können wir das Objekt, auf welches sich das `this` Keyword bezieht ändern. In **Funktionen** bezieht sich `this` auf das _Objekt, zu dem die Funktion gehört_. Wir erklären die `setTimeout` Funktion im _globalen Objekt_, sodass sich `this` in `setTimeout` auf das _globale Objekt_ bezieht. Im globalen Objekt gibt es _status_ mit dem Wert `"😎"`, was geloggt wird. -

@@ -2634,13 +2633,13 @@ Mit der `call` Methode können wir das Objekt, auf welches sich das `this` Keywo ```javascript const person = { name: "Lydia", - age: 21 -} + age: 21, +}; -let city = person.city -city = "Amsterdam" +let city = person.city; +city = "Amsterdam"; -console.log(person) +console.log(person); ``` - A: `{ name: "Lydia", age: 21 }` @@ -2671,15 +2670,15 @@ Wenn wir `person` loggen bekommen wir daher das unveränderte Objekt angezeigt. ```javascript function checkAge(age) { if (age < 18) { - const message = "Sorry, you're too young." + const message = "Sorry, you're too young."; } else { - const message = "Yay! You're old enough!" + const message = "Yay! You're old enough!"; } - return message + return message; } -console.log(checkAge(21)) +console.log(checkAge(21)); ``` - A: `"Sorry, you're too young."` @@ -2702,9 +2701,9 @@ Variablen mit dem `const` und `let` Keyword sind _block-scoped_. Ein Block ist a ###### 85. Welche Information wird geloggt? ```javascript -fetch('https://www.website.com/api/user/1') - .then(res => res.json()) - .then(res => console.log(res)) +fetch("https://www.website.com/api/user/1") + .then((res) => res.json()) + .then((res) => console.log(res)); ``` - A: Das Ergebnis der `fetch` Methode. @@ -2749,16 +2748,16 @@ Wenn wir `hasName` gleich `name` setzen, so beinhaltet `hasName` den Wert von `n `new Boolean(true)` gibt einen Objekt Wrapper aus, nicht ein Boolean ansich. `name.length` gibt die Länge des Arguments aus, nicht den Boolean Wert. +

- --- ###### 87. Was wird ausgegeben? ```javascript -console.log("I want pizza"[0]) +console.log("I want pizza"[0]); ``` - A: `"""` @@ -2784,10 +2783,10 @@ Diese Methode funktioniert nicht in IE7 und davor. Hier muss `.charAt()` verwend ```javascript function sum(num1, num2 = num1) { - console.log(num1 + num2) + console.log(num1 + num2); } -sum(10) +sum(10); ``` - A: `NaN` @@ -2813,13 +2812,13 @@ Wenn man den Wert des Standard Paramenters gleich dem Parameter setztm der _dana ```javascript // module.js -export default () => "Hello world" -export const name = "Lydia" +export default () => "Hello world"; +export const name = "Lydia"; // index.js -import * as data from "./module" +import * as data from "./module"; -console.log(data) +console.log(data); ``` - A: `{ default: function default(), name: "Lydia" }` @@ -2846,12 +2845,12 @@ Das `data` Objekt hat eine Standard Property für alle Standard Exporte, andere ```javascript class Person { constructor(name) { - this.name = name + this.name = name; } } -const member = new Person("John") -console.log(typeof member) +const member = new Person("John"); +console.log(typeof member); ``` - A: `"class"` @@ -2868,7 +2867,7 @@ Klassen sind syntaktischer Zucker für Funktionskontruktoren. Das Equivalent der ```javascript function Person() { - this.name = name + this.name = name; } ``` @@ -2882,9 +2881,9 @@ Das Aufrufen eines Funktionskonstruktors mit `new` hat zur Folge, dass eine Inst ###### 91. Was wird ausgegeben? ```javascript -let newList = [1, 2, 3].push(4) +let newList = [1, 2, 3].push(4); -console.log(newList.push(5)) +console.log(newList.push(5)); ``` - A: `[1, 2, 3, 4, 5]` @@ -2910,13 +2909,14 @@ Dann versuchen wir die `.push` Methode auf `newList` anzuwenden. Da `newList` de ```javascript function giveLydiaPizza() { - return "Here is pizza!" + return "Here is pizza!"; } -const giveLydiaChocolate = () => "Here's chocolate... now go hit the gym already." +const giveLydiaChocolate = () => + "Here's chocolate... now go hit the gym already."; -console.log(giveLydiaPizza.prototype) -console.log(giveLydiaChocolate.prototype) +console.log(giveLydiaPizza.prototype); +console.log(giveLydiaChocolate.prototype); ``` - A: `{ constructor: ...}` `{ constructor: ...}` @@ -2941,11 +2941,11 @@ Reguläre Funktionen wie `giveLydiaPizza` haben eine `prototype` Property, die e ```javascript const person = { name: "Lydia", - age: 21 -} + age: 21, +}; for (const [x, y] of Object.entries(person)) { - console.log(x, y) + console.log(x, y); } ``` @@ -2997,13 +2997,14 @@ getItems(["banana", "apple"], "pear", "orange") ```javascript function getItems(fruitList, favoriteFruit, ...args) { - return [...fruitList, ...args, favoriteFruit] + return [...fruitList, ...args, favoriteFruit]; } -getItems(["banana", "apple"], "pear", "orange") +getItems(["banana", "apple"], "pear", "orange"); ``` Dieses Beispiel würde funktionieren und `[ 'banana', 'apple', 'orange', 'pear' ]` ausgeben. +

@@ -3013,17 +3014,14 @@ Dieses Beispiel würde funktionieren und `[ 'banana', 'apple', 'orange', 'pear' ```javascript function nums(a, b) { - if - (a > b) - console.log('a is bigger') - else - console.log('b is bigger') - return - a + b + if (a > b) console.log("a is bigger"); + else console.log("b is bigger"); + return; + a + b; } -console.log(nums(4, 2)) -console.log(nums(1, 2)) +console.log(nums(4, 2)); +console.log(nums(1, 2)); ``` - A: `a is bigger`, `6` und `b is bigger`, `3` @@ -3041,8 +3039,8 @@ In JavaScript muss das Semikolon _nicht_ explizit gesetzt werden, allerdings set In unserem Beispiel haben wir ein `return` Statement gefolgt von einem anderen Wert `a + b` auf der _nächsten Zeile_. Da es eine neue Zeile ist, weiß JavaScript nicht, dass das der Wert ist, den wir eigentlich ausgeben wollten. Stattdessen wird automatisch ein Semikolon nach `return` gesetzt, was man wiefolgt lesen kann: ```javascript - return; - a + b +return; +a + b; ``` Das bedeutet, dass `a + b` nie erreicht wird, da die Funktion auf der Zeile davor mit dem `return` Keyword endet. Wenn wie hier kein Wert ausgegeben wird, gibt die Funktion `undefined` aus. @@ -3058,18 +3056,18 @@ Bedenke: Semikolons werden **nicht** automatisch nach `if/else` Statements geset ```javascript class Person { constructor() { - this.name = "Lydia" + this.name = "Lydia"; } } Person = class AnotherPerson { constructor() { - this.name = "Sarah" + this.name = "Sarah"; } -} +}; -const member = new Person() -console.log(member.name) +const member = new Person(); +console.log(member.name); ``` - A: `"Lydia"` @@ -3093,11 +3091,11 @@ Wir können Klassen gleich anderen Klassen oder Funktions Konstruktoren setzen. ```javascript const info = { - [Symbol('a')]: 'b' -} + [Symbol("a")]: "b", +}; -console.log(info) -console.log(Object.keys(info)) +console.log(info); +console.log(Object.keys(info)); ``` - A: `{Symbol('a'): 'b'}` und `["{Symbol('a')"]` @@ -3145,13 +3143,13 @@ console.log(getUser(user)) Die `getList` Funktion bekommt ein Array als Argument zugewiesen. Zwischen den Klammern der `getList` Funktion wird das Array direkt destrukturiert. Man könnte das auch wiefolgt sehen: - `[x, ...y] = [1, 2, 3, 4]` +`[x, ...y] = [1, 2, 3, 4]` Mit dem Rest Parameter `...y` packen wir alle übrigen Argumente in ein Array. Die übrigen Argumente sind in dem Fall `2`, `3` und `4`. Der Wert von `y` ist ein Array mit den restlichen Parametern. Der Wert von `x` ist gleich `1` sodass `[1, [2, 3, 4]]` geloggt wird. Die `getUser` Funktion bekommt ein Objekt zugewiesen. Bei Arrow Funktionen müssen wir keine geschweiften Klammern verwenden, wenn wir nur einen Wert ausgeben. Wenn wir aber ein _Objekt_ von einer Arrow Funktion ausgeben lassen möchten, so muss dieses zwischen Klammern stehen, ansonsten wird nichts ausgegeben. Die folgende Funktion hätte ein Objekt ausgegeben: -```const getUser = user => ({ name: user.name, age: user.age })``` +`const getUser = user => ({ name: user.name, age: user.age })` Da kein Wert ausgegeben wird, gibt die Funktion `undefined` aus. @@ -3163,9 +3161,9 @@ Da kein Wert ausgegeben wird, gibt die Funktion `undefined` aus. ###### 99. Was wird ausgegeben? ```javascript -const name = "Lydia" +const name = "Lydia"; -console.log(name()) +console.log(name()); ``` - A: `SyntaxError` @@ -3196,8 +3194,8 @@ ReferenceErrors werden ausgeworfen, wenn JavaScript eine Referenz zu einem Wert ```javascript // 🎉✨ Das ist unsere 100. Frage! ✨🎉 -const output = `${[] && 'Im'}possible! -You should${'' && `n't`} see a therapist after so much JavaScript lol` +const output = `${[] && "Im"}possible! +You should${"" && `n't`} see a therapist after so much JavaScript lol`; ``` - A: `possible! You should see a therapist after so much JavaScript lol` @@ -3222,11 +3220,11 @@ You should${'' && `n't`} see a therapist after so much JavaScript lol` ###### 101. Was wird ausgegeben? ```javascript -const one = (false || {} || null) -const two = (null || false || "") -const three = ([] || 0 || true) +const one = false || {} || null; +const two = null || false || ""; +const three = [] || 0 || true; -console.log(one, two, three) +console.log(one, two, three); ``` - A: `false` `null` `[]` @@ -3255,16 +3253,16 @@ Mit dem `||` Operator geben wir den ersten truthy Operand aus. Wenn alle Werte f ###### 102. What's the value of output? ```javascript -const myPromise = () => Promise.resolve('I have resolved!') +const myPromise = () => Promise.resolve("I have resolved!"); function firstFunction() { - myPromise().then(res => console.log(res)) - console.log('second') + myPromise().then((res) => console.log(res)); + console.log("second"); } async function secondFunction() { - console.log(await myPromise()) - console.log('second') + console.log(await myPromise()); + console.log("second"); } ``` @@ -3297,14 +3295,14 @@ Das bedeutet, dass auf `myPromise` gewartet und dann der Wert `I have resolved` ###### 103. Was wird ausgegeben? ```javascript -const set = new Set() +const set = new Set(); -set.add(1) -set.add("Lydia") -set.add({ name: "Lydia" }) +set.add(1); +set.add("Lydia"); +set.add({ name: "Lydia" }); for (let item of set) { - console.log(item + 2) + console.log(item + 2); } ``` @@ -3334,7 +3332,7 @@ Der zweite Wert hingegen ist der String `"Lydia"`. `"Lydia"` ist ein String und ###### 104. Was wird ausgegeben? ```javascript -Promise.resolve(5) +Promise.resolve(5); ``` - A: `5` @@ -3361,15 +3359,15 @@ In diesem Fall haben wir nur die Zahl `5` übergeben und diese wird genauso ausg ```javascript function compareMembers(person1, person2 = person) { if (person1 !== person2) { - console.log("Not the same!") + console.log("Not the same!"); } else { - console.log("They are the same!") + console.log("They are the same!"); } } -const person = { name: "Lydia" } +const person = { name: "Lydia" }; -compareMembers(person) +compareMembers(person); ``` - A: `Not the same!` @@ -3404,11 +3402,11 @@ const colorConfig = { green: true, black: true, yellow: false, -} +}; -const colors = ["pink", "red", "blue"] +const colors = ["pink", "red", "blue"]; -console.log(colorConfig.colors[1]) +console.log(colorConfig.colors[1]); ``` - A: `true` @@ -3435,7 +3433,7 @@ JavaScript interpretiert Statements. Wenn wir Klammern-Notation verwenden wird d ###### 107. Was wird ausgegeben? ```javascript -console.log('❤️' === '❤️') +console.log("❤️" === "❤️"); ``` - A: `true` @@ -3456,14 +3454,14 @@ Emojis sind im Endeffekt nur Unicodes. Der Unicode für das Herz Emoji ist `"U+2 ###### 108. Welche Methode verändert das ursprüngliche Array? ```javascript -const emojis = ['✨', '🥑', '😍'] +const emojis = ["✨", "🥑", "😍"]; -emojis.map(x => x + '✨') -emojis.filter(x => x !== '🥑') -emojis.find(x => x !== '🥑') -emojis.reduce((acc, cur) => acc + '✨') -emojis.slice(1, 2, '✨') -emojis.splice(1, 2, '✨') +emojis.map((x) => x + "✨"); +emojis.filter((x) => x !== "🥑"); +emojis.find((x) => x !== "🥑"); +emojis.reduce((acc, cur) => acc + "✨"); +emojis.slice(1, 2, "✨"); +emojis.splice(1, 2, "✨"); ``` - A: `All of them` @@ -3483,18 +3481,17 @@ Mit der `splice` Methode ändern wir das ursprüngliche Array durch löschen, er

- --- ###### 109. Was wird ausgegeben? ```javascript -const food = ['🍕', '🍫', '🥑', '🍔'] -const info = { favoriteFood: food[0] } +const food = ["🍕", "🍫", "🥑", "🍔"]; +const info = { favoriteFood: food[0] }; -info.favoriteFood = '🍝' +info.favoriteFood = "🍝"; -console.log(food) +console.log(food); ``` - A: `['🍕', '🍫', '🥑', '🍔']` @@ -3519,7 +3516,7 @@ Dann ändern wir den Wert von `favoriteFood` am `info` Objekt. Das `food` Array ###### 110. Was macht diese Methode? ```javascript -JSON.parse() +JSON.parse(); ``` - A: Parsed JSON in einen JavaScript Wert @@ -3536,16 +3533,16 @@ Mit der `JSON.parse()` Methode können wir einen JSON String zu einem JavaScript ```javascript // Stringifying a number into valid JSON, then parsing the JSON string to a JavaScript value: -const jsonNumber = JSON.stringify(4) // '4' -JSON.parse(jsonNumber) // 4 +const jsonNumber = JSON.stringify(4); // '4' +JSON.parse(jsonNumber); // 4 // Stringifying an array value into valid JSON, then parsing the JSON string to a JavaScript value: -const jsonArray = JSON.stringify([1, 2, 3]) // '[1, 2, 3]' -JSON.parse(jsonArray) // [1, 2, 3] +const jsonArray = JSON.stringify([1, 2, 3]); // '[1, 2, 3]' +JSON.parse(jsonArray); // [1, 2, 3] // Stringifying an object into valid JSON, then parsing the JSON string to a JavaScript value: -const jsonArray = JSON.stringify({ name: "Lydia" }) // '{"name":"Lydia"}' -JSON.parse(jsonArray) // { name: 'Lydia' } +const jsonArray = JSON.stringify({ name: "Lydia" }); // '{"name":"Lydia"}' +JSON.parse(jsonArray); // { name: 'Lydia' } ```

@@ -3556,14 +3553,14 @@ JSON.parse(jsonArray) // { name: 'Lydia' } ###### 111. Was wird ausgegeben? ```javascript -let name = 'Lydia' +let name = "Lydia"; function getName() { - console.log(name) - let name = 'Sarah' + console.log(name); + let name = "Sarah"; } -getName() +getName(); ``` - A: Lydia @@ -3583,13 +3580,13 @@ Variablen mit dem `let` und `const` Keyword werden gehoisted, aber entgegen `var Hätten wir die `name` Variable nicht innerhalb `getName` deklariert, so hätte JavaScript außerhalb der Funktion in der _Scope-Kette_ weitergesucht. Der äußere Scope beinhaltet ebenfalls eine Variable `name` mit dem Wert `'Lydia'`. In diesem Fall wäre `Lydia` geloggt worden. ```javascript -let name = 'Lydia' +let name = "Lydia"; function getName() { - console.log(name) + console.log(name); } -getName() // Lydia +getName(); // Lydia ```

@@ -3601,18 +3598,18 @@ getName() // Lydia ```javascript function* generatorOne() { - yield ['a', 'b', 'c']; + yield ["a", "b", "c"]; } function* generatorTwo() { - yield* ['a', 'b', 'c']; + yield* ["a", "b", "c"]; } -const one = generatorOne() -const two = generatorTwo() +const one = generatorOne(); +const two = generatorTwo(); -console.log(one.next().value) -console.log(two.next().value) +console.log(one.next().value); +console.log(two.next().value); ``` - A: `a` and `a` @@ -3630,17 +3627,17 @@ Mit dem `yield` Keyword, halten wir Werte in einer Generator-Funktion. Mit dem ` In `generatorOne` halten wir das gesamte Array `['a', 'b', 'c']` mit dem `yield` Keyword. Der Wert von `value` am Objekt gibt die `next` Methode an `one` (`one.next().value`) aus, was dem gesamten Array entspricht: `['a', 'b', 'c']`. ```javascript -console.log(one.next().value) // ['a', 'b', 'c'] -console.log(one.next().value) // undefined +console.log(one.next().value); // ['a', 'b', 'c'] +console.log(one.next().value); // undefined ``` In `generatorTwo` verwenden wir das `yield*` Keyword. Das bedeutet, dass der erste gehaltene Wert von `two` gleich dem ersten gehaltenen Wert ist. Das ist das Array `['a', 'b', 'c']`. Der erste gehaltene Wert ist `a`, was ausgegeben wird. ```javascript -console.log(two.next().value) // 'a' -console.log(two.next().value) // 'b' -console.log(two.next().value) // 'c' -console.log(two.next().value) // undefined +console.log(two.next().value); // 'a' +console.log(two.next().value); // 'b' +console.log(two.next().value); // 'c' +console.log(two.next().value); // undefined ```

@@ -3651,7 +3648,7 @@ console.log(two.next().value) // undefined ###### 113. Was wird ausgegeben? ```javascript -console.log(`${(x => x)('I love')} to program`) +console.log(`${((x) => x)("I love")} to program`); ``` - A: `I love to program` @@ -3741,19 +3738,19 @@ Beim Setzen eines Key/Wert Paars mit der `set` Methode wird der Key als erstes A ```javascript const person = { name: "Lydia", - age: 21 -} + age: 21, +}; -const changeAge = (x = { ...person }) => x.age += 1 +const changeAge = (x = { ...person }) => (x.age += 1); const changeAgeAndName = (x = { ...person }) => { - x.age += 1 - x.name = "Sarah" -} + x.age += 1; + x.name = "Sarah"; +}; -changeAge(person) -changeAgeAndName() +changeAge(person); +changeAgeAndName(); -console.log(person) +console.log(person); ``` - A: `{name: "Sarah", age: 22}` @@ -3781,7 +3778,7 @@ Dann führen wir `changeAgeAndName` aus, allerdings ohne Parameter. Stattdessen ```javascript function sumValues(x, y, z) { - return x + y + z; + return x + y + z; } ``` @@ -3832,15 +3829,15 @@ Mit dem`+=` Operanden erhöhen wir den Wert von `num` um `1`. `num` hatte den ur ```javascript const person = { - firstName: "Lydia", - lastName: "Hallie", - pet: { - name: "Mara", - breed: "Dutch Tulip Hound" - }, - getFullName() { - return `${this.firstName} ${this.lastName}`; - } + firstName: "Lydia", + lastName: "Hallie", + pet: { + name: "Mara", + breed: "Dutch Tulip Hound", + }, + getFullName() { + return `${this.firstName} ${this.lastName}`; + }, }; console.log(person.pet?.name); @@ -3877,9 +3874,9 @@ Mit den optionalen Kettenoperator `?.` müssen wir nicht mehr prüfen, ob die ti const groceries = ["banana", "apple", "peanuts"]; if (groceries.indexOf("banana")) { - console.log("We have to buy bananas!"); + console.log("We have to buy bananas!"); } else { - console.log(`We don't have to buy bananas!`); + console.log(`We don't have to buy bananas!`); } ``` @@ -3904,10 +3901,10 @@ Wir haben die Kondition `groceries.indexOf("banana")` an das if-Statement überg ```javascript const config = { - languages: [], - set language(lang) { - return this.languages.push(lang); - } + languages: [], + set language(lang) { + return this.languages.push(lang); + }, }; console.log(config.language); @@ -3961,9 +3958,9 @@ console.log(!typeof name === "string"); ###### 123. Was ist der Output?? ```javascript -const add = x => y => z => { - console.log(x, y, z); - return x + y + z; +const add = (x) => (y) => (z) => { + console.log(x, y, z); + return x + y + z; }; add(4)(5)(6); @@ -3990,16 +3987,16 @@ Die `add` Funktion gibt eine Arrow Funktion zurück, welche eine Arrow Funktion ```javascript async function* range(start, end) { - for (let i = start; i <= end; i++) { - yield Promise.resolve(i); - } + for (let i = start; i <= end; i++) { + yield Promise.resolve(i); + } } (async () => { - const gen = range(1, 3); - for await (const item of gen) { - console.log(item); - } + const gen = range(1, 3); + for await (const item of gen) { + console.log(item); + } })(); ``` @@ -4024,7 +4021,7 @@ Die Generator-Funktion `range` gibt ein asynchrones Objekt mit Promisen für jed ```javascript const myFunc = ({ x, y, z }) => { - console.log(x, y, z); + console.log(x, y, z); }; myFunc(1, 2, 3); @@ -4051,20 +4048,20 @@ myFunc(1, 2, 3); ```javascript function getFine(speed, amount) { - const formattedSpeed = new Intl.NumberFormat('en-US', { - style: 'unit', - unit: 'mile-per-hour' + const formattedSpeed = new Intl.NumberFormat("en-US", { + style: "unit", + unit: "mile-per-hour", }).format(speed); - const formattedAmount = new Intl.NumberFormat('en-US', { - style: 'currency', - currency: 'USD' + const formattedAmount = new Intl.NumberFormat("en-US", { + style: "currency", + currency: "USD", }).format(amount); return `The driver drove ${formattedSpeed} and has to pay ${formattedAmount}`; } -console.log(getFine(130, 300)) +console.log(getFine(130, 300)); ``` - A: The driver drove 130 and has to pay 300 @@ -4087,8 +4084,8 @@ Mit der Methode `Intl.NumberFormat` können wir einen numerischen Wert in einen ###### 127. Was ist der Output? ```javascript -const spookyItems = ['👻', '🎃', '🕸']; -({ item: spookyItems[3] } = { item: '💀' }); +const spookyItems = ["👻", "🎃", "🕸"]; +({ item: spookyItems[3] } = { item: "💀" }); console.log(spookyItems); ``` @@ -4113,7 +4110,7 @@ Durch die destrukturierende Zuweisung können wir Werte des Ojekts von der recht ###### 128. Was ist der Output? ```javascript -const name = 'Lydia Hallie'; +const name = "Lydia Hallie"; const age = 21; console.log(Number.isNaN(name)); @@ -4133,7 +4130,7 @@ console.log(isNaN(age)); #### Antwort: C -Mit der Methode `Number.isNaN` kann geprüft werden, ob der übergebene Parameter vom Typ _Number_ mit Wert `NaN` ist. `name` ist kein numerischer Wert, deswegen ist der Rückgabewert von `Number.isNaN(name)` in diesem Fall `false`. `age` ist zwar ein numerischer Wert, aber nicht gleich `NaN`, weswegen `Number.isNaN(age)` `false` ausgibt. +Mit der Methode `Number.isNaN` kann geprüft werden, ob der übergebene Parameter vom Typ _Number_ mit Wert `NaN` ist. `name` ist kein numerischer Wert, deswegen ist der Rückgabewert von `Number.isNaN(name)` in diesem Fall `false`. `age` ist zwar ein numerischer Wert, aber nicht gleich `NaN`, weswegen `Number.isNaN(age)` `false` ausgibt. Die Methode `isNaN` prüft, ob der Eingabeparameter nicht vom Typ _Number_ ist. `name` ist ein String, darum gibt `isNaN(name)` `true` zurück. `age` ist ein numerischer Wert, weswegen `isNaN(age)` `false` ausgibt. @@ -4149,7 +4146,7 @@ const randomValue = 21; function getInfo() { console.log(typeof randomValue); - const randomValue = 'Lydia Hallie'; + const randomValue = "Lydia Hallie"; } getInfo(); @@ -4175,7 +4172,7 @@ Variablen die mit `const` deklariert werden, können nicht vor ihrer Initialisie ###### 130. Was ist der Output? ```javascript -const myPromise = Promise.resolve('Woah some cool data'); +const myPromise = Promise.resolve("Woah some cool data"); (async () => { try { @@ -4183,7 +4180,7 @@ const myPromise = Promise.resolve('Woah some cool data'); } catch { throw new Error(`Oops didn't work`); } finally { - console.log('Oh finally!'); + console.log("Oh finally!"); } })(); ``` @@ -4208,7 +4205,7 @@ Im `try`-Block loggen wir den mit dem `await`-Operator den Wert der Variable `my ###### 131. Was ist der Output? ```javascript -const emojis = ['🥑', ['✨', '✨', ['🍕', '🍕']]]; +const emojis = ["🥑", ["✨", "✨", ["🍕", "🍕"]]]; console.log(emojis.flat(1)); ``` @@ -4281,19 +4278,19 @@ Wir rufen nun `counterTwo.increment()` auf, wodurch der Wert von `count` auf `3` ###### 133. Was ist der Output? ```javascript -const myPromise = Promise.resolve(Promise.resolve('Promise!')); +const myPromise = Promise.resolve(Promise.resolve("Promise!")); function funcOne() { - myPromise.then(res => res).then(res => console.log(res)); - setTimeout(() => console.log('Timeout!', 0)); - console.log('Last line!'); + myPromise.then((res) => res).then((res) => console.log(res)); + setTimeout(() => console.log("Timeout!", 0)); + console.log("Last line!"); } async function funcTwo() { const res = await myPromise; console.log(await res); - setTimeout(() => console.log('Timeout!', 0)); - console.log('Last line!'); + setTimeout(() => console.log("Timeout!", 0)); + console.log("Last line!"); } funcOne(); @@ -4321,4 +4318,4 @@ Die nächste Zeile ist die _asynchrone_ Funktion `setTimeout`, deren Callback an Wir kommen zur letzten Zeile in `funcTwo`, die `Last line!` in der Console ausgibt. Da `funcTwo` abgearbeitet und aus dem Call Stack entfernt wurde, ist der Call Stack leer. Die wartenden Callbacks (`() => console.log("Timeout!")` aus `funcOne` und `() => console.log("Timeout!")` aus `funcTwo`) werden dem Call Stack nacheinander hinzugefügt. Der erste Callback loggt `Timeout!` und wird aus dem Stack entfernt. Anschließend loggt der zweite Callback `Timeout!` und wird aus dem Stack entfernt. Somit ist das Ergebnis `Last line! Promise! Promise! Last line! Timeout! Timeout!`

-
\ No newline at end of file +
diff --git a/es-ES/README-ES.md b/es-ES/README-ES.md index 5c3ddc40..577e66f0 100644 --- a/es-ES/README-ES.md +++ b/es-ES/README-ES.md @@ -1,17 +1,16 @@ +# Lista de preguntas (avanzadas) de JavaScript -# Lista de preguntas (avanzadas) de JavaScript +Publico diariamente preguntas de opción múltiple en JavaScript en mi [Instagram](https://www.instagram.com/theavocoder), ¡que también publicaré aquí! - Publico diariamente preguntas de opción múltiple en JavaScript en mi [Instagram](https://www.instagram.com/theavocoder), ¡que también publicaré aquí! - - Desde lo básico a lo avanzado: comprueba si realmente conoces _Javascript_, actualiza tus conocimientos o simplemente prepárate para tu próxima entrevista 💪 🚀 Actualizaré este repo semanalmente con nuevas preguntas. - - Las respuestas se encuentran en las secciones contraídas debajo de las preguntas, simplemente haz clic en ellas para expandirlas. Buena suerte ❤️ +Desde lo básico a lo avanzado: comprueba si realmente conoces _Javascript_, actualiza tus conocimientos o simplemente prepárate para tu próxima entrevista 💪 🚀 Actualizaré este repo semanalmente con nuevas preguntas. + +Las respuestas se encuentran en las secciones contraídas debajo de las preguntas, simplemente haz clic en ellas para expandirlas. Buena suerte ❤️ ¿Quieres recibir un email cada vez que agregue más preguntas?
✨✉Suscríbete a las actualizaciones por email✉✨ - Lista de lenguajes disponibles: + - [🇸🇦 العربية](../ar-AR/README_AR.md) - [🇪🇬 اللغة العامية](../ar-EG/README_ar-EG.md) - [🇧🇦 Bosanski](../bs-BS/README-bs_BS.md) @@ -25,6 +24,7 @@ Lista de lenguajes disponibles: - [🇳🇱 Nederlands](../nl-NL/README.md) - [🇵🇱 Polski](../pl-PL/README.md) - [🇧🇷 Português Brasil](../pt-BR/README_pt_BR.md) +- [🇷o Română](../ro-RO/README.ro.md) - [🇷🇺 Русский](../ru-RU/README.md) - [🇽🇰 Shqip](../sq-KS/README_sq_KS.md) - [🇹🇭 ไทย](../th-TH/README-th_TH.md) @@ -34,7 +34,6 @@ Lista de lenguajes disponibles: - [🇨🇳 简体中文](../zh-CN/README-zh_CN.md) - [🇹🇼 繁體中文](../zh-TW/README_zh-TW.md) - --- ###### 1. ¿Qué devuelve la siguiente función? @@ -63,6 +62,7 @@ sayHi(); Dentro de la función, primero declaramos la variable `name` con la palabra reservada ` var`. Esto significa que la variable se _eleva_ (el espacio de memoria se configura durante la fase de creación. Hace referencia al termino [hoisting](https://developer.mozilla.org/es/docs/Glossary/Hoisting)) con el valor predeterminado de `indefinido`, hasta que realmente llegamos a la línea donde definimos la variable. Aún no hemos definido la variable en la línea donde intentamos registrar la variable `name`, por lo que aún mantiene el valor de` undefined`. Las variables con la palabra clave `let` (y` const`) se _elevan_, pero a diferencia de `var`, no se inicializa . No son accesibles antes de la línea que los declaramos (inicializamos). Esto se llama la ["zona muerta temporal"](https://wesbos.com/temporal-dead-zone/). Cuando intentamos acceder a las variables antes de que se declaren, JavaScript lanza un `ReferenceError` +

@@ -106,7 +106,7 @@ const shape = { diameter() { return this.radius * 2; }, - perimeter: () => 2 * Math.PI * this.radius + perimeter: () => 2 * Math.PI * this.radius, }; shape.diameter(); @@ -163,12 +163,12 @@ En el segundo caso la cadena `'Lydia'` es un valor verdadero. Lo que realmente e ```javascript const bird = { - size: "small" + size: "small", }; const mouse = { name: "Mickey", - small: true + small: true, }; ``` @@ -186,7 +186,7 @@ En JavaScript, todas las _keys_ son cadenas (a menos que sea un símbolo). A pes JavaScript interpreta declaraciones. Cuando usamos la notación de corchetes, ve el corchete de apertura `[` y continúa hasta que encuentra el corchete de cierre `]`. Solo de esta manera se evaluará la afirmación. -`mouse [bird.size]`: Primero evalúa `bird.size`, que es` "small" `. `mouse ["small"]` devuelve `true` +`mouse [bird.size]`: Primero evalúa `bird.size`, que es`"small"`. `mouse ["small"]` devuelve `true` Sin embargo, con la notación de puntos, esto no sucede. `mouse` no tiene una clave llamada` bird`, lo que significa que `mouse.bird` es` undefined`. Luego, pedimos el `tamaño` usando la notación de puntos:` mouse.bird.size`. Como `mouse.bird` es` undefined`, en realidad estamos preguntando `undefined.size`. Esto no es válido y generará un error similar `al Cannot read property "size" of undefined` @@ -363,7 +363,7 @@ function Person(firstName, lastName) { const member = new Person("Lydia", "Hallie"); Person.getFullName = function () { return `${this.firstName} ${this.lastName}`; -} +}; console.log(member.getFullName()); ``` @@ -420,7 +420,7 @@ console.log(sarah); Para `sarah`, no usamos la palabra reservada `new`. Cuando se usa `new`, se refiere al nuevo objeto vacío que creamos. Sin embargo, si no se agrega `new', se refiere al **objeto global**! -En el ejemplo `this.firstName` equivale a `"Sarah"` y `this.lastName` equivale a `"Smith"`. Lo que realmente hicimos fue definir `global.firstName = `Sarah'` y `global.lastName = `Smith'`. La misma `sarah` se deja `indefinida`. +En el ejemplo `this.firstName` equivale a `"Sarah"` y `this.lastName` equivale a `"Smith"`. Lo que realmente hicimos fue definir `global.firstName = `Sarah'`y`global.lastName = `Smith'`. La misma `sarah` se deja `indefinida`.

@@ -487,7 +487,7 @@ sum(1, "2"); JavaScript es un **lenguaje dinámicamente tipado** o de tipado débil, esto significa que no es necesario declarar el tipo de variable antes de usarla pues será determinado automáticamente cuando el programa comience a ser procesado. Los valores se pueden convertir automáticamente en otro tipo sin que se sepa, esto se llama denomina _implicit type coercion_ (Más info [aquí](https://medium.com/@ManuCastrillonM/entendiendo-la-coerci%C3%B3n-en-javascript-bc202d22d23f)). **La coerción es la conversión de un tipo a otro.** -En este ejemplo, JavaScript convierte el número `1` en una cadena, para que la función tenga sentido y devuelva un valor. Durante la suma de un tipo numérico (`1`) y un tipo de cadena (`'2'`), el número se trata como una cadena. Podemos concatenar cadenas como `"Hello" + "World"``, así que lo que está pasando aquí es `"1" + "2"` que devuelve `"12"` +En este ejemplo, JavaScript convierte el número `1` en una cadena, para que la función tenga sentido y devuelva un valor. Durante la suma de un tipo numérico (`1`) y un tipo de cadena (`'2'`), el número se trata como una cadena. Podemos concatenar cadenas como ` "Hello" + "World"``, así que lo que está pasando aquí es `"1" + "2"`que devuelve`"12"`

@@ -554,8 +554,8 @@ getPersonInfo`${person} is ${age} years old`; #### Respuesta correcta: B - _Tagged templates_ es un caso de uso de [template literals](https://codeburst.io/javascript-template-literals-tag-functions-for-beginners-758a041160e1). Una _plantilla etiquetada_ es una llamada de función que utiliza una plantilla literal de la que obtener sus argumentos. Si se usan literales de plantillas etiquetadas, el valor del primer argumento es siempre una matriz de los valores de las cadenas. El resto de los argumentos obtienen los valores de las expresiones pasadas. +

@@ -755,7 +755,6 @@ Todas las claves de un objeto (excepto los símbolos) actúan como cadenas, incl No funciona así para un conjunto. No hay un "1" en nuestro set: `set.has('1')` devuelve `falso`. Tiene el tipo numérico `1`, `set.has(1)` devuelve `true`. -

@@ -821,7 +820,8 @@ for (let i = 1; i < 5; i++) {

#### Respuesta correcta: C -La sentencia `continue` omite una iteración si una cierta condición, en este caso `(i === 3)`, devuelve `true`. + +La sentencia `continue` omite una iteración si una cierta condición, en este caso `(i === 3)`, devuelve `true`.

@@ -837,7 +837,7 @@ String.prototype.giveLydiaPizza = () => { const name = "Lydia"; -console.log(name.giveLydiaPizza()) +console.log(name.giveLydiaPizza()); ``` - A: `"Just give Lydia pizza already!"` @@ -921,7 +921,7 @@ Después de que la _callback_ es empujada a la WebAPI, la función `setTimeout` -Ahora, `foo` es invocado, y ``"First"`` está siendo registrado. +Ahora, `foo` es invocado, y `"First"` está siendo registrado. @@ -949,9 +949,7 @@ Se invoca el `bar`, se registra el `"Second"` y se quita de la pila. ```html
- +
``` @@ -977,9 +975,7 @@ El elemento anidado más profundo que causa el evento es el destino de ese event ```html
-

- Click here! -

+

Click here!

``` @@ -1023,7 +1019,7 @@ sayHi.bind(person, 21); #### Respuesta correcta: D -En ambos podemos pasar el objeto al que queremos que se refiera la palabra reservada `this`. Sin embargo, la diferencia es que `.call` es *ejecutado inmediatamente*! +En ambos podemos pasar el objeto al que queremos que se refiera la palabra reservada `this`. Sin embargo, la diferencia es que `.call` es _ejecutado inmediatamente_! `.bind` devuelve una copia de la función, pero con un contexto enlazado. Es decir, no se ejecuta de inmediato. @@ -1091,7 +1087,6 @@ Solo hay seis valores falsos: - `''` (cadena vacía) - `false` - Los constructores de funciones, como `new Number` y `new Boolean` son correctos.

@@ -1215,7 +1210,10 @@ Lo que diferencia a un tipo primitivo de un objeto es que los primeros no tienen ###### 40. ¿Qué devuelve la siguiente función? ```javascript -[[0, 1], [2, 3]].reduce( +[ + [0, 1], + [2, 3], +].reduce( (acc, cur) => { return acc.concat(cur); }, @@ -1233,7 +1231,7 @@ Lo que diferencia a un tipo primitivo de un objeto es que los primeros no tienen #### Respuesta correcta: C -`[1, 2]` es nuestro valor inicial. Este es el valor con el que empezamos y el valor del primer `acc`. Durante la primera ronda, `acc` es` [1,2] `, y `cur` es `[0, 1]`. Los concatenamos, lo que resulta en `[1, 2, 0, 1]`. +`[1, 2]` es nuestro valor inicial. Este es el valor con el que empezamos y el valor del primer `acc`. Durante la primera ronda, `acc` es`[1,2]`, y `cur` es `[0, 1]`. Los concatenamos, lo que resulta en `[1, 2, 0, 1]`. Entonces, `[1, 2, 0, 1]` es `acc` y` [2, 3]` es `cur`. Los concatenamos, y obtenemos `[1, 2, 0, 1, 2, 3]` @@ -1363,7 +1361,7 @@ const secondPromise = new Promise((res, rej) => { setTimeout(res, 100, "two"); }); -Promise.race([firstPromise, secondPromise]).then(res => console.log(res)); +Promise.race([firstPromise, secondPromise]).then((res) => console.log(res)); ``` - A: `"one"` @@ -1427,7 +1425,7 @@ Solo estamos modificando el valor de la variable `person`, y no el primer elemen ```javascript const person = { name: "Lydia", - age: 21 + age: 21, }; for (const item in person) { @@ -1507,7 +1505,7 @@ Solo el primer número en el string es devuelto. Según en la _base_ seleccionad ###### 50. ¿Cuál es el resultado? ```javascript -[1, 2, 3].map(num => { +[1, 2, 3].map((num) => { if (typeof num === "number") return; return num * 2; }); @@ -1684,7 +1682,7 @@ class Dog { } } -Dog.prototype.bark = function() { +Dog.prototype.bark = function () { console.log(`Woof I am ${this.name}`); }; @@ -1912,7 +1910,7 @@ Las propiedades añadidas usando el método `defineProperty` son inmutables por const settings = { username: "lydiahallie", level: 19, - health: 90 + health: 90, }; const data = JSON.stringify(settings, ["level", "health"]); @@ -1946,7 +1944,7 @@ Si el reemplazador es una _función_, esta función es llamada en cada propiedad let num = 10; const increaseNumber = () => num++; -const increasePassedNumber = number => number++; +const increasePassedNumber = (number) => number++; const num1 = increaseNumber(); const num2 = increasePassedNumber(num1); @@ -2036,7 +2034,7 @@ El valor del acumulador es igual al valor previamente devuelto por la función d En la primera llamada, el acumulador (`x`) es `1`, y el valor actual (`y`) es `2`. No devolvemos desde la función de callback, mostramos por consola el acumulador y el valor actual: se muestra `1` y `2`. -Si no devuelves un valor de una función, se devuelve `undefined`. En la siguiente llamada, el acumulador es `undefined`, y el valor actual es `3`. Se muestra por consola `undefined` y `3`. +Si no devuelves un valor de una función, se devuelve `undefined`. En la siguiente llamada, el acumulador es `undefined`, y el valor actual es `3`. Se muestra por consola `undefined` y `3`. En la cuarta llamada, otra vez no devolvemos desde la función de callback. El acumulador es una vez más `undefined`, y el valor actual es `4`. Se muestra por consola `undefined` y `4`. @@ -2055,7 +2053,7 @@ class Dog { }; class Labrador extends Dog { - // 1 + // 1 constructor(name, size) { this.size = size; } @@ -2069,7 +2067,7 @@ class Labrador extends Dog { super(name); this.size = size; } - // 4 + // 4 constructor(name, size) { this.name = name; this.size = size; @@ -2103,12 +2101,12 @@ La clase `Labrador` recibe dos argumentos, `name` porque extiende de `Dog`, y `s ```javascript // index.js -console.log('running index.js'); -import { sum } from './sum.js'; +console.log("running index.js"); +import { sum } from "./sum.js"; console.log(sum(1, 2)); // sum.js -console.log('running sum.js'); +console.log("running sum.js"); export const sum = (a, b) => a + b; ``` @@ -2124,7 +2122,7 @@ export const sum = (a, b) => a + b; Con `import`, todos los módulos importados son _pre-convertidos_. Esto significa que los módulos importados son ejecutados _primero_, y el código en el fichero que importa el módulo se ejecuta _después_. -¡Esto es una diferencia existente entre `require()` en CommonJS e `import`! Con `require()`, puedes cargar dependencias bajo demanda mientras el código está siendo ejecutado. Si hubiéramos usado `require` en lugar de `import`, se habría mostrado por consola `running index.js`, `running sum.js`, `3`. +¡Esto es una diferencia existente entre `require()` en CommonJS e `import`! Con `require()`, puedes cargar dependencias bajo demanda mientras el código está siendo ejecutado. Si hubiéramos usado `require` en lugar de `import`, se habría mostrado por consola `running index.js`, `running sum.js`, `3`.

@@ -2134,9 +2132,9 @@ Con `import`, todos los módulos importados son _pre-convertidos_. Esto signific ###### 68. ¿Cuál es el resultado? ```javascript -console.log(Number(2) === Number(2)) -console.log(Boolean(false) === Boolean(false)) -console.log(Symbol('foo') === Symbol('foo')) +console.log(Number(2) === Number(2)); +console.log(Boolean(false) === Boolean(false)); +console.log(Symbol("foo") === Symbol("foo")); ``` - A: `true`, `true`, `false` @@ -2159,15 +2157,15 @@ Cada Symbol es completamente único. El propósito del argumento pasado a Symbol ###### 69. ¿Cuál es el resultado? ```javascript -const name = "Lydia Hallie" -console.log(name.padStart(13)) -console.log(name.padStart(2)) +const name = "Lydia Hallie"; +console.log(name.padStart(13)); +console.log(name.padStart(2)); ``` - A: `"Lydia Hallie"`, `"Lydia Hallie"` - B: `" Lydia Hallie"`, `" Lydia Hallie"` (`"[13 espacios en blanco]Lydia Hallie"`, `"[2 espacios en blanco]Lydia Hallie"`) - C: `" Lydia Hallie"`, `"Lydia Hallie"` (`"[1 espacio en blanco]Lydia Hallie"`, `"Lydia Hallie"`) -- D: `"Lydia Hallie"`, `"Lyd"`, +- D: `"Lydia Hallie"`, `"Lyd"`,
Solución

@@ -2435,7 +2433,7 @@ La función `sum` siempre devuelve el mismo resultado. Si pasamos `1` y `2`, _si ```javascript const add = () => { const cache = {}; - return num => { + return (num) => { if (num in cache) { return `From cache! ${cache[num]}`; } else { @@ -2480,21 +2478,21 @@ La tercera vez, pasamos `5 * 2` a la función, que se evalúa como `10`. El obje ###### 79. ¿Cuál es el resultado? ```javascript -const myLifeSummedUp = ["☕", "💻", "🍷", "🍫"] +const myLifeSummedUp = ["☕", "💻", "🍷", "🍫"]; for (let item in myLifeSummedUp) { - console.log(item) + console.log(item); } for (let item of myLifeSummedUp) { - console.log(item) + console.log(item); } ``` - A: `0` `1` `2` `3` y `"☕"` ` "💻"` `"🍷"` `"🍫"` - B: `"☕"` ` "💻"` `"🍷"` `"🍫"` y `"☕"` ` "💻"` `"🍷"` `"🍫"` - C: `"☕"` ` "💻"` `"🍷"` `"🍫"` y `0` `1` `2` `3` -- D: `0` `1` `2` `3` y `{0: "☕", 1: "💻", 2: "🍷", 3: "🍫"}` +- D: `0` `1` `2` `3` y `{0: "☕", 1: "💻", 2: "🍷", 3: "🍫"}`

Solución

@@ -2517,14 +2515,14 @@ Con un bucle _for-of_, podemos iterar sobre **iterables**. Un array es un iterab ###### 80. ¿Cuál es el resultado? ```javascript -const list = [1 + 2, 1 * 2, 1 / 2] -console.log(list) +const list = [1 + 2, 1 * 2, 1 / 2]; +console.log(list); ``` - A: `["1 + 2", "1 * 2", "1 / 2"]` - B: `["12", 2, 0.5]` - C: `[3, 2, 0.5]` -- D: `[1, 1, 1]` +- D: `[1, 1, 1]`

Solución

@@ -2544,16 +2542,16 @@ El elemento será igual al valor retornado. `1 + 2` devuelve `3`, `1 * 2` devuel ```javascript function sayHi(name) { - return `Hi there, ${name}` + return `Hi there, ${name}`; } -console.log(sayHi()) +console.log(sayHi()); ``` - A: `Hi there, ` - B: `Hi there, undefined` - C: `Hi there, null` -- D: `ReferenceError` +- D: `ReferenceError`

Solución

@@ -2576,21 +2574,21 @@ En ese caso, si no pasáramos un valor o si pasáramos `undefined`, `name` siemp ###### 82. ¿Cuál es el resultado? ```javascript -var status = "😎" +var status = "😎"; setTimeout(() => { - const status = "😍" + const status = "😍"; const data = { status: "🥑", getStatus() { - return this.status - } - } + return this.status; + }, + }; - console.log(data.getStatus()) - console.log(data.getStatus.call(this)) -}, 0) + console.log(data.getStatus()); + console.log(data.getStatus.call(this)); +}, 0); ``` - A: `"🥑"` y `"😍"` @@ -2617,13 +2615,13 @@ Con el método `call`, podemos cambiar el objeto al cual `this` referencia. En * ```javascript const person = { name: "Lydia", - age: 21 -} + age: 21, +}; -let city = person.city -city = "Amsterdam" +let city = person.city; +city = "Amsterdam"; -console.log(person) +console.log(person); ``` - A: `{ name: "Lydia", age: 21 }` @@ -2654,15 +2652,15 @@ Cuando se muestra por consola el objeto `person`, se devuelve el objeto sin modi ```javascript function checkAge(age) { if (age < 18) { - const message = "Sorry, you're too young." + const message = "Sorry, you're too young."; } else { - const message = "Yay! You're old enough!" + const message = "Yay! You're old enough!"; } - return message + return message; } -console.log(checkAge(21)) +console.log(checkAge(21)); ``` - A: `"Sorry, you're too young."` @@ -2685,15 +2683,15 @@ Las variables con `const` y `let` tienen _alcance de bloque_. Un bloque es cualq ###### 85. ¿Qué tipo de información se mostrará por consola? ```javascript -fetch('https://www.website.com/api/user/1') - .then(res => res.json()) - .then(res => console.log(res)) +fetch("https://www.website.com/api/user/1") + .then((res) => res.json()) + .then((res) => console.log(res)); ``` - A: El resultado del método `fetch`. - B: El resultado de la segunda invocación del método `fetch`. - C: El resultado de callback en el `.then()` anterior. -- D: Sería siempre `undefined`. +- D: Sería siempre `undefined`.

Solución

@@ -2741,7 +2739,7 @@ Asignándole a `hasName` el valor de `name`, asignas a `hasName` cualquier valor ###### 87. ¿Cuál es el resultado? ```javascript -console.log("I want pizza"[0]) +console.log("I want pizza"[0]); ``` - A: `"""` @@ -2767,10 +2765,10 @@ Observa que este método no está soportado en IE7 y versiones anteriores. En es ```javascript function sum(num1, num2 = num1) { - console.log(num1 + num2) + console.log(num1 + num2); } -sum(10) +sum(10); ``` - A: `NaN` @@ -2795,14 +2793,14 @@ Si estuvieras intentando asignar un valor por defecto a un parámetro igual a ot ###### 89. ¿Cuál es el resultado? ```javascript -// module.js -export default () => "Hello world" -export const name = "Lydia" +// module.js +export default () => "Hello world"; +export const name = "Lydia"; -// index.js -import * as data from "./module" +// index.js +import * as data from "./module"; -console.log(data) +console.log(data); ``` - A: `{ default: function default(), name: "Lydia" }` @@ -2829,12 +2827,12 @@ El objeto `data` tiene una propiedad `default` para la exportación por defecto, ```javascript class Person { constructor(name) { - this.name = name + this.name = name; } } -const member = new Person("John") -console.log(typeof member) +const member = new Person("John"); +console.log(typeof member); ``` - A: `"class"` @@ -2851,11 +2849,11 @@ Las clases son azúcar sintáctico para los constructores de funciones. El equiv ```javascript function Person() { - this.name = name + this.name = name; } ``` -Llamar a un constructor de funciones con `new` crea una instancia de `Person`, `typeof` devuelve `"object"` con una instancia. `typeof member` devuelve `"object"`. +Llamar a un constructor de funciones con `new` crea una instancia de `Person`, `typeof` devuelve `"object"` con una instancia. `typeof member` devuelve `"object"`.

@@ -2865,9 +2863,9 @@ Llamar a un constructor de funciones con `new` crea una instancia de `Person`, ` ###### 91. ¿Cuál es el resultado? ```javascript -let newList = [1, 2, 3].push(4) +let newList = [1, 2, 3].push(4); -console.log(newList.push(5)) +console.log(newList.push(5)); ``` - A: `[1, 2, 3, 4, 5]` @@ -2893,17 +2891,18 @@ Después, intentamos usar el método `.push` en `newList`. Como `newList` es el ```javascript function giveLydiaPizza() { - return "Here is pizza!" + return "Here is pizza!"; } -const giveLydiaChocolate = () => "Here's chocolate... now go hit the gym already." +const giveLydiaChocolate = () => + "Here's chocolate... now go hit the gym already."; -console.log(giveLydiaPizza.prototype) -console.log(giveLydiaChocolate.prototype) +console.log(giveLydiaPizza.prototype); +console.log(giveLydiaChocolate.prototype); ``` -- A: `{ constructor: ...}` `{ constructor: ...}` -- B: `{}` `{ constructor: ...}` +- A: `{ constructor: ...}` `{ constructor: ...}` +- B: `{}` `{ constructor: ...}` - C: `{ constructor: ...}` `{}` - D: `{ constructor: ...}` `undefined` @@ -2924,16 +2923,16 @@ Las funciones regulares, como la función `giveLydiaPizza`, tienen la propiedad ```javascript const person = { name: "Lydia", - age: 21 -} + age: 21, +}; for (const [x, y] of Object.entries(person)) { - console.log(x, y) + console.log(x, y); } ``` - A: `name` `Lydia` y `age` `21` -- B: `["name", "Lydia"]` y `["age", 21]` +- B: `["name", "Lydia"]` y `["age", 21]` - C: `["name", "age"]` y `undefined` - D: `Error` @@ -2944,7 +2943,7 @@ for (const [x, y] of Object.entries(person)) { `Object.entries(person)` devuelve un array de arrays anidados, conteniendo claves y objetos: -`[ [ 'name', 'Lydia' ], [ 'age', 21 ] ]` +`[ [ 'name', 'Lydia' ], [ 'age', 21 ] ]` Usando el bucle `for-of`, podemos iterar sobre cada elemento en el array, los subarrays en este caso. Podemos desestructurar los subarrays instantáneamente en el bucle for-of, usando `const [x, y]`. `x` es igual al primer elemento del subarray, `y` es igual al segundo elemento en el subarray. @@ -2968,7 +2967,7 @@ getItems(["banana", "apple"], "pear", "orange") ``` - A: `["banana", "apple", "pear", "orange"]` -- B: `[["banana", "apple"], "pear", "orange"]` +- B: `[["banana", "apple"], "pear", "orange"]` - C: `["banana", "apple", ["pear"], "orange"]` - D: `SyntaxError` @@ -2981,13 +2980,14 @@ getItems(["banana", "apple"], "pear", "orange") ```javascript function getItems(fruitList, favoriteFruit, ...args) { - return [...fruitList, ...args, favoriteFruit] + return [...fruitList, ...args, favoriteFruit]; } -getItems(["banana", "apple"], "pear", "orange") +getItems(["banana", "apple"], "pear", "orange"); ``` El ejemplo de arriba sí que funciona. Devuelve el array `[ 'banana', 'apple', 'orange', 'pear' ]` +

@@ -2997,17 +2997,14 @@ El ejemplo de arriba sí que funciona. Devuelve el array `[ 'banana', 'apple', ' ```javascript function nums(a, b) { - if - (a > b) - console.log('a is bigger') - else - console.log('b is bigger') - return - a + b + if (a > b) console.log("a is bigger"); + else console.log("b is bigger"); + return; + a + b; } -console.log(nums(4, 2)) -console.log(nums(1, 2)) +console.log(nums(4, 2)); +console.log(nums(1, 2)); ``` - A: `a is bigger`, `6` y `b is bigger`, `3` @@ -3020,13 +3017,13 @@ console.log(nums(1, 2)) #### Answer: B -En JavaScript, no _tenemos_ que escribir el punto y coma (`;`) de forma explicita, sin embargo el motor de JavaScript todavía las añade al final de cada sentencia. Esto se denomina **Insercción automática de punto y coma**. Una sentencia puede ser, por ejemplo, variables, o palabras clave como `throw`, `return`, `break`, etc. +En JavaScript, no _tenemos_ que escribir el punto y coma (`;`) de forma explicita, sin embargo el motor de JavaScript todavía las añade al final de cada sentencia. Esto se denomina **Insercción automática de punto y coma**. Una sentencia puede ser, por ejemplo, variables, o palabras clave como `throw`, `return`, `break`, etc. Aqui, escribimos una sentencia `return`, y otra sentencia de valor `a + b` en una _nueva línea_. Sin embargo, como es una línea nueva, el motor no sabe que en realidad es el valor que queríamos devolver. En cambio, añadió automáticamente un punto y coma después de `return`. Puedes ver esto como: ```javascript - return; - a + b +return; +a + b; ``` Esto significa que nunca se alcanza `a + b`, ya que una función deja de ejecutarse después de la palabra clave` return`. Si no se devuelve ningún valor, como aquí, la función devuelve `undefined`. ¡Ten en cuenta que no hay inserción automática después de las sentencias `if/else`! @@ -3041,18 +3038,18 @@ Esto significa que nunca se alcanza `a + b`, ya que una función deja de ejecuta ```javascript class Person { constructor() { - this.name = "Lydia" + this.name = "Lydia"; } } Person = class AnotherPerson { constructor() { - this.name = "Sarah" + this.name = "Sarah"; } -} +}; -const member = new Person() -console.log(member.name) +const member = new Person(); +console.log(member.name); ``` - A: `"Lydia"` @@ -3076,11 +3073,11 @@ Podemos establecer clases iguales a otros constructures de clases/funciones. En ```javascript const info = { - [Symbol('a')]: 'b' -} + [Symbol("a")]: "b", +}; -console.log(info) -console.log(Object.keys(info)) +console.log(info); +console.log(Object.keys(info)); ``` - A: `{Symbol('a'): 'b'}` y `["{Symbol('a')"]` @@ -3127,13 +3124,13 @@ console.log(getUser(user)) La función `getList` recibe un array argumento. Entre los paréntesis de la función `getList`, desestructuramos este array de inmediato. Podrías ver esto como: - `[x, ...y] = [1, 2, 3, 4]` +`[x, ...y] = [1, 2, 3, 4]` Con el parámetro rest `...y`, ponemos todos los argumentos "restantes" en un array. Los argumentos restantes son `2`, `3` and `4` en este caso. El valor de `y` es un array, conteniendo todos los parámetros restantes. El valor de `x` es igual a `1` en este caso, por la tanto cuando registramos `[x, y]`, se imprime `[1, [2, 3, 4]]`. - La función `getUser` recibe un objeto. Con las funciones flecha, no _tenemos_ que escribir llaves cuando simplemente devolvemos un valor. Sin embargo, si quieres devolver un _objeto_ desde una función llave, tienes que escribir el objeto entre paréntesis, ¡de otra manera no se devuelve ningún valor! La siguiente función habría devuelto un objeto: +La función `getUser` recibe un objeto. Con las funciones flecha, no _tenemos_ que escribir llaves cuando simplemente devolvemos un valor. Sin embargo, si quieres devolver un _objeto_ desde una función llave, tienes que escribir el objeto entre paréntesis, ¡de otra manera no se devuelve ningún valor! La siguiente función habría devuelto un objeto: -```const getUser = user => ({ name: user.name, age: user.age })``` +`const getUser = user => ({ name: user.name, age: user.age })` Como no se devuelve ningún valor en este caso, la función devuelve `undefined`. @@ -3145,9 +3142,9 @@ Como no se devuelve ningún valor en este caso, la función devuelve `undefined` ###### 99. ¿Cuál es el resultado? ```javascript -const name = "Lydia" +const name = "Lydia"; -console.log(name()) +console.log(name()); ``` - A: `SyntaxError` @@ -3160,11 +3157,11 @@ console.log(name()) #### Answer: C -La variable `name` contiene el valor de una cadena, que no es una función, por lo tanto no puede invocar. +La variable `name` contiene el valor de una cadena, que no es una función, por lo tanto no puede invocar. Se genera una excepción de tipo TypeError cuando un valor no es del tipo esperado. JavaScript esperaba que `name` fuera una función ya que estamos intentando invocarla. Era una cadena sin embargo, por lo tanto se lanza una excepción del tipo TypeError: name is not a function! -Se lanzan errores del tipo SyntaxError cuando has escrito algo que no es válido JavaScript, pro ejemplo cuando has escrito `return` como `retrun`. +Se lanzan errores del tipo SyntaxError cuando has escrito algo que no es válido JavaScript, pro ejemplo cuando has escrito `return` como `retrun`. Se lanzan errores del tipo ReferenceError cuando JavaScript no puede encontrar una referencia a un valor al que estás intentando acceder.

@@ -3177,8 +3174,8 @@ Se lanzan errores del tipo ReferenceError cuando JavaScript no puede encontrar u ```javascript // 🎉✨ This is my 100th question! ✨🎉 -const output = `${[] && 'Im'}possible! -You should${'' && `n't`} see a therapist after so much JavaScript lol` +const output = `${[] && "Im"}possible! +You should${"" && `n't`} see a therapist after so much JavaScript lol`; ``` - A: `possible! You should see a therapist after so much JavaScript lol` @@ -3203,11 +3200,11 @@ You should${'' && `n't`} see a therapist after so much JavaScript lol` ###### 101. ¿Cuál es el valor de la salida? ```javascript -const one = (false || {} || null) -const two = (null || false || "") -const three = ([] || 0 || true) +const one = false || {} || null; +const two = null || false || ""; +const three = [] || 0 || true; -console.log(one, two, three) +console.log(one, two, three); ``` - A: `false` `null` `[]` @@ -3236,20 +3233,20 @@ Con el operador `||`, podemos devolver el primer operando verdadero. Si todos lo ###### 102. ¿Cuál es el valor de la salida? ```javascript -const myPromise = () => Promise.resolve('I have resolved!') +const myPromise = () => Promise.resolve("I have resolved!"); function firstFunction() { - myPromise().then(res => console.log(res)) - console.log('second') + myPromise().then((res) => console.log(res)); + console.log("second"); } async function secondFunction() { - console.log(await myPromise()) - console.log('second') + console.log(await myPromise()); + console.log("second"); } -firstFunction() -secondFunction() +firstFunction(); +secondFunction(); ``` - A: `I have resolved!`, `second` y `I have resolved!`, `second` @@ -3264,13 +3261,13 @@ secondFunction() Con una promesa, básicamente decimos _Quiero ejecutar esta función, pero la dejaré a un lado por ahora mientras se está ejecutando, ya que esto puede llevar un tiempo. Solo cuando se resuelve (o se rechaza) un cierto valor, y cuando la pila de llamadas está vacía, quiero usar este valor._ -Podemos obtener este valor con las palabras clave `.then` y `await` en una función `async`. Aunque podemos obtener el valor de una promesa tanto con `.then` como con` wait ', funcionan de manera un poco diferente. +Podemos obtener este valor con las palabras clave `.then` y `await` en una función `async`. Aunque podemos obtener el valor de una promesa tanto con `.then` como con` wait ', funcionan de manera un poco diferente. -En la función `firstFunction`, dejamos (de algún modo) a un lado la función myPromise mientras se estaba ejecutando, y seguimos ejecutando el otro código, que es `console.log('second')` en este caso. Luego, la función se resolvió con la cadena `I have resolved`, que luego se imprimió una vez que pila de llamadas quedó vacía. +En la función `firstFunction`, dejamos (de algún modo) a un lado la función myPromise mientras se estaba ejecutando, y seguimos ejecutando el otro código, que es `console.log('second')` en este caso. Luego, la función se resolvió con la cadena `I have resolved`, que luego se imprimió una vez que pila de llamadas quedó vacía. Con la palabra clave await en `secondFunction`, literalmente hacemos una pausa en la ejecución de una función asíncrona hasta que el valor se haya resuelto antes de pasar a la siguiente línea de código. -Esto significa que se esperó a que `myPromise` resolviera con el valor `I have resolved`, y solo una vez que eso sucedió, pasamos a la siguiente línea: `second` que se imprime. +Esto significa que se esperó a que `myPromise` resolviera con el valor `I have resolved`, y solo una vez que eso sucedió, pasamos a la siguiente línea: `second` que se imprime.

@@ -3280,14 +3277,14 @@ Esto significa que se esperó a que `myPromise` resolviera con el valor `I have ###### 103. ¿Cuál es el valor de la salida? ```javascript -const set = new Set() +const set = new Set(); -set.add(1) -set.add("Lydia") -set.add({ name: "Lydia" }) +set.add(1); +set.add("Lydia"); +set.add({ name: "Lydia" }); for (let item of set) { - console.log(item + 2) + console.log(item + 2); } ``` @@ -3301,11 +3298,11 @@ for (let item of set) { #### Answer: C -El operador `+` no solo se usa para sumar valores numéricos, sino que también podemos usarlo para concatenar cadenas. Cada vez que el motor de JavaScript ve que uno o más valores no son un número, coerce el número en una cadena. +El operador `+` no solo se usa para sumar valores numéricos, sino que también podemos usarlo para concatenar cadenas. Cada vez que el motor de JavaScript ve que uno o más valores no son un número, coerce el número en una cadena. El primero es `1`, que es un valor numérico. `1 + 2` devuelve el número 3. -Sin embargo, el segundo es la cadena `"Lydia"`. `"Lydia"` es una cadena y `2` es un número: `2` coerce a una cadena. `"Lydia"` y `"2"` son concatenados, cuyo resultado es la cadena `"Lydia2"`. +Sin embargo, el segundo es la cadena `"Lydia"`. `"Lydia"` es una cadena y `2` es un número: `2` coerce a una cadena. `"Lydia"` y `"2"` son concatenados, cuyo resultado es la cadena `"Lydia2"`. `{ name: "Lydia" }` es un objeto. Ni un número ni un objeto son una cadena, así que se convierten a cadena ambos. Cada vez que convertimos un objeto estandar, se convierte en `"[Object object]"`. `"[Object object]"` concatenado con `"2"` resulta en `"[Object object]2"`. @@ -3317,7 +3314,7 @@ Sin embargo, el segundo es la cadena `"Lydia"`. `"Lydia"` es una cadena y `2` es ###### 104. ¿Cuál es el valor? ```javascript -Promise.resolve(5) +Promise.resolve(5); ``` - A: `5` @@ -3332,7 +3329,7 @@ Promise.resolve(5) Podemos pasar cualquier tipo de valor que queramos a `Promise.resolve`, ya sea una promesa o no promesa. El método en sí mismo devuelve una promesa con el valor resuelto (``). Si pasas una función estandar, será una promesa resuelta con un valor normal. Si pasas una promesa, será una promesa resuelta con el valor resuelto de esa promesa pasada. -En este caso, acabamos de pasar el valor numérico `5`. Devuelve una promesa resuelta con el valor `5`. +En este caso, acabamos de pasar el valor numérico `5`. Devuelve una promesa resuelta con el valor `5`.

@@ -3344,15 +3341,15 @@ En este caso, acabamos de pasar el valor numérico `5`. Devuelve una promesa res ```javascript function compareMembers(person1, person2 = person) { if (person1 !== person2) { - console.log("Not the same!") + console.log("Not the same!"); } else { - console.log("They are the same!") + console.log("They are the same!"); } } -const person = { name: "Lydia" } +const person = { name: "Lydia" }; -compareMembers(person) +compareMembers(person); ``` - A: `Not the same!` @@ -3365,13 +3362,13 @@ compareMembers(person) #### Answer: B -Los objetos se pasan por referencia. Cuando verificamos la igualdad estricta de los objetos (`===`), estamos comparando sus referencias. +Los objetos se pasan por referencia. Cuando verificamos la igualdad estricta de los objetos (`===`), estamos comparando sus referencias. Establecemos el valor por defecto para `person2` igual al objeto `person`, y pasamos el objeto `person` como el valor de `person1`. Esto significa que ambos valores tienen una referencia al mismo punto en la memoria, por lo tanto, son iguales. -El bloque de código en la instrucción `else` se ejecuta, y se imprime `They are the same!`. +El bloque de código en la instrucción `else` se ejecuta, y se imprime `They are the same!`.

@@ -3387,11 +3384,11 @@ const colorConfig = { green: true, black: true, yellow: false, -} +}; -const colors = ["pink", "red", "blue"] +const colors = ["pink", "red", "blue"]; -console.log(colorConfig.colors[1]) +console.log(colorConfig.colors[1]); ``` - A: `true` @@ -3404,11 +3401,11 @@ console.log(colorConfig.colors[1]) #### Answer: D -En JavaScript, tenemos dos formas de acceder a las propiedades de un objeto: notación por corchetes o notación por punto. En este ejemplo, usamos la notación por punto (`colorConfig.colors`) en lugar de la notación por corchetes (`colorConfig["colors"]`). +En JavaScript, tenemos dos formas de acceder a las propiedades de un objeto: notación por corchetes o notación por punto. En este ejemplo, usamos la notación por punto (`colorConfig.colors`) en lugar de la notación por corchetes (`colorConfig["colors"]`). Con la notación por punto, JavaScript intenta encontrar la propiedad en el objeto con ese nombre exacto. En este ejemplo, JavaScript intenta encontrar una propiedad llamada `colors` en el objeto `colorConfig`. No hay propiedad llamada `colors`, por lo que devuelve `undefined`. Luego, intentamos acceder al valor del primer elemento usando `[1]`. No podemos hacer esto en un valor que sea `undefined`, por lo que lanza una expeción `TypeError`: `Cannot read property '1' of undefined`. -JavaScript interpreta (o descompone) las sentencias. Cuando usamos la notación por corchetes, ve el primer corchete de apertura `[` y continúa hasta que encuentra el corchete de cierre `]`. Solo entonces, evaluará la declaración. Si hubiéramos utilizado `colorConfig[colors[1]]`, habría devuelto el valor de la propiedad `red` del objeto `colorConfig`. +JavaScript interpreta (o descompone) las sentencias. Cuando usamos la notación por corchetes, ve el primer corchete de apertura `[` y continúa hasta que encuentra el corchete de cierre `]`. Solo entonces, evaluará la declaración. Si hubiéramos utilizado `colorConfig[colors[1]]`, habría devuelto el valor de la propiedad `red` del objeto `colorConfig`.

@@ -3418,7 +3415,7 @@ JavaScript interpreta (o descompone) las sentencias. Cuando usamos la notación ###### 107. ¿Cuál es el valor? ```javascript -console.log('❤️' === '❤️') +console.log("❤️" === "❤️"); ``` - A: `true` @@ -3429,7 +3426,7 @@ console.log('❤️' === '❤️') #### Answer: A -Bajo el capó, los emojis son caracteres unicode. Los valores unicode para el emoji del corazón son `"U+2764 U+FE0F"`. Estos son siempre los mismos para los mismos emojis, por lo que estamos comparando dos cadenas iguales entre sí, lo que devuelve verdadero. +Bajo el capó, los emojis son caracteres unicode. Los valores unicode para el emoji del corazón son `"U+2764 U+FE0F"`. Estos son siempre los mismos para los mismos emojis, por lo que estamos comparando dos cadenas iguales entre sí, lo que devuelve verdadero.

@@ -3439,19 +3436,19 @@ Bajo el capó, los emojis son caracteres unicode. Los valores unicode para el em ###### 108. ¿Cuál de estos métodos modifica el array original? ```javascript -const emojis = ['✨', '🥑', '😍'] +const emojis = ["✨", "🥑", "😍"]; -emojis.map(x => x + '✨') -emojis.filter(x => x !== '🥑') -emojis.find(x => x !== '🥑') -emojis.reduce((acc, cur) => acc + '✨') -emojis.slice(1, 2, '✨') -emojis.splice(1, 2, '✨') +emojis.map((x) => x + "✨"); +emojis.filter((x) => x !== "🥑"); +emojis.find((x) => x !== "🥑"); +emojis.reduce((acc, cur) => acc + "✨"); +emojis.slice(1, 2, "✨"); +emojis.splice(1, 2, "✨"); ``` - A: `All of them` - B: `map` `reduce` `slice` `splice` -- C: `map` `slice` `splice` +- C: `map` `slice` `splice` - D: `splice`
Solución @@ -3459,7 +3456,7 @@ emojis.splice(1, 2, '✨') #### Answer: D -Con el método `splice`, modificamos el array original eliminando, reemplazando o agregando elementos. En este caso, eliminamos 2 elementos desde el índice 1 (eliminamos `'🥑'` y `'😍'`) y agregamos el emoji ✨ en su lugar. +Con el método `splice`, modificamos el array original eliminando, reemplazando o agregando elementos. En este caso, eliminamos 2 elementos desde el índice 1 (eliminamos `'🥑'` y `'😍'`) y agregamos el emoji ✨ en su lugar. `map`, `filter` y `slice` devuelven un nuevo array, `find` devuelve un elemento, y `reduce` devuelve un valor reducido. @@ -3471,17 +3468,17 @@ Con el método `splice`, modificamos el array original eliminando, reemplazando ###### 109. ¿Cuál es el resultado? ```javascript -const food = ['🍕', '🍫', '🥑', '🍔'] -const info = { favoriteFood: food[0] } +const food = ["🍕", "🍫", "🥑", "🍔"]; +const info = { favoriteFood: food[0] }; -info.favoriteFood = '🍝' +info.favoriteFood = "🍝"; -console.log(food) +console.log(food); ``` - A: `['🍕', '🍫', '🥑', '🍔']` - B: `['🍝', '🍫', '🥑', '🍔']` -- C: `['🍝', '🍕', '🍫', '🥑', '🍔']` +- C: `['🍝', '🍕', '🍫', '🥑', '🍔']` - D: `ReferenceError`
Solución @@ -3489,7 +3486,7 @@ console.log(food) #### Answer: A -Establecemos el valor de la propiedad `favoriteFood` en el objeto` info` igual a la cadena con el emoji de la pizza, `'🍕'`. Una cadena es un tipo de dato primitivo. En JavaScript, los tipos de datos primitivos actúan por referencia +Establecemos el valor de la propiedad `favoriteFood` en el objeto` info` igual a la cadena con el emoji de la pizza, `'🍕'`. Una cadena es un tipo de dato primitivo. En JavaScript, los tipos de datos primitivos actúan por referencia En JavaScript, los tipos de datos primitivos (todo aquello que no es un objeto) interactúan por _valor_. En este caso, establecemos el valor de la propiedad `favoriteFood` en el objeto` info` igual al valor del primer elemento en el array `food`, la cadena del emoji de la pizza en este caso (`'🍕'`). Una cadena es un tipo de datos primitivo e interactúa por valor (consulte mi [artículo](https://www.theavocoder.com/complete-javascript/2018/12/21/by-value-vs-by-reference) si estás interesado en aprender más) @@ -3503,7 +3500,7 @@ Luego, cambiamos el valor de la propiedad `favoriteFood` en el objeto` info`. El ###### 110. ¿Qué hace este método? ```javascript -JSON.parse() +JSON.parse(); ``` - A: Parses JSON to a JavaScript value @@ -3516,20 +3513,20 @@ JSON.parse() #### Answer: A -Con el método `JSON.parse()`, podemos convertir la cadena de texto en formato JSON a un valor en JavaScript. +Con el método `JSON.parse()`, podemos convertir la cadena de texto en formato JSON a un valor en JavaScript. ```javascript // Stringifying a number into valid JSON, then parsing the JSON string to a JavaScript value: -const jsonNumber = JSON.stringify(4) // '4' -JSON.parse(jsonNumber) // 4 +const jsonNumber = JSON.stringify(4); // '4' +JSON.parse(jsonNumber); // 4 // Stringifying an array value into valid JSON, then parsing the JSON string to a JavaScript value: -const jsonArray = JSON.stringify([1, 2, 3]) // '[1, 2, 3]' -JSON.parse(jsonArray) // [1, 2, 3] +const jsonArray = JSON.stringify([1, 2, 3]); // '[1, 2, 3]' +JSON.parse(jsonArray); // [1, 2, 3] // Stringifying an object into valid JSON, then parsing the JSON string to a JavaScript value: -const jsonArray = JSON.stringify({ name: "Lydia" }) // '{"name":"Lydia"}' -JSON.parse(jsonArray) // { name: 'Lydia' } +const jsonArray = JSON.stringify({ name: "Lydia" }); // '{"name":"Lydia"}' +JSON.parse(jsonArray); // { name: 'Lydia' } ```

@@ -3537,17 +3534,17 @@ JSON.parse(jsonArray) // { name: 'Lydia' } --- -###### 111. ¿Cuál es el resultado? +###### 111. ¿Cuál es el resultado? ```javascript -let name = 'Lydia' +let name = "Lydia"; function getName() { - console.log(name) - let name = 'Sarah' + console.log(name); + let name = "Sarah"; } -getName() +getName(); ``` - A: Lydia @@ -3560,20 +3557,20 @@ getName() #### Answer: D -Cada función tiene su propio _contexto de ejecución_ (o _ámbito_). La función `getName` primero mira dentro de su propio contexto (ámbito) para ver si contiene la variable `name` a la que estamos intentando acceder. En este caso, la función `getName` contiene su propia variable `name`: declaramos la variable `name` con la palabra clave` let`, y con el valor de `'Sarah'`. +Cada función tiene su propio _contexto de ejecución_ (o _ámbito_). La función `getName` primero mira dentro de su propio contexto (ámbito) para ver si contiene la variable `name` a la que estamos intentando acceder. En este caso, la función `getName` contiene su propia variable `name`: declaramos la variable `name` con la palabra clave` let`, y con el valor de `'Sarah'`. -Las variables con la palabra clave `let` (y `const`) se mueven al comienzo (hoisting), pero a diferencia de `var`, no se inicializan. No son accesibles antes de la línea en la que las declaramos (inicializamos). Esto se llama la "zona muerta temporal". Cuando intentamos acceder a las variables antes de que se declaren, JavaScript genera una excepción del tipo `ReferenceError`. +Las variables con la palabra clave `let` (y `const`) se mueven al comienzo (hoisting), pero a diferencia de `var`, no se inicializan. No son accesibles antes de la línea en la que las declaramos (inicializamos). Esto se llama la "zona muerta temporal". Cuando intentamos acceder a las variables antes de que se declaren, JavaScript genera una excepción del tipo `ReferenceError`. -Si no hubiéramos declarado la variable `name` dentro de la función `getName`, el motor de JavaScript habría mirado hacia abajo _ámbito encadenado_. El alcance externo tiene una variable llamada `name` con el valor de `Lydia`. En ese caso, habría imprimido `Lydia`. +Si no hubiéramos declarado la variable `name` dentro de la función `getName`, el motor de JavaScript habría mirado hacia abajo _ámbito encadenado_. El alcance externo tiene una variable llamada `name` con el valor de `Lydia`. En ese caso, habría imprimido `Lydia`. ```javascript -let name = 'Lydia' +let name = "Lydia"; function getName() { - console.log(name) + console.log(name); } -getName() // Lydia +getName(); // Lydia ```

@@ -3585,18 +3582,18 @@ getName() // Lydia ```javascript function* generatorOne() { - yield ['a', 'b', 'c']; + yield ["a", "b", "c"]; } function* generatorTwo() { - yield* ['a', 'b', 'c']; + yield* ["a", "b", "c"]; } -const one = generatorOne() -const two = generatorTwo() +const one = generatorOne(); +const two = generatorTwo(); -console.log(one.next().value) -console.log(two.next().value) +console.log(one.next().value); +console.log(two.next().value); ``` - A: `a` y `a` @@ -3614,17 +3611,17 @@ Con la palabra clave `yield`, cedemos valores en una función generadora. Con la En la función `generatorOne`, cedemos todo el array `['a', 'b', 'c']` usando la palabra clave `yield`. El valor de la propiedad `value` en el objeto devuelto por el método `next` en `one` (`one.next().value`) es igual a todo el array `['a', 'b', 'c']`. ```javascript -console.log(one.next().value) // ['a', 'b', 'c'] -console.log(one.next().value) // undefined +console.log(one.next().value); // ['a', 'b', 'c'] +console.log(one.next().value); // undefined ``` -En la función `generatorTwo`, usamos la palabra clave `yield*`. Esto significa que el primer valor cedido de `two` es igual al primer valor cedido en el iterador. El iterador es el array `['a', 'b', 'c']`. El primer valor producido es `a`, por lo que la primera vez que llamamos a `two.next().value`, se devuelve `a`. +En la función `generatorTwo`, usamos la palabra clave `yield*`. Esto significa que el primer valor cedido de `two` es igual al primer valor cedido en el iterador. El iterador es el array `['a', 'b', 'c']`. El primer valor producido es `a`, por lo que la primera vez que llamamos a `two.next().value`, se devuelve `a`. ```javascript -console.log(two.next().value) // 'a' -console.log(two.next().value) // 'b' -console.log(two.next().value) // 'c' -console.log(two.next().value) // undefined +console.log(two.next().value); // 'a' +console.log(two.next().value); // 'b' +console.log(two.next().value); // 'c' +console.log(two.next().value); // undefined ```

@@ -3635,7 +3632,7 @@ console.log(two.next().value) // undefined ###### 113. ¿Cuál es el resultado? ```javascript -console.log(`${(x => x)('I love')} to program`) +console.log(`${((x) => x)("I love")} to program`); ``` - A: `I love to program` @@ -3648,7 +3645,7 @@ console.log(`${(x => x)('I love')} to program`) #### Answer: A -Las expresiones dentro de las plantillas de cadena de texto se evalúan primero. Esto significa que la cadena contendrá el valor devuelto de la expresión, la función invocada inmediatamente `(x => x)('I love')` en este caso. Pasamos el valor `'I love'` como argumento para la función de flecha `x => x`. `x` es igual a `'I love'`, que se devuelve tal cual. Esto da como resultado `I love to program`. +Las expresiones dentro de las plantillas de cadena de texto se evalúan primero. Esto significa que la cadena contendrá el valor devuelto de la expresión, la función invocada inmediatamente `(x => x)('I love')` en este caso. Pasamos el valor `'I love'` como argumento para la función de flecha `x => x`. `x` es igual a `'I love'`, que se devuelve tal cual. Esto da como resultado `I love to program`.

@@ -3660,11 +3657,11 @@ Las expresiones dentro de las plantillas de cadena de texto se evalúan primero. ```javascript let config = { alert: setInterval(() => { - console.log('Alert!') - }, 1000) -} + console.log("Alert!"); + }, 1000), +}; -config = null +config = null; ``` - A: The `setInterval` callback won't be invoked @@ -3687,17 +3684,17 @@ Normalmente, cuando establecemos objetos iguales a `null`, esos objetos se recog ###### 115. ¿Qué método(s) devolverá el valor `'Hello world!'`? ```javascript -const myMap = new Map() -const myFunc = () => 'greeting' +const myMap = new Map(); +const myFunc = () => "greeting"; -myMap.set(myFunc, 'Hello world!') +myMap.set(myFunc, "Hello world!"); //1 -myMap.get('greeting') +myMap.get("greeting"); //2 -myMap.get(myFunc) +myMap.get(myFunc); //3 -myMap.get(() => 'greeting') +myMap.get(() => "greeting"); ``` - A: 1 @@ -3710,10 +3707,10 @@ myMap.get(() => 'greeting') #### Answer: B -Al agregar un par clave/valor utilizando el método `set`, la clave será el valor del primer argumento pasado a la función `set`, y el valor será el segundo argumento pasado a la función `set`. La clave es la _función_ `() => 'greeting'` en este caso, y el valor `'Hello world'`. `myMap` ahora es `{ () => 'greeting' => 'Hello world!' }`. +Al agregar un par clave/valor utilizando el método `set`, la clave será el valor del primer argumento pasado a la función `set`, y el valor será el segundo argumento pasado a la función `set`. La clave es la _función_ `() => 'greeting'` en este caso, y el valor `'Hello world'`. `myMap` ahora es `{ () => 'greeting' => 'Hello world!' }`. 1 es incorrecto, ya que la clave no es `'greeting'` sino `() => 'greeting'`. -3 es incorrecto, ya que estamos creando una nueva función pasándola como parámetro al método `get`. El objeto interactúa por _referencia_. Las funciones son objetos, por eso dos funciones nunca son estrictamente iguales, aunque sean idénticas: tienen una referencia a un punto diferente en la memoria. +3 es incorrecto, ya que estamos creando una nueva función pasándola como parámetro al método `get`. El objeto interactúa por _referencia_. Las funciones son objetos, por eso dos funciones nunca son estrictamente iguales, aunque sean idénticas: tienen una referencia a un punto diferente en la memoria.

@@ -3725,19 +3722,19 @@ Al agregar un par clave/valor utilizando el método `set`, la clave será el val ```javascript const person = { name: "Lydia", - age: 21 -} + age: 21, +}; -const changeAge = (x = { ...person }) => x.age += 1 +const changeAge = (x = { ...person }) => (x.age += 1); const changeAgeAndName = (x = { ...person }) => { - x.age += 1 - x.name = "Sarah" -} + x.age += 1; + x.name = "Sarah"; +}; -changeAge(person) -changeAgeAndName() +changeAge(person); +changeAgeAndName(); -console.log(person) +console.log(person); ``` - A: `{name: "Sarah", age: 22}` @@ -3750,7 +3747,7 @@ console.log(person) #### Answer: C -Tanto las funciones `changeAge` como `changeAgeAndName` tienen un parámetro por defecto, a saber, un objeto _nuevo_ creado `{ ...person }`. Este objeto tiene copias de todos los pares clave/valor en el objeto `person`. +Tanto las funciones `changeAge` como `changeAgeAndName` tienen un parámetro por defecto, a saber, un objeto _nuevo_ creado `{ ...person }`. Este objeto tiene copias de todos los pares clave/valor en el objeto `person`. Primero, invocamos la función `changeAge` y le pasamos el objeto `person` como argumento. Esta función aumenta el valor de la propiedad `age` en 1. `person` ahora es `{name: "Lydia", age: 22}`. diff --git a/fr-FR/README_fr-FR.md b/fr-FR/README_fr-FR.md index cce10323..cbdbee30 100644 --- a/fr-FR/README_fr-FR.md +++ b/fr-FR/README_fr-FR.md @@ -19,6 +19,7 @@ Les réponses se trouvent dans les sections repliées en dessous des questions, - [🇳🇱 Nederlands](../nl-NL/README.md) - [🇵🇱 Polski](../pl-PL/README.md) - [🇧🇷 Português Brasil](../pt-BR/README_pt_BR.md) +- [🇷o Română](../ro-RO/README.ro.md) - [🇷🇺 Русский](../ru-RU/README.md) - [🇽🇰 Shqip](../sq-KS/README_sq_KS.md) - [🇹🇭 ไทย](../th-TH/README-th_TH.md) @@ -100,7 +101,7 @@ const shape = { diameter() { return this.radius * 2; }, - perimeter: () => 2 * Math.PI * this.radius + perimeter: () => 2 * Math.PI * this.radius, }; shape.diameter(); @@ -157,12 +158,12 @@ La chaîne de caractère `'Lydia'` est une valeur considérée comme vraie _(tru ```javascript const bird = { - size: "small" + size: "small", }; const mouse = { name: "Mickey", - small: true + small: true, }; ``` @@ -358,7 +359,7 @@ function Person(firstName, lastName) { } const member = new Person("Lydia", "Hallie"); -Person.getFullName = function() { +Person.getFullName = function () { return `${this.firstName} ${this.lastName}`; }; @@ -378,7 +379,7 @@ console.log(member.getFullName()); Vous ne pouvez pas ajouter de propriétés à un constructeur comme pour des objets normaux. Si vous voulez ajouter une fonctionnalité pour tous les objets en une fois, vous devez utiliser le prototype. Donc dans ce cas, ```js -Person.prototype.getFullName = function() { +Person.prototype.getFullName = function () { return `${this.firstName} ${this.lastName}`; }; ``` @@ -834,7 +835,7 @@ String.prototype.giveLydiaPizza = () => { const name = "Lydia"; -console.log(name.giveLydiaPizza()) +console.log(name.giveLydiaPizza()); ``` - A: `"Just give Lydia pizza already!"` @@ -946,9 +947,7 @@ C'est ici qu'une boucle d'événement commence à fonctionner. La **boucle d'év ```html
- +
``` @@ -974,9 +973,7 @@ L'élément imbriqué le plus profond qui a provoqué l'événement est la cible ```html
-

- Click here! -

+

Click here!

``` @@ -1201,7 +1198,7 @@ JavaScript n'a que des types et des objets primitifs. Les types primitifs sont `boolean`, `null`, `undefined`, `bigint`, `number`, `string` et `symbol`. -Ce qui différencie une primitive d'un objet, c'est que les primitives n'ont aucune propriété ou méthode. Cependant, vous remarquerez que `'foo'.toUpperCase()` est évalué à `'FOO'` et n'entraîne pas de `TypeError`. En effet, lorsque vous essayez d'accéder à une propriété ou à une méthode sur une primitive telle qu'une chaîne, JavaScript encapsule implicitement l'objet à l'aide de l'une des classes d'encapsulation, à savoir `String`, puis supprime immédiatement l'encapsulation après l'évaluation de l'expression. Toutes les primitives à l'exception de `null` et` undefined` présentent ce comportement. +Ce qui différencie une primitive d'un objet, c'est que les primitives n'ont aucune propriété ou méthode. Cependant, vous remarquerez que `'foo'.toUpperCase()` est évalué à `'FOO'` et n'entraîne pas de `TypeError`. En effet, lorsque vous essayez d'accéder à une propriété ou à une méthode sur une primitive telle qu'une chaîne, JavaScript encapsule implicitement l'objet à l'aide de l'une des classes d'encapsulation, à savoir `String`, puis supprime immédiatement l'encapsulation après l'évaluation de l'expression. Toutes les primitives à l'exception de `null` et` undefined` présentent ce comportement.

@@ -1211,7 +1208,10 @@ Ce qui différencie une primitive d'un objet, c'est que les primitives n'ont auc ###### 40. Quelle est la sortie ? ```javascript -[[0, 1], [2, 3]].reduce( +[ + [0, 1], + [2, 3], +].reduce( (acc, cur) => { return acc.concat(cur); }, @@ -1359,7 +1359,7 @@ const secondPromise = new Promise((res, rej) => { setTimeout(res, 100, "two"); }); -Promise.race([firstPromise, secondPromise]).then(res => console.log(res)); +Promise.race([firstPromise, secondPromise]).then((res) => console.log(res)); ``` - A: `"one"` @@ -1423,7 +1423,7 @@ Nous modifions seulement la valeur de la variable `person`, et non le premier é ```javascript const person = { name: "Lydia", - age: 21 + age: 21, }; for (const item in person) { @@ -1503,7 +1503,7 @@ Seuls les premiers nombres de la chaîne sont renvoyés. Basé sur la base dix ( ###### 50. Quelle est la sortie ? ```javascript -[1, 2, 3].map(num => { +[1, 2, 3].map((num) => { if (typeof num === "number") return; return num * 2; }); @@ -1680,7 +1680,7 @@ class Dog { } } -Dog.prototype.bark = function() { +Dog.prototype.bark = function () { console.log(`Woof I am ${this.name}`); }; @@ -1908,7 +1908,7 @@ Les propriétés ajoutées à l'aide de la méthode `defineProperty` sont immuab const settings = { username: "lydiahallie", level: 19, - health: 90 + health: 90, }; const data = JSON.stringify(settings, ["level", "health"]); @@ -1942,7 +1942,7 @@ Si le remplaçant est une _fonction_, cette fonction est appelée sur chaque pro let num = 10; const increaseNumber = () => num++; -const increasePassedNumber = number => number++; +const increasePassedNumber = (number) => number++; const num1 = increaseNumber(); const num2 = increasePassedNumber(num1); @@ -1963,7 +1963,7 @@ console.log(num2); L'opérateur arithmétique `++` _renvoie en premier_ la valeur de l'opérande, _puis incrémente_ la valeur de l'opérande. La valeur de `num1` est égale à `10`, puisque la fonction `increaseNumber` renvoie d'abord la valeur de `num`, qui correspond à `10`, et augmente la valeur de `num` par la suite. -`num2` est égal à `10`, puisque nous avons passé `num1` à la commande `increasePassedNumber`. `number` est égal à `10` (la valeur de `num1`). Encore une fois, l'opérateur arithmétique `++` _renvoie d'abord_ la valeur de l'opérande, puis incrémente_ la valeur de l'opérande. La valeur de `nombre` est `10`, donc `num2` est égal à `10`. +`num2` est égal à `10`, puisque nous avons passé `num1` à la commande `increasePassedNumber`. `number` est égal à `10` (la valeur de `num1`). Encore une fois, l'opérateur arithmétique `++` _renvoie d'abord_ la valeur de l'opérande, puis incrémente\_ la valeur de l'opérande. La valeur de `nombre` est `10`, donc `num2` est égal à `10`.

@@ -1997,7 +1997,7 @@ multiply(value); Dans ES6, nous pouvons initialiser les paramètres avec une valeur par défaut. La valeur du paramètre sera la valeur par défaut, si aucune autre valeur n'a été passée à la fonction, ou si la valeur du paramètre est `"undefined"`. Dans ce cas, nous répartissons les propriétés de l'objet `value` dans un nouvel objet, donc `x` a la valeur par défaut `{number: 10}`. -L'argument par défaut est évalué at _call time_! Chaque fois que nous appelons la fonction, un a _new_ object créé. Nous invoquons la fonction `multiply` les deux premières fois sans passer de valeur: `x` a la valeur par défaut `{number: 10}`. Nous enregistrons ensuite la valeur multipliée de ce nombre, qui est `20`. +L'argument par défaut est évalué at _call time_! Chaque fois que nous appelons la fonction, un a _new_ object créé. Nous invoquons la fonction `multiply` les deux premières fois sans passer de valeur: `x` a la valeur par défaut `{number: 10}`. Nous enregistrons ensuite la valeur multipliée de ce nombre, qui est `20`. La troisième fois que nous invoquons multiplier, nous passons un argument: l'objet appelé `value`. L'opérateur `* =` est en fait un raccourci pour `x.number = x.number * 2`: nous modifions la valeur de `x.number`, et enregistrons la valeur multipliée `20`. diff --git a/id-ID/README.md b/id-ID/README.md index 26a566cc..3da87c42 100644 --- a/id-ID/README.md +++ b/id-ID/README.md @@ -1,10 +1,10 @@

Pertanyaan JavaScript

- --- +--- - Saya post pertanyaan pilihan ganda ke [Instagram](https://www.instagram.com/theavocoder) **stories** saya, yang saya post juga di sini ! update terakhir: December 24th +Saya post pertanyaan pilihan ganda ke [Instagram](https://www.instagram.com/theavocoder) **stories** saya, yang saya post juga di sini ! update terakhir: December 24th - Mulai tingkat dasar ke mahir: tes seberapa paham kamu tentang javascript, segarkan sedikit pengetahuan kamu, atau bersiap-siap untuk coding interview kamu! :muscle: :rocket: Saya update repo ini secara berkala dengan pertanyaan baru. Saya masukkan jawaban dibagian yang **tersembunyi** di bawah pertanyaan, cukup klik pada bagian itu untuk menampilkannya. Pertanyaan ini hanya untuk bersenang-senang, Semoga berhasil :heart: +Mulai tingkat dasar ke mahir: tes seberapa paham kamu tentang javascript, segarkan sedikit pengetahuan kamu, atau bersiap-siap untuk coding interview kamu! :muscle: :rocket: Saya update repo ini secara berkala dengan pertanyaan baru. Saya masukkan jawaban dibagian yang **tersembunyi** di bawah pertanyaan, cukup klik pada bagian itu untuk menampilkannya. Pertanyaan ini hanya untuk bersenang-senang, Semoga berhasil :heart: Jangan sungkan untuk terhubung dengan saya! 😊
Instagram || Twitter || LinkedIn || Blog @@ -29,6 +29,7 @@ Jangan sungkan untuk terhubung dengan saya! 😊
- [🇳🇱 Nederlands](../nl-NL/README.md) - [🇵🇱 Polski](../pl-PL/README.md) - [🇧🇷 Português Brasil](../pt-BR/README_pt_BR.md) +- [🇷o Română](../ro-RO/README.ro.md) - [🇷🇺 Русский](../ru-RU/README.md) - [🇽🇰 Shqip](../sq-KS/README_sq_KS.md) - [🇹🇭 ไทย](../th-TH/README-th_TH.md) @@ -49,7 +50,7 @@ Jangan sungkan untuk terhubung dengan saya! 😊
function sayHi() { console.log(name); console.log(age); - var name = 'Lydia'; + var name = "Lydia"; let age = 21; } @@ -69,6 +70,7 @@ sayHi(); Di dalam function, kita membuat sebuah variabel `name` dan variabel tersebut di deklarasikan menggunakan `var`. Artinya variable tersebut di hoisting (dalam fase pembuatan ini menggunakan memory penyimpanan) dengan isi standar-nya `undefined`, saat javascript mengeksekusi baris code pembuatan variabel-nya. variabel `name` isinya masih undefined, jadi isi dari variabel tersebut `undefined` Mendeklarasikan varibel menggunakan `let` (dan `const`) juga terkena hoisting, tidak seperti `var`, variabel declaration `let` dan `const` tidak ditentukan isi standar-nya. `let` dan `const` tidak bisa diakses sebelum di tentukan dulu isi-nya. Kejadian ini disebut "temporal dead zone". Saat kita mencoba memanggil variabel yang belum ditentukan isi-nya, Javascript mengeluarkan error `ReferenceError`. +

@@ -95,9 +97,10 @@ for (let i = 0; i < 3; i++) { #### Jawaban: C -Karena antrean peristiwa di JavaScript, fungsi callback `setTimeout` disebut _after_ loop telah dijalankan. Karena variabel `i` di loop pertama dideklarasikan menggunakan kata kunci` var`, nilai ini adalah global. Selama perulangan, kita menambah nilai `i` sebesar `1` setiap kali, menggunakan operator unary` ++ `. Pada saat fungsi callback `setTimeout` dipanggil,` i` sama dengan `3` di contoh pertama. +Karena antrean peristiwa di JavaScript, fungsi callback `setTimeout` disebut _after_ loop telah dijalankan. Karena variabel `i` di loop pertama dideklarasikan menggunakan kata kunci` var`, nilai ini adalah global. Selama perulangan, kita menambah nilai `i` sebesar `1` setiap kali, menggunakan operator unary`++`. Pada saat fungsi callback `setTimeout` dipanggil,` i` sama dengan `3` di contoh pertama. Pada perulangan kedua, variabel `i` dideklarasikan menggunakan kata kunci` let`: variabel yang dideklarasikan dengan kata kunci `let` (dan` const`) memiliki cakupan blok (blok adalah apa saja di antara `{}`). Selama setiap iterasi, `i` akan memiliki nilai baru, dan setiap nilai dicakup di dalam loop. +

@@ -143,7 +146,7 @@ Tidak ada nilai 'radius' pada objek itu, yang mengembalikan 'tidak ditentukan'. ```javascript +true; -!'Lydia'; +!"Lydia"; ``` - A: `1` dan `false` @@ -157,8 +160,7 @@ Tidak ada nilai 'radius' pada objek itu, yang mengembalikan 'tidak ditentukan'. Tia unary plus mencoba mengonversi operan menjadi angka. `true` adalah` 1`, dan `false` adalah` 0`. -String "'Lydia'` adalah nilai yang benar. Apa yang sebenarnya kami tanyakan adalah "apakah nilai kebenaran ini salah?". Ini mengembalikan `salah`. - +String "'Lydia'`adalah nilai yang benar. Apa yang sebenarnya kami tanyakan adalah "apakah nilai kebenaran ini salah?". Ini mengembalikan`salah`.

@@ -169,11 +171,11 @@ String "'Lydia'` adalah nilai yang benar. Apa yang sebenarnya kami tanyakan adal ```javascript const bird = { - size: 'small', + size: "small", }; const mouse = { - name: 'Mickey', + name: "Mickey", small: true, }; ``` @@ -187,6 +189,7 @@ const mouse = {

#### Jawaban: A + Pada JavaScript, semua kunci objek adalah string (kecuali jika itu berupa Simbol). Meskipun kita mungkin tidak mengetiknya sebagai string, tetap saja mereka selalu berubah menjadi string didalamnya. JavaScript menginterpretasikan (atau membuka) pernyataan-pernyataan. Saat kita menggunakan notasi kurung siku, ia melihat kurung buka pertama `[` dan terus berjalan sampai menemukan kurung tutup `]`. Baru setelah itu akan mengevaluasi pernyataannya. `mouse[bird.size]`: Pertama, ini mengevaluasi `bird.size`, yang mana `"small"`. `mouse["small"]` mengembalikan nilai `true`. @@ -201,11 +204,11 @@ Namun, dengan notasi dot (.), hal ini tidak terjadi. `mouse` tidak memiliki kunc ###### 6. Apa yang akan tampil? ```javascript -let c = { greeting: 'Hey!' }; +let c = { greeting: "Hey!" }; let d; d = c; -c.greeting = 'Hello'; +c.greeting = "Hello"; console.log(d.greeting); ``` @@ -275,13 +278,13 @@ class Chameleon { return this.newColor; } - constructor({ newColor = 'green' } = {}) { + constructor({ newColor = "green" } = {}) { this.newColor = newColor; } } -const freddie = new Chameleon({ newColor: 'purple' }); -console.log(freddie.colorChange('orange')); +const freddie = new Chameleon({ newColor: "purple" }); +console.log(freddie.colorChange("orange")); ``` - A: `orange` @@ -331,10 +334,10 @@ Untuk menghindari hal ini, kita bisa menggunakan `" use strict "`. Ini memastika ```javascript function bark() { - console.log('Woof!'); + console.log("Woof!"); } -bark.animal = 'dog'; +bark.animal = "dog"; ``` - A: Nothing, this is totally fine! @@ -364,8 +367,8 @@ function Person(firstName, lastName) { this.lastName = lastName; } -const member = new Person('Lydia', 'Hallie'); -Person.getFullName = function() { +const member = new Person("Lydia", "Hallie"); +Person.getFullName = function () { return `${this.firstName} ${this.lastName}`; }; @@ -385,7 +388,7 @@ console.log(member.getFullName()); Anda tidak dapat menambahkan properti ke constructor seperti yang Anda lakukan dengan objek biasa. Jika Anda ingin menambahkan fitur ke semua objek sekaligus, Anda harus menggunakan prototipe sebagai gantinya. Jadi dalam kasus ini: ```js -Person.prototype.getFullName = function() { +Person.prototype.getFullName = function () { return `${this.firstName} ${this.lastName}`; }; ``` @@ -405,8 +408,8 @@ function Person(firstName, lastName) { this.lastName = lastName; } -const lydia = new Person('Lydia', 'Hallie'); -const sarah = Person('Sarah', 'Smith'); +const lydia = new Person("Lydia", "Hallie"); +const sarah = Person("Sarah", "Smith"); console.log(lydia); console.log(sarah); @@ -476,7 +479,7 @@ function sum(a, b) { return a + b; } -sum(1, '2'); +sum(1, "2"); ``` - A: `NaN` @@ -543,7 +546,7 @@ function getPersonInfo(one, two, three) { console.log(three); } -const person = 'Lydia'; +const person = "Lydia"; const age = 21; getPersonInfo`${person} is ${age} years old`; @@ -570,9 +573,9 @@ Jika Anda menggunakan literal template yang diberi tag, nilai argumen pertama se ```javascript function checkAge(data) { if (data === { age: 18 }) { - console.log('You are an adult!'); + console.log("You are an adult!"); } else if (data == { age: 18 }) { - console.log('You are still an adult.'); + console.log("You are still an adult."); } else { console.log(`Hmm.. You don't have an age I guess`); } @@ -632,7 +635,7 @@ Parameter sisanya (`... args`.) Memungkinkan kita "mengumpulkan" semua argumen y ```javascript function getAge() { - 'use strict'; + "use strict"; age = 21; console.log(age); } @@ -660,7 +663,7 @@ Dengan `" use strict "`, Anda dapat memastikan bahwa Anda tidak mendeklarasikan ###### 21. What's value of `sum`? ```javascript -const sum = eval('10*10+5'); +const sum = eval("10*10+5"); ``` - A: `105` @@ -683,7 +686,7 @@ const sum = eval('10*10+5'); ###### 22. Sampai berapa lama kah cool_secret dapat diakses? ```javascript -sessionStorage.setItem('cool_secret', 123); +sessionStorage.setItem("cool_secret", 123); ``` - A: Selamanya, data tersebut tidak akan hilang. @@ -736,12 +739,12 @@ Anda tidak dapat melakukan ini dengan `let` atau `const` karena mereka block-sco ###### 24. Apa yang akan tampil? ```javascript -const obj = { 1: 'a', 2: 'b', 3: 'c' }; +const obj = { 1: "a", 2: "b", 3: "c" }; const set = new Set([1, 2, 3, 4, 5]); -obj.hasOwnProperty('1'); +obj.hasOwnProperty("1"); obj.hasOwnProperty(1); -set.has('1'); +set.has("1"); set.has(1); ``` @@ -767,7 +770,7 @@ It doesn't work that way for a set. There is no `'1'` in our set: `set.has('1')` ###### 25. Apa yang akan tampil? ```javascript -const obj = { a: 'one', b: 'two', a: 'three' }; +const obj = { a: "one", b: "two", a: "three" }; console.log(obj); ``` @@ -836,12 +839,12 @@ Pernyataan `continue` melewatkan iterasi jika kondisi tertentu mengembalikan `tr ```javascript String.prototype.giveLydiaPizza = () => { - return 'Just give Lydia pizza already!'; + return "Just give Lydia pizza already!"; }; -const name = 'Lydia'; +const name = "Lydia"; -console.log(name.giveLydiaPizza()) +console.log(name.giveLydiaPizza()); ``` - A: `"Just give Lydia pizza already!"` @@ -865,8 +868,8 @@ console.log(name.giveLydiaPizza()) ```javascript const a = {}; -const b = { key: 'b' }; -const c = { key: 'c' }; +const b = { key: "b" }; +const c = { key: "c" }; a[b] = 123; a[c] = 456; @@ -898,9 +901,9 @@ Then, we log `a[b]`, which is actually `a["object Object"]`. We just set that to ###### 30. Apa yang akan tampil? ```javascript -const foo = () => console.log('First'); -const bar = () => setTimeout(() => console.log('Second')); -const baz = () => console.log('Third'); +const foo = () => console.log("First"); +const bar = () => setTimeout(() => console.log("Second")); +const baz = () => console.log("Third"); bar(); foo(); @@ -953,9 +956,7 @@ Di sinilah serangkaian acara mulai bekerja. Sebuah **event loop** (putaran kejad ```html

- +
``` @@ -981,9 +982,7 @@ The deepest nested element that caused the event is the target of the event. You ```html
-

- Click here! -

+

Click here!

``` @@ -1007,7 +1006,7 @@ If we click `p`, we see two logs: `p` and `div`. During event propagation, there ###### 33. Apa yang akan tampil? ```javascript -const person = { name: 'Lydia' }; +const person = { name: "Lydia" }; function sayHi(age) { return `${this.name} is ${age}`; @@ -1070,8 +1069,8 @@ FYI: there are only 7 built-in types: `null`, `undefined`, `boolean`, `number`, ```javascript 0; new Number(0); -(''); -(' '); +(""); +(" "); new Boolean(false); undefined; ``` @@ -1218,11 +1217,14 @@ What differentiates a primitive from an object is that primitives do not have an ###### 40. Apa yang akan tampil? ```javascript -[[0, 1], [2, 3]].reduce( +[ + [0, 1], + [2, 3], +].reduce( (acc, cur) => { return acc.concat(cur); }, - [1, 2], + [1, 2] ); ``` @@ -1249,7 +1251,7 @@ Then, `[1, 2, 0, 1]` is `acc` and `[2, 3]` is `cur`. We concatenate them, and ge ```javascript !!null; -!!''; +!!""; !!1; ``` @@ -1277,7 +1279,7 @@ Then, `[1, 2, 0, 1]` is `acc` and `[2, 3]` is `cur`. We concatenate them, and ge ###### 42. What does the `setInterval` method return in the browser? ```javascript -setInterval(() => console.log('Hi'), 1000); +setInterval(() => console.log("Hi"), 1000); ``` - A: a unique id @@ -1300,7 +1302,7 @@ Itu adalah mengembalikan sebuah id unik. id unik dapat digunakan untuk menghapus ###### 43. What does this return? ```javascript -[...'Lydia']; +[..."Lydia"]; ``` - A: `["L", "y", "d", "i", "a"]` @@ -1359,14 +1361,14 @@ Then, we invoke the function again with the `next()` method. It starts to contin ```javascript const firstPromise = new Promise((res, rej) => { - setTimeout(res, 500, 'one'); + setTimeout(res, 500, "one"); }); const secondPromise = new Promise((res, rej) => { - setTimeout(res, 100, 'two'); + setTimeout(res, 100, "two"); }); -Promise.race([firstPromise, secondPromise]).then(res => console.log(res)); +Promise.race([firstPromise, secondPromise]).then((res) => console.log(res)); ``` - A: `"one"` @@ -1389,7 +1391,7 @@ When we pass multiple promises to the `Promise.race` method, it resolves/rejects ###### 46. Apa yang akan tampil? ```javascript -let person = { name: 'Lydia' }; +let person = { name: "Lydia" }; const members = [person]; person = null; @@ -1429,7 +1431,7 @@ We are only modifying the value of the `person` variable, and not the first elem ```javascript const person = { - name: 'Lydia', + name: "Lydia", age: 21, }; @@ -1458,7 +1460,7 @@ With a `for-in` loop, we can iterate through object keys, in this case `name` an ###### 48. Apa yang akan tampil? ```javascript -console.log(3 + 4 + '5'); +console.log(3 + 4 + "5"); ``` - A: `"345"` @@ -1485,7 +1487,7 @@ Operator associativity is the order in which the compiler evaluates the expressi ###### 49. What's the value of `num`? ```javascript -const num = parseInt('7*6', 10); +const num = parseInt("7*6", 10); ``` - A: `42` @@ -1510,8 +1512,8 @@ Only the first numbers in the string is returned. Based on the _radix_ (the seco ###### 50. What's the output`? ```javascript -[1, 2, 3].map(num => { - if (typeof num === 'number') return; +[1, 2, 3].map((num) => { + if (typeof num === "number") return; return num * 2; }); ``` @@ -1539,12 +1541,12 @@ However, we don’t return a value. When we don’t return a value from the func ```javascript function getInfo(member, year) { - member.name = 'Lydia'; - year = '1998'; + member.name = "Lydia"; + year = "1998"; } -const person = { name: 'Sarah' }; -const birthYear = '1997'; +const person = { name: "Sarah" }; +const birthYear = "1997"; getInfo(person, birthYear); @@ -1576,15 +1578,15 @@ The value of `person` is an object. The argument `member` has a (copied) referen ```javascript function greeting() { - throw 'Hello world!'; + throw "Hello world!"; } function sayHi() { try { const data = greeting(); - console.log('It worked!', data); + console.log("It worked!", data); } catch (e) { - console.log('Oh no an error:', e); + console.log("Oh no an error:", e); } } @@ -1614,8 +1616,8 @@ With the `catch` statement, we can specify what to do if an exception is thrown ```javascript function Car() { - this.make = 'Lamborghini'; - return { make: 'Maserati' }; + this.make = "Lamborghini"; + return { make: "Maserati" }; } const myCar = new Car(); @@ -1687,11 +1689,11 @@ class Dog { } } -Dog.prototype.bark = function() { +Dog.prototype.bark = function () { console.log(`Woof I am ${this.name}`); }; -const pet = new Dog('Mara'); +const pet = new Dog("Mara"); pet.bark(); @@ -1756,7 +1758,7 @@ export default counter; ```javascript // index.js -import myCounter from './counter'; +import myCounter from "./counter"; myCounter += 1; @@ -1777,7 +1779,6 @@ Modul yang diimpor adalah _read-only_: Anda tidak dapat mengubah modul yang diim Ketika kita mencoba untuk menambah nilai `myCounter`, itu melemparkan kesalahan: `myCounter` adalah baca-saja dan tidak dapat dimodifikasi. -

@@ -1786,7 +1787,7 @@ Ketika kita mencoba untuk menambah nilai `myCounter`, itu melemparkan kesalahan: ###### 58. Apa yang akan tampil? ```javascript -const name = 'Lydia'; +const name = "Lydia"; age = 21; console.log(delete name); @@ -1857,7 +1858,7 @@ This means that the value of `y` is equal to the first value in the array, which ###### 60. Apa yang akan tampil? ```javascript -const user = { name: 'Lydia', age: 21 }; +const user = { name: "Lydia", age: 21 }; const admin = { admin: true, ...user }; console.log(admin); @@ -1883,9 +1884,9 @@ It's possible to combine objects using the spread operator `...`. It lets you cr ###### 61. Apa yang akan tampil? ```javascript -const person = { name: 'Lydia' }; +const person = { name: "Lydia" }; -Object.defineProperty(person, 'age', { value: 21 }); +Object.defineProperty(person, "age", { value: 21 }); console.log(person); console.log(Object.keys(person)); @@ -1914,12 +1915,12 @@ Properties added using the `defineProperty` method are immutable by default. You ```javascript const settings = { - username: 'lydiahallie', + username: "lydiahallie", level: 19, health: 90, }; -const data = JSON.stringify(settings, ['level', 'health']); +const data = JSON.stringify(settings, ["level", "health"]); console.log(data); ``` @@ -1950,7 +1951,7 @@ If the replacer is a _function_, this function gets called on every property in let num = 10; const increaseNumber = () => num++; -const increasePassedNumber = number => number++; +const increasePassedNumber = (number) => number++; const num1 = increaseNumber(); const num2 = increasePassedNumber(num1); @@ -2106,12 +2107,12 @@ The `Labrador` class receives two arguments, `name` since it extends `Dog`, and ```javascript // index.js -console.log('running index.js'); -import { sum } from './sum.js'; +console.log("running index.js"); +import { sum } from "./sum.js"; console.log(sum(1, 2)); // sum.js -console.log('running sum.js'); +console.log("running sum.js"); export const sum = (a, b) => a + b; ``` @@ -2139,7 +2140,7 @@ This is a difference between `require()` in CommonJS and `import`! With `require ```javascript console.log(Number(2) === Number(2)); console.log(Boolean(false) === Boolean(false)); -console.log(Symbol('foo') === Symbol('foo')); +console.log(Symbol("foo") === Symbol("foo")); ``` - A: `true`, `true`, `false` @@ -2162,7 +2163,7 @@ Every Symbol is entirely unique. The purpose of the argument passed to the Symbo ###### 69. Apa yang akan tampil? ```javascript -const name = 'Lydia Hallie'; +const name = "Lydia Hallie"; console.log(name.padStart(13)); console.log(name.padStart(2)); ``` @@ -2189,7 +2190,7 @@ If the argument passed to the `padStart` method is smaller than the length of th ###### 70. Apa yang akan tampil? ```javascript -console.log('🥑' + '💻'); +console.log("🥑" + "💻"); ``` - A: `"🥑💻"` @@ -2213,11 +2214,11 @@ With the `+` operator, you can concatenate strings. In this case, we are concate ```javascript function* startGame() { - const answer = yield 'Do you love JavaScript?'; - if (answer !== 'Yes') { + const answer = yield "Do you love JavaScript?"; + if (answer !== "Yes") { return "Oh wow... Guess we're gone here"; } - return 'JavaScript loves you back ❤️'; + return "JavaScript loves you back ❤️"; } const game = startGame(); @@ -2285,7 +2286,7 @@ In this case, the string is `Hello\nworld`, which gets logged. ```javascript async function getData() { - return await Promise.resolve('I made it!'); + return await Promise.resolve("I made it!"); } const data = getData(); @@ -2322,7 +2323,7 @@ function addToList(item, list) { return list.push(item); } -const result = addToList('apple', ['banana']); +const result = addToList("apple", ["banana"]); console.log(result); ``` @@ -2382,7 +2383,7 @@ Since `shape` is frozen, and since the value of `x` is not an object, we cannot ###### 76. Apa yang akan tampil? ```javascript -const { name: myName } = { name: 'Lydia' }; +const { name: myName } = { name: "Lydia" }; console.log(name); ``` @@ -2438,7 +2439,7 @@ The `sum` function always returns the same result. If we pass `1` and `2`, it wi ```javascript const add = () => { const cache = {}; - return num => { + return (num) => { if (num in cache) { return `From cache! ${cache[num]}`; } else { @@ -2483,7 +2484,7 @@ The third time, we pass `5 * 2` to the function which gets evaluated to `10`. Th ###### 79. What is the output? ```javascript -const myLifeSummedUp = ['☕', '💻', '🍷', '🍫']; +const myLifeSummedUp = ["☕", "💻", "🍷", "🍫"]; for (let item in myLifeSummedUp) { console.log(item); @@ -2579,13 +2580,13 @@ Pada kasus ini, juka kita tidak mengisi nilai atau mengisi `undefined`, `name` a ###### 82. What is the output? ```javascript -var status = '😎'; +var status = "😎"; setTimeout(() => { - const status = '😍'; + const status = "😍"; const data = { - status: '🥑', + status: "🥑", getStatus() { return this.status; }, @@ -2619,12 +2620,12 @@ With the `call` method, we can change the object to which the `this` keyword ref ```javascript const person = { - name: 'Lydia', + name: "Lydia", age: 21, }; let city = person.city; -city = 'Amsterdam'; +city = "Amsterdam"; console.log(person); ``` @@ -2688,9 +2689,9 @@ Variables with the `const` and `let` keyword are _block-scoped_. A block is anyt ###### 85. What kind of information would get logged? ```javascript -fetch('https://www.website.com/api/user/1') - .then(res => res.json()) - .then(res => console.log(res)) +fetch("https://www.website.com/api/user/1") + .then((res) => res.json()) + .then((res) => console.log(res)); ``` - A: The result of the `fetch` method. @@ -2744,7 +2745,7 @@ By setting `hasName` equal to `name`, you set `hasName` equal to whatever value ###### 87. Apa yang akan tampil? ```javascript -console.log('I want pizza'[0]); +console.log("I want pizza"[0]); ``` - A: `"""` @@ -2799,11 +2800,11 @@ If you're trying to set a default parameter's value equal to a parameter which i ```javascript // module.js -export default () => 'Hello world'; -export const name = 'Lydia'; +export default () => "Hello world"; +export const name = "Lydia"; // index.js -import * as data from './module'; +import * as data from "./module"; console.log(data); ``` @@ -2836,7 +2837,7 @@ class Person { } } -const member = new Person('John'); +const member = new Person("John"); console.log(typeof member); ``` @@ -2896,7 +2897,7 @@ Then, we try to use the `.push` method on `newList`. Since `newList` is the nume ```javascript function giveLydiaPizza() { - return 'Here is pizza!'; + return "Here is pizza!"; } const giveLydiaChocolate = () => @@ -2927,7 +2928,7 @@ Regular functions, such as the `giveLydiaPizza` function, have a `prototype` pro ```javascript const person = { - name: 'Lydia', + name: "Lydia", age: 21, }; @@ -2987,7 +2988,7 @@ function getItems(fruitList, favoriteFruit, ...args) { return [...fruitList, ...args, favoriteFruit]; } -getItems(['banana', 'apple'], 'pear', 'orange'); +getItems(["banana", "apple"], "pear", "orange"); ``` The above example works. This returns the array `[ 'banana', 'apple', 'orange', 'pear' ]` @@ -3001,8 +3002,8 @@ The above example works. This returns the array `[ 'banana', 'apple', 'orange', ```javascript function nums(a, b) { - if (a > b) console.log('a is bigger'); - else console.log('b is bigger'); + if (a > b) console.log("a is bigger"); + else console.log("b is bigger"); return; a + b; } @@ -3042,13 +3043,13 @@ This means that `a + b` is never reached, since a function stops running after t ```javascript class Person { constructor() { - this.name = 'Lydia'; + this.name = "Lydia"; } } Person = class AnotherPerson { constructor() { - this.name = 'Sarah'; + this.name = "Sarah"; } }; @@ -3077,7 +3078,7 @@ Kita dapat mengatur kelas yang sama dengan kelas / fungsi konstruktor lainnya. D ```javascript const info = { - [Symbol('a')]: 'b', + [Symbol("a")]: "b", }; console.log(info); @@ -3096,7 +3097,7 @@ console.log(Object.keys(info)); Simbol bukanlah merupakan suatu _enumerable_. Metode Object.keys akan mengembalikan semua properti kunci _enumerable_ pada sebuah objek. Simbol tidak akan terlihat, dan array kosong dikembalikan. Saat mencatat seluruh objek, semua properti akan terlihat, bahkan yang bukan non-enumerable. -Ini adalah salah satu dari banyak kualitas simbol: Disamping selain mewakili nilai yang sepenuhnya unik (yang mencegah terjadinya benturan nama yang tidak disengaja pada objek, misalnya saat bekerja dengan 2 library yang ingin menambahkan properti ke objek yang sama), anda juga dapat "menyembunyikan" properti pada objek dengan cara ini (meskipun tidak seluruhnya. Anda masih dapat mengakses simbol menggunakan metode `Object.getOwnPropertySymbols()`). +Ini adalah salah satu dari banyak kualitas simbol: Disamping selain mewakili nilai yang sepenuhnya unik (yang mencegah terjadinya benturan nama yang tidak disengaja pada objek, misalnya saat bekerja dengan 2 library yang ingin menambahkan properti ke objek yang sama), anda juga dapat "menyembunyikan" properti pada objek dengan cara ini (meskipun tidak seluruhnya. Anda masih dapat mengakses simbol menggunakan metode `Object.getOwnPropertySymbols()`).

@@ -3130,7 +3131,7 @@ Fungsi `getList` menerima array sebagai argumennya. Di antara tanda kurung pada `[x, ...y] = [1, 2, 3, 4]` -Dengan parameter sisa `...y`, kita akan meletakkan semua argumen "yang tersisa" dalam array. Dalam kasus ini argumen yang tersisa adalah `2`, `3` dan `4`. Nilai dari `y` merupakan suatu array, yang berisi semua parameter lainnya. Pada kasus ini nilai dari `x` sama dengan `1`, jadi saat kita mencatat `[x, y]`, maka catatannya `[1, [2, 3, 4]]`. +Dengan parameter sisa `...y`, kita akan meletakkan semua argumen "yang tersisa" dalam array. Dalam kasus ini argumen yang tersisa adalah `2`, `3` dan `4`. Nilai dari `y` merupakan suatu array, yang berisi semua parameter lainnya. Pada kasus ini nilai dari `x` sama dengan `1`, jadi saat kita mencatat `[x, y]`, maka catatannya `[1, [2, 3, 4]]`. Fungsi `getUser` menerima sebuah objek. Dengan fungsi tanda panah, kita tidak _perlu_ menulis tanda kurung kurawal jika hanya mengembalikan satu nilai. Namun, jika anda mengembalikan nilai _object_ dari fungsi tanda panah, Anda harus menuliskannya di antara tanda kurung, jika tidak maka tidak ada nilai yang dikembalikan! Fungsi berikut akan mengembalikan sebuah objek: @@ -3146,7 +3147,7 @@ Karena tidak ada nilai yang dikembalikan dalam kasus ini, maka fungsi akan menge ###### 99. Apa yang akan tampil? ```javascript -const name = 'Lydia'; +const name = "Lydia"; console.log(name()); ``` @@ -3178,8 +3179,8 @@ ReferenceErrors muncul ketika JavaScript tidak dapat menemukan nilai referensi k ```javascript // 🎉✨ This is my 100th question! ✨🎉 -const output = `${[] && 'Im'}possible! -You should${'' && `n't`} see a therapist after so much JavaScript lol`; +const output = `${[] && "Im"}possible! +You should${"" && `n't`} see a therapist after so much JavaScript lol`; ``` - A: `possible! You should see a therapist after so much JavaScript lol` @@ -3205,7 +3206,7 @@ You should${'' && `n't`} see a therapist after so much JavaScript lol`; ```javascript const one = false || {} || null; -const two = null || false || ''; +const two = null || false || ""; const three = [] || 0 || true; console.log(one, two, three); @@ -3237,16 +3238,16 @@ With the `||` operator, we can return the first truthy operand. If all values ar ###### 102. What's the value of output? ```javascript -const myPromise = () => Promise.resolve('I have resolved!'); +const myPromise = () => Promise.resolve("I have resolved!"); function firstFunction() { - myPromise().then(res => console.log(res)); - console.log('second'); + myPromise().then((res) => console.log(res)); + console.log("second"); } async function secondFunction() { console.log(await myPromise()); - console.log('second'); + console.log("second"); } firstFunction(); @@ -3284,8 +3285,8 @@ This means that it waited for the `myPromise` to resolve with the value `I have const set = new Set(); set.add(1); -set.add('Lydia'); -set.add({ name: 'Lydia' }); +set.add("Lydia"); +set.add({ name: "Lydia" }); for (let item of set) { console.log(item + 2); @@ -3345,13 +3346,13 @@ In this case, we just passed the numerical value `5`. It returns a resolved prom ```javascript function compareMembers(person1, person2 = person) { if (person1 !== person2) { - console.log('Not the same!'); + console.log("Not the same!"); } else { - console.log('They are the same!'); + console.log("They are the same!"); } } -const person = { name: 'Lydia' }; +const person = { name: "Lydia" }; compareMembers(person); ``` @@ -3390,7 +3391,7 @@ const colorConfig = { yellow: false, }; -const colors = ['pink', 'red', 'blue']; +const colors = ["pink", "red", "blue"]; console.log(colorConfig.colors[1]); ``` @@ -3419,7 +3420,7 @@ JavaScript interprets (or unboxes) statements. When we use bracket notation, it ###### 107. Apakah hasil nilai dibawah ini ? ```javascript -console.log('❤️' === '❤️'); +console.log("❤️" === "❤️"); ``` - A: `true` @@ -3472,10 +3473,10 @@ Metode `splice`, akan memodifikasi array aslinya dengan cara menghapus, menggant ###### 109. Apa yang akan tampil? ```javascript -const food = ['🍕', '🍫', '🥑', '🍔']; +const food = ["🍕", "🍫", "🥑", "🍔"]; const info = { favoriteFood: food[0] }; -info.favoriteFood = '🍝'; +info.favoriteFood = "🍝"; console.log(food); ``` @@ -3529,7 +3530,7 @@ const jsonArray = JSON.stringify([1, 2, 3]); // '[1, 2, 3]' JSON.parse(jsonArray); // [1, 2, 3] // Stringifying an object into valid JSON, then parsing the JSON string to a JavaScript value: -const jsonArray = JSON.stringify({ name: 'Lydia' }); // '{"name":"Lydia"}' +const jsonArray = JSON.stringify({ name: "Lydia" }); // '{"name":"Lydia"}' JSON.parse(jsonArray); // { name: 'Lydia' } ``` @@ -3541,11 +3542,11 @@ JSON.parse(jsonArray); // { name: 'Lydia' } ###### 111. Apa yang akan tampil? ```javascript -let name = 'Lydia'; +let name = "Lydia"; function getName() { console.log(name); - let name = 'Sarah'; + let name = "Sarah"; } getName(); @@ -3568,7 +3569,7 @@ Variables with the `let` keyword (and `const`) are hoisted, but unlike `var`, do If we wouldn't have declared the `name` variable within the `getName` function, the javascript engine would've looked down the _scope chain_. The outer scope has a variable called `name` with the value of `Lydia`. In that case, it would've logged `Lydia`. ```javascript -let name = 'Lydia'; +let name = "Lydia"; function getName() { console.log(name); @@ -3586,11 +3587,11 @@ getName(); // Lydia ```javascript function* generatorOne() { - yield ['a', 'b', 'c']; + yield ["a", "b", "c"]; } function* generatorTwo() { - yield* ['a', 'b', 'c']; + yield* ["a", "b", "c"]; } const one = generatorOne(); @@ -3636,7 +3637,7 @@ console.log(two.next().value); // undefined ###### 113. Apa yang akan tampil? ```javascript -console.log(`${(x => x)('I love')} to program`); +console.log(`${((x) => x)("I love")} to program`); ``` - A: `I love to program` @@ -3661,7 +3662,7 @@ Expressions within template literals are evaluated first. This means that the st ```javascript let config = { alert: setInterval(() => { - console.log('Alert!'); + console.log("Alert!"); }, 1000), }; @@ -3689,16 +3690,16 @@ Normally when we set objects equal to `null`, those objects get _garbage collect ```javascript const myMap = new Map(); -const myFunc = () => 'greeting'; +const myFunc = () => "greeting"; -myMap.set(myFunc, 'Hello world!'); +myMap.set(myFunc, "Hello world!"); //1 -myMap.get('greeting'); +myMap.get("greeting"); //2 myMap.get(myFunc); //3 -myMap.get(() => 'greeting'); +myMap.get(() => "greeting"); ``` - A: 1 @@ -3725,14 +3726,14 @@ When adding a key/value pair using the `set` method, the key will be the value o ```javascript const person = { - name: 'Lydia', + name: "Lydia", age: 21, }; const changeAge = (x = { ...person }) => (x.age += 1); const changeAgeAndName = (x = { ...person }) => { x.age += 1; - x.name = 'Sarah'; + x.name = "Sarah"; }; changeAge(person); @@ -3791,7 +3792,7 @@ With the spread operator `...`, we can _spread_ iterables to individual elements ```javascript let num = 1; -const list = ['🥳', '🤠', '🥰', '🤪']; +const list = ["🥳", "🤠", "🥰", "🤪"]; console.log(list[(num += 1)]); ``` @@ -3817,11 +3818,11 @@ With the `+=` operand, we're incrementing the value of `num` by `1`. `num` had t ```javascript const person = { - firstName: 'Lydia', - lastName: 'Hallie', + firstName: "Lydia", + lastName: "Hallie", pet: { - name: 'Mara', - breed: 'Dutch Tulip Hound', + name: "Mara", + breed: "Dutch Tulip Hound", }, getFullName() { return `${this.firstName} ${this.lastName}`; @@ -3859,10 +3860,10 @@ With the optional chaining operator `?.`, we no longer have to explicitly check ###### 120. Apa yang akan tampil? ```javascript -const groceries = ['banana', 'apple', 'peanuts']; +const groceries = ["banana", "apple", "peanuts"]; -if (groceries.indexOf('banana')) { - console.log('We have to buy bananas!'); +if (groceries.indexOf("banana")) { + console.log("We have to buy bananas!"); } else { console.log(`We don't have to buy bananas!`); } @@ -3918,10 +3919,10 @@ The `language` method is a `setter`. Setters don't hold an actual value, their p ###### 122. Apa yang akan tampil? ```javascript -const name = 'Lydia Hallie'; +const name = "Lydia Hallie"; -console.log(!typeof name === 'object'); -console.log(!typeof name === 'string'); +console.log(!typeof name === "object"); +console.log(!typeof name === "string"); ``` - A: `false` `true` @@ -3946,7 +3947,7 @@ console.log(!typeof name === 'string'); ###### 123. Apa yang akan tampil? ```javascript -const add = x => y => z => { +const add = (x) => (y) => (z) => { console.log(x, y, z); return x + y + z; }; @@ -4072,8 +4073,8 @@ With the `Intl.NumberFormat` method, we can format numeric values to any locale. ###### 127. Apa yang akan tampil? ```javascript -const spookyItems = ['👻', '🎃', '🕸']; -({ item: spookyItems[3] } = { item: '💀' }); +const spookyItems = ["👻", "🎃", "🕸"]; +({ item: spookyItems[3] } = { item: "💀" }); console.log(spookyItems); ``` @@ -4098,7 +4099,7 @@ By destructuring objects, we can unpack values from the right-hand object, and a ###### 128. Apa yang akan tampil? ```javascript -const name = 'Lydia Hallie'; +const name = "Lydia Hallie"; const age = 21; console.log(Number.isNaN(name)); @@ -4134,7 +4135,7 @@ const randomValue = 21; function getInfo() { console.log(typeof randomValue); - const randomValue = 'Lydia Hallie'; + const randomValue = "Lydia Hallie"; } getInfo(); @@ -4160,7 +4161,7 @@ Variables declared with the `const` keyword are not referencable before their in ###### 130. Apa yang akan tampil? ```javascript -const myPromise = Promise.resolve('Woah some cool data'); +const myPromise = Promise.resolve("Woah some cool data"); (async () => { try { @@ -4168,7 +4169,7 @@ const myPromise = Promise.resolve('Woah some cool data'); } catch { throw new Error(`Oops didn't work`); } finally { - console.log('Oh finally!'); + console.log("Oh finally!"); } })(); ``` @@ -4193,7 +4194,7 @@ In the `try` block, we're logging the awaited value of the `myPromise` variable: ###### 131. Apa yang akan tampil? ```javascript -const emojis = ['🥑', ['✨', '✨', ['🍕', '🍕']]]; +const emojis = ["🥑", ["✨", "✨", ["🍕", "🍕"]]]; console.log(emojis.flat(1)); ``` @@ -4266,19 +4267,19 @@ We invoke the `counterTwo.increment()`, which sets the `count` to `3`. Then, we ###### 133. Apa yang akan tampil? ```javascript -const myPromise = Promise.resolve(Promise.resolve('Promise!')); +const myPromise = Promise.resolve(Promise.resolve("Promise!")); function funcOne() { - myPromise.then(res => res).then(res => console.log(res)); - setTimeout(() => console.log('Timeout!', 0)); - console.log('Last line!'); + myPromise.then((res) => res).then((res) => console.log(res)); + setTimeout(() => console.log("Timeout!", 0)); + console.log("Last line!"); } async function funcTwo() { const res = await myPromise; console.log(await res); - setTimeout(() => console.log('Timeout!', 0)); - console.log('Last line!'); + setTimeout(() => console.log("Timeout!", 0)); + console.log("Last line!"); } funcOne(); @@ -4319,7 +4320,7 @@ export default function sum(x) { } // index.js -import * as sum from './sum'; +import * as sum from "./sum"; ``` - A: `sum(4)` @@ -4336,12 +4337,12 @@ With the asterisk `*`, we import all exported values from that file, both defaul ```javascript // info.js -export const name = 'Lydia'; +export const name = "Lydia"; export const age = 21; -export default 'I love JavaScript'; +export default "I love JavaScript"; // index.js -import * as info from './info'; +import * as info from "./info"; console.log(info); ``` @@ -4372,13 +4373,13 @@ We can invoke this function, by calling `sum.default` ```javascript const handler = { - set: () => console.log('Added a new property!'), - get: () => console.log('Accessed a property!'), + set: () => console.log("Added a new property!"), + get: () => console.log("Accessed a property!"), }; const person = new Proxy({}, handler); -person.name = 'Lydia'; +person.name = "Lydia"; person.name; ``` @@ -4408,7 +4409,7 @@ Then, we access a property value on the proxy object, the `get` property on the ###### 136. Which of the following will modify the `person` object? ```javascript -const person = { name: 'Lydia Hallie' }; +const person = { name: "Lydia Hallie" }; Object.seal(person); ``` @@ -4436,9 +4437,9 @@ However, you can still modify the value of existing properties. ```javascript const person = { - name: 'Lydia Hallie', + name: "Lydia Hallie", address: { - street: '100 Main St', + street: "100 Main St", }, }; @@ -4468,9 +4469,9 @@ However, it only _shallowly_ freezes the object, meaning that only _direct_ prop ```javascript const person = { - name: 'Lydia Hallie', + name: "Lydia Hallie", address: { - street: '100 Main St', + street: "100 Main St", }, }; @@ -4499,7 +4500,7 @@ However, it only _shallowly_ freezes the object, meaning that only _direct_ prop ###### 139. Apa yang akan tampil? ```javascript -const add = x => x + x; +const add = (x) => x + x; function myFunc(num = 2, value = add(num)) { console.log(num, value); @@ -4532,21 +4533,21 @@ Then, we invoked `myFunc(3)` and passed the value `3` as the value for the argum ```javascript class Counter { - #number = 10 + #number = 10; increment() { - this.#number++ + this.#number++; } getNum() { - return this.#number + return this.#number; } } -const counter = new Counter() -counter.increment() +const counter = new Counter(); +counter.increment(); -console.log(counter.#number) +console.log(counter.#number); ``` - A: `10` @@ -4570,8 +4571,8 @@ In ES2020, we can add private variables in classes by using the `#`. We cannot a ```javascript const teams = [ - { name: 'Team 1', members: ['Paul', 'Lisa'] }, - { name: 'Team 2', members: ['Laura', 'Tim'] }, + { name: "Team 1", members: ["Paul", "Lisa"] }, + { name: "Team 2", members: ["Laura", "Tim"] }, ]; function* getMembers(members) { @@ -4614,8 +4615,8 @@ Jika kita telah menulis `yield`, `return yield`, atau `return`, maka seluruh fun ```javascript const person = { - name: 'Lydia Hallie', - hobbies: ['coding'], + name: "Lydia Hallie", + hobbies: ["coding"], }; function addHobby(hobby, hobbies = person.hobbies) { @@ -4623,9 +4624,9 @@ function addHobby(hobby, hobbies = person.hobbies) { return hobbies; } -addHobby('running', []); -addHobby('dancing'); -addHobby('baking', person.hobbies); +addHobby("running", []); +addHobby("dancing"); +addHobby("baking", person.hobbies); console.log(person.hobbies); ``` @@ -4694,11 +4695,11 @@ Kita membuat variabel `pet` yang merupakan turunan dari class `Flamingo`. Saat k ###### 144. Manakah dari pilihan di bawah ini yang salah? ```javascript -const emojis = ['🎄', '🎅🏼', '🎁', '⭐']; +const emojis = ["🎄", "🎅🏼", "🎁", "⭐"]; -/* 1 */ emojis.push('🦌'); +/* 1 */ emojis.push("🦌"); /* 2 */ emojis.splice(0, 2); -/* 3 */ emojis = [...emojis, '🥂']; +/* 3 */ emojis = [...emojis, "🥂"]; /* 4 */ emojis.length = 0; ``` @@ -4741,7 +4742,7 @@ const person = { #### Jawaban: C Objek tidak dapat diulang secara default. Sebuah iterable adalah sebuah iterable jika protokol iterator ada. Kita dapat menambahkan ini secara manual dengan menambahkan simbol iterator - `[Symbol.iterator]`, dimana harus mengembalikan objek generator, sebagai contoh dengan membuat fungsi generator `*[Symbol.iterator]() {}`. Fungsi generator ini harus menghasilkan `Object.values` dari objek `person` jika kita mau mengembalikan array `["Lydia Hallie", 21]`: `yield* Object.values(this)`. +`[Symbol.iterator]`, dimana harus mengembalikan objek generator, sebagai contoh dengan membuat fungsi generator `*[Symbol.iterator]() {}`. Fungsi generator ini harus menghasilkan `Object.values` dari objek `person` jika kita mau mengembalikan array `["Lydia Hallie", 21]`: `yield* Object.values(this)`.

@@ -4754,11 +4755,11 @@ Objek tidak dapat diulang secara default. Sebuah iterable adalah sebuah iterable let count = 0; const nums = [0, 1, 2, 3]; -nums.forEach(num => { - if (num) count += 1 -}) +nums.forEach((num) => { + if (num) count += 1; +}); -console.log(count) +console.log(count); ``` - A: 1 @@ -4782,19 +4783,19 @@ Pernyataan `if` didalam perulangan `forEach` akan mengecek apakah nilai dari `nu ```javascript class Calc { - constructor() { - this.count = 0 - } + constructor() { + this.count = 0; + } - increase() { - this.count ++ - } + increase() { + this.count++; + } } -const calc = new Calc() -new Calc().increase() +const calc = new Calc(); +new Calc().increase(); -console.log(calc.count) +console.log(calc.count); ``` - A: `0` @@ -4818,25 +4819,25 @@ Kami mengatur variabel `calc` sama dengan instance baru dari class `Calc`. Kemud ```javascript const user = { - email: "e@mail.com", - password: "12345" -} + email: "e@mail.com", + password: "12345", +}; const updateUser = ({ email, password }) => { - if (email) { - Object.assign(user, { email }) - } + if (email) { + Object.assign(user, { email }); + } - if (password) { - user.password = password - } + if (password) { + user.password = password; + } - return user -} + return user; +}; -const updatedUser = updateUser({ email: "new@email.com" }) +const updatedUser = updateUser({ email: "new@email.com" }); -console.log(updatedUser === user) +console.log(updatedUser === user); ``` - A: `false` @@ -4857,12 +4858,13 @@ Fungsi `updateUser` memperbarui nilai properti `email` dan `password` pada pengg --- ###### 149. Apa hasilnya? + ```javascript -const fruit = ['🍌', '🍊', '🍎'] +const fruit = ["🍌", "🍊", "🍎"]; -fruit.slice(0, 1) -fruit.splice(0, 1) -fruit.unshift('🍇') +fruit.slice(0, 1); +fruit.splice(0, 1); +fruit.unshift("🍇"); ``` - A: `['🍌', '🍊', '🍎']` @@ -4888,13 +4890,13 @@ Akhirnya, kita memanggil metode `unshift` pada array `fruit`, yang memodifikasi ```javascript const animals = {}; -let dog = { emoji: '🐶' } -let cat = { emoji: '🐈' } +let dog = { emoji: "🐶" }; +let cat = { emoji: "🐈" }; -animals[dog] = { ...dog, name: "Mara" } -animals[cat] = { ...cat, name: "Sara" } +animals[dog] = { ...dog, name: "Mara" }; +animals[cat] = { ...cat, name: "Sara" }; -console.log(animals[dog]) +console.log(animals[dog]); ``` - A: `{ emoji: "🐶", name: "Mara" }` @@ -4909,9 +4911,9 @@ console.log(animals[dog]) Kunci objek diubah menjadi string. -Karena nilai `dog` adalah sebuah objek, `animals[dog]`sebenarnya berarti kita membuat properti baru bernama `"object Object"`yang sama dengan objek baru. `animals["object Object"]` sekarang sama dengan `{ emoji: "🐶", name: "Mara"}`. +Karena nilai `dog` adalah sebuah objek, `animals[dog]`sebenarnya berarti kita membuat properti baru bernama `"object Object"`yang sama dengan objek baru. `animals["object Object"]` sekarang sama dengan `{ emoji: "🐶", name: "Mara"}`. -`cat` juga merupakan objek, yang berarti bahwa `animals[cat]` sebenarnya berarti bahwa kami menimpa nilai `animals[``"``object Object``"``]` dengan properti cat yang baru. +`cat` juga merupakan objek, yang berarti bahwa `animals[cat]` sebenarnya berarti bahwa kami menimpa nilai ` animals[``"``object Object``"``] ` dengan properti cat yang baru. Mencatat `animals[dog]`, atau sebenarnya `animals["object Object"]` karena mengonversi objek `dog` menjadi string menghasilkan `"object Object"`, mengembalikan `{emoji: "🐈", nama: "Sara"}`. @@ -4924,10 +4926,10 @@ Mencatat `animals[dog]`, atau sebenarnya `animals["object Object"]` karena mengo ```javascript const user = { - email: "my@email.com", - updateEmail: (email) => { - this.email = email; - }, + email: "my@email.com", + updateEmail: (email) => { + this.email = email; + }, }; user.updateEmail("new@email.com"); @@ -4954,20 +4956,20 @@ Fungsi `updateEmail` adalah fungsi panah, dan tidak terikat ke objek `user`. Art ###### 152. Apa hasilnya? ```javascript -const promise1 = Promise.resolve('First') -const promise2 = Promise.resolve('Second') -const promise3 = Promise.reject('Third') -const promise4 = Promise.resolve('Fourth') +const promise1 = Promise.resolve("First"); +const promise2 = Promise.resolve("Second"); +const promise3 = Promise.reject("Third"); +const promise4 = Promise.resolve("Fourth"); const runPromises = async () => { - const res1 = await Promise.all([promise1, promise2]); - const res2 = await Promise.all([promise3, promise4]); - return [res1, res2]; -} + const res1 = await Promise.all([promise1, promise2]); + const res2 = await Promise.all([promise3, promise4]); + return [res1, res2]; +}; runPromises() - .then(res => console.log(res)) - .catch(err => console.log(err)) + .then((res) => console.log(res)) + .catch((err) => console.log(err)); ``` - A: `[['First', 'Second'], ['Fourth']]` @@ -5024,18 +5026,18 @@ Ini membuat array subarray yang berisi kunci dan nilai yang benar, yang menghasi ###### 154. Apa hasilnya? ```javascript -const createMember = ({ email, address = {}}) => { - const validEmail = /.+\@.+\..+/.test(email) - if (!validEmail) throw new Error("Valid email pls") +const createMember = ({ email, address = {} }) => { + const validEmail = /.+\@.+\..+/.test(email); + if (!validEmail) throw new Error("Valid email pls"); - return { - email, - address: address ? address : null - } -} + return { + email, + address: address ? address : null, + }; +}; -const member = createMember({ email: "my@email.com" }) -console.log(member) +const member = createMember({ email: "my@email.com" }); +console.log(member); ``` - A: `{ email: "my@email.com", address: null }` @@ -5058,13 +5060,13 @@ Nilai default dari `address` adalah objek kosong `{}`. Saat kita menyetel variab ###### 155. Apa hasilnya? ```javascript -let randomValue = { name: "Lydia" } -randomValue = 23 +let randomValue = { name: "Lydia" }; +randomValue = 23; if (!typeof randomValue === "string") { - console.log("It's not a string!") + console.log("It's not a string!"); } else { - console.log("Yay it's a string!") + console.log("Yay it's a string!"); } ``` diff --git a/it-IT/README.md b/it-IT/README.md index 71b71ca5..8b116031 100644 --- a/it-IT/README.md +++ b/it-IT/README.md @@ -8,13 +8,12 @@ Da base ad avanzato: metti alla prova quanto conosci JavaScript, rinfresca un po' le tue conoscenze o preparati per il tuo colloquio di programmazione! :muscle: :rocket: Aggiorno regolarmente questo repository con nuove domande. Ho aggiunto le risposte nelle **sezioni compresse** sotto le domande, cliccaci sopra per espanderle. È solo per divertimento, buona fortuna! :heart: - Sentiti libero di contattarmi! 😊
Instagram || Twitter || LinkedIn || Blog - -| Sentiti libero di usarli in un progetto! 😃 Apprezzerei _molto_ un riferimento a questa repository, creo le domande e le spiegazioni (sì, sono triste lol) e la community mi aiuta tantissimo a mantenerlo e migliorarlo! 💪🏼 Grazie e buon divertimento! | + +| Sentiti libero di usarli in un progetto! 😃 Apprezzerei _molto_ un riferimento a questa repository, creo le domande e le spiegazioni (sì, sono triste lol) e la community mi aiuta tantissimo a mantenerlo e migliorarlo! 💪🏼 Grazie e buon divertimento! | Traduzione a cura di: Lucia Cenetiempo |---| @@ -37,6 +36,7 @@ Traduzione a cura di: Lucia Cenetie - [🇳🇱 Nederlands](../nl-NL/README.md) - [🇵🇱 Polski](../pl-PL/README.md) - [🇧🇷 Português Brasil](../pt-BR/README_pt_BR.md) +- [🇷o Română](../ro-RO/README.ro.md) - [🇷🇺 Русский](../ru-RU/README.md) - [🇽🇰 Shqip](../sq-KS/README_sq_KS.md) - [🇹🇭 ไทย](../th-TH/README-th_TH.md) @@ -57,7 +57,7 @@ Traduzione a cura di: Lucia Cenetie function sayHi() { console.log(name); console.log(age); - var name = 'Lydia'; + var name = "Lydia"; let age = 21; } @@ -75,8 +75,8 @@ sayHi(); #### Risposta: D -All'interno della funzione, dichiariamo prima la variabile `name` con la parola chiave `var`. Ciò significa che la variabile viene sollevata all'interno del codice (ovvero lo spazio di memoria viene impostato durante la fase di creazione) e viene inizializzata con il valore predefinito di `undefined`, finché non arriviamo effettivamente alla riga in cui la definiamo. -Al momento in cui proviamo ad eseguire il log della variabile `name` non l'abbiamo ancora dichiarata, quindi mantiene il valore di `undefined`. +All'interno della funzione, dichiariamo prima la variabile `name` con la parola chiave `var`. Ciò significa che la variabile viene sollevata all'interno del codice (ovvero lo spazio di memoria viene impostato durante la fase di creazione) e viene inizializzata con il valore predefinito di `undefined`, finché non arriviamo effettivamente alla riga in cui la definiamo. +Al momento in cui proviamo ad eseguire il log della variabile `name` non l'abbiamo ancora dichiarata, quindi mantiene il valore di `undefined`. Le variabili dichiarate con la chiave `let` (o `const`) vengono sollevate, ma a differenza delle variabili dichiarate con `var`, non vengono inizializzate. Per questo motivo non sono accessibili prima della loro dichiarazione (dove le inizializzaimo). Questa è chiamata "temporal dead zone". Quando proviamo ad accedere alle variabili prima che vengano dichiarate, JavaScript genera un `ReferenceError`. @@ -155,7 +155,7 @@ Non troviamo quindi alcun valore `radius` in quell'oggetto e quindi viene restit ```javascript +true; -!'Lydia'; +!"Lydia"; ``` - A: `1` and `false` @@ -180,11 +180,11 @@ La stringa `'Lydia'` è un valore veritiero. Quello che in realtà ci stiamo chi ```javascript const bird = { - size: 'small', + size: "small", }; const mouse = { - name: 'Mickey', + name: "Mickey", small: true, }; ``` @@ -215,11 +215,11 @@ Con l'utilizzo del punto questo non accade perché `mouse` non ha una chiave chi ###### 6. Qual è l'output? ```javascript -let c = { greeting: 'Hey!' }; +let c = { greeting: "Hey!" }; let d; d = c; -c.greeting = 'Hello'; +c.greeting = "Hello"; console.log(d.greeting); ``` @@ -289,13 +289,13 @@ class Chameleon { return this.newColor; } - constructor({ newColor = 'green' } = {}) { + constructor({ newColor = "green" } = {}) { this.newColor = newColor; } } -const freddie = new Chameleon({ newColor: 'purple' }); -console.log(freddie.colorChange('orange')); +const freddie = new Chameleon({ newColor: "purple" }); +console.log(freddie.colorChange("orange")); ``` - A: `orange` @@ -347,10 +347,10 @@ Per evitare ciò, possiamo usare `"use strict"`. Questo assicura di aver dichiar ```javascript function bark() { - console.log('Woof!'); + console.log("Woof!"); } -bark.animal = 'dog'; +bark.animal = "dog"; ``` - A: Niente, va benissimo! @@ -380,8 +380,8 @@ function Person(firstName, lastName) { this.lastName = lastName; } -const member = new Person('Lydia', 'Hallie'); -Person.getFullName = function() { +const member = new Person("Lydia", "Hallie"); +Person.getFullName = function () { return `${this.firstName} ${this.lastName}`; }; @@ -402,9 +402,8 @@ In JavaScript, le funzioni sono oggetti e quindi il metodo `getFullName` viene a Se vuoi che un metodo sia disponibile per tutte le istanze dell'oggetto, devi aggiungerlo alla proprietà del prototipo: - ```js -Person.prototype.getFullName = function() { +Person.prototype.getFullName = function () { return `${this.firstName} ${this.lastName}`; }; ``` @@ -422,8 +421,8 @@ function Person(firstName, lastName) { this.lastName = lastName; } -const lydia = new Person('Lydia', 'Hallie'); -const sarah = Person('Sarah', 'Smith'); +const lydia = new Person("Lydia", "Hallie"); +const sarah = Person("Sarah", "Smith"); console.log(lydia); console.log(sarah); @@ -493,7 +492,7 @@ function sum(a, b) { return a + b; } -sum(1, '2'); +sum(1, "2"); ``` - A: `NaN` @@ -544,7 +543,7 @@ Utilizzando l'operatore unario come **prefisso** `++number` succede che: 1. Incrementa prima il valore (il numero è ora `2`) 2. Restituisce subito dopo il valore già incrementato (`2`) -Quindi il nostro log sarà `0 2 2`. +Quindi il nostro log sarà `0 2 2`.

@@ -560,7 +559,7 @@ function getPersonInfo(one, two, three) { console.log(three); } -const person = 'Lydia'; +const person = "Lydia"; const age = 21; getPersonInfo`${person} is ${age} years old`; @@ -575,7 +574,7 @@ getPersonInfo`${person} is ${age} years old`; #### Risposta: B -Utilizzando i template literals, il valore del primo argomento sarà un array di valori della stringa. Gli altri argomenti prenderanno i valori dell'espressione passata. +Utilizzando i template literals, il valore del primo argomento sarà un array di valori della stringa. Gli altri argomenti prenderanno i valori dell'espressione passata.

@@ -587,9 +586,9 @@ Utilizzando i template literals, il valore del primo argomento sarà un array di ```javascript function checkAge(data) { if (data === { age: 18 }) { - console.log('You are an adult!'); + console.log("You are an adult!"); } else if (data == { age: 18 }) { - console.log('You are still an adult.'); + console.log("You are still an adult."); } else { console.log(`Hmm.. You don't have an age I guess`); } @@ -649,7 +648,7 @@ Il parametro rest (`...args`) ci permette di "collettare" tutti gli argomenti in ```javascript function getAge() { - 'use strict'; + "use strict"; age = 21; console.log(age); } @@ -677,7 +676,7 @@ Con `"use strict"`, puoi assicurarti di non dichiarare variabili globali per sba ###### 21. Qual è il valore di `sum`? ```javascript -const sum = eval('10*10+5'); +const sum = eval("10*10+5"); ``` - A: `105` @@ -700,7 +699,7 @@ const sum = eval('10*10+5'); ###### 22. Per quanto tempo cool_secret è accessibile? ```javascript -sessionStorage.setItem('cool_secret', 123); +sessionStorage.setItem("cool_secret", 123); ``` - A: Per sempre, i dati non vanno persi. @@ -753,12 +752,12 @@ Non puoi farlo con `let` o `const` poiché sono block-scoped. ###### 24. Qual è l'output? ```javascript -const obj = { 1: 'a', 2: 'b', 3: 'c' }; +const obj = { 1: "a", 2: "b", 3: "c" }; const set = new Set([1, 2, 3, 4, 5]); -obj.hasOwnProperty('1'); +obj.hasOwnProperty("1"); obj.hasOwnProperty(1); -set.has('1'); +set.has("1"); set.has(1); ``` @@ -784,7 +783,7 @@ Per i set non funziona allo stesso modo degli oggetti. Non c'è alcun `'1'` nel ###### 25. Qual è l'output? ```javascript -const obj = { a: 'one', b: 'two', a: 'three' }; +const obj = { a: "one", b: "two", a: "three" }; console.log(obj); ``` @@ -853,12 +852,12 @@ L'istruzione `continue` salta un'iterazione se una certa condizione restituisce ```javascript String.prototype.giveLydiaPizza = () => { - return 'Just give Lydia pizza already!'; + return "Just give Lydia pizza already!"; }; -const name = 'Lydia'; +const name = "Lydia"; -console.log(name.giveLydiaPizza()) +console.log(name.giveLydiaPizza()); ``` - A: `"Just give Lydia pizza already!"` @@ -871,7 +870,7 @@ console.log(name.giveLydiaPizza()) #### Risposta: A -`String` è un costruttore built-in, a cui possiamo aggiungere proprietà. In questo caso è stato appena aggiunto un metodo al suo prototipo. +`String` è un costruttore built-in, a cui possiamo aggiungere proprietà. In questo caso è stato appena aggiunto un metodo al suo prototipo. Le stringhe primitive vengono automaticamente convertite in un oggetto stringa, generato dalla string prototype function. Quindi, tutte le stringhe hanno accesso a quel metodo!

@@ -883,8 +882,8 @@ Le stringhe primitive vengono automaticamente convertite in un oggetto stringa, ```javascript const a = {}; -const b = { key: 'b' }; -const c = { key: 'c' }; +const b = { key: "b" }; +const c = { key: "c" }; a[b] = 123; a[c] = 456; @@ -916,9 +915,9 @@ Quindi, quando facciamo console.log di `a[b]`, che in realtà è `a["[object Obj ###### 30. Qual è l'output? ```javascript -const foo = () => console.log('First'); -const bar = () => setTimeout(() => console.log('Second')); -const baz = () => console.log('Third'); +const foo = () => console.log("First"); +const bar = () => setTimeout(() => console.log("Second")); +const baz = () => console.log("Third"); bar(); foo(); @@ -971,9 +970,7 @@ La WebAPI non può semplicemente aggiungere elementi allo stack ogni volta che ```html
- +
``` @@ -999,9 +996,7 @@ L'elemento annidato più in profondità è quello che ha causato l'evento ed è ```html
-

- Click here! -

+

Click here!

``` @@ -1025,7 +1020,7 @@ Se clicchiamo su `p`, vediamo due log: `p` e `div`. Durante la propagazione dell ###### 33. Qual è l'output? ```javascript -const person = { name: 'Lydia' }; +const person = { name: "Lydia" }; function sayHi(age) { return `${this.name} is ${age}`; @@ -1088,8 +1083,8 @@ Ci sono solo 7 tipi built-in: `null`, `undefined`, `boolean`, `number`, `string` ```javascript 0; new Number(0); -(''); -(' '); +(""); +(" "); new Boolean(false); undefined; ``` @@ -1238,11 +1233,14 @@ Ciò che differenzia un tipo primitivo da un oggetto è che i primitivi non hann ###### 40. Qual è l'output? ```javascript -[[0, 1], [2, 3]].reduce( +[ + [0, 1], + [2, 3], +].reduce( (acc, cur) => { return acc.concat(cur); }, - [1, 2], + [1, 2] ); ``` @@ -1259,6 +1257,7 @@ Ciò che differenzia un tipo primitivo da un oggetto è che i primitivi non hann `[1, 2]` rappresenta il nostro valore interno. Ovvero il valore con cui iniziamo e il valore del primo `acc`. Durante il primo round, `acc` è `[1,2]` e `cur` è `[0, 1]`. Li concateniamo ottenendo `[1, 2, 0, 1]`. A questo punto `acc` corrisponderà a `[1, 2, 0, 1]` e `cur` sarà ancora `[2, 3]`. Li concateniamo e otteniamo `[1, 2, 0, 1, 2, 3]` +

@@ -1268,7 +1267,7 @@ A questo punto `acc` corrisponderà a `[1, 2, 0, 1]` e `cur` sarà ancora `[2, 3 ```javascript !!null; -!!''; +!!""; !!1; ``` @@ -1296,7 +1295,7 @@ A questo punto `acc` corrisponderà a `[1, 2, 0, 1]` e `cur` sarà ancora `[2, 3 ###### 42. Cosa restituisce il metodo `setInterval` nel browser? ```javascript -setInterval(() => console.log('Hi'), 1000); +setInterval(() => console.log("Hi"), 1000); ``` - A: un ID univoco @@ -1319,7 +1318,7 @@ Restituisce un ID univoco. Questo id può essere usato per cancellare quell'inte ###### 43. Cosa restituisce? ```javascript -[...'Lydia']; +[..."Lydia"]; ``` - A: `["L", "y", "d", "i", "a"]` @@ -1378,14 +1377,14 @@ Invochiamo di nuovo la funzione con il metodo `next()`. Inizia a continuare da d ```javascript const firstPromise = new Promise((res, rej) => { - setTimeout(res, 500, 'one'); + setTimeout(res, 500, "one"); }); const secondPromise = new Promise((res, rej) => { - setTimeout(res, 100, 'two'); + setTimeout(res, 100, "two"); }); -Promise.race([firstPromise, secondPromise]).then(res => console.log(res)); +Promise.race([firstPromise, secondPromise]).then((res) => console.log(res)); ``` - A: `"one"` @@ -1408,7 +1407,7 @@ Quando passiamo più promises al metodo `Promise.race`, questo risolve/rifiuta l ###### 46. Qual è l'output? ```javascript -let person = { name: 'Lydia' }; +let person = { name: "Lydia" }; const members = [person]; person = null; @@ -1448,7 +1447,7 @@ Stiamo modificando solo il valore della variabile `person`, e non il primo eleme ```javascript const person = { - name: 'Lydia', + name: "Lydia", age: 21, }; @@ -1477,7 +1476,7 @@ Con il ciclo `for-in`, possiamo iterare le chiavi degli oggetti, in questo caso ###### 48. Qual è l'output? ```javascript -console.log(3 + 4 + '5'); +console.log(3 + 4 + "5"); ``` - A: `"345"` @@ -1504,7 +1503,7 @@ L'associazione è l'ordine in cui il compilatore valuta le espressioni, da sinis ###### 49. Qual è il valore di `num`? ```javascript -const num = parseInt('7*6', 10); +const num = parseInt("7*6", 10); ``` - A: `42` @@ -1529,8 +1528,8 @@ Viene restituito solo il primo valore della stringa. In base alla _radice_ (ovve ###### 50. Qual è l'output? ```javascript -[1, 2, 3].map(num => { - if (typeof num === 'number') return; +[1, 2, 3].map((num) => { + if (typeof num === "number") return; return num * 2; }); ``` @@ -1558,12 +1557,12 @@ Tuttavia, non ritorniamo un valore. Quando non ritorniamo un valore dalla funzio ```javascript function getInfo(member, year) { - member.name = 'Lydia'; - year = '1998'; + member.name = "Lydia"; + year = "1998"; } -const person = { name: 'Sarah' }; -const birthYear = '1997'; +const person = { name: "Sarah" }; +const birthYear = "1997"; getInfo(person, birthYear); @@ -1585,6 +1584,7 @@ Gli argomenti vengono passati come _valori_, a meno che il loro valore non sia u La variabile `birthYear` ha un riferimento al valore `"1997"`. Anche l'argomento `year` fa riferimento al valore `"1997"`, ma non è lo stesso valore a cui fa riferimento `birthYear`. Quando aggiorniamo il valore di `year` impostando `year` uguale a `"1998"`, stiamo solo aggiornando il valore di `year`. `birthYear` è ancora uguale a `"1997"`. Il valore di `person` è un oggetto. L'argomento `member` ha un riferimento (copiato) dello stesso oggetto. Quando modifichiamo una proprietà dell'oggetto a cui `member` fa riferimento, verrà modificato anche il valore di `person`, poiché entrambi hanno un riferimento allo stesso oggetto. La proprietà `name` di `person` è ora uguale al valore `"Lydia"` +

@@ -1594,15 +1594,15 @@ Il valore di `person` è un oggetto. L'argomento `member` ha un riferimento (cop ```javascript function greeting() { - throw 'Hello world!'; + throw "Hello world!"; } function sayHi() { try { const data = greeting(); - console.log('It worked!', data); + console.log("It worked!", data); } catch (e) { - console.log('Oh no an error:', e); + console.log("Oh no an error:", e); } } @@ -1632,8 +1632,8 @@ Con l'istruzione `catch`, possiamo specificare cosa fare se viene generata un'ec ```javascript function Car() { - this.make = 'Lamborghini'; - return { make: 'Maserati' }; + this.make = "Lamborghini"; + return { make: "Maserati" }; } const myCar = new Car(); @@ -1705,11 +1705,11 @@ class Dog { } } -Dog.prototype.bark = function() { +Dog.prototype.bark = function () { console.log(`Woof I am ${this.name}`); }; -const pet = new Dog('Mara'); +const pet = new Dog("Mara"); pet.bark(); @@ -1774,7 +1774,7 @@ export default counter; ```javascript // index.js -import myCounter from './counter'; +import myCounter from "./counter"; myCounter += 1; @@ -1803,7 +1803,7 @@ Quando proviamo ad incrementare il valore di `myCounter`, viene generato un erro ###### 58. Qual è l'output? ```javascript -const name = 'Lydia'; +const name = "Lydia"; age = 21; console.log(delete name); @@ -1874,7 +1874,7 @@ Questo significa che il valore di `y` è uguale al primo valore nell'array, che ###### 60. Qual è l'output? ```javascript -const user = { name: 'Lydia', age: 21 }; +const user = { name: "Lydia", age: 21 }; const admin = { admin: true, ...user }; console.log(admin); @@ -1900,9 +1900,9 @@ console.log(admin); ###### 61. Qual è l'output? ```javascript -const person = { name: 'Lydia' }; +const person = { name: "Lydia" }; -Object.defineProperty(person, 'age', { value: 21 }); +Object.defineProperty(person, "age", { value: 21 }); console.log(person); console.log(Object.keys(person)); @@ -1931,12 +1931,12 @@ Le proprietà aggiunte usando il metodo `defineProperty` sono immutabili per imp ```javascript const settings = { - username: 'lydiahallie', + username: "lydiahallie", level: 19, health: 90, }; -const data = JSON.stringify(settings, ['level', 'health']); +const data = JSON.stringify(settings, ["level", "health"]); console.log(data); ``` @@ -1967,7 +1967,7 @@ Se il replacer è una _funzione_, questa funzione viene chiamata su ogni proprie let num = 10; const increaseNumber = () => num++; -const increasePassedNumber = number => number++; +const increasePassedNumber = (number) => number++; const num1 = increaseNumber(); const num2 = increasePassedNumber(num1); @@ -2049,7 +2049,7 @@ La quarta volta, passiamo di nuovo l'oggetto `value`, in questo caso `x.number` #### Risposta: D -Il primo argomento che il metodo `reduce` riceve è l'_accumulatore_, in questo caso `x`. Il secondo argomento è il _valore corrente_ `y`. +Il primo argomento che il metodo `reduce` riceve è l'_accumulatore_, in questo caso `x`. Il secondo argomento è il _valore corrente_ `y`. Con il metodo reduce, eseguiamo una funzione di callback su ogni elemento dell'array, che alla fine potrebbe risultare in un singolo valore. In questo esempio, non stiamo restituendo alcun valore, stiamo semplicemente loggando i valori dell'accumulatore e il valore corrente. @@ -2061,6 +2061,7 @@ Alla prima chiamata, l'accumulatore (`x`) è `1` e il valore corrente (`y`) è ` Se non restituisci un valore da una funzione questa restituisce `undefined`. Alla chiamata successiva, l'accumulatore è `undefined` e il valore corrente è "3". `undefined` e `3` vengono loggati. Alla quarta chiamata, di nuovo non facciamo un return dalla funzione di callback. L'accumulatore è di nuovo `undefined` e il valore corrente è "4". `undefined` e `4` vengono loggati. +

@@ -2124,12 +2125,12 @@ La classe `Labrador` riceve due argomenti, `name` poiché estende `Dog`, e `size ```javascript // index.js -console.log('running index.js'); -import { sum } from './sum.js'; +console.log("running index.js"); +import { sum } from "./sum.js"; console.log(sum(1, 2)); // sum.js -console.log('running sum.js'); +console.log("running sum.js"); export const sum = (a, b) => a + b; ``` @@ -2157,7 +2158,7 @@ Questa è una delle differenze tra `require()` in CommonJS e `import`. Con `requ ```javascript console.log(Number(2) === Number(2)); console.log(Boolean(false) === Boolean(false)); -console.log(Symbol('foo') === Symbol('foo')); +console.log(Symbol("foo") === Symbol("foo")); ``` - A: `true`, `true`, `false` @@ -2180,7 +2181,7 @@ Ogni Simbolo è unico. Lo scopo dell'argomento passato a Symbol è di dargli una ###### 69. Qual è l'output? ```javascript -const name = 'Lydia Hallie'; +const name = "Lydia Hallie"; console.log(name.padStart(13)); console.log(name.padStart(2)); ``` @@ -2207,7 +2208,7 @@ Se l'argomento passato al metodo `padStart` è inferiore alla lunghezza dell'arr ###### 70. Qual è l'output? ```javascript -console.log('🥑' + '💻'); +console.log("🥑" + "💻"); ``` - A: `"🥑💻"` @@ -2231,11 +2232,11 @@ Con l'operatore `+` puoi concatenare stringhe. In questo caso, stiamo concatenan ```javascript function* startGame() { - const answer = yield 'Do you love JavaScript?'; - if (answer !== 'Yes') { + const answer = yield "Do you love JavaScript?"; + if (answer !== "Yes") { return "Oh wow... Guess we're gone here"; } - return 'JavaScript loves you back ❤️'; + return "JavaScript loves you back ❤️"; } const game = startGame(); @@ -2303,7 +2304,7 @@ In questo caso, è la stringa `Hello\nworld` che viene loggata. ```javascript async function getData() { - return await Promise.resolve('I made it!'); + return await Promise.resolve("I made it!"); } const data = getData(); @@ -2340,7 +2341,7 @@ function addToList(item, list) { return list.push(item); } -const result = addToList('apple', ['banana']); +const result = addToList("apple", ["banana"]); console.log(result); ``` @@ -2354,10 +2355,10 @@ console.log(result); #### Risposta: B -Il metodo `.push()` restituisce la _lunghezza_ del nuovo array! -Inizialmente, l'array conteneva un solo elemento (la stringa `"banana"`) e aveva una lunghezza di `1`. Dopo aver aggiunto la stringa `"apple"` allo stesso array, questo contiene due elementi e ha una lunghezza di `2` +Il metodo `.push()` restituisce la _lunghezza_ del nuovo array! +Inizialmente, l'array conteneva un solo elemento (la stringa `"banana"`) e aveva una lunghezza di `1`. Dopo aver aggiunto la stringa `"apple"` allo stesso array, questo contiene due elementi e ha una lunghezza di `2` -Attraverso la funzione `addToList`, il metodo `push` modifica l'array originale. +Attraverso la funzione `addToList`, il metodo `push` modifica l'array originale. Per restituire l'_array_ dalla funzione invece della _lunghezza dell'array_, serve fare un return di `list` dopo aver inserito l'`item`.

@@ -2390,10 +2391,10 @@ console.log(shape); `Object.freeze` rende impossibile aggiungere, rimuovere o modificare le proprietà di un oggetto (a meno che il valore della proprietà non sia un altro oggetto). -Quando creiamo la variabile `shape` e la impostiamo come all'oggetto congelato `box`, anche `shape` si riferisce ad un oggetto congelato. +Quando creiamo la variabile `shape` e la impostiamo come all'oggetto congelato `box`, anche `shape` si riferisce ad un oggetto congelato. Puoi controllare se un oggetto è congelato usando `Object.isFrozen`. In questo caso, `Object.isFrozen(shape)` restituisce true, poiché la variabile `shape` ha un riferimento a un oggetto congelato. -Poiché `shape` è congelata, e poiché il valore di `x` non è un oggetto, non possiamo modificare la proprietà `x`. +Poiché `shape` è congelata, e poiché il valore di `x` non è un oggetto, non possiamo modificare la proprietà `x`. `x` è ancora uguale a `10` e `{ x: 10, y: 20 }` viene loggato.

@@ -2404,7 +2405,7 @@ Poiché `shape` è congelata, e poiché il valore di `x` non è un oggetto, non ###### 76. Qual è l'output? ```javascript -const { name: myName } = { name: 'Lydia' }; +const { name: myName } = { name: "Lydia" }; console.log(name); ``` @@ -2460,7 +2461,7 @@ La funzione `sum` restituisce sempre lo stesso risultato. Se le passiamo `1` e ` ```javascript const add = () => { const cache = {}; - return num => { + return (num) => { if (num in cache) { return `From cache! ${cache[num]}`; } else { @@ -2487,13 +2488,13 @@ console.log(addFunction(5 * 2)); #### Risposta: C -La funzione `add` è una funzione _memoizzata_. Con la memorizzazione, possiamo memorizzare nella cache i risultati di una funzione per velocizzarne l'esecuzione. +La funzione `add` è una funzione _memoizzata_. Con la memorizzazione, possiamo memorizzare nella cache i risultati di una funzione per velocizzarne l'esecuzione. In questo caso, creiamo un oggetto `cache` che memorizza i valori precedentemente restituiti. Se chiamiamo di nuovo la funzione `addFunction` con lo stesso argomento, prima controlla se ha già ottenuto quel valore nella sua cache, in tal caso, verrà restituito il valore della cache, consentendo di risparmiare tempo di esecuzione. Altrimenti, se non è memorizzato nella cache, calcolerà il valore e lo memorizzerà in seguito. -Chiamiamo la funzione `addFunction` tre volte con lo stesso valore: alla prima chiamata, il valore della funzione quando `num` è uguale a `10` non è ancora memorizzato nella cache. -La condizione dell'istruzione if `num in cache` restituisce `false`, e il blocco else viene eseguito: `Calculated! 20` viene loggato e il valore del risultato viene aggiunto all'oggetto cache. +Chiamiamo la funzione `addFunction` tre volte con lo stesso valore: alla prima chiamata, il valore della funzione quando `num` è uguale a `10` non è ancora memorizzato nella cache. +La condizione dell'istruzione if `num in cache` restituisce `false`, e il blocco else viene eseguito: `Calculated! 20` viene loggato e il valore del risultato viene aggiunto all'oggetto cache. `cache` ora è uguale a `{ 10: 20 }`. La seconda volta, l'oggetto `cache` contiene il valore che viene restituito per `10`. La condizione dell'istruzione if `num in cache` restituisce `true` e `'From cache! 20'` viene loggato. @@ -2508,7 +2509,7 @@ La terza volta, passiamo `5 * 2` alla funzione che viene valutata a `10`. L'ogge ###### 79. Qual è l'output? ```javascript -const myLifeSummedUp = ['☕', '💻', '🍷', '🍫']; +const myLifeSummedUp = ["☕", "💻", "🍷", "🍫"]; for (let item in myLifeSummedUp) { console.log(item); @@ -2604,13 +2605,13 @@ In questo caso, se non abbiamo passato un valore o se abbiamo passato `undefined ###### 82. Qual è l'output? ```javascript -var status = '😎'; +var status = "😎"; setTimeout(() => { - const status = '😍'; + const status = "😍"; const data = { - status: '🥑', + status: "🥑", getStatus() { return this.status; }, @@ -2644,12 +2645,12 @@ Con il metodo `call` possiamo cambiare l'oggetto a cui fa riferimento la parola ```javascript const person = { - name: 'Lydia', + name: "Lydia", age: 21, }; let city = person.city; -city = 'Amsterdam'; +city = "Amsterdam"; console.log(person); ``` @@ -2713,9 +2714,9 @@ Le variabili con la chiave `const` e `let` sono _block-scoped_. Un blocco è qua ###### 85. Che tipo di informazioni verrebbero loggate? ```javascript -fetch('https://www.website.com/api/user/1') - .then(res => res.json()) - .then(res => console.log(res)); +fetch("https://www.website.com/api/user/1") + .then((res) => res.json()) + .then((res) => console.log(res)); ``` - A: Il risultato del metodo `fetch`. @@ -2753,7 +2754,7 @@ function getName(name) { #### Risposta: A -Con `!!name`, determiniamo se il valore di `name` è vero o falso. Se il nome è vero, cosa che vogliamo testare, `!name` restituisce `false`. +Con `!!name`, determiniamo se il valore di `name` è vero o falso. Se il nome è vero, cosa che vogliamo testare, `!name` restituisce `false`. `!false` (che è `!!name`) restituisce `true`. Impostando `hasName` uguale a `name`, imposti `hasName` uguale a qualsiasi valore passato alla funzione `getName`, non il valore booleano `true`. @@ -2770,7 +2771,7 @@ Impostando `hasName` uguale a `name`, imposti `hasName` uguale a qualsiasi valor ###### 87. Qual è l'output? ```javascript -console.log('I want pizza'[0]); +console.log("I want pizza"[0]); ``` - A: `"""` @@ -2815,6 +2816,7 @@ sum(10); È possibile impostare il valore di un parametro predefinito uguale a un altro parametro della funzione, purché sia stato definito _prima_ del parametro predefinito. Passiamo il valore `10` alla funzione `sum`. Se la funzione `sum` riceve solo 1 argomento, significa che il valore di `num2` non è passato e il valore di `num1` è uguale al valore passato `10` in questo caso. Il valore predefinito di `num2` è il valore di `num1`, che è `10`. `num1 + num2` restituisce `20`. Se stai cercando di impostare il valore di un parametro predefinito uguale a un parametro che è definito _dopo_ (a destra), il valore del parametro non è stato ancora inizializzato, il che genererà un errore. +

@@ -2824,11 +2826,11 @@ Se stai cercando di impostare il valore di un parametro predefinito uguale a un ```javascript // module.js -export default () => 'Hello world'; -export const name = 'Lydia'; +export default () => "Hello world"; +export const name = "Lydia"; // index.js -import * as data from './module'; +import * as data from "./module"; console.log(data); ``` @@ -2861,7 +2863,7 @@ class Person { } } -const member = new Person('John'); +const member = new Person("John"); console.log(typeof member); ``` @@ -2921,7 +2923,7 @@ Quindi quando proviamo a usare il metodo `.push` su `newList` poiché `newList` ```javascript function giveLydiaPizza() { - return 'Here is pizza!'; + return "Here is pizza!"; } const giveLydiaChocolate = () => @@ -2942,6 +2944,7 @@ console.log(giveLydiaChocolate.prototype); #### Risposta: D Le funzioni regolari, come la funzione `giveLydiaPizza`, hanno una proprietà `prototipo`, che è un oggetto (prototype object) con un `costruttore`. Tuttavia, le arrow functions, come la funzione `giveLydiaChocolate`, non hanno una proprietà `prototype`. Viene quindi restituito `undefined` quando si tenta di accedere alla proprietà `prototype` usando `giveLydiaChocolate.prototype`. +

@@ -2951,7 +2954,7 @@ Le funzioni regolari, come la funzione `giveLydiaPizza`, hanno una proprietà `p ```javascript const person = { - name: 'Lydia', + name: "Lydia", age: 21, }; @@ -3011,7 +3014,7 @@ function getItems(fruitList, favoriteFruit, ...args) { return [...fruitList, ...args, favoriteFruit]; } -getItems(['banana', 'apple'], 'pear', 'orange'); +getItems(["banana", "apple"], "pear", "orange"); ``` L'esempio qui sopra invece funziona e restituisce l'array `[ 'banana', 'apple', 'orange', 'pear' ]` @@ -3025,9 +3028,9 @@ L'esempio qui sopra invece funziona e restituisce l'array `[ 'banana', 'apple', ```javascript function nums(a, b) { - if (a > b) console.log('a is bigger'); - else console.log('b is bigger'); - return + if (a > b) console.log("a is bigger"); + else console.log("b is bigger"); + return; a + b; } @@ -3045,10 +3048,10 @@ console.log(nums(1, 2)); #### Risposta: B -In JavaScript, non _è necessario_ scrivere il punto e virgola (`;`) in modo esplicito poiché il motore JavaScript li aggiunge comunque dopo le istruzioni. +In JavaScript, non _è necessario_ scrivere il punto e virgola (`;`) in modo esplicito poiché il motore JavaScript li aggiunge comunque dopo le istruzioni. Questo procedimento è chiamato **Automatic Semicolon Insertion**. Un'istruzione può ad esempio essere una variabile o parole chiave come `throw`, `return`, `break`, ecc. -Qui, abbiamo scritto un'istruzione di `return` e un altro valore `a + b` su una _nuova riga_. Tuttavia, trattandosi di una nuova linea, il motore non sa che in realtà è il valore che volevamo restituire. Invece, ha aggiunto automaticamente un punto e virgola dopo `return`. +Qui, abbiamo scritto un'istruzione di `return` e un altro valore `a + b` su una _nuova riga_. Tuttavia, trattandosi di una nuova linea, il motore non sa che in realtà è il valore che volevamo restituire. Invece, ha aggiunto automaticamente un punto e virgola dopo `return`. Potresti considerare ad esempio: @@ -3057,7 +3060,7 @@ return; a + b; ``` -`a + b` non viene mai raggiunto, poiché la funzione smette di funzionare dopo la parola chiave `return`. +`a + b` non viene mai raggiunto, poiché la funzione smette di funzionare dopo la parola chiave `return`. Se non viene restituito alcun valore, come qui, la funzione restituisce `undefined`. Nota: non c'è un inserimento automatico dopo le istruzioni `if/else`!

@@ -3070,13 +3073,13 @@ Se non viene restituito alcun valore, come qui, la funzione restituisce `undefin ```javascript class Person { constructor() { - this.name = 'Lydia'; + this.name = "Lydia"; } } Person = class AnotherPerson { constructor() { - this.name = 'Sarah'; + this.name = "Sarah"; } }; @@ -3094,7 +3097,7 @@ console.log(member.name); #### Risposta: B -Possiamo impostare classi uguali ad altre classi/costruttori di funzioni. In questo caso, impostiamo `Person` uguale a `AnotherPerson`. Il name su questo costruttore è `Sarah`, quindi la proprietà del nome di`Person` sulla nuova istanza `member` è `"Sarah"`. +Possiamo impostare classi uguali ad altre classi/costruttori di funzioni. In questo caso, impostiamo `Person` uguale a `AnotherPerson`. Il name su questo costruttore è `Sarah`, quindi la proprietà del nome di`Person` sulla nuova istanza `member` è `"Sarah"`.

@@ -3105,7 +3108,7 @@ Possiamo impostare classi uguali ad altre classi/costruttori di funzioni. In que ```javascript const info = { - [Symbol('a')]: 'b', + [Symbol("a")]: "b", }; console.log(info); @@ -3158,7 +3161,7 @@ La funzione `getList` riceve un array come argomento. Tra le parentesi della fun `[x, ...y] = [1, 2, 3, 4]` -Con il parametro rest `...y`, mettiamo tutti gli argomenti "rimanenti" in un array. Gli argomenti rimanenti sono `2`, `3` e `4` in questo caso. +Con il parametro rest `...y`, mettiamo tutti gli argomenti "rimanenti" in un array. Gli argomenti rimanenti sono `2`, `3` e `4` in questo caso. Il valore di `y` è un array, contenente tutti i parametri rimanenti. Il valore di `x` è uguale a `1` in questo caso, quindi quando facciamo un console.log di `[x, y]`, viene loggato `[1, [2, 3, 4]]`. La funzione `getUser` riceve un oggetto. Con le arrow functions, non _è necessario_ scrivere parentesi graffe se restituiamo solo un valore. Tuttavia, se vuoi restituire istantaneamente un _oggetto_ da una arrow function, devi scriverlo tra parentesi tonde, altrimenti tutto ciò che si trova tra le due parentesi graffe verrà interpretato come un'istruzione di blocco. In questo caso il codice tra parentesi non è un codice JavaScript valido, quindi viene generato un `SyntaxError`. @@ -3175,7 +3178,7 @@ La seguente funzione avrebbe restituito un oggetto: ###### 99. Qual è l'output? ```javascript -const name = 'Lydia'; +const name = "Lydia"; console.log(name()); ``` @@ -3207,8 +3210,8 @@ I ReferenceErrors vengono generati quando JavaScript non è in grado di trovare ```javascript // 🎉✨ This is my 100th question! ✨🎉 -const output = `${[] && 'Im'}possible! -You should${'' && `n't`} see a therapist after so much JavaScript lol`; +const output = `${[] && "Im"}possible! +You should${"" && `n't`} see a therapist after so much JavaScript lol`; ``` - A: `possible! You should see a therapist after so much JavaScript lol` @@ -3234,7 +3237,7 @@ You should${'' && `n't`} see a therapist after so much JavaScript lol`; ```javascript const one = false || {} || null; -const two = null || false || ''; +const two = null || false || ""; const three = [] || 0 || true; console.log(one, two, three); @@ -3266,16 +3269,16 @@ Con l'operatore `||` possiamo restituire il primo operando veritiero. Se tutti i ###### 102. Qual è il valore dell'output? ```javascript -const myPromise = () => Promise.resolve('I have resolved!'); +const myPromise = () => Promise.resolve("I have resolved!"); function firstFunction() { - myPromise().then(res => console.log(res)); - console.log('second'); + myPromise().then((res) => console.log(res)); + console.log("second"); } async function secondFunction() { console.log(await myPromise()); - console.log('second'); + console.log("second"); } firstFunction(); @@ -3313,8 +3316,8 @@ Ciò significa che ha aspettato che `myPromise` si risolvesse con il valore `I h const set = new Set(); set.add(1); -set.add('Lydia'); -set.add({ name: 'Lydia' }); +set.add("Lydia"); +set.add({ name: "Lydia" }); for (let item of set) { console.log(item + 2); @@ -3374,13 +3377,13 @@ In questo caso, abbiamo appena passato il valore numerico `5`. Restituisce una p ```javascript function compareMembers(person1, person2 = person) { if (person1 !== person2) { - console.log('Not the same!'); + console.log("Not the same!"); } else { - console.log('They are the same!'); + console.log("They are the same!"); } } -const person = { name: 'Lydia' }; +const person = { name: "Lydia" }; compareMembers(person); ``` @@ -3419,7 +3422,7 @@ const colorConfig = { yellow: false, }; -const colors = ['pink', 'red', 'blue']; +const colors = ["pink", "red", "blue"]; console.log(colorConfig.colors[1]); ``` @@ -3448,7 +3451,7 @@ JavaScript interpreta (o decomprime) le istruzioni. Quando usiamo la notazione t ###### 107. Qual è il suo valore? ```javascript -console.log('❤️' === '❤️'); +console.log("❤️" === "❤️"); ``` - A: `true` @@ -3469,14 +3472,14 @@ Le emoji sono unicode. L'unicode per l'emoji del cuore è `"U+2764 U+FE0F"`. Que ###### 108. Quale di questi metodi modifica l'array originale? ```javascript -const emojis = ['✨', '🥑', '😍']; +const emojis = ["✨", "🥑", "😍"]; -emojis.map(x => x + '✨'); -emojis.filter(x => x !== '🥑'); -emojis.find(x => x !== '🥑'); -emojis.reduce((acc, cur) => acc + '✨'); -emojis.slice(1, 2, '✨'); -emojis.splice(1, 2, '✨'); +emojis.map((x) => x + "✨"); +emojis.filter((x) => x !== "🥑"); +emojis.find((x) => x !== "🥑"); +emojis.reduce((acc, cur) => acc + "✨"); +emojis.slice(1, 2, "✨"); +emojis.splice(1, 2, "✨"); ``` - A: `All of them` @@ -3492,6 +3495,7 @@ emojis.splice(1, 2, '✨'); Con il metodo `splice` modifichiamo l'array originale cancellando, sostituendo o aggiungendo elementi. In questo caso, abbiamo rimosso 2 elementi dall'indice 1 (abbiamo rimosso `'🥑'` e `'😍'`) e aggiunto invece l'emoji ✨. `map`, `filter` e `slice` restituiscono un nuovo array, `find` restituisce un elemento e `reduce` restituisce un valore ridotto. +

@@ -3500,10 +3504,10 @@ Con il metodo `splice` modifichiamo l'array originale cancellando, sostituendo o ###### 109. Qual è l'output? ```javascript -const food = ['🍕', '🍫', '🥑', '🍔']; +const food = ["🍕", "🍫", "🥑", "🍔"]; const info = { favoriteFood: food[0] }; -info.favoriteFood = '🍝'; +info.favoriteFood = "🍝"; console.log(food); ``` @@ -3523,6 +3527,7 @@ Impostiamo il valore della proprietà `favoriteFood` sull'oggetto `info` uguale In JavaScript, i tipi di dati primitivi (tutto ciò che non è un oggetto) interagiscono per _value_. In questo caso, impostiamo il valore della proprietà `favoriteFood` sull'oggetto `info` uguale al valore del primo elemento nell'array `food`, in questo caso la stringa con l'emoji della pizza (`'🍕'`). Una stringa è un tipo di dati primitivo e interagisce per valore (vedi il mio [blogpost](https://www.theavocoder.com/complete-javascript/2018/12/21/by-value-vs-by-reference) se sei interessato a saperne di più). Quindi, cambiamo il valore della proprietà `favoriteFood` sull'oggetto `info`. L'array `food` non è cambiato, poiché il valore di `favoriteFood` era semplicemente una _copia_ del valore del primo elemento nell'array e non ha un riferimento allo stesso punto in memoria dell'elemento su ` food[0]`. Quando logghiamo food, è ancora l'array originale, `['🍕', '🍫', '🥑', '🍔']`. +

@@ -3556,7 +3561,7 @@ const jsonArray = JSON.stringify([1, 2, 3]); // '[1, 2, 3]' JSON.parse(jsonArray); // [1, 2, 3] // Stringhiamo un object in un JSON valido, quindi analizziamo la stringa JSON come valore JavaScript: -const jsonArray = JSON.stringify({ name: 'Lydia' }); // '{"name":"Lydia"}' +const jsonArray = JSON.stringify({ name: "Lydia" }); // '{"name":"Lydia"}' JSON.parse(jsonArray); // { name: 'Lydia' } ``` @@ -3568,11 +3573,11 @@ JSON.parse(jsonArray); // { name: 'Lydia' } ###### 111. Qual è l'output? ```javascript -let name = 'Lydia'; +let name = "Lydia"; function getName() { console.log(name); - let name = 'Sarah'; + let name = "Sarah"; } getName(); @@ -3595,7 +3600,7 @@ Le variabili con la chiave `let` (e `const`) vengono sollevate, ma a differenza Se non avessimo dichiarato la variabile `name` all'interno della funzione `getName`, JavaScript avrebbe esaminato la _scope chain_. Lo scope esterno ha una variabile chiamata `name` con il valore di `Lydia`. In tal caso, avrebbe loggato "Lydia". ```javascript -let name = 'Lydia'; +let name = "Lydia"; function getName() { console.log(name); @@ -3613,11 +3618,11 @@ getName(); // Lydia ```javascript function* generatorOne() { - yield ['a', 'b', 'c']; + yield ["a", "b", "c"]; } function* generatorTwo() { - yield* ['a', 'b', 'c']; + yield* ["a", "b", "c"]; } const one = generatorOne(); @@ -3663,7 +3668,7 @@ console.log(two.next().value); // undefined ###### 113. Qual è l'output? ```javascript -console.log(`${(x => x)('I love')} to program`); +console.log(`${((x) => x)("I love")} to program`); ``` - A: `I love to program` @@ -3688,7 +3693,7 @@ Le espressioni all'interno dei template literals vengono valutate per prime. Ci ```javascript let config = { alert: setInterval(() => { - console.log('Alert!'); + console.log("Alert!"); }, 1000), }; @@ -3720,16 +3725,16 @@ Dal momento che non è stato cancellato, la funzione di callback `setInterval` v ```javascript const myMap = new Map(); -const myFunc = () => 'greeting'; +const myFunc = () => "greeting"; -myMap.set(myFunc, 'Hello world!'); +myMap.set(myFunc, "Hello world!"); //1 -myMap.get('greeting'); +myMap.get("greeting"); //2 myMap.get(myFunc); //3 -myMap.get(() => 'greeting'); +myMap.get(() => "greeting"); ``` - A: 1 @@ -3756,14 +3761,14 @@ Quando si aggiunge una coppia chiave/valore usando il metodo `set`, la chiave sa ```javascript const person = { - name: 'Lydia', + name: "Lydia", age: 21, }; const changeAge = (x = { ...person }) => (x.age += 1); const changeAgeAndName = (x = { ...person }) => { x.age += 1; - x.name = 'Sarah'; + x.name = "Sarah"; }; changeAge(person); @@ -3787,6 +3792,7 @@ Entrambe le funzioni `changeAge` e `changeAgeAndName` hanno un parametro predefi Per prima cosa, invochiamo la funzione `changeAge` e passiamo l'oggetto `person` come argomento. Questa funzione aumenta il valore della proprietà `age` di 1. `person` ora è `{ name: "Lydia", age: 22 }`. Quindi, invochiamo la funzione `changeAgeAndName`, tuttavia non passiamo un parametro. Invece, il valore di `x` è uguale a un _nuovo_ oggetto: `{ ...person }`. Poiché si tratta di un nuovo oggetto, non influisce sui valori delle proprietà sull'oggetto `person`. `person` è ancora uguale a `{ name: "Lydia", age: 22 }`. +

@@ -3821,7 +3827,7 @@ Con l'operatore spread `...`, possiamo _distribuire_ gli iterabili come singoli ```javascript let num = 1; -const list = ['🥳', '🤠', '🥰', '🤪']; +const list = ["🥳", "🤠", "🥰", "🤪"]; console.log(list[(num += 1)]); ``` @@ -3847,11 +3853,11 @@ Con l'operando `+=`, stiamo incrementando il valore di `num` di `1`. `num` aveva ```javascript const person = { - firstName: 'Lydia', - lastName: 'Hallie', + firstName: "Lydia", + lastName: "Hallie", pet: { - name: 'Mara', - breed: 'Dutch Tulip Hound', + name: "Mara", + breed: "Dutch Tulip Hound", }, getFullName() { return `${this.firstName} ${this.lastName}`; @@ -3889,10 +3895,10 @@ Con l'operatore di concatenamento opzionale `?.`, non è più necessario verific ###### 120. Qual è l'output? ```javascript -const groceries = ['banana', 'apple', 'peanuts']; +const groceries = ["banana", "apple", "peanuts"]; -if (groceries.indexOf('banana')) { - console.log('We have to buy bananas!'); +if (groceries.indexOf("banana")) { + console.log("We have to buy bananas!"); } else { console.log(`We don't have to buy bananas!`); } @@ -3948,10 +3954,10 @@ Il metodo `language` è un `setter`. I setter non detengono un valore effettivo, ###### 122. Qual è l'output? ```javascript -const name = 'Lydia Hallie'; +const name = "Lydia Hallie"; -console.log(!typeof name === 'object'); -console.log(!typeof name === 'string'); +console.log(!typeof name === "object"); +console.log(!typeof name === "string"); ``` - A: `false` `true` @@ -3967,6 +3973,7 @@ console.log(!typeof name === 'string'); `typeof name` restituisce `"string"`. La stringa `"string"` è un valore veritiero, quindi `!typeof name` restituisce il valore booleano `false`. `false === "object"` e `false === "string"` restituiscono entrambi `false`. (Se volessimo verificare se il tipo era (non)uguale a un certo tipo, avremmo dovuto scrivere `!==` invece di `!typeof`) +

@@ -3975,7 +3982,7 @@ console.log(!typeof name === 'string'); ###### 123. Qual è l'output? ```javascript -const add = x => y => z => { +const add = (x) => (y) => (z) => { console.log(x, y, z); return x + y + z; }; @@ -3993,7 +4000,7 @@ add(4)(5)(6); #### Risposta: A -La funzione `add` restituisce una arrow function, che restituisce una arrow function, che restituisce arrow function (mi segui ancora?). +La funzione `add` restituisce una arrow function, che restituisce una arrow function, che restituisce arrow function (mi segui ancora?). La prima funzione riceve un argomento `x` con il valore di `4`. Invochiamo la seconda funzione, che riceve un argomento `y` con il valore `5`. Quindi invochiamo la terza funzione, che riceve un argomento `z` con il valore `6`. Quando si tenta di accedere ai valori `x`, `y` e `z` all'interno dell'ultima arrow function, il motore JS risale la catena dell'ambito per trovare i valori per `x` e `y`. Questo restituisce `4` `5` `6`.

@@ -4066,20 +4073,20 @@ myFunc(1, 2, 3); ```javascript function getFine(speed, amount) { - const formattedSpeed = new Intl.NumberFormat('en-US', { - style: 'unit', - unit: 'mile-per-hour' + const formattedSpeed = new Intl.NumberFormat("en-US", { + style: "unit", + unit: "mile-per-hour", }).format(speed); - const formattedAmount = new Intl.NumberFormat('en-US', { - style: 'currency', - currency: 'USD' + const formattedAmount = new Intl.NumberFormat("en-US", { + style: "currency", + currency: "USD", }).format(amount); return `The driver drove ${formattedSpeed} and has to pay ${formattedAmount}`; } -console.log(getFine(130, 300)) +console.log(getFine(130, 300)); ``` - A: The driver drove 130 and has to pay 300 @@ -4102,8 +4109,8 @@ Con il metodo `Intl.NumberFormat`, possiamo formattare i valori numerici in qual ###### 127. Qual è l'output? ```javascript -const spookyItems = ['👻', '🎃', '🕸']; -({ item: spookyItems[3] } = { item: '💀' }); +const spookyItems = ["👻", "🎃", "🕸"]; +({ item: spookyItems[3] } = { item: "💀" }); console.log(spookyItems); ``` @@ -4128,7 +4135,7 @@ Destrutturando gli oggetti, possiamo decomprimere i valori dall'oggetto di destr ###### 128. Qual è l'output? ```javascript -const name = 'Lydia Hallie'; +const name = "Lydia Hallie"; const age = 21; console.log(Number.isNaN(name)); @@ -4151,6 +4158,7 @@ console.log(isNaN(age)); Con il metodo `Number.isNaN`, puoi controllare se il valore passato è un _valore numerico_ e uguale a `NaN`. `name` non è un valore numerico, quindi `Number.isNaN(name)` restituisce `false`. `age` è un valore numerico, ma non è uguale a `NaN`, quindi `Numero.isNaN(age)` restituisce `false`. Con il metodo `isNaN`, puoi verificare se il valore che passi non è un numero. `name` non è un numero, quindi `isNaN(name)` restituisce true. `age` è un numero, quindi `isNaN(age)` restituisce `false`. +

@@ -4163,7 +4171,7 @@ const randomValue = 21; function getInfo() { console.log(typeof randomValue); - const randomValue = 'Lydia Hallie'; + const randomValue = "Lydia Hallie"; } getInfo(); @@ -4180,6 +4188,7 @@ getInfo(); #### Risposta: D Le variabili dichiarate con la chiave `const` non sono referenziabili prima della loro inizializzazione: questa viene chiamata _temporal dead zone_. Nella funzione `getInfo`, la variabile `randomValue` ha lo scopo nell'ambito funzionale di `getInfo`. Nella riga in cui vogliamo registrare il valore di `typeof randomValue`, la variabile `randomValue` non è ancora inizializzata: viene lanciato un `ReferenceError`! Il motore non è andato giù per la catena dell'ambito poiché abbiamo dichiarato la variabile `randomValue` nella funzione `getInfo`. +

@@ -4188,7 +4197,7 @@ Le variabili dichiarate con la chiave `const` non sono referenziabili prima dell ###### 130. Qual è l'output? ```javascript -const myPromise = Promise.resolve('Woah some cool data'); +const myPromise = Promise.resolve("Woah some cool data"); (async () => { try { @@ -4196,7 +4205,7 @@ const myPromise = Promise.resolve('Woah some cool data'); } catch { throw new Error(`Oops didn't work`); } finally { - console.log('Oh finally!'); + console.log("Oh finally!"); } })(); ``` @@ -4221,7 +4230,7 @@ Nel blocco `try`, stiamo loggando il valore atteso della variabile `myPromise`: ###### 131. Qual è l'output? ```javascript -const emojis = ['🥑', ['✨', '✨', ['🍕', '🍕']]]; +const emojis = ["🥑", ["✨", "✨", ["🍕", "🍕"]]]; console.log(emojis.flat(1)); ``` @@ -4237,6 +4246,7 @@ console.log(emojis.flat(1)); #### Risposta: B Con il metodo `flat`, possiamo creare un nuovo array appiattito. La profondità dell'array appiattito dipende dal valore che passiamo. In questo caso, abbiamo passato il valore `1` (cosa che non dovevamo fare, questo è il valore predefinito), il che significa che solo gli array sulla prima profondità verranno concatenati. `['🥑']` e `['✨', '✨', ['🍕', '🍕']]` in questo caso. Concatenando questi due array si ottengono `['🥑', '✨', '✨', ['🍕', '🍕']]`. +

@@ -4293,19 +4303,19 @@ Invochiamo `counterTwo.increment()`, che imposta `count` su `3`. Quindi, logghia ###### 133. Qual è l'output? ```javascript -const myPromise = Promise.resolve(Promise.resolve('Promise')); +const myPromise = Promise.resolve(Promise.resolve("Promise")); function funcOne() { - setTimeout(() => console.log('Timeout 1!'), 0); - myPromise.then(res => res).then(res => console.log(`${res} 1!`)); - console.log('Last line 1!'); + setTimeout(() => console.log("Timeout 1!"), 0); + myPromise.then((res) => res).then((res) => console.log(`${res} 1!`)); + console.log("Last line 1!"); } async function funcTwo() { const res = await myPromise; - console.log(`${res} 2!`) - setTimeout(() => console.log('Timeout 2!'), 0); - console.log('Last line 2!'); + console.log(`${res} 2!`); + setTimeout(() => console.log("Timeout 2!"), 0); + console.log("Last line 2!"); } funcOne(); @@ -4335,6 +4345,7 @@ In `funcTwo`, la variabile `res` ottiene `Promise` perché `Promise.resolve(Prom Quindi lo stack di chiamate è vuoto. Le promise sono _microattività_, quindi vengono risolte per prime quando lo stack di chiamate è vuoto, quindi `Promise 1!` viene registrato. Ora, da quando `funcTwo` è uscito dallo stack delle chiamate, lo stack delle chiamate è vuoto. Le callback in attesa nella coda (`() => console.log("Timeout 1!")` da `funcOne`, e `() => console.log("Timeout 2!")` da `funcTwo`) vengono aggiunti allo stack di chiamate uno per uno. Il primo callback registra `Timeout 1!` e viene eliminato dallo stack. Quindi, il secondo callback registra `Timeout 2!` e viene eliminato dallo stack. +

@@ -4349,7 +4360,7 @@ export default function sum(x) { } // index.js -import * as sum from './sum'; +import * as sum from "./sum"; ``` - A: `sum(4)` @@ -4366,12 +4377,12 @@ Con l'asterisco `*`, importiamo tutti i valori esportati da quel file, sia prede ```javascript // info.js -export const name = 'Lydia'; +export const name = "Lydia"; export const age = 21; -export default 'I love JavaScript'; +export default "I love JavaScript"; // index.js -import * as info from './info'; +import * as info from "./info"; console.log(info); ``` @@ -4402,13 +4413,13 @@ Possiamo invocare questa funzione, chiamando `sum.default` ```javascript const handler = { - set: () => console.log('Added a new property!'), - get: () => console.log('Accessed a property!'), + set: () => console.log("Added a new property!"), + get: () => console.log("Accessed a property!"), }; const person = new Proxy({}, handler); -person.name = 'Lydia'; +person.name = "Lydia"; person.name; ``` @@ -4438,7 +4449,7 @@ Quindi, accediamo a un valore di proprietà sull'oggetto proxy, la proprietà `g ###### 136. Quale delle seguenti opzioni modificherà l'oggetto `persona`? ```javascript -const person = { name: 'Lydia Hallie' }; +const person = { name: "Lydia Hallie" }; Object.seal(person); ``` @@ -4466,9 +4477,9 @@ Tuttavia, puoi comunque modificare il valore delle proprietà esistenti. ```javascript const person = { - name: 'Lydia Hallie', + name: "Lydia Hallie", address: { - street: '100 Main St', + street: "100 Main St", }, }; @@ -4497,7 +4508,7 @@ Tuttavia, blocca solo _poco profondamente_ l'oggetto, il che significa che solo ###### 138. Qual è l'output? ```javascript -const add = x => x + x; +const add = (x) => x + x; function myFunc(num = 2, value = add(num)) { console.log(num, value); @@ -4519,7 +4530,7 @@ myFunc(3); Per prima cosa, abbiamo invocato `myFunc()` senza passare alcun argomento. Dal momento che non abbiamo passato argomenti, `num` e `value` hanno i loro valori predefiniti: num è `2` e `value` il valore restituito dalla funzione `add`. Alla funzione `add`, passiamo `num` come argomento, che aveva il valore di `2`. `add` restituisce `4`, che è il valore di `value`. -Quindi, abbiamo invocato `myFunc(3)` e passato il valore `3` come valore per l'argomento `num`. Non abbiamo passato un argomento per `value`. +Quindi, abbiamo invocato `myFunc(3)` e passato il valore `3` come valore per l'argomento `num`. Non abbiamo passato un argomento per `value`. Poiché non abbiamo passato un valore per l'argomento `value`, ha ottenuto il valore predefinito: il valore restituito dalla funzione `add`. Ad `add` passiamo `num`, che ha il valore di `3`. `add` restituisce `6`, che è il valore di `value`.

@@ -4531,21 +4542,21 @@ Poiché non abbiamo passato un valore per l'argomento `value`, ha ottenuto il va ```javascript class Counter { - #number = 10 + #number = 10; increment() { - this.#number++ + this.#number++; } getNum() { - return this.#number + return this.#number; } } -const counter = new Counter() -counter.increment() +const counter = new Counter(); +counter.increment(); -console.log(counter.#number) +console.log(counter.#number); ``` - A: `10` @@ -4569,8 +4580,8 @@ In ES2020, possiamo aggiungere variabili private nelle classi usando `#`. Non po ```javascript const teams = [ - { name: 'Team 1', members: ['Paul', 'Lisa'] }, - { name: 'Team 2', members: ['Laura', 'Tim'] }, + { name: "Team 1", members: ["Paul", "Lisa"] }, + { name: "Team 2", members: ["Laura", "Tim"] }, ]; function* getMembers(members) { @@ -4613,8 +4624,8 @@ Se avessimo scritto `yield`, `return yield` o `return`, l'intera funzione del ge ```javascript const person = { - name: 'Lydia Hallie', - hobbies: ['coding'], + name: "Lydia Hallie", + hobbies: ["coding"], }; function addHobby(hobby, hobbies = person.hobbies) { @@ -4622,9 +4633,9 @@ function addHobby(hobby, hobbies = person.hobbies) { return hobbies; } -addHobby('running', []); -addHobby('dancing'); -addHobby('baking', person.hobbies); +addHobby("running", []); +addHobby("dancing"); +addHobby("baking", person.hobbies); console.log(person.hobbies); ``` @@ -4683,7 +4694,7 @@ const pet = new Flamingo(); #### Risposta: B -Creiamo la variabile `pet` che è un'istanza della classe `Flamingo`. Quando istanziamo questa istanza, il `constructor` su `Flamingo` viene chiamato. Per prima cosa, `"I'm pink. 🌸"` viene loggato, dopodiché chiamiamo `super()`. +Creiamo la variabile `pet` che è un'istanza della classe `Flamingo`. Quando istanziamo questa istanza, il `constructor` su `Flamingo` viene chiamato. Per prima cosa, `"I'm pink. 🌸"` viene loggato, dopodiché chiamiamo `super()`. `super()` chiama il costruttore della classe genitore, `Bird`. Il costruttore in `Bird` viene chiamato e registra `"I'm a bird. 🦢"`. @@ -4695,11 +4706,11 @@ Creiamo la variabile `pet` che è un'istanza della classe `Flamingo`. Quando ist ###### 143. Quale delle opzioni genera un errore? ```javascript -const emojis = ['🎄', '🎅🏼', '🎁', '⭐']; +const emojis = ["🎄", "🎅🏼", "🎁", "⭐"]; -/* 1 */ emojis.push('🦌'); +/* 1 */ emojis.push("🦌"); /* 2 */ emojis.splice(0, 2); -/* 3 */ emojis = [...emojis, '🥂']; +/* 3 */ emojis = [...emojis, "🥂"]; /* 4 */ emojis.length = 0; ``` @@ -4741,7 +4752,7 @@ const person = { #### Risposta: C -Gli oggetti non sono iterabili per impostazione predefinita. Un iterabile è un iterabile se è presente il protocollo iteratore. +Gli oggetti non sono iterabili per impostazione predefinita. Un iterabile è un iterabile se è presente il protocollo iteratore. Possiamo aggiungerlo manualmente aggiungendo il simbolo dell'iteratore `[Symbol.iterator]`, che deve restituire un oggetto generatore, ad esempio trasformandolo in una funzione del generatore `*[Symbol.iterator]() {}`. Questa funzione di generazione deve fornire gli `Object.values` dell'oggetto `person` se vogliamo che restituisca l'array `["Lydia Hallie", 21]`: `yield* Object.values(this)`.

@@ -4755,11 +4766,11 @@ Possiamo aggiungerlo manualmente aggiungendo il simbolo dell'iteratore `[Symbol. let count = 0; const nums = [0, 1, 2, 3]; -nums.forEach(num => { - if (num) count += 1 -}) +nums.forEach((num) => { + if (num) count += 1; +}); -console.log(count) +console.log(count); ``` - A: 1 @@ -4783,12 +4794,12 @@ La condizione `if` all'interno del ciclo `forEach` controlla se il valore di `nu ```javascript function getFruit(fruits) { - console.log(fruits?.[1]?.[1]) + console.log(fruits?.[1]?.[1]); } -getFruit([['🍊', '🍌'], ['🍍']]) -getFruit() -getFruit([['🍍'], ['🍊', '🍌']]) +getFruit([["🍊", "🍌"], ["🍍"]]); +getFruit(); +getFruit([["🍍"], ["🍊", "🍌"]]); ``` - A: `null`, `undefined`, 🍌 @@ -4808,6 +4819,7 @@ Innanzitutto, stiamo cercando di registrare il secondo elemento nel sottoarray ` Quindi, stiamo invocando la funzione `getFruits` senza passare un valore come argomento, il che significa che `fruits` ha un valore di `undefined` per impostazione predefinita. Poiché stiamo concatenando condizionatamente l'elemento sull'indice `1` di `fruits`, restituisce `undefined` poiché questo elemento sull'indice `1` non esiste. Infine, stiamo cercando di registrare il secondo elemento nel sottoarray `['🍊', '🍌']` di `['🍍'], ['🍊', '🍌']`. L'elemento nell'indice `1` all'interno di questo sottoarray è `🍌`, che viene registrato. +

@@ -4817,19 +4829,19 @@ Infine, stiamo cercando di registrare il secondo elemento nel sottoarray `['🍊 ```javascript class Calc { - constructor() { - this.count = 0 - } + constructor() { + this.count = 0; + } - increase() { - this.count ++ - } + increase() { + this.count++; + } } -const calc = new Calc() -new Calc().increase() +const calc = new Calc(); +new Calc().increase(); -console.log(calc.count) +console.log(calc.count); ``` - A: `0` @@ -4843,6 +4855,7 @@ console.log(calc.count) #### Risposta: A Impostiamo la variabile `calc` uguale a una nuova istanza della classe `Calc`. Quindi, istanziamo una nuova `Calc` e invochiamo il metodo `increase` su questa istanza. Poiché la proprietà count è all'interno del costruttore della classe `Calc`, la proprietà count non è condivisa sul prototipo di `Calc`. Ciò significa che il valore di count non è stato aggiornato per l'istanza a cui punta il calc, count è ancora `0`. +

@@ -4852,25 +4865,25 @@ Impostiamo la variabile `calc` uguale a una nuova istanza della classe `Calc`. Q ```javascript const user = { - email: "e@mail.com", - password: "12345" -} + email: "e@mail.com", + password: "12345", +}; const updateUser = ({ email, password }) => { - if (email) { - Object.assign(user, { email }) - } + if (email) { + Object.assign(user, { email }); + } - if (password) { - user.password = password - } + if (password) { + user.password = password; + } - return user -} + return user; +}; -const updatedUser = updateUser({ email: "new@email.com" }) +const updatedUser = updateUser({ email: "new@email.com" }); -console.log(updatedUser === user) +console.log(updatedUser === user); ``` - A: `false` @@ -4893,13 +4906,13 @@ La funzione `updateUser` aggiorna i valori delle proprietà `email` e `password` ###### 149. Qual è l'output? ```javascript -const fruit = ['🍌', '🍊', '🍎'] +const fruit = ["🍌", "🍊", "🍎"]; -fruit.slice(0, 1) -fruit.splice(0, 1) -fruit.unshift('🍇') +fruit.slice(0, 1); +fruit.splice(0, 1); +fruit.unshift("🍇"); -console.log(fruit) +console.log(fruit); ``` - A: `['🍌', '🍊', '🍎']` @@ -4925,13 +4938,13 @@ Infine, invochiamo il metodo `unshift` sull'array `fruit`, che modifica l'array ```javascript const animals = {}; -let dog = { emoji: '🐶' } -let cat = { emoji: '🐈' } +let dog = { emoji: "🐶" }; +let cat = { emoji: "🐈" }; -animals[dog] = { ...dog, name: "Mara" } -animals[cat] = { ...cat, name: "Sara" } +animals[dog] = { ...dog, name: "Mara" }; +animals[cat] = { ...cat, name: "Sara" }; -console.log(animals[dog]) +console.log(animals[dog]); ``` - A: `{ emoji: "🐶", name: "Mara" }` @@ -4946,12 +4959,12 @@ console.log(animals[dog]) Le chiavi degli oggetti vengono convertite in stringhe. -Poiché il valore di `dog` è un oggetto, `animals[dog]` significa in realtà che stiamo creando una nuova proprietà chiamata `"object Object"` uguale al nuovo oggetto. +Poiché il valore di `dog` è un oggetto, `animals[dog]` significa in realtà che stiamo creando una nuova proprietà chiamata `"object Object"` uguale al nuovo oggetto. `animals["object Object"]` è ora uguale a `{ emoji: "🐶", name: "Mara"}`. Anche `cat` è un oggetto, il che significa che `animals[cat]` in realtà stiamo sovrascrivendo il valore di `animals["object Object"]` con le nuove proprietà cat. -Loggando `animals[dog]`, o effettivamente `animals["object Object"]`, poiché la conversione dell'oggetto `dog` in una stringa risulta `"object Object"`, restituisce `{ emoji: "🐈", name: "Sara" }`. +Loggando `animals[dog]`, o effettivamente `animals["object Object"]`, poiché la conversione dell'oggetto `dog` in una stringa risulta `"object Object"`, restituisce `{ emoji: "🐈", name: "Sara" }`.

@@ -4962,14 +4975,14 @@ Loggando `animals[dog]`, o effettivamente `animals["object Object"]`, poiché la ```javascript const user = { - email: "my@email.com", - updateEmail: email => { - this.email = email - } -} + email: "my@email.com", + updateEmail: (email) => { + this.email = email; + }, +}; -user.updateEmail("new@email.com") -console.log(user.email) +user.updateEmail("new@email.com"); +console.log(user.email); ``` - A: `my@email.com` @@ -4992,20 +5005,20 @@ La funzione `updateEmail` è una arrow function e non è legata all'oggetto `use ###### 152. Qual è l'output? ```javascript -const promise1 = Promise.resolve('First') -const promise2 = Promise.resolve('Second') -const promise3 = Promise.reject('Third') -const promise4 = Promise.resolve('Fourth') +const promise1 = Promise.resolve("First"); +const promise2 = Promise.resolve("Second"); +const promise3 = Promise.reject("Third"); +const promise4 = Promise.resolve("Fourth"); const runPromises = async () => { - const res1 = await Promise.all([promise1, promise2]) - const res2 = await Promise.all([promise3, promise4]) - return [res1, res2] -} + const res1 = await Promise.all([promise1, promise2]); + const res2 = await Promise.all([promise3, promise4]); + return [res1, res2]; +}; runPromises() - .then(res => console.log(res)) - .catch(err => console.log(err)) + .then((res) => console.log(res)) + .catch((err) => console.log(err)); ``` - A: `[['First', 'Second'], ['Fourth']]` @@ -5025,16 +5038,19 @@ Il metodo `Promise.all` esegue le promise passate in parallelo. Se una promise f --- -###### 153. Quale dovrebbe essere il valore di `method` per loggare ` {nome: "Lydia", età: 22} `? +###### 153. Quale dovrebbe essere il valore di `method` per loggare `{nome: "Lydia", età: 22}`? ```javascript -const keys = ["name", "age"] -const values = ["Lydia", 22] +const keys = ["name", "age"]; +const values = ["Lydia", 22]; -const method = /* ?? */ -Object[method](keys.map((_, i) => { - return [keys[i], values[i]] -})) // { name: "Lydia", age: 22 } +const method = + /* ?? */ + Object[method]( + keys.map((_, i) => { + return [keys[i], values[i]]; + }) + ); // { name: "Lydia", age: 22 } ``` - A: `entries` @@ -5059,18 +5075,18 @@ Questo crea una matrice di sottoarray contenenti le chiavi e i valori corretti, ###### 154. Qual è l'output? ```javascript -const createMember = ({ email, address = {}}) => { - const validEmail = /.+\@.+\..+/.test(email) - if (!validEmail) throw new Error("Valid email pls") +const createMember = ({ email, address = {} }) => { + const validEmail = /.+\@.+\..+/.test(email); + if (!validEmail) throw new Error("Valid email pls"); - return { - email, - address: address ? address : null - } -} + return { + email, + address: address ? address : null, + }; +}; -const member = createMember({ email: "my@email.com" }) -console.log(member) +const member = createMember({ email: "my@email.com" }); +console.log(member); ``` - A: `{ email: "my@email.com", address: null }` @@ -5093,13 +5109,13 @@ Il valore predefinito di `address` è un oggetto vuoto `{}`. Quando abbiamo impo ###### 155. Qual è l'output? ```javascript -let randomValue = { name: "Lydia" } -randomValue = 23 +let randomValue = { name: "Lydia" }; +randomValue = 23; if (!typeof randomValue === "string") { - console.log("It's not a string!") + console.log("It's not a string!"); } else { - console.log("Yay it's a string!") + console.log("Yay it's a string!"); } ``` diff --git a/ja-JA/README-ja_JA.md b/ja-JA/README-ja_JA.md index 1cc85d76..6fcf3655 100644 --- a/ja-JA/README-ja_JA.md +++ b/ja-JA/README-ja_JA.md @@ -1,13 +1,13 @@ -# JavaScript (高度な) 問題集 +# JavaScript (高度な) 問題集 -私は毎日、JavaScriptに関する選択問題を [Instagram](https://www.instagram.com/theavocoder)に投稿していますが、ここにも投稿します。 +私は毎日、JavaScript に関する選択問題を [Instagram](https://www.instagram.com/theavocoder)に投稿していますが、ここにも投稿します。 -初級から上級まで: JavaScriptの知識のテストを行ったり、知識を少し深めたり、コーディング面接の準備をしてください。:muscle: :rocket: 私はこのレポを毎週新しい質問で更新します。Last update: June 29th +初級から上級まで: JavaScript の知識のテストを行ったり、知識を少し深めたり、コーディング面接の準備をしてください。:muscle: :rocket: 私はこのレポを毎週新しい質問で更新します。Last update: June 29th 答えは質問の下の折りたたまれたセクションにあります、クリックすればそれを広げられます。幸運を祈ります。:heart: - 利用可能な言語リスト: + - [🇸🇦 العربية](../ar-AR/README_AR.md) - [🇪🇬 اللغة العامية](../ar-EG/README_ar-EG.md) - [🇧🇦 Bosanski](../bs-BS/README-bs_BS.md) @@ -21,6 +21,7 @@ - [🇳🇱 Nederlands](../nl-NL/README.md) - [🇵🇱 Polski](../pl-PL/README.md) - [🇧🇷 Português Brasil](../pt-BR/README_pt_BR.md) +- [🇷o Română](../ro-RO/README.ro.md) - [🇷🇺 Русский](../ru-RU/README.md) - [🇽🇰 Shqip](../sq-KS/README_sq_KS.md) - [🇹🇭 ไทย](../th-TH/README-th_TH.md) @@ -55,13 +56,13 @@ sayHi(); #### 答え: D -関数内で、まず `var`キーワードを使って `name`変数を宣言します。これは、変数が定義されている行に実際に到達するまで、変数がデフォルト値の `undefined`で初期化される(作成時にメモリ空間が設定される)ことを意味します。 +関数内で、まず `var`キーワードを使って `name`変数を宣言します。これは、変数が定義されている行に実際に到達するまで、変数がデフォルト値の `undefined`で初期化される(作成時にメモリ空間が設定される)ことを意味します。 `name`変数をログ出力を実行している行では、まだ変数を定義していませんので、`undefined`の値を保持しています。 `let`キーワード(または`const`)を持つ変数は持ち上げられますが、 `var`とは異なり、初期化されません。それらを宣言(初期化)する行の前にはアクセスできません。これは"temporal dead zone"と呼ばれます。 -宣言される前に変数にアクセスしようとすると、JavaScriptは `ReferenceError`を投げます。 +宣言される前に変数にアクセスしようとすると、JavaScript は `ReferenceError`を投げます。

@@ -89,9 +90,9 @@ for (let i = 0; i < 3; i++) { #### 答え: C -JavaScriptのイベントキューのため、`setTimeout`コールバック関数はループが実行された後に呼び出されます。最初のループの変数 `i`は`var`キーワードを使って宣言されているので、この値はグローバル変数となります。ループの間、単項演算子 `++`を使用して、毎回 `i`の値を`1`ずつインクリメントしました。 最初の例では `setTimeout`コールバック関数が呼び出されるまでに`i`は`3`となりました。 +JavaScript のイベントキューのため、`setTimeout`コールバック関数はループが実行された後に呼び出されます。最初のループの変数 `i`は`var`キーワードを使って宣言されているので、この値はグローバル変数となります。ループの間、単項演算子 `++`を使用して、毎回 `i`の値を`1`ずつインクリメントしました。 最初の例では `setTimeout`コールバック関数が呼び出されるまでに`i`は`3`となりました。 -2番目のループでは、変数 `i`が `let`キーワードを使って宣言されました。 `let`(または`const`)キーワードで宣言された変数はブロックスコープです(ブロックは `{}`の間のものです)。それぞれの繰り返しの間、 `i`は新しい値を持ち、それぞれの値はループの内側にあります。 +2 番目のループでは、変数 `i`が `let`キーワードを使って宣言されました。 `let`(または`const`)キーワードで宣言された変数はブロックスコープです(ブロックは `{}`の間のものです)。それぞれの繰り返しの間、 `i`は新しい値を持ち、それぞれの値はループの内側にあります。

@@ -106,7 +107,7 @@ const shape = { diameter() { return this.radius * 2; }, - perimeter: () => 2 * Math.PI * this.radius + perimeter: () => 2 * Math.PI * this.radius, }; shape.diameter(); @@ -125,7 +126,7 @@ shape.perimeter(); `diameter`の値は正則関数であり、`perimeter`の値はアロー関数です。 -アロー関数では、`this`キーワードは通常の関数とは異なり、現在の周囲の範囲を参照します。これは、`perimeter`関数を呼ぶと、shapeオブジェクトではなく、その周囲の範囲(例えば window)を参照することを意味します。 +アロー関数では、`this`キーワードは通常の関数とは異なり、現在の周囲の範囲を参照します。これは、`perimeter`関数を呼ぶと、shape オブジェクトではなく、その周囲の範囲(例えば window)を参照することを意味します。 そのオブジェクトには`radius`という値はなく、`undefined`を返します。 @@ -152,7 +153,7 @@ shape.perimeter(); 単項プラスは、オペランドを数値に変換しようとします。`true`は`1`、`false`は`0`です -文字列「Lydia」は truthy valueです。ここで求めているのは、「このtruthy valueは、falsyなのか」ということです。これは `false`を返します。 +文字列「Lydia」は truthy value です。ここで求めているのは、「この truthy value は、falsy なのか」ということです。これは `false`を返します。

@@ -163,12 +164,12 @@ shape.perimeter(); ```javascript const bird = { - size: "small" + size: "small", }; const mouse = { name: "Mickey", - small: true + small: true, }; ``` @@ -182,15 +183,15 @@ const mouse = { #### 答え: A -JavaScriptでは、すべてのオブジェクトキーは文字列です(Symbolでない限り)。たとえそれを文字列として入力していなくても、それらは常にフードの下で文字列に変換されます。 +JavaScript では、すべてのオブジェクトキーは文字列です(Symbol でない限り)。たとえそれを文字列として入力していなくても、それらは常にフードの下で文字列に変換されます。 -JavaScriptは、ステートメントを解釈(または、ボックス解除)します。大括弧表記を使用すると、最初の左大括弧 `[`を見て、右大括弧 `]`が見つかるまで進みます。その時だけ、そのステートメントを評価します。 +JavaScript は、ステートメントを解釈(または、ボックス解除)します。大括弧表記を使用すると、最初の左大括弧 `[`を見て、右大括弧 `]`が見つかるまで進みます。その時だけ、そのステートメントを評価します。 `mouse [bird.size]`: まず最初に、`bird.size`が評価されます。これは文字列の `"small"`となります。 `mouse["small"]`は、`true`を返します。 しかし、ドット表記では、これは起こりません。 `mouse`は`bird`と呼ばれるキーを持っていません。 つまり`mouse.bird`は`undefined`となります。 -また、ドット表記を使って `size`を求めます: `mouse.bird.size`。 mouse.birdは未定義なので、実際にはundefined.sizeを要求しています。これは有効ではないので、`Cannot read property "size" of undefined`ような、エラーをスローします。 +また、ドット表記を使って `size`を求めます: `mouse.bird.size`。 mouse.bird は未定義なので、実際には undefined.size を要求しています。これは有効ではないので、`Cannot read property "size" of undefined`ような、エラーをスローします。

@@ -221,13 +222,13 @@ console.log(d.greeting); #### 答え: A -JavaScriptでは、すべてのオブジェクトは互いに等しく設定すると参照によって相互作用します。 +JavaScript では、すべてのオブジェクトは互いに等しく設定すると参照によって相互作用します。 まず、変数`c`は、オブジェクトに対する値を保持します。その後、`c`オブジェクトに対して持っている値と同じ参照で`d`に代入します。 -1つのオブジェクトを変更すると、それらすべてが変更されます。 +1 つのオブジェクトを変更すると、それらすべてが変更されます。

@@ -260,7 +261,7 @@ console.log(b === c); `==`演算子を使うとき、同じ値を持っているかどうか? をチェックするだけとなります。それらは両方とも`3`の値を持っているので、それは`true`を返します。 -しかし、`===`演算子を使う時は、値と型は同じであるべきです。 そうでないので: `new Number()`は数値ではなく、**オブジェクト**となります。なので、両方ともfalseを返します。 +しかし、`===`演算子を使う時は、値と型は同じであるべきです。 そうでないので: `new Number()`は数値ではなく、**オブジェクト**となります。なので、両方とも false を返します。

@@ -321,7 +322,7 @@ console.log(greetign); #### 答え: A -グローバルオブジェクトに、空のオブジェクトを作成したばかりなので、オブジェクトはログ出力されます。`greeting`を`greetign`と誤って入力した場合、JSインタプリタは実際にこれを `global.greetign = {}`(またはブラウザの `window.greetign = {}`)と見なします。 +グローバルオブジェクトに、空のオブジェクトを作成したばかりなので、オブジェクトはログ出力されます。`greeting`を`greetign`と誤って入力した場合、JS インタプリタは実際にこれを `global.greetign = {}`(またはブラウザの `window.greetign = {}`)と見なします。 これを避けるために、"use strict"を使用する事ができます。これにより、変数を何かに設定する前に、変数宣言したことを確認できます。 @@ -350,7 +351,7 @@ bark.animal = "dog"; #### 答え: A -関数はオブジェクトとなるので、これはJavaScriptで可能です。(プリミティブ型以外はすべてオブジェクトです。) +関数はオブジェクトとなるので、これは JavaScript で可能です。(プリミティブ型以外はすべてオブジェクトです。) 関数は特別な種類のオブジェクトです。自分で書いたコードは実際の機能ではありません。関数はプロパティを持つオブジェクトです。よって、このプロパティは呼び出し可能となります。 @@ -368,7 +369,7 @@ function Person(firstName, lastName) { } const member = new Person("Lydia", "Hallie"); -Person.getFullName = function() { +Person.getFullName = function () { return `${this.firstName} ${this.lastName}`; }; @@ -388,7 +389,7 @@ console.log(member.getFullName()); 通常のオブジェクトのようにコンストラクタにプロパティを追加することはできません。一度にすべてのオブジェクトに機能を追加したい場合は、代わりにプロトタイプを使用する必要があります。だからこの場合は、 ```js -Person.prototype.getFullName = function() { +Person.prototype.getFullName = function () { return `${this.firstName} ${this.lastName}`; }; ``` @@ -397,7 +398,7 @@ Person.prototype.getFullName = function() { その場合、多くのメモリスペースを浪費する事でしょう。なぜならそれらはまだその特性を持ち、それは各インスタンスのためにメモリスペースを消費するからです。 -その代わりに、プロトタイプに追加するだけであれば、メモリ内の1箇所に配置するだけで、すべてのユーザーがアクセスできます。 +その代わりに、プロトタイプに追加するだけであれば、メモリ内の 1 箇所に配置するだけで、すべてのユーザーがアクセスできます。

@@ -440,7 +441,7 @@ console.log(sarah); --- -###### 13. イベント伝播の3つの段階はどれですか? +###### 13. イベント伝播の 3 つの段階はどれですか? - A: Target > Capturing > Bubbling - B: Bubbling > Target > Capturing @@ -473,9 +474,9 @@ console.log(sarah); **基本オブジェクト**を除き、すべてのオブジェクトにプロトタイプがあります。ベースオブジェクトは`.toString`のようないくつかのメソッドとプロパティにアクセスできます。 -これが、組み込みのJavaScriptメソッドを使用できる理由です。このような方法はすべてプロトタイプで利用できます。 +これが、組み込みの JavaScript メソッドを使用できる理由です。このような方法はすべてプロトタイプで利用できます。 -JavaScriptはそれをあなたのオブジェクト上で直接見つけることはできませんが、プロトタイプチェーンをたどり、見つけます。 +JavaScript はそれをあなたのオブジェクト上で直接見つけることはできませんが、プロトタイプチェーンをたどり、見つけます。

@@ -502,9 +503,9 @@ sum(1, "2"); #### 答え: C -JavaScriptは、**動的に型付けされた言語**です。: 特定の変数がどんな型であるかは指定しません。知らないうちに、値が自動的に別の型に変換されることがあります。この事を`implicit type coercion`と呼ばれてます。 **Coercion**は、ある型から別の型に変換しています。 +JavaScript は、**動的に型付けされた言語**です。: 特定の変数がどんな型であるかは指定しません。知らないうちに、値が自動的に別の型に変換されることがあります。この事を`implicit type coercion`と呼ばれてます。 **Coercion**は、ある型から別の型に変換しています。 -この例では、関数が意味を成して値を返すために、JavaScriptは数字の`1`を文字列に変換します。数値型(`1`)と 文字列型(`'2'`)の追加中は、数字は文字列として扱われます。 +この例では、関数が意味を成して値を返すために、JavaScript は数字の`1`を文字列に変換します。数値型(`1`)と 文字列型(`'2'`)の追加中は、数字は文字列として扱われます。 `"Hello"+"World"`のように文字列を連結することができるので、ここで起こっているのは`"1"+"2"`で、これは `"12"`を返します。 @@ -534,13 +535,11 @@ console.log(number); **接尾辞** 単項演算子 `++`: -1.値を返す(これは`0`を返す) -2.値を増やす(numberは現在`1`です) +1.値を返す(これは`0`を返す) 2.値を増やす(number は現在`1`です) **接頭辞** 単項演算子 `++`: -1.値を増やす(数値は2になります) -2.値を返す(これは`2`を返します) +1.値を増やす(数値は 2 になります) 2.値を返す(これは`2`を返します) これは`0 2 2`を返します。 @@ -605,9 +604,9 @@ checkAge({ age: 18 }); #### 答え: C -等価性をテストするとき、プリミティブはそれらの値によって比較され、オブジェクトはそれらの参照によって比較されます。 JavaScriptは、オブジェクトがメモリ内の同じ場所への参照を持っているかどうかを確認します。 +等価性をテストするとき、プリミティブはそれらの値によって比較され、オブジェクトはそれらの参照によって比較されます。 JavaScript は、オブジェクトがメモリ内の同じ場所への参照を持っているかどうかを確認します。 -比較している2つのオブジェクトにはそれがありません。パラメータとして渡したオブジェクトが、等価性を確認するために使用したオブジェクトとは異なるメモリ内の場所を参照しています。 +比較している 2 つのオブジェクトにはそれがありません。パラメータとして渡したオブジェクトが、等価性を確認するために使用したオブジェクトとは異なるメモリ内の場所を参照しています。 これが `{ age: 18 } === { age: 18 }`と、`{ age: 18 } == { age: 18 }`の両方が、`false`を返す理由です。 @@ -665,7 +664,7 @@ getAge(); #### 答え: C -`"use strict"`を使うと、誤ってグローバル変数を宣言しないようにすることができます。変数`age`を宣言したことは一度もありませんし、`"use strict"`を使っているので参照エラーになります。 +`"use strict"`を使うと、誤ってグローバル変数を宣言しないようにすることができます。変数`age`を宣言したことは一度もありませんし、`"use strict"`を使っているので参照エラーになります。 `"use strict"`を使用しなかった場合は、プロパティ`age`がグローバルオブジェクトに追加されたことになるので、それは機能します。 @@ -674,7 +673,7 @@ getAge(); --- -###### 21. sumの値は何? +###### 21. sum の値は何? ```javascript const sum = eval("10*10+5"); @@ -697,7 +696,7 @@ const sum = eval("10*10+5"); --- -###### 22. cool_secretは、どのくらいの期間アクセス可能ですか? +###### 22. cool_secret は、どのくらいの期間アクセス可能ですか? ```javascript sessionStorage.setItem("cool_secret", 123); @@ -772,9 +771,9 @@ set.has(1); #### 答え: C -すべてのオブジェクトキー(Symbolsを除く)は、文字列として自分で入力しなくても、内部では文字列です。これが、`obj.hasOwnProperty('1')`も​​trueを返す理由です。 +すべてのオブジェクトキー(Symbols を除く)は、文字列として自分で入力しなくても、内部では文字列です。これが、`obj.hasOwnProperty('1')`も ​​true を返す理由です。 -setではそうはいきません。上記のsetには`'1'` はありません: `set.has('1')`は、`false`を返します。数値型`1`の`set.has(1)`は、`true`を返します。 +set ではそうはいきません。上記の set には`'1'` はありません: `set.has('1')`は、`false`を返します。数値型`1`の`set.has(1)`は、`true`を返します。

@@ -798,14 +797,14 @@ console.log(obj); #### 答え: C -同じ名前のキーが2つある場合、最初の位置にあるキーは置き換えられ、最後に指定された値になります。 +同じ名前のキーが 2 つある場合、最初の位置にあるキーは置き換えられ、最後に指定された値になります。

--- -###### 26. JavaScriptのglobal execution contextは、2つを作成します。: それはグローバルオブジェクトと "this"キーワードです。 +###### 26. JavaScript の global execution context は、2 つを作成します。: それはグローバルオブジェクトと "this"キーワードです。 - A: true - B: false @@ -816,7 +815,7 @@ console.log(obj); #### 答え: A -基本的なexecution contextは、グローバルな実行コンテキストです。それはあなたのコードの至る所でアクセス可能なものです。 +基本的な execution context は、グローバルな実行コンテキストです。それはあなたのコードの至る所でアクセス可能なものです。

@@ -858,7 +857,7 @@ String.prototype.giveLydiaPizza = () => { const name = "Lydia"; -console.log(name.giveLydiaPizza()) +console.log(name.giveLydiaPizza()); ``` - A: `"Just give Lydia pizza already!"` @@ -905,9 +904,9 @@ console.log(a[b]); #### 答え: B -オブジェクトキーは自動的に文字列に変換されます。オブジェクトaのキーとして、値123で設定しようとしています。 +オブジェクトキーは自動的に文字列に変換されます。オブジェクト a のキーとして、値 123 で設定しようとしています。 -しかし、オブジェクトを文字列化すると、それは`"[object Object]"`​​になってしまいます。なので、ここで行っているのは、 `a["object Object"] = 123`です。 +しかし、オブジェクトを文字列化すると、それは`"[object Object]"`​​ になってしまいます。なので、ここで行っているのは、 `a["object Object"] = 123`です。 その後、同じことをもう一度試みています。`c`は暗黙のうちに文字列化している別のオブジェクトです。そのため、`a["object Object"] = 456`となります。 @@ -942,9 +941,9 @@ baz(); `setTimeout`関数があり、それを最初に呼び出したのですが、それは最後にログ出力されました。 -これは、ブラウザにはランタイムエンジンがあるだけでなく、`WebAPI`と呼ばれるものもあるからです。`WebAPI`は最初に`setTimeout`関数を与えてくれます。例えばDOMです。 +これは、ブラウザにはランタイムエンジンがあるだけでなく、`WebAPI`と呼ばれるものもあるからです。`WebAPI`は最初に`setTimeout`関数を与えてくれます。例えば DOM です。 -callbackがWebAPIにプッシュされた後、`setTimeout`関数自体(コールバックではありません!)がスタックからポップされます。 +callback が WebAPI にプッシュされた後、`setTimeout`関数自体(コールバックではありません!)がスタックからポップされます。 @@ -956,11 +955,11 @@ callbackがWebAPIにプッシュされた後、`setTimeout`関数自体(コー -WebAPIは、準備が整ったときにスタックに、なにかを追加することはできません。代わりに、コールバック関数を`queue`と呼ばれるものにプッシュします。 +WebAPI は、準備が整ったときにスタックに、なにかを追加することはできません。代わりに、コールバック関数を`queue`と呼ばれるものにプッシュします。 -event loopが機能し始めるところです。 **event loop**はスタックとタスクキューを調べます。スタックが空の場合は、キューの最初のものを取り出し、それをスタックにプッシュします。 +event loop が機能し始めるところです。 **event loop**はスタックとタスクキューを調べます。スタックが空の場合は、キューの最初のものを取り出し、それをスタックにプッシュします。 @@ -971,14 +970,12 @@ event loopが機能し始めるところです。 **event loop**はスタック --- -###### 31.ボタンをクリックしたときのevent.targetは何ですか? +###### 31.ボタンをクリックしたときの event.target は何ですか? ```html
- +
``` @@ -1000,14 +997,11 @@ event loopが機能し始めるところです。 **event loop**はスタック --- - -###### 32. p要素をクリックすると、ログ出力はどうなりますか。 +###### 32. p 要素をクリックすると、ログ出力はどうなりますか。 ```html
-

- Click here! -

+

Click here!

``` @@ -1021,7 +1015,7 @@ event loopが機能し始めるところです。 **event loop**はスタック #### 答え: A -`p`をクリックすると、`p`と`div`の2つのログが表示されます。イベント伝播中は、キャプチャ、ターゲット、バブリングの3つのフェーズがあります。 +`p`をクリックすると、`p`と`div`の 2 つのログが表示されます。イベント伝播中は、キャプチャ、ターゲット、バブリングの 3 つのフェーズがあります。 デフォルトでは、イベントハンドラはバブリング段階で実行されます(`useCapture`を`true`に設定しない限り)。最も深くネストした要素から外側に向かって進みます。 @@ -1084,14 +1078,14 @@ typeof sayHi(); `sayHi`関数は、即時呼び出し関数式(IIFE)の戻り値を返します。この関数は`0`を返しました。それは`"number"`型です。 -参考:7つの組み込み型しかありません: `null`, `undefined`, `boolean`, `number`, `string`, `object`, `symbol`, そして `bigint`。関数はオブジェクトなので、`"function"`型ではなく`"object"`型です。 +参考:7 つの組み込み型しかありません: `null`, `undefined`, `boolean`, `number`, `string`, `object`, `symbol`, そして `bigint`。関数はオブジェクトなので、`"function"`型ではなく`"object"`型です。

--- -###### 35. これらの値のどれがfalsyですか? +###### 35. これらの値のどれが falsy ですか? ```javascript 0; @@ -1105,14 +1099,14 @@ undefined; - A: `0`, `''`, `undefined` - B: `0`, `new Number(0)`, `''`, `new Boolean(false)`, `undefined` - C: `0`, `''`, `new Boolean(false)`, `undefined` -- D: これらすべてfalsy +- D: これらすべて falsy
答え

#### 答え: A -falsyの値は6つだけです。 +falsy の値は 6 つだけです。 - `undefined` - `null` @@ -1121,7 +1115,7 @@ falsyの値は6つだけです。 - `''` (empty string) - `false` -`new Number`や、`new Boolean`のような関数コンストラクタはtruthyです。 +`new Number`や、`new Boolean`のような関数コンストラクタは truthy です。

@@ -1171,11 +1165,11 @@ console.log(numbers); #### 答え: C -配列の長さを超える値を配列内の要素に設定すると、JavaScriptでは、"empty slots"と呼ばれるものを作成します。これらは実際には、`undefined`の値を持ちますが、あなたは以下のようなものを見るでしょう +配列の長さを超える値を配列内の要素に設定すると、JavaScript では、"empty slots"と呼ばれるものを作成します。これらは実際には、`undefined`の値を持ちますが、あなたは以下のようなものを見るでしょう `[1, 2, 3, 7 x empty, 11]` -実行場所によって異なります(browser、nodeなどによって異なります)。 +実行場所によって異なります(browser、node などによって異なります)。

@@ -1212,18 +1206,18 @@ console.log(numbers); 後に、このブロックスコープ変数を`1`に設定し、変数`y`の値を設定します。ここで、ブロックスコープ変数`x`をログ出力します。これは`1`となります。 -`catch`ブロック以外では、`x`は未定義、`y`は2です。 `catch`ブロックの外側で`console.log(x)`した場合は、`undefined`を返し、`y`は`2`を返します。 +`catch`ブロック以外では、`x`は未定義、`y`は 2 です。 `catch`ブロックの外側で`console.log(x)`した場合は、`undefined`を返し、`y`は`2`を返します。

--- -###### 39. JavaScriptのすべてはどちらかです... +###### 39. JavaScript のすべてはどちらかです... - A: primitive か object - B: function か object -- C: ひっかけ問題! objectsのみ +- C: ひっかけ問題! objects のみ - D: number か object
答え @@ -1231,13 +1225,13 @@ console.log(numbers); #### 答え: A -JavaScriptにはプリミティブ型とオブジェクトしかありません。 +JavaScript にはプリミティブ型とオブジェクトしかありません。 プリミティブ型は、`boolean`, `null`, `undefined`, `bigint`, `number`, `string`, そして`symbol`です。 プリミティブとオブジェクトを区別するのは、プリミティブにはプロパティもメソッドもないということです。 -ただし、`'foo'.toUpperCase()`は`'FOO'`と評価され、`TypeError`にはなりません。これは、文字列のようなプリミティブのプロパティやメソッドにアクセスしようとすると、JavaScriptがラッパークラスの1つ、すなわち`String`を使ってオブジェクトを暗黙的にラップし、式が評価された後ラッパーを直ちに破棄するためです。 +ただし、`'foo'.toUpperCase()`は`'FOO'`と評価され、`TypeError`にはなりません。これは、文字列のようなプリミティブのプロパティやメソッドにアクセスしようとすると、JavaScript がラッパークラスの 1 つ、すなわち`String`を使ってオブジェクトを暗黙的にラップし、式が評価された後ラッパーを直ちに破棄するためです。 `null`と`undefined`を除くすべてのプリミティブはこの振る舞いをします。 @@ -1249,7 +1243,10 @@ JavaScriptにはプリミティブ型とオブジェクトしかありません ###### 40. 何が出力されるでしょうか? ```javascript -[[0, 1], [2, 3]].reduce( +[ + [0, 1], + [2, 3], +].reduce( (acc, cur) => { return acc.concat(cur); }, @@ -1294,25 +1291,24 @@ JavaScriptにはプリミティブ型とオブジェクトしかありません #### 答え: B -`null`はfalsyです。`!null`は`true`を返します。`!true`は`false`を返します。 +`null`は falsy です。`!null`は`true`を返します。`!true`は`false`を返します。 -`""`はfalsyです。`!""`は`true`を返します。`!true`は`false`を返します。 +`""`は falsy です。`!""`は`true`を返します。`!true`は`false`を返します。 -`1`はtruthyです。`!1`は`false`を返します。`!false`は`true`を返します。 +`1`は truthy です。`!1`は`false`を返します。`!false`は`true`を返します。

--- - ###### 42. `setInterval`メソッドはブラウザに何を返しますか? ```javascript setInterval(() => console.log("Hi"), 1000); ``` -- A: ユニークid +- A: ユニーク id - B: 指定されたミリ秒数 - C: 渡された関数 - D: `undefined` @@ -1322,7 +1318,7 @@ setInterval(() => console.log("Hi"), 1000); #### 答え: A -一意のIDを返します。このIDは `clearInterval()`関数で、その間隔をクリアするために使うことができます。 +一意の ID を返します。この ID は `clearInterval()`関数で、その間隔をクリアするために使うことができます。

@@ -1345,7 +1341,7 @@ setInterval(() => console.log("Hi"), 1000); #### 答え: A -文字列はイテラブルです。スプレッド演算子は、イテラブルのすべての文字を1つの要素にマッピングします。 +文字列はイテラブルです。スプレッド演算子は、イテラブルのすべての文字を 1 つの要素にマッピングします。

@@ -1402,7 +1398,7 @@ const secondPromise = new Promise((res, rej) => { setTimeout(res, 100, "two"); }); -Promise.race([firstPromise, secondPromise]).then(res => console.log(res)); +Promise.race([firstPromise, secondPromise]).then((res) => console.log(res)); ``` - A: `"one"` @@ -1417,7 +1413,7 @@ Promise.race([firstPromise, secondPromise]).then(res => console.log(res)); 複数のプロミスを`Promise.race`メソッドに渡した時、"resolves/rejects"は、"最初"のプロミスの"resolves/rejects"を行います。 -`setTimeout`メソッドには、タイマーを渡します: 最初のプロミスには500ms(`firstPromise`)、2番目のプロミスには100ms(`secondPromise`)。 +`setTimeout`メソッドには、タイマーを渡します: 最初のプロミスには 500ms(`firstPromise`)、2 番目のプロミスには 100ms(`secondPromise`)。 これは、`secondPromise`が最初に`'two'`の値で解決されることを意味します。`res`は`'two'`の値を保持するようになり、ログ出力されます。 @@ -1461,7 +1457,7 @@ console.log(members); その要素はオブジェクトへの異なる(コピーされた)参照を持っているので、`person`変数の値を変更するだけで配列の最初の要素は変更されません。 `members`の最初の要素はまだ元のオブジェクトへの参照を保持しています。 - + `members`配列をログ出力したとき、最初の要素はまだオブジェクトの値を保持しているので、それがログ出力されます。

@@ -1474,7 +1470,7 @@ console.log(members); ```javascript const person = { name: "Lydia", - age: 21 + age: 21, }; for (const item in person) { @@ -1517,18 +1513,18 @@ console.log(3 + 4 + "5"); #### 答え: B -演算子結合性は、コンパイラーが式を評価する順序(左から右または右から左)となります。これは、すべての演算子が同じ優先順位を持つ場合にのみ発生します。演算子の種類は1つだけです: `+`。さらに、結合性は左から右です。 +演算子結合性は、コンパイラーが式を評価する順序(左から右または右から左)となります。これは、すべての演算子が同じ優先順位を持つ場合にのみ発生します。演算子の種類は 1 つだけです: `+`。さらに、結合性は左から右です。 `3 + 4`が最初に評価されます。これは数字の`7`になります。 -`7 + '5'`は、強制的に`"75"`になります。 JavaScriptでは、数字の`7`を文字列に変換します。質問15を参照してください。2つの文字列を演算子の`+`を使って連結することができます。よって、`"7" + "5"`は、`"75"`になります。 +`7 + '5'`は、強制的に`"75"`になります。 JavaScript では、数字の`7`を文字列に変換します。質問 15 を参照してください。2 つの文字列を演算子の`+`を使って連結することができます。よって、`"7" + "5"`は、`"75"`になります。

--- -###### 49. numの値は何ですか? +###### 49. num の値は何ですか? ```javascript const num = parseInt("7*6", 10); @@ -1544,9 +1540,9 @@ const num = parseInt("7*6", 10); #### 答え: C -文字列の最初の数字だけが返されます。"基数"(解析する数値の種類を指定するための2番目の引数: 基数10, 16進数, 8進数, 2進数など)に基づいて、`parseInt`は文字列内の文字が有効かどうかをチェックします。基数の中で有効な数字ではない文字に出会うと、構文解析を停止して次の文字を無視します。 +文字列の最初の数字だけが返されます。"基数"(解析する数値の種類を指定するための 2 番目の引数: 基数 10, 16 進数, 8 進数, 2 進数など)に基づいて、`parseInt`は文字列内の文字が有効かどうかをチェックします。基数の中で有効な数字ではない文字に出会うと、構文解析を停止して次の文字を無視します。 -`*`は、有効な数字ではありません。`"7"`を、10進数の`7`に解析するだけです。そのままnumは`7`の値を保持します。 +`*`は、有効な数字ではありません。`"7"`を、10 進数の`7`に解析するだけです。そのまま num は`7`の値を保持します。

@@ -1556,7 +1552,7 @@ const num = parseInt("7*6", 10); ###### 50. 何が出力されるでしょうか? ```javascript -[1, 2, 3].map(num => { +[1, 2, 3].map((num) => { if (typeof num === "number") return; return num * 2; }); @@ -1572,7 +1568,7 @@ const num = parseInt("7*6", 10); #### 答え: C -配列をマッピングするとき、`num`の値に代入されるのは、ループで渡ってくる要素となります。この場合、要素は数値なので、ifステートメント `typeof num === "number"`の条件は`true`を返します。 map関数は新しい配列を作成して関数から返された値を挿入します。 +配列をマッピングするとき、`num`の値に代入されるのは、ループで渡ってくる要素となります。この場合、要素は数値なので、if ステートメント `typeof num === "number"`の条件は`true`を返します。 map 関数は新しい配列を作成して関数から返された値を挿入します。 ただし、値は返されません。関数から値を返さないと、関数は`undefined`を返します。配列内のすべての要素に対して関数ブロックが呼び出されるので、各要素に対して`undefined`を返します。 @@ -1607,7 +1603,7 @@ console.log(person, birthYear); #### 答え: A -値がオブジェクトでない限り、引数は"値"によって渡され、その後、"参照"によって渡されます。 `birthYear`はオブジェクトではなく文字列なので、値で渡されます。引数を値で渡すと、その値の"コピー"が作成されます(質問46を参照)。 +値がオブジェクトでない限り、引数は"値"によって渡され、その後、"参照"によって渡されます。 `birthYear`はオブジェクトではなく文字列なので、値で渡されます。引数を値で渡すと、その値の"コピー"が作成されます(質問 46 を参照)。 変数`birthYear`は、値`"1997"`への参照を持ちます。引数`year`は、値`"1997"`も参照していますが、それは`birthYear`が参照しているのと同じ値ではありません。`year`に`"1998"`を代入することによって`year`の値を更新したとしても、`year`の値を更新するだけです。`birthYear`はまだ`"1997"`となります。 @@ -1715,15 +1711,15 @@ y = 10; let x = y; ``` -`y`に`10`を代入すると、実際にはグローバルオブジェクトにプロパティ`y`が追加されます(ブラウザでは`window`、nodeでは`global`)。ブラウザでは、`window.y`は`10`となりました。 +`y`に`10`を代入すると、実際にはグローバルオブジェクトにプロパティ`y`が追加されます(ブラウザでは`window`、node では`global`)。ブラウザでは、`window.y`は`10`となりました。 -それから、変数`x`を`10`である値`y`で宣言します。`let`キーワードで宣言された変数は"ブロックスコープ"となり、宣言されたブロック内でのみ定義されます。この場合は即時関数(IIFE)となります。 +それから、変数`x`を`10`である値`y`で宣言します。`let`キーワードで宣言された変数は"ブロックスコープ"となり、宣言されたブロック内でのみ定義されます。この場合は即時関数(IIFE)となります。 `typeof`演算子使用時、オペランド`x`は定義されていません: 宣言されているブロックの外側で`x`にアクセスしようとしています。これは`x`が定義されていないことを意味します。 値が割り当てられていない、または宣言されていない値は`"undefined"`型となります。なので`console.log(typeof x)`は`"undefined"`を返します。 -yに関しては、`y`に`10`を代入するときにグローバル変数`y`を作成しました。この値は、コード内のどこからでもアクセスできます。`y`が定義されていて、`"number"`型の値を保持します。よって`console.log(typeof y)`は`"number"`を返します。 +y に関しては、`y`に`10`を代入するときにグローバル変数`y`を作成しました。この値は、コード内のどこからでもアクセスできます。`y`が定義されていて、`"number"`型の値を保持します。よって`console.log(typeof y)`は`"number"`を返します。

@@ -1737,7 +1733,7 @@ class Dog { } } -Dog.prototype.bark = function() { +Dog.prototype.bark = function () { console.log(`Woof I am ${this.name}`); }; @@ -1789,10 +1785,9 @@ console.log(set); #### 答え: D - `Set`オブジェクトは _unique_ の値の集合です: 値は集合の中で一度だけ現れることができます -値`1`が重複したイテラブル`[1、1、2、3、4]`を渡しました。セット内に同じ値を2つ持つことはできないので、そのうちの1つが削除され`{1、2、3、4}`となります。 +値`1`が重複したイテラブル`[1、1、2、3、4]`を渡しました。セット内に同じ値を 2 つ持つことはできないので、そのうちの 1 つが削除され`{1、2、3、4}`となります。

@@ -1855,9 +1850,9 @@ console.log(delete age); #### 答え: A -`delete`演算子は、ブール値を返します: 正常に削除された場合はtrue、それ以外の場合はfalseを返します。`var`, `const`または`let`キーワードで宣言された変数は`delete`演算子を使って削除することはできません。 +`delete`演算子は、ブール値を返します: 正常に削除された場合は true、それ以外の場合は false を返します。`var`, `const`または`let`キーワードで宣言された変数は`delete`演算子を使って削除することはできません。 -`name`変数は`const`キーワードで宣言されているので、削除は成功しません: `false`が返されます。 +`name`変数は`const`キーワードで宣言されているので、削除は成功しません: `false`が返されます。 `age`を`21`に設定すると、実際にはグローバルオブジェクトに`age`というプロパティを追加されました。グローバルオブジェクトからもプロパティを削除することができますので、`delete age`は`true`を返します。 @@ -1957,7 +1952,7 @@ console.log(Object.keys(person)); #### 答え: B -`defineProperty`メソッドを使うと、オブジェクトに新しいプロパティを追加したり、既存のプロパティを修正することができます。 `defineProperty`メソッドを使ってオブジェクトにプロパティを追加すると、それらはデフォルトでは _列挙できません_。 +`defineProperty`メソッドを使うと、オブジェクトに新しいプロパティを追加したり、既存のプロパティを修正することができます。 `defineProperty`メソッドを使ってオブジェクトにプロパティを追加すると、それらはデフォルトでは _列挙できません_。 `Object.keys`メソッドはオブジェクトから全ての _enumerable_ (列挙可能)なプロパティ名を返します。上記の場合は`"name"`だけとなります。 @@ -1974,7 +1969,7 @@ console.log(Object.keys(person)); const settings = { username: "lydiahallie", level: 19, - health: 90 + health: 90, }; const data = JSON.stringify(settings, ["level", "health"]); @@ -1991,11 +1986,11 @@ console.log(data); #### 答え: A -`JSON.stringify`の2番目の引数は _replacer_ です。replacerは、関数または配列のいずれかにすることができ、値を文字列化する対象とその方法を制御できます。 +`JSON.stringify`の 2 番目の引数は _replacer_ です。replacer は、関数または配列のいずれかにすることができ、値を文字列化する対象とその方法を制御できます。 -replacerが _array_ の場合、名前が配列に含まれるプロパティのみがJSON文字列に追加されます。上記の場合、`"level"`と`"health"`という名前のプロパティだけが含まれ、`"username"`は除外されます。`data`は`"{" level ":19、" health ":90}"`となります。 +replacer が _array_ の場合、名前が配列に含まれるプロパティのみが JSON 文字列に追加されます。上記の場合、`"level"`と`"health"`という名前のプロパティだけが含まれ、`"username"`は除外されます。`data`は`"{" level ":19、" health ":90}"`となります。 -replacerが _function_ の場合、この関数は文字列化しているオブジェクト内のすべてのプロパティに対して呼び出されます。この関数から返される値は、JSON文字列に追加されたときのプロパティの値になり、値が`undefined`の場合、このプロパティはJSON文字列から除外されます。 +replacer が _function_ の場合、この関数は文字列化しているオブジェクト内のすべてのプロパティに対して呼び出されます。この関数から返される値は、JSON 文字列に追加されたときのプロパティの値になり、値が`undefined`の場合、このプロパティは JSON 文字列から除外されます。

@@ -2008,7 +2003,7 @@ replacerが _function_ の場合、この関数は文字列化しているオブ let num = 10; const increaseNumber = () => num++; -const increasePassedNumber = number => number++; +const increasePassedNumber = (number) => number++; const num1 = increaseNumber(); const num2 = increasePassedNumber(num1); @@ -2061,18 +2056,17 @@ multiply(value); #### 答え: C - -ES6では、パラメータをデフォルト値で初期化できます。値が関数に渡されていない場合やパラメータの値が `"undefined"`の場合、パラメータの値はデフォルト値になります。上記の場合、`value`オブジェクトのプロパティを新しいオブジェクトに分割代入されるので、`x`のデフォルト値は`{number:10}`になります。 +ES6 では、パラメータをデフォルト値で初期化できます。値が関数に渡されていない場合やパラメータの値が `"undefined"`の場合、パラメータの値はデフォルト値になります。上記の場合、`value`オブジェクトのプロパティを新しいオブジェクトに分割代入されるので、`x`のデフォルト値は`{number:10}`になります。 デフォルトの引数は、_呼び出し時_ に評価されます。関数を呼び出すたびに、_新しい_ オブジェクトが作成されます。 -最初に値を渡さずに2回、`multiply`関数を呼び出します: `x`のデフォルト値は `{number:10}`となり、その数の乗算された値、つまり `20`を出力します。 +最初に値を渡さずに 2 回、`multiply`関数を呼び出します: `x`のデフォルト値は `{number:10}`となり、その数の乗算された値、つまり `20`を出力します。 -3回目のmultiplyを呼び出すとき、引数を渡します: `value`というオブジェクトです。 +3 回目の multiply を呼び出すとき、引数を渡します: `value`というオブジェクトです。 `*=`演算子は`x.number = x.number * 2`の省略形となります: `x.number`の値は乗算した値に修正され、`20`を出力します。 -4回目は、`value`オブジェクトをもう一度渡します。`x.number`は以前は`20`に修正されているので、`x.number *= 2`は`40`を出力します。 +4 回目は、`value`オブジェクトをもう一度渡します。`x.number`は以前は`20`に修正されているので、`x.number *= 2`は`40`を出力します。

@@ -2095,8 +2089,7 @@ ES6では、パラメータをデフォルト値で初期化できます。値 #### 答え: D - -`reduce`メソッドが受け取る最初の引数は _アキュムレータ_ となります。この場合は`x`です。 2番目の引数は、_現在の値_ `y`です。 reduceメソッドでは、配列内のすべての要素に対してコールバック関数を実行します。これにより、最終的に1つの値が得られます。 +`reduce`メソッドが受け取る最初の引数は _アキュムレータ_ となります。この場合は`x`です。 2 番目の引数は、_現在の値_ `y`です。 reduce メソッドでは、配列内のすべての要素に対してコールバック関数を実行します。これにより、最終的に 1 つの値が得られます。 上記の例では、値を返していません。単にアキュムレータの値と現在の値を記録しています。 @@ -2106,14 +2099,14 @@ ES6では、パラメータをデフォルト値で初期化できます。値 関数から値を返さなければ、`undefined`を返します。次の呼び出しでは、アキュムレータは`undefined`で、現在の値は`3`です。`undefined`と`3`が出力されます。 -4回目の呼び出しでも、コールバック関数からは戻りません。アキュムレータもまた`undefined`であり、現在の値は`4`となり、`undefined`と`4`が出力されます。 +4 回目の呼び出しでも、コールバック関数からは戻りません。アキュムレータもまた`undefined`であり、現在の値は`4`となり、`undefined`と`4`が出力されます。

--- -###### 66. どのコンストラクタを使えば `Dog` classを継承できるでしょうか? +###### 66. どのコンストラクタを使えば `Dog` class を継承できるでしょうか? ```javascript class Dog { @@ -2123,7 +2116,7 @@ class Dog { }; class Labrador extends Dog { - // 1 + // 1 constructor(name, size) { this.size = size; } @@ -2137,7 +2130,7 @@ class Labrador extends Dog { super(name); this.size = size; } - // 4 + // 4 constructor(name, size) { this.name = name; this.size = size; @@ -2156,13 +2149,14 @@ class Labrador extends Dog { #### 答え: B -派生クラスでは、`super`を呼び出す前に、`this`キーワードにアクセスすることはできません。そうしようとすると、ReferenceErrorがスローされます: 1と4は参照エラーをスローします。 +派生クラスでは、`super`を呼び出す前に、`this`キーワードにアクセスすることはできません。そうしようとすると、ReferenceError がスローされます: 1 と 4 は参照エラーをスローします。 `super`キーワードを使って、与えられた引数で、その親クラスのコンストラクタを呼び出します。親のコンストラクタは`name`引数を受け取るので、`name`を`super`に渡す必要があります。 -`Labrador`クラスは2つの引数、`Dog`を拡張するための`name`と、`Labrador`クラスの追加のプロパティとしての`size`を受け取ります。 +`Labrador`クラスは 2 つの引数、`Dog`を拡張するための`name`と、`Labrador`クラスの追加のプロパティとしての`size`を受け取ります。 + +両方とも`Labrador`のコンストラクタ関数に渡す必要があります。これはコンストラクタ 2 を使って正しく実行されます。 -両方とも`Labrador`のコンストラクタ関数に渡す必要があります。これはコンストラクタ2を使って正しく実行されます。

@@ -2172,12 +2166,12 @@ class Labrador extends Dog { ```javascript // index.js -console.log('running index.js'); -import { sum } from './sum.js'; +console.log("running index.js"); +import { sum } from "./sum.js"; console.log(sum(1, 2)); // sum.js -console.log('running sum.js'); +console.log("running sum.js"); export const sum = (a, b) => a + b; ``` @@ -2193,9 +2187,9 @@ export const sum = (a, b) => a + b; `import`キーワードを使うと、全てのインポートされたモジュールは _事前解析_ されます。これは、インポートされたモジュールが _最初_ に実行され、_その後_ モジュールをインポートしたファイル内のコードが実行されることを意味します。 -これはCommonJSの`require()`と`import`の違いです。`require()`を使うと、コードが実行されている間に依存関係をオンデマンドでロードすることができます。 +これは CommonJS の`require()`と`import`の違いです。`require()`を使うと、コードが実行されている間に依存関係をオンデマンドでロードすることができます。 -`import`の代わりに`require`を使用したとしたら、`running index.js`, `running sum.js`, `3`が出力されているはずです。 +`import`の代わりに`require`を使用したとしたら、`running index.js`, `running sum.js`, `3`が出力されているはずです。

@@ -2205,9 +2199,9 @@ export const sum = (a, b) => a + b; ###### 68. 何が出力されるでしょうか? ```javascript -console.log(Number(2) === Number(2)) -console.log(Boolean(false) === Boolean(false)) -console.log(Symbol('foo') === Symbol('foo')) +console.log(Number(2) === Number(2)); +console.log(Boolean(false) === Boolean(false)); +console.log(Symbol("foo") === Symbol("foo")); ``` - A: `true`, `true`, `false` @@ -2220,9 +2214,9 @@ console.log(Symbol('foo') === Symbol('foo')) #### 答え: A -すべてのシンボルは完全にユニークです。シンボルに渡される引数の目的は、シンボルに説明を与えることです。Symbolの値は渡された引数に依存しません。 +すべてのシンボルは完全にユニークです。シンボルに渡される引数の目的は、シンボルに説明を与えることです。Symbol の値は渡された引数に依存しません。 -等価性をテストしているので、2つのまったく新しいシンボルを作成します: 最初の`Symbol('foo')`と、2番目の`Symbol('foo')`です。これら2つの値は一意であり、互いに等しくはありません、なので`Symbol('foo') === Symbol('foo')`は`false`を返します。 +等価性をテストしているので、2 つのまったく新しいシンボルを作成します: 最初の`Symbol('foo')`と、2 番目の`Symbol('foo')`です。これら 2 つの値は一意であり、互いに等しくはありません、なので`Symbol('foo') === Symbol('foo')`は`false`を返します。

@@ -2232,22 +2226,22 @@ console.log(Symbol('foo') === Symbol('foo')) ###### 69. 何が出力されるでしょうか? ```javascript -const name = "Lydia Hallie" -console.log(name.padStart(13)) -console.log(name.padStart(2)) +const name = "Lydia Hallie"; +console.log(name.padStart(13)); +console.log(name.padStart(2)); ``` - A: `"Lydia Hallie"`, `"Lydia Hallie"` - B: `" Lydia Hallie"`, `" Lydia Hallie"` (`"[13x whitespace]Lydia Hallie"`, `"[2x whitespace]Lydia Hallie"`) - C: `" Lydia Hallie"`, `"Lydia Hallie"` (`"[1x whitespace]Lydia Hallie"`, `"Lydia Hallie"`) -- D: `"Lydia Hallie"`, `"Lyd"`, +- D: `"Lydia Hallie"`, `"Lyd"`,
答え

#### 答え: C -`padStart`メソッドを使うと、文字列の先頭にパディングを追加できます。このメソッドに渡される値は、パディングとともに文字列の長さの _合計_ です。文字列`"Lydia Hallie"`の長さは`12`です。 `name.padStart(13)`は、12 + 1が13であるため、文字列の先頭に1スペースを挿入されます。 +`padStart`メソッドを使うと、文字列の先頭にパディングを追加できます。このメソッドに渡される値は、パディングとともに文字列の長さの _合計_ です。文字列`"Lydia Hallie"`の長さは`12`です。 `name.padStart(13)`は、12 + 1 が 13 であるため、文字列の先頭に 1 スペースを挿入されます。 `padStart`メソッドに渡された引数が、配列の長さよりも小さい場合、パディングは追加されません。 @@ -2272,7 +2266,6 @@ console.log("🥑" + "💻"); #### 答え: A - `+`演算子を使うと、文字列を連結することができます。この場合、文字列`"🥑"`を文字列`"💻"`と連結して、結果として`"🥑💻"`となります。

@@ -2280,7 +2273,7 @@ console.log("🥑" + "💻"); --- -###### 71. console.logステートメントの後にコメントアウトされている値を、ログ出力する方法を教えてください。 +###### 71. console.log ステートメントの後にコメントアウトされている値を、ログ出力する方法を教えてください。 ```javascript function* startGame() { @@ -2308,11 +2301,11 @@ console.log(/* 2 */); // JavaScript loves you back ❤️ ジェネレータ関数は、`yield`キーワードを見るとその実行を「一時停止」します。まず、関数に文字列 "Do you love JavaScript?" を返させる必要があります。これは `game.next().value`を呼び出すことによって行うことができます。 -最初の`yield`キーワードが見つかるまで、すべての行が実行されます。関数内の最初の行に`yield`キーワードがあります: 実行は最初のyieldで停止します! _これは変数 `answer`がまだ定義されていないことを意味します!_ +最初の`yield`キーワードが見つかるまで、すべての行が実行されます。関数内の最初の行に`yield`キーワードがあります: 実行は最初の yield で停止します! _これは変数 `answer`がまだ定義されていないことを意味します!_ -`game.next("Yes").value`を呼び出すと、前の`yield`は`next()`関数に渡されたパラメータの値、この場合は`"Yes"`に置き換えられます。変数`answer`の値は現在`"Yes"`となります。 +`game.next("Yes").value`を呼び出すと、前の`yield`は`next()`関数に渡されたパラメータの値、この場合は`"Yes"`に置き換えられます。変数`answer`の値は現在`"Yes"`となります。 -if-statemnetの条件は`false`を返し、`JavaScript loves you back ❤️`が、出力されます。 +if-statemnet の条件は`false`を返し、`JavaScript loves you back ❤️`が、出力されます。

@@ -2375,7 +2368,7 @@ console.log(data); #### 答え: C -非同期関数は常に、promiseを返します。`await`はpromiseが解決されるのを待たなければなりません: `getData()`を呼び出すと、`data`は保留中のpromiseが返されます。 +非同期関数は常に、promise を返します。`await`は promise が解決されるのを待たなければなりません: `getData()`を呼び出すと、`data`は保留中の promise が返されます。 解決した値`"I made it"`にアクセスしたい場合は、`data`に対して`.then()`メソッドを使用することができます: @@ -2409,10 +2402,10 @@ console.log(result); #### 答え: B -`.push()`メソッドは新しい配列の長さを返します。以前は、配列は1つの要素(文字列 `" banana "`)を含み、長さは `1`でした。文字列 `" apple "`を配列に追加した後、配列は2つの要素を含み、長さは `2`になります。これは `addToList`関数から返されます。 +`.push()`メソッドは新しい配列の長さを返します。以前は、配列は 1 つの要素(文字列 `" banana "`)を含み、長さは `1`でした。文字列 `" apple "`を配列に追加した後、配列は 2 つの要素を含み、長さは `2`になります。これは `addToList`関数から返されます。 The `.push()` method returns the _length_ of the new array! Previously, the array contained one element (the string `"banana"`) and had a length of `1`. After adding the string `"apple"` to the array, the array contains two elements, and has a length of `2`. This gets returned from the `addToList` function. -`push`メソッドは元の配列を修正します。配列の長さではなく関数から配列を返したい場合は、itemをプッシュした後にlistを返すべきです。 +`push`メソッドは元の配列を修正します。配列の長さではなく関数から配列を返したい場合は、item をプッシュした後に list を返すべきです。 The `push` method modifies the original array. If you wanted to return the _array_ from the function rather than the _length of the array_, you should have returned `list` after pushing `item` to it.

@@ -2447,7 +2440,7 @@ console.log(shape); 変数`shape`を作成し、フリーズしたオブジェクト`box`に代入すると、`shape`はフリーズしたオブジェクトとなります。オブジェクトがフリーズしているかどうかは `Object.isFrozen`を使って確認できます。 -この場合、変数`shape`はフリーズしたオブジェクトへの参照を持っているので、`Object.isFrozen(shape)`はtrueを返します。 +この場合、変数`shape`はフリーズしたオブジェクトへの参照を持っているので、`Object.isFrozen(shape)`は true を返します。 `shape`はフリーズされており、`x`の値はオブジェクトではないので、プロパティ`x`を変更することはできません。 @@ -2478,9 +2471,9 @@ console.log(name); 右側のオブジェクトからプロパティ`name`をアンパックするとき、その値`"Lydia"`を`myName`という名前の変数に代入します。 -`{name:myName}`を使って、右側の `name`プロパティの値で`myName`という新しい変数を作りたいことをJavaScriptに伝えます。 +`{name:myName}`を使って、右側の `name`プロパティの値で`myName`という新しい変数を作りたいことを JavaScript に伝えます。 -定義されていない変数`name`を出力しようとしているので、ReferenceErrorが投げられます。 +定義されていない変数`name`を出力しようとしているので、ReferenceError が投げられます。

@@ -2517,7 +2510,7 @@ function sum(a, b) { ```javascript const add = () => { const cache = {}; - return num => { + return (num) => { if (num in cache) { return `From cache! ${cache[num]}`; } else { @@ -2548,15 +2541,15 @@ console.log(addFunction(5 * 2)); 同じ引数を指定してもう一度`addFunction`関数を呼び出すと、最初にキャッシュ内でその値がすでに取得されているかどうかを調べます。 -この場合、cachesの値が返され、実行時間が短縮されます。そうでなくキャッシュされていなければ、値を計算した後にそれを格納します。 +この場合、caches の値が返され、実行時間が短縮されます。そうでなくキャッシュされていなければ、値を計算した後にそれを格納します。 -同じ値で3回`addFunction`関数を呼び出します: 最初の呼び出しでは、`num`に`10`を代入した時、関数の値はまだキャッシュされていません。 +同じ値で 3 回`addFunction`関数を呼び出します: 最初の呼び出しでは、`num`に`10`を代入した時、関数の値はまだキャッシュされていません。 -ifステートメントの`num in cache`の条件は`false`を返し、elseブロックが実行されます: `Calculated! 20`が出力され、結果の値がキャッシュオブジェクトに追加されます。 `cache`は現在 `{ 10: 20 }`となります。 +if ステートメントの`num in cache`の条件は`false`を返し、else ブロックが実行されます: `Calculated! 20`が出力され、結果の値がキャッシュオブジェクトに追加されます。 `cache`は現在 `{ 10: 20 }`となります。 -2回目は、`cache`オブジェクトは`10`に対して返される値を含みます。 ifステートメントの`num in cache`の条件は`true`となり、`'From cache! 20'`を返します。 よって`'From cache! 20'`が出力されます。 +2 回目は、`cache`オブジェクトは`10`に対して返される値を含みます。 if ステートメントの`num in cache`の条件は`true`となり、`'From cache! 20'`を返します。 よって`'From cache! 20'`が出力されます。 -3回目は、`10`に評価される関数に`5 * 2`を渡します。`cache`オブジェクトは`10`に対して返される値を含みます。ifステートメントの`num in cache`の条件は`true`となり、`'From cache! 20'`を返します。 よって`'From cache! 20'`が出力されます。 +3 回目は、`10`に評価される関数に`5 * 2`を渡します。`cache`オブジェクトは`10`に対して返される値を含みます。if ステートメントの`num in cache`の条件は`true`となり、`'From cache! 20'`を返します。 よって`'From cache! 20'`が出力されます。

@@ -2566,21 +2559,21 @@ ifステートメントの`num in cache`の条件は`false`を返し、elseブ ###### 79. 何が出力されるでしょうか? ```javascript -const myLifeSummedUp = ["☕", "💻", "🍷", "🍫"] +const myLifeSummedUp = ["☕", "💻", "🍷", "🍫"]; for (let item in myLifeSummedUp) { - console.log(item) + console.log(item); } for (let item of myLifeSummedUp) { - console.log(item) + console.log(item); } ``` - A: `0` `1` `2` `3` and `"☕"` ` "💻"` `"🍷"` `"🍫"` - B: `"☕"` ` "💻"` `"🍷"` `"🍫"` and `"☕"` ` "💻"` `"🍷"` `"🍫"` - C: `"☕"` ` "💻"` `"🍷"` `"🍫"` and `0` `1` `2` `3` -- D: `0` `1` `2` `3` and `{0: "☕", 1: "💻", 2: "🍷", 3: "🍫"}` +- D: `0` `1` `2` `3` and `{0: "☕", 1: "💻", 2: "🍷", 3: "🍫"}`
答え

@@ -2605,14 +2598,14 @@ _for-of_ ループを使うと、**反復可能オブジェクト**を繰り返 ###### 80. 何が出力されるでしょうか? ```javascript -const list = [1 + 2, 1 * 2, 1 / 2] -console.log(list) +const list = [1 + 2, 1 * 2, 1 / 2]; +console.log(list); ``` - A: `["1 + 2", "1 * 2", "1 / 2"]` - B: `["12", 2, 0.5]` - C: `[3, 2, 0.5]` -- D: `[1, 1, 1]` +- D: `[1, 1, 1]`

答え

@@ -2632,16 +2625,16 @@ console.log(list) ```javascript function sayHi(name) { - return `Hi there, ${name}` + return `Hi there, ${name}`; } -console.log(sayHi()) +console.log(sayHi()); ``` - A: `Hi there, ` - B: `Hi there, undefined` - C: `Hi there, null` -- D: `ReferenceError` +- D: `ReferenceError`

答え

@@ -2650,7 +2643,7 @@ console.log(sayHi()) 関数に値が渡されていない限り、引数はデフォルトで`undefined`の値を持ちます。上記の場合、`name`引数に値を渡さなかったので、`name`は`undefined`となり出力されます。 -ES6では、このデフォルトの`undefined`値を、デフォルトパラメータで上書きすることができます。例: +ES6 では、このデフォルトの`undefined`値を、デフォルトパラメータで上書きすることができます。例: `function sayHi(name = "Lydia") { ... }` @@ -2664,21 +2657,21 @@ ES6では、このデフォルトの`undefined`値を、デフォルトパラメ ###### 82. 何が出力されるでしょうか? ```javascript -var status = "😎" +var status = "😎"; setTimeout(() => { - const status = "😍" + const status = "😍"; const data = { status: "🥑", getStatus() { - return this.status - } - } + return this.status; + }, + }; - console.log(data.getStatus()) - console.log(data.getStatus.call(this)) -}, 0) + console.log(data.getStatus()); + console.log(data.getStatus.call(this)); +}, 0); ``` - A: `"🥑"` and `"😍"` @@ -2695,7 +2688,7 @@ setTimeout(() => { メソッドは`data`オブジェクトに属しているので、`this`は `data`オブジェクトを参照します。 `this.status`をログ出力すると、`data`オブジェクトの`status`プロパティの`"🥑"`がログ出力されます。 -`call`メソッドを使うと、`this`キーワードが参照するオブジェクトを変更することができます。 **関数**では、`this`キーワードは _その関数が属するオブジェクトを参照します_ 。 +`call`メソッドを使うと、`this`キーワードが参照するオブジェクトを変更することができます。 **関数**では、`this`キーワードは _その関数が属するオブジェクトを参照します_ 。 _グローバルオブジェクトで_ `setTimeout`関数を宣言したので、`setTimeout`関数内では、 `this`キーワードは _グローバルオブジェクト_ を参照します。 @@ -2711,13 +2704,13 @@ _グローバルオブジェクトで_ `setTimeout`関数を宣言したので ```javascript const person = { name: "Lydia", - age: 21 -} + age: 21, +}; -let city = person.city -city = "Amsterdam" +let city = person.city; +city = "Amsterdam"; -console.log(person) +console.log(person); ``` - A: `{ name: "Lydia", age: 21 }` @@ -2734,7 +2727,7 @@ console.log(person) 我々は`person`オブジェクト自身を参照して _いない_ ことに注意してください。`person`オブジェクトの`city`プロパティを、変数`city`に代入するだけです。 -それから、`city`に、文字列`"Amsterdam"`を代入しますこれは personオブジェクトを変更しません: そのオブジェクトへの参照はありません。 +それから、`city`に、文字列`"Amsterdam"`を代入しますこれは person オブジェクトを変更しません: そのオブジェクトへの参照はありません。 `person`オブジェクトをログ出力するとき、未修正のオブジェクトが返されます。 @@ -2748,15 +2741,15 @@ console.log(person) ```javascript function checkAge(age) { if (age < 18) { - const message = "Sorry, you're too young." + const message = "Sorry, you're too young."; } else { - const message = "Yay! You're old enough!" + const message = "Yay! You're old enough!"; } - return message + return message; } -console.log(checkAge(21)) +console.log(checkAge(21)); ``` - A: `"Sorry, you're too young."` @@ -2769,7 +2762,7 @@ console.log(checkAge(21)) #### 答え: C -`const`と`let`キーワードを持つ変数は _ブロックスコープ_ です。ブロックは中括弧(`{ }`)で囲まれたものです。上記の場合、if/elseステートメントが中括弧となります。宣言されたブロックの外側で変数を参照することはできません。ReferenceError がスローされます。 +`const`と`let`キーワードを持つ変数は _ブロックスコープ_ です。ブロックは中括弧(`{ }`)で囲まれたものです。上記の場合、if/else ステートメントが中括弧となります。宣言されたブロックの外側で変数を参照することはできません。ReferenceError がスローされます。

@@ -2779,29 +2772,29 @@ console.log(checkAge(21)) ###### 85. どのような情報が出力されますか? ```javascript -fetch('https://www.website.com/api/user/1') - .then(res => res.json()) - .then(res => console.log(res)) +fetch("https://www.website.com/api/user/1") + .then((res) => res.json()) + .then((res) => console.log(res)); ``` - A: `fetch`メソッドの結果 -- B: 2回目の `fetch`メソッド呼び出しの結果 +- B: 2 回目の `fetch`メソッド呼び出しの結果 - C: 前の`.then()`でのコールバックの結果 -- D: 常に undefined. +- D: 常に undefined.
答え

#### 答え: C -2番目の`.then`の`res`の値は、前の`.then`の戻り値と同じとなります。値が次のハンドラに渡されるように、`.then`を連鎖させることができます。 +2 番目の`.then`の`res`の値は、前の`.then`の戻り値と同じとなります。値が次のハンドラに渡されるように、`.then`を連鎖させることができます。

--- -###### 86. 引数としてtrueを渡すことができない場合、どのオプションが`hasName`を`true`に設定するための方法ですか? +###### 86. 引数として true を渡すことができない場合、どのオプションが`hasName`を`true`に設定するための方法ですか? ```javascript function getName(name) { @@ -2819,7 +2812,7 @@ function getName(name) { #### 答え: A -`!!name`を使って、`name`の値が、truthyか falseyかを判断します。nameがtruthyであり、これをテストしたい場合、`!name`は`false`を返します。`!false`(これは実際には`!!name`です)は`true`を返します。 +`!!name`を使って、`name`の値が、truthy か falsey かを判断します。name が truthy であり、これをテストしたい場合、`!name`は`false`を返します。`!false`(これは実際には`!!name`です)は`true`を返します。 `hasName`に`name`を代入することで、`getName`関数に渡されたどんな値も`hasName`に代入されます。ブール値`true`は設定できません。 diff --git a/ko-KR/README-ko_KR.md b/ko-KR/README-ko_KR.md index 13651a7c..ef2d94e1 100644 --- a/ko-KR/README-ko_KR.md +++ b/ko-KR/README-ko_KR.md @@ -34,6 +34,7 @@ - [🇳🇱 Nederlands](../nl-NL/README.md) - [🇵🇱 Polski](../pl-PL/README.md) - [🇧🇷 Português Brasil](../pt-BR/README_pt_BR.md) +- [🇷o Română](../ro-RO/README.ro.md) - [🇷🇺 Русский](../ru-RU/README.md) - [🇽🇰 Shqip](../sq-KS/README_sq_KS.md) - [🇹🇭 ไทย](../th-TH/README-th_TH.md) @@ -54,7 +55,7 @@ function sayHi() { console.log(name); console.log(age); - var name = 'Lydia'; + var name = "Lydia"; let age = 21; } @@ -150,7 +151,7 @@ console.log(shape.perimeter()); ```javascript +true; -!'Lydia'; +!"Lydia"; ``` - A: `1` 그리고 `false` @@ -175,11 +176,11 @@ console.log(shape.perimeter()); ```javascript const bird = { - size: 'small', + size: "small", }; const mouse = { - name: 'Mickey', + name: "Mickey", small: true, }; ``` @@ -210,11 +211,11 @@ JavaScript는 문장을 해석(또는 분)해요. 대괄호 표기를 사용하 ###### 6. 무엇이 출력 될까요? ```javascript -let c = { greeting: 'Hey!' }; +let c = { greeting: "Hey!" }; let d; d = c; -c.greeting = 'Hello'; +c.greeting = "Hello"; console.log(d.greeting); ``` @@ -229,7 +230,7 @@ console.log(d.greeting); #### 답: A -JavaScript에서 모든 객체는 서로를 동일하게 설정하면 _참조_로 상호작용해요. +JavaScript에서 모든 객체는 서로를 동일하게 설정하면 *참조*로 상호작용해요. 우선, 변수 `c`는 객체에 대한 값을 갖고 있어요. 그 후 `c`가 객체에 가지고 있는 것과 동일한 참조를 `d`에 할당해요. @@ -284,13 +285,13 @@ class Chameleon { return this.newColor; } - constructor({ newColor = 'green' } = {}) { + constructor({ newColor = "green" } = {}) { this.newColor = newColor; } } -const freddie = new Chameleon({ newColor: 'purple' }); -console.log(freddie.colorChange('orange')); +const freddie = new Chameleon({ newColor: "purple" }); +console.log(freddie.colorChange("orange")); ``` - A: `orange` @@ -340,10 +341,10 @@ console.log(greetign); ```javascript function bark() { - console.log('Woof!'); + console.log("Woof!"); } -bark.animal = 'dog'; +bark.animal = "dog"; ``` - A: 별일 없어요, 이건 완전히 괜찮아요! @@ -373,7 +374,7 @@ function Person(firstName, lastName) { this.lastName = lastName; } -const member = new Person('Lydia', 'Hallie'); +const member = new Person("Lydia", "Hallie"); Person.getFullName = function () { return `${this.firstName} ${this.lastName}`; }; @@ -414,8 +415,8 @@ function Person(firstName, lastName) { this.lastName = lastName; } -const lydia = new Person('Lydia', 'Hallie'); -const sarah = Person('Sarah', 'Smith'); +const lydia = new Person("Lydia", "Hallie"); +const sarah = Person("Sarah", "Smith"); console.log(lydia); console.log(sarah); @@ -485,7 +486,7 @@ function sum(a, b) { return a + b; } -sum(1, '2'); +sum(1, "2"); ``` - A: `NaN` @@ -552,7 +553,7 @@ function getPersonInfo(one, two, three) { console.log(three); } -const person = 'Lydia'; +const person = "Lydia"; const age = 21; getPersonInfo`${person} is ${age} years old`; @@ -579,9 +580,9 @@ getPersonInfo`${person} is ${age} years old`; ```javascript function checkAge(data) { if (data === { age: 18 }) { - console.log('You are an adult!'); + console.log("You are an adult!"); } else if (data == { age: 18 }) { - console.log('You are still an adult.'); + console.log("You are still an adult."); } else { console.log(`Hmm.. You don't have an age I guess`); } @@ -641,7 +642,7 @@ rest 파라미터 (`...args`)는 남아있는 모든 인수을 하나의 배열 ```javascript function getAge() { - 'use strict'; + "use strict"; age = 21; console.log(age); } @@ -669,7 +670,7 @@ getAge(); ###### 21. `sum`의 값은 무엇일까요? ```javascript -const sum = eval('10*10+5'); +const sum = eval("10*10+5"); ``` - A: `105` @@ -692,7 +693,7 @@ const sum = eval('10*10+5'); ###### 22. cool_secret에 몇 시간이나 접근이 가능할까요? ```javascript -sessionStorage.setItem('cool_secret', 123); +sessionStorage.setItem("cool_secret", 123); ``` - A: 영원히, 데이터는 사라지지 않아요. @@ -745,12 +746,12 @@ console.log(num); ###### 24. 무엇이 출력 될까요? ```javascript -const obj = { 1: 'a', 2: 'b', 3: 'c' }; +const obj = { 1: "a", 2: "b", 3: "c" }; const set = new Set([1, 2, 3, 4, 5]); -obj.hasOwnProperty('1'); +obj.hasOwnProperty("1"); obj.hasOwnProperty(1); -set.has('1'); +set.has("1"); set.has(1); ``` @@ -776,7 +777,7 @@ set에서는 동작하지 않아요. set에는 `'1'`이 없어요: `set.has('1') ###### 25. 무엇이 출력 될까요? ```javascript -const obj = { a: 'one', b: 'two', a: 'three' }; +const obj = { a: "one", b: "two", a: "three" }; console.log(obj); ``` @@ -845,12 +846,12 @@ for (let i = 1; i < 5; i++) { ```javascript String.prototype.giveLydiaPizza = () => { - return 'Just give Lydia pizza already!'; + return "Just give Lydia pizza already!"; }; -const name = 'Lydia'; +const name = "Lydia"; -console.log(name.giveLydiaPizza()) +console.log(name.giveLydiaPizza()); ``` - A: `"Just give Lydia pizza already!"` @@ -874,8 +875,8 @@ console.log(name.giveLydiaPizza()) ```javascript const a = {}; -const b = { key: 'b' }; -const c = { key: 'c' }; +const b = { key: "b" }; +const c = { key: "c" }; a[b] = 123; a[c] = 456; @@ -907,9 +908,9 @@ console.log(a[b]); ###### 30. 무엇이 출력 될까요? ```javascript -const foo = () => console.log('First'); -const bar = () => setTimeout(() => console.log('Second')); -const baz = () => console.log('Third'); +const foo = () => console.log("First"); +const bar = () => setTimeout(() => console.log("Second")); +const baz = () => console.log("Third"); bar(); foo(); @@ -1012,7 +1013,7 @@ WebAPI는 준비가 될 때마다 stack에 항목을 추가할 수 없어요. ###### 33. 무엇이 출력 될까요? ```javascript -const person = { name: 'Lydia' }; +const person = { name: "Lydia" }; function sayHi(age) { console.log(`${this.name} is ${age}`); @@ -1075,8 +1076,8 @@ console.log(typeof sayHi()); ```javascript 0; new Number(0); -(''); -(' '); +(""); +(" "); new Boolean(false); undefined; ``` @@ -1259,7 +1260,7 @@ JavaScript는 원시형과 객체만 가지고 있어요. ```javascript !!null; -!!''; +!!""; !!1; ``` @@ -1287,7 +1288,7 @@ JavaScript는 원시형과 객체만 가지고 있어요. ###### 42. `setInterval` 메소드는 브라우저에게 무엇을 반환 할까요? ```javascript -setInterval(() => console.log('Hi'), 1000); +setInterval(() => console.log("Hi"), 1000); ``` - A: 유니크한 id @@ -1310,7 +1311,7 @@ setInterval(() => console.log('Hi'), 1000); ###### 43. 이것은 무엇을 반환할까요? ```javascript -[...'Lydia']; +[..."Lydia"]; ``` - A: `["L", "y", "d", "i", "a"]` @@ -1369,11 +1370,11 @@ console.log(gen.next().value); ```javascript const firstPromise = new Promise((res, rej) => { - setTimeout(res, 500, 'one'); + setTimeout(res, 500, "one"); }); const secondPromise = new Promise((res, rej) => { - setTimeout(res, 100, 'two'); + setTimeout(res, 100, "two"); }); Promise.race([firstPromise, secondPromise]).then((res) => console.log(res)); @@ -1399,7 +1400,7 @@ Promise.race([firstPromise, secondPromise]).then((res) => console.log(res)); ###### 46. 무엇이 출력 될까요? ```javascript -let person = { name: 'Lydia' }; +let person = { name: "Lydia" }; const members = [person]; person = null; @@ -1420,7 +1421,7 @@ console.log(members); -그 후, `members`라는 변수를 선언해요. 배열의 첫 번째 요소에 `person` 변수의 값을 대입해요. 서로를 같게 설정하면 _참조_로 상호작용해요. 어떤 변수에서 다른 변수로 참조를 할당하면, 그 참조의 _복사본_ 을 만들어요. (그들은 _같은_ 참조를 가지고 있지 않다는 것을 유의하세요!) +그 후, `members`라는 변수를 선언해요. 배열의 첫 번째 요소에 `person` 변수의 값을 대입해요. 서로를 같게 설정하면 *참조*로 상호작용해요. 어떤 변수에서 다른 변수로 참조를 할당하면, 그 참조의 _복사본_ 을 만들어요. (그들은 _같은_ 참조를 가지고 있지 않다는 것을 유의하세요!) @@ -1439,7 +1440,7 @@ console.log(members); ```javascript const person = { - name: 'Lydia', + name: "Lydia", age: 21, }; @@ -1468,7 +1469,7 @@ for (const item in person) { ###### 48. 무엇이 출력 될까요? ```javascript -console.log(3 + 4 + '5'); +console.log(3 + 4 + "5"); ``` - A: `"345"` @@ -1495,7 +1496,7 @@ console.log(3 + 4 + '5'); ###### 49. `num`의 값은 무엇일까요? ```javascript -const num = parseInt('7*6', 10); +const num = parseInt("7*6", 10); ``` - A: `42` @@ -1521,7 +1522,7 @@ const num = parseInt('7*6', 10); ```javascript [1, 2, 3].map((num) => { - if (typeof num === 'number') return; + if (typeof num === "number") return; return num * 2; }); ``` @@ -1549,12 +1550,12 @@ const num = parseInt('7*6', 10); ```javascript function getInfo(member, year) { - member.name = 'Lydia'; - year = '1998'; + member.name = "Lydia"; + year = "1998"; } -const person = { name: 'Sarah' }; -const birthYear = '1997'; +const person = { name: "Sarah" }; +const birthYear = "1997"; getInfo(person, birthYear); @@ -1586,15 +1587,15 @@ console.log(person, birthYear); ```javascript function greeting() { - throw 'Hello world!'; + throw "Hello world!"; } function sayHi() { try { const data = greeting(); - console.log('It worked!', data); + console.log("It worked!", data); } catch (e) { - console.log('Oh no an error:', e); + console.log("Oh no an error:", e); } } @@ -1624,8 +1625,8 @@ sayHi(); ```javascript function Car() { - this.make = 'Lamborghini'; - return { make: 'Maserati' }; + this.make = "Lamborghini"; + return { make: "Maserati" }; } const myCar = new Car(); @@ -1701,7 +1702,7 @@ Dog.prototype.bark = function () { console.log(`Woof I am ${this.name}`); }; -const pet = new Dog('Mara'); +const pet = new Dog("Mara"); pet.bark(); @@ -1766,7 +1767,7 @@ export default counter; ```javascript // index.js -import myCounter from './counter'; +import myCounter from "./counter"; myCounter += 1; @@ -1866,7 +1867,7 @@ console.log(y); ###### 60. 무엇이 출력 될까요? ```javascript -const user = { name: 'Lydia', age: 21 }; +const user = { name: "Lydia", age: 21 }; const admin = { admin: true, ...user }; console.log(admin); @@ -1892,9 +1893,9 @@ spread 연산자 `...` 를 사용해 객체를 결합할 수 있어요. 이것 ###### 61. 무엇이 출력 될까요? ```javascript -const person = { name: 'Lydia' }; +const person = { name: "Lydia" }; -Object.defineProperty(person, 'age', { value: 21 }); +Object.defineProperty(person, "age", { value: 21 }); console.log(person); console.log(Object.keys(person)); @@ -1923,12 +1924,12 @@ console.log(Object.keys(person)); ```javascript const settings = { - username: 'lydiahallie', + username: "lydiahallie", level: 19, health: 90, }; -const data = JSON.stringify(settings, ['level', 'health']); +const data = JSON.stringify(settings, ["level", "health"]); console.log(data); ``` @@ -1959,7 +1960,7 @@ replacer가 _함수_ 라면, 문자열로 변환 할 객체의 모든 속성에 let num = 10; const increaseNumber = () => num++; -const increasePassedNumber = number => number++; +const increasePassedNumber = (number) => number++; const num1 = increaseNumber(); const num2 = increasePassedNumber(num1); @@ -2116,12 +2117,12 @@ class Labrador extends Dog { ```javascript // index.js -console.log('running index.js'); -import { sum } from './sum.js'; +console.log("running index.js"); +import { sum } from "./sum.js"; console.log(sum(1, 2)); // sum.js -console.log('running sum.js'); +console.log("running sum.js"); export const sum = (a, b) => a + b; ``` @@ -2149,7 +2150,7 @@ export const sum = (a, b) => a + b; ```javascript console.log(Number(2) === Number(2)); console.log(Boolean(false) === Boolean(false)); -console.log(Symbol('foo') === Symbol('foo')); +console.log(Symbol("foo") === Symbol("foo")); ``` - A: `true`, `true`, `false` @@ -2172,7 +2173,7 @@ console.log(Symbol('foo') === Symbol('foo')); ###### 69. 무엇이 출력 될까요? ```javascript -const name = 'Lydia Hallie'; +const name = "Lydia Hallie"; console.log(name.padStart(13)); console.log(name.padStart(2)); ``` @@ -2199,7 +2200,7 @@ console.log(name.padStart(2)); ###### 70. 무엇이 출력 될까요? ```javascript -console.log('🥑' + '💻'); +console.log("🥑" + "💻"); ``` - A: `"🥑💻"` @@ -2223,11 +2224,11 @@ console.log('🥑' + '💻'); ```javascript function* startGame() { - const answer = yield 'Do you love JavaScript?'; - if (answer !== 'Yes') { + const answer = yield "Do you love JavaScript?"; + if (answer !== "Yes") { return "Oh wow... Guess we're gone here"; } - return 'JavaScript loves you back ❤️'; + return "JavaScript loves you back ❤️"; } const game = startGame(); @@ -2295,7 +2296,7 @@ console.log(String.raw`Hello\nworld`); ```javascript async function getData() { - return await Promise.resolve('I made it!'); + return await Promise.resolve("I made it!"); } const data = getData(); @@ -2332,7 +2333,7 @@ function addToList(item, list) { return list.push(item); } -const result = addToList('apple', ['banana']); +const result = addToList("apple", ["banana"]); console.log(result); ``` @@ -2392,7 +2393,7 @@ console.log(shape); ###### 76. 무엇이 출력 될까요? ```javascript -const { name: myName } = { name: 'Lydia' }; +const { name: myName } = { name: "Lydia" }; console.log(name); ``` @@ -2493,7 +2494,7 @@ console.log(addFunction(5 * 2)); ###### 79. 무엇이 출력 될까요? ```javascript -const myLifeSummedUp = ['☕', '💻', '🍷', '🍫']; +const myLifeSummedUp = ["☕", "💻", "🍷", "🍫"]; for (let item in myLifeSummedUp) { console.log(item); @@ -2589,13 +2590,13 @@ ES6에서, 기본값 `undefined` 값을 기본값 매개변수로 덮어쓸 수 ###### 82. 무엇이 출력 될까요? ```javascript -var status = '😎'; +var status = "😎"; setTimeout(() => { - const status = '😍'; + const status = "😍"; const data = { - status: '🥑', + status: "🥑", getStatus() { return this.status; }, @@ -2629,12 +2630,12 @@ setTimeout(() => { ```javascript const person = { - name: 'Lydia', + name: "Lydia", age: 21, }; let city = person.city; -city = 'Amsterdam'; +city = "Amsterdam"; console.log(person); ``` @@ -2698,7 +2699,7 @@ console.log(checkAge(21)); ###### 85. 어떤 종류의 정보가 출력될까요? ```javascript -fetch('https://www.website.com/api/user/1') +fetch("https://www.website.com/api/user/1") .then((res) => res.json()) .then((res) => console.log(res)); ``` @@ -2754,7 +2755,7 @@ function getName(name) { ###### 87. 무엇이 출력 될까요? ```javascript -console.log('I want pizza'[0]); +console.log("I want pizza"[0]); ``` - A: `"""` @@ -2809,11 +2810,11 @@ sum(10); ```javascript // module.js -export default () => 'Hello world'; -export const name = 'Lydia'; +export default () => "Hello world"; +export const name = "Lydia"; // index.js -import * as data from './module'; +import * as data from "./module"; console.log(data); ``` @@ -2846,7 +2847,7 @@ class Person { } } -const member = new Person('John'); +const member = new Person("John"); console.log(typeof member); ``` @@ -2906,7 +2907,7 @@ console.log(newList.push(5)); ```javascript function giveLydiaPizza() { - return 'Here is pizza!'; + return "Here is pizza!"; } const giveLydiaChocolate = () => @@ -2937,7 +2938,7 @@ console.log(giveLydiaChocolate.prototype); ```javascript const person = { - name: 'Lydia', + name: "Lydia", age: 21, }; @@ -2997,7 +2998,7 @@ function getItems(fruitList, favoriteFruit, ...args) { return [...fruitList, ...args, favoriteFruit]; } -getItems(['banana', 'apple'], 'pear', 'orange'); +getItems(["banana", "apple"], "pear", "orange"); ``` 위의 예시는 동작해요. 배열 `[ 'banana', 'apple', 'orange', 'pear' ]`을 반환해요. @@ -3011,8 +3012,8 @@ getItems(['banana', 'apple'], 'pear', 'orange'); ```javascript function nums(a, b) { - if (a > b) console.log('a is bigger'); - else console.log('b is bigger'); + if (a > b) console.log("a is bigger"); + else console.log("b is bigger"); return; a + b; } @@ -3052,13 +3053,13 @@ a + b; ```javascript class Person { constructor() { - this.name = 'Lydia'; + this.name = "Lydia"; } } Person = class AnotherPerson { constructor() { - this.name = 'Sarah'; + this.name = "Sarah"; } }; @@ -3087,7 +3088,7 @@ console.log(member.name); ```javascript const info = { - [Symbol('a')]: 'b', + [Symbol("a")]: "b", }; console.log(info); @@ -3156,7 +3157,7 @@ rest 파라미터를 사용해 `...y`에 모든 "남은" 인수을 배열에 넣 ###### 99. 무엇이 출력 될까요? ```javascript -const name = 'Lydia'; +const name = "Lydia"; console.log(name()); ``` @@ -3188,8 +3189,8 @@ ReferenceErrors는 JavaScript가 접근하려고 하는 값의 참조를 찾을 ```javascript // 🎉✨ 이번이 내 100번째 질문이에요! ✨🎉 -const output = `${[] && 'Im'}possible! -You should${'' && `n't`} see a therapist after so much JavaScript lol`; +const output = `${[] && "Im"}possible! +You should${"" && `n't`} see a therapist after so much JavaScript lol`; ``` - A: `possible! You should see a therapist after so much JavaScript lol` @@ -3215,7 +3216,7 @@ You should${'' && `n't`} see a therapist after so much JavaScript lol`; ```javascript const one = false || {} || null; -const two = null || false || ''; +const two = null || false || ""; const three = [] || 0 || true; console.log(one, two, three); @@ -3247,16 +3248,16 @@ console.log(one, two, three); ###### 102. 무엇이 출력 될까요? ```javascript -const myPromise = () => Promise.resolve('I have resolved!'); +const myPromise = () => Promise.resolve("I have resolved!"); function firstFunction() { myPromise().then((res) => console.log(res)); - console.log('second'); + console.log("second"); } async function secondFunction() { console.log(await myPromise()); - console.log('second'); + console.log("second"); } firstFunction(); @@ -3294,8 +3295,8 @@ promise를 사용하면, 기본적으로 _이 함수를 실행하고 싶지만, const set = new Set(); set.add(1); -set.add('Lydia'); -set.add({ name: 'Lydia' }); +set.add("Lydia"); +set.add({ name: "Lydia" }); for (let item of set) { console.log(item + 2); @@ -3355,13 +3356,13 @@ promise 또는 non-promise가 아니더라도, 어떤 유형의 값이라도 `Pr ```javascript function compareMembers(person1, person2 = person) { if (person1 !== person2) { - console.log('Not the same!'); + console.log("Not the same!"); } else { - console.log('They are the same!'); + console.log("They are the same!"); } } -const person = { name: 'Lydia' }; +const person = { name: "Lydia" }; compareMembers(person); ``` @@ -3400,7 +3401,7 @@ const colorConfig = { yellow: false, }; -const colors = ['pink', 'red', 'blue']; +const colors = ["pink", "red", "blue"]; console.log(colorConfig.colors[1]); ``` @@ -3429,7 +3430,7 @@ JavaScript 문장을 해석(또는 참조형 변수를 원시 데이터 타입 ###### 107. 값은 무엇일까요? ```javascript -console.log('❤️' === '❤️'); +console.log("❤️" === "❤️"); ``` - A: `true` @@ -3450,14 +3451,14 @@ console.log('❤️' === '❤️'); ###### 108. 다음 중 원본 배열을 수정하는 method는 무엇일까요? ```javascript -const emojis = ['✨', '🥑', '😍']; +const emojis = ["✨", "🥑", "😍"]; -emojis.map((x) => x + '✨'); -emojis.filter((x) => x !== '🥑'); -emojis.find((x) => x !== '🥑'); -emojis.reduce((acc, cur) => acc + '✨'); -emojis.slice(1, 2, '✨'); -emojis.splice(1, 2, '✨'); +emojis.map((x) => x + "✨"); +emojis.filter((x) => x !== "🥑"); +emojis.find((x) => x !== "🥑"); +emojis.reduce((acc, cur) => acc + "✨"); +emojis.slice(1, 2, "✨"); +emojis.splice(1, 2, "✨"); ``` - A: `All of them` @@ -3482,10 +3483,10 @@ emojis.splice(1, 2, '✨'); ###### 109. 무엇이 출력 될까요? ```javascript -const food = ['🍕', '🍫', '🥑', '🍔']; +const food = ["🍕", "🍫", "🥑", "🍔"]; const info = { favoriteFood: food[0] }; -info.favoriteFood = '🍝'; +info.favoriteFood = "🍝"; console.log(food); ``` @@ -3539,7 +3540,7 @@ const jsonArray = JSON.stringify([1, 2, 3]); // '[1, 2, 3]' JSON.parse(jsonArray); // [1, 2, 3] // 객체를 유효한 JSON 문자열로 변환해요, 그리고 나서 JSON 문자열의 구문을 분석해 JavaScript 값으로 생성해요. -const jsonArray = JSON.stringify({ name: 'Lydia' }); // '{"name":"Lydia"}' +const jsonArray = JSON.stringify({ name: "Lydia" }); // '{"name":"Lydia"}' JSON.parse(jsonArray); // { name: 'Lydia' } ``` @@ -3551,11 +3552,11 @@ JSON.parse(jsonArray); // { name: 'Lydia' } ###### 111. 무엇이 출력 될까요? ```javascript -let name = 'Lydia'; +let name = "Lydia"; function getName() { console.log(name); - let name = 'Sarah'; + let name = "Sarah"; } getName(); @@ -3578,7 +3579,7 @@ getName(); `getName` 함수 안에 `name` 변수를 선언하지 않았다면, javaScript 엔진은 _스코프 체인_ 을 살펴봤을 거예요. 외부 범위에는 값이 `Lydia`인 `name`이라는 변수가 있어요. 이 경우 `Lydia`를 출력할 거예요. ```javascript -let name = 'Lydia'; +let name = "Lydia"; function getName() { console.log(name); @@ -3596,11 +3597,11 @@ getName(); // Lydia ```javascript function* generatorOne() { - yield ['a', 'b', 'c']; + yield ["a", "b", "c"]; } function* generatorTwo() { - yield* ['a', 'b', 'c']; + yield* ["a", "b", "c"]; } const one = generatorOne(); @@ -3646,7 +3647,7 @@ console.log(two.next().value); // undefined ###### 113. 무엇이 출력 될까요? ```javascript -console.log(`${((x) => x)('I love')} to program`); +console.log(`${((x) => x)("I love")} to program`); ``` - A: `I love to program` @@ -3671,7 +3672,7 @@ console.log(`${((x) => x)('I love')} to program`); ```javascript let config = { alert: setInterval(() => { - console.log('Alert!'); + console.log("Alert!"); }, 1000), }; @@ -3703,16 +3704,16 @@ config = null; ```javascript const myMap = new Map(); -const myFunc = () => 'greeting'; +const myFunc = () => "greeting"; -myMap.set(myFunc, 'Hello world!'); +myMap.set(myFunc, "Hello world!"); //1 -myMap.get('greeting'); +myMap.get("greeting"); //2 myMap.get(myFunc); //3 -myMap.get(() => 'greeting'); +myMap.get(() => "greeting"); ``` - A: 1 @@ -3739,14 +3740,14 @@ myMap.get(() => 'greeting'); ```javascript const person = { - name: 'Lydia', + name: "Lydia", age: 21, }; const changeAge = (x = { ...person }) => (x.age += 1); const changeAgeAndName = (x = { ...person }) => { x.age += 1; - x.name = 'Sarah'; + x.name = "Sarah"; }; changeAge(person); @@ -3805,7 +3806,7 @@ function sumValues(x, y, z) { ```javascript let num = 1; -const list = ['🥳', '🤠', '🥰', '🤪']; +const list = ["🥳", "🤠", "🥰", "🤪"]; console.log(list[(num += 1)]); ``` @@ -3831,11 +3832,11 @@ console.log(list[(num += 1)]); ```javascript const person = { - firstName: 'Lydia', - lastName: 'Hallie', + firstName: "Lydia", + lastName: "Hallie", pet: { - name: 'Mara', - breed: 'Dutch Tulip Hound', + name: "Mara", + breed: "Dutch Tulip Hound", }, getFullName() { return `${this.firstName} ${this.lastName}`; @@ -3873,10 +3874,10 @@ optional chaining 연산자 `?.`를 사용하면, 더 깊이 중첩된 값이 ###### 120. 무엇이 출력 될까요? ```javascript -const groceries = ['banana', 'apple', 'peanuts']; +const groceries = ["banana", "apple", "peanuts"]; -if (groceries.indexOf('banana')) { - console.log('We have to buy bananas!'); +if (groceries.indexOf("banana")) { + console.log("We have to buy bananas!"); } else { console.log(`We don't have to buy bananas!`); } @@ -3932,10 +3933,10 @@ console.log(config.language); ###### 122. 무엇이 출력 될까요? ```javascript -const name = 'Lydia Hallie'; +const name = "Lydia Hallie"; -console.log(!typeof name === 'object'); -console.log(!typeof name === 'string'); +console.log(!typeof name === "object"); +console.log(!typeof name === "string"); ``` - A: `false` `true` @@ -4050,14 +4051,14 @@ myFunc(1, 2, 3); ```javascript function getFine(speed, amount) { - const formattedSpeed = new Intl.NumberFormat('en-US', { - style: 'unit', - unit: 'mile-per-hour', + const formattedSpeed = new Intl.NumberFormat("en-US", { + style: "unit", + unit: "mile-per-hour", }).format(speed); - const formattedAmount = new Intl.NumberFormat('en-US', { - style: 'currency', - currency: 'USD', + const formattedAmount = new Intl.NumberFormat("en-US", { + style: "currency", + currency: "USD", }).format(amount); return `The driver drove ${formattedSpeed} and has to pay ${formattedAmount}`; @@ -4086,8 +4087,8 @@ console.log(getFine(130, 300)); ###### 127. 무엇이 출력 될까요? ```javascript -const spookyItems = ['👻', '🎃', '🕸']; -({ item: spookyItems[3] } = { item: '💀' }); +const spookyItems = ["👻", "🎃", "🕸"]; +({ item: spookyItems[3] } = { item: "💀" }); console.log(spookyItems); ``` @@ -4112,7 +4113,7 @@ console.log(spookyItems); ###### 128. 무엇이 출력 될까요? ```javascript -const name = 'Lydia Hallie'; +const name = "Lydia Hallie"; const age = 21; console.log(Number.isNaN(name)); @@ -4148,7 +4149,7 @@ const randomValue = 21; function getInfo() { console.log(typeof randomValue); - const randomValue = 'Lydia Hallie'; + const randomValue = "Lydia Hallie"; } getInfo(); @@ -4174,7 +4175,7 @@ getInfo(); ###### 130. 무엇이 출력 될까요? ```javascript -const myPromise = Promise.resolve('Woah some cool data'); +const myPromise = Promise.resolve("Woah some cool data"); (async () => { try { @@ -4182,7 +4183,7 @@ const myPromise = Promise.resolve('Woah some cool data'); } catch { throw new Error(`Oops didn't work`); } finally { - console.log('Oh finally!'); + console.log("Oh finally!"); } })(); ``` @@ -4207,7 +4208,7 @@ const myPromise = Promise.resolve('Woah some cool data'); ###### 131. 무엇이 출력 될까요? ```javascript -const emojis = ['🥑', ['✨', '✨', ['🍕', '🍕']]]; +const emojis = ["🥑", ["✨", "✨", ["🍕", "🍕"]]]; console.log(emojis.flat(1)); ``` @@ -4280,19 +4281,19 @@ console.log(counterOne.count); ###### 133. 무엇이 출력 될까요? ```javascript -const myPromise = Promise.resolve(Promise.resolve('Promise!')); +const myPromise = Promise.resolve(Promise.resolve("Promise!")); function funcOne() { myPromise.then((res) => res).then((res) => console.log(res)); - setTimeout(() => console.log('Timeout!'), 0); - console.log('Last line!'); + setTimeout(() => console.log("Timeout!"), 0); + console.log("Last line!"); } async function funcTwo() { const res = await myPromise; console.log(await res); - setTimeout(() => console.log('Timeout!'), 0); - console.log('Last line!'); + setTimeout(() => console.log("Timeout!"), 0); + console.log("Last line!"); } funcOne(); @@ -4333,7 +4334,7 @@ export default function sum(x) { } // index.js -import * as sum from './sum'; +import * as sum from "./sum"; ``` - A: `sum(4)` @@ -4350,12 +4351,12 @@ import * as sum from './sum'; ```javascript // info.js -export const name = 'Lydia'; +export const name = "Lydia"; export const age = 21; -export default 'I love JavaScript'; +export default "I love JavaScript"; // index.js -import * as info from './info'; +import * as info from "./info"; console.log(info); ``` @@ -4386,13 +4387,13 @@ console.log(info); ```javascript const handler = { - set: () => console.log('Added a new property!'), - get: () => console.log('Accessed a property!'), + set: () => console.log("Added a new property!"), + get: () => console.log("Accessed a property!"), }; const person = new Proxy({}, handler); -person.name = 'Lydia'; +person.name = "Lydia"; person.name; ``` @@ -4422,7 +4423,7 @@ Proxy 객체를 사용하면, 두번째 인수로 전달 한 객체에 사용자 ###### 136. 다음 중 어느 것이 `person` 객체를 수정 할 수 있을까요? ```javascript -const person = { name: 'Lydia Hallie' }; +const person = { name: "Lydia Hallie" }; Object.seal(person); ``` @@ -4450,9 +4451,9 @@ Object.seal(person); ```javascript const person = { - name: 'Lydia Hallie', + name: "Lydia Hallie", address: { - street: '100 Main St', + street: "100 Main St", }, }; @@ -4552,8 +4553,8 @@ ES2020에서, `#`을 사용한 private 변수를 추가 할 수 있어요. 클 ```javascript const teams = [ - { name: 'Team 1', members: ['Paul', 'Lisa'] }, - { name: 'Team 2', members: ['Laura', 'Tim'] }, + { name: "Team 1", members: ["Paul", "Lisa"] }, + { name: "Team 2", members: ["Laura", "Tim"] }, ]; function* getMembers(members) { @@ -4596,8 +4597,8 @@ obj.next(); // { value: "Lisa", done: false } ```javascript const person = { - name: 'Lydia Hallie', - hobbies: ['coding'], + name: "Lydia Hallie", + hobbies: ["coding"], }; function addHobby(hobby, hobbies = person.hobbies) { @@ -4605,9 +4606,9 @@ function addHobby(hobby, hobbies = person.hobbies) { return hobbies; } -addHobby('running', []); -addHobby('dancing'); -addHobby('baking', person.hobbies); +addHobby("running", []); +addHobby("dancing"); +addHobby("baking", person.hobbies); console.log(person.hobbies); ``` @@ -4676,11 +4677,11 @@ const pet = new Flamingo(); ###### 143. 다음 중 어느 것의 결과가 오류일까요? ```javascript -const emojis = ['🎄', '🎅🏼', '🎁', '⭐']; +const emojis = ["🎄", "🎅🏼", "🎁", "⭐"]; -/* 1 */ emojis.push('🦌'); +/* 1 */ emojis.push("🦌"); /* 2 */ emojis.splice(0, 2); -/* 3 */ emojis = [...emojis, '🥂']; +/* 3 */ emojis = [...emojis, "🥂"]; /* 4 */ emojis.length = 0; ``` @@ -4766,9 +4767,9 @@ function getFruit(fruits) { console.log(fruits?.[1]?.[1]); } -getFruit([['🍊', '🍌'], ['🍍']]); +getFruit([["🍊", "🍌"], ["🍍"]]); getFruit(); -getFruit([['🍍'], ['🍊', '🍌']]); +getFruit([["🍍"], ["🍊", "🍌"]]); ``` - A: `null`, `undefined`, 🍌 @@ -4798,19 +4799,19 @@ getFruit([['🍍'], ['🍊', '🍌']]); ```javascript class Calc { - constructor() { - this.count = 0 - } + constructor() { + this.count = 0; + } - increase() { - this.count ++ - } + increase() { + this.count++; + } } -const calc = new Calc() -new Calc().increase() +const calc = new Calc(); +new Calc().increase(); -console.log(calc.count) +console.log(calc.count); ``` - A: `0` @@ -4834,25 +4835,25 @@ console.log(calc.count) ```javascript const user = { - email: "e@mail.com", - password: "12345" -} + email: "e@mail.com", + password: "12345", +}; const updateUser = ({ email, password }) => { - if (email) { - Object.assign(user, { email }) - } + if (email) { + Object.assign(user, { email }); + } - if (password) { - user.password = password - } + if (password) { + user.password = password; + } - return user -} + return user; +}; -const updatedUser = updateUser({ email: "new@email.com" }) +const updatedUser = updateUser({ email: "new@email.com" }); -console.log(updatedUser === user) +console.log(updatedUser === user); ``` - A: `false` @@ -4875,13 +4876,13 @@ console.log(updatedUser === user) ###### 149. 무엇이 출력 될까요? ```javascript -const fruit = ['🍌', '🍊', '🍎'] +const fruit = ["🍌", "🍊", "🍎"]; -fruit.slice(0, 1) -fruit.splice(0, 1) -fruit.unshift('🍇') +fruit.slice(0, 1); +fruit.splice(0, 1); +fruit.unshift("🍇"); -console.log(fruit) +console.log(fruit); ``` - A: `['🍌', '🍊', '🍎']` @@ -4907,13 +4908,13 @@ console.log(fruit) ```javascript const animals = {}; -let dog = { emoji: '🐶' } -let cat = { emoji: '🐈' } +let dog = { emoji: "🐶" }; +let cat = { emoji: "🐈" }; -animals[dog] = { ...dog, name: "Mara" } -animals[cat] = { ...cat, name: "Sara" } +animals[dog] = { ...dog, name: "Mara" }; +animals[cat] = { ...cat, name: "Sara" }; -console.log(animals[dog]) +console.log(animals[dog]); ``` - A: `{ emoji: "🐶", name: "Mara" }` @@ -4930,7 +4931,7 @@ console.log(animals[dog]) `dog`의 값은 객체 이므로, 사실 `animals[dog]`는 새로운 객체에 `"object Object"`라고 불리는 새로운 속성을 만든 걸 의미해요. 이제 `animals["object Object"]`는 `{ emoji: "🐶", name: "Mara"}`예요. -`cat`도 물론 객체고, 사실 `animals[cat]`은 `animals[``"``object Object``"``]`을 새로운 속성 cat으로 덮어쓰고 있다는 것을 의미해요. +`cat`도 물론 객체고, 사실 `animals[cat]`은 ` animals[``"``object Object``"``] `을 새로운 속성 cat으로 덮어쓰고 있다는 것을 의미해요. `animals[dog]` 또는 `animals["object Object"]`(`dog` 객체를 문자열로 변환한 결과는 `"object Object"`)를 출력하면, `{ emoji: "🐈", name: "Sara" }`를 반환해요. @@ -4943,14 +4944,14 @@ console.log(animals[dog]) ```javascript const user = { - email: "my@email.com", - updateEmail: email => { - this.email = email - } -} + email: "my@email.com", + updateEmail: (email) => { + this.email = email; + }, +}; -user.updateEmail("new@email.com") -console.log(user.email) +user.updateEmail("new@email.com"); +console.log(user.email); ``` - A: `my@email.com` @@ -4973,20 +4974,20 @@ console.log(user.email) ###### 152. 무엇이 출력 될까요? ```javascript -const promise1 = Promise.resolve('First') -const promise2 = Promise.resolve('Second') -const promise3 = Promise.reject('Third') -const promise4 = Promise.resolve('Fourth') +const promise1 = Promise.resolve("First"); +const promise2 = Promise.resolve("Second"); +const promise3 = Promise.reject("Third"); +const promise4 = Promise.resolve("Fourth"); const runPromises = async () => { - const res1 = await Promise.all([promise1, promise2]) - const res2 = await Promise.all([promise3, promise4]) - return [res1, res2] -} + const res1 = await Promise.all([promise1, promise2]); + const res2 = await Promise.all([promise3, promise4]); + return [res1, res2]; +}; runPromises() - .then(res => console.log(res)) - .catch(err => console.log(err)) + .then((res) => console.log(res)) + .catch((err) => console.log(err)); ``` - A: `[['First', 'Second'], ['Fourth']]` @@ -5009,13 +5010,16 @@ runPromises() ###### 153. 무엇이 `method`의 값이어야 `{ name: "Lydia", age: 22 }`를 출력할까요? ```javascript -const keys = ["name", "age"] -const values = ["Lydia", 22] +const keys = ["name", "age"]; +const values = ["Lydia", 22]; -const method = /* ?? */ -Object[method](keys.map((_, i) => { - return [keys[i], values[i]] -})) // { name: "Lydia", age: 22 } +const method = + /* ?? */ + Object[method]( + keys.map((_, i) => { + return [keys[i], values[i]]; + }) + ); // { name: "Lydia", age: 22 } ``` - A: `entries` @@ -5040,18 +5044,18 @@ Object[method](keys.map((_, i) => { ###### 154. 무엇이 출력 될까요? ```javascript -const createMember = ({ email, address = {}}) => { - const validEmail = /.+\@.+\..+/.test(email) - if (!validEmail) throw new Error("Valid email pls") +const createMember = ({ email, address = {} }) => { + const validEmail = /.+\@.+\..+/.test(email); + if (!validEmail) throw new Error("Valid email pls"); - return { - email, - address: address ? address : null - } -} + return { + email, + address: address ? address : null, + }; +}; -const member = createMember({ email: "my@email.com" }) -console.log(member) +const member = createMember({ email: "my@email.com" }); +console.log(member); ``` - A: `{ email: "my@email.com", address: null }` @@ -5074,13 +5078,13 @@ console.log(member) ###### 155. 무엇이 출력 될까요? ```javascript -let randomValue = { name: "Lydia" } -randomValue = 23 +let randomValue = { name: "Lydia" }; +randomValue = 23; if (!typeof randomValue === "string") { - console.log("It's not a string!") + console.log("It's not a string!"); } else { - console.log("Yay it's a string!") + console.log("Yay it's a string!"); } ``` diff --git a/nl-NL/README.md b/nl-NL/README.md index 0400e8ed..1852e0e0 100644 --- a/nl-NL/README.md +++ b/nl-NL/README.md @@ -2,14 +2,15 @@

JavaScript Vragen

- --- +--- + +Ik plaats JavaScript meerkeuzevragen op mijn [Instagram](https://www.instagram.com/theavocoder) **stories**, welke ik ook hier zal plaatsen! Laatste update: 24 december - Ik plaats JavaScript meerkeuzevragen op mijn [Instagram](https://www.instagram.com/theavocoder) **stories**, welke ik ook hier zal plaatsen! Laatste update: 24 december +Van beginner naar expert: test hoe goed je JavaScript kent, fris je kennis een beetje op, of bereid je voor op een sollicitatiegesprek! :muscle: :rocket: Ik zal deze repository regelmatig updaten met nieuwe vragen. Ik heb de antwoorden toegevoegd in de **ingeklapte secties** onder een vraag, zodat je er makkelijk op kan klikken om ze uit te klappen. Het is gewoon voor je plezier, veel succes! :heart: - Van beginner naar expert: test hoe goed je JavaScript kent, fris je kennis een beetje op, of bereid je voor op een sollicitatiegesprek! :muscle: :rocket: Ik zal deze repository regelmatig updaten met nieuwe vragen. Ik heb de antwoorden toegevoegd in de **ingeklapte secties** onder een vraag, zodat je er makkelijk op kan klikken om ze uit te klappen. Het is gewoon voor je plezier, veel succes! :heart: +Voel je vrij om contact met mij op te nemen! 😊
+Instagram || Twitter || LinkedIn || Blog - Voel je vrij om contact met mij op te nemen! 😊
- Instagram || Twitter || LinkedIn || Blog --- @@ -30,6 +31,7 @@ - [🇰🇷 한국어](../ko-KR/README-ko_KR.md) - [🇵🇱 Polski](../pl-PL/README.md) - [🇧🇷 Português Brasil](../pt-BR/README_pt_BR.md) +- [🇷o Română](../ro-RO/README.ro.md) - [🇷🇺 Русский](../ru-RU/README.md) - [🇽🇰 Shqip](../sq-KS/README_sq_KS.md) - [🇹🇭 ไทย](../th-TH/README-th_TH.md) @@ -114,7 +116,7 @@ const shape = { diameter() { return this.radius * 2; }, - perimeter: () => 2 * Math.PI * this.radius + perimeter: () => 2 * Math.PI * this.radius, }; console.log(shape.diameter()); @@ -171,12 +173,12 @@ De string `'Lydia'` is een truthy waarde. Wat we eigenlijk vragen, is "is deze t ```javascript const bird = { - size: "small" + size: "small", }; const mouse = { name: "Mickey", - small: true + small: true, }; ``` @@ -203,7 +205,6 @@ Echter, met de dot notatie zal dit niet gebeuren. `mouse` heeft geen propertie g --- - ###### 6. Wat is de uitkomst? ```javascript @@ -263,7 +264,7 @@ console.log(b === c); `new Number()` is een ingebouwde functie constructor. En ook al lijkt het misschien op een nummer, dat is het niet. Het is een object en bevat ten opzichte van een nummer veel extra opties. -Wanneer we de `==` operator gebruiken wordt er alleen op de _waarde_ gecheckt. Zowel `a` als `b` bevatten de waarde `3`, dus geeft dit `true` terug. +Wanneer we de `==` operator gebruiken wordt er alleen op de _waarde_ gecheckt. Zowel `a` als `b` bevatten de waarde `3`, dus geeft dit `true` terug. Echter, wanneer we de `===` operator gebruiken wordt er zowel op de _waarde_ als op het _type_ gecheckt. Omdat `new Number()` een **object** is en geen nummer zal dit `false` teruggeven. @@ -371,7 +372,7 @@ function Person(firstName, lastName) { } const member = new Person("Lydia", "Hallie"); -Person.getFullName = function() { +Person.getFullName = function () { return `${this.firstName} ${this.lastName}`; }; @@ -391,7 +392,7 @@ console.log(member.getFullName()); Je kunt geen properties toevoegen aan een instantie van een object, zoals je kan met normale objecten. Als je een feature toe wilt voegen aan alle objecten in één keer zul je dit middels de prototype van een object moeten doen. In dit geval, ```js -Person.prototype.getFullName = function() { +Person.prototype.getFullName = function () { return `${this.firstName} ${this.lastName}`; }; ``` @@ -847,7 +848,7 @@ String.prototype.giveLydiaPizza = () => { const name = "Lydia"; -console.log(name.giveLydiaPizza()) +console.log(name.giveLydiaPizza()); ``` - A: `"Just give Lydia pizza already!"` @@ -943,7 +944,7 @@ De WebAPI kan niet zomaar dingen toevoegen aan de stack. In plaats daarvan wordt -Dit is waar de event loop zijn intrede doet. Een ***event loop* naar de stack en de task queue. Als de stack leeg is pakt het het eerste ding op van de queue en zet het op de stack. +Dit is waar de event loop zijn intrede doet. Een _\*\*event loop_ naar de stack en de task queue. Als de stack leeg is pakt het het eerste ding op van de queue en zet het op de stack. @@ -959,9 +960,7 @@ Dit is waar de event loop zijn intrede doet. Een ***event loop* naar de stack en ```html
- +
``` @@ -987,9 +986,7 @@ Het diepst geneste element dat het event afvuurt is de target van het event. Je ```html
-

- Click here! -

+

Click here!

``` @@ -1224,7 +1221,10 @@ Wat primitieven onderscheidt van objecten is dat primitieven geen properties of ###### 40. Wat is de uitkomst? ```javascript -[[0, 1], [2, 3]].reduce( +[ + [0, 1], + [2, 3], +].reduce( (acc, cur) => { return acc.concat(cur); }, @@ -1349,6 +1349,7 @@ console.log(gen.next().value);

#### Antwoord: C + Reguliere functies kunnen niet worden gestopt halverwege na de aanroep. Echter, een generator functie kan wel "gestopt" worden halverwege, en later verder gaan waar ik gestopt is. Elke keer als een generator functie het keyword `yield` aantreft levert de functie de waarde op gespecificeerd achter `yield`. Let op dat een generator functie in dat geval niet de waarde _teruggeeft_, maar de waarde _oplevert_. Eerst initialiseren we de generator functie met `i`, dat gelijk is aan `10`. We roepen de generator functie aan met de `next()` methode. De eerste keer dat we de generator functie aanroepen is `i` gelijk aan `10`. De eerste `yield` wordt aangetroffen: het levert de waarde op van `i`. De generator is nu "gepauzeerd" en `10` wordt gelogd. @@ -1371,7 +1372,7 @@ const secondPromise = new Promise((res, rej) => { setTimeout(res, 100, "two"); }); -Promise.race([firstPromise, secondPromise]).then(res => console.log(res)); +Promise.race([firstPromise, secondPromise]).then((res) => console.log(res)); ``` - A: `"one"` @@ -1435,7 +1436,7 @@ We passaen alleen de waarde aan van de `person` variabele en niet van het eerste ```javascript const person = { name: "Lydia", - age: 21 + age: 21, }; for (const item in person) { @@ -1515,7 +1516,7 @@ Alleen het eerste getal in de string wordt geretourneerd. Gebaseerd op de _radix ###### 50. Wat is de uitkomst? ```javascript -[1, 2, 3].map(num => { +[1, 2, 3].map((num) => { if (typeof num === "number") return; return num * 2; }); @@ -1565,6 +1566,7 @@ console.log(person, birthYear);

#### Antwoord: A + Argumenten worden meegegeven _by value_, tenzij de waarde een object is. Dan worden ze meegegeven _by reference_. `birthYear` is een string en geen object, waardoor het dus doorgegeven wordt _by value_. Wanneer we een argument meegeven _by value_ wordt er een _copy_ aangemaakt van het argument (zie vraag 46). De variabele `birthYear` heeft een referentie naar de waarde `"1997"`. Het argument `year` heeft ook een referentie naar de waarde '"1997"', maar het is niet dezelfde waarde als waar `birthYear` een referentie naar heeft. Wanneer we de waarde van `year` veranderen naar `"1998"`, veranderen we alleen de waarde van `year`. `birthYear` is nog steeds gelijk aan `"1997"`. @@ -1691,7 +1693,7 @@ class Dog { } } -Dog.prototype.bark = function() { +Dog.prototype.bark = function () { console.log(`Woof I am ${this.name}`); }; @@ -1714,7 +1716,7 @@ pet.bark(); #### Antwoord: A -We kunnen properties verwijderen van een object als we gebruik maken van het `delete` keyword, en ook op het prototype. Bij het verwijderen van een propertie op de prototype zal het niet meer beschikbaar zijn in de prototype chain. In dit geval is de `bark()` methode niet meer beschikbaar op de protoype na `delete Dog.prototype.bark`. +We kunnen properties verwijderen van een object als we gebruik maken van het `delete` keyword, en ook op het prototype. Bij het verwijderen van een propertie op de prototype zal het niet meer beschikbaar zijn in de prototype chain. In dit geval is de `bark()` methode niet meer beschikbaar op de protoype na `delete Dog.prototype.bark`. Wanneer we iets proberen aan te roepen dat geen functie is zal er een `TypeError` gegooid worden. In dit geval `TypeError: pet.bark is not a function`, omdat `pet.bark` `undefined` is. @@ -1904,7 +1906,7 @@ console.log(Object.keys(person)); #### Antwoord: B -Met de `defineProperty` methode kunnen we properties toevoegen aan een object, of bestaande properties aanpassen. Wanneer we properties toevoegen aan een object door gebruik te maken van `defineProperty` zijn deze standaard _not enumerable_. De `Object.keys` methode geeft alle _enumerable_ propertie namen terug van een object, in dit geval alleen `"name"`. +Met de `defineProperty` methode kunnen we properties toevoegen aan een object, of bestaande properties aanpassen. Wanneer we properties toevoegen aan een object door gebruik te maken van `defineProperty` zijn deze standaard _not enumerable_. De `Object.keys` methode geeft alle _enumerable_ propertie namen terug van een object, in dit geval alleen `"name"`. Properties toegevoegd met de `defineProperty` methode zijn standaard onveranderbaar. Je kunt dit gedrag aanpassen door, in het derde argument, de `writable`, `configurable` en `enumerable` opties mee te geven. Op die manier geeft de `defineProperties` je veel controle over de properties die je wilt toevoegen aan een object. @@ -1919,7 +1921,7 @@ Properties toegevoegd met de `defineProperty` methode zijn standaard onveranderb const settings = { username: "lydiahallie", level: 19, - health: 90 + health: 90, }; const data = JSON.stringify(settings, ["level", "health"]); @@ -1953,7 +1955,7 @@ Als de replacer een _functie_ is zal die functie worden aangeroepen over elke pr let num = 10; const increaseNumber = () => num++; -const increasePassedNumber = number => number++; +const increasePassedNumber = (number) => number++; const num1 = increaseNumber(); const num2 = increasePassedNumber(num1); @@ -2009,7 +2011,7 @@ multiply(value); In ES6 kunnen we parameters initialiseren met een standaard waarde. De waarde van de parameter zal deze standaard waarde behouden zolang er geen andere waarde wordt meegegeven aan de functie, of als de waarde van de parameter `"undefined"` is. In dit geval kopiëren we de properties van het `value` object naar een nieuw object gebruikmakend van de spread operator, dus `x` heeft de standaard waarde `{ number: 10 }`. -De standaard waarde wordt geëvalueerd tijdens _call time_ (aanroeptijd)! Elke keer wanneer we de functie aanroepen wordt er een nieuw object aangemaakt. We roepen de `multiply` functie de eerste twee keer aan zonder een waarde mee te geven: `x` heeft de standaard waarde van `{ number: 10 }`. We loggen dan de vermenigvuldigde waarde van dat getal, wat `20` is. +De standaard waarde wordt geëvalueerd tijdens _call time_ (aanroeptijd)! Elke keer wanneer we de functie aanroepen wordt er een nieuw object aangemaakt. We roepen de `multiply` functie de eerste twee keer aan zonder een waarde mee te geven: `x` heeft de standaard waarde van `{ number: 10 }`. We loggen dan de vermenigvuldigde waarde van dat getal, wat `20` is. De derde keer dat we de functie `multiply` aanroepen geven we wel een waarde mee: het object genaamd `value`. De `*=` operator is eigenlijk een verkorting van `x.number = x.number * 2`: we passen de waarde van `x.number` aan en loggen de vermenigvuldigde waarde `20`. @@ -2040,11 +2042,11 @@ Het eerste argument van de `reduce` methode is de _accumulator_, in dit geval `x In dit voorbeeld geven we geen waarde terug. We loggen enkel the waarden van de accumulator en de huidige waarde. -De waarde van de accumulator is gelijk aan de vorige teruggegeven waarde van de callback functie. Als je niet de optionele `initialValue` meegeeft aan de `reduce` methode, de accumulator is gelijk aan het eerste element tijdens de eerste aanroep. +De waarde van de accumulator is gelijk aan de vorige teruggegeven waarde van de callback functie. Als je niet de optionele `initialValue` meegeeft aan de `reduce` methode, de accumulator is gelijk aan het eerste element tijdens de eerste aanroep. Tijdens de eerste aanroep is de accumulator (`x`) `1` en de huidige waarde (`y`) `2`. We geven niets terug in de callback function, we loggen de accumulator en de huidige waarde: `1` en `2` worden gelogd. -Als je niets teruggeeft in een functie, zal de functie `undefined` teruggeven. Tijdens de volgende aanroep is de accumulator `undefined` en de huidige waarde `3`. `undefined` en `3` worden gelogt. +Als je niets teruggeeft in een functie, zal de functie `undefined` teruggeven. Tijdens de volgende aanroep is de accumulator `undefined` en de huidige waarde `3`. `undefined` en `3` worden gelogt. Tijdens de vierde aanroep geven we wederom niets terug in de callback functie. De accumulator is wederom `undefined`, en de huidige waarde `4`. `undefined` en `4` worden gelogt. @@ -2063,7 +2065,7 @@ class Dog { }; class Labrador extends Dog { - // 1 + // 1 constructor(name, size) { this.size = size; } @@ -2077,7 +2079,7 @@ class Labrador extends Dog { super(name); this.size = size; } - // 4 + // 4 constructor(name, size) { this.name = name; this.size = size; @@ -2111,12 +2113,12 @@ De `Labrador` class verwacht twee argumenten, `name` omdat het een afgeleide is ```javascript // index.js -console.log('running index.js'); -import { sum } from './sum.js'; +console.log("running index.js"); +import { sum } from "./sum.js"; console.log(sum(1, 2)); // sum.js -console.log('running sum.js'); +console.log("running sum.js"); export const sum = (a, b) => a + b; ``` @@ -2142,9 +2144,9 @@ Dit is een verschil tussen `require()` in CommonJS en `import`! Met `require()` ###### 68. Wat is de uitkomst? ```javascript -console.log(Number(2) === Number(2)) -console.log(Boolean(false) === Boolean(false)) -console.log(Symbol('foo') === Symbol('foo')) +console.log(Number(2) === Number(2)); +console.log(Boolean(false) === Boolean(false)); +console.log(Symbol("foo") === Symbol("foo")); ``` - A: `true`, `true`, `false` @@ -2167,22 +2169,22 @@ Elk Symbol is volledig uniek. Het doel van het argument dat meegegeven wordt aan ###### 69. Wat is de uitkomst? ```javascript -const name = "Lydia Hallie" -console.log(name.padStart(13)) -console.log(name.padStart(2)) +const name = "Lydia Hallie"; +console.log(name.padStart(13)); +console.log(name.padStart(2)); ``` - A: `"Lydia Hallie"`, `"Lydia Hallie"` - B: `" Lydia Hallie"`, `" Lydia Hallie"` (`"[13x whitespace]Lydia Hallie"`, `"[2x whitespace]Lydia Hallie"`) - C: `" Lydia Hallie"`, `"Lydia Hallie"` (`"[1x whitespace]Lydia Hallie"`, `"Lydia Hallie"`) -- D: `"Lydia Hallie"`, `"Lyd"`, +- D: `"Lydia Hallie"`, `"Lyd"`,

Antwoord

#### Antwoord: C -Met de `padStart` methode kunnen we witruimte toevoegen aan het begin van de string. De waarde die meegegeven wordt aan de methode is de _totale_ lengte van de string, samen met de witruimte. De string `"Lydia Hallie"` heeft een lengte van `13`. `name.padStart(13)` plaatst 1 spatie toe aan het begin van de string omdat 12 + 1 = 13. +Met de `padStart` methode kunnen we witruimte toevoegen aan het begin van de string. De waarde die meegegeven wordt aan de methode is de _totale_ lengte van de string, samen met de witruimte. De string `"Lydia Hallie"` heeft een lengte van `13`. `name.padStart(13)` plaatst 1 spatie toe aan het begin van de string omdat 12 + 1 = 13. Als het argument dat we meegeven aan de `padStart` methode kleiner is dan de lengte van de string zullen er geen spaties worden toegevoegd. @@ -2443,7 +2445,7 @@ De `sum` functie geeft altijd dezelfde waarde terug. Als we `1` en `2` meegeven ```javascript const add = () => { const cache = {}; - return num => { + return (num) => { if (num in cache) { return `From cache! ${cache[num]}`; } else { @@ -2488,21 +2490,21 @@ De derde keer geven we `5 * 2` mee aan de functie wat `10` oplevert. Het `cache` ###### 79. Wat is de uitkomst? ```javascript -const myLifeSummedUp = ["☕", "💻", "🍷", "🍫"] +const myLifeSummedUp = ["☕", "💻", "🍷", "🍫"]; for (let item in myLifeSummedUp) { - console.log(item) + console.log(item); } for (let item of myLifeSummedUp) { - console.log(item) + console.log(item); } ``` - A: `0` `1` `2` `3` en `"☕"` ` "💻"` `"🍷"` `"🍫"` - B: `"☕"` ` "💻"` `"🍷"` `"🍫"` en `"☕"` ` "💻"` `"🍷"` `"🍫"` - C: `"☕"` ` "💻"` `"🍷"` `"🍫"` en `0` `1` `2` `3` -- D: `0` `1` `2` `3` en `{0: "☕", 1: "💻", 2: "🍷", 3: "🍫"}` +- D: `0` `1` `2` `3` en `{0: "☕", 1: "💻", 2: "🍷", 3: "🍫"}`

Antwoord

@@ -2525,21 +2527,21 @@ Met de _for-of_ loop kunnen we itereren over **iterables**. Een array is een ite ###### 80. Wat is de uitkomst? ```javascript -const list = [1 + 2, 1 * 2, 1 / 2] -console.log(list) +const list = [1 + 2, 1 * 2, 1 / 2]; +console.log(list); ``` - A: `["1 + 2", "1 * 2", "1 / 2"]` - B: `["12", 2, 0.5]` - C: `[3, 2, 0.5]` -- D: `[1, 1, 1]` +- D: `[1, 1, 1]`

Antwoord

#### Antwoord: C -Array elementen kunnen elke waarde bevatten. Nummers, strings, objecten, andere arrays, null, boolean waarden, undefined en andere expressies zoals datums, functies en berekeningen. +Array elementen kunnen elke waarde bevatten. Nummers, strings, objecten, andere arrays, null, boolean waarden, undefined en andere expressies zoals datums, functies en berekeningen. Het element zal gelijk zijn aan de teruggegeven waarde. `1 + 2` geeft `3` terug, `1 * 2` geeft `2` terug en `1 / 2` geeft `0.5` terug. @@ -2552,16 +2554,16 @@ Het element zal gelijk zijn aan de teruggegeven waarde. `1 + 2` geeft `3` terug, ```javascript function sayHi(name) { - return `Hi there, ${name}` + return `Hi there, ${name}`; } -console.log(sayHi()) +console.log(sayHi()); ``` - A: `Hi there, ` - B: `Hi there, undefined` - C: `Hi there, null` -- D: `ReferenceError` +- D: `ReferenceError`

Antwoord

@@ -2574,7 +2576,7 @@ In ES6 kunnen we argumenten een standaard waarde geven. Als voorbeeld: `function sayHi(name = "Lydia") { ... }` -In dit geval zal de waarde van het argument `name`, als we geen waarde meegeven aan de functie, standaard `Lydia` bevatten. +In dit geval zal de waarde van het argument `name`, als we geen waarde meegeven aan de functie, standaard `Lydia` bevatten.

@@ -2584,21 +2586,21 @@ In dit geval zal de waarde van het argument `name`, als we geen waarde meegeven ###### 82. Wat is de uitkomst? ```javascript -var status = "😎" +var status = "😎"; setTimeout(() => { - const status = "😍" + const status = "😍"; const data = { status: "🥑", getStatus() { - return this.status - } - } + return this.status; + }, + }; - console.log(data.getStatus()) - console.log(data.getStatus.call(this)) -}, 0) + console.log(data.getStatus()); + console.log(data.getStatus.call(this)); +}, 0); ``` - A: `"🥑"` en `"😍"` @@ -2625,13 +2627,13 @@ Met de `call` methode kunnen we het object veranderen waarnaar het keyword `this ```javascript const person = { name: "Lydia", - age: 21 -} + age: 21, +}; -let city = person.city -city = "Amsterdam" +let city = person.city; +city = "Amsterdam"; -console.log(person) +console.log(person); ``` - A: `{ name: "Lydia", age: 21 }` @@ -2662,15 +2664,15 @@ Wanneer we het object `person` loggen, wordt het onaangepaste object gelogd. ```javascript function checkAge(age) { if (age < 18) { - const message = "Sorry, you're too young." + const message = "Sorry, you're too young."; } else { - const message = "Yay! You're old enough!" + const message = "Yay! You're old enough!"; } - return message + return message; } -console.log(checkAge(21)) +console.log(checkAge(21)); ``` - A: `"Sorry, you're too young."` @@ -2693,9 +2695,9 @@ Variabelen gedeclareerd met de keywords `const` en `let` zijn _block-scoped_. Ee ###### 85. Welke informatie zal worden gelogd? ```javascript -fetch('https://www.website.com/api/user/1') - .then(res => res.json()) - .then(res => console.log(res)) +fetch("https://www.website.com/api/user/1") + .then((res) => res.json()) + .then((res) => console.log(res)); ``` - A: Het resultaat van de `fetch` methode. @@ -2735,7 +2737,7 @@ function getName(name) { Met `!!name` stellen we vast of de waarde van `name` truthy of falsy is. Als `name` truthy is, dit is wat we willen testen, zal `!name` `false` teruggeven. `!false` (wat `!!name` feitelijk is) geeft `true` terug. -Wanneer we `hasName` vullen met `name`, vullen we het met dat wat we meegeven aan de `getName` functie, niet de boolean waarde `true`. +Wanneer we `hasName` vullen met `name`, vullen we het met dat wat we meegeven aan de `getName` functie, niet de boolean waarde `true`. `new Boolean(true)` geeft een object wrapper terug, niet de boolean waarde zelf. @@ -2749,7 +2751,7 @@ Wanneer we `hasName` vullen met `name`, vullen we het met dat wat we meegeven aa ###### 87. Wat is de uitkomst? ```javascript -console.log("I want pizza"[0]) +console.log("I want pizza"[0]); ``` - A: `"""` @@ -2775,10 +2777,10 @@ Let op dat deze methode niet ondersteund wordt in IE7 en daaronder. In dat geval ```javascript function sum(num1, num2 = num1) { - console.log(num1 + num2) + console.log(num1 + num2); } -sum(10) +sum(10); ``` - A: `NaN` @@ -2793,7 +2795,7 @@ sum(10) Je kunt een parameters standaard waarde gelijk zetten aan een andere parameter van diezelfde functie, zolang deze definieerd is _voor_ de parameter met een standaard waarde. We geen de waarde `10` mee aan de `sum` functie. Als de `sum` functie maar één argument meekrijgt betekent dit dat de waarde van `num2` gevuld wordt met de waarde van `num1`. `10` in dit geval. De standaard waarde van `num2` is de waarde van `num1`, wat `10` is. `num1 + num2` geeft `20` terug. -Als je probeert de standaard waarde van een parameter te vullen met de waarde van een parameter welke gedefinieerd is _na_ de standaard parameter, dan is de parameter nog niet geïnitialiseerd en wordt er een error gegooid. +Als je probeert de standaard waarde van een parameter te vullen met de waarde van een parameter welke gedefinieerd is _na_ de standaard parameter, dan is de parameter nog niet geïnitialiseerd en wordt er een error gegooid.

@@ -2803,14 +2805,14 @@ Als je probeert de standaard waarde van een parameter te vullen met de waarde va ###### 89. Wat is de uitkomst? ```javascript -// module.js -export default () => "Hello world" -export const name = "Lydia" +// module.js +export default () => "Hello world"; +export const name = "Lydia"; -// index.js -import * as data from "./module" +// index.js +import * as data from "./module"; -console.log(data) +console.log(data); ``` - A: `{ default: function default(), name: "Lydia" }` @@ -2822,6 +2824,7 @@ console.log(data)

#### Antwoord: A + Met de `import * as name` syntax importeren we _alle exports_ van `module.js` bestand in het bestand `index.js` als een nieuw object met de naam `data`. In het bestand `module.js` zijn er twee exports: de standaard export en de benoemde export. De standaard export is een functie dat de string `"Hello world"` teruggeeft, en de benoemde export is de variabele `name` wat de waarde van de string `"Lydia"` bevat. Het object `data` bevat een propertie `default` voor de standaard export. Andere properties hebben de naam van de benoemde exports en hun corresponderende waarden. @@ -2836,12 +2839,12 @@ Het object `data` bevat een propertie `default` voor de standaard export. Andere ```javascript class Person { constructor(name) { - this.name = name + this.name = name; } } -const member = new Person("John") -console.log(typeof member) +const member = new Person("John"); +console.log(typeof member); ``` - A: `"class"` @@ -2858,7 +2861,7 @@ Classes zijn een syntactisch sausje voor functie constructors. Het equivalent va ```javascript function Person() { - this.name = name + this.name = name; } ``` @@ -2872,9 +2875,9 @@ Het aanroepen van de functie contructor met `new` resulteert in het creëeren va ###### 91. Wat is de uitkomst? ```javascript -let newList = [1, 2, 3].push(4) +let newList = [1, 2, 3].push(4); -console.log(newList.push(5)) +console.log(newList.push(5)); ``` - A: `[1, 2, 3, 4, 5]` @@ -2900,17 +2903,18 @@ Dan gebruiken we de `.push` methode op `newList`. Omdat `newList` nu de numeriek ```javascript function giveLydiaPizza() { - return "Here is pizza!" + return "Here is pizza!"; } -const giveLydiaChocolate = () => "Here's chocolate... now go hit the gym already." +const giveLydiaChocolate = () => + "Here's chocolate... now go hit the gym already."; -console.log(giveLydiaPizza.prototype) -console.log(giveLydiaChocolate.prototype) +console.log(giveLydiaPizza.prototype); +console.log(giveLydiaChocolate.prototype); ``` -- A: `{ constructor: ...}` `{ constructor: ...}` -- B: `{}` `{ constructor: ...}` +- A: `{ constructor: ...}` `{ constructor: ...}` +- B: `{}` `{ constructor: ...}` - C: `{ constructor: ...}` `{}` - D: `{ constructor: ...}` `undefined` @@ -2931,16 +2935,16 @@ Reguliere functies zoals de `giveLydiaPizza` functie hebben een `prototype` prop ```javascript const person = { name: "Lydia", - age: 21 -} + age: 21, +}; for (const [x, y] of Object.entries(person)) { - console.log(x, y) + console.log(x, y); } ``` - A: `name` `Lydia` en `age` `21` -- B: `["name", "Lydia"]` en `["age", 21]` +- B: `["name", "Lydia"]` en `["age", 21]` - C: `["name", "age"]` en `undefined` - D: `Error` @@ -2951,11 +2955,11 @@ for (const [x, y] of Object.entries(person)) { `Object.entries(person)` retourneert een array van geneste arrays, welke de keys en objecten bevat: -`[ [ 'name', 'Lydia' ], [ 'age', 21 ] ]` +`[ [ 'name', 'Lydia' ], [ 'age', 21 ] ]` Gebruikmakend van de `for-of` loop kunnen we itereren over elk element in de array, de subarrays in dit geval. We kunnen de subarrays direct destructureren door `const [x, y]` te gebruiken. `x` is gelijk aan het eerste element in de subarray, `y` is gelijk aan het tweede element in de subarray. -De eerste subarray wat wordt gelogd is `[ "name", "Lydia" ]`, waarbij `x` gelijk is aan `"name"` en `y` gelijk is aan `"Lydia"`. +De eerste subarray wat wordt gelogd is `[ "name", "Lydia" ]`, waarbij `x` gelijk is aan `"name"` en `y` gelijk is aan `"Lydia"`. De tweede subarray wat wordt gelogd is `[ "age", "21" ]`, waarbij `x` gelijk is aan `"age"` en `y` gelijk is aan `"21"`.

@@ -2974,7 +2978,7 @@ getItems(["banana", "apple"], "pear", "orange") ``` - A: `["banana", "apple", "pear", "orange"]` -- B: `[["banana", "apple"], "pear", "orange"]` +- B: `[["banana", "apple"], "pear", "orange"]` - C: `["banana", "apple", ["pear"], "orange"]` - D: `SyntaxError` @@ -2987,10 +2991,10 @@ getItems(["banana", "apple"], "pear", "orange") ```javascript function getItems(fruitList, favoriteFruit, ...args) { - return [...fruitList, ...args, favoriteFruit] + return [...fruitList, ...args, favoriteFruit]; } -getItems(["banana", "apple"], "pear", "orange") +getItems(["banana", "apple"], "pear", "orange"); ``` Het bovenstaande voorbeeld werkt. Dit geeft de array `[ 'banana', 'apple', 'orange', 'pear' ]` terug. @@ -3004,17 +3008,14 @@ Het bovenstaande voorbeeld werkt. Dit geeft de array `[ 'banana', 'apple', 'oran ```javascript function nums(a, b) { - if - (a > b) - console.log('a is bigger') - else - console.log('b is bigger') - return - a + b + if (a > b) console.log("a is bigger"); + else console.log("b is bigger"); + return; + a + b; } -console.log(nums(4, 2)) -console.log(nums(1, 2)) +console.log(nums(4, 2)); +console.log(nums(1, 2)); ``` - A: `a is bigger`, `6` en `b is bigger`, `3` @@ -3032,8 +3033,8 @@ In JavaScript _hoeven_ we geen puntkomma's te schrijven, alhoewel de JavaScript Hier schreven we een `return` statement en op de _nieuwe regel_ `a + b`. Maar omdat het een nieuwe regel betreft weet de engine niet wat we eigenlijk wilde retourneren. In plaats daarvan wordt er na `return` automatisch een puntkomma toegevoegd. Je kunt dit zien als: ```javascript - return; - a + b +return; +a + b; ``` Dat betekent dat `a + b` nooit bereikt zal worden, omdat de functie stopt na het keyword `return`. Als er geen waarde wordt geretourneerd, zoals nu, zal de functie `undefined` teruggeven. Let op dat er geen automatisch insertion plaatsvindt na `if/else` statements! @@ -3048,18 +3049,18 @@ Dat betekent dat `a + b` nooit bereikt zal worden, omdat de functie stopt na het ```javascript class Person { constructor() { - this.name = "Lydia" + this.name = "Lydia"; } } Person = class AnotherPerson { constructor() { - this.name = "Sarah" + this.name = "Sarah"; } -} +}; -const member = new Person() -console.log(member.name) +const member = new Person(); +console.log(member.name); ``` - A: `"Lydia"` @@ -3083,11 +3084,11 @@ We kunnen classes gelijk zetten tot andere classes/functie constructors. In dit ```javascript const info = { - [Symbol('a')]: 'b' -} + [Symbol("a")]: "b", +}; -console.log(info) -console.log(Object.keys(info)) +console.log(info); +console.log(Object.keys(info)); ``` - A: `{Symbol('a'): 'b'}` en `["{Symbol('a')"]` @@ -3134,13 +3135,13 @@ console.log(getUser(user)) De `getList` functie ontvangt een array als argument. Tussen de haakjes van de `getList` functie destructureren we deze array direct. Je kunt het zien als: - `[x, ...y] = [1, 2, 3, 4]` +`[x, ...y] = [1, 2, 3, 4]` Met de rest parameter `...y` stoppen we alle "overgebleven" argumenten in een array. De overgebleven argumenten zijn in dit geval `2`, `3` en `4`. De waarde van `y` is een array die alle rest parameters bevat. De waarde van `x` is gelijk aan `1` in dit geval, dus wanneer we `[x, y]` loggen wordt `[1, [2, 3, 4]]` gelogd. - + De `getUser` functie ontvangt een object. Met arrow functies _hoeven_ we geen accolades te gebruiken als we maar één waarde willen retourneren. Echter, als je een _object_ wilt retourneren in een arraow functie zal je het tussen haakjes moeten schrijven. Anders zal er geen waarde geretourneerd worden! De volgende functie zal wel een object geretourneerd hebben: -```const getUser = user => ({ name: user.name, age: user.age })``` +`const getUser = user => ({ name: user.name, age: user.age })` Omdat er geen waarde geretourneerd wordt in dit geval zal de functie `undefined` retourneren. @@ -3152,9 +3153,9 @@ Omdat er geen waarde geretourneerd wordt in dit geval zal de functie `undefined` ###### 99. Wat is de uitkomst? ```javascript -const name = "Lydia" +const name = "Lydia"; -console.log(name()) +console.log(name()); ``` - A: `SyntaxError` @@ -3184,8 +3185,8 @@ ReferenceErrors worden gegooid wanneer JavaScript niet in staat is een referenti ```javascript // 🎉✨ This is my 100th question! ✨🎉 -const output = `${[] && 'Im'}possible! -You should${'' && `n't`} see a therapist after so much JavaScript lol` +const output = `${[] && "Im"}possible! +You should${"" && `n't`} see a therapist after so much JavaScript lol`; ``` - A: `possible! You should see a therapist after so much JavaScript lol` @@ -3210,11 +3211,11 @@ You should${'' && `n't`} see a therapist after so much JavaScript lol` ###### 101. Wat is de waarde van output? ```javascript -const one = (false || {} || null) -const two = (null || false || "") -const three = ([] || 0 || true) +const one = false || {} || null; +const two = null || false || ""; +const three = [] || 0 || true; -console.log(one, two, three) +console.log(one, two, three); ``` - A: `false` `null` `[]` @@ -3243,20 +3244,20 @@ Met de `||` (or) operator kunnen we de eerste truthy waarde retourneren. Als all ###### 102. Wat is de waarde van output? ```javascript -const myPromise = () => Promise.resolve('I have resolved!') +const myPromise = () => Promise.resolve("I have resolved!"); function firstFunction() { - myPromise().then(res => console.log(res)) - console.log('second') + myPromise().then((res) => console.log(res)); + console.log("second"); } async function secondFunction() { - console.log(await myPromise()) - console.log('second') + console.log(await myPromise()); + console.log("second"); } -firstFunction() -secondFunction() +firstFunction(); +secondFunction(); ``` - A: `I have resolved!`, `second` en `I have resolved!`, `second` @@ -3287,14 +3288,14 @@ Dit betekent dat het wacht tot de `myPromise` is opgelost met de waarde `I have ###### 103. Wat is de waarde van output? ```javascript -const set = new Set() +const set = new Set(); -set.add(1) -set.add("Lydia") -set.add({ name: "Lydia" }) +set.add(1); +set.add("Lydia"); +set.add({ name: "Lydia" }); for (let item of set) { - console.log(item + 2) + console.log(item + 2); } ``` @@ -3324,7 +3325,7 @@ Echter, de tweede is de string `"Lydia"`. `"Lydia"` is een string en `2` is een ###### 104. Wat is de waarde? ```javascript -Promise.resolve(5) +Promise.resolve(5); ``` - A: `5` @@ -3351,15 +3352,15 @@ In dit geval geven we alleen de numerieke waarde `5` mee. Het geeft de opgeloste ```javascript function compareMembers(person1, person2 = person) { if (person1 !== person2) { - console.log("Not the same!") + console.log("Not the same!"); } else { - console.log("They are the same!") + console.log("They are the same!"); } } -const person = { name: "Lydia" } +const person = { name: "Lydia" }; -compareMembers(person) +compareMembers(person); ``` - A: `Not the same!` @@ -3394,11 +3395,11 @@ const colorConfig = { green: true, black: true, yellow: false, -} +}; -const colors = ["pink", "red", "blue"] +const colors = ["pink", "red", "blue"]; -console.log(colorConfig.colors[1]) +console.log(colorConfig.colors[1]); ``` - A: `true` @@ -3425,7 +3426,7 @@ JavaScript interpreteert (of beter gezegd unboxed) statements. Wanneer we blokha ###### 107. Wat is de waarde? ```javascript -console.log('❤️' === '❤️') +console.log("❤️" === "❤️"); ``` - A: `true` @@ -3446,19 +3447,19 @@ Onder de motorkap zijn emojis unicodes. De unicodes voor het hart zijn `"U+2764 ###### 108. Welke van onderstaande methoden passen de originele array aan? ```javascript -const emojis = ['✨', '🥑', '😍'] +const emojis = ["✨", "🥑", "😍"]; -emojis.map(x => x + '✨') -emojis.filter(x => x !== '🥑') -emojis.find(x => x !== '🥑') -emojis.reduce((acc, cur) => acc + '✨') -emojis.slice(1, 2, '✨') -emojis.splice(1, 2, '✨') +emojis.map((x) => x + "✨"); +emojis.filter((x) => x !== "🥑"); +emojis.find((x) => x !== "🥑"); +emojis.reduce((acc, cur) => acc + "✨"); +emojis.slice(1, 2, "✨"); +emojis.splice(1, 2, "✨"); ``` - A: `All of them` - B: `map` `reduce` `slice` `splice` -- C: `map` `slice` `splice` +- C: `map` `slice` `splice` - D: `splice`
Antwoord @@ -3478,17 +3479,17 @@ Met de `splice` methode passen we de originele array aan door elementen te verwi ###### 109. Wat is de uitkomst? ```javascript -const food = ['🍕', '🍫', '🥑', '🍔'] -const info = { favoriteFood: food[0] } +const food = ["🍕", "🍫", "🥑", "🍔"]; +const info = { favoriteFood: food[0] }; -info.favoriteFood = '🍝' +info.favoriteFood = "🍝"; -console.log(food) +console.log(food); ``` - A: `['🍕', '🍫', '🥑', '🍔']` - B: `['🍝', '🍫', '🥑', '🍔']` -- C: `['🍝', '🍕', '🍫', '🥑', '🍔']` +- C: `['🍝', '🍕', '🍫', '🥑', '🍔']` - D: `ReferenceError`
Antwoord @@ -3510,7 +3511,7 @@ Daarna veranderen we de waarde van de property `favoriteFood` op het object `inf ###### 110. Wat doet onderstaande methode? ```javascript -JSON.parse() +JSON.parse(); ``` - A: Ontleedt JSON naar een JavaScript waarde @@ -3527,16 +3528,16 @@ Met de `JSON.parse()` methode kunnen we een JSON string parsen naar een JavaScri ```javascript // Stringifying een nummer naar valide JSON, daarna de JSON string parsen naar een JavaScript waarde: -const jsonNumber = JSON.stringify(4) // '4' -JSON.parse(jsonNumber) // 4 +const jsonNumber = JSON.stringify(4); // '4' +JSON.parse(jsonNumber); // 4 // Stringifying een array waarde naar een valide JSON, daarna de JSON string parsen naar een JavaScript waarde: -const jsonArray = JSON.stringify([1, 2, 3]) // '[1, 2, 3]' -JSON.parse(jsonArray) // [1, 2, 3] +const jsonArray = JSON.stringify([1, 2, 3]); // '[1, 2, 3]' +JSON.parse(jsonArray); // [1, 2, 3] // Stringifying een object naar valide JSON, daarna de JSON string parsen naar een JavaScript waarde: -const jsonArray = JSON.stringify({ name: "Lydia" }) // '{"name":"Lydia"}' -JSON.parse(jsonArray) // { name: 'Lydia' } +const jsonArray = JSON.stringify({ name: "Lydia" }); // '{"name":"Lydia"}' +JSON.parse(jsonArray); // { name: 'Lydia' } ```

@@ -3544,17 +3545,17 @@ JSON.parse(jsonArray) // { name: 'Lydia' } --- -###### 111. Wat is de uitkomst? +###### 111. Wat is de uitkomst? ```javascript -let name = 'Lydia' +let name = "Lydia"; function getName() { - console.log(name) - let name = 'Sarah' + console.log(name); + let name = "Sarah"; } -getName() +getName(); ``` - A: Lydia @@ -3574,13 +3575,13 @@ Variabelen gedeclareerd met het keyword `let` (en `const`) worden gehoisted, maa Als we de variabele `name` **niet** niet hadden gedeclareerd binnen de `getName` functie zou de JavaScript engine doorgezocht hebben door de _scope chain_. De bovenliggende scope heeft een variabele `name` met de waarde `Lydia`. In dat geval zou `Lydia` gelogged worden. ```javascript -let name = 'Lydia' +let name = "Lydia"; function getName() { - console.log(name) + console.log(name); } -getName() // Lydia +getName(); // Lydia ```

@@ -3592,18 +3593,18 @@ getName() // Lydia ```javascript function* generatorOne() { - yield ['a', 'b', 'c']; + yield ["a", "b", "c"]; } function* generatorTwo() { - yield* ['a', 'b', 'c']; + yield* ["a", "b", "c"]; } -const one = generatorOne() -const two = generatorTwo() +const one = generatorOne(); +const two = generatorTwo(); -console.log(one.next().value) -console.log(two.next().value) +console.log(one.next().value); +console.log(two.next().value); ``` - A: `a` en `a` @@ -3621,17 +3622,17 @@ Met het keyword `yield` , we `yield` waarden in een generator functie. Met het k In `generatorOne` leveren we de volledige array `['a', 'b', 'c']` op, gebruikmakend van het keyword `yield`. De waarde van de propertie `value` op het object geretourneerd door de `next` methode op `one` (`one.next().value`) is gelijk aan de volledige array `['a', 'b', 'c']`. ```javascript -console.log(one.next().value) // ['a', 'b', 'c'] -console.log(one.next().value) // undefined +console.log(one.next().value); // ['a', 'b', 'c'] +console.log(one.next().value); // undefined ``` In `generatorTwo` gebruiken we het keyword `yield*`. Dit betekent dat de eerste opgeleverde waarde van `two` is gelijk aan de eerste opgeleverde waarde in de iterator. The iterator is de array `['a', 'b', 'c']`. De eerste opgeleverde waarde is `a`, dus de eerste keer dat we `two.next().value` aanroepen wordt `a` geretourneerd. ```javascript -console.log(two.next().value) // 'a' -console.log(two.next().value) // 'b' -console.log(two.next().value) // 'c' -console.log(two.next().value) // undefined +console.log(two.next().value); // 'a' +console.log(two.next().value); // 'b' +console.log(two.next().value); // 'c' +console.log(two.next().value); // undefined ```

@@ -3642,7 +3643,7 @@ console.log(two.next().value) // undefined ###### 113. Wat is de uitkomst? ```javascript -console.log(`${(x => x)('I love')} to program`) +console.log(`${((x) => x)("I love")} to program`); ``` - A: `I love to program` @@ -3667,11 +3668,11 @@ Expressies binnen template literals worden eerste geëvalueerd. Dit betekent dat ```javascript let config = { alert: setInterval(() => { - console.log('Alert!') - }, 1000) -} + console.log("Alert!"); + }, 1000), +}; -config = null +config = null; ``` - A: De `setInterval` callback zal niet worden aangeroepen @@ -3694,17 +3695,17 @@ Normaal als we objecten gelijk maken aan `null` worden deze objecten opgeruimd d ###### 115. Welke methode(n) zal de waarde `'Hello world!'` teruggeven? ```javascript -const myMap = new Map() -const myFunc = () => 'greeting' +const myMap = new Map(); +const myFunc = () => "greeting"; -myMap.set(myFunc, 'Hello world!') +myMap.set(myFunc, "Hello world!"); //1 -myMap.get('greeting') +myMap.get("greeting"); //2 -myMap.get(myFunc) +myMap.get(myFunc); //3 -myMap.get(() => 'greeting') +myMap.get(() => "greeting"); ``` - A: 1 @@ -3732,19 +3733,19 @@ Als een **key/value** paar wordt toegevoegd gebruikmakend van de `set` methode z ```javascript const person = { name: "Lydia", - age: 21 -} + age: 21, +}; -const changeAge = (x = { ...person }) => x.age += 1 +const changeAge = (x = { ...person }) => (x.age += 1); const changeAgeAndName = (x = { ...person }) => { - x.age += 1 - x.name = "Sarah" -} + x.age += 1; + x.name = "Sarah"; +}; -changeAge(person) -changeAgeAndName() +changeAge(person); +changeAgeAndName(); -console.log(person) +console.log(person); ``` - A: `{name: "Sarah", age: 22}` @@ -3772,7 +3773,7 @@ Dan roepen we de functie `changeAgeAndName` aan, echter geven we geen parameter ```javascript function sumValues(x, y, z) { - return x + y + z; + return x + y + z; } ``` @@ -3823,15 +3824,15 @@ Met de `+=` operator verhogen we de waarde van `num` met `1`. `num` heeft een in ```javascript const person = { - firstName: "Lydia", - lastName: "Hallie", - pet: { - name: "Mara", - breed: "Dutch Tulip Hound" - }, - getFullName() { - return `${this.firstName} ${this.lastName}`; - } + firstName: "Lydia", + lastName: "Hallie", + pet: { + name: "Mara", + breed: "Dutch Tulip Hound", + }, + getFullName() { + return `${this.firstName} ${this.lastName}`; + }, }; console.log(person.pet?.name); @@ -3854,7 +3855,7 @@ Met de _optional chaining operator_ `?.` hoeven we niet langer expliciet te chec `person.pet?.name`: `person` heeft een propertie genaamd `pet`: `person.pet` is niet _nullish_. Het heeft een propertie genaamd ``name` en retourneerd `Mara`. `person.pet?.family?.name`: `person` heeft een propertie genaamd `pet`: `person.pet` is niet _nullish_. `pet` heeft _geen_ propertie genaamd `family`, `person.pet.family` is _nullish_. De expressie geeft `undefined` terug. -`person.getFullName?.()`: `person` heeft een propertie genaamd `getFullName`: `person.getFullName()` is niet __nullish__ en kan worden aangeroepen, wat `Lydia Hallie` retourneerd. +`person.getFullName?.()`: `person` heeft een propertie genaamd `getFullName`: `person.getFullName()` is niet **nullish** en kan worden aangeroepen, wat `Lydia Hallie` retourneerd. `member.getLastName?.()`: `member` is niet gedefinieerd: `member.getLastName()` is _nullish_. The expressie geeft `undefined` terug.

@@ -3868,9 +3869,9 @@ Met de _optional chaining operator_ `?.` hoeven we niet langer expliciet te chec const groceries = ["banana", "apple", "peanuts"]; if (groceries.indexOf("banana")) { - console.log("We have to buy bananas!"); + console.log("We have to buy bananas!"); } else { - console.log(`We don't have to buy bananas!`); + console.log(`We don't have to buy bananas!`); } ``` @@ -3895,10 +3896,10 @@ We geven de conditie `groceries.indexOf("banana")` mee aan de if-statement. `gro ```javascript const config = { - languages: [], - set language(lang) { - return this.languages.push(lang); - } + languages: [], + set language(lang) { + return this.languages.push(lang); + }, }; console.log(config.language); @@ -3952,9 +3953,9 @@ console.log(!typeof name === "string"); ###### 123. Wat is de uitkomst? ```javascript -const add = x => y => z => { - console.log(x, y, z); - return x + y + z; +const add = (x) => (y) => (z) => { + console.log(x, y, z); + return x + y + z; }; add(4)(5)(6); @@ -3981,16 +3982,16 @@ De `add` functie retourneert een arrow functie, die een arrow functie retourneer ```javascript async function* range(start, end) { - for (let i = start; i <= end; i++) { - yield Promise.resolve(i); - } + for (let i = start; i <= end; i++) { + yield Promise.resolve(i); + } } (async () => { - const gen = range(1, 3); - for await (const item of gen) { - console.log(item); - } + const gen = range(1, 3); + for await (const item of gen) { + console.log(item); + } })(); ``` @@ -4015,7 +4016,7 @@ De generator functie `range` retourneert een async object met promises voor elk ```javascript const myFunc = ({ x, y, z }) => { - console.log(x, y, z); + console.log(x, y, z); }; myFunc(1, 2, 3); @@ -4139,8 +4140,8 @@ Met de `isNaN` methode kun je checken of een waarde die je meegeeft geen numerie const randomValue = 21; function getInfo() { - console.log(typeof randomValue); - const randomValue = "Lydia Hallie"; + console.log(typeof randomValue); + const randomValue = "Lydia Hallie"; } getInfo(); @@ -4169,13 +4170,13 @@ Variables declared with the `const` keyword are not referencable before their in const myPromise = Promise.resolve("Woah some cool data"); (async () => { - try { - console.log(await myPromise); - } catch { - throw new Error(`Oops didn't work`); - } finally { - console.log("Oh finally!"); - } + try { + console.log(await myPromise); + } catch { + throw new Error(`Oops didn't work`); + } finally { + console.log("Oh finally!"); + } })(); ``` @@ -4225,13 +4226,13 @@ Met de `flat` methode kunnen we een nieuwe platgemaakte array maken. De diepte v ```javascript class Counter { - constructor() { - this.count = 0; - } + constructor() { + this.count = 0; + } - increment() { - this.count++; - } + increment() { + this.count++; + } } const counterOne = new Counter(); @@ -4275,16 +4276,16 @@ We roepen `counterTwo.increment()` aan, wat `count` gelijk maakt aan `3`. Als we const myPromise = Promise.resolve(Promise.resolve("Promise!")); function funcOne() { - myPromise.then(res => res).then(res => console.log(res)); - setTimeout(() => console.log("Timeout!", 0)); - console.log("Last line!"); + myPromise.then((res) => res).then((res) => console.log(res)); + setTimeout(() => console.log("Timeout!", 0)); + console.log("Last line!"); } async function funcTwo() { - const res = await myPromise; - console.log(await res); - setTimeout(() => console.log("Timeout!", 0)); - console.log("Last line!"); + const res = await myPromise; + console.log(await res); + setTimeout(() => console.log("Timeout!", 0)); + console.log("Last line!"); } funcOne(); @@ -4301,7 +4302,7 @@ funcTwo(); #### Antwoord: D -Eerst roepen we `funcOne` aan. Op de eerste regel van `funcOne` roepen we de promise `myPromise` aan, wat een _asynchrone_ operatie is. Zolang de JavaScript engine bezig is met het afmaken van de promise wordt de rest van de functie `funcOne` uitgevoerd. De volgende regel is een _asynchrone_ `setTimeout` functie, waarvan de callback functie naar de Web API wordt gestuurd. +Eerst roepen we `funcOne` aan. Op de eerste regel van `funcOne` roepen we de promise `myPromise` aan, wat een _asynchrone_ operatie is. Zolang de JavaScript engine bezig is met het afmaken van de promise wordt de rest van de functie `funcOne` uitgevoerd. De volgende regel is een _asynchrone_ `setTimeout` functie, waarvan de callback functie naar de Web API wordt gestuurd. Zowel de promise als de timeout zijn _asynchrone_ operaties en de functie worden uitgevoerd terwijl de engine bezig is om de promise uit te voeren en de `setTimeout` callback functie af te handelen. Dit betekent dat `Last line!` als eerste wordt gelogd, omdat dit geen _asynchrone_ operatie is. Dit is de laatste regel van `funcOne`. Ondertussen wordt de promise opgelost en `Promise!` wordt gelogd. Echter, omdat we `funcTwo()` aanroepen en de callstack nog niet leeg is kan de callback van de `setTimeout` functie nog niet toegevoegd worden aan de callstack. @@ -4316,12 +4317,12 @@ We komen op de laatste regel van `funcTwo` wat `Last line!` logt naar het consol --- -###### 134. Hoe kunnen we `sum` uit `sum.js` aanroepen in `index.js`?` +###### 134. Hoe kunnen we `sum` uit `sum.js` aanroepen in `index.js`?` ```javascript // sum.js export default function sum(x) { - return x + x; + return x + x; } // index.js @@ -4378,8 +4379,8 @@ We kunnen deze functie aanvoeren door `sum.default` aan te roepen. ```javascript const handler = { - set: () => console.log("Added a new property!"), - get: () => console.log("Accessed a property!") + set: () => console.log("Added a new property!"), + get: () => console.log("Accessed a property!"), }; const person = new Proxy({}, handler); @@ -4429,7 +4430,7 @@ Object.seal(person); #### Antwoord: A -Met `Object.seal` kunnen we voorkomen dat nieuwe properties kunnen worden _toegevoegd_ of bestaande properties worden _verwijderd_. +Met `Object.seal` kunnen we voorkomen dat nieuwe properties kunnen worden _toegevoegd_ of bestaande properties worden _verwijderd_. Echter kunnen van de bestaande properties nog steeds aanpassen. @@ -4442,10 +4443,10 @@ Echter kunnen van de bestaande properties nog steeds aanpassen. ```javascript const person = { - name: "Lydia Hallie", - address: { - street: "100 Main St" - } + name: "Lydia Hallie", + address: { + street: "100 Main St", + }, }; Object.freeze(person); @@ -4473,10 +4474,10 @@ Echter wordt het object enkel _oppervlakkig_ bevroren wat betekent dat alleen _d ###### 138. Wat is de uitkomst? ```javascript -const add = x => x + x; +const add = (x) => x + x; function myFunc(num = 2, value = add(num)) { - console.log(num, value); + console.log(num, value); } myFunc(); @@ -4506,21 +4507,21 @@ Daarna roepen we de functie `myFunc(3)` aan het geven `3` meet als de waarde voo ```javascript class Counter { - #number = 10 + #number = 10; increment() { - this.#number++ + this.#number++; } getNum() { - return this.#number + return this.#number; } } -const counter = new Counter() -counter.increment() +const counter = new Counter(); +counter.increment(); -console.log(counter.#number) +console.log(counter.#number); ``` - A: `10` @@ -4544,20 +4545,20 @@ In ES2020 kunnen we private variabelen toevoegen aan classes door gebruik te mak ```javascript const teams = [ - { name: "Team 1", members: ["Paul", "Lisa"] }, - { name: "Team 2", members: ["Laura", "Tim"] } + { name: "Team 1", members: ["Paul", "Lisa"] }, + { name: "Team 2", members: ["Laura", "Tim"] }, ]; function* getMembers(members) { - for (let i = 0; i < members.length; i++) { - yield members[i]; - } + for (let i = 0; i < members.length; i++) { + yield members[i]; + } } function* getTeams(teams) { - for (let i = 0; i < teams.length; i++) { - // ✨ SOMETHING IS MISSING HERE ✨ - } + for (let i = 0; i < teams.length; i++) { + // ✨ SOMETHING IS MISSING HERE ✨ + } } const obj = getTeams(teams); @@ -4588,13 +4589,13 @@ Als we `yield`, `return yield`, of `return` hadden geschreven zou de gehele gene ```javascript const person = { - name: "Lydia Hallie", - hobbies: ["coding"] + name: "Lydia Hallie", + hobbies: ["coding"], }; function addHobby(hobby, hobbies = person.hobbies) { - hobbies.push(hobby); - return hobbies; + hobbies.push(hobby); + return hobbies; } addHobby("running", []); @@ -4633,16 +4634,16 @@ Na het pushen van `dancing` en `baking` is de waarde van `person.hobbies` gelijk ```javascript class Bird { - constructor() { - console.log("I'm a bird. 🦢"); - } + constructor() { + console.log("I'm a bird. 🦢"); + } } class Flamingo extends Bird { - constructor() { - console.log("I'm pink. 🌸"); - super(); - } + constructor() { + console.log("I'm pink. 🌸"); + super(); + } } const pet = new Flamingo(); diff --git a/pl-PL/README.md b/pl-PL/README.md index 866f4458..ca8e1a3b 100644 --- a/pl-PL/README.md +++ b/pl-PL/README.md @@ -10,10 +10,11 @@ Od podstawowych do zaawansowanych: sprawdź, jak dobrze znasz JavaScript, odświ Nie krępuj się ze mną kontaktować! 😊
Instagram || Twitter || LinkedIn || Blog + -| Śmiało używaj ich w projekcie! 😃 Byłabym _bardzo_ wdzięczna za referencje do tego repozytorium, tworzę pytania i wyjaśnienia (tak, jestem smutna lol) i społeczność bardzo mi pomaga w utrzymaniu i ulepszaniu go! 💪🏼 Dziękuję i baw się dobrze! | -|---| +| Śmiało używaj ich w projekcie! 😃 Byłabym _bardzo_ wdzięczna za referencje do tego repozytorium, tworzę pytania i wyjaśnienia (tak, jestem smutna lol) i społeczność bardzo mi pomaga w utrzymaniu i ulepszaniu go! 💪🏼 Dziękuję i baw się dobrze! | +| ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --- @@ -32,6 +33,7 @@ Nie krępuj się ze mną kontaktować! 😊
- [🇰🇷 한국어](./ko-KR/README-ko_KR.md) - [🇳🇱 Nederlands](./nl-NL/README.md) - [🇧🇷 Português Brasil](./pt-BR/README_pt_BR.md) +- [🇷o Română](../ro-RO/README.ro.md) - [🇷🇺 Русский](./ru-RU/README.md) - [🇽🇰 Shqip](../sq-KS/README_sq_KS.md) - [🇹🇭 ไทย](./th-TH/README-th_TH.md) @@ -52,7 +54,7 @@ Nie krępuj się ze mną kontaktować! 😊
function sayHi() { console.log(name); console.log(age); - var name = 'Lydia'; + var name = "Lydia"; let age = 21; } @@ -148,7 +150,7 @@ Na tym obiekcie nie ma wartości `radius`, co powoduje zwrócenie `NaN` (Not a N ```javascript +true; -!'Lydia'; +!"Lydia"; ``` - A: `1` and `false` @@ -173,11 +175,11 @@ Operator jednoargumentowy plus próbuje przekonwertować operand na liczbę. `tr ```javascript const bird = { - size: 'small', + size: "small", }; const mouse = { - name: 'Mickey', + name: "Mickey", small: true, }; ``` @@ -208,11 +210,11 @@ Jednakże, w przypadku notacji kropkowej, to się nie dzieje. `mouse` nie ma klu ###### 6. Jaki jest wynik? ```javascript -let c = { greeting: 'Hey!' }; +let c = { greeting: "Hey!" }; let d; d = c; -c.greeting = 'Hello'; +c.greeting = "Hello"; console.log(d.greeting); ``` @@ -282,13 +284,13 @@ class Chameleon { return this.newColor; } - constructor({ newColor = 'green' } = {}) { + constructor({ newColor = "green" } = {}) { this.newColor = newColor; } } -const freddie = new Chameleon({ newColor: 'purple' }); -console.log(freddie.colorChange('orange')); +const freddie = new Chameleon({ newColor: "purple" }); +console.log(freddie.colorChange("orange")); ``` - A: `orange` @@ -343,10 +345,10 @@ Aby temu zapobiec, możemy użyć `"use strict"`. Powoduje to, że musisz zadekl ```javascript function bark() { - console.log('Woof!'); + console.log("Woof!"); } -bark.animal = 'dog'; +bark.animal = "dog"; ``` - A: Nothing, this is totally fine! @@ -376,8 +378,8 @@ function Person(firstName, lastName) { this.lastName = lastName; } -const member = new Person('Lydia', 'Hallie'); -Person.getFullName = function() { +const member = new Person("Lydia", "Hallie"); +Person.getFullName = function () { return `${this.firstName} ${this.lastName}`; }; @@ -399,7 +401,7 @@ W JavaScript funkcje są obiektami, więc metoda `getFullName` jest dodawana do Jeśli chcesz, aby metoda była dostępna dla wszystkich instancji obiektów, musisz dodać ją do właściwości prototype: ```js -Person.prototype.getFullName = function() { +Person.prototype.getFullName = function () { return `${this.firstName} ${this.lastName}`; }; ``` @@ -417,8 +419,8 @@ function Person(firstName, lastName) { this.lastName = lastName; } -const lydia = new Person('Lydia', 'Hallie'); -const sarah = Person('Sarah', 'Smith'); +const lydia = new Person("Lydia", "Hallie"); +const sarah = Person("Sarah", "Smith"); console.log(lydia); console.log(sarah); @@ -488,7 +490,7 @@ function sum(a, b) { return a + b; } -sum(1, '2'); +sum(1, "2"); ``` - A: `NaN` @@ -534,7 +536,7 @@ Operator jednoargumentowy **Postfix** `++`: 1. Zwraca wartość (ten zwraca `0`) 2. Zwiększa wartość (liczba wynosi teraz `1`) -Operator jednoargumentowy **Prefix** `++`: +Operator jednoargumentowy **Prefix** `++`: 1. Zwiększa wartość (liczba wynosi teraz `2`) 2. Zwraca wartość (to zwraca `2`) @@ -555,7 +557,7 @@ function getPersonInfo(one, two, three) { console.log(three); } -const person = 'Lydia'; +const person = "Lydia"; const age = 21; getPersonInfo`${person} is ${age} years old`; @@ -582,9 +584,9 @@ W przypadku użycia `template strings`, wartością pierwszego argumentu jest za ```javascript function checkAge(data) { if (data === { age: 18 }) { - console.log('You are an adult!'); + console.log("You are an adult!"); } else if (data == { age: 18 }) { - console.log('You are still an adult.'); + console.log("You are still an adult."); } else { console.log(`Hmm.. You don't have an age I guess`); } @@ -644,7 +646,7 @@ Parametr reszty (`...args`) pozwala nam "zbierać" wszystkie pozostałe argument ```javascript function getAge() { - 'use strict'; + "use strict"; age = 21; console.log(age); } @@ -672,7 +674,7 @@ Dzięki `"use strict"` możesz upewnić się, że przypadkowo nie zadeklarujesz ###### 21. Jaka jest wartość `sum`? ```javascript -const sum = eval('10*10+5'); +const sum = eval("10*10+5"); ``` - A: `105` @@ -695,7 +697,7 @@ const sum = eval('10*10+5'); ###### 22. Jak długo cool_secret jest dostępny? ```javascript -sessionStorage.setItem('cool_secret', 123); +sessionStorage.setItem("cool_secret", 123); ``` - A: Dane nigdy nie zostaną utracone. @@ -748,12 +750,12 @@ Nie można tego zrobić za pomocą `let` lub `const`, ponieważ są one blokowe. ###### 24. Jaki jest wynik? ```javascript -const obj = { 1: 'a', 2: 'b', 3: 'c' }; +const obj = { 1: "a", 2: "b", 3: "c" }; const set = new Set([1, 2, 3, 4, 5]); -obj.hasOwnProperty('1'); +obj.hasOwnProperty("1"); obj.hasOwnProperty(1); -set.has('1'); +set.has("1"); set.has(1); ``` @@ -779,7 +781,7 @@ Nie działa to w ten sam sposób dla zbioru. W zbiorze nie ma klucza `'1'`:`set. ###### 25. Jaki jest wynik? ```javascript -const obj = { a: 'one', b: 'two', a: 'three' }; +const obj = { a: "one", b: "two", a: "three" }; console.log(obj); ``` @@ -848,12 +850,12 @@ Instrukcja `continue` pomija iterację, jeśli określony warunek zwróci `true` ```javascript String.prototype.giveLydiaPizza = () => { - return 'Just give Lydia pizza already!'; + return "Just give Lydia pizza already!"; }; -const name = 'Lydia'; +const name = "Lydia"; -console.log(name.giveLydiaPizza()) +console.log(name.giveLydiaPizza()); ``` - A: `"Just give Lydia pizza already!"` @@ -877,8 +879,8 @@ console.log(name.giveLydiaPizza()) ```javascript const a = {}; -const b = { key: 'b' }; -const c = { key: 'c' }; +const b = { key: "b" }; +const c = { key: "c" }; a[b] = 123; a[c] = 456; @@ -910,9 +912,9 @@ Następnie wyświetlamy w konsoli `a[b]`, co w rzeczywistości jest `a["[obiekt ###### 30. Jaki jest wynik? ```javascript -const foo = () => console.log('First'); -const bar = () => setTimeout(() => console.log('Second')); -const baz = () => console.log('Third'); +const foo = () => console.log("First"); +const bar = () => setTimeout(() => console.log("Second")); +const baz = () => console.log("Third"); bar(); foo(); @@ -965,9 +967,7 @@ W tym miejscu zaczyna działać pętla zdarzeń. **Pętla zdarzeń** patrzy na s ```html
- +
``` @@ -993,9 +993,7 @@ Najgłębiej zagnieżdżony element, który spowodował zdarzenie jest celem zda ```html
-

- Click here! -

+

Click here!

``` @@ -1019,7 +1017,7 @@ Jeśli klikniemy `p`, zobaczymy dwa logi: `p` i `div`. Podczas propagacji zdarze ###### 33. Jaki jest wynik? ```javascript -const person = { name: 'Lydia' }; +const person = { name: "Lydia" }; function sayHi(age) { return `${this.name} is ${age}`; @@ -1069,7 +1067,6 @@ console.log(typeof sayHi()); #### Odpowiedź: B Funkcja `sayHi` zwraca zwróconą wartość natychmiast wywołanego wyrażenia funkcyjnego (IIFE). Ta funkcja zwróciła wartość `0`, która jest typu `"number"`. - FYI: `typeof` może zwrócić następującą listę wartości: `undefined`, `boolean`, `number`, `bigint`, `string`, `symbol`, `function` i `object`. Zauważ, że `typeof null` zwraca `"object"`.

@@ -1082,8 +1079,8 @@ FYI: `typeof` może zwrócić następującą listę wartości: `undefined`, `boo ```javascript 0; new Number(0); -(''); -(' '); +(""); +(" "); new Boolean(false); undefined; ``` @@ -1232,11 +1229,14 @@ To, co odróżnia prymityw od obiektu, to fakt, że prymitywy nie mają żadnych ###### 40. Jaki jest wynik? ```javascript -[[0, 1], [2, 3]].reduce( +[ + [0, 1], + [2, 3], +].reduce( (acc, cur) => { return acc.concat(cur); }, - [1, 2], + [1, 2] ); ``` @@ -1263,7 +1263,7 @@ Następnie `[1, 2, 0, 1]` to `acc`, a `[2, 3]` to `cur`. Łączymy je i otrzymuj ```javascript !!null; -!!''; +!!""; !!1; ``` @@ -1291,7 +1291,7 @@ Następnie `[1, 2, 0, 1]` to `acc`, a `[2, 3]` to `cur`. Łączymy je i otrzymuj ###### 42. Co zwraca metoda `setInterval` w przeglądarce? ```javascript -setInterval(() => console.log('Hi'), 1000); +setInterval(() => console.log("Hi"), 1000); ``` - A: unikalny identyfikator @@ -1314,7 +1314,7 @@ Zwraca unikalny identyfikator. Ten identyfikator może być użyty do wyczyszcze ###### 43. Co to zwróci? ```javascript -[...'Lydia']; +[..."Lydia"]; ``` - A: `["L", "y", "d", "i", "a"]` @@ -1373,14 +1373,14 @@ Następnie ponownie wywołujemy funkcję za pomocą metody `next()`. Kontynuuje ```javascript const firstPromise = new Promise((res, rej) => { - setTimeout(res, 500, 'one'); + setTimeout(res, 500, "one"); }); const secondPromise = new Promise((res, rej) => { - setTimeout(res, 100, 'two'); + setTimeout(res, 100, "two"); }); -Promise.race([firstPromise, secondPromise]).then(res => console.log(res)); +Promise.race([firstPromise, secondPromise]).then((res) => console.log(res)); ``` - A: `"one"` @@ -1403,7 +1403,7 @@ Kiedy przekazujemy wiele 'promise' do metody `Promise.race`, rozwiązuje ona/odr ###### 46. Jaki jest wynik? ```javascript -let person = { name: 'Lydia' }; +let person = { name: "Lydia" }; const members = [person]; person = null; @@ -1443,7 +1443,7 @@ Modyfikujemy tylko wartość zmiennej `person`, a nie pierwszy element w tablicy ```javascript const person = { - name: 'Lydia', + name: "Lydia", age: 21, }; @@ -1472,7 +1472,7 @@ Za pomocą pętli `for-in` możemy iterować po kluczach obiektów, w tym przypa ###### 48. Jaki jest wynik? ```javascript -console.log(3 + 4 + '5'); +console.log(3 + 4 + "5"); ``` - A: `"345"` @@ -1499,7 +1499,7 @@ Asocjatywność operatorów to kolejność, w jakiej kompilator ocenia wyrażeni ###### 49. Jaka jest wartość `num`? ```javascript -const num = parseInt('7*6', 10); +const num = parseInt("7*6", 10); ``` - A: `42` @@ -1524,8 +1524,8 @@ Zwracana jest tylko pierwsza liczba w łańcuchu. W oparciu o _radix_ (drugi arg ###### 50. Jaki jest wynik? ```javascript -[1, 2, 3].map(num => { - if (typeof num === 'number') return; +[1, 2, 3].map((num) => { + if (typeof num === "number") return; return num * 2; }); ``` @@ -1545,4 +1545,4 @@ Podczas mapowania tablicy, wartość `num` jest równa elementowi, nad którym a Nie zwracamy jednak żadnej wartości. Gdy nie zwracamy wartości z funkcji, funkcja zwraca `undefined`. Dla każdego elementu w tablicy wywoływany jest blok funkcji, więc dla każdego elementu zwracamy `undefined`.

-
\ No newline at end of file +
diff --git a/pt-BR/README_pt_BR.md b/pt-BR/README_pt_BR.md index e59c6a6f..a0a0a211 100644 --- a/pt-BR/README_pt_BR.md +++ b/pt-BR/README_pt_BR.md @@ -19,6 +19,7 @@ As respostas estão em seções recolhidas abaixo das questões, basta clicar ne - [🇰🇷 한국어](../ko-KR/README-ko_KR.md) - [🇳🇱 Nederlands](../nl-NL/README.md) - [🇵🇱 Polski](../pl-PL/README.md) +- [🇷o Română](../ro-RO/README.ro.md) - [🇷🇺 Русский](../ru-RU/README.md) - [🇽🇰 Shqip](../sq-KS/README_sq_KS.md) - [🇹🇭 ไทย](../th-TH/README-th_TH.md) @@ -28,7 +29,6 @@ As respostas estão em seções recolhidas abaixo das questões, basta clicar ne - [🇨🇳 简体中文](../zh-CN/README-zh_CN.md) - [🇹🇼 繁體中文](../zh-TW/README_zh-TW.md) - --- ###### 1. Qual o resultado? @@ -101,7 +101,7 @@ const shape = { diameter() { return this.radius * 2; }, - perimeter: () => 2 * Math.PI * this.radius + perimeter: () => 2 * Math.PI * this.radius, }; shape.diameter(); @@ -147,8 +147,9 @@ Não há `radius` fora de shape, então retorna `undefined`. O operador unário `+` tenta converter um operando para um número. `true` é `1`, e `false` é `0`. -A string `'Lydia'` tem valor truthy*. O que estamos realmente perguntando é "Esse valor truthy é falsy?". Isso retorna `false`. -###### *Nota do tradutor: truthy é um termo único ao JavaScript que denota valores que podem ser convertidos em um booleano `True`. Sua contraparte é falsy, que são valores que podem ser convertidos em um booleano `false`. Para fins de consistência, mantenho os termos originais. +A string `'Lydia'` tem valor truthy\*. O que estamos realmente perguntando é "Esse valor truthy é falsy?". Isso retorna `false`. + +###### \*Nota do tradutor: truthy é um termo único ao JavaScript que denota valores que podem ser convertidos em um booleano `True`. Sua contraparte é falsy, que são valores que podem ser convertidos em um booleano `false`. Para fins de consistência, mantenho os termos originais.

@@ -159,12 +160,12 @@ A string `'Lydia'` tem valor truthy*. O que estamos realmente perguntando é "Es ```javascript const bird = { - size: "small" + size: "small", }; const mouse = { name: "Mickey", - small: true + small: true, }; ``` @@ -250,7 +251,7 @@ console.log(b === c); `new Number()` é uma funcção construtura padrão do JavaScript. Ainda que parece com um número, não é realmente um número: Tem um monte de funções extras e é um objeto. -Quando usamos o operador `==`, só conferimos se ambas tem o mesmo valor. Ambas tem o valor de `3`, então retorna `true`. +Quando usamos o operador `==`, só conferimos se ambas tem o mesmo valor. Ambas tem o valor de `3`, então retorna `true`. Contudo, quando usamos o operador `===`, ambos valor e tipo tem de ser o mesmo. E não são: `new Number()` não é um número, é um **objeto**. Ambos retornam `false`. @@ -314,7 +315,7 @@ console.log(greetign); Cria o log do objeto, pois criamos um objeto vazio no objeto global! Quando erramos a digitação de `greeting` como `greetign`, o interpretador do JavaScript viu isso como `global.greetign = {}` (ou `window.greetign = {}` em um navegador). -Para evitar esse comportamento, podemos usar `"use strict"`. Isso garante que você tenha declarado uma variável antes de poder inicializá-la com algum valor. +Para evitar esse comportamento, podemos usar `"use strict"`. Isso garante que você tenha declarado uma variável antes de poder inicializá-la com algum valor.

@@ -359,7 +360,7 @@ function Person(firstName, lastName) { } const member = new Person("Lydia", "Hallie"); -Person.getFullName = function() { +Person.getFullName = function () { return `${this.firstName} ${this.lastName}`; }; @@ -381,7 +382,7 @@ Você não pode adicionar propriedades para um construtor igual aos objetos norm Então nesse caso ```js -Person.prototype.getFullName = function() { +Person.prototype.getFullName = function () { return `${this.firstName} ${this.lastName}`; }; ``` @@ -440,7 +441,8 @@ Afirmamos que `this.firstName` vale `"Sarah"` e `this.lastName` vale `"Smith"`. #### Resposta: D Durate a fase do **capturing**, o evento percorre os elementos pais até chegar no elemento algo. Isso alcança o elemento **target**, e o **bubbling** começa. - ##### *Nota do tradutor: _bubbling_ descreve uma forma específica de propagação de eventos. Em tradução livre é "borbulhar", que indica como os eventos "sobem" a cadeia onde estão aninhados, mas prefiro por manter o original, visto que é o nome dessa forma de propagação. + +##### \*Nota do tradutor: _bubbling_ descreve uma forma específica de propagação de eventos. Em tradução livre é "borbulhar", que indica como os eventos "sobem" a cadeia onde estão aninhados, mas prefiro por manter o original, visto que é o nome dessa forma de propagação. @@ -459,7 +461,7 @@ Durate a fase do **capturing**, o evento percorre os elementos pais até chegar #### Resposta: B -Todos objetos tem protótipos, exceto pelo **base object**. O base object tem acesso à alguns métodos e propriedades, como `.toString`. É o motivo de podermos usar métodos já embutidos no JavaScript! Todos métodos desse tipo já estão embutidos no protótipo. Apesar do JavaScript não encontrar algum método diretamente no seu objeto, ele percorre a cadeia de protótipos até encontrar no base, o que torna acessível para todo objeto. +Todos objetos tem protótipos, exceto pelo **base object**. O base object tem acesso à alguns métodos e propriedades, como `.toString`. É o motivo de podermos usar métodos já embutidos no JavaScript! Todos métodos desse tipo já estão embutidos no protótipo. Apesar do JavaScript não encontrar algum método diretamente no seu objeto, ele percorre a cadeia de protótipos até encontrar no base, o que torna acessível para todo objeto.

@@ -514,7 +516,7 @@ console.log(number); #### Resposta: C -O operador unário no **sufixo** `++`: +O operador unário no **sufixo** `++`: 1. Retorna o valor (retorna o valor `0`) 2. Incrementa o valor (numero agora é `1`) @@ -587,7 +589,7 @@ checkAge({ age: 18 }); #### Resposta: C -Quando testamos igualdade, primitivos são comparados por seus _valores_, enquanto objetos são comparados por suas _referências_. O JavaScript confere se os objetos tem a referência para o mesmo local na memória. +Quando testamos igualdade, primitivos são comparados por seus _valores_, enquanto objetos são comparados por suas _referências_. O JavaScript confere se os objetos tem a referência para o mesmo local na memória. Os dois objetos que estamos comparando não são assim: O objeto que passamos como parâmetro faz referência a uma posição na memória diferente daquela que o objeto que usamos para conferir a igualdade. @@ -788,7 +790,7 @@ Se temos duas chaves com o mesmo nome, a última irá substituir a primeira. Ain ###### 26. O contexto global de execução do JavaScript cria duas coisas para você: O objeto global, e a palavra-chave `this`. - A: Verdadeiro -- B: Falso +- B: Falso - C: Depende
Resposta @@ -838,7 +840,7 @@ String.prototype.giveLydiaPizza = () => { const name = "Lydia"; -console.log(name.giveLydiaPizza()) +console.log(name.giveLydiaPizza()); ``` - A: `"Just give Lydia pizza already!"` @@ -950,9 +952,7 @@ A `WebAPI` não pode simplesmente adicionar coisas ao stack sempre que ficam pro ```html
- +
``` @@ -967,7 +967,7 @@ A `WebAPI` não pode simplesmente adicionar coisas ao stack sempre que ficam pro #### Resposta: C -O elemento mais interno no aninhamento que causou o evento é o alvo do evento. Você pode parar o _bubbling_ com `event.stopPropagation`. +O elemento mais interno no aninhamento que causou o evento é o alvo do evento. Você pode parar o _bubbling_ com `event.stopPropagation`.

@@ -978,9 +978,7 @@ O elemento mais interno no aninhamento que causou o evento é o alvo do evento. ```html
-

- Click here! -

+

Click here!

``` @@ -1055,7 +1053,7 @@ typeof sayHi(); A função `sayHi` retorna o valor retornado pela arrow function pois ela é uma IIFE (Immediately Invoked Function Expression ou Expressão de Função Invocada Imediatamente). Essa IIFE retornou `0`, que é do tipo `"number"`. -Para saber mais: Só existem 7 tipos já definidos: `null`, `undefined`, `boolean`, `number`, `string`, `object`, `symbol`, e `bigint`. `"function"` não é um tipo, uma vez que funções são objetos, elas são do tipo `"object"`. +Para saber mais: Só existem 7 tipos já definidos: `null`, `undefined`, `boolean`, `number`, `string`, `object`, `symbol`, e `bigint`. `"function"` não é um tipo, uma vez que funções são objetos, elas são do tipo `"object"`.

@@ -1215,7 +1213,10 @@ O que diferencia um primitivo de um objeto é que primitivos não possuem métod ###### 40. Qual o resultado? ```javascript -[[0, 1], [2, 3]].reduce( +[ + [0, 1], + [2, 3], +].reduce( (acc, cur) => { return acc.concat(cur); }, @@ -1278,7 +1279,7 @@ setInterval(() => console.log("Hi"), 1000); ``` - A: um id único -- B: a quantidade de millisegundos especificada +- B: a quantidade de millisegundos especificada - C: a função passada - D: `undefined` @@ -1362,7 +1363,7 @@ const secondPromise = new Promise((res, rej) => { setTimeout(res, 100, "two"); }); -Promise.race([firstPromise, secondPromise]).then(res => console.log(res)); +Promise.race([firstPromise, secondPromise]).then((res) => console.log(res)); ``` - A: `"one"` @@ -1426,7 +1427,7 @@ Estamos apenas modificando o valor da variável `person`, e não o primeiro elem ```javascript const person = { name: "Lydia", - age: 21 + age: 21, }; for (const item in person) { @@ -1506,7 +1507,7 @@ Apenas os primeiros números da string é retornado. Baseado no _radix_ (o segun ###### 50. Qual o resultado? ```javascript -[1, 2, 3].map(num => { +[1, 2, 3].map((num) => { if (typeof num === "number") return; return num * 2; }); @@ -1675,7 +1676,7 @@ class Dog { this.name = name; } } -Dog.prototype.bark = function() { +Dog.prototype.bark = function () { console.log(`Woof I am ${this.name}`); }; const pet = new Dog("Mara"); @@ -1850,7 +1851,6 @@ console.log(admin); #### Resposta: B - É possível combinar objetos usando o operador o spread operator `...`. Ele permite criar cópias dos pares de um objeto e adicioná-las a outro objeto. Nesse caso, criamos cópias do objeto `user` e as adicionamos ao objeto `admin`. O objeto `admin` agora contém os pares de chave/valor copiados, o que resulta em `{ admin: true, name: "Lydia", age: 21 }`.

@@ -1878,10 +1878,12 @@ console.log(Object.keys(person));

#### Resposta: B -Com o método `defineProperty`, podemos adicionar novas propriedades a um objeto ou modificar propriedades já existentes. Quando adicionamos uma propriedade a um objeto usando o método `defineProperty`, ela é, por padrão, _não enumerável_. O método`Object.keys` retorna todos os nomes de uma propriedade _enumerável_ de um objeto. Nesse caso, apenas `"name"`. -Propriedades adicionadas usando o método `defineProperty` são imutáveis por padrão. Você pode sobrepor esse comportamento usando as propriedade `writable`, `configurable` e `enumerable`. +Com o método `defineProperty`, podemos adicionar novas propriedades a um objeto ou modificar propriedades já existentes. Quando adicionamos uma propriedade a um objeto usando o método `defineProperty`, ela é, por padrão, _não enumerável_. O método`Object.keys` retorna todos os nomes de uma propriedade _enumerável_ de um objeto. Nesse caso, apenas `"name"`. + +Propriedades adicionadas usando o método `defineProperty` são imutáveis por padrão. Você pode sobrepor esse comportamento usando as propriedade `writable`, `configurable` e `enumerable`. Assim, o método `defineProperty` dá a você muito mais controle sobre as propriedades que você está adicionando a um objeto. +

@@ -1893,7 +1895,7 @@ Assim, o método `defineProperty` dá a você muito mais controle sobre as propr const settings = { username: "lydiahallie", level: 19, - health: 90 + health: 90, }; const data = JSON.stringify(settings, ["level", "health"]); @@ -1915,17 +1917,19 @@ O segundo argumento de `JSON.stringify` é o _substituo_. O substituto pode ser Se o substituto (replacer) for um _array_, apenas os nomes de propriedades incluídos no array serão adicionados à string JSON. Nesse caso, apenas as propriedades com os nomes `"level"` ed `"health"` são incluída, `"username"` é excluída. `data` agora é igual a `"{"level":19, "health":90}"`. Se o substituto (replacer) for uma _função_, essa função é chamada em c ada propriedade no objeto que está sendo "Stringfied". O valor retornado dessa função será o valor da propriedade quanto adicionado à string JSON. Se o valor for `undefined`, essa propriedade é excluída da string JSON. +

--- + ###### 63. Qual o resultado? ```javascript let num = 10; const increaseNumber = () => num++; -const increasePassedNumber = number => number++; +const increasePassedNumber = (number) => number++; const num1 = increaseNumber(); const num2 = increasePassedNumber(num1); @@ -1952,6 +1956,7 @@ O operador unário `++` primeiro _retorna_ o valor do operando, depois _incremen --- + ###### 64. Qual o resultado? ```javascript @@ -1989,6 +1994,7 @@ Na quarta vez, passamos o objeto `value` novamente. `x.number` foi modificado an --- + ###### 65. Qual o resultado? ```javascript @@ -2074,16 +2080,17 @@ A classe `Labrador` recebe dois argumentos, `name`, pois estende `Dog`, e `size` --- + ###### 67. Qual o resultado? ```javascript // index.js -console.log('running index.js'); -import { sum } from './sum.js'; +console.log("running index.js"); +import { sum } from "./sum.js"; console.log(sum(1, 2)); // sum.js -console.log('running sum.js'); +console.log("running sum.js"); export const sum = (a, b) => a + b; ``` @@ -2105,12 +2112,13 @@ Esta é uma diferença entre `require()` no CommonJS e `import`! Com `require()` --- + ###### 68. Qual o resultado? ```javascript console.log(Number(2) === Number(2)); console.log(Boolean(false) === Boolean(false)); -console.log(Symbol('foo') === Symbol('foo')); +console.log(Symbol("foo") === Symbol("foo")); ``` - A: `true`, `true`, `false` @@ -2129,10 +2137,11 @@ Todo símbolo (Symbol) é totalmente único. O objetivo do argumento passado ao --- + ###### 69. Qual o resultado? ```javascript -const name = 'Lydia Hallie'; +const name = "Lydia Hallie"; console.log(name.padStart(13)); console.log(name.padStart(2)); ``` @@ -2155,10 +2164,11 @@ Se o argumento passado para o método `padStart` for menor que o comprimento da --- + ###### 70. Qual o resultado? ```javascript -console.log('🥑' + '💻'); +console.log("🥑" + "💻"); ``` - A: `"🥑💻"` @@ -2182,11 +2192,11 @@ Com o operador `+`, você pode concatenar seqüências de caracteres (strings). ```javascript function* iniciarJogo() { - const resposta = yield 'Você ama JavaScript?'; - if (resposta !== 'Sim') { + const resposta = yield "Você ama JavaScript?"; + if (resposta !== "Sim") { return "Uau... Acho que entramos aqui"; } - return 'O JavaScript também ama você ❤️'; + return "O JavaScript também ama você ❤️"; } const jogo = iniciarJogo(); @@ -2249,11 +2259,12 @@ Neste caso, a string é `Hello\nworld`, que é registrada. --- + ###### 73. Qual o resultado? ```javascript async function getData() { - return await Promise.resolve('I made it!'); + return await Promise.resolve("I made it!"); } const data = getData(); @@ -2282,6 +2293,7 @@ Isso teria registrado `"Consegui!"` --- + ###### 74. Qual o resultado? ```javascript @@ -2289,7 +2301,7 @@ function addToList(item, list) { return list.push(item); } -const result = addToList('apple', ['banana']); +const result = addToList("apple", ["banana"]); console.log(result); ``` @@ -2349,7 +2361,7 @@ Como `shape` está congelado, e como o valor de `x` não é um objeto, não pode ###### 76.Qual o resultado? ```javascript -const { name: myName } = { name: 'Lydia' }; +const { name: myName } = { name: "Lydia" }; console.log(name); ``` @@ -2405,7 +2417,7 @@ A função `sum` sempre retorna o mesmo resultado. Se passarmos `1` e` 2`, ele _ ```javascript const add = () => { const cache = {}; - return num => { + return (num) => { if (num in cache) { return `From cache! ${cache[num]}`; } else { @@ -2436,7 +2448,7 @@ A função `add` é uma função _memoized_ (memorizada). Com a memorização, p Se chamarmos a função `addFunction` novamente com o mesmo argumento, ela primeiro verifica se já obteve esse valor em seu cache. Se for o caso, o valor dos caches será retornado, o que economiza tempo de execução. Caso contrário, se não estiver armazenado em cache, ele calculará o valor e o armazenará posteriormente. -Chamamos a função `addFunction` três vezes com o mesmo valor: na primeira chamada, o valor da função quando `num` é igual a `10` ainda não é armazenado em cache. A condição da instrução if `num in cache` retorna `false`, e o bloco else é executado: `Calculated! 20` é registrado e o valor do resultado é adicionado ao objeto de cache. `cache` agora se parece com` {10:20} `. +Chamamos a função `addFunction` três vezes com o mesmo valor: na primeira chamada, o valor da função quando `num` é igual a `10` ainda não é armazenado em cache. A condição da instrução if `num in cache` retorna `false`, e o bloco else é executado: `Calculated! 20` é registrado e o valor do resultado é adicionado ao objeto de cache. `cache` agora se parece com`{10:20}`. Na segunda vez, o objeto `cache` contém o valor que é retornado para `10`. A condição da instrução if `num in cache` retorna `true`, e `'From cache! 20'` é registrado. @@ -2450,7 +2462,7 @@ Na terceira vez, passamos `5 * 2` para a função que é avaliada como `10`. O o ###### 79. Qual o resultado? ```javascript -const myLifeSummedUp = ['☕', '💻', '🍷', '🍫']; +const myLifeSummedUp = ["☕", "💻", "🍷", "🍫"]; for (let item in myLifeSummedUp) { console.log(item); @@ -2475,7 +2487,7 @@ Com um loop _for-in_, podemos iterar sobre propriedades **enumeráveis​​**. `{0:" ☕ ", 1:" 💻 ", 2:" 🍷 ", 3:" 🍫 "}` -Onde as chaves são as propriedades enumeráveis. `0`` 1` `2`` 3` são registrados. +Onde as chaves são as propriedades enumeráveis. ` 0`` 1 ` ` 2`` 3 ` são registrados. Com um loop _for-of_, podemos iterar sobre **iteráveis**. Um array é um iterável. Quando iteramos sobre o array, a variável "item" é igual ao elemento sobre o qual está iterando no momento, `" ☕ "` `" 💻 "` `" 🍷 "` `" 🍫 "` são registrados. @@ -2508,4 +2520,4 @@ O elemento será igual ao valor retornado. `1 + 2` retorna` 3`, `1 * 2` retorna`

---- \ No newline at end of file +--- diff --git a/ro-RO/README.ro.md b/ro-RO/README.ro.md new file mode 100644 index 00000000..3205d61c --- /dev/null +++ b/ro-RO/README.ro.md @@ -0,0 +1,49 @@ +
+ +

Întrebări JavaScript

+ +--- + +Postez întrebări JavaScript cu opțiuni multiple pe [Instagram](https://www.instagram.com/theavocoder) **stories**, pe care le voi posta și aici! Ultima actualizare: 12 Iunie + +De la nivel de bază la avansat: testează cât de bine cunoști JavaScript, reîmprospătează-ți puțin cunoștințele sau pregătește-te pentru interviul tău de codare! :muscle: :rocket: Actualizez acest depozit în mod regulat cu întrebări noi. Am adăugat răspunsurile în **secțiunile restrânse** de sub întrebări, pur și simplu dă clic pe ele pentru a le extinde. Este doar pentru distracție, mult noroc! :heart: + +Nu ezita să mă contactezi! 😊
+Instagram || Twitter || LinkedIn || Blog + +
+ +| Simte-te liber să le folosești într-un proiect! 😃 Aș aprecia _cu adevărat_ o referință la acest depozit, eu creez întrebările și explicațiile (da, sunt tristă lol) și comunitatea mă ajută foarte mult să îl mențin și să îl îmbunătățesc! 💪🏼 Mulțumesc și distracție plăcută! | +| -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | + +--- + +
Vezi 20 de traduceri disponibile 🇸🇦🇪🇬🇧🇦🇩🇪🇪🇸🇫🇷🇮🇩🇯🇵🇰🇷🇳🇱🇧🇷🇷🇺🇹🇭🇹🇷🇺🇦🇻🇳🇨🇳🇹🇼🇽🇰 +

+ +- [🇸🇦 العربية](./ar-AR/README_AR.md) +- [🇪🇬 اللغة العامية](./ar-EG/README_ar-EG.md) +- [🇧🇦 Bosanski](./bs-BS/README-bs_BS.md) +- [🇩🇪 Deutsch](./de-DE/README.md) +- [🇪🇸 Español](./es-ES/README-ES.md) +- [🇫🇷 Français](./fr-FR/README_fr-FR.md) +- [🇮🇩 Indonesia](./id-ID/README.md) +- [🇮🇹 Italiano](./it-IT/README.md) +- [🇯🇵 日本語](./ja-JA/README-ja_JA.md) +- [🇰🇷 한국어](./ko-KR/README-ko_KR.md) +- [🇳🇱 Nederlands](./nl-NL/README.md) +- [🇵🇱 Polski](./pl-PL/README.md) +- [🇧🇷 Português Brasil](./pt-BR/README_pt_BR.md) +- [🇷🇺 Русский](./ru-RU/README.md) +- [🇽🇰 Shqip](./sq-KS/README_sq_KS.md) +- [🇹🇭 ไทย](./th-TH/README-th_TH.md) +- [🇹🇷 Türkçe](./tr-TR/README-tr_TR.md) +- [🇺🇦 Українська мова](./uk-UA/README.md) +- [🇻🇳 Tiếng Việt](./vi-VI/README-vi.md) +- [🇨🇳 简体中文](./zh-CN/README-zh_CN.md) +- [🇹🇼 繁體中文](./zh-TW/README_zh-TW.md) + +

+
+ +--- diff --git a/ru-RU/README.md b/ru-RU/README.md index 17a083ab..35f9e86f 100644 --- a/ru-RU/README.md +++ b/ru-RU/README.md @@ -10,10 +10,11 @@ Не стесняйтесь обращаться ко мне (Lydia Hallie)! 😊
Instagram || Twitter || LinkedIn || Blog + | Не стесняйтесь использовать эти примеры в проектах! 😃 Я (Lydia Hallie) была бы _действительно_ признателена за ссылку на этот репозиторий. Я добавляю вопросы и объяснения, и сообщество очень помогает мне поддерживать и улучшать все это! 💪🏼 Спасибо и приятного просмотра! | -|---| +| ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --- @@ -33,6 +34,7 @@ - [🇳🇱 Nederlands](../nl-NL/README.md) - [🇵🇱 Polski](../pl-PL/README.md) - [🇧🇷 Português Brasil](../pt-BR/README_pt_BR.md) +- [🇷o Română](../ro-RO/README.ro.md) - [🇬🇧 English](../README.md) - [🇽🇰 Shqip](../sq-KS/README_sq_KS.md) - [🇹🇭 ไทย](../th-TH/README-th_TH.md) @@ -117,7 +119,7 @@ const shape = { diameter() { return this.radius * 2; }, - perimeter: () => 2 * Math.PI * this.radius + perimeter: () => 2 * Math.PI * this.radius, }; console.log(shape.diameter()); @@ -149,7 +151,7 @@ console.log(shape.perimeter()); ```javascript +true; -!'Lydia'; +!"Lydia"; ``` - A: `1` и `false` @@ -174,12 +176,12 @@ console.log(shape.perimeter()); ```javascript const bird = { - size: 'small' + size: "small", }; const mouse = { - name: 'Mickey', - small: true + name: "Mickey", + small: true, }; ``` @@ -209,11 +211,11 @@ JavaScript интерпретирует (или распаковывает) оп ###### 6. Что будет в консоли? ```javascript -let c = { greeting: 'Hey!' }; +let c = { greeting: "Hey!" }; let d; d = c; -c.greeting = 'Hello'; +c.greeting = "Hello"; console.log(d.greeting); ``` @@ -283,13 +285,13 @@ class Chameleon { return this.newColor; } - constructor({ newColor = 'green' } = {}) { + constructor({ newColor = "green" } = {}) { this.newColor = newColor; } } -const freddie = new Chameleon({ newColor: 'purple' }); -freddie.colorChange('orange'); +const freddie = new Chameleon({ newColor: "purple" }); +freddie.colorChange("orange"); ``` - A: `orange` @@ -344,10 +346,10 @@ console.log(greetign); ```javascript function bark() { - console.log('Woof!'); + console.log("Woof!"); } -bark.animal = 'dog'; +bark.animal = "dog"; ``` - A: Ничего, всё в порядке! @@ -377,10 +379,10 @@ function Person(firstName, lastName) { this.lastName = lastName; } -const member = new Person('Lydia', 'Hallie'); +const member = new Person("Lydia", "Hallie"); Person.getFullName = function () { return `${this.firstName} ${this.lastName}`; -} +}; console.log(member.getFullName()); ``` @@ -402,7 +404,7 @@ console.log(member.getFullName()); ```js Person.prototype.getFullName = function () { return `${this.firstName} ${this.lastName}`; -} +}; ```

@@ -418,8 +420,8 @@ function Person(firstName, lastName) { this.lastName = lastName; } -const lydia = new Person('Lydia', 'Hallie'); -const sarah = Person('Sarah', 'Smith'); +const lydia = new Person("Lydia", "Hallie"); +const sarah = Person("Sarah", "Smith"); console.log(lydia); console.log(sarah); @@ -489,7 +491,7 @@ function sum(a, b) { return a + b; } -sum(1, '2'); +sum(1, "2"); ``` - A: `NaN` @@ -556,7 +558,7 @@ function getPersonInfo(one, two, three) { console.log(three); } -const person = 'Lydia'; +const person = "Lydia"; const age = 21; getPersonInfo`${person} is ${age} years old`; @@ -583,9 +585,9 @@ getPersonInfo`${person} is ${age} years old`; ```javascript function checkAge(data) { if (data === { age: 18 }) { - console.log('Ты взрослый!'); + console.log("Ты взрослый!"); } else if (data == { age: 18 }) { - console.log('Ты все еще взрослый.'); + console.log("Ты все еще взрослый."); } else { console.log(`Хмм.. Кажется, у тебя нет возраста.`); } @@ -645,7 +647,7 @@ getAge(21); ```javascript function getAge() { - 'use strict'; + "use strict"; age = 21; console.log(age); } @@ -673,7 +675,7 @@ getAge(); ###### 21. Чему будет равно `sum`? ```javascript -const sum = eval('10*10+5'); +const sum = eval("10*10+5"); ``` - A: `105` @@ -696,7 +698,7 @@ const sum = eval('10*10+5'); ###### 22. Как долго будет доступен cool_secret? ```javascript -sessionStorage.setItem('cool_secret', 123); +sessionStorage.setItem("cool_secret", 123); ``` - A: Всегда, данные не потеряются. @@ -749,12 +751,12 @@ console.log(num); ###### 24. Каким будет результат? ```javascript -const obj = { 1: 'a', 2: 'b', 3: 'c' }; +const obj = { 1: "a", 2: "b", 3: "c" }; const set = new Set([1, 2, 3, 4, 5]); -obj.hasOwnProperty('1'); +obj.hasOwnProperty("1"); obj.hasOwnProperty(1); -set.has('1'); +set.has("1"); set.has(1); ``` @@ -780,7 +782,7 @@ set.has(1); ###### 25. Что будет в консоли? ```javascript -const obj = { a: 'one', b: 'two', a: 'three' }; +const obj = { a: "one", b: "two", a: "three" }; console.log(obj); ``` @@ -849,12 +851,12 @@ for (let i = 1; i < 5; i++) { ```javascript String.prototype.giveLydiaPizza = () => { - return 'Just give Lydia pizza already!'; + return "Just give Lydia pizza already!"; }; -const name = 'Lydia'; +const name = "Lydia"; -console.log(name.giveLydiaPizza()) +console.log(name.giveLydiaPizza()); ``` - A: `"Just give Lydia pizza already!"` @@ -878,8 +880,8 @@ console.log(name.giveLydiaPizza()) ```javascript const a = {}; -const b = { key: 'b' }; -const c = { key: 'c' }; +const b = { key: "b" }; +const c = { key: "c" }; a[b] = 123; a[c] = 456; @@ -911,9 +913,9 @@ console.log(a[b]); ###### 30. Каким будет результат? ```javascript -const foo = () => console.log('First'); -const bar = () => setTimeout(() => console.log('Second')); -const baz = () => console.log('Third'); +const foo = () => console.log("First"); +const bar = () => setTimeout(() => console.log("Second")); +const baz = () => console.log("Third"); bar(); foo(); @@ -966,9 +968,7 @@ WebAPI не может добавлять содержимое в стек ко ```html
- +
``` @@ -994,9 +994,7 @@ WebAPI не может добавлять содержимое в стек ко ```html
-

- Кликни меня! -

+

Кликни меня!

``` @@ -1020,7 +1018,7 @@ WebAPI не может добавлять содержимое в стек ко ###### 33. Что будет в консоли? ```javascript -const person = { name: 'Lydia' }; +const person = { name: "Lydia" }; function sayHi(age) { console.log(`${this.name} is ${age}`); @@ -1233,7 +1231,10 @@ console.log(numbers); ###### 40. Каким будет результат? ```javascript -[[0, 1], [2, 3]].reduce( +[ + [0, 1], + [2, 3], +].reduce( (acc, cur) => { return acc.concat(cur); }, @@ -1264,7 +1265,7 @@ console.log(numbers); ```javascript !!null; -!!''; +!!""; !!1; ``` @@ -1292,7 +1293,7 @@ console.log(numbers); ###### 42. Что возвращает метод `setInterval` в браузере? ```javascript -setInterval(() => console.log('Hi'), 1000); +setInterval(() => console.log("Hi"), 1000); ``` - A: уникальный id @@ -1315,7 +1316,7 @@ setInterval(() => console.log('Hi'), 1000); ###### 43. Каким будет результат? ```javascript -[...'Lydia']; +[..."Lydia"]; ``` - A: `["L", "y", "d", "i", "a"]` @@ -1374,14 +1375,14 @@ console.log(gen.next().value); ```javascript const firstPromise = new Promise((res, rej) => { - setTimeout(res, 500, 'один'); + setTimeout(res, 500, "один"); }); const secondPromise = new Promise((res, rej) => { - setTimeout(res, 100, 'два'); + setTimeout(res, 100, "два"); }); -Promise.race([firstPromise, secondPromise]).then(res => console.log(res)); +Promise.race([firstPromise, secondPromise]).then((res) => console.log(res)); ``` - A: `"один"` @@ -1404,7 +1405,7 @@ Promise.race([firstPromise, secondPromise]).then(res => console.log(res)); ###### 46. Каким будет результат? ```javascript -let person = { name: 'Lydia' }; +let person = { name: "Lydia" }; const members = [person]; person = null; @@ -1444,8 +1445,8 @@ console.log(members); ```javascript const person = { - name: 'Lydia', - age: 21 + name: "Lydia", + age: 21, }; for (const item in person) { @@ -1473,7 +1474,7 @@ for (const item in person) { ###### 48. Каким будет результат? ```javascript -console.log(3 + 4 + '5'); +console.log(3 + 4 + "5"); ``` - A: `"345"` @@ -1525,8 +1526,8 @@ const num = parseInt("7*6", 10); ###### 50. Каким будет результат? ```javascript -[1, 2, 3].map(num => { - if (typeof num === 'number') return; +[1, 2, 3].map((num) => { + if (typeof num === "number") return; return num * 2; }); ``` @@ -1554,12 +1555,12 @@ const num = parseInt("7*6", 10); ```javascript function getInfo(member, year) { - member.name = 'Lydia'; + member.name = "Lydia"; year = 1998; } -const person = { name: 'Sarah' }; -const birthYear = '1997'; +const person = { name: "Sarah" }; +const birthYear = "1997"; getInfo(person, birthYear); @@ -1578,7 +1579,7 @@ console.log(person, birthYear); Аргументы передаются _значением_, если их значение не является объектом, то они передаются _ссылкой_. `birthYear` передается по значению, поскольку это строка, а не объект. Когда мы передаем аргументы по значению, создается _копия_ этого значения (см. вопрос 46). -Переменная `birthYear` имеет ссылку на значение `"1997"`. Аргумент `year` также имеет ссылку на значение` "1997" `, но это не то же самое значение, на которое имеется ссылка для `birthYear`. Когда мы обновляем значение `year`, устанавливая `year` равным `"1998"`, мы обновляем только значение `year`. `birthYear` по-прежнему равно `"1997"`. +Переменная `birthYear` имеет ссылку на значение `"1997"`. Аргумент `year` также имеет ссылку на значение`"1997"`, но это не то же самое значение, на которое имеется ссылка для `birthYear`. Когда мы обновляем значение `year`, устанавливая `year` равным `"1998"`, мы обновляем только значение `year`. `birthYear` по-прежнему равно `"1997"`. Значение `person` является объектом. Аргумент `member` имеет (скопированную) ссылку на _тот же_ объект. Когда мы изменяем свойство объекта, на который `member` ссылается, значение `person` также будет изменено, поскольку они оба имеют ссылку на один и тот же объект. Свойство `name` объекта `person` теперь равно значению `"Lydia"`. @@ -1591,15 +1592,15 @@ console.log(person, birthYear); ```javascript function greeting() { - throw 'Hello world!'; + throw "Hello world!"; } function sayHi() { try { const data = greeting(); - console.log('It worked!', data); + console.log("It worked!", data); } catch (e) { - console.log('Oh no an error:', e); + console.log("Oh no an error:", e); } } @@ -1629,8 +1630,8 @@ sayHi(); ```javascript function Car() { - this.make = 'Lamborghini'; - return { make: 'Maserati' }; + this.make = "Lamborghini"; + return { make: "Maserati" }; } const myCar = new Car(); @@ -1702,11 +1703,11 @@ class Dog { } } -Dog.prototype.bark = function() { +Dog.prototype.bark = function () { console.log(`Woof I am ${this.name}`); }; -const pet = new Dog('Mara'); +const pet = new Dog("Mara"); pet.bark(); @@ -1771,7 +1772,7 @@ export default counter; ```javascript // index.js -import myCounter from './counter'; +import myCounter from "./counter"; myCounter += 1; @@ -1800,7 +1801,7 @@ console.log(myCounter); ###### 58. Какой будет вывод? ```javascript -const name = 'Lydia'; +const name = "Lydia"; age = 21; console.log(delete name); @@ -1871,7 +1872,7 @@ console.log(y); ###### 60. Какой будет вывод? ```javascript -const user = { name: 'Lydia', age: 21 }; +const user = { name: "Lydia", age: 21 }; const admin = { admin: true, ...user }; console.log(admin); @@ -1897,9 +1898,9 @@ console.log(admin); ###### 61. Какой будет вывод? ```javascript -const person = { name: 'Lydia' }; +const person = { name: "Lydia" }; -Object.defineProperty(person, 'age', { value: 21 }); +Object.defineProperty(person, "age", { value: 21 }); console.log(person); console.log(Object.keys(person)); @@ -1928,12 +1929,12 @@ console.log(Object.keys(person)); ```javascript const settings = { - username: 'lydiahallie', + username: "lydiahallie", level: 19, - health: 90 + health: 90, }; -const data = JSON.stringify(settings, ['level', 'health']); +const data = JSON.stringify(settings, ["level", "health"]); console.log(data); ``` @@ -1964,7 +1965,7 @@ console.log(data); let num = 10; const increaseNumber = () => num++; -const increasePassedNumber = number => number++; +const increasePassedNumber = (number) => number++; const num1 = increaseNumber(); const num2 = increasePassedNumber(num1); @@ -2121,12 +2122,12 @@ class Labrador extends Dog { ```javascript // index.js -console.log('running index.js'); -import { sum } from './sum.js'; +console.log("running index.js"); +import { sum } from "./sum.js"; console.log(sum(1, 2)); // sum.js -console.log('running sum.js'); +console.log("running sum.js"); export const sum = (a, b) => a + b; ``` @@ -2152,9 +2153,9 @@ export const sum = (a, b) => a + b; ###### 68. Какой будет вывод? ```javascript -console.log(Number(2) === Number(2)) -console.log(Boolean(false) === Boolean(false)) -console.log(Symbol('foo') === Symbol('foo')) +console.log(Number(2) === Number(2)); +console.log(Boolean(false) === Boolean(false)); +console.log(Symbol("foo") === Symbol("foo")); ``` - A: `true`, `true`, `false` @@ -2177,9 +2178,9 @@ console.log(Symbol('foo') === Symbol('foo')) ###### 69. Какой будет вывод? ```javascript -const name = 'Lydia Hallie' -console.log(name.padStart(13)) -console.log(name.padStart(2)) +const name = "Lydia Hallie"; +console.log(name.padStart(13)); +console.log(name.padStart(2)); ``` - A: `"Lydia Hallie"`, `"Lydia Hallie"` @@ -2300,7 +2301,7 @@ console.log(String.raw`Hello\nworld`); ```javascript async function getData() { - return await Promise.resolve('I made it!'); + return await Promise.resolve("I made it!"); } const data = getData(); @@ -2337,7 +2338,7 @@ function addToList(item, list) { return list.push(item); } -const result = addToList('apple', ['banana']); +const result = addToList("apple", ["banana"]); console.log(result); ``` @@ -2397,7 +2398,7 @@ console.log(shape); ###### 76. Какой будет вывод? ```javascript -const { firstName: myName } = { firstName: 'Lydia' }; +const { firstName: myName } = { firstName: "Lydia" }; console.log(firstName); ``` @@ -2415,7 +2416,7 @@ console.log(firstName); Используя [деструктурирующее присваивание](https://developer.mozilla.org/ru/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment), мы можем распаковывать значения из массивов или свойства из объектов в отдельные переменные: ```javascript -const { firstName } = { firstName: 'Lydia' }; +const { firstName } = { firstName: "Lydia" }; // Версия ES5: // var firstName = { firstName: 'Lydia' }.firstName; @@ -2425,7 +2426,7 @@ console.log(firstName); // "Lydia" Также свойство можно распаковать из объекта и присвоить переменной с именем, отличным от имени свойства объекта: ```javascript -const { firstName: myName } = { firstName: 'Lydia' }; +const { firstName: myName } = { firstName: "Lydia" }; // Версия ES5: // var myName = { firstName: 'Lydia' }.firstName; @@ -2438,12 +2439,11 @@ console.log(firstName); // Тут будет ошибка Uncaught ReferenceErro **Примечание.** Помните о свойствах глобальной области видимости: ```javascript -const { name: myName } = { name: 'Lydia' }; +const { name: myName } = { name: "Lydia" }; console.log(myName); // "lydia" console.log(name); // "" ----- Браузер, например, Chrome console.log(name); // ReferenceError: name is not defined ----- NodeJS - ``` Всякий раз, когда Javascript не может найти переменную в _текущей области видимости_, то поднимается вверх по [цепочке областей видимости](https://developer.mozilla.org/ru/docs/Web/JavaScript/Closures#лексическая_область_видимости) и ищет ее на каждом уровне, и если достигает области верхнего уровня, также известной как **Глобальная область**, и все еще не находит нужной ссылки, то выдает `ReferenceError`. @@ -2487,7 +2487,7 @@ function sum(a, b) { ```javascript const add = () => { const cache = {}; - return num => { + return (num) => { if (num in cache) { return `From cache! ${cache[num]}`; } else { @@ -2532,21 +2532,21 @@ console.log(addFunction(5 * 2)); ###### 79. Какой будет вывод? ```javascript -const myLifeSummedUp = ['☕', '💻', '🍷', '🍫'] +const myLifeSummedUp = ["☕", "💻", "🍷", "🍫"]; for (let item in myLifeSummedUp) { - console.log(item) + console.log(item); } for (let item of myLifeSummedUp) { - console.log(item) + console.log(item); } ``` - A: `0` `1` `2` `3` и `"☕"` ` "💻"` `"🍷"` `"🍫"` - B: `"☕"` ` "💻"` `"🍷"` `"🍫"` и `"☕"` ` "💻"` `"🍷"` `"🍫"` - C: `"☕"` ` "💻"` `"🍷"` `"🍫"` и `0` `1` `2` `3` -- D: `0` `1` `2` `3` и `{0: "☕", 1: "💻", 2: "🍷", 3: "🍫"}` +- D: `0` `1` `2` `3` и `{0: "☕", 1: "💻", 2: "🍷", 3: "🍫"}`
Ответ

@@ -2569,14 +2569,14 @@ for (let item of myLifeSummedUp) { ###### 80. Какой будет вывод? ```javascript -const list = [1 + 2, 1 * 2, 1 / 2] -console.log(list) +const list = [1 + 2, 1 * 2, 1 / 2]; +console.log(list); ``` - A: `["1 + 2", "1 * 2", "1 / 2"]` - B: `["12", 2, 0.5]` - C: `[3, 2, 0.5]` -- D: `[1, 1, 1]` +- D: `[1, 1, 1]`

Ответ

@@ -2596,16 +2596,16 @@ console.log(list) ```javascript function sayHi(name) { - return `Hi there, ${name}` + return `Hi there, ${name}`; } -console.log(sayHi()) +console.log(sayHi()); ``` - A: `Hi there, ` - B: `Hi there, undefined` - C: `Hi there, null` -- D: `ReferenceError` +- D: `ReferenceError`

Ответ

@@ -2628,21 +2628,21 @@ console.log(sayHi()) ###### 82. Какой будет вывод? ```javascript -var status = '😎' +var status = "😎"; setTimeout(() => { - const status = '😍' + const status = "😍"; const data = { - status: '🥑', + status: "🥑", getStatus() { - return this.status - } - } + return this.status; + }, + }; - console.log(data.getStatus()) - console.log(data.getStatus.call(this)) -}, 0) + console.log(data.getStatus()); + console.log(data.getStatus.call(this)); +}, 0); ``` - A: `"🥑"` и `"😍"` @@ -2668,14 +2668,14 @@ setTimeout(() => { ```javascript const person = { - name: 'Lydia', - age: 21 -} + name: "Lydia", + age: 21, +}; -let city = person.city -city = 'Amsterdam' +let city = person.city; +city = "Amsterdam"; -console.log(person) +console.log(person); ``` - A: `{ name: "Lydia", age: 21 }` @@ -2706,15 +2706,15 @@ console.log(person) ```javascript function checkAge(age) { if (age < 18) { - const message = "Sorry, you're too young." + const message = "Sorry, you're too young."; } else { - const message = "Yay! You're old enough!" + const message = "Yay! You're old enough!"; } - return message + return message; } -console.log(checkAge(21)) +console.log(checkAge(21)); ``` - A: `"Sorry, you're too young."` @@ -2737,9 +2737,9 @@ console.log(checkAge(21)) ###### 85. Какая информация будетвыведена в лог? ```javascript -fetch('https://www.website.com/api/user/1') - .then(res => res.json()) - .then(res => console.log(res)) +fetch("https://www.website.com/api/user/1") + .then((res) => res.json()) + .then((res) => console.log(res)); ``` - A: Результат метода `fetch`. @@ -2793,7 +2793,7 @@ function getName(name) { ###### 87. Какой будет вывод? ```javascript -console.log('I want pizza'[0]) +console.log("I want pizza"[0]); ``` - A: `"""` @@ -2819,10 +2819,10 @@ console.log('I want pizza'[0]) ```javascript function sum(num1, num2 = num1) { - console.log(num1 + num2) + console.log(num1 + num2); } -sum(10) +sum(10); ``` - A: `NaN` @@ -2848,13 +2848,13 @@ sum(10) ```javascript // module.js -export default () => 'Hello world' -export const name = 'Lydia' +export default () => "Hello world"; +export const name = "Lydia"; // index.js -import * as data from './module' +import * as data from "./module"; -console.log(data) +console.log(data); ``` - A: `{ default: function default(), name: "Lydia" }` @@ -2881,12 +2881,12 @@ console.log(data) ```javascript class Person { constructor(name) { - this.name = name + this.name = name; } } -const member = new Person('John') -console.log(typeof member) +const member = new Person("John"); +console.log(typeof member); ``` - A: `"class"` @@ -2903,7 +2903,7 @@ console.log(typeof member) ```javascript function Person() { - this.name = name + this.name = name; } ``` @@ -2917,9 +2917,9 @@ function Person() { ###### 91. Какой будет вывод? ```javascript -let newList = [1, 2, 3].push(4) +let newList = [1, 2, 3].push(4); -console.log(newList.push(5)) +console.log(newList.push(5)); ``` - A: `[1, 2, 3, 4, 5]` @@ -2945,14 +2945,14 @@ console.log(newList.push(5)) ```javascript function giveLydiaPizza() { - return 'Here is pizza!' + return "Here is pizza!"; } const giveLydiaChocolate = () => - "Here's chocolate... now go hit the gym already." + "Here's chocolate... now go hit the gym already."; -console.log(giveLydiaPizza.prototype) -console.log(giveLydiaChocolate.prototype) +console.log(giveLydiaPizza.prototype); +console.log(giveLydiaChocolate.prototype); ``` - A: `{ constructor: ...}` `{ constructor: ...}` @@ -2976,12 +2976,12 @@ console.log(giveLydiaChocolate.prototype) ```javascript const person = { - name: 'Lydia', - age: 21 -} + name: "Lydia", + age: 21, +}; for (const [x, y] of Object.entries(person)) { - console.log(x, y) + console.log(x, y); } ``` @@ -3033,10 +3033,10 @@ getItems(["banana", "apple"], "pear", "orange") ```javascript function getItems(fruitList, favoriteFruit, ...args) { - return [...fruitList, ...args, favoriteFruit] + return [...fruitList, ...args, favoriteFruit]; } -getItems(["banana", "apple"], "pear", "orange") +getItems(["banana", "apple"], "pear", "orange"); ``` Приведенный выше пример работает. Это возвращает массив `[ 'banana', 'apple', 'orange', 'pear' ]` @@ -3050,14 +3050,14 @@ getItems(["banana", "apple"], "pear", "orange") ```javascript function nums(a, b) { - if (a > b) console.log('a is bigger') - else console.log('b is bigger') - return - a + b; + if (a > b) console.log("a is bigger"); + else console.log("b is bigger"); + return; + a + b; } -console.log(nums(4, 2)) -console.log(nums(1, 2)) +console.log(nums(4, 2)); +console.log(nums(1, 2)); ``` - A: `a is bigger`, `6` and `b is bigger`, `3` @@ -3075,8 +3075,8 @@ console.log(nums(1, 2)) Здесь мы написали инструкцию `return` и другое значение `a + b` в новой строке. Однако, поскольку это новая линия, движок не знает, что это на самом деле значение, которое мы хотели бы вернуть. Вместо этого он автоматически добавляет точку с запятой после `return`. Вы можете увидеть это как: ```javascript - return; - a + b +return; +a + b; ``` Это означает, что `a + b` никогда не достигается, так как функция перестает выполняться после ключевого слова `return`. Если значение не возвращается, как здесь, функция возвращает значение `undefined`. Обратите внимание, что после операторов `if / else` автоматической вставки нет! @@ -3091,18 +3091,18 @@ console.log(nums(1, 2)) ```javascript class Person { constructor() { - this.name = 'Lydia' + this.name = "Lydia"; } } Person = class AnotherPerson { constructor() { - this.name = 'Sarah' + this.name = "Sarah"; } -} +}; -const member = new Person() -console.log(member.name) +const member = new Person(); +console.log(member.name); ``` - A: `"Lydia"` @@ -3126,11 +3126,11 @@ console.log(member.name) ```javascript const info = { - [Symbol('a')]: 'b' -} + [Symbol("a")]: "b", +}; -console.log(info) -console.log(Object.keys(info)) +console.log(info); +console.log(Object.keys(info)); ``` - A: `{Symbol('a'): 'b'}` and `["{Symbol('a')"]` @@ -3185,7 +3185,7 @@ console.log(getUser(user)) Следующая функция вернула бы объект: -```const getUser = user => ({ name: user.name, age: user.age })``` +`const getUser = user => ({ name: user.name, age: user.age })`

@@ -3195,9 +3195,9 @@ console.log(getUser(user)) ###### 99. Какой будет вывод? ```javascript -const name = 'Lydia' +const name = "Lydia"; -console.log(name()) +console.log(name()); ``` - A: `SyntaxError` @@ -3227,8 +3227,8 @@ ReferenceErrors генерируется, когда JavaScript не может ```javascript // 🎉✨ This is my 100th question! ✨🎉 -const output = `${[] && 'Im'}possible! -You should${'' && `n't`} see a therapist after so much JavaScript lol` +const output = `${[] && "Im"}possible! +You should${"" && `n't`} see a therapist after so much JavaScript lol`; ``` - A: `possible! You should see a therapist after so much JavaScript lol` @@ -3253,11 +3253,11 @@ You should${'' && `n't`} see a therapist after so much JavaScript lol` ###### 101. Какое значение будет на выходе? ```javascript -const one = (false || {} || null) -const two = (null || false || '') -const three = ([] || 0 || true) +const one = false || {} || null; +const two = null || false || ""; +const three = [] || 0 || true; -console.log(one, two, three) +console.log(one, two, three); ``` - A: `false` `null` `[]` @@ -3286,20 +3286,20 @@ console.log(one, two, three) ###### 102. Какое значение будет на выходе? ```javascript -const myPromise = () => Promise.resolve('I have resolved!') +const myPromise = () => Promise.resolve("I have resolved!"); function firstFunction() { - myPromise().then(res => console.log(res)) - console.log('second') + myPromise().then((res) => console.log(res)); + console.log("second"); } async function secondFunction() { - console.log(await myPromise()) - console.log('second') + console.log(await myPromise()); + console.log("second"); } -firstFunction() -secondFunction() +firstFunction(); +secondFunction(); ``` - A: `I have resolved!`, `second` and `I have resolved!`, `second` @@ -3330,14 +3330,14 @@ secondFunction() ###### 103. Какое значение будет на выходе? ```javascript -const set = new Set() +const set = new Set(); -set.add(1) -set.add('Lydia') -set.add({ name: 'Lydia' }) +set.add(1); +set.add("Lydia"); +set.add({ name: "Lydia" }); for (let item of set) { - console.log(item + 2) + console.log(item + 2); } ``` @@ -3367,7 +3367,7 @@ for (let item of set) { ###### 104. Чему равно значение? ```javascript -Promise.resolve(5) +Promise.resolve(5); ``` - A: `5` @@ -3394,15 +3394,15 @@ Promise.resolve(5) ```javascript function compareMembers(person1, person2 = person) { if (person1 !== person2) { - console.log('Not the same!') + console.log("Not the same!"); } else { - console.log('They are the same!') + console.log("They are the same!"); } } -const person = { name: 'Lydia' } +const person = { name: "Lydia" }; -compareMembers(person) +compareMembers(person); ``` - A: `Not the same!` @@ -3437,11 +3437,11 @@ const colorConfig = { green: true, black: true, yellow: false, -} +}; -const colors = ['pink', 'red', 'blue'] +const colors = ["pink", "red", "blue"]; -console.log(colorConfig.colors[1]) +console.log(colorConfig.colors[1]); ``` - A: `true` @@ -3468,7 +3468,7 @@ JavaScript интерпретирует (или распаковывает) оп ###### 107. Чему равно значение? ```javascript -console.log('❤️' === '❤️') +console.log("❤️" === "❤️"); ``` - A: `true` @@ -3489,19 +3489,19 @@ console.log('❤️' === '❤️') ###### 108. Какой из этих методов модифицирует исходный массив? ```javascript -const emojis = ['✨', '🥑', '😍'] +const emojis = ["✨", "🥑", "😍"]; -emojis.map(x => x + '✨') -emojis.filter(x => x !== '🥑') -emojis.find(x => x !== '🥑') -emojis.reduce((acc, cur) => acc + '✨') -emojis.slice(1, 2, '✨') -emojis.splice(1, 2, '✨') +emojis.map((x) => x + "✨"); +emojis.filter((x) => x !== "🥑"); +emojis.find((x) => x !== "🥑"); +emojis.reduce((acc, cur) => acc + "✨"); +emojis.slice(1, 2, "✨"); +emojis.splice(1, 2, "✨"); ``` - A: `All of them` - B: `map` `reduce` `slice` `splice` -- C: `map` `slice` `splice` +- C: `map` `slice` `splice` - D: `splice`
Ответ @@ -3521,17 +3521,17 @@ emojis.splice(1, 2, '✨') ###### 109. Какое значение будет на выходе? ```javascript -const food = ['🍕', '🍫', '🥑', '🍔'] -const info = { favoriteFood: food[0] } +const food = ["🍕", "🍫", "🥑", "🍔"]; +const info = { favoriteFood: food[0] }; -info.favoriteFood = '🍝' +info.favoriteFood = "🍝"; -console.log(food) +console.log(food); ``` - A: `['🍕', '🍫', '🥑', '🍔']` - B: `['🍝', '🍫', '🥑', '🍔']` -- C: `['🍝', '🍕', '🍫', '🥑', '🍔']` +- C: `['🍝', '🍕', '🍫', '🥑', '🍔']` - D: `ReferenceError`
Ответ @@ -3553,7 +3553,7 @@ console.log(food) ###### 110. Что делает этот метод? ```javascript -JSON.parse() +JSON.parse(); ``` - A: Разбирает JSON в значение JavaScript @@ -3570,16 +3570,16 @@ JSON.parse() ```javascript // Преобразование числа в допустимый JSON, затем преобразование строки JSON в значение JavaScript: -const jsonNumber = JSON.stringify(4) // '4' -JSON.parse(jsonNumber) // 4 +const jsonNumber = JSON.stringify(4); // '4' +JSON.parse(jsonNumber); // 4 // Преобразование значения массива в допустимый JSON, затем разбор строки JSON в значение JavaScript: -const jsonArray = JSON.stringify([1, 2, 3]) // '[1, 2, 3]' -JSON.parse(jsonArray) // [1, 2, 3] +const jsonArray = JSON.stringify([1, 2, 3]); // '[1, 2, 3]' +JSON.parse(jsonArray); // [1, 2, 3] // Преобразование объекта в допустимый JSON, затем преобразование строки JSON в значение JavaScript: -const jsonArray = JSON.stringify({ name: 'Lydia' }) // '{"name":"Lydia"}' -JSON.parse(jsonArray) // { name: 'Lydia' } +const jsonArray = JSON.stringify({ name: "Lydia" }); // '{"name":"Lydia"}' +JSON.parse(jsonArray); // { name: 'Lydia' } ```

@@ -3587,17 +3587,17 @@ JSON.parse(jsonArray) // { name: 'Lydia' } --- -###### 111. Какое значение будет на выходе? +###### 111. Какое значение будет на выходе? ```javascript -let name = 'Lydia' +let name = "Lydia"; function getName() { - console.log(name) - let name = 'Sarah' + console.log(name); + let name = "Sarah"; } -getName() +getName(); ``` - A: Lydia @@ -3617,13 +3617,13 @@ getName() Если бы мы не объявили переменную `name` в функции `getName`, движок javascript посмотрел бы вниз по _цепочки области действия_. Внешняя область имеет переменную с именем `name` со значением `Lydia`. В этом случае он бы записал `Lydia`. ```javascript -let name = 'Lydia' +let name = "Lydia"; function getName() { - console.log(name) + console.log(name); } -getName() // Lydia +getName(); // Lydia ```

@@ -3635,18 +3635,18 @@ getName() // Lydia ```javascript function* generatorOne() { - yield ['a', 'b', 'c']; + yield ["a", "b", "c"]; } function* generatorTwo() { - yield* ['a', 'b', 'c']; + yield* ["a", "b", "c"]; } -const one = generatorOne() -const two = generatorTwo() +const one = generatorOne(); +const two = generatorTwo(); -console.log(one.next().value) -console.log(two.next().value) +console.log(one.next().value); +console.log(two.next().value); ``` - A: `a` and `a` @@ -3664,17 +3664,17 @@ console.log(two.next().value) В `generatorOne` мы получаем весь массив `['a', 'b', 'c']`, используя ключевое слово `yield`. Значение свойства `value` для объекта, возвращаемого методом `next` для `one` (`one.next().value`), равно всему массиву `['a', 'b', 'c']`. ```javascript -console.log(one.next().value) // ['a', 'b', 'c'] -console.log(one.next().value) // undefined +console.log(one.next().value); // ['a', 'b', 'c'] +console.log(one.next().value); // undefined ``` В файле `generatorTwo` мы используем ключевое слово `yield*`. Это означает, что первое полученное значение `two` равно первому полученному значению в итераторе. Итератор - это массив `['a', 'b', 'c']`. Первым полученным значением является `a`, поэтому в первый раз, когда мы вызываем `two.next().value`, возвращается `a`. ```javascript -console.log(two.next().value) // 'a' -console.log(two.next().value) // 'b' -console.log(two.next().value) // 'c' -console.log(two.next().value) // undefined +console.log(two.next().value); // 'a' +console.log(two.next().value); // 'b' +console.log(two.next().value); // 'c' +console.log(two.next().value); // undefined ```

@@ -3685,7 +3685,7 @@ console.log(two.next().value) // undefined ###### 113. Какое значение будет на выходе? ```javascript -console.log(`${(x => x)('I love')} to program`) +console.log(`${((x) => x)("I love")} to program`); ``` - A: `I love to program` @@ -3710,11 +3710,11 @@ console.log(`${(x => x)('I love')} to program`) ```javascript let config = { alert: setInterval(() => { - console.log('Alert!') - }, 1000) -} + console.log("Alert!"); + }, 1000), +}; -config = null +config = null; ``` - A: обратный вызов `setInterval` не будет вызван @@ -3741,17 +3741,17 @@ config = null ###### 115. Какие методы вернут значение `'Hello world!'`? ```javascript -const myMap = new Map() -const myFunc = () => 'greeting' +const myMap = new Map(); +const myFunc = () => "greeting"; -myMap.set(myFunc, 'Hello world!') +myMap.set(myFunc, "Hello world!"); //1 -myMap.get('greeting') +myMap.get("greeting"); //2 -myMap.get(myFunc) +myMap.get(myFunc); //3 -myMap.get(() => 'greeting') +myMap.get(() => "greeting"); ``` - A: 1 @@ -3778,20 +3778,20 @@ myMap.get(() => 'greeting') ```javascript const person = { - name: 'Lydia', - age: 21 -} + name: "Lydia", + age: 21, +}; -const changeAge = (x = { ...person }) => x.age += 1 +const changeAge = (x = { ...person }) => (x.age += 1); const changeAgeAndName = (x = { ...person }) => { - x.age += 1 - x.name = 'Sarah' -} + x.age += 1; + x.name = "Sarah"; +}; -changeAge(person) -changeAgeAndName() +changeAge(person); +changeAgeAndName(); -console.log(person) +console.log(person); ``` - A: `{name: "Sarah", age: 22}` @@ -3819,7 +3819,7 @@ console.log(person) ```javascript function sumValues(x, y, z) { - return x + y + z; + return x + y + z; } ``` @@ -3870,15 +3870,15 @@ console.log(list[(num += 1)]); ```javascript const person = { - firstName: 'Lydia', - lastName: 'Hallie', - pet: { - name: 'Mara', - breed: 'Dutch Tulip Hound' - }, - getFullName() { - return `${this.firstName} ${this.lastName}`; - } + firstName: "Lydia", + lastName: "Hallie", + pet: { + name: "Mara", + breed: "Dutch Tulip Hound", + }, + getFullName() { + return `${this.firstName} ${this.lastName}`; + }, }; console.log(person.pet?.name); @@ -3912,12 +3912,12 @@ console.log(member.getLastName?.()); ###### 120. Что будет на выходе? ```javascript -const groceries = ['banana', 'apple', 'peanuts']; +const groceries = ["banana", "apple", "peanuts"]; -if (groceries.indexOf('banana')) { - console.log('We have to buy bananas!'); +if (groceries.indexOf("banana")) { + console.log("We have to buy bananas!"); } else { - console.log(`We don't have to buy bananas!`); + console.log(`We don't have to buy bananas!`); } ``` @@ -3931,7 +3931,7 @@ if (groceries.indexOf('banana')) { #### Ответ: B -Мы передали условие `groceries.indexOf("banana")` в оператор `if`. `groceries.indexOf("banana")` возвращает `0`, что является ложным значением. Поскольку условие в операторе `if` ложно, выполняется код в блоке `else`, и в лог выводится ``We don't have to buy bananas!``. +Мы передали условие `groceries.indexOf("banana")` в оператор `if`. `groceries.indexOf("banana")` возвращает `0`, что является ложным значением. Поскольку условие в операторе `if` ложно, выполняется код в блоке `else`, и в лог выводится `We don't have to buy bananas!`.

@@ -3942,10 +3942,10 @@ if (groceries.indexOf('banana')) { ```javascript const config = { - languages: [], - set language(lang) { - return this.languages.push(lang); - } + languages: [], + set language(lang) { + return this.languages.push(lang); + }, }; console.log(config.language); @@ -3971,10 +3971,10 @@ console.log(config.language); ###### 122. Что будет на выходе? ```javascript -const name = 'Lydia Hallie'; +const name = "Lydia Hallie"; -console.log(!typeof name === 'object'); -console.log(!typeof name === 'string'); +console.log(!typeof name === "object"); +console.log(!typeof name === "string"); ``` - A: `false` `true` @@ -3999,9 +3999,9 @@ console.log(!typeof name === 'string'); ###### 123. Что будет на выходе? ```javascript -const add = x => y => z => { - console.log(x, y, z); - return x + y + z; +const add = (x) => (y) => (z) => { + console.log(x, y, z); + return x + y + z; }; add(4)(5)(6); @@ -4028,16 +4028,16 @@ add(4)(5)(6); ```javascript async function* range(start, end) { - for (let i = start; i <= end; i++) { - yield Promise.resolve(i); - } + for (let i = start; i <= end; i++) { + yield Promise.resolve(i); + } } (async () => { - const gen = range(1, 3); - for await (const item of gen) { - console.log(item); - } + const gen = range(1, 3); + for await (const item of gen) { + console.log(item); + } })(); ``` @@ -4062,7 +4062,7 @@ async function* range(start, end) { ```javascript const myFunc = ({ x, y, z }) => { - console.log(x, y, z); + console.log(x, y, z); }; myFunc(1, 2, 3); @@ -4186,8 +4186,8 @@ console.log(isNaN(age)); const randomValue = 21; function getInfo() { - console.log(typeof randomValue); - const randomValue = 'Lydia Hallie'; + console.log(typeof randomValue); + const randomValue = "Lydia Hallie"; } getInfo(); @@ -4213,16 +4213,16 @@ getInfo(); ###### 130. Что будет на выходе? ```javascript -const myPromise = Promise.resolve('Woah some cool data'); +const myPromise = Promise.resolve("Woah some cool data"); (async () => { - try { - console.log(await myPromise); - } catch { - throw new Error(`Oops didn't work`); - } finally { - console.log('Oh finally!'); - } + try { + console.log(await myPromise); + } catch { + throw new Error(`Oops didn't work`); + } finally { + console.log("Oh finally!"); + } })(); ``` @@ -4246,7 +4246,7 @@ const myPromise = Promise.resolve('Woah some cool data'); ###### 131. Что будет на выходе? ```javascript -const emojis = ['🥑', ['✨', '✨', ['🍕', '🍕']]]; +const emojis = ["🥑", ["✨", "✨", ["🍕", "🍕"]]]; console.log(emojis.flat(1)); ``` @@ -4319,19 +4319,19 @@ console.log(counterOne.count); ###### 133. Что будет на выходе? ```javascript -const myPromise = Promise.resolve(Promise.resolve('Promise!')); +const myPromise = Promise.resolve(Promise.resolve("Promise!")); function funcOne() { - myPromise.then(res => res).then(res => console.log(res)); - setTimeout(() => console.log('Timeout!', 0)); - console.log('Last line!'); + myPromise.then((res) => res).then((res) => console.log(res)); + setTimeout(() => console.log("Timeout!", 0)); + console.log("Last line!"); } async function funcTwo() { const res = await myPromise; console.log(await res); - setTimeout(() => console.log('Timeout!', 0)); - console.log('Last line!'); + setTimeout(() => console.log("Timeout!", 0)); + console.log("Last line!"); } funcOne(); @@ -4376,7 +4376,7 @@ export default function sum(x) { } // index.js -import * as sum from './sum'; +import * as sum from "./sum"; ``` - A: `sum(4)` @@ -4393,12 +4393,12 @@ import * as sum from './sum'; ```javascript // info.js -export const name = 'Lydia'; +export const name = "Lydia"; export const age = 21; -export default 'I love JavaScript'; +export default "I love JavaScript"; // index.js -import * as info from './info'; +import * as info from "./info"; console.log(info); ``` @@ -4429,13 +4429,13 @@ console.log(info); ```javascript const handler = { - set: () => console.log('Added a new property!'), - get: () => console.log('Accessed a property!'), + set: () => console.log("Added a new property!"), + get: () => console.log("Accessed a property!"), }; const person = new Proxy({}, handler); -person.name = 'Lydia'; +person.name = "Lydia"; person.name; ``` @@ -4465,7 +4465,7 @@ C помощью Proxy мы можем добавить собственное ###### 136. Какое из перечисленных действий может модифицировать объект `person`? ```javascript -const person = { name: 'Lydia Hallie' }; +const person = { name: "Lydia Hallie" }; Object.seal(person); ``` @@ -4493,9 +4493,9 @@ Object.seal(person); ```javascript const person = { - name: 'Lydia Hallie', + name: "Lydia Hallie", address: { - street: '100 Main St', + street: "100 Main St", }, }; @@ -4524,7 +4524,7 @@ Object.freeze(person); ###### 138. Что будет на выходе? ```javascript -const add = x => x + x; +const add = (x) => x + x; function myFunc(num = 2, value = add(num)) { console.log(num, value); @@ -4557,21 +4557,21 @@ myFunc(3); ```javascript class Counter { - #number = 10 + #number = 10; increment() { - this.#number++ + this.#number++; } getNum() { - return this.#number + return this.#number; } } -const counter = new Counter() -counter.increment() +const counter = new Counter(); +counter.increment(); -console.log(counter.#number) +console.log(counter.#number); ``` - A: `10` @@ -4595,8 +4595,8 @@ console.log(counter.#number) ```javascript const teams = [ - { name: 'Team 1', members: ['Paul', 'Lisa'] }, - { name: 'Team 2', members: ['Laura', 'Tim'] }, + { name: "Team 1", members: ["Paul", "Lisa"] }, + { name: "Team 2", members: ["Laura", "Tim"] }, ]; function* getMembers(members) { @@ -4639,8 +4639,8 @@ obj.next(); // { value: "Lisa", done: false } ```javascript const person = { - name: 'Lydia Hallie', - hobbies: ['coding'], + name: "Lydia Hallie", + hobbies: ["coding"], }; function addHobby(hobby, hobbies = person.hobbies) { @@ -4648,9 +4648,9 @@ function addHobby(hobby, hobbies = person.hobbies) { return hobbies; } -addHobby('running', []); -addHobby('dancing'); -addHobby('baking', person.hobbies); +addHobby("running", []); +addHobby("dancing"); +addHobby("baking", person.hobbies); console.log(person.hobbies); ``` @@ -4719,11 +4719,11 @@ const pet = new Flamingo(); ###### 143. Какой/какие из вариантов приведет к ошибке? ```javascript -const emojis = ['🎄', '🎅🏼', '🎁', '⭐']; +const emojis = ["🎄", "🎅🏼", "🎁", "⭐"]; -/* 1 */ emojis.push('🦌'); +/* 1 */ emojis.push("🦌"); /* 2 */ emojis.splice(0, 2); -/* 3 */ emojis = [...emojis, '🥂']; +/* 3 */ emojis = [...emojis, "🥂"]; /* 4 */ emojis.length = 0; ``` @@ -4778,11 +4778,11 @@ const person = { let count = 0; const nums = [0, 1, 2, 3]; -nums.forEach(num => { - if (num) count += 1 -}) +nums.forEach((num) => { + if (num) count += 1; +}); -console.log(count) +console.log(count); ``` - A: 1 @@ -4806,12 +4806,12 @@ console.log(count) ```javascript function getFruit(fruits) { - console.log(fruits?.[1]?.[1]) + console.log(fruits?.[1]?.[1]); } -getFruit([['🍊', '🍌'], ['🍍']]) -getFruit() -getFruit([['🍍'], ['🍊', '🍌']]) +getFruit([["🍊", "🍌"], ["🍍"]]); +getFruit(); +getFruit([["🍍"], ["🍊", "🍌"]]); ``` - A: `null`, `undefined`, 🍌 @@ -4841,19 +4841,19 @@ getFruit([['🍍'], ['🍊', '🍌']]) ```javascript class Calc { - constructor() { - this.count = 0 - } + constructor() { + this.count = 0; + } - increase() { - this.count ++ - } + increase() { + this.count++; + } } -const calc = new Calc() -new Calc().increase() +const calc = new Calc(); +new Calc().increase(); -console.log(calc.count) +console.log(calc.count); ``` - A: `0` @@ -4877,25 +4877,25 @@ console.log(calc.count) ```javascript const user = { - email: "e@mail.com", - password: "12345" -} + email: "e@mail.com", + password: "12345", +}; const updateUser = ({ email, password }) => { - if (email) { - Object.assign(user, { email }) - } + if (email) { + Object.assign(user, { email }); + } - if (password) { - user.password = password - } + if (password) { + user.password = password; + } - return user -} + return user; +}; -const updatedUser = updateUser({ email: "new@email.com" }) +const updatedUser = updateUser({ email: "new@email.com" }); -console.log(updatedUser === user) +console.log(updatedUser === user); ``` - A: `false` @@ -4918,13 +4918,13 @@ console.log(updatedUser === user) ###### 149. Что будет на выходе? ```javascript -const fruit = ['🍌', '🍊', '🍎'] +const fruit = ["🍌", "🍊", "🍎"]; -fruit.slice(0, 1) -fruit.splice(0, 1) -fruit.unshift('🍇') +fruit.slice(0, 1); +fruit.splice(0, 1); +fruit.unshift("🍇"); -console.log(fruit) +console.log(fruit); ``` - A: `['🍌', '🍊', '🍎']` @@ -4950,13 +4950,13 @@ console.log(fruit) ```javascript const animals = {}; -let dog = { emoji: '🐶' } -let cat = { emoji: '🐈' } +let dog = { emoji: "🐶" }; +let cat = { emoji: "🐈" }; -animals[dog] = { ...dog, name: "Mara" } -animals[cat] = { ...cat, name: "Sara" } +animals[dog] = { ...dog, name: "Mara" }; +animals[cat] = { ...cat, name: "Sara" }; -console.log(animals[dog]) +console.log(animals[dog]); ``` - A: `{ emoji: "🐶", name: "Mara" }` @@ -4986,14 +4986,14 @@ console.log(animals[dog]) ```javascript const user = { - email: "my@email.com", - updateEmail: email => { - this.email = email - } -} + email: "my@email.com", + updateEmail: (email) => { + this.email = email; + }, +}; -user.updateEmail("new@email.com") -console.log(user.email) +user.updateEmail("new@email.com"); +console.log(user.email); ``` - A: `my@email.com` @@ -5016,20 +5016,20 @@ console.log(user.email) ###### 152. Что будет на выходе? ```javascript -const promise1 = Promise.resolve('First') -const promise2 = Promise.resolve('Second') -const promise3 = Promise.reject('Third') -const promise4 = Promise.resolve('Fourth') +const promise1 = Promise.resolve("First"); +const promise2 = Promise.resolve("Second"); +const promise3 = Promise.reject("Third"); +const promise4 = Promise.resolve("Fourth"); const runPromises = async () => { - const res1 = await Promise.all([promise1, promise2]) - const res2 = await Promise.all([promise3, promise4]) - return [res1, res2] -} + const res1 = await Promise.all([promise1, promise2]); + const res2 = await Promise.all([promise3, promise4]); + return [res1, res2]; +}; runPromises() - .then(res => console.log(res)) - .catch(err => console.log(err)) + .then((res) => console.log(res)) + .catch((err) => console.log(err)); ``` - A: `[['First', 'Second'], ['Fourth']]` @@ -5052,13 +5052,16 @@ runPromises() ###### 153. Каким должно быть значение `method` для регистрации `{ name: "Lydia", age: 22 }`? ```javascript -const keys = ["name", "age"] -const values = ["Lydia", 22] +const keys = ["name", "age"]; +const values = ["Lydia", 22]; -const method = /* ?? */ -Object[method](keys.map((_, i) => { - return [keys[i], values[i]] -})) // { name: "Lydia", age: 22 } +const method = + /* ?? */ + Object[method]( + keys.map((_, i) => { + return [keys[i], values[i]]; + }) + ); // { name: "Lydia", age: 22 } ``` - A: `entries` @@ -5083,18 +5086,18 @@ Object[method](keys.map((_, i) => { ###### 154. Что будет на выходе? ```javascript -const createMember = ({ email, address = {}}) => { - const validEmail = /.+\@.+\..+/.test(email) - if (!validEmail) throw new Error("Valid email pls") +const createMember = ({ email, address = {} }) => { + const validEmail = /.+\@.+\..+/.test(email); + if (!validEmail) throw new Error("Valid email pls"); - return { - email, - address: address ? address : null - } -} + return { + email, + address: address ? address : null, + }; +}; -const member = createMember({ email: "my@email.com" }) -console.log(member) +const member = createMember({ email: "my@email.com" }); +console.log(member); ``` - A: `{ email: "my@email.com", address: null }` @@ -5117,13 +5120,13 @@ console.log(member) ###### 155. Что будет на выходе? ```javascript -let randomValue = { name: "Lydia" } -randomValue = 23 +let randomValue = { name: "Lydia" }; +randomValue = 23; if (!typeof randomValue === "string") { - console.log("It's not a string!") + console.log("It's not a string!"); } else { - console.log("Yay it's a string!") + console.log("Yay it's a string!"); } ``` diff --git a/sq-KS/README_sq_KS.md b/sq-KS/README_sq_KS.md index aa1eb9dc..8446493c 100644 --- a/sq-KS/README_sq_KS.md +++ b/sq-KS/README_sq_KS.md @@ -10,9 +10,10 @@ Nga konceptet bazike tek ato të avancuara: testo se sa mirë e njeh JavaScript- Mos hezitoni të më kontaktoni! 😊 Instagram || Twitter || LinkedIn || Blog + -| Ndjehuni të lirë të i përdorni në projektet e juaja |😃 Do të e vlerësoja shumë referencimin tuaj në ketë repositori, unë i krijoj pyetjet dhe poashtu edhe përgjigjet (lol) dhe komuniteti me ndihmon shumë të e përmirësoj dhe të mirëmbajë! 💪🏼 Faleminderit! +| Ndjehuni të lirë të i përdorni në projektet e juaja |😃 Do të e vlerësoja shumë referencimin tuaj në ketë repositori, unë i krijoj pyetjet dhe poashtu edhe përgjigjet (lol) dhe komuniteti me ndihmon shumë të e përmirësoj dhe të mirëmbajë! 💪🏼 Faleminderit! --- @@ -32,6 +33,7 @@ Mos hezitoni të më kontaktoni! 😊 - [🇳🇱 Nederlands](../nl-NL/README.md) - [🇵🇱 Polski](../pl-PL/README.md) - [🇧🇷 Português Brasil](../pt-BR/README_pt_BR.md) +- [🇷o Română](../ro-RO/README.ro.md) - [🇷🇺 Русский](../ru-RU/README.md) - [🇽🇰 Shqip](./sq-KS/README_sq_KS.md) - [🇹🇭 ไทย](../th-TH/README-th_TH.md) @@ -46,13 +48,13 @@ Mos hezitoni të më kontaktoni! 😊 --- -###### 1. Cila është vlera e saj? +###### 1. Cila është vlera e saj? ```javascript function sayHi() { console.log(name); console.log(age); - var name = 'Lydia'; + var name = "Lydia"; let age = 21; } @@ -78,7 +80,7 @@ Variablat me fjalën kyçe `let` (dhe `const`) hoistohen, por ndryshe nga `var`, --- -###### 2. Cila është vlera e saj? +###### 2. Cila është vlera e saj? ```javascript for (var i = 0; i < 3; i++) { @@ -99,7 +101,7 @@ for (let i = 0; i < 3; i++) { #### Përgjigja: C -Për shkak të ***event queque*** në JavaScript, funksioni callback `setTimeout` thirret pas ekzekutimit të unazës. Pasi që variabla `i` në iterimin e parë u deklarua duke përdorur fjalën kyçe `var`, kjo vlerë ishte globale. Gjatë unazës, ne rritëm vlerën e `i` me `1` çdo herë, duke përdorur operatorin unar `++`. Deri në kohën që funksioni callback `setTimeout` u thirr, `i` ishte e barabartë me `3` në unazën e parë. +Për shkak të **_event queque_** në JavaScript, funksioni callback `setTimeout` thirret pas ekzekutimit të unazës. Pasi që variabla `i` në iterimin e parë u deklarua duke përdorur fjalën kyçe `var`, kjo vlerë ishte globale. Gjatë unazës, ne rritëm vlerën e `i` me `1` çdo herë, duke përdorur operatorin unar `++`. Deri në kohën që funksioni callback `setTimeout` u thirr, `i` ishte e barabartë me `3` në unazën e parë. Në unazën e dytë, variabla `i` u deklarua duke përdorur fjalën kyçe `let`: variablat e deklaruara me fjalën kyçe `let` (dhe `const`) janë të qasshme në bllok (një bllok është çdo gjë mes `{ }`). Gjatë çdo iteracioni, `i` do të ketë një vlerë të re, dhe çdo vlerë është e qasshme brenda unazës. @@ -148,7 +150,7 @@ Në funksionet shigjeta, fjala kyçe `this` referohet në qasjen në rrethinën ```javascript +true; -!'Lydia'; +!"Lydia"; ``` - A: `1` and `false` @@ -173,11 +175,11 @@ Vargu i karaktereve (stringu) `'Lydia'` konsiderohet si vlerë `true`. Çfarë n ```javascript const bird = { - size: 'small', + size: "small", }; const mouse = { - name: 'Mickey', + name: "Mickey", small: true, }; ``` @@ -208,11 +210,11 @@ Megjithatë, me notacionin pikë, kjo nuk ndodh. `mouse` nuk ka një çelës të ###### 6. Cila është vlera e saj? ```javascript -let c = { greeting: 'Hey!' }; +let c = { greeting: "Hey!" }; let d; d = c; -c.greeting = 'Hello'; +c.greeting = "Hello"; console.log(d.greeting); ``` @@ -266,7 +268,7 @@ console.log(b === c); Kur përdorim operatorin `==` (operatorin i barazimit), ai kontrollon vetëm nëse ka të njëjtën _vlerë_. Të dy kanë vlerën `3`, kështu që kthen `true`. -Megjithatë, kur përdorim operatorin `===` (operatori i barazisë strikte), të dy vlerat dhe tipi i tyre duhet të jenë të njëjta. Nuk është: `new Number()` nuk është një numër, është një __objekt__. Të dy kthejnë `false`. +Megjithatë, kur përdorim operatorin `===` (operatori i barazisë strikte), të dy vlerat dhe tipi i tyre duhet të jenë të njëjta. Nuk është: `new Number()` nuk është një numër, është një **objekt**. Të dy kthejnë `false`.

@@ -282,13 +284,13 @@ class Chameleon { return this.newColor; } - constructor({ newColor = 'green' } = {}) { + constructor({ newColor = "green" } = {}) { this.newColor = newColor; } } -const freddie = new Chameleon({ newColor: 'purple' }); -console.log(freddie.colorChange('orange')); +const freddie = new Chameleon({ newColor: "purple" }); +console.log(freddie.colorChange("orange")); ``` - A: `orange` @@ -343,10 +345,10 @@ Për të shmangur këtë, ne mund të përdorim `"use strict"`. Kjo siguron që ```javascript function bark() { - console.log('Woof!'); + console.log("Woof!"); } -bark.animal = 'dog'; +bark.animal = "dog"; ``` - A: Asgjë, gjithçka është në rregull! @@ -376,8 +378,8 @@ function Person(firstName, lastName) { this.lastName = lastName; } -const member = new Person('Lydia', 'Hallie'); -Person.getFullName = function() { +const member = new Person("Lydia", "Hallie"); +Person.getFullName = function () { return `${this.firstName} ${this.lastName}`; }; @@ -399,7 +401,7 @@ Në JavaScript, funksionet janë objekte dhe për këtë arsye metoda `getFullNa Nëse dëshironi që një metodë të jetë e qasshme për të gjitha instancat e objektit, duhet ta shtoni atë në vetinë e quajtur "prototype": ```js -Person.prototype.getFullName = function() { +Person.prototype.getFullName = function () { return `${this.firstName} ${this.lastName}`; }; ``` @@ -417,8 +419,8 @@ function Person(firstName, lastName) { this.lastName = lastName; } -const lydia = new Person('Lydia', 'Hallie'); -const sarah = Person('Sarah', 'Smith'); +const lydia = new Person("Lydia", "Hallie"); +const sarah = Person("Sarah", "Smith"); console.log(lydia); console.log(sarah); @@ -488,7 +490,7 @@ function sum(a, b) { return a + b; } -sum(1, '2'); +sum(1, "2"); ``` - A: `NaN` @@ -501,7 +503,7 @@ sum(1, '2'); #### Përgjigja: C -JavaScript është gjuhë e shkruar në mënyrë dinamike __dynamically typed language__: ne nuk specifikojmë se çfarë tipe janë variablat e caktuara. Vlerat mund të konvertohen automatikisht në një tip tjetër pa e ditur ju dhe ky proces quhet _implicit type coercion_ (shndërrimi i tipit në mënyrë të nënkuptuar). __Coercion__ është shndërrimi nga një tip në një tjetër. +JavaScript është gjuhë e shkruar në mënyrë dinamike **dynamically typed language**: ne nuk specifikojmë se çfarë tipe janë variablat e caktuara. Vlerat mund të konvertohen automatikisht në një tip tjetër pa e ditur ju dhe ky proces quhet _implicit type coercion_ (shndërrimi i tipit në mënyrë të nënkuptuar). **Coercion** është shndërrimi nga një tip në një tjetër. Në këtë shembull, JavaScript konverton numrin `1` në string, në mënyrë që për funksionin të ketë kuptim dhe të kthejë një vlerë. Përgjatë mbledhjes të një tipi number (`1`) dhe një tipi string (`'2'`), numri trajtohet si string. Ne mund ti bashkojmë stringjet si `"Hello" + "World"`, kështu që ajo që po ndodh këtu është `"1" + "2"` e cila kthen "12"`. @@ -555,7 +557,7 @@ function getPersonInfo(one, two, three) { console.log(three); } -const person = 'Lydia'; +const person = "Lydia"; const age = 21; getPersonInfo`${person} is ${age} years old`; @@ -582,9 +584,9 @@ Nëse përdorni literale të shabllonit (template literals) të etiketuar, vlera ```javascript function checkAge(data) { if (data === { age: 18 }) { - console.log('You are an adult!'); + console.log("You are an adult!"); } else if (data == { age: 18 }) { - console.log('You are still an adult.'); + console.log("You are still an adult."); } else { console.log(`Hmm.. You don't have an age I guess`); } @@ -644,7 +646,7 @@ Parametri "rest" (`...args`) na lejon të "mbledhim" të gjitha argumentet e mbe ```javascript function getAge() { - 'use strict'; + "use strict"; age = 21; console.log(age); } @@ -672,7 +674,7 @@ Me `"use strict"`, mund të siguroheni se nuk do të deklaroni variabla globale ###### 21. Sa do të jetë vlera e `sum`? ```javascript -const sum = eval('10*10+5'); +const sum = eval("10*10+5"); ``` - A: `105` @@ -695,7 +697,7 @@ const sum = eval('10*10+5'); ###### 22. Sa kohë është e qasshme cool_secret? ```javascript -sessionStorage.setItem('cool_secret', 123); +sessionStorage.setItem("cool_secret", 123); ``` - A: Përgjithmonë, e dhëna nuk humb. @@ -748,12 +750,12 @@ Ju nuk mund ta bëni këtë me 'let' ose 'const' pasi ato kanë qasje në bllok ###### 24. Cila është vlera e saj? ```javascript -const obj = { 1: 'a', 2: 'b', 3: 'c' }; +const obj = { 1: "a", 2: "b", 3: "c" }; const set = new Set([1, 2, 3, 4, 5]); -obj.hasOwnProperty('1'); +obj.hasOwnProperty("1"); obj.hasOwnProperty(1); -set.has('1'); +set.has("1"); set.has(1); ``` @@ -779,7 +781,7 @@ Nuk funksionon në këtë mënyrë për një "set". Nuk ka asnjë `'1'` në set- ###### 25. Cila është vlera e saj? ```javascript -const obj = { a: 'one', b: 'two', a: 'three' }; +const obj = { a: "one", b: "two", a: "three" }; console.log(obj); ``` @@ -848,12 +850,12 @@ Deklarata `continue` kalon një iterim nëse një kusht i caktuar kthen `true`. ```javascript String.prototype.giveLydiaPizza = () => { - return 'Just give Lydia pizza already!'; + return "Just give Lydia pizza already!"; }; -const name = 'Lydia'; +const name = "Lydia"; -console.log(name.giveLydiaPizza()) +console.log(name.giveLydiaPizza()); ``` - A: `"Just give Lydia pizza already!"` @@ -877,8 +879,8 @@ console.log(name.giveLydiaPizza()) ```javascript const a = {}; -const b = { key: 'b' }; -const c = { key: 'c' }; +const b = { key: "b" }; +const c = { key: "c" }; a[b] = 123; a[c] = 456; @@ -910,9 +912,9 @@ Pastaj ne e printojmë `a[b]` e cila është `a["[object Object]"]`. We sapo e v ###### 30. Cila është vlera e saj? ```javascript -const foo = () => console.log('First'); -const bar = () => setTimeout(() => console.log('Second')); -const baz = () => console.log('Third'); +const foo = () => console.log("First"); +const bar = () => setTimeout(() => console.log("Second")); +const baz = () => console.log("Third"); bar(); foo(); @@ -965,9 +967,7 @@ Këtu fillon të funksionojë event loop. Një **event loop** shikon "stack" dhe ```html
- +
``` @@ -993,9 +993,7 @@ Elementi më thellë i mbivendosur që shkaktoi ngjarjen është objektivi i ngj ```html
-

- Click here! -

+

Click here!

``` @@ -1019,7 +1017,7 @@ Nëse klikojmë `p`, shohim dy dalje: `p` dhe `div`. Gjatë "event propagation", ###### 33. Cila është vlera e saj? ```javascript -const person = { name: 'Lydia' }; +const person = { name: "Lydia" }; function sayHi(age) { return `${this.name} is ${age}`; @@ -1082,8 +1080,8 @@ FYI: `typeof` mund të kthejë listën e mëposhtme të vlerave: `undefined`, `b ```javascript 0; new Number(0); -(''); -(' '); +(""); +(" "); new Boolean(false); undefined; ``` @@ -1232,11 +1230,14 @@ Ajo që e dallon një tip primitiv nga një objekt është se primitivët nuk ka ###### 40. Cila është vlera e saj? ```javascript -[[0, 1], [2, 3]].reduce( +[ + [0, 1], + [2, 3], +].reduce( (acc, cur) => { return acc.concat(cur); }, - [1, 2], + [1, 2] ); ``` @@ -1263,7 +1264,7 @@ Pastaj, `[1, 2, 0, 1]` është `acc` dhe `[2, 3]` është `cur`. I bashkojmë at ```javascript !!null; -!!''; +!!""; !!1; ``` @@ -1291,7 +1292,7 @@ Pastaj, `[1, 2, 0, 1]` është `acc` dhe `[2, 3]` është `cur`. I bashkojmë at ###### 42. Çfarë do të kthejë në browser funksioni `setInterval`? ```javascript -setInterval(() => console.log('Hi'), 1000); +setInterval(() => console.log("Hi"), 1000); ``` - A: një id unike @@ -1314,7 +1315,7 @@ Kthen një id unike. Kjo id mund të përdoret për të pastruar intervalin me f ###### 43. Çfarë do të kthehet si rezultat? ```javascript -[...'Lydia']; +[..."Lydia"]; ``` - A: `["L", "y", "d", "i", "a"]` @@ -1334,7 +1335,7 @@ Stringu është i iterueshëm. Operatori i përhapjes (spread operator) iteron --- -###### 44. Cila është vlera e saj? +###### 44. Cila është vlera e saj? ```javascript function* generator(i) { @@ -1373,14 +1374,14 @@ Pastaj, ne e thirrim funksionin përsëri me metodën `next()`. Fillon dhe vazhd ```javascript const firstPromise = new Promise((res, rej) => { - setTimeout(res, 500, 'one'); + setTimeout(res, 500, "one"); }); const secondPromise = new Promise((res, rej) => { - setTimeout(res, 100, 'two'); + setTimeout(res, 100, "two"); }); -Promise.race([firstPromise, secondPromise]).then(res => console.log(res)); +Promise.race([firstPromise, secondPromise]).then((res) => console.log(res)); ``` - A: `"one"` @@ -1403,7 +1404,7 @@ Kur i kalojmë premtime (promises) të shumta metodës `Promise.race`, ajo zgjid ###### 46. Cila është vlera e saj? ```javascript -let person = { name: 'Lydia' }; +let person = { name: "Lydia" }; const members = [person]; person = null; @@ -1443,7 +1444,7 @@ Ne po e modifikojmë vetëm vlerën e variblës `person`, dhe jo të elementit t ```javascript const person = { - name: 'Lydia', + name: "Lydia", age: 21, }; @@ -1472,7 +1473,7 @@ Me unazën `for-in`, ne mund të iterojmë përgjatë çelësave të objektit, n ###### 48. Cila është vlera e saj? ```javascript -console.log(3 + 4 + '5'); +console.log(3 + 4 + "5"); ``` - A: `"345"` @@ -1499,7 +1500,7 @@ Radha e veprimeve matematikore të operatorit është rendi në të cilin përpi ###### 49. What's the value of `num`? ```javascript -const num = parseInt('7*6', 10); +const num = parseInt("7*6", 10); ``` - A: `42` @@ -1524,8 +1525,8 @@ Kthehen vetëm numrat e parë në string. Bazuar në _radix (bazë)_ (argumenti ###### 50. Cila është vlera e saj? ```javascript -[1, 2, 3].map(num => { - if (typeof num === 'number') return; +[1, 2, 3].map((num) => { + if (typeof num === "number") return; return num * 2; }); ``` @@ -1553,12 +1554,12 @@ Megjithatë, ne nuk kthejmë një vlerë. Kur nuk kthejmë një vlerë nga funks ```javascript function getInfo(member, year) { - member.name = 'Lydia'; - year = '1998'; + member.name = "Lydia"; + year = "1998"; } -const person = { name: 'Sarah' }; -const birthYear = '1997'; +const person = { name: "Sarah" }; +const birthYear = "1997"; getInfo(person, birthYear); @@ -1590,15 +1591,15 @@ Vlera e `person` është objekt. Argumenti `member` ka referencë (të kopjuar) ```javascript function greeting() { - throw 'Hello world!'; + throw "Hello world!"; } function sayHi() { try { const data = greeting(); - console.log('It worked!', data); + console.log("It worked!", data); } catch (e) { - console.log('Oh no an error:', e); + console.log("Oh no an error:", e); } } @@ -1628,8 +1629,8 @@ Me deklaratën `catch`, ne mund të specifikojmë se çfarë të bëjmë nëse n ```javascript function Car() { - this.make = 'Lamborghini'; - return { make: 'Maserati' }; + this.make = "Lamborghini"; + return { make: "Maserati" }; } const myCar = new Car(); @@ -1703,11 +1704,11 @@ class Dog { } } -Dog.prototype.bark = function() { +Dog.prototype.bark = function () { console.log(`Woof I am ${this.name}`); }; -const pet = new Dog('Mara'); +const pet = new Dog("Mara"); pet.bark(); @@ -1772,7 +1773,7 @@ export default counter; ```javascript // index.js -import myCounter from './counter'; +import myCounter from "./counter"; myCounter += 1; @@ -1801,7 +1802,7 @@ Kur tentojmë të rrisim vlerën e `myCounter`, do të marrim një error: `myCou ###### 58. Cila është vlera e saj? ```javascript -const name = 'Lydia'; +const name = "Lydia"; age = 21; console.log(delete name); @@ -1818,7 +1819,7 @@ console.log(delete age); #### Përgjigja: A -Operatori "delete" kthen një vlerë booleane: `true` në fshirje të suksesshme, përndryshe do të kthejë `false`. Megjithatë, variablat e deklaruara me fjalën kyçe `var`, `const` ose `let` nuk mund të fshihen duke përdorur operatorin `delete`. +Operatori "delete" kthen një vlerë booleane: `true` në fshirje të suksesshme, përndryshe do të kthejë `false`. Megjithatë, variablat e deklaruara me fjalën kyçe `var`, `const` ose `let` nuk mund të fshihen duke përdorur operatorin `delete`. Variabla `name` u deklarua me fjalën kyçe `const`, kështu që fshirja e saj nuk ishte e suksesshme: u kthye `false`. Kur vendosëm `age` të barabartë me `21`, ne në fakt shtuam një veti të quajtur `age` në objektin global. Ju mund të fshini me sukses vetitë nga objektet në këtë mënyrë, gjithashtu edhe objektin global, kështu që `delete age` kthen `true`. @@ -1872,7 +1873,7 @@ Kjo do të thotë se vlera e `y` është e barabartë me vlerën e parë në arr ###### 60. Cila është vlera e saj? ```javascript -const user = { name: 'Lydia', age: 21 }; +const user = { name: "Lydia", age: 21 }; const admin = { admin: true, ...user }; console.log(admin); @@ -1898,9 +1899,9 @@ console.log(admin); ###### 61. Cila është vlera e saj? ```javascript -const person = { name: 'Lydia' }; +const person = { name: "Lydia" }; -Object.defineProperty(person, 'age', { value: 21 }); +Object.defineProperty(person, "age", { value: 21 }); console.log(person); console.log(Object.keys(person)); @@ -1929,12 +1930,12 @@ Vetitë e shtuara duke përdorur metodën `defineProperty` janë të pandryshues ```javascript const settings = { - username: 'lydiahallie', + username: "lydiahallie", level: 19, health: 90, }; -const data = JSON.stringify(settings, ['level', 'health']); +const data = JSON.stringify(settings, ["level", "health"]); console.log(data); ``` @@ -1965,7 +1966,7 @@ Nëse zëvendësuesi është një _funksion_, ky funksion thirret në çdo veti let num = 10; const increaseNumber = () => num++; -const increasePassedNumber = number => number++; +const increasePassedNumber = (number) => number++; const num1 = increaseNumber(); const num2 = increasePassedNumber(num1); @@ -1986,7 +1987,7 @@ console.log(num2); Operatori unar `++` fillimisht kthen vlerën e operandit, pastaj e rrit vlerën e tij. Vlera e `num1` është `10`, meqenëse funksioni `increaseNumber` fillimisht kthen vlerën e `num`, e cila është `10`, dhe vetëm pastaj e rrit vlerën e `num`. -`num2` është `10`, pasi ne e kaluam `num1` si argument tek `increasePassedNumber`. `number` është i barabartë me `10`(vlera e `num1`). Përsëri, operatori unar `++` _së pari kthen_ vlerën e operandit, dhe pastaj rrit vlerën e tij. Vlera e `number` është `10`, kështu që `num2` është e barabartë me `10`. +`num2` është `10`, pasi ne e kaluam `num1` si argument tek `increasePassedNumber`. `number` është i barabartë me `10`(vlera e `num1`). Përsëri, operatori unar `++` _së pari kthen_ vlerën e operandit, dhe pastaj rrit vlerën e tij. Vlera e `number` është `10`, kështu që `num2` është e barabartë me `10`.

@@ -2122,12 +2123,12 @@ Klasa `Labrador` merr dy argumente, `name` meqenëse trashëgon klasën 'Dog', d ```javascript // index.js -console.log('running index.js'); -import { sum } from './sum.js'; +console.log("running index.js"); +import { sum } from "./sum.js"; console.log(sum(1, 2)); // sum.js -console.log('running sum.js'); +console.log("running sum.js"); export const sum = (a, b) => a + b; ``` @@ -2155,7 +2156,7 @@ Ky është një dallimi në mes `require()` në CommonJS dhe `import`! Me `requi ```javascript console.log(Number(2) === Number(2)); console.log(Boolean(false) === Boolean(false)); -console.log(Symbol('foo') === Symbol('foo')); +console.log(Symbol("foo") === Symbol("foo")); ``` - A: `true`, `true`, `false` @@ -2178,7 +2179,7 @@ console.log(Symbol('foo') === Symbol('foo')); ###### 69. Cila është vlera e saj? ```javascript -const name = 'Lydia Hallie'; +const name = "Lydia Hallie"; console.log(name.padStart(13)); console.log(name.padStart(2)); ``` @@ -2205,7 +2206,7 @@ Nëse argumenti i kaluar në metodën `padStart` është më i vogël se gjatës ###### 70. Cila është vlera e saj? ```javascript -console.log('🥑' + '💻'); +console.log("🥑" + "💻"); ``` - A: `"🥑💻"` @@ -2229,11 +2230,11 @@ Me operatorin `+`, ju mund të bashkoni vargjet. Në këtë rast, ne po bashkojm ```javascript function* startGame() { - const Përgjigja = yield 'Do you love JavaScript?'; - if (Përgjigja !== 'Yes') { + const Përgjigja = yield "Do you love JavaScript?"; + if (Përgjigja !== "Yes") { return "Oh wow... Guess we're done here"; } - return 'JavaScript loves you back ❤️'; + return "JavaScript loves you back ❤️"; } const game = startGame(); @@ -2271,7 +2272,7 @@ console.log(String.raw`Hello\nworld`); - A: `Hello world!` - B: `Hello`      `world` - C: `Hello\nworld` -- D: `Hello\n`      `world` +- D: `Hello\n`      `world`
Përgjigja

@@ -2301,7 +2302,7 @@ Në këtë rast, `Hello\nworld` do të printohet. ```javascript async function getData() { - return await Promise.resolve('I made it!'); + return await Promise.resolve("I made it!"); } const data = getData(); @@ -2338,7 +2339,7 @@ function addToList(item, list) { return list.push(item); } -const result = addToList('apple', ['banana']); +const result = addToList("apple", ["banana"]); console.log(result); ``` @@ -2398,7 +2399,7 @@ Meqenëse `shape` është e ngrirë dhe meqenëse vlera e `x` nuk është një o ###### 76. Cila është vlera e saj? ```javascript -const { firstName: myName } = { firstName: 'Lydia' }; +const { firstName: myName } = { firstName: "Lydia" }; console.log(firstName); ``` @@ -2416,7 +2417,7 @@ console.log(firstName); Duke përdorur [sintaksen e funksioneve destruktuese](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment) ne mund të targetojmë vlerat nga vargjet, ose vetitë nga objektet, në variabla të veçanta: ```javascript -const { firstName } = { firstName: 'Lydia' }; +const { firstName } = { firstName: "Lydia" }; // versioni i ES5: // var firstName = { firstName: 'Lydia' }.firstName; @@ -2426,7 +2427,7 @@ console.log(firstName); // "Lydia" Gjithashtu, një veti mund të targetohet nga një objekt dhe t'i caktohet një variableje me një emër të ndryshëm nga vetia e objektit: ```javascript -const { firstName: myName } = { firstName: 'Lydia' }; +const { firstName: myName } = { firstName: "Lydia" }; // versioni i ES5: // var myName = { firstName: 'Lydia' }.firstName; @@ -2436,21 +2437,20 @@ console.log(firstName); // Uncaught ReferenceError: firstName is not defined Prandaj, `firstName` nuk ekziston si variabël, kështu që tentimi për të qasur vlerën e saj do të ngrejë një `ReferenceError`. -**Shënim:** Kujdes nga vetitë e `global scope`: +**Shënim:** Kujdes nga vetitë e `global scope`: ```javascript -const { name: myName } = { name: 'Lydia' }; +const { name: myName } = { name: "Lydia" }; console.log(myName); // "lydia" console.log(name); // "" ----- Browser psh. Chrome console.log(name); // ReferenceError: name is not defined ----- NodeJS - ``` -Kurdo që JavaScript nuk mundet të gjejë një varibël në _current scope_, ngrihet në [Scope chain](https://github.com/getify/You-Dont-Know-JS/blob/2nd-ed/scope-closures/ch3.md) dhe kërkon për të dhe në qoftëse e arrin nivelin më të lartë të shtrirjes (the top-level scope), të quajtur __Global scope__, dhe ende nuk e gjen do të ngrejë `ReferenceError`. +Kurdo që JavaScript nuk mundet të gjejë një varibël në _current scope_, ngrihet në [Scope chain](https://github.com/getify/You-Dont-Know-JS/blob/2nd-ed/scope-closures/ch3.md) dhe kërkon për të dhe në qoftëse e arrin nivelin më të lartë të shtrirjes (the top-level scope), të quajtur **Global scope**, dhe ende nuk e gjen do të ngrejë `ReferenceError`. -- Në __Browsers__ si _Chrome_, `name` është _vetia e shtrirjes globale e vjetëruar_. Në këtë shembull, kodi funksionon brenda _global scope_ dhe nuk ka asnjë variabël lokale të përcaktuar nga përdoruesi për `name`, prandaj ai kërkon _variables/properties_ të paracaktuara në shtrirjen globale, në këtë rast shfletuesve, ai kërkon përmes objektit `window`, dhe do të nxjerrë vlerën [window.name](https://developer.mozilla.org/en-US/docs/Web/API/Window/name) e cila është e barabartë me një varg __bosh__. -- Në __NodeJS__, nuk ka një veçori të tillë në objektin `global`, kështu që përpjekja për të iu qasur një variable joekzistente do të ngrejë një [ReferenceError](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/Not_defined). +- Në **Browsers** si _Chrome_, `name` është _vetia e shtrirjes globale e vjetëruar_. Në këtë shembull, kodi funksionon brenda _global scope_ dhe nuk ka asnjë variabël lokale të përcaktuar nga përdoruesi për `name`, prandaj ai kërkon _variables/properties_ të paracaktuara në shtrirjen globale, në këtë rast shfletuesve, ai kërkon përmes objektit `window`, dhe do të nxjerrë vlerën [window.name](https://developer.mozilla.org/en-US/docs/Web/API/Window/name) e cila është e barabartë me një varg **bosh**. +- Në **NodeJS**, nuk ka një veçori të tillë në objektin `global`, kështu që përpjekja për të iu qasur një variable joekzistente do të ngrejë një [ReferenceError](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/Not_defined).

@@ -2482,12 +2482,12 @@ Funksioni `sum` _gjithmonë_ kthen të njëjtin rezultat. Nëse i kalojmë `1` d --- -###### 78. Cila është vlera e saj? +###### 78. Cila është vlera e saj? ```javascript const add = () => { const cache = {}; - return num => { + return (num) => { if (num in cache) { return `From cache! ${cache[num]}`; } else { @@ -2529,10 +2529,10 @@ Herën e tretë, ne kalojmë `5 * 2` te funksioni i cili llogaritet si `10`. Obj --- -###### 79. Cila është vlera e saj? +###### 79. Cila është vlera e saj? ```javascript -const myLifeSummedUp = ['☕', '💻', '🍷', '🍫']; +const myLifeSummedUp = ["☕", "💻", "🍷", "🍫"]; for (let item in myLifeSummedUp) { console.log(item); @@ -2559,14 +2559,14 @@ Me unazën _for-in_, ne mund të iterojmë në vetitë _e numërueshme_. Në nj Ku çelësat janë vetitë e numërueshme. `0` `1` `2` `3` printohet. -Me unazën _for-of_, ne mund të iterojmë mbi __iterables__. Një array është një "iterable". Kur iterojmë mbi array, variabla "item" është e barabartë me elementin mbi të cilin po iterojmë aktualisht, "☕"` `"💻"` `"🍷"` `"🍫"` printohet. +Me unazën _for-of_, ne mund të iterojmë mbi **iterables**. Një array është një "iterable". Kur iterojmë mbi array, variabla "item" është e barabartë me elementin mbi të cilin po iterojmë aktualisht, "☕"` `"💻"` `"🍷"` `"🍫"` printohet.

--- -###### 80. Cila është vlera e saj? +###### 80. Cila është vlera e saj? ```javascript const list = [1 + 2, 1 * 2, 1 / 2]; @@ -2592,7 +2592,7 @@ Elementi do të jetë i barabartë me vlerën e kthyer. `1 + 2` kthen `3`, `1 * --- -###### 81. Cila është vlera e saj? +###### 81. Cila është vlera e saj? ```javascript function sayHi(name) { @@ -2625,16 +2625,16 @@ Në këtë rast, nëse ne nuk kalojmë ndonjë vlerë ose e kalojmë `undefined` --- -###### 82. Cila është vlera e saj? +###### 82. Cila është vlera e saj? ```javascript -var status = '😎'; +var status = "😎"; setTimeout(() => { - const status = '😍'; + const status = "😍"; const data = { - status: '🥑', + status: "🥑", getStatus() { return this.status; }, @@ -2655,25 +2655,25 @@ setTimeout(() => { #### Përgjigja: B -Vlera e fjalës kyçe `this` varet nga vendi ku e përdorni. Në një __metodë__, si metoda `getStatus`, fjala kyçe `this` i referohet _objektit që i përket metoda_. Metoda i përket objektit `data`, kështu që `this` i referohet objektit `data`. Kur printojmë `this.status`, vetia `status` në objektin `data` printohet, që është `"🥑"`. +Vlera e fjalës kyçe `this` varet nga vendi ku e përdorni. Në një **metodë**, si metoda `getStatus`, fjala kyçe `this` i referohet _objektit që i përket metoda_. Metoda i përket objektit `data`, kështu që `this` i referohet objektit `data`. Kur printojmë `this.status`, vetia `status` në objektin `data` printohet, që është `"🥑"`. -Me metodën `call`, ne mund të ndryshojmë objektin të cilit i referohet fjala kyçe `this`. Në __funksione__, fjala kyçe `this` i referohet _objektit të cilit i përket funksioni_. Ne deklaruam funksionin `setTimeout` në objektin _global_, kështu që brenda funksionit `setTimeout`, fjala kyçe `this` i referohet objektit _global_. Në objektin global, ekziston një variabël e quajtur _status_ me vlerën `"😎"`. Kur printoni `this.status`, `"😎"` printohet. +Me metodën `call`, ne mund të ndryshojmë objektin të cilit i referohet fjala kyçe `this`. Në **funksione**, fjala kyçe `this` i referohet _objektit të cilit i përket funksioni_. Ne deklaruam funksionin `setTimeout` në objektin _global_, kështu që brenda funksionit `setTimeout`, fjala kyçe `this` i referohet objektit _global_. Në objektin global, ekziston një variabël e quajtur _status_ me vlerën `"😎"`. Kur printoni `this.status`, `"😎"` printohet.

--- -###### 83. Cila është vlera e saj? +###### 83. Cila është vlera e saj? ```javascript const person = { - name: 'Lydia', + name: "Lydia", age: 21, }; let city = person.city; -city = 'Amsterdam'; +city = "Amsterdam"; console.log(person); ``` @@ -2701,7 +2701,7 @@ Kur printojmë objektin `person`. objekti i pamodifikuar kthehet. --- -###### 84. Cila është vlera e saj? +###### 84. Cila është vlera e saj? ```javascript function checkAge(age) { @@ -2737,9 +2737,9 @@ Variablat e deklaruara me fjalët kyçe `const` dhe `let` janë të qasshme vet ###### 85. Çfarë lloj informacioni do të printohet? ```javascript -fetch('https://www.website.com/api/user/1') - .then(res => res.json()) - .then(res => console.log(res)); +fetch("https://www.website.com/api/user/1") + .then((res) => res.json()) + .then((res) => console.log(res)); ``` - A: Rezultati i metodës `fetch`. @@ -2793,7 +2793,7 @@ Kur vendosim `hasName` të barabartë me `name`, ju vendosni `hasName` të barab ###### 87. Cila është vlera e saj? ```javascript -console.log('I want pizza'[0]); +console.log("I want pizza"[0]); ``` - A: `"""` @@ -2848,11 +2848,11 @@ Në qoftëse provoni të vendosni një vlerë të paradefinuar të barabartë me ```javascript // module.js -export default () => 'Hello world'; -export const name = 'Lydia'; +export default () => "Hello world"; +export const name = "Lydia"; // index.js -import * as data from './module'; +import * as data from "./module"; console.log(data); ``` @@ -2885,7 +2885,7 @@ class Person { } } -const member = new Person('John'); +const member = new Person("John"); console.log(typeof member); ``` @@ -2934,7 +2934,7 @@ console.log(newList.push(5)); Metoda `.push` kthen _gjatësinë e re_ të array, jo vetë array! Duke vendosur `newList` të barabartë me `[1, 2, 3].push(4)`, e vendosim `newList` të barabartë me gjatësinë e re të array: `4`. -Pastaj, ne provojmë të përdorim metodën `.push` në `newList`. Meqenëse `newList` është vlera numerike e `4` ne nuk mund të përdorim metodën `.push`: do të ngrihet TypeError. +Pastaj, ne provojmë të përdorim metodën `.push` në `newList`. Meqenëse `newList` është vlera numerike e `4` ne nuk mund të përdorim metodën `.push`: do të ngrihet TypeError.

@@ -2945,7 +2945,7 @@ Pastaj, ne provojmë të përdorim metodën `.push` në `newList`. Meqenëse `n ```javascript function giveLydiaPizza() { - return 'Here is pizza!'; + return "Here is pizza!"; } const giveLydiaChocolate = () => @@ -2976,7 +2976,7 @@ Funskionet e rregullta, të tillë si funksioni `giveLydiaPizza`, kanë vetinë ```javascript const person = { - name: 'Lydia', + name: "Lydia", age: 21, }; @@ -3035,7 +3035,7 @@ function getItems(fruitList, favoriteFruit, ...args) { return [...fruitList, ...args, favoriteFruit]; } -getItems(['banana', 'apple'], 'pear', 'orange'); +getItems(["banana", "apple"], "pear", "orange"); ``` Shembulli i mësipërm funskionon. Do të kthejë array `[ 'banana', 'apple', 'orange', 'pear' ]` @@ -3049,9 +3049,9 @@ Shembulli i mësipërm funskionon. Do të kthejë array `[ 'banana', 'apple', 'o ```javascript function nums(a, b) { - if (a > b) console.log('a is bigger'); - else console.log('b is bigger'); - return + if (a > b) console.log("a is bigger"); + else console.log("b is bigger"); + return; a + b; } @@ -3069,7 +3069,7 @@ console.log(nums(1, 2)); #### Përgjigja: B -Në JavaScript, nuk e duhet të e shkruajmë pikëpresjen `;` në mënyrë eksplicite, sidoqoftë makina e JavaScript prapë i vendos ato pas deklarimeve. Kjo quhet __Automatic Semicolon Insertion__ (vendosja e pikëpresjes automatikisht). Një deklaratë për shembull mund të jetë variabla, ose fjalët kyçe si `throw`, `return`, `break` etj. +Në JavaScript, nuk e duhet të e shkruajmë pikëpresjen `;` në mënyrë eksplicite, sidoqoftë makina e JavaScript prapë i vendos ato pas deklarimeve. Kjo quhet **Automatic Semicolon Insertion** (vendosja e pikëpresjes automatikisht). Një deklaratë për shembull mund të jetë variabla, ose fjalët kyçe si `throw`, `return`, `break` etj. Në këtë rast, ne shkruajtëm deklaratën `return`, dhe vlerën tjetër `a + b` në rresht të ri. Sidoqoftë, meqenëse është rresht i ri, makina nuk e di se në të vërtetë ajo është vlera që ne po dëshirojmë të kthejmë. Në vend se të e llogarisë në atë mënyrë, në mënyrë automatike vendoset `return`. Kjo mund të shikohet edhe si kjo sintaksë: @@ -3090,13 +3090,13 @@ Kjo do të thotë se `a + b` nuk arrihet asnjëherë, meqenëse funksioni ndalon ```javascript class Person { constructor() { - this.name = 'Lydia'; + this.name = "Lydia"; } } Person = class AnotherPerson { constructor() { - this.name = 'Sarah'; + this.name = "Sarah"; } }; @@ -3125,7 +3125,7 @@ Ne mund të iu shoqërojmë klasave konstruktorët e tjerë të klasave/funksion ```javascript const info = { - [Symbol('a')]: 'b', + [Symbol("a")]: "b", }; console.log(info); @@ -3142,9 +3142,9 @@ console.log(Object.keys(info)); #### Përgjigja: D -Një Symbol nuk është i _numërueshëm_. Metoda Object.keys kthen të gjithë çelësat e _numërueshëm në një objekt. Symbol nuk do të jetë i dukshëm, dhe një array i zbrazët do të kthehet. Kur e printojmë objektin në tërësi, të gjitha vetitë janë të dukshme, edhe ato të cilat nuk janë te numërueshme. +Një Symbol nuk është i _numërueshëm_. Metoda Object.keys kthen të gjithë çelësat e \_numërueshëm në një objekt. Symbol nuk do të jetë i dukshëm, dhe një array i zbrazët do të kthehet. Kur e printojmë objektin në tërësi, të gjitha vetitë janë të dukshme, edhe ato të cilat nuk janë te numërueshme. -Kjo është vetëm një nga shumë vetitë e symbol, përveç përfaqësimit të një vlere krejtësisht unike (e cila parandalon konflikt në emërtim të objekteve, për shembull kur punoni me 2 librari që duan të shtojnë vetitë në të njëjtin objekt), ju gjithashtu mund të "fshehni" vetitë e objekteve në këtë mënyrë (edhe pse jo plotësisht. Ju mund t'i qaseni simboleve duke përdorur metodën `Object.getOwnPropertySymbols()`). +Kjo është vetëm një nga shumë vetitë e symbol, përveç përfaqësimit të një vlere krejtësisht unike (e cila parandalon konflikt në emërtim të objekteve, për shembull kur punoni me 2 librari që duan të shtojnë vetitë në të njëjtin objekt), ju gjithashtu mund të "fshehni" vetitë e objekteve në këtë mënyrë (edhe pse jo plotësisht. Ju mund t'i qaseni simboleve duke përdorur metodën `Object.getOwnPropertySymbols()`).

@@ -3194,7 +3194,7 @@ Funskioni i meposhtëm do të kthente një objekt: ###### 99. Cila është vlera e saj? ```javascript -const name = 'Lydia'; +const name = "Lydia"; console.log(name()); ``` @@ -3226,8 +3226,8 @@ ReferenceErrors ngrihen kur Javascript-i nuk është në gjendje të gjejë refe ```javascript // 🎉✨ Kjo është pytja jonë e 100! ✨🎉 -const output = `${[] && 'Im'}possible! -You should${'' && `n't`} see a therapist after so much JavaScript lol`; +const output = `${[] && "Im"}possible! +You should${"" && `n't`} see a therapist after so much JavaScript lol`; ``` - A: `possible! You should see a therapist after so much JavaScript lol` @@ -3253,7 +3253,7 @@ You should${'' && `n't`} see a therapist after so much JavaScript lol`; ```javascript const one = false || {} || null; -const two = null || false || ''; +const two = null || false || ""; const three = [] || 0 || true; console.log(one, two, three); @@ -3285,16 +3285,16 @@ Me operatorin `||`, ne mund të kthejmë vlerën e parë "truthy" të operandit. ###### 102. Cila është vlera në dalje? ```javascript -const myPromise = () => Promise.resolve('I have resolved!'); +const myPromise = () => Promise.resolve("I have resolved!"); function firstFunction() { - myPromise().then(res => console.log(res)); - console.log('second'); + myPromise().then((res) => console.log(res)); + console.log("second"); } async function secondFunction() { console.log(await myPromise()); - console.log('second'); + console.log("second"); } firstFunction(); @@ -3332,8 +3332,8 @@ Kjo do të thotë se pret për `myPromise` të zgjidhet me vlerën `I have resol const set = new Set(); set.add(1); -set.add('Lydia'); -set.add({ name: 'Lydia' }); +set.add("Lydia"); +set.add({ name: "Lydia" }); for (let item of set) { console.log(item + 2); @@ -3393,13 +3393,13 @@ Në këtë rast, ne vetëm i kaluam si argument vlerën numerike `5`. Kthen prom ```javascript function compareMembers(person1, person2 = person) { if (person1 !== person2) { - console.log('Not the same!'); + console.log("Not the same!"); } else { - console.log('They are the same!'); + console.log("They are the same!"); } } -const person = { name: 'Lydia' }; +const person = { name: "Lydia" }; compareMembers(person); ``` @@ -3416,7 +3416,7 @@ compareMembers(person); Objektet vendosen si argumente në bazë të referencës së tyre. Kur i kontrollojmë objektet me operatorin për barazim strikt (`===`), ne po kontorllojmë referencën e tyre. -Ne e paracaktuam vlerën e `person2` të barabartë me objektin `person`, dhe e kaluam objektin `person` si vlerë të `person1`. +Ne e paracaktuam vlerën e `person2` të barabartë me objektin `person`, dhe e kaluam objektin `person` si vlerë të `person1`. Kjo do të thotë që të dy vlerat kanë referencë të e njejta hapësirë memorike, dhe kështu ato janë të barabarta. @@ -3438,7 +3438,7 @@ const colorConfig = { yellow: false, }; -const colors = ['pink', 'red', 'blue']; +const colors = ["pink", "red", "blue"]; console.log(colorConfig.colors[1]); ``` @@ -3467,7 +3467,7 @@ JavaScript i interpreton deklarimet. Kur përdorim notacionin me kllapa të mëd ###### 107. Cila është vlera e saj? ```javascript -console.log('❤️' === '❤️'); +console.log("❤️" === "❤️"); ``` - A: `true` @@ -3488,14 +3488,14 @@ Në prapavijë, emoji-t janë kode të veçanta. Unikodet për emoji-t e zemrës ###### 108. Cila nga këto metoda e modifikon array origjinal? ```javascript -const emojis = ['✨', '🥑', '😍']; +const emojis = ["✨", "🥑", "😍"]; -emojis.map(x => x + '✨'); -emojis.filter(x => x !== '🥑'); -emojis.find(x => x !== '🥑'); -emojis.reduce((acc, cur) => acc + '✨'); -emojis.slice(1, 2, '✨'); -emojis.splice(1, 2, '✨'); +emojis.map((x) => x + "✨"); +emojis.filter((x) => x !== "🥑"); +emojis.find((x) => x !== "🥑"); +emojis.reduce((acc, cur) => acc + "✨"); +emojis.slice(1, 2, "✨"); +emojis.splice(1, 2, "✨"); ``` - A: `All of them` @@ -3520,10 +3520,10 @@ Me motodën `splice`, ne modifikojmë array origjinal duke fshirë, zëvendësua ###### 109. Cila është vlera e saj? ```javascript -const food = ['🍕', '🍫', '🥑', '🍔']; +const food = ["🍕", "🍫", "🥑", "🍔"]; const info = { favoriteFood: food[0] }; -info.favoriteFood = '🍝'; +info.favoriteFood = "🍝"; console.log(food); ``` @@ -3577,7 +3577,7 @@ const jsonArray = JSON.stringify([1, 2, 3]); // '[1, 2, 3]' JSON.parse(jsonArray); // [1, 2, 3] // Stringifimi i një objekti në JSON valid, pastaj parsimi i JSON stringut në një vlerë të JavaScript: -const jsonArray = JSON.stringify({ name: 'Lydia' }); // '{"name":"Lydia"}' +const jsonArray = JSON.stringify({ name: "Lydia" }); // '{"name":"Lydia"}' JSON.parse(jsonArray); // { name: 'Lydia' } ``` @@ -3589,11 +3589,11 @@ JSON.parse(jsonArray); // { name: 'Lydia' } ###### 111. Cila është vlera e saj? ```javascript -let name = 'Lydia'; +let name = "Lydia"; function getName() { console.log(name); - let name = 'Sarah'; + let name = "Sarah"; } getName(); @@ -3616,7 +3616,7 @@ Variablat me fjalën kyçe `let` (dhe `const`) ngriten (hoistoh-en), por për da Nëse nuk do të kishim deklaruar `name` brenda funksionit `getName`, makina e JavaScript do të kishte shikuar poshtë _zingjirit të shtrirjes_. Fusha e jashtme ka variabël të quajtur `name` me vlerë `Lydia`. Në këtë rast, do të kishte printuat `Lydia`. ```javascript -let name = 'Lydia'; +let name = "Lydia"; function getName() { console.log(name); @@ -3634,11 +3634,11 @@ getName(); // Lydia ```javascript function* generatorOne() { - yield ['a', 'b', 'c']; + yield ["a", "b", "c"]; } function* generatorTwo() { - yield* ['a', 'b', 'c']; + yield* ["a", "b", "c"]; } const one = generatorOne(); @@ -3684,7 +3684,7 @@ console.log(two.next().value); // undefined ###### 113. Cila është vlera e saj? ```javascript -console.log(`${(x => x)('I love')} to program`); +console.log(`${((x) => x)("I love")} to program`); ``` - A: `I love to program` @@ -3709,7 +3709,7 @@ Shprehjet brenda shablloneve literale vlerësohen së pari. Kjo do të thotë q ```javascript let config = { alert: setInterval(() => { - console.log('Alert!'); + console.log("Alert!"); }, 1000), }; @@ -3728,7 +3728,7 @@ config = null; Zakonisht kur i vendosim objektet të barabarta me `null`, ato objekte mirren nga _garbage collector_ pasi nuk ka më referencë për ato objekte. Megjithatë, meqenëse funksioni callback brenda `setInterval` është një funksion me shigjetë (pra i lidhur me objektin `config`), funksioni callback ende mban një referencë për objektin `config`. Për sa kohë ka një referencë, objekti nuk do të merret nga 'garbage collector' (menaxhuesi i memories për të u larguar). -Meqenëse ky është një interval, vendosja e `config` në '`null` ose `delete` `config.alert` nuk do të mbledhet nga garbage-collector për intervalin, kështu që intervali do të vazhdojë të thirret. +Meqenëse ky është një interval, vendosja e `config` në '`null` ose `delete` `config.alert` nuk do të mbledhet nga garbage-collector për intervalin, kështu që intervali do të vazhdojë të thirret. Për ta hequr nga memoria duhet të e pastrojmë me `clearInterval(config.alert)`. Meqenëse nuk u fshi, funksioni `setInterval` callback do të vazhdojë të thirret çdo 1000ms (1s). @@ -3741,16 +3741,16 @@ Meqenëse nuk u fshi, funksioni `setInterval` callback do të vazhdojë të thir ```javascript const myMap = new Map(); -const myFunc = () => 'greeting'; +const myFunc = () => "greeting"; -myMap.set(myFunc, 'Hello world!'); +myMap.set(myFunc, "Hello world!"); //1 -myMap.get('greeting'); +myMap.get("greeting"); //2 myMap.get(myFunc); //3 -myMap.get(() => 'greeting'); +myMap.get(() => "greeting"); ``` - A: 1 @@ -3777,14 +3777,14 @@ Kur shtoni një çift çelës/vlerë duke përdorur metodën `set`, çelësi do ```javascript const person = { - name: 'Lydia', + name: "Lydia", age: 21, }; const changeAge = (x = { ...person }) => (x.age += 1); const changeAgeAndName = (x = { ...person }) => { x.age += 1; - x.name = 'Sarah'; + x.name = "Sarah"; }; changeAge(person); @@ -3843,7 +3843,7 @@ Me operatorin spread `...`, me mund të _përhapim_ iteruesit në elemente indiv ```javascript let num = 1; -const list = ['🥳', '🤠', '🥰', '🤪']; +const list = ["🥳", "🤠", "🥰", "🤪"]; console.log(list[(num += 1)]); ``` @@ -3869,11 +3869,11 @@ Me operandin `+=`, ne po rrisim vlerën e `sum` për `1`. `num` kishte vlerën i ```javascript const person = { - firstName: 'Lydia', - lastName: 'Hallie', + firstName: "Lydia", + lastName: "Hallie", pet: { - name: 'Mara', - breed: 'Dutch Tulip Hound', + name: "Mara", + breed: "Dutch Tulip Hound", }, getFullName() { return `${this.firstName} ${this.lastName}`; @@ -3911,10 +3911,10 @@ Me operatorin opsional të zinxhirit `?.`, nuk duhet të kontrollojmë më në m ###### 120. Cila është vlera e saj? ```javascript -const groceries = ['banana', 'apple', 'peanuts']; +const groceries = ["banana", "apple", "peanuts"]; -if (groceries.indexOf('banana')) { - console.log('We have to buy bananas!'); +if (groceries.indexOf("banana")) { + console.log("We have to buy bananas!"); } else { console.log(`We don't have to buy bananas!`); } @@ -3970,10 +3970,10 @@ Metoda `language` është metodë `setter` (vendosëse). Vendosësit nuk mbajë ###### 122. Cila është vlera e saj? ```javascript -const name = 'Lydia Hallie'; +const name = "Lydia Hallie"; -console.log(!typeof name === 'object'); -console.log(!typeof name === 'string'); +console.log(!typeof name === "object"); +console.log(!typeof name === "string"); ``` - A: `false` `true` @@ -3998,7 +3998,7 @@ console.log(!typeof name === 'string'); ###### 123. Cila është vlera e saj? ```javascript -const add = x => y => z => { +const add = (x) => (y) => (z) => { console.log(x, y, z); return x + y + z; }; @@ -4016,7 +4016,7 @@ add(4)(5)(6); #### Përgjigja: A -Funksioni `add` kthen një funksion shigjete, i cili kthen një funksion shigjete, i cili kthen një funksion shigjete. Funksioni i parë merr një argument `x` me vlerën `4`. Ne e thërrasim funksionin e dytë, i cili merr një argument `y` me vlerën `5`. Pastaj thërrasim funksionin e tretë, i cili merr një argument `z` me vlerën `6`. Kur po provojmë të qasemi në vlerën `x`, `y` dhe `z` brenda funksionit të fundit të shigjetës, makina JS shkon lart në zinxhirin e shtrirjes për të gjetur vlerat për `x` dhe `y` përkatësisht. Kjo kthen `4` `5` `6`. +Funksioni `add` kthen një funksion shigjete, i cili kthen një funksion shigjete, i cili kthen një funksion shigjete. Funksioni i parë merr një argument `x` me vlerën `4`. Ne e thërrasim funksionin e dytë, i cili merr një argument `y` me vlerën `5`. Pastaj thërrasim funksionin e tretë, i cili merr një argument `z` me vlerën `6`. Kur po provojmë të qasemi në vlerën `x`, `y` dhe `z` brenda funksionit të fundit të shigjetës, makina JS shkon lart në zinxhirin e shtrirjes për të gjetur vlerat për `x` dhe `y` përkatësisht. Kjo kthen `4` `5` `6`.

@@ -4088,20 +4088,20 @@ myFunc(1, 2, 3); ```javascript function getFine(speed, amount) { - const formattedSpeed = new Intl.NumberFormat('en-US', { - style: 'unit', - unit: 'mile-per-hour' + const formattedSpeed = new Intl.NumberFormat("en-US", { + style: "unit", + unit: "mile-per-hour", }).format(speed); - const formattedAmount = new Intl.NumberFormat('en-US', { - style: 'currency', - currency: 'USD' + const formattedAmount = new Intl.NumberFormat("en-US", { + style: "currency", + currency: "USD", }).format(amount); return `The driver drove ${formattedSpeed} and has to pay ${formattedAmount}`; } -console.log(getFine(130, 300)) +console.log(getFine(130, 300)); ``` - A: The driver drove 130 and has to pay 300 @@ -4124,8 +4124,8 @@ Me metoden `Intl.NumberFormat`, ne mund të formatojmë vlerat numerike në çdo ###### 127. Cila është vlera e saj? ```javascript -const spookyItems = ['👻', '🎃', '🕸']; -({ item: spookyItems[3] } = { item: '💀' }); +const spookyItems = ["👻", "🎃", "🕸"]; +({ item: spookyItems[3] } = { item: "💀" }); console.log(spookyItems); ``` @@ -4150,7 +4150,7 @@ Duke destrukturuar objektet, ne mund të targetojmë vlerat nga objekti i djatht ###### 128. Cila është vlera e saj? ```javascript -const name = 'Lydia Hallie'; +const name = "Lydia Hallie"; const age = 21; console.log(Number.isNaN(name)); @@ -4186,7 +4186,7 @@ const randomValue = 21; function getInfo() { console.log(typeof randomValue); - const randomValue = 'Lydia Hallie'; + const randomValue = "Lydia Hallie"; } getInfo(); @@ -4212,7 +4212,7 @@ Variablat e deklaruara me fjalën kyçe `const` nuk janë të referueshme para i ###### 130. Cila është vlera e saj? ```javascript -const myPromise = Promise.resolve('Woah some cool data'); +const myPromise = Promise.resolve("Woah some cool data"); (async () => { try { @@ -4220,7 +4220,7 @@ const myPromise = Promise.resolve('Woah some cool data'); } catch { throw new Error(`Oops didn't work`); } finally { - console.log('Oh finally!'); + console.log("Oh finally!"); } })(); ``` @@ -4245,7 +4245,7 @@ Në bllokun `try`, ne jemi duke printuar vlerën e pritur të variablës `myProm ###### 131. Cila është vlera e saj? ```javascript -const emojis = ['🥑', ['✨', '✨', ['🍕', '🍕']]]; +const emojis = ["🥑", ["✨", "✨", ["🍕", "🍕"]]]; console.log(emojis.flat(1)); ``` @@ -4318,19 +4318,19 @@ Ne thërrasim `counterTwo.increment()`, i cili vendos `count` në `3`. Pastaj, p ###### 133. Cila është vlera e saj? ```javascript -const myPromise = Promise.resolve(Promise.resolve('Promise')); +const myPromise = Promise.resolve(Promise.resolve("Promise")); function funcOne() { - setTimeout(() => console.log('Timeout 1!'), 0); - myPromise.then(res => res).then(res => console.log(`${res} 1!`)); - console.log('Last line 1!'); + setTimeout(() => console.log("Timeout 1!"), 0); + myPromise.then((res) => res).then((res) => console.log(`${res} 1!`)); + console.log("Last line 1!"); } async function funcTwo() { const res = await myPromise; - console.log(`${res} 2!`) - setTimeout(() => console.log('Timeout 2!'), 0); - console.log('Last line 2!'); + console.log(`${res} 2!`); + setTimeout(() => console.log("Timeout 2!"), 0); + console.log("Last line 2!"); } funcOne(); @@ -4375,7 +4375,7 @@ export default function sum(x) { } // index.js -import * as sum from './sum'; +import * as sum from "./sum"; ``` - A: `sum(4)` @@ -4392,12 +4392,12 @@ Me yllin `*`, ne importojmë të gjitha vlerat e eksportuara nga ai fajll, si at ```javascript // info.js -export const name = 'Lydia'; +export const name = "Lydia"; export const age = 21; -export default 'I love JavaScript'; +export default "I love JavaScript"; // index.js -import * as info from './info'; +import * as info from "./info"; console.log(info); ``` @@ -4428,13 +4428,13 @@ Mund të e thërrasim këtë funksion, duke thirrur `sum.default` ```javascript const handler = { - set: () => console.log('Added a new property!'), - get: () => console.log('Accessed a property!'), + set: () => console.log("Added a new property!"), + get: () => console.log("Accessed a property!"), }; const person = new Proxy({}, handler); -person.name = 'Lydia'; +person.name = "Lydia"; person.name; ``` @@ -4464,7 +4464,7 @@ Pastaj, ne i qasemi një vlerë të vetisë në objektin proxy, vetia `get` në ###### 136. Cili nga opsionet e mëposhtme do të modifikojë objektin `person`? ```javascript -const person = { name: 'Lydia Hallie' }; +const person = { name: "Lydia Hallie" }; Object.seal(person); ``` @@ -4492,9 +4492,9 @@ Megjithatë, ju ende mund të modifikoni vlerën e vetive ekzistuese. ```javascript const person = { - name: 'Lydia Hallie', + name: "Lydia Hallie", address: { - street: '100 Main St', + street: "100 Main St", }, }; @@ -4523,7 +4523,7 @@ Megjithatë, ajo vetëm _ngrin sipërfaqësisht_ objektin, që do të thotë se ###### 138. Cila është vlera e saj? ```javascript -const add = x => x + x; +const add = (x) => x + x; function myFunc(num = 2, value = add(num)) { console.log(num, value); @@ -4556,21 +4556,21 @@ Më pas, ne thirrëm `myFunc(3)` dhe kaluam vlerën `3` si vlerë për argumenti ```javascript class Counter { - #number = 10 + #number = 10; increment() { - this.#number++ + this.#number++; } getNum() { - return this.#number + return this.#number; } } -const counter = new Counter() -counter.increment() +const counter = new Counter(); +counter.increment(); -console.log(counter.#number) +console.log(counter.#number); ``` - A: `10` @@ -4594,8 +4594,8 @@ Në ES2020, mund të shtojmë variabla private në klasa duke përdorur `#`. Nuk ```javascript const teams = [ - { name: 'Team 1', members: ['Paul', 'Lisa'] }, - { name: 'Team 2', members: ['Laura', 'Tim'] }, + { name: "Team 1", members: ["Paul", "Lisa"] }, + { name: "Team 2", members: ["Laura", "Tim"] }, ]; function* getMembers(members) { @@ -4638,8 +4638,8 @@ Nëse do të shkruanim `yield`, `return yield`, ose `return`, gjithë funksioni ```javascript const person = { - name: 'Lydia Hallie', - hobbies: ['coding'], + name: "Lydia Hallie", + hobbies: ["coding"], }; function addHobby(hobby, hobbies = person.hobbies) { @@ -4647,9 +4647,9 @@ function addHobby(hobby, hobbies = person.hobbies) { return hobbies; } -addHobby('running', []); -addHobby('dancing'); -addHobby('baking', person.hobbies); +addHobby("running", []); +addHobby("dancing"); +addHobby("baking", person.hobbies); console.log(person.hobbies); ``` @@ -4718,11 +4718,11 @@ Krijojmë variablën `pet` që është një instancë e klasës `Flamingo`. Kur ###### 143. Cila nga opsionet rezulton me gabim? ```javascript -const emojis = ['🎄', '🎅🏼', '🎁', '⭐']; +const emojis = ["🎄", "🎅🏼", "🎁", "⭐"]; -/* 1 */ emojis.push('🦌'); +/* 1 */ emojis.push("🦌"); /* 2 */ emojis.splice(0, 2); -/* 3 */ emojis = [...emojis, '🥂']; +/* 3 */ emojis = [...emojis, "🥂"]; /* 4 */ emojis.length = 0; ``` @@ -4777,11 +4777,11 @@ Objektet nuk janë të paraprakisht të iterueshme. Një objekt është i iterue let count = 0; const nums = [0, 1, 2, 3]; -nums.forEach(num => { - if (num) count += 1 -}) +nums.forEach((num) => { + if (num) count += 1; +}); -console.log(count) +console.log(count); ``` - A: 1 @@ -4805,12 +4805,12 @@ Kushti `if` brenda ciklit `forEach` kontrollon nëse vlera e `num` është e vë ```javascript function getFruit(fruits) { - console.log(fruits?.[1]?.[1]) + console.log(fruits?.[1]?.[1]); } -getFruit([['🍊', '🍌'], ['🍍']]) -getFruit() -getFruit([['🍍'], ['🍊', '🍌']]) +getFruit([["🍊", "🍌"], ["🍍"]]); +getFruit(); +getFruit([["🍍"], ["🍊", "🍌"]]); ``` - A: `null`, `undefined`, 🍌 @@ -4825,7 +4825,7 @@ getFruit([['🍍'], ['🍊', '🍌']]) Simboli ? na lejon të i qasemi opsionalisht vetive më të thella brenda objekteve. Ne po provojmë të shfaqim elementin në indeksin 1 brenda në nën-array që është në indeksin 1 të array fruits. Nëse nën-array në indeksin 1 në array fruits nuk ekziston, thjesht do të kthejë undefined. Nëse nën-array në indeksin 1 në vargun fruits ekziston, por ky nën-array nuk ka një artikull në indeksin e tij 1, gjithashtu do të kthejë undefined. -Së pari, ne po përpiqemi të printojmë artikullin e dytë në nën-array `['🍍']` të `[['🍊', '🍌'], ['🍍']]`. Ky nën-array përmban vetëm një element, që do të thotë se nuk ka element në indeksin `1`, dhe kthen `undefined`. +Së pari, ne po përpiqemi të printojmë artikullin e dytë në nën-array `['🍍']` të `[['🍊', '🍌'], ['🍍']]`. Ky nën-array përmban vetëm një element, që do të thotë se nuk ka element në indeksin `1`, dhe kthen `undefined`. Më pas, ne po thërrasim funksionin `getFruits` pa kaluar një vlerë si argument, që do të thotë se `fruits` ka vlerë `undefined` të paracaktuar. Pasi që po lidhim në mënyrë kushtëzuese elementin në indeksin `1` të `fruits`, kthen `undefined` pasi ky element në indeksin `1` nuk ekziston. @@ -4840,19 +4840,19 @@ Së fundmi, po përpiqemi të shfaqim artikullin e dytë në nën-array `['🍊' ```javascript class Calc { - constructor() { - this.count = 0 - } + constructor() { + this.count = 0; + } - increase() { - this.count ++ - } + increase() { + this.count++; + } } -const calc = new Calc() -new Calc().increase() +const calc = new Calc(); +new Calc().increase(); -console.log(calc.count) +console.log(calc.count); ``` - A: `0` @@ -4876,25 +4876,25 @@ Ne i caktojmë variablës `calc` të jetë e barabartë me një instancë të re ```javascript const user = { - email: "e@mail.com", - password: "12345" -} + email: "e@mail.com", + password: "12345", +}; const updateUser = ({ email, password }) => { - if (email) { - Object.assign(user, { email }) - } + if (email) { + Object.assign(user, { email }); + } - if (password) { - user.password = password - } + if (password) { + user.password = password; + } - return user -} + return user; +}; -const updatedUser = updateUser({ email: "new@email.com" }) +const updatedUser = updateUser({ email: "new@email.com" }); -console.log(updatedUser === user) +console.log(updatedUser === user); ``` - A: `false` @@ -4917,13 +4917,13 @@ Funksioni `updateUser` përditëson vlerat e vetive `email` dhe `password` në u ###### 149. Cila është vlera e saj? ```javascript -const fruit = ['🍌', '🍊', '🍎'] +const fruit = ["🍌", "🍊", "🍎"]; -fruit.slice(0, 1) -fruit.splice(0, 1) -fruit.unshift('🍇') +fruit.slice(0, 1); +fruit.splice(0, 1); +fruit.unshift("🍇"); -console.log(fruit) +console.log(fruit); ``` - A: `['🍌', '🍊', '🍎']` @@ -4949,13 +4949,13 @@ Në fund, ne thirrim metodën `unshift` në array e frutave, e cila modifikon ar ```javascript const animals = {}; -let dog = { emoji: '🐶' } -let cat = { emoji: '🐈' } +let dog = { emoji: "🐶" }; +let cat = { emoji: "🐈" }; -animals[dog] = { ...dog, name: "Mara" } -animals[cat] = { ...cat, name: "Sara" } +animals[dog] = { ...dog, name: "Mara" }; +animals[cat] = { ...cat, name: "Sara" }; -console.log(animals[dog]) +console.log(animals[dog]); ``` - A: `{ emoji: "🐶", name: "Mara" }` @@ -4985,14 +4985,14 @@ Duke printuar `animals[dog]`, ose në fakt `animals["object Object"]` pasi që k ```javascript const user = { - email: "my@email.com", - updateEmail: email => { - this.email = email - } -} + email: "my@email.com", + updateEmail: (email) => { + this.email = email; + }, +}; -user.updateEmail("new@email.com") -console.log(user.email) +user.updateEmail("new@email.com"); +console.log(user.email); ``` - A: `my@email.com` @@ -5015,20 +5015,20 @@ Funksioni `updateEmail` është një funksion shigjetë dhe nuk është i lidhur ###### 152. Cila është vlera e saj? ```javascript -const promise1 = Promise.resolve('First') -const promise2 = Promise.resolve('Second') -const promise3 = Promise.reject('Third') -const promise4 = Promise.resolve('Fourth') +const promise1 = Promise.resolve("First"); +const promise2 = Promise.resolve("Second"); +const promise3 = Promise.reject("Third"); +const promise4 = Promise.resolve("Fourth"); const runPromises = async () => { - const res1 = await Promise.all([promise1, promise2]) - const res2 = await Promise.all([promise3, promise4]) - return [res1, res2] -} + const res1 = await Promise.all([promise1, promise2]); + const res2 = await Promise.all([promise3, promise4]); + return [res1, res2]; +}; runPromises() - .then(res => console.log(res)) - .catch(err => console.log(err)) + .then((res) => console.log(res)) + .catch((err) => console.log(err)); ``` - A: `[['First', 'Second'], ['Fourth']]` @@ -5051,13 +5051,16 @@ Metoda `Promise.all` ekzekuton premtimet e dhëna si argumente paralelisht. Nës ###### 153. Cila duhet të jetë vlera e `method` për të printuar `{ name: "Lydia", age: 22 }`? ```javascript -const keys = ["name", "age"] -const values = ["Lydia", 22] +const keys = ["name", "age"]; +const values = ["Lydia", 22]; -const method = /* ?? */ -Object[method](keys.map((_, i) => { - return [keys[i], values[i]] -})) // { name: "Lydia", age: 22 } +const method = + /* ?? */ + Object[method]( + keys.map((_, i) => { + return [keys[i], values[i]]; + }) + ); // { name: "Lydia", age: 22 } ``` - A: `entries` @@ -5070,7 +5073,7 @@ Object[method](keys.map((_, i) => { #### Përgjigja: C -Metoda `fromEntries` transformon një array 2d në një objekt. Elementi i parë në çdo nën-array do të jetë çelësi, dhe elementi i dytë në çdo nën-array do të jetë vlera. Në këtë rast, ne jemi duke mapuar mbi array `keys`, i cili kthen një array ku elementi i parë është elementi në array të çelësave në indeksin aktual, dhe elementi i dytë është elementi i vlerave të array në indeksin aktual. +Metoda `fromEntries` transformon një array 2d në një objekt. Elementi i parë në çdo nën-array do të jetë çelësi, dhe elementi i dytë në çdo nën-array do të jetë vlera. Në këtë rast, ne jemi duke mapuar mbi array `keys`, i cili kthen një array ku elementi i parë është elementi në array të çelësave në indeksin aktual, dhe elementi i dytë është elementi i vlerave të array në indeksin aktual. Kjo krijon një array të nën-arrays që përmbajnë çelësat dhe vlerat e duhura, të cilat rezultojnë në `{ name: "Lydia", age: 22 }` @@ -5082,18 +5085,18 @@ Kjo krijon një array të nën-arrays që përmbajnë çelësat dhe vlerat e duh ###### 154. Cila është vlera e saj? ```javascript -const createMember = ({ email, address = {}}) => { - const validEmail = /.+\@.+\..+/.test(email) - if (!validEmail) throw new Error("Valid email pls") +const createMember = ({ email, address = {} }) => { + const validEmail = /.+\@.+\..+/.test(email); + if (!validEmail) throw new Error("Valid email pls"); - return { - email, - address: address ? address : null - } -} + return { + email, + address: address ? address : null, + }; +}; -const member = createMember({ email: "my@email.com" }) -console.log(member) +const member = createMember({ email: "my@email.com" }); +console.log(member); ``` - A: `{ email: "my@email.com", address: null }` @@ -5116,13 +5119,13 @@ Vlera e paracaktuar e `address` është një objekt i zbrazët `{}`. Kur vendos ###### 155. Cila është vlera e saj? ```javascript -let randomValue = { name: "Lydia" } -randomValue = 23 +let randomValue = { name: "Lydia" }; +randomValue = 23; if (!typeof randomValue === "string") { - console.log("It's not a string!") + console.log("It's not a string!"); } else { - console.log("Yay it's a string!") + console.log("Yay it's a string!"); } ``` diff --git a/th-TH/README.md b/th-TH/README.md index 22550eb2..edcb70ce 100644 --- a/th-TH/README.md +++ b/th-TH/README.md @@ -16,8 +16,8 @@ - ลิสต์ภาษาอื่นๆ: + - [🇸🇦 العربية](../ar-AR/README_AR.md) - [🇪🇬 اللغة العامية](../ar-EG/README_ar-EG.md) - [🇧🇦 Bosanski](../bs-BS/README-bs_BS.md) @@ -32,6 +32,7 @@ - [🇳🇱 Nederlands](../nl-NL/README.md) - [🇵🇱 Polski](../pl-PL/README.md) - [🇧🇷 Português Brasil](../pt-BR/README_pt_BR.md) +- [🇷o Română](../ro-RO/README.ro.md) - [🇷🇺 Русский](../ru-RU/README.md) - [🇽🇰 Shqip](../sq-KS/README_sq_KS.md) - [🇹🇷 Türkçe](../tr-TR/README-tr_TR.md) @@ -40,7 +41,6 @@ - [🇨🇳 简体中文](../zh-CN/README-zh_CN.md) - [🇹🇼 繁體中文](../zh-TW/README_zh-TW.md) - --- ###### 1. ผลลัพธ์ที่ได้คืออะไร? @@ -113,7 +113,7 @@ const shape = { diameter() { return this.radius * 2; }, - perimeter: () => 2 * Math.PI * this.radius + perimeter: () => 2 * Math.PI * this.radius, }; console.log(shape.diameter()); @@ -170,12 +170,12 @@ String `'Lydia'` เป็นค่าความจริง สิ่งท ```javascript const bird = { - size: "small" + size: "small", }; const mouse = { name: "Mickey", - small: true + small: true, }; ``` @@ -202,7 +202,6 @@ JavaScript interprets (or unboxes) statements. เมื่อเราใช้ --- - ###### 6. ผลลัพธ์ที่ได้คืออะไร? ```javascript @@ -370,7 +369,7 @@ function Person(firstName, lastName) { } const member = new Person("Lydia", "Hallie"); -Person.getFullName = function() { +Person.getFullName = function () { return `${this.firstName} ${this.lastName}`; }; @@ -390,7 +389,7 @@ console.log(member.getFullName()); You can't add properties to a constructor like you can with regular objects. If you want to add a feature to all objects at once, you have to use the prototype instead. So in this case, ```js -Person.prototype.getFullName = function() { +Person.prototype.getFullName = function () { return `${this.firstName} ${this.lastName}`; }; ``` @@ -846,7 +845,7 @@ String.prototype.giveLydiaPizza = () => { const name = "Lydia"; -console.log(name.giveLydiaPizza()) +console.log(name.giveLydiaPizza()); ``` - A: `"Just give Lydia pizza already!"` @@ -958,9 +957,7 @@ This is where an event loop starts to work. An **event loop** looks at the stack ```html
- +
``` @@ -986,9 +983,7 @@ The deepest nested element that caused the event is the target of the event. You ```html
-

- Click here! -

+

Click here!

``` @@ -1064,6 +1059,7 @@ console.log(typeof sayHi()); The `sayHi` function returns the returned value of the immediately invoked function (IIFE). This function returned `0`, which is type `"number"`. FYI: there are only 7 built-in types: `null`, `undefined`, `boolean`, `number`, `string`, `object`, `symbol`, และ `bigint`. `"function"` is not a type, since functions are objects, it's of type `"object"`. +

@@ -1222,7 +1218,10 @@ What differentiates a primitive from an object is that primitives do not have an ###### 40. ผลลัพธ์ที่ได้คืออะไร? ```javascript -[[0, 1], [2, 3]].reduce( +[ + [0, 1], + [2, 3], +].reduce( (acc, cur) => { return acc.concat(cur); }, @@ -1370,7 +1369,7 @@ const secondPromise = new Promise((res, rej) => { setTimeout(res, 100, "two"); }); -Promise.race([firstPromise, secondPromise]).then(res => console.log(res)); +Promise.race([firstPromise, secondPromise]).then((res) => console.log(res)); ``` - A: `"one"` @@ -1434,7 +1433,7 @@ We are only modifying the value of the `person` variable, and not the first elem ```javascript const person = { name: "Lydia", - age: 21 + age: 21, }; for (const item in person) { @@ -1514,7 +1513,7 @@ Only the first numbers in the string is returned. Based on the _radix_ (the seco ###### 50. ผลลัพธ์ที่ได้คืออะไร? ```javascript -[1, 2, 3].map(num => { +[1, 2, 3].map((num) => { if (typeof num === "number") return; return num * 2; }); @@ -1691,7 +1690,7 @@ class Dog { } } -Dog.prototype.bark = function() { +Dog.prototype.bark = function () { console.log(`Woof I am ${this.name}`); }; @@ -1919,7 +1918,7 @@ Properties added using the `defineProperty` method are immutable by default. You const settings = { username: "lydiahallie", level: 19, - health: 90 + health: 90, }; const data = JSON.stringify(settings, ["level", "health"]); @@ -1953,7 +1952,7 @@ If the replacer is a _function_, this function gets called on every property in let num = 10; const increaseNumber = () => num++; -const increasePassedNumber = number => number++; +const increasePassedNumber = (number) => number++; const num1 = increaseNumber(); const num2 = increasePassedNumber(num1); @@ -2010,9 +2009,9 @@ In ES6, we can initialize parameters with a default value. The value of the para The default argument is evaluated at _call time_! Every time we call the function, a _new_ object is created. We invoke the `multiply` function the first two times without passing a value: `x` has the default value of `{ number: 10 }`. We then log the multiplied value of that number, which is `20`. -The third time we invoke multiply, we do pass an argument: the object called `value`. The `*=` operator is actually shorthand for `x.number = x.number * 2`: we modify the value of `x.number`, and log the multiplied value `20`. +The third time we invoke multiply, we do pass an argument: the object called `value`. The `*=` operator is actually shorthand for `x.number = x.number * 2`: we modify the value of `x.number`, and log the multiplied value `20`. -The fourth time, we pass the `value` object again. `x.number` was previously modified to `20`, so `x.number *= 2` logs `40`. +The fourth time, we pass the `value` object again. `x.number` was previously modified to `20`, so `x.number *= 2` logs `40`.

@@ -2035,17 +2034,18 @@ The fourth time, we pass the `value` object again. `x.number` was previously mod #### คำตอบ: D -The first argument that the `reduce` method receives is the _accumulator_, `x` in this case. The second argument is the _current value_, `y`. With the reduce method, we execute a callback function on every element in the array, which could ultimately result in one single value. +The first argument that the `reduce` method receives is the _accumulator_, `x` in this case. The second argument is the _current value_, `y`. With the reduce method, we execute a callback function on every element in the array, which could ultimately result in one single value. In this example, we are not returning any values, we are simply logging the values of the accumulator and the current value. The value of the accumulator is equal to the previously returned value of the callback function. If you don't pass the optional `initialValue` argument to the `reduce` method, the accumulator is equal to the first element on the first call. -On the first call, the accumulator (`x`) is `1`, and the current value (`y`) is `2`. We don't return from the callback function, we log the accumulator and current value: `1` และ `2` get logged. +On the first call, the accumulator (`x`) is `1`, and the current value (`y`) is `2`. We don't return from the callback function, we log the accumulator and current value: `1` และ `2` get logged. -If you don't return a value from a function, it returns `undefined`. On the next call, the accumulator is `undefined`, and the current value is `3`. `undefined` และ `3` get logged. +If you don't return a value from a function, it returns `undefined`. On the next call, the accumulator is `undefined`, and the current value is `3`. `undefined` และ `3` get logged. On the fourth call, we again don't return from the callback function. The accumulator is again `undefined`, and the current value is `4`. `undefined` และ `4` get logged. +

@@ -2061,7 +2061,7 @@ class Dog { }; class Labrador extends Dog { - // 1 + // 1 constructor(name, size) { this.size = size; } @@ -2075,7 +2075,7 @@ class Labrador extends Dog { super(name); this.size = size; } - // 4 + // 4 constructor(name, size) { this.name = name; this.size = size; @@ -2096,9 +2096,10 @@ class Labrador extends Dog { In a derived class, you cannot access the `this` keyword before calling `super`. If you try to do that, it will throw a ReferenceError: 1 and 4 would throw a reference error. -With the `super` keyword, we call that parent class's constructor with the given arguments. The parent's constructor receives the `name` argument, so we need to pass `name` to `super`. +With the `super` keyword, we call that parent class's constructor with the given arguments. The parent's constructor receives the `name` argument, so we need to pass `name` to `super`. + +The `Labrador` class receives two arguments, `name` since it extends `Dog`, และ `size` as an extra property on the `Labrador` class. They both need to be passed to the constructor function on `Labrador`, which is done correctly using constructor 2. -The `Labrador` class receives two arguments, `name` since it extends `Dog`, และ `size` as an extra property on the `Labrador` class. They both need to be passed to the constructor function on `Labrador`, which is done correctly using constructor 2.

@@ -2108,12 +2109,12 @@ The `Labrador` class receives two arguments, `name` since it extends `Dog`, แ ```javascript // index.js -console.log('running index.js'); -import { sum } from './sum.js'; +console.log("running index.js"); +import { sum } from "./sum.js"; console.log(sum(1, 2)); // sum.js -console.log('running sum.js'); +console.log("running sum.js"); export const sum = (a, b) => a + b; ``` @@ -2129,7 +2130,7 @@ export const sum = (a, b) => a + b; With the `import` keyword, all imported modules are _pre-parsed_. This means that the imported modules get run _first_, the code in the file which imports the module gets executed _after_. -This is a difference between `require()` in CommonJS and `import`! With `require()`, you can load dependencies on demand while the code is being run. If we would have used `require` instead of `import`, `running index.js`, `running sum.js`, `3` would have been logged to the console. +This is a difference between `require()` in CommonJS and `import`! With `require()`, you can load dependencies on demand while the code is being run. If we would have used `require` instead of `import`, `running index.js`, `running sum.js`, `3` would have been logged to the console.

@@ -2139,9 +2140,9 @@ This is a difference between `require()` in CommonJS and `import`! With `require ###### 68. ผลลัพธ์ที่ได้คืออะไร? ```javascript -console.log(Number(2) === Number(2)) -console.log(Boolean(false) === Boolean(false)) -console.log(Symbol('foo') === Symbol('foo')) +console.log(Number(2) === Number(2)); +console.log(Boolean(false) === Boolean(false)); +console.log(Symbol("foo") === Symbol("foo")); ``` - A: `true`, `true`, `false` @@ -2154,7 +2155,7 @@ console.log(Symbol('foo') === Symbol('foo')) #### คำตอบ: A -Every Symbol is entirely unique. The purpose of the argument passed to the Symbol is to give the Symbol a description. The value of the Symbol is not dependent on the passed argument. As we test equality, we are creating two entirely new symbols: the first `Symbol('foo')`, and the second `Symbol('foo')`. These two values are unique and not equal to each other, `Symbol('foo') === Symbol('foo')` returns `false`. +Every Symbol is entirely unique. The purpose of the argument passed to the Symbol is to give the Symbol a description. The value of the Symbol is not dependent on the passed argument. As we test equality, we are creating two entirely new symbols: the first `Symbol('foo')`, and the second `Symbol('foo')`. These two values are unique and not equal to each other, `Symbol('foo') === Symbol('foo')` returns `false`.

@@ -2164,15 +2165,15 @@ Every Symbol is entirely unique. The purpose of the argument passed to the Symbo ###### 69. ผลลัพธ์ที่ได้คืออะไร? ```javascript -const name = "Lydia Hallie" -console.log(name.padStart(13)) -console.log(name.padStart(2)) +const name = "Lydia Hallie"; +console.log(name.padStart(13)); +console.log(name.padStart(2)); ``` - A: `"Lydia Hallie"`, `"Lydia Hallie"` - B: `" Lydia Hallie"`, `" Lydia Hallie"` (`"[13x whitespace]Lydia Hallie"`, `"[2x whitespace]Lydia Hallie"`) - C: `" Lydia Hallie"`, `"Lydia Hallie"` (`"[1x whitespace]Lydia Hallie"`, `"Lydia Hallie"`) -- D: `"Lydia Hallie"`, `"Lyd"`, +- D: `"Lydia Hallie"`, `"Lyd"`,
คำตอบ

@@ -2440,7 +2441,7 @@ The `sum` function always returns the same result. If we pass `1` และ `2`, ```javascript const add = () => { const cache = {}; - return num => { + return (num) => { if (num in cache) { return `From cache! ${cache[num]}`; } else { @@ -2485,21 +2486,21 @@ The third time, we pass `5 * 2` to the function which gets evaluated to `10`. Th ###### 79. ผลลัพธ์ที่ได้คืออะไร? ```javascript -const myLifeSummedUp = ["☕", "💻", "🍷", "🍫"] +const myLifeSummedUp = ["☕", "💻", "🍷", "🍫"]; for (let item in myLifeSummedUp) { - console.log(item) + console.log(item); } for (let item of myLifeSummedUp) { - console.log(item) + console.log(item); } ``` - A: `0` `1` `2` `3` และ `"☕"` ` "💻"` `"🍷"` `"🍫"` - B: `"☕"` ` "💻"` `"🍷"` `"🍫"` และ `"☕"` ` "💻"` `"🍷"` `"🍫"` - C: `"☕"` ` "💻"` `"🍷"` `"🍫"` และ `0` `1` `2` `3` -- D: `0` `1` `2` `3` และ `{0: "☕", 1: "💻", 2: "🍷", 3: "🍫"}` +- D: `0` `1` `2` `3` และ `{0: "☕", 1: "💻", 2: "🍷", 3: "🍫"}`

คำตอบ

@@ -2522,14 +2523,14 @@ With a _for-of_ loop, we can iterate over **iterables**. An array is an iterable ###### 80. ผลลัพธ์ที่ได้คืออะไร? ```javascript -const list = [1 + 2, 1 * 2, 1 / 2] -console.log(list) +const list = [1 + 2, 1 * 2, 1 / 2]; +console.log(list); ``` - A: `["1 + 2", "1 * 2", "1 / 2"]` - B: `["12", 2, 0.5]` - C: `[3, 2, 0.5]` -- D: `[1, 1, 1]` +- D: `[1, 1, 1]`

คำตอบ

@@ -2538,7 +2539,7 @@ console.log(list) Array elements can hold any value. Numbers, strings, objects, other arrays, null, boolean values, undefined, and other expressions such as dates, functions, and calculations. -The element will be equal to the returned value. `1 + 2` returns `3`, `1 * 2` returns `2`, และ `1 / 2` returns `0.5`. +The element will be equal to the returned value. `1 + 2` returns `3`, `1 * 2` returns `2`, และ `1 / 2` returns `0.5`.

@@ -2549,16 +2550,16 @@ The element will be equal to the returned value. `1 + 2` returns `3`, `1 * 2` r ```javascript function sayHi(name) { - return `Hi there, ${name}` + return `Hi there, ${name}`; } -console.log(sayHi()) +console.log(sayHi()); ``` - A: `Hi there, ` - B: `Hi there, undefined` - C: `Hi there, null` -- D: `ReferenceError` +- D: `ReferenceError`
คำตอบ

@@ -2581,21 +2582,21 @@ In this case, if we didn't pass a value or if we passed `undefined`, `name` woul ###### 82. ผลลัพธ์ที่ได้คืออะไร? ```javascript -var status = "😎" +var status = "😎"; setTimeout(() => { - const status = "😍" + const status = "😍"; const data = { status: "🥑", getStatus() { - return this.status - } - } + return this.status; + }, + }; - console.log(data.getStatus()) - console.log(data.getStatus.call(this)) -}, 0) + console.log(data.getStatus()); + console.log(data.getStatus.call(this)); +}, 0); ``` - A: `"🥑"` และ `"😍"` @@ -2612,7 +2613,6 @@ The value of the `this` keyword is dependent on where you use it. In a **method* With the `call` method, we can change the object to which the `this` keyword refers. In **functions**, the `this` keyword refers to the _the object that the function belongs to_. We declared the `setTimeout` function on the _global object_, so within the `setTimeout` function, the `this` keyword refers to the _global object_. On the global object, there is a variable called _status_ with the value of `"😎"`. When logging `this.status`, `"😎"` gets logged. -

@@ -2623,13 +2623,13 @@ With the `call` method, we can change the object to which the `this` keyword ref ```javascript const person = { name: "Lydia", - age: 21 -} + age: 21, +}; -let city = person.city -city = "Amsterdam" +let city = person.city; +city = "Amsterdam"; -console.log(person) +console.log(person); ``` - A: `{ name: "Lydia", age: 21 }` @@ -2642,13 +2642,13 @@ console.log(person) #### คำตอบ: A -We set the variable `city` equal to the value of the property called `city` on the `person` object. There is no property on this object called `city`, so the variable `city` has the value of `undefined`. +We set the variable `city` equal to the value of the property called `city` on the `person` object. There is no property on this object called `city`, so the variable `city` has the value of `undefined`. Note that we are _not_ referencing the `person` object itself! We simply set the variable `city` equal to the current value of the `city` property on the `person` object. Then, we set `city` equal to the string `"Amsterdam"`. This doesn't change the person object: there is no reference to that object. -When logging the `person` object, the unmodified object gets returned. +When logging the `person` object, the unmodified object gets returned.

@@ -2660,15 +2660,15 @@ When logging the `person` object, the unmodified object gets returned. ```javascript function checkAge(age) { if (age < 18) { - const message = "Sorry, you're too young." + const message = "Sorry, you're too young."; } else { - const message = "Yay! You're old enough!" + const message = "Yay! You're old enough!"; } - return message + return message; } -console.log(checkAge(21)) +console.log(checkAge(21)); ``` - A: `"Sorry, you're too young."` @@ -2691,15 +2691,15 @@ Variables with the `const` และ `let` keyword are _block-scoped_. A block i ###### 85. ข้อมูลแบบไหนที่เราได้ใน log? ```javascript -fetch('https://www.website.com/api/user/1') - .then(res => res.json()) - .then(res => console.log(res)) +fetch("https://www.website.com/api/user/1") + .then((res) => res.json()) + .then((res) => console.log(res)); ``` - A: The result of the `fetch` method. - B: The result of the second invocation of the `fetch` method. - C: The result of the callback in the previous `.then()`. -- D: It would always be undefined. +- D: It would always be undefined.
คำตอบ

@@ -2747,7 +2747,7 @@ By setting `hasName` equal to `name`, you set `hasName` equal to whatever value ###### 87. ผลลัพธ์ที่ได้คืออะไร? ```javascript -console.log("I want pizza"[0]) +console.log("I want pizza"[0]); ``` - A: `"""` @@ -2773,10 +2773,10 @@ Note that this method is not supported in IE7 and below. In that case, use `.cha ```javascript function sum(num1, num2 = num1) { - console.log(num1 + num2) + console.log(num1 + num2); } -sum(10) +sum(10); ``` - A: `NaN` @@ -2789,9 +2789,9 @@ sum(10) #### คำตอบ: B -You can set a default parameter's value equal to another parameter of the function, as long as they've been defined _before_ the default parameter. We pass the value `10` to the `sum` function. If the `sum` function only receives 1 argument, it means that the value for `num2` is not passed, and the value of `num1` is equal to the passed value `10` in this case. The default value of `num2` is the value of `num1`, which is `10`. `num1 + num2` returns `20`. +You can set a default parameter's value equal to another parameter of the function, as long as they've been defined _before_ the default parameter. We pass the value `10` to the `sum` function. If the `sum` function only receives 1 argument, it means that the value for `num2` is not passed, and the value of `num1` is equal to the passed value `10` in this case. The default value of `num2` is the value of `num1`, which is `10`. `num1 + num2` returns `20`. -If you're trying to set a default parameter's value equal to a parameter which is defined _after_ (to the right), the parameter's value hasn't been initialized yet, which will throw an error. +If you're trying to set a default parameter's value equal to a parameter which is defined _after_ (to the right), the parameter's value hasn't been initialized yet, which will throw an error.

@@ -2801,14 +2801,14 @@ If you're trying to set a default parameter's value equal to a parameter which i ###### 89. ผลลัพธ์ที่ได้คืออะไร? ```javascript -// module.js -export default () => "Hello world" -export const name = "Lydia" +// module.js +export default () => "Hello world"; +export const name = "Lydia"; -// index.js -import * as data from "./module" +// index.js +import * as data from "./module"; -console.log(data) +console.log(data); ``` - A: `{ default: function default(), name: "Lydia" }` @@ -2821,9 +2821,9 @@ console.log(data) #### คำตอบ: A -With the `import * as name` syntax, we import _all exports_ from the `module.js` file into the `index.js` file as a new object called `data` is created. In the `module.js` file, there are two exports: the default export, and a named export. The default export is a function which returns the string `"Hello World"`, and the named export is a variable called `name` which has the value of the string `"Lydia"`. +With the `import * as name` syntax, we import _all exports_ from the `module.js` file into the `index.js` file as a new object called `data` is created. In the `module.js` file, there are two exports: the default export, and a named export. The default export is a function which returns the string `"Hello World"`, and the named export is a variable called `name` which has the value of the string `"Lydia"`. -The `data` object has a `default` property for the default export, other properties have the names of the named exports and their corresponding values. +The `data` object has a `default` property for the default export, other properties have the names of the named exports and their corresponding values.

@@ -2835,12 +2835,12 @@ The `data` object has a `default` property for the default export, other propert ```javascript class Person { constructor(name) { - this.name = name + this.name = name; } } -const member = new Person("John") -console.log(typeof member) +const member = new Person("John"); +console.log(typeof member); ``` - A: `"class"` @@ -2857,11 +2857,11 @@ Classes are syntactical sugar for function constructors. The equivalent of the ` ```javascript function Person() { - this.name = name + this.name = name; } ``` -Calling a function constructor with `new` results in the creation of an instance of `Person`, `typeof` keyword returns `"object"` for an instance. `typeof member` returns `"object"`. +Calling a function constructor with `new` results in the creation of an instance of `Person`, `typeof` keyword returns `"object"` for an instance. `typeof member` returns `"object"`.

@@ -2871,9 +2871,9 @@ Calling a function constructor with `new` results in the creation of an instance ###### 91. ผลลัพธ์ที่ได้คืออะไร? ```javascript -let newList = [1, 2, 3].push(4) +let newList = [1, 2, 3].push(4); -console.log(newList.push(5)) +console.log(newList.push(5)); ``` - A: `[1, 2, 3, 4, 5]` @@ -2886,7 +2886,7 @@ console.log(newList.push(5)) #### คำตอบ: D -The `.push` method returns the _new length_ of the array, not the array itself! By setting `newList` equal to `[1, 2, 3].push(4)`, we set `newList` equal to the new length of the array: `4`. +The `.push` method returns the _new length_ of the array, not the array itself! By setting `newList` equal to `[1, 2, 3].push(4)`, we set `newList` equal to the new length of the array: `4`. Then, we try to use the `.push` method on `newList`. Since `newList` is the numerical value `4`, we cannot use the `.push` method: a TypeError is thrown. @@ -2899,17 +2899,18 @@ Then, we try to use the `.push` method on `newList`. Since `newList` is the nume ```javascript function giveLydiaPizza() { - return "Here is pizza!" + return "Here is pizza!"; } -const giveLydiaChocolate = () => "Here's chocolate... now go hit the gym already." +const giveLydiaChocolate = () => + "Here's chocolate... now go hit the gym already."; -console.log(giveLydiaPizza.prototype) -console.log(giveLydiaChocolate.prototype) +console.log(giveLydiaPizza.prototype); +console.log(giveLydiaChocolate.prototype); ``` -- A: `{ constructor: ...}` `{ constructor: ...}` -- B: `{}` `{ constructor: ...}` +- A: `{ constructor: ...}` `{ constructor: ...}` +- B: `{}` `{ constructor: ...}` - C: `{ constructor: ...}` `{}` - D: `{ constructor: ...}` `undefined` @@ -2918,7 +2919,7 @@ console.log(giveLydiaChocolate.prototype) #### คำตอบ: D -Regular functions, such as the `giveLydiaPizza` function, have a `prototype` property, which is an object (prototype object) with a `constructor` property. Arrow functions however, such as the `giveLydiaChocolate` function, do not have this `prototype` property. `undefined` gets returned when trying to access the `prototype` property using `giveLydiaChocolate.prototype`. +Regular functions, such as the `giveLydiaPizza` function, have a `prototype` property, which is an object (prototype object) with a `constructor` property. Arrow functions however, such as the `giveLydiaChocolate` function, do not have this `prototype` property. `undefined` gets returned when trying to access the `prototype` property using `giveLydiaChocolate.prototype`.

@@ -2930,16 +2931,16 @@ Regular functions, such as the `giveLydiaPizza` function, have a `prototype` pro ```javascript const person = { name: "Lydia", - age: 21 -} + age: 21, +}; for (const [x, y] of Object.entries(person)) { - console.log(x, y) + console.log(x, y); } ``` - A: `name` `Lydia` และ `age` `21` -- B: `["name", "Lydia"]` และ `["age", 21]` +- B: `["name", "Lydia"]` และ `["age", 21]` - C: `["name", "age"]` และ `undefined` - D: `Error` @@ -2950,9 +2951,9 @@ for (const [x, y] of Object.entries(person)) { `Object.entries(person)` returns an array of nested arrays, containing the keys and objects: -`[ [ 'name', 'Lydia' ], [ 'age', 21 ] ]` +`[ [ 'name', 'Lydia' ], [ 'age', 21 ] ]` -Using the `for-of` loop, we can iterate over each element in the array, the subarrays in this case. We can destructure the subarrays instantly in the for-of loop, using `const [x, y]`. `x` is equal to the first element in the subarray, `y` is equal to the second element in the subarray. +Using the `for-of` loop, we can iterate over each element in the array, the subarrays in this case. We can destructure the subarrays instantly in the for-of loop, using `const [x, y]`. `x` is equal to the first element in the subarray, `y` is equal to the second element in the subarray. The first subarray is `[ "name", "Lydia" ]`, with `x` equal to `"name"`, และ `y` equal to `"Lydia"`, which get logged. The second subarray is `[ "age", 21 ]`, with `x` equal to `"age"`, และ `y` equal to `21`, which get logged. @@ -2973,7 +2974,7 @@ getItems(["banana", "apple"], "pear", "orange") ``` - A: `["banana", "apple", "pear", "orange"]` -- B: `[["banana", "apple"], "pear", "orange"]` +- B: `[["banana", "apple"], "pear", "orange"]` - C: `["banana", "apple", ["pear"], "orange"]` - D: `SyntaxError` @@ -2982,17 +2983,18 @@ getItems(["banana", "apple"], "pear", "orange") #### คำตอบ: D -`...args` is a rest parameter. The rest parameter's value is an array containing all remaining arguments, **and can only be the last parameter**! In this example, the rest parameter was the second parameter. This is not possible, and will throw a syntax error. +`...args` is a rest parameter. The rest parameter's value is an array containing all remaining arguments, **and can only be the last parameter**! In this example, the rest parameter was the second parameter. This is not possible, and will throw a syntax error. ```javascript function getItems(fruitList, favoriteFruit, ...args) { - return [...fruitList, ...args, favoriteFruit] + return [...fruitList, ...args, favoriteFruit]; } -getItems(["banana", "apple"], "pear", "orange") +getItems(["banana", "apple"], "pear", "orange"); ``` The above example works. This returns the array `[ 'banana', 'apple', 'orange', 'pear' ]` +

@@ -3002,17 +3004,14 @@ The above example works. This returns the array `[ 'banana', 'apple', 'orange', ```javascript function nums(a, b) { - if - (a > b) - console.log('a is bigger') - else - console.log('b is bigger') - return - a + b + if (a > b) console.log("a is bigger"); + else console.log("b is bigger"); + return; + a + b; } -console.log(nums(4, 2)) -console.log(nums(1, 2)) +console.log(nums(4, 2)); +console.log(nums(1, 2)); ``` - A: `a is bigger`, `6` และ `b is bigger`, `3` @@ -3025,13 +3024,13 @@ console.log(nums(1, 2)) #### คำตอบ: B -In JavaScript, we don't _have_ to write the semicolon (`;`) explicitly, however the JavaScript engine still adds them after statements. This is called **Automatic Semicolon Insertion**. A statement can for example be variables, or keywords like `throw`, `return`, `break`, etc. +In JavaScript, we don't _have_ to write the semicolon (`;`) explicitly, however the JavaScript engine still adds them after statements. This is called **Automatic Semicolon Insertion**. A statement can for example be variables, or keywords like `throw`, `return`, `break`, etc. Here, we wrote a `return` statement, and another value `a + b` on a _new line_. However, since it's a new line, the engine doesn't know that it's actually the value that we wanted to return. Instead, it automatically added a semicolon after `return`. You could see this as: ```javascript - return; - a + b +return; +a + b; ``` This means that `a + b` is never reached, since a function stops running after the `return` keyword. If no value gets returned, like here, the function returns `undefined`. Note that there is no automatic insertion after `if/else` statements! @@ -3046,18 +3045,18 @@ This means that `a + b` is never reached, since a function stops running after t ```javascript class Person { constructor() { - this.name = "Lydia" + this.name = "Lydia"; } } Person = class AnotherPerson { constructor() { - this.name = "Sarah" + this.name = "Sarah"; } -} +}; -const member = new Person() -console.log(member.name) +const member = new Person(); +console.log(member.name); ``` - A: `"Lydia"` @@ -3081,11 +3080,11 @@ We can set classes equal to other classes/function constructors. In this case, w ```javascript const info = { - [Symbol('a')]: 'b' -} + [Symbol("a")]: "b", +}; -console.log(info) -console.log(Object.keys(info)) +console.log(info); +console.log(Object.keys(info)); ``` - A: `{Symbol('a'): 'b'}` และ `["{Symbol('a')"]` @@ -3132,13 +3131,13 @@ console.log(getUser(user)) The `getList` function receives an array as its argument. Between the parentheses of the `getList` function, we destructure this array right away. You could see this as: - `[x, ...y] = [1, 2, 3, 4]` +`[x, ...y] = [1, 2, 3, 4]` - With the rest parameter `...y`, we put all "remaining" arguments in an array. The remaining arguments are `2`, `3` และ `4` in this case. The value of `y` is an array, containing all the rest parameters. The value of `x` is equal to `1` in this case, so when we log `[x, y]`, `[1, [2, 3, 4]]` gets logged. +With the rest parameter `...y`, we put all "remaining" arguments in an array. The remaining arguments are `2`, `3` และ `4` in this case. The value of `y` is an array, containing all the rest parameters. The value of `x` is equal to `1` in this case, so when we log `[x, y]`, `[1, [2, 3, 4]]` gets logged. - The `getUser` function receives an object. With arrow functions, we don't _have_ to write curly brackets if we just return one value. However, if you want to return an _object_ from an arrow function, you have to write it between parentheses, otherwise no value gets returned! The following function would have returned an object: +The `getUser` function receives an object. With arrow functions, we don't _have_ to write curly brackets if we just return one value. However, if you want to return an _object_ from an arrow function, you have to write it between parentheses, otherwise no value gets returned! The following function would have returned an object: -```const getUser = user => ({ name: user.name, age: user.age })``` +`const getUser = user => ({ name: user.name, age: user.age })` Since no value gets returned in this case, the function returns `undefined`. @@ -3150,9 +3149,9 @@ Since no value gets returned in this case, the function returns `undefined`. ###### 99. ผลลัพธ์ที่ได้คืออะไร? ```javascript -const name = "Lydia" +const name = "Lydia"; -console.log(name()) +console.log(name()); ``` - A: `SyntaxError` @@ -3165,11 +3164,11 @@ console.log(name()) #### คำตอบ: C -The variable `name` holds the value of a string, which is not a function, thus cannot invoke. +The variable `name` holds the value of a string, which is not a function, thus cannot invoke. TypeErrors get thrown when a value is not of the expected type. JavaScript expected `name` to be a function since we're trying to invoke it. It was a string however, so a TypeError gets thrown: name is not a function! -SyntaxErrors get thrown when you've written something that isn't valid JavaScript, for example when you've written the word `return` as `retrun`. +SyntaxErrors get thrown when you've written something that isn't valid JavaScript, for example when you've written the word `return` as `retrun`. ReferenceErrors get thrown when JavaScript isn't able to find a reference to a value that you're trying to access.

@@ -3182,8 +3181,8 @@ ReferenceErrors get thrown when JavaScript isn't able to find a reference to a v ```javascript // 🎉✨ This is my 100th question! ✨🎉 -const output = `${[] && 'Im'}possible! -You should${'' && `n't`} see a therapist after so much JavaScript lol` +const output = `${[] && "Im"}possible! +You should${"" && `n't`} see a therapist after so much JavaScript lol`; ``` - A: `possible! You should see a therapist after so much JavaScript lol` @@ -3208,11 +3207,11 @@ You should${'' && `n't`} see a therapist after so much JavaScript lol` ###### 101. ผลลัพธ์ที่ได้คืออะไร? ```javascript -const one = (false || {} || null) -const two = (null || false || "") -const three = ([] || 0 || true) +const one = false || {} || null; +const two = null || false || ""; +const three = [] || 0 || true; -console.log(one, two, three) +console.log(one, two, three); ``` - A: `false` `null` `[]` @@ -3241,20 +3240,20 @@ With the `||` operator, we can return the first truthy operand. If all values ar ###### 102. ผลลัพธ์ที่ได้คืออะไร? ```javascript -const myPromise = () => Promise.resolve('I have resolved!') +const myPromise = () => Promise.resolve("I have resolved!"); function firstFunction() { - myPromise().then(res => console.log(res)) - console.log('second') + myPromise().then((res) => console.log(res)); + console.log("second"); } async function secondFunction() { - console.log(await myPromise()) - console.log('second') + console.log(await myPromise()); + console.log("second"); } -firstFunction() -secondFunction() +firstFunction(); +secondFunction(); ``` - A: `I have resolved!`, `second` และ `I have resolved!`, `second` @@ -3269,13 +3268,13 @@ secondFunction() With a promise, we basically say _I want to execute this function, but I'll put it aside for now while it's running since this might take a while. Only when a certain value is resolved (or rejected), and when the call stack is empty, I want to use this value._ -We can get this value with both `.then` and the `await` keyword in an `async` function. Although we can get a promise's value with both `.then` และ `await`, they work a bit differently. +We can get this value with both `.then` and the `await` keyword in an `async` function. Although we can get a promise's value with both `.then` และ `await`, they work a bit differently. -In the `firstFunction`, we (sort of) put the myPromise function aside while it was running, but continued running the other code, which is `console.log('second')` in this case. Then, the function resolved with the string `I have resolved`, which then got logged after it saw that the callstack was empty. +In the `firstFunction`, we (sort of) put the myPromise function aside while it was running, but continued running the other code, which is `console.log('second')` in this case. Then, the function resolved with the string `I have resolved`, which then got logged after it saw that the callstack was empty. With the await keyword in `secondFunction`, we literally pause the execution of an async function until the value has been resolved before moving to the next line. -This means that it waited for the `myPromise` to resolve with the value `I have resolved`, and only once that happened, we moved to the next line: `second` got logged. +This means that it waited for the `myPromise` to resolve with the value `I have resolved`, and only once that happened, we moved to the next line: `second` got logged.

@@ -3285,14 +3284,14 @@ This means that it waited for the `myPromise` to resolve with the value `I have ###### 103. ผลลัพธ์ที่ได้คืออะไร? ```javascript -const set = new Set() +const set = new Set(); -set.add(1) -set.add("Lydia") -set.add({ name: "Lydia" }) +set.add(1); +set.add("Lydia"); +set.add({ name: "Lydia" }); for (let item of set) { - console.log(item + 2) + console.log(item + 2); } ``` @@ -3306,11 +3305,11 @@ for (let item of set) { #### คำตอบ: C -The `+` operator is not only used for adding numerica lvalues, but we can also use it to concatenate strings. Whenever the JavaScript engine sees that one or more values are not a number, it coerces the number into a string. +The `+` operator is not only used for adding numerica lvalues, but we can also use it to concatenate strings. Whenever the JavaScript engine sees that one or more values are not a number, it coerces the number into a string. The first one is `1`, which is a numerical value. `1 + 2` returns the number 3. -However, the second one is a string `"Lydia"`. `"Lydia"` is a string and `2` is a number: `2` gets coerced into a string. `"Lydia"` และ `"2"` get concatenated, whic hresults in the string `"Lydia2"`. +However, the second one is a string `"Lydia"`. `"Lydia"` is a string and `2` is a number: `2` gets coerced into a string. `"Lydia"` และ `"2"` get concatenated, whic hresults in the string `"Lydia2"`. `{ name: "Lydia" }` is an object. Neither a number nor an object is a string, so it stringifies both. Whenever we stringify a regular object, it becomes `"[object Object]"`. `"[object Object]"` concatenated with `"2"` becomes `"[object Object]2"`. @@ -3322,7 +3321,7 @@ However, the second one is a string `"Lydia"`. `"Lydia"` is a string and `2` is ###### 104. ผลลัพธ์ที่ได้คืออะไร? ```javascript -Promise.resolve(5) +Promise.resolve(5); ``` - A: `5` @@ -3337,7 +3336,7 @@ Promise.resolve(5) We can pass any type of value we want to `Promise.resolve`, either a promise or a non-promise. The method itself returns a promise with the resolved value (``). If you pass a regular function, it'll be a resolved promise with a regular value. If you pass a promise, it'll be a resolved promise with the resolved value of that passed promise. -In this case, we just passed the numerical value `5`. It returns a resolved promise with the value `5`. +In this case, we just passed the numerical value `5`. It returns a resolved promise with the value `5`.

@@ -3349,15 +3348,15 @@ In this case, we just passed the numerical value `5`. It returns a resolved prom ```javascript function compareMembers(person1, person2 = person) { if (person1 !== person2) { - console.log("Not the same!") + console.log("Not the same!"); } else { - console.log("They are the same!") + console.log("They are the same!"); } } -const person = { name: "Lydia" } +const person = { name: "Lydia" }; -compareMembers(person) +compareMembers(person); ``` - A: `Not the same!` @@ -3370,13 +3369,13 @@ compareMembers(person) #### คำตอบ: B -Objects are passed by reference. When we check objects for strict equality (`===`), we're comparing their references. +Objects are passed by reference. When we check objects for strict equality (`===`), we're comparing their references. We set the default value for `person2` equal to the `person` object, and passed the `person` object as the value for `person1`. This means that both values have a reference to the same spot in memory, thus they are equal. -The code block in the `else` statement gets run, and `They are the same!` gets logged. +The code block in the `else` statement gets run, and `They are the same!` gets logged.

@@ -3392,11 +3391,11 @@ const colorConfig = { green: true, black: true, yellow: false, -} +}; -const colors = ["pink", "red", "blue"] +const colors = ["pink", "red", "blue"]; -console.log(colorConfig.colors[1]) +console.log(colorConfig.colors[1]); ``` - A: `true` @@ -3409,11 +3408,11 @@ console.log(colorConfig.colors[1]) #### คำตอบ: D -In JavaScript, we have two ways to access properties on an object: bracket notation, or dot notation. In this example, we use dot notation (`colorConfig.colors`) instead of bracket notation (`colorConfig["colors"]`). +In JavaScript, we have two ways to access properties on an object: bracket notation, or dot notation. In this example, we use dot notation (`colorConfig.colors`) instead of bracket notation (`colorConfig["colors"]`). With dot notation, JavaScript tries to find the property on the object with that exact name. In this example, JavaScript tries to find a property called `colors` on the `colorConfig` object. There is no proprety called `colorConfig`, so this returns `undefined`. Then, we try to access the value of the first element by using `[1]`. We cannot do this on a value that's `undefined`, so it throws a `TypeError`: `Cannot read property '1' of undefined`. -JavaScript interprets (or unboxes) statements. When we use bracket notation, it sees the first opening bracket `[` and keeps going until it finds the closing bracket `]`. Only then, it will evaluate the statement. If we would've used `colorConfig[colors[1]]`, it would have returned the value of the `red` property on the `colorConfig` object. +JavaScript interprets (or unboxes) statements. When we use bracket notation, it sees the first opening bracket `[` and keeps going until it finds the closing bracket `]`. Only then, it will evaluate the statement. If we would've used `colorConfig[colors[1]]`, it would have returned the value of the `red` property on the `colorConfig` object.

@@ -3423,7 +3422,7 @@ JavaScript interprets (or unboxes) statements. When we use bracket notation, it ###### 107. ผลลัพธ์ที่ได้คืออะไร? ```javascript -console.log('❤️' === '❤️') +console.log("❤️" === "❤️"); ``` - A: `true` @@ -3434,7 +3433,7 @@ console.log('❤️' === '❤️') #### คำตอบ: A -Under the hood, emojis are unicodes. The unicodes for the heart emoji is `"U+2764 U+FE0F"`. These are always the same for the same emojis, so we're comparing two equal strings to each other, which returns true. +Under the hood, emojis are unicodes. The unicodes for the heart emoji is `"U+2764 U+FE0F"`. These are always the same for the same emojis, so we're comparing two equal strings to each other, which returns true.

@@ -3444,19 +3443,19 @@ Under the hood, emojis are unicodes. The unicodes for the heart emoji is `"U+276 ###### 108. Which of these methods modifies the original array? ```javascript -const emojis = ['✨', '🥑', '😍'] +const emojis = ["✨", "🥑", "😍"]; -emojis.map(x => x + '✨') -emojis.filter(x => x !== '🥑') -emojis.find(x => x !== '🥑') -emojis.reduce((acc, cur) => acc + '✨') -emojis.slice(1, 2, '✨') -emojis.splice(1, 2, '✨') +emojis.map((x) => x + "✨"); +emojis.filter((x) => x !== "🥑"); +emojis.find((x) => x !== "🥑"); +emojis.reduce((acc, cur) => acc + "✨"); +emojis.slice(1, 2, "✨"); +emojis.splice(1, 2, "✨"); ``` - A: `All of them` - B: `map` `reduce` `slice` `splice` -- C: `map` `slice` `splice` +- C: `map` `slice` `splice` - D: `splice`
คำตอบ @@ -3464,7 +3463,7 @@ emojis.splice(1, 2, '✨') #### คำตอบ: D -With `splice` method, we modify the original array by deleting, replacing or adding elements. In this case, we removed 2 items from index 1 (we removed `'🥑'` และ `'😍'`) and added the ✨ emoji instead. +With `splice` method, we modify the original array by deleting, replacing or adding elements. In this case, we removed 2 items from index 1 (we removed `'🥑'` และ `'😍'`) and added the ✨ emoji instead. `map`, `filter` และ `slice` return a new array, `find` returns an element, and `reduce` returns a reduced value. diff --git a/tr-TR/README-tr_TR.md b/tr-TR/README-tr_TR.md index e34ae66b..f1abe649 100644 --- a/tr-TR/README-tr_TR.md +++ b/tr-TR/README-tr_TR.md @@ -9,7 +9,6 @@ Cevaplar, soruların altında gizlenmiştir. Görmek için sadece tıklayın. İ Daha fazla soru eklendikçe eposta almak ister misiniz?
✨✉Eposta bildirimlerine abone olun✉✨ - Mevcut dillerin listesi: - [🇸🇦 العربية](../ar-AR/README_AR.md) @@ -26,6 +25,7 @@ Mevcut dillerin listesi: - [🇳🇱 Nederlands](../nl-NL/README.md) - [🇵🇱 Polski](../pl-PL/README.md) - [🇧🇷 Português Brasil](../pt-BR/README_pt_BR.md) +- [🇷o Română](../ro-RO/README.ro.md) - [🇷🇺 Русский](../ru-RU/README.md) - [🇽🇰 Shqip](../sq-KS/README_sq_KS.md) - [🇹🇭 ไทย](../th-TH/README-th_TH.md) @@ -60,8 +60,9 @@ sayHi(); #### Cevap: D Fonksiyonun içinde, önce `var` anahtar kelimesi ile `name` değişkenini tanımladık. Bu demektir ki, değişken varsayılan değeri olan `undefined` ile "hoisting" (hafızada alan oluşturma aşaması) olur, ta ki gerçekten değişkene değer ataması yaptığımız satıra varana dek. `name` değişkenini loglayama çalıştığımız satırda henüz değişkeni tanımlamadık, bu yüzden hala `undefined` değerini saklıyor. - + `let` (ve `const`) anahtar kelimelerine sahip değişkenler de "hoisted" olur, ama `var`'ın aksine ilk değer ataması yapılmaz. Değişkenleri tanımladığımız (ilk değer ataması yaptığımız) satırdan önce erişilebilir değillerdir. Bu, "geçici ölü alan / geçici değişmez çıktı alanı", "temporal dead zone", olarak adlandırılır. Değişkenlere, tanımlanmadan önce erişmeye çalıştığımız zaman, Javascript `ReferenceError` hatası fırlatır. +

@@ -91,6 +92,7 @@ for (let i = 0; i < 3; i++) { Javascript'deki olay kuyruğundan dolayı, `setTimeout` callback fonksiyonu, döngü uygulandıktan _sonra_ çağrılır. `i` değişkeni, ilk döngü sırasında `var` anahtar kelimesi ile tanımlandığından, bu değişken globaldir. Döngü boyunca, `++` unary operatörünü kullanarak, `i`'nin değerini her seferinde `1` arttırdık. İlk örnekte, `setTimeout` callback fonksiyonu çağrıldığı zaman, `i`'nin değeri `3`'e eşitti. İkinci döngüde, `i` değişkeni `let` anahtar kelimesi kullanılarak tanımlandı: `let` (ve `const`) ile tanımlanan değişkenler "block-scope"dur (block `{}` arasındaki herhangi bir şeydir). Her bir tekrarda, `i` yeni değere sahip olacak ve her değer döngü içinde "scoped" olacak. +

@@ -104,7 +106,7 @@ const shape = { diameter() { return this.radius * 2; }, - perimeter: () => 2 * Math.PI * this.radius + perimeter: () => 2 * Math.PI * this.radius, }; console.log(shape.diameter()); @@ -125,7 +127,7 @@ console.log(shape.perimeter()); Arrow fonksiyonlarda, `this` anahtar kelimesi, sıradan fonksiyonların aksine, kendi sardığı mevcut scope'u referans alır. Bu demektir ki, `perimeter`'i çağırdığımız zaman, `shape` objesini değil, kendi sardığı scope'u referans alıyor (örneğin window). -Bu objede, `radius` değeri olmadığından `undefined` döndürüyor. +Bu objede, `radius` değeri olmadığından `undefined` döndürüyor.

@@ -150,7 +152,8 @@ Bu objede, `radius` değeri olmadığından `undefined` döndürüyor. Artı (unary plus), işlemeye çalıştığı değişkeni sayıya çevirmeye çalışır. `true` `1` ve `false` `0` demektir. -`'Lydia'` harf dizisi doğrusal ("truthy") bir değerdir. Aslında sorduğumuz şey, "bu doğrusal değer yanlış-ımsı ("falsy") mı?". Bu da `false` döndürür. +`'Lydia'` harf dizisi doğrusal ("truthy") bir değerdir. Aslında sorduğumuz şey, "bu doğrusal değer yanlış-ımsı ("falsy") mı?". Bu da `false` döndürür. +

@@ -160,12 +163,12 @@ Artı (unary plus), işlemeye çalıştığı değişkeni sayıya çevirmeye ça ```javascript const bird = { - size: "small" + size: "small", }; const mouse = { name: "Mickey", - small: true + small: true, }; ``` @@ -186,12 +189,12 @@ Javascript, ifadeleri yorumlar (ya da açar ("unboxes")). Köşeli parentez nota `mouse[bird.size]`: Önce `bird.size` çalıştırılır, o da `"small"` demektir. `mouse["small"]`, `true` döndürür. Ancak, nokta notasyonunda bu gerçekleşmez. `mouse`, `bird` diye bir keye sahip değildir ki bu da `mouse.bird`, `undefined` demektir. Sonra, nokta notasyonunu kullanarak `size`'a ulaşmak istiyoruz: `mouse.bird.size`. `mouse.bird`, `undefined` olduğundan, aslında ulaşmaya çalıştığımız `undefined.size`. Bu geçerli değil ve `Cannot read property "size" of undefined`'a benzer bir hata fırlatacaktır. +

--- - ###### 6. Çıktısı Nedir? ```javascript @@ -253,6 +256,7 @@ console.log(b === c); `==` operatörünü kullandığımız zaman, sadece aynı _değer_'e sahip olup olmadığını kontrol eder. İkisi de `3` değerine sahip, yani `true` döndürür. Ancak, `===` kullandığımız zaman değer _ve_ tip aynı olmalıdır. Öyle değil: `new Number()`, sayı ("number") değildir, **nesne**dir. İkisi de `false` döndürür. +

@@ -287,6 +291,7 @@ console.log(freddie.colorChange("orange")); #### Cevap: D `colorChange` fonksiyonu statiktir. Statik methodlar, sadece oluşturuldukları kurucuda var olmak için tasarlanmıştır ve herhangi bir "children"a aktarılamaz. `freddie`, "child" olduğundan, fonksiyon aktarılmadı ve `freddie` üzerinden erişilebilir değil: `TypeError` hatası fırlatılır. +

@@ -312,6 +317,7 @@ console.log(greetign); Nesneyi loglar çünkü global nesne üzerinde boş bir nesne oluşturduk. `greeting`'i `greetign` olarak yanlış yazdığımız zaman, JS yorumlayıcısı bunu `global.greetign = {}` olarak gördü (ya da tarayıcı içinde `window.greetign = {}`). Bundan kaçınmak için, `"use strict"` kullanabiliriz. Bu, bir değişkene herhangi bir atama yapmadan önce tanımladığınızdan emin olmanızı sağlar. +

@@ -355,7 +361,7 @@ function Person(firstName, lastName) { } const member = new Person("Lydia", "Hallie"); -Person.getFullName = function() { +Person.getFullName = function () { return `${this.firstName} ${this.lastName}`; }; @@ -373,8 +379,9 @@ console.log(member.getFullName()); #### Cevap: A Sıradan fonksiyonlarla yaptığınız gibi bir yapıcıya ("constructor") özellik ekleyemezsiniz. Eğer, tek seferde tüm nesnelere özellik eklemek isterseniz, bunun yerine prototype kullanmalısınız. Yani bu durumda, + ```js -Person.prototype.getFullName = function() { +Person.prototype.getFullName = function () { return `${this.firstName} ${this.lastName}`; }; ``` @@ -414,6 +421,7 @@ console.log(sarah); `sarah` için `new` anahtar kelimesi kullanmadık. `new` kullandığınız zaman, oluşturduğumuz yeni boş nesneyi referans gösterir. Lakin, `new`'i eklemezseniz, **global nesne**'yi referans gösterir! `this.firstName`, `"Sarah"`'a eşittir ve `this.lastName`, `"Smith"`'e eşittir dedik. Aslında yaptığımız, `global.firstName = 'Sarah'` ve `global.lastName = 'Smith'` diye tanımlamaydı. `sarah`'ın kendisi `undefined` olarak kalır. +

@@ -431,7 +439,7 @@ console.log(sarah); #### Cevap: D -**capturing** aşaması süresince, olay ata ("ancestor) elemanlardan hedef elemana doğru gider. Daha sonra **target** elemana ulaşır ve **bubbling** başlar. +**capturing** aşaması süresince, olay ata ("ancestor) elemanlardan hedef elemana doğru gider. Daha sonra **target** elemana ulaşır ve **bubbling** başlar. @@ -451,6 +459,7 @@ console.log(sarah); #### Cevap: B Bütün nesneler prototiplere ("prototypes") sahiptir, **temel nesne**, **base object**, hariç. Temel nesne, kullanıcı tarafından oluşturulmuş nesnedir, ya da `new` anahtar kelimesi kullanarak oluşturulmuş bir nesnedir. Temel nesne bazı method ve özelliklere erişebilir, `.toString` gibi. Yerleşik gelen Javascript methodlarını kullanabilme sebebi budur! Buna benzer tüm methodlar prototip üzerinden erişebilir. Her ne kadar Javascript, methodu direkt olarak nesneniz üzerinden bulamasa da, prototip zinciri üzerinden aşağıya doğru gider ve orada bulur, böylece sizin için erişebilir yapar. +

@@ -506,7 +515,6 @@ console.log(number); **son ek**, **postfix**, `++` unary operatörü: - 1. Değer döndürür (`0` döndürür) 2. Değeri arttırır (sayı şimdi `1`) @@ -686,7 +694,7 @@ sessionStorage.setItem("cool_secret", 123); `sessionStorage` içinde saklanan veri _sekme_ kapatıldıktan sonra kaldırılır. -Eğer `localStorage` kullandıysanız, veri sonsuza kadar orada olacaktır, örnek olarak `localStorage.clear()` çalıştırılmadığı sürece. +Eğer `localStorage` kullandıysanız, veri sonsuza kadar orada olacaktır, örnek olarak `localStorage.clear()` çalıştırılmadığı sürece.

@@ -829,7 +837,7 @@ String.prototype.giveLydiaPizza = () => { const name = "Lydia"; -console.log(name.giveLydiaPizza()) +console.log(name.giveLydiaPizza()); ``` - A: `"Just give Lydia pizza already!"` @@ -941,9 +949,7 @@ Burası olay döngüsünün çalışmaya başlayacapı yerdir. **olay döngüsü ```html
- +
``` @@ -969,9 +975,7 @@ Olaya sebep olan en derindeki iç eleman, olayın hedefidir ("event.target"). `e ```html
-

- Click here! -

+

Click here!

``` @@ -1185,7 +1189,7 @@ Sonra, bu block-scoped değişkeni `1`'e eşit olarak ayarladık ve `y` değişk - A: primitifdir ya da nesnedir - B: fonksiyondur or nesnedir - C: tuzak soru! sadece nesnedir -- D: sayıdır (number) ya da nesnedir +- D: sayıdır (number) ya da nesnedir
Cevap

@@ -1206,7 +1210,10 @@ Primitif ve nesneyi birbirinden ayıran, primitif tiplerin herhangi bir özelli ###### 40. Çıktısı Nedir? ```javascript -[[0, 1], [2, 3]].reduce( +[ + [0, 1], + [2, 3], +].reduce( (acc, cur) => { return acc.concat(cur); }, @@ -1332,7 +1339,7 @@ console.log(gen.next().value); #### Cevap: C -Sıradan fonksiyonlar yürütmenin başlamasının ardından yarı yolda durdurulamaz. Ancak, bir generator fonksiyon yarı yolda "durdurabilir" ve sonra nerede kaldıysa devam edebilir. Bir generator fonksiyon ne zaman `yield` anahtar kelimesiyle karşılaşsa, yield'de belirtilen değeri verir. Dikkat edin, generator fonksiyon değeri _döndürmez_ (_return_), değeri _verir_ (_yield_). +Sıradan fonksiyonlar yürütmenin başlamasının ardından yarı yolda durdurulamaz. Ancak, bir generator fonksiyon yarı yolda "durdurabilir" ve sonra nerede kaldıysa devam edebilir. Bir generator fonksiyon ne zaman `yield` anahtar kelimesiyle karşılaşsa, yield'de belirtilen değeri verir. Dikkat edin, generator fonksiyon değeri _döndürmez_ (_return_), değeri _verir_ (_yield_). Önce, generator fonksiyonu `i`'yi `10`'a eşitleyerek başlatıyoruz. `next()` metodunu kullanarak generator fonksiyonu çalıştırıyoruz. İlk kez generator fonksiyonu çalıştırdığımızda, `i` `10`'a eşit. Fonksiyon ilk `yield` anahtar kelimesi ile karşılaşıyor: `i`'nin değerini veriyor. Generatır şimdi "durdu", ve `10` loglandı. @@ -1354,7 +1361,7 @@ const secondPromise = new Promise((res, rej) => { setTimeout(res, 100, "two"); }); -Promise.race([firstPromise, secondPromise]).then(res => console.log(res)); +Promise.race([firstPromise, secondPromise]).then((res) => console.log(res)); ``` - A: `"one"` @@ -1406,7 +1413,7 @@ Sonra, `person` değişkenini `null`'a eşit olarak ayarlarız. -Sadece `person` değişkeninin değerini değiştiriyoruz, dizideki ilk elemanı değil, ilk eleman nesneyi gösteren farklı (kopyalanmış) bir referansa sahip. `members` içindeki ilk eleman hala orijinal nesneyi gösteren referansını saklıyor. `members` dizisini logladığımız zaman, ilk elemanın hala sakladığı nesnenin değeri loglanır. +Sadece `person` değişkeninin değerini değiştiriyoruz, dizideki ilk elemanı değil, ilk eleman nesneyi gösteren farklı (kopyalanmış) bir referansa sahip. `members` içindeki ilk eleman hala orijinal nesneyi gösteren referansını saklıyor. `members` dizisini logladığımız zaman, ilk elemanın hala sakladığı nesnenin değeri loglanır.

@@ -1418,7 +1425,7 @@ Sadece `person` değişkeninin değerini değiştiriyoruz, dizideki ilk elemanı ```javascript const person = { name: "Lydia", - age: 21 + age: 21, }; for (const item in person) { @@ -1498,7 +1505,7 @@ Sadece string içindeki ilk sayılar döndürülür. _Sayı tabanına_ (hangi ti ###### 50. Çıktısı Nedir`? ```javascript -[1, 2, 3].map(num => { +[1, 2, 3].map((num) => { if (typeof num === "number") return; return num * 2; }); @@ -1514,7 +1521,7 @@ Sadece string içindeki ilk sayılar döndürülür. _Sayı tabanına_ (hangi ti #### Cevap: C -Dizi üzerinde eşleme yaparken, `num`'ın değeri, o anda döngüye giren elemanın değerine eşittir. Bu durumda, elemanlar sayı, yani `typeof num === "number"` koşul ifadesi `true` durdurur. map fonksiyonu yeni bir dizi oluşturur ve fonksiyondan dönen değerleri yerleştirir. +Dizi üzerinde eşleme yaparken, `num`'ın değeri, o anda döngüye giren elemanın değerine eşittir. Bu durumda, elemanlar sayı, yani `typeof num === "number"` koşul ifadesi `true` durdurur. map fonksiyonu yeni bir dizi oluşturur ve fonksiyondan dönen değerleri yerleştirir. Ancak, biz değer döndürmüyoruz. Bir fonksiyondan değer döndürmediğimiz zaman, fonksiyon `undefined` döndürür. Dizideki her eleman için, fonksiyon bloğu çağrılır, yani her bir eleman için `undefined` döndürürüz. @@ -1675,7 +1682,7 @@ class Dog { } } -Dog.prototype.bark = function() { +Dog.prototype.bark = function () { console.log(`Woof I am ${this.name}`); }; @@ -1903,7 +1910,7 @@ console.log(Object.keys(person)); const settings = { username: "lydiahallie", level: 19, - health: 90 + health: 90, }; const data = JSON.stringify(settings, ["level", "health"]); @@ -1922,7 +1929,7 @@ console.log(data); `JSON.stringify`'ın ikinci argumanı _değiştiricidir_, _"replacer"_. Değiştirici bir fonksiyon ya da bir dizi olabilir, ve değerlerin hangilerinin ve nasıl string'e dönüşeceğini kontrol etmenize izin verir. -Eğer değiştirici _dizi_ ise, sadece dizi içinde ismi geçem özellikler JSON string'e dahil edilmiş olur. Bu durumda, sadece `"level"` ve `"health"` isimli özellikler dahil edildi, `"username"` dışarıda bırakıldı. `data`, `"{"level":19, "health":90}"` eşittir. +Eğer değiştirici _dizi_ ise, sadece dizi içinde ismi geçem özellikler JSON string'e dahil edilmiş olur. Bu durumda, sadece `"level"` ve `"health"` isimli özellikler dahil edildi, `"username"` dışarıda bırakıldı. `data`, `"{"level":19, "health":90}"` eşittir. Eğer değiştirici _fonksiyon_ ise, stringe dönüştürülen her özellik için bu fonksiyon çağrılır. Bu fonksiyondan dönen değer, JSON stringe eklenmiş olacak özelliğin değeri olacaktır. Eğer değer `undefined`'sa, bu özellik JSON stringe dahil edilmez. @@ -1937,7 +1944,7 @@ Eğer değiştirici _fonksiyon_ ise, stringe dönüştürülen her özellik içi let num = 10; const increaseNumber = () => num++; -const increasePassedNumber = number => number++; +const increasePassedNumber = (number) => number++; const num1 = increaseNumber(); const num2 = increasePassedNumber(num1); @@ -2025,7 +2032,7 @@ Bu örnekte, geriye bir değer döndürmüyoruz, sadece biriktiricinin değerini Biriktiricinin değeri, bir önceki callback fonksiyonunun dönen değerine eşittir. Eğer, opsiyonel olan `initialValue` agümanını `reduce` methoduna geçmezseniz, biriktiricinin değeri, ilk çağrılışta gelen elemana eşit olur. -İlk çağrılışta, biriktirici (`x`) `1`'dir, ve `y`'nin o anki değeri `2`'dir. callback fonksiyonundan bir şey döndürmüyoruz, biriktiriciyi ve o anki değeri logluyoruz: `1` ve `2` loglanır. +İlk çağrılışta, biriktirici (`x`) `1`'dir, ve `y`'nin o anki değeri `2`'dir. callback fonksiyonundan bir şey döndürmüyoruz, biriktiriciyi ve o anki değeri logluyoruz: `1` ve `2` loglanır. Eğer bir fonksiyondan değer döndürmezseniz, fonksiyon `undefined` döndürür. Sonraki çağrılışta, biriktirici `undefined`, ve o anki geçerli değer `3`'tür. `undefined` ve `3` loglanır. @@ -2046,7 +2053,7 @@ class Dog { }; class Labrador extends Dog { - // 1 + // 1 constructor(name, size) { this.size = size; } @@ -2060,7 +2067,7 @@ class Labrador extends Dog { super(name); this.size = size; } - // 4 + // 4 constructor(name, size) { this.name = name; this.size = size; @@ -2083,7 +2090,7 @@ Türetilmiş bir sınıfta, `super`'i çağırmadan önce `this` anahtar kelimes `super` anahtar kelimesiyle, parent sınıfın yapıcı methodunu verilen argümanlarla beraber çağırırız. Parent sınıfın yapıcısı `name` argümanını alıyor, bu yüzden `super`'e `name`'i vermemiz gerek. -`Dog` sınıfı iki argüman alıyor, `name` `Animal` sınıfından türediğinden, ve `size` `Dog` sınıfı üzerinde ekstra özellik olarak. İkisinin de `Dog` yapıcı methoduna geçilmesi gerek, bu da 2. yapıcı methodda doğru şekilde kullanılarak yapılmıştır. +`Dog` sınıfı iki argüman alıyor, `name` `Animal` sınıfından türediğinden, ve `size` `Dog` sınıfı üzerinde ekstra özellik olarak. İkisinin de `Dog` yapıcı methoduna geçilmesi gerek, bu da 2. yapıcı methodda doğru şekilde kullanılarak yapılmıştır.

@@ -2094,12 +2101,12 @@ Türetilmiş bir sınıfta, `super`'i çağırmadan önce `this` anahtar kelimes ```javascript // index.js -console.log('running index.js'); -import { sum } from './sum.js'; +console.log("running index.js"); +import { sum } from "./sum.js"; console.log(sum(1, 2)); // sum.js -console.log('running sum.js'); +console.log("running sum.js"); export const sum = (a, b) => a + b; ``` @@ -2125,9 +2132,9 @@ CommonJS'deki `require()` ve `import` arasındaki fark budur! `require()` ile, b ###### 68. Çıktısı Nedir? ```javascript -console.log(Number(2) === Number(2)) -console.log(Boolean(false) === Boolean(false)) -console.log(Symbol('foo') === Symbol('foo')) +console.log(Number(2) === Number(2)); +console.log(Boolean(false) === Boolean(false)); +console.log(Symbol("foo") === Symbol("foo")); ``` - A: `true`, `true`, `false` @@ -2150,15 +2157,15 @@ Her Symbol tamamen benzersizdir. Symbol'e geçilen argümanın amacı, Symbol'e ###### 69. Çıktısı Nedir? ```javascript -const name = "Lydia Hallie" -console.log(name.padStart(13)) -console.log(name.padStart(2)) +const name = "Lydia Hallie"; +console.log(name.padStart(13)); +console.log(name.padStart(2)); ``` - A: `"Lydia Hallie"`, `"Lydia Hallie"` - B: `" Lydia Hallie"`, `" Lydia Hallie"` (`"[13x whitespace]Lydia Hallie"`, `"[2x whitespace]Lydia Hallie"`) - C: `" Lydia Hallie"`, `"Lydia Hallie"` (`"[1x whitespace]Lydia Hallie"`, `"Lydia Hallie"`) -- D: `"Lydia Hallie"`, `"Lyd"`, +- D: `"Lydia Hallie"`, `"Lyd"`,
Cevap

@@ -2191,6 +2198,7 @@ console.log("🥑" + "💻"); #### Cevap: A `+` operatörü ile stringleri birleştirebilirsiniz. Bu örnekte, `"🥑"` ile `"💻"` birleştiriyoruz, `"🥑💻"` olarak sonuçlanıyor. +

@@ -2386,7 +2394,7 @@ Eşitliğin sağ tarafındaki nesneden `name` özelliğini çıkarttığımız z `{ name: myName }` ile, JavaScript'e diyoruz ki; eşitliğin sağ tarafındaki `name` özelliğinin değeriyle birlikte `myName` diye bir değişken tanımlamak istiyoruz. -`name`'i loglamayı denediğimizden dolayı, ki bu değişken tanımlanmamış, ReferenceError fırlatılır. +`name`'i loglamayı denediğimizden dolayı, ki bu değişken tanımlanmamış, ReferenceError fırlatılır.

@@ -2423,7 +2431,7 @@ Saf fonksiyon, aynı argümanlar geçildiği zaman, _her zaman_ aynı sonucu dö ```javascript const add = () => { const cache = {}; - return num => { + return (num) => { if (num in cache) { return `From cache! ${cache[num]}`; } else { @@ -2455,9 +2463,9 @@ console.log(addFunction(5 * 2)); Eğer `addFunction` fonksiyonunu aynı argüman ile tekrar çağırırsak, önce cache içinde o değerin hali hazırda olup olmadığını kontrol eder. Eğer varsa, cache değeri döndürülecektir ki böylece çalışma zamanından tasarruf sağlanır. Eğer yoksa, cache'lenmemişse, değeri hesaplayıp ardından saklayacaktır. `addFunction` fonksiyonunu üç kez aynı değer ile çağırıyoruz: ilk çağırmada, `num` `10`'a eşit olduğu zaman fonksiyonun değeri henüz cache'lenmemiş. `num in cache` if ifadesi `false` döndürür - ve else bloğu çalıştırılır: `Calculated! 20` loglanır, ve sonuç cache nesnesine eklenir. `cache` şimdi şuna benziyor; `{ 10: 20 }` +ve else bloğu çalıştırılır: `Calculated! 20` loglanır, ve sonuç cache nesnesine eklenir. `cache` şimdi şuna benziyor; `{ 10: 20 }` -İkincide, `cache` nesnesi `10` için döndürülen değeri içeriyor. `num in cache` if ifadesi `true` döndürür, ve `'From cache! 20'` loglanır. +İkincide, `cache` nesnesi `10` için döndürülen değeri içeriyor. `num in cache` if ifadesi `true` döndürür, ve `'From cache! 20'` loglanır. Üçüncü sefer de, fonksiyona `5 * 2` geçiyoruz ki bu da `10` olarak değerlendirilir. `cache` nesnesi `10` için döndürülen değeri içeriyor. `num in cache` if ifadesi `true` döndürür, ve `'From cache! 20'` loglanır. @@ -2469,21 +2477,21 @@ Eğer `addFunction` fonksiyonunu aynı argüman ile tekrar çağırırsak, önce ###### 79. Çıktısı Nedir? ```javascript -const myLifeSummedUp = ["☕", "💻", "🍷", "🍫"] +const myLifeSummedUp = ["☕", "💻", "🍷", "🍫"]; for (let item in myLifeSummedUp) { - console.log(item) + console.log(item); } for (let item of myLifeSummedUp) { - console.log(item) + console.log(item); } ``` - A: `0` `1` `2` `3` ve `"☕"` ` "💻"` `"🍷"` `"🍫"` - B: `"☕"` ` "💻"` `"🍷"` `"🍫"` ve `"☕"` ` "💻"` `"🍷"` `"🍫"` - C: `"☕"` ` "💻"` `"🍷"` `"🍫"` ve `0` `1` `2` `3` -- D: `0` `1` `2` `3` ve `{0: "☕", 1: "💻", 2: "🍷", 3: "🍫"}` +- D: `0` `1` `2` `3` ve `{0: "☕", 1: "💻", 2: "🍷", 3: "🍫"}`
Cevap

@@ -2506,14 +2514,14 @@ _for-of_ döngüsü ile, **yinelenebilirler** (**iterables**) üzerinde iterasyo ###### 80. Çıktısı Nedir? ```javascript -const list = [1 + 2, 1 * 2, 1 / 2] -console.log(list) +const list = [1 + 2, 1 * 2, 1 / 2]; +console.log(list); ``` - A: `["1 + 2", "1 * 2", "1 / 2"]` - B: `["12", 2, 0.5]` - C: `[3, 2, 0.5]` -- D: `[1, 1, 1]` +- D: `[1, 1, 1]`

Cevap

@@ -2533,16 +2541,16 @@ Eleman dönen değere eşit olacaktır. `1 + 2` `3` döndürür, `1 * 2` `2` dö ```javascript function sayHi(name) { - return `Hi there, ${name}` + return `Hi there, ${name}`; } -console.log(sayHi()) +console.log(sayHi()); ``` - A: `Hi there, ` - B: `Hi there, undefined` - C: `Hi there, null` -- D: `ReferenceError` +- D: `ReferenceError`

Cevap

@@ -2565,21 +2573,21 @@ Bu örnekte, eğer bir değer geçmeseydik ya da `undefined` geçseydik, `name` ###### 82. Çıktısı Nedir? ```javascript -var status = "😎" +var status = "😎"; setTimeout(() => { - const status = "😍" + const status = "😍"; const data = { status: "🥑", getStatus() { - return this.status - } - } + return this.status; + }, + }; - console.log(data.getStatus()) - console.log(data.getStatus.call(this)) -}, 0) + console.log(data.getStatus()); + console.log(data.getStatus.call(this)); +}, 0); ``` - A: `"🥑"` ve `"😍"` @@ -2606,13 +2614,13 @@ setTimeout(() => { ```javascript const person = { name: "Lydia", - age: 21 -} + age: 21, +}; -let city = person.city -city = "Amsterdam" +let city = person.city; +city = "Amsterdam"; -console.log(person) +console.log(person); ``` - A: `{ name: "Lydia", age: 21 }` @@ -2624,13 +2632,13 @@ console.log(person)

#### Cevap: A - + `city` değişkenini, `person` nesnesindeki `city` özelliğinin değerine eşitledik. `person` nesnesinde `city` diye isimlendirilmiş bir özellik yok, bu yüzden `city` değişkeni `undefined` değerine sahip olur. `person` nesnesinin kendisini referans _göstermediğimize_ dikkat edin! Sadece `city` değişkenini, `person` nesnesindeki `city` özelliğinin o andaki değerine eşitledik. Sonra, `city`'i `"Amsterdam"` string'ine eşitledik. Bu `person` nesnesini değiştirmez: bu nesneye referans yok. - + `person` nesnesini logladığımız zaman, değişikliğe uğramamış nesne döndürülür.

@@ -2643,15 +2651,15 @@ Sonra, `city`'i `"Amsterdam"` string'ine eşitledik. Bu `person` nesnesini deği ```javascript function checkAge(age) { if (age < 18) { - const message = "Sorry, you're too young." + const message = "Sorry, you're too young."; } else { - const message = "Yay! You're old enough!" + const message = "Yay! You're old enough!"; } - return message + return message; } -console.log(checkAge(21)) +console.log(checkAge(21)); ``` - A: `"Sorry, you're too young."` @@ -2674,15 +2682,15 @@ console.log(checkAge(21)) ###### 85. Loglanacak değer ne tür olur? ```javascript -fetch('https://www.website.com/api/user/1') - .then(res => res.json()) - .then(res => console.log(res)) +fetch("https://www.website.com/api/user/1") + .then((res) => res.json()) + .then((res) => console.log(res)); ``` - A: `fetch` methodunun sonucu. - B: `fetch` methodunun ikinci kez çağrılmasından dönen sonuç. - C: Bir önceki `.then()`'in sonucu. -- D: Her zaman `undefined` olacaktır. +- D: Her zaman `undefined` olacaktır.
Cevap

@@ -2730,7 +2738,7 @@ function getName(name) { ###### 87. Çıktısı Nedir? ```javascript -console.log("I want pizza"[0]) +console.log("I want pizza"[0]); ``` - A: `"""` @@ -2756,10 +2764,10 @@ Bu yöntemin IE7 ve altında desteklenmediğine dikkat edin. Bu durumda, `.charA ```javascript function sum(num1, num2 = num1) { - console.log(num1 + num2) + console.log(num1 + num2); } -sum(10) +sum(10); ``` - A: `NaN` @@ -2773,7 +2781,7 @@ sum(10) #### Cevap: B Varsayılan parametrenin değerini fonksiyonun başka parametresine eşitleyebilirsiniz, varsayılan parametreden _önce_ tanımladıkları müddetçe. `sum` fonksiyonuna `10` değerini geçtik. Eğer `sum` fonksiyonu sadece 1 argüman alırsa, `num2` değeri geçilmedi demektir, ve `num1`'ın değeri geçtiğimiz `10` değerine eşittir bu durumda. `num2`'nun varsayılan değeri `num1`'dır ki o da `10`'dur. `num1 + num2` `20` döndürür. - + Eğer varsayılan parametrenin değerini, _sonrasında_ (sağında) tanımlanmış bir parametreye eşitlemeye çalışıyorsanız, parametrenin değeri henüz oluşturulmamıştır, hata fırlatacaktır.

@@ -2784,14 +2792,14 @@ Eğer varsayılan parametrenin değerini, _sonrasında_ (sağında) tanımlanmı ###### 89. Çıktısı Nedir? ```javascript -// module.js -export default () => "Hello world" -export const name = "Lydia" +// module.js +export default () => "Hello world"; +export const name = "Lydia"; -// index.js -import * as data from "./module" +// index.js +import * as data from "./module"; -console.log(data) +console.log(data); ``` - A: `{ default: function default(), name: "Lydia" }` @@ -2818,12 +2826,12 @@ console.log(data) ```javascript class Person { constructor(name) { - this.name = name + this.name = name; } } -const member = new Person("John") -console.log(typeof member) +const member = new Person("John"); +console.log(typeof member); ``` - A: `"class"` @@ -2840,7 +2848,7 @@ Sınıflar fonksiyon yapıcıları için "syntactical sugar"dır. `Person` sın ```javascript function Person() { - this.name = name + this.name = name; } ``` @@ -2854,9 +2862,9 @@ Bir fonksiyon yapıcısını `new` ile çağırmak `Person` "instance" oluşturu ###### 91. Çıktısı Nedir? ```javascript -let newList = [1, 2, 3].push(4) +let newList = [1, 2, 3].push(4); -console.log(newList.push(5)) +console.log(newList.push(5)); ``` - A: `[1, 2, 3, 4, 5]` @@ -2869,7 +2877,7 @@ console.log(newList.push(5)) #### Cevap: D -`.push` methodu dizinin _yeni uzunluğunu_ döndürür, dizinin kendisini değil! `newList`'i `[1, 2, 3].push(4)`'a eşitleyerek, `newList`'i dizinin yeni uzunluğuna eşitledik: `4`. +`.push` methodu dizinin _yeni uzunluğunu_ döndürür, dizinin kendisini değil! `newList`'i `[1, 2, 3].push(4)`'a eşitleyerek, `newList`'i dizinin yeni uzunluğuna eşitledik: `4`. Sonra, `.push` methodunu `newList` üzerinde kullanmayı denedik. `newList` sayısal değer `4` olduğundan, `.push` methodunu kullanamayız: TypeError fırlatılır. @@ -2882,17 +2890,18 @@ Sonra, `.push` methodunu `newList` üzerinde kullanmayı denedik. `newList` say ```javascript function giveLydiaPizza() { - return "Here is pizza!" + return "Here is pizza!"; } -const giveLydiaChocolate = () => "Here's chocolate... now go hit the gym already." +const giveLydiaChocolate = () => + "Here's chocolate... now go hit the gym already."; -console.log(giveLydiaPizza.prototype) -console.log(giveLydiaChocolate.prototype) +console.log(giveLydiaPizza.prototype); +console.log(giveLydiaChocolate.prototype); ``` -- A: `{ constructor: ...}` `{ constructor: ...}` -- B: `{}` `{ constructor: ...}` +- A: `{ constructor: ...}` `{ constructor: ...}` +- B: `{}` `{ constructor: ...}` - C: `{ constructor: ...}` `{}` - D: `{ constructor: ...}` `undefined` @@ -2901,7 +2910,7 @@ console.log(giveLydiaChocolate.prototype) #### Cevap: D -Sıradan fonksiyonlar, `giveLydiaPizza` gibi, `constructor` özelliği olan `prototype` nesnesi özelliğine sahiptir. Ancak ok fonksiyonlar (arrow functions), `giveLydiaChocolate` gibi, bu `prototype` özelliğine sahip değildir. `giveLydiaChocolate.prototype` ile `prototype` özelliğine erişmeye çalışıldığında `undefined` döndürülür. +Sıradan fonksiyonlar, `giveLydiaPizza` gibi, `constructor` özelliği olan `prototype` nesnesi özelliğine sahiptir. Ancak ok fonksiyonlar (arrow functions), `giveLydiaChocolate` gibi, bu `prototype` özelliğine sahip değildir. `giveLydiaChocolate.prototype` ile `prototype` özelliğine erişmeye çalışıldığında `undefined` döndürülür.

@@ -2913,16 +2922,16 @@ Sıradan fonksiyonlar, `giveLydiaPizza` gibi, `constructor` özelliği olan `pro ```javascript const person = { name: "Lydia", - age: 21 -} + age: 21, +}; for (const [x, y] of Object.entries(person)) { - console.log(x, y) + console.log(x, y); } ``` - A: `name` `Lydia` ve `age` `21` -- B: `["name", "Lydia"]` ve `["age", 21]` +- B: `["name", "Lydia"]` ve `["age", 21]` - C: `["name", "age"]` ve `undefined` - D: `Error` @@ -2933,7 +2942,7 @@ for (const [x, y] of Object.entries(person)) { `Object.entries(person)` key ve nesneleri içeren dizilerden oluşan dizi döndürür: -`[ [ 'name', 'Lydia' ], [ 'age', 21 ] ]` +`[ [ 'name', 'Lydia' ], [ 'age', 21 ] ]` `for-of` döngüsünü kullanarak, dizi içindeki her bir elemanı gezebiliriz, alt dizileri bu örnekte. for-of döngüsü içinde alt dizileri `const [x, y]` kullanarak parçalayabiliriz. `x` alt dizideki ilk elemana, `y` alt dizideki ikinci elemana eşittir. @@ -2956,7 +2965,7 @@ getItems(["banana", "apple"], "pear", "orange") ``` - A: `["banana", "apple", "pear", "orange"]` -- B: `[["banana", "apple"], "pear", "orange"]` +- B: `[["banana", "apple"], "pear", "orange"]` - C: `["banana", "apple", ["pear"], "orange"]` - D: `SyntaxError` @@ -2969,10 +2978,10 @@ getItems(["banana", "apple"], "pear", "orange") ```javascript function getItems(fruitList, favoriteFruit, ...args) { - return [...fruitList, ...args, favoriteFruit] + return [...fruitList, ...args, favoriteFruit]; } -getItems(["banana", "apple"], "pear", "orange") +getItems(["banana", "apple"], "pear", "orange"); ``` Yukarıdaki örnek çalışır. `[ 'banana', 'apple', 'orange', 'pear' ]` dizisini döndürür. @@ -2986,17 +2995,14 @@ Yukarıdaki örnek çalışır. `[ 'banana', 'apple', 'orange', 'pear' ]` dizisi ```javascript function nums(a, b) { - if - (a > b) - console.log('a is bigger') - else - console.log('b is bigger') - return - a + b + if (a > b) console.log("a is bigger"); + else console.log("b is bigger"); + return; + a + b; } -console.log(nums(4, 2)) -console.log(nums(1, 2)) +console.log(nums(4, 2)); +console.log(nums(1, 2)); ``` - A: `a is bigger`, `6` ve `b is bigger`, `3` @@ -3009,13 +3015,13 @@ console.log(nums(1, 2)) #### Cevap: B -JavaScript'te, noktalı virgülü (`;`) özellikle yazmak _zorunda değiliz_, ancak JavaScript motoru ifadelerden sonra noktalı virgül eklemektedir. bu **Automatic Semicolon Insertion**, **Otomatik Noktalı Virgül Ekleme**, olarak adlandırılır. İfade, örneğin, değişkenler ya da `throw`, `return`, `break`, vb. gibi anahtar kelimeler olabilir. +JavaScript'te, noktalı virgülü (`;`) özellikle yazmak _zorunda değiliz_, ancak JavaScript motoru ifadelerden sonra noktalı virgül eklemektedir. bu **Automatic Semicolon Insertion**, **Otomatik Noktalı Virgül Ekleme**, olarak adlandırılır. İfade, örneğin, değişkenler ya da `throw`, `return`, `break`, vb. gibi anahtar kelimeler olabilir. + +Burada, bir `return` ifadesi yazdık, ve _yeni bir satırda_ başka bir değer olarak `a + b`. Ancak, `a + b` yeni satırda olduğundan, JavaScript motoru onun aslında bizim döndürmek istediğimiz değer olduğunu bilmiyor. Onun yerine, `return`'den sonra otomatik olarak noktalı virgül ekliyor. Şöyle düşünebilirsiniz: -Burada, bir `return` ifadesi yazdık, ve _yeni bir satırda_ başka bir değer olarak `a + b`. Ancak, `a + b` yeni satırda olduğundan, JavaScript motoru onun aslında bizim döndürmek istediğimiz değer olduğunu bilmiyor. Onun yerine, `return`'den sonra otomatik olarak noktalı virgül ekliyor. Şöyle düşünebilirsiniz: - ```javascript - return; - a + b +return; +a + b; ``` Fonksiyon `return` anahtar kelimesinden sonra çalışmayı durduracağından, `a + b` asla ulaşılamaz demektir. Eğer hiçbir değer döndürülmezse, fonksiyon `undefined` döndürür. Dikkat etmeniz gereken, `if/else` ifadelerinden sonra otomatik ekleme yapılmadığıdır! @@ -3030,18 +3036,18 @@ Fonksiyon `return` anahtar kelimesinden sonra çalışmayı durduracağından, ` ```javascript class Person { constructor() { - this.name = "Lydia" + this.name = "Lydia"; } } Person = class AnotherPerson { constructor() { - this.name = "Sarah" + this.name = "Sarah"; } -} +}; -const member = new Person() -console.log(member.name) +const member = new Person(); +console.log(member.name); ``` - A: `"Lydia"` @@ -3065,11 +3071,11 @@ Sınıfları diğer sınıf/fonksiyon yapıcılara eşitleyebiliriz. Bu örnekte ```javascript const info = { - [Symbol('a')]: 'b' -} + [Symbol("a")]: "b", +}; -console.log(info) -console.log(Object.keys(info)) +console.log(info); +console.log(Object.keys(info)); ``` - A: `{Symbol('a'): 'b'}` ve `["{Symbol('a')"]` @@ -3084,7 +3090,7 @@ console.log(Object.keys(info)) Symbol _sayılabilir_, "_enumerable_" değildir. Object.keys methodu nesne üzerindeki tüm _sayılabilir_ özellikleri döndürür. Symbol gizli kalır ve boş bir dizi döndürülür. Tüm nesne loglandığı zaman, bütün özellikler görülebilir, sayılabilir olmayanlar bile. -Bu symbol'ün birçok özelliğinden birisidir: tamamen benzersiz bir değer temsil etmenin yanında (ki nesneler üzerindeki kazara isim çakışmasını önler, örneğin aynı nesneye özellikler eklemek isteyen 2 kütüphaneyle çalışırken), ayrıca bu yolla nesne üzerindeki özellikleri "saklayabilirsiniz" (gerçi tamamen değil. `Object.getOwnPropertySymbols()` methodunu kullanarak symbol'lere hala erişebilirsiniz). +Bu symbol'ün birçok özelliğinden birisidir: tamamen benzersiz bir değer temsil etmenin yanında (ki nesneler üzerindeki kazara isim çakışmasını önler, örneğin aynı nesneye özellikler eklemek isteyen 2 kütüphaneyle çalışırken), ayrıca bu yolla nesne üzerindeki özellikleri "saklayabilirsiniz" (gerçi tamamen değil. `Object.getOwnPropertySymbols()` methodunu kullanarak symbol'lere hala erişebilirsiniz).

@@ -3116,13 +3122,13 @@ console.log(getUser(user)) `getList` fonksiyonu argüman olarak bir dizi alır. `getList` fonksiyonunun parentezleri arasında, bu diziyi anında parçalıyoruz. Şu şekilde görebilirsiniz: - `[x, ...y] = [1, 2, 3, 4]` +`[x, ...y] = [1, 2, 3, 4]` - `...y` rest parametresi ile, dizi içinde "geriye kalan" tüm argümanları topluyoruz. Geriye kalan argümanlar `2`, `3`, ve `4` bu durumda. `y`'nin değeri tüm rest parametleri içeren bir dizi. `x`'in değeri `1`'a eşit, yani `[x, y]` logladığımız zaman, `[1, [2, 3, 4]]` loglanır. +`...y` rest parametresi ile, dizi içinde "geriye kalan" tüm argümanları topluyoruz. Geriye kalan argümanlar `2`, `3`, ve `4` bu durumda. `y`'nin değeri tüm rest parametleri içeren bir dizi. `x`'in değeri `1`'a eşit, yani `[x, y]` logladığımız zaman, `[1, [2, 3, 4]]` loglanır. - `getUser` fonksiyonu bir nesne alıyor. Ok fonksiyonlar ile, eğer sadece bir değer döndürmek istiyorsak süslü parentezleri yazmak _zorunda değiliz._ Ancak, bir ok fonksiyondan bir _nesne_ döndürmek istiyorsanız, parentezler arasında yazmak zorundasınız, aksi halde değer döndürülmez! Aşağıdaki fonksiyon bir nesne döndürecektir: +`getUser` fonksiyonu bir nesne alıyor. Ok fonksiyonlar ile, eğer sadece bir değer döndürmek istiyorsak süslü parentezleri yazmak _zorunda değiliz._ Ancak, bir ok fonksiyondan bir _nesne_ döndürmek istiyorsanız, parentezler arasında yazmak zorundasınız, aksi halde değer döndürülmez! Aşağıdaki fonksiyon bir nesne döndürecektir: -```const getUser = user => ({ name: user.name, age: user.age })``` +`const getUser = user => ({ name: user.name, age: user.age })` Bu örnekte değer döndürülmediği için, fonksiyon `undefined` döndürür. @@ -3134,9 +3140,9 @@ Bu örnekte değer döndürülmediği için, fonksiyon `undefined` döndürür. ###### 99. Çıktısı Nedir? ```javascript -const name = "Lydia" +const name = "Lydia"; -console.log(name()) +console.log(name()); ``` - A: `SyntaxError` @@ -3149,11 +3155,11 @@ console.log(name()) #### Cevap: C - `name` değişkeni string bir değer saklıyor, ki bu bir fonksiyon değil, bu yüzden çağrılamaz. +`name` değişkeni string bir değer saklıyor, ki bu bir fonksiyon değil, bu yüzden çağrılamaz. -TypeError'lar bir değer beklenilen tipte olmadığı zaman fırlatılır. `name`'i çağırmaya çalıştığımızdan, JavaScript `name`'in bir fonksiyon olmasını bekliyor. Ancak o bir string, bu yüzden TypeError fırlatılır: name is not a function! +TypeError'lar bir değer beklenilen tipte olmadığı zaman fırlatılır. `name`'i çağırmaya çalıştığımızdan, JavaScript `name`'in bir fonksiyon olmasını bekliyor. Ancak o bir string, bu yüzden TypeError fırlatılır: name is not a function! -SyntaxError'lar JavaScript'in geçerli olmadığı bir şeyler yazdığız zaman fırlatılır, örneğin `return`'ü `retrun` olarak yazdığınız zaman. +SyntaxError'lar JavaScript'in geçerli olmadığı bir şeyler yazdığız zaman fırlatılır, örneğin `return`'ü `retrun` olarak yazdığınız zaman. ReferenceError'lar erişmeye çalıştığınız değer için JavaScript referans bulamadığı zaman fırlatılır. @@ -3167,8 +3173,8 @@ ReferenceError'lar erişmeye çalıştığınız değer için JavaScript referan ```javascript // 🎉✨ 100. soru! ✨🎉 -const output = `${[] && 'Im'}possible! -You should${'' && `n't`} see a therapist after so much JavaScript lol` +const output = `${[] && "Im"}possible! +You should${"" && `n't`} see a therapist after so much JavaScript lol`; ``` - A: `possible! You should see a therapist after so much JavaScript lol` @@ -3183,7 +3189,7 @@ You should${'' && `n't`} see a therapist after so much JavaScript lol` `[]` doğrusal bir değerdir. `&&` operatörü ile, eğer soldaki değer doğrusal bir değerse sağdaki değer döndürülür. Bu örnekte, soldaki değer `[]` doğrusal bir değerdir, böylece `"Im"` döndürülür. -`""` yanlış-ımsı bir değerdir. Eğer soldaki değer yanlış-ımsı ise, bir şey döndürülmez. `n't` döndürülmedi. +`""` yanlış-ımsı bir değerdir. Eğer soldaki değer yanlış-ımsı ise, bir şey döndürülmez. `n't` döndürülmedi.

@@ -3193,11 +3199,11 @@ You should${'' && `n't`} see a therapist after so much JavaScript lol` ###### 101. Çıktısı Nedir? ```javascript -const one = (false || {} || null) -const two = (null || false || "") -const three = ([] || 0 || true) +const one = false || {} || null; +const two = null || false || ""; +const three = [] || 0 || true; -console.log(one, two, three) +console.log(one, two, three); ``` - A: `false` `null` `[]` diff --git a/uk-UA/README.md b/uk-UA/README.md index 3b38c921..aeb4f3ee 100644 --- a/uk-UA/README.md +++ b/uk-UA/README.md @@ -20,6 +20,7 @@ - [🇳🇱 Nederlands](../nl-NL/README.md) - [🇵🇱 Polski](../pl-PL/README.md) - [🇧🇷 Português Brasil](../pt-BR/README_pt_BR.md) +- [🇷o Română](../ro-RO/README.ro.md) - [🇷🇺 Русский](../ru-RU/README.md) - [🇽🇰 Shqip](../sq-KS/README_sq_KS.md) - [🇹🇭 ไทย](../th-TH/README-th_TH.md) @@ -100,7 +101,7 @@ const shape = { diameter() { return this.radius * 2; }, - perimeter: () => 2 * Math.PI * this.radius + perimeter: () => 2 * Math.PI * this.radius, }; shape.diameter(); @@ -157,12 +158,12 @@ shape.perimeter(); ```javascript const bird = { - size: "small" + size: "small", }; const mouse = { name: "Mickey", - small: true + small: true, }; ``` @@ -356,7 +357,7 @@ function Person(firstName, lastName) { } const member = new Person("Lydia", "Hallie"); -Person.getFullName = function() { +Person.getFullName = function () { return `${this.firstName} ${this.lastName}`; }; @@ -376,7 +377,7 @@ console.log(member.getFullName()); Не можна додавати властивості конструктору, як звичайному об'єкту. Якщо потрібно додати фічу до всіх об'єктів, то необхідно використовувати прототипи. В даному випадку, ```js -Person.prototype.getFullName = function() { +Person.prototype.getFullName = function () { return `${this.firstName} ${this.lastName}`; }; ``` @@ -832,7 +833,7 @@ String.prototype.giveLydiaPizza = () => { const name = "Lydia"; -console.log(name.giveLydiaPizza()) +console.log(name.giveLydiaPizza()); ``` - A: `"Just give Lydia pizza already!"` @@ -944,9 +945,7 @@ baz(); ```html
- +
``` @@ -972,9 +971,7 @@ baz(); ```html
-

- Click here! -

+

Click here!

``` @@ -1209,7 +1206,10 @@ console.log(numbers); ###### 40. Що буде в консолі? ```javascript -[[0, 1], [2, 3]].reduce( +[ + [0, 1], + [2, 3], +].reduce( (acc, cur) => { return acc.concat(cur); }, @@ -1344,21 +1344,20 @@ console.log(gen.next().value);

- --- ###### 45. Що повернеться? ```javascript const firstPromise = new Promise((res, rej) => { - setTimeout(res, 500, 'one'); + setTimeout(res, 500, "one"); }); const secondPromise = new Promise((res, rej) => { - setTimeout(res, 100, 'two'); + setTimeout(res, 100, "two"); }); -Promise.race([firstPromise, secondPromise]).then(res => console.log(res)); +Promise.race([firstPromise, secondPromise]).then((res) => console.log(res)); ``` - A: `"one"` @@ -1381,7 +1380,7 @@ Promise.race([firstPromise, secondPromise]).then(res => console.log(res)); ###### 46. Що буде на виході? ```javascript -let person = { name: 'Lydia' }; +let person = { name: "Lydia" }; const members = [person]; person = null; diff --git a/vi-VI/README-vi.md b/vi-VI/README-vi.md index 8750b2d6..249532dd 100644 --- a/vi-VI/README-vi.md +++ b/vi-VI/README-vi.md @@ -7,6 +7,7 @@ Các câu hỏi sẽ từ cơ bản đến nâng cao: kiểm tra trình độ Ja Các đáp án được đặt dưới mỗi câu hỏi, hãy click để tham khảo chúng. Chúc may mắn :heart: Danh sách các ngôn ngữ khác: + - [🇸🇦 العربية](../ar-AR/README_AR.md) - [🇪🇬 اللغة العامية](../ar-EG/README_ar-EG.md) - [🇧🇦 Bosanski](../bs-BS/README-bs_BS.md) @@ -21,6 +22,7 @@ Danh sách các ngôn ngữ khác: - [🇳🇱 Nederlands](../nl-NL/README.md) - [🇵🇱 Polski](../pl-PL/README.md) - [🇧🇷 Português Brasil](../pt-BR/README_pt_BR.md) +- [🇷o Română](../ro-RO/README.ro.md) - [🇷🇺 Русский](../ru-RU/README.md) - [🇽🇰 Shqip](../sq-KS/README_sq_KS.md) - [🇹🇭 ไทย](../th-TH/README-th_TH.md) @@ -101,7 +103,7 @@ const shape = { diameter() { return this.radius * 2; }, - perimeter: () => 2 * Math.PI * this.radius + perimeter: () => 2 * Math.PI * this.radius, }; shape.diameter(); @@ -147,7 +149,7 @@ Khi không có giá trị `radius` tại object đó, nó sẽ trả về `undef Phép toán cộng `+` sẽ convert một toán hạng sang dạng number. `true` là `1`, và `false` is `0`. -Chuỗi `'Lydia'` là một _truthy value_. Điều chúng ta thật sự đang hỏi chính là "có phải một giá trị truthy là falsy?". Rõ ràng câu trả lời là `false` rồi. +Chuỗi `'Lydia'` là một _truthy value_. Điều chúng ta thật sự đang hỏi chính là "có phải một giá trị truthy là falsy?". Rõ ràng câu trả lời là `false` rồi.

@@ -158,12 +160,12 @@ Chuỗi `'Lydia'` là một _truthy value_. Điều chúng ta thật sự đang ```javascript const bird = { - size: "small" + size: "small", }; const mouse = { name: "Mickey", - small: true + small: true, }; ``` @@ -183,14 +185,13 @@ JavaScript thông dịch (hay unboxes) từng câu lệnh. Khi chúng ta sử d `mouse[bird.size]`: Giá trị đầu tiên `bird.size` là `"small"`. `mouse["small"]` sẽ trả về `true` -Tuy nhiên, khi chúng ta sử dụng dấu chấm `.`, điều trên không còn đúng nữa. `mouse` không hề có key nào tên là `bird`, có nghĩa `mouse.bird` sẽ là `undefined`. Sau đó chúng ta gọi `size` sử dụng chấm `.`: `mouse.bird.size`. Vì `mouse.bird` là `undefined`, lời gọi sẽ trở thành `undefined.size`. Đây là một lời gọi không hợp lệ, nó sẽ throw ra một lỗi kiểu như `Cannot read property "size" of undefined`. +Tuy nhiên, khi chúng ta sử dụng dấu chấm `.`, điều trên không còn đúng nữa. `mouse` không hề có key nào tên là `bird`, có nghĩa `mouse.bird` sẽ là `undefined`. Sau đó chúng ta gọi `size` sử dụng chấm `.`: `mouse.bird.size`. Vì `mouse.bird` là `undefined`, lời gọi sẽ trở thành `undefined.size`. Đây là một lời gọi không hợp lệ, nó sẽ throw ra một lỗi kiểu như `Cannot read property "size" of undefined`.

--- - ###### 6. Output là gì? ```javascript @@ -213,7 +214,7 @@ console.log(d.greeting); #### Đáp án: A -Trong JavaScript, tất cả các object sẽ được _tham chiếu_ khi chúng được gán _bằng_wwwww một giá trị khác. +Trong JavaScript, tất cả các object sẽ được _tham chiếu_ khi chúng được gán \_bằng_wwwww một giá trị khác. Đầu tiên, giá trị `c` có giá trị là một object. Sau đó, chúng ta gán `d` tham chiếu tới object mà `c` trỏ tới. @@ -358,7 +359,7 @@ function Person(firstName, lastName) { } const member = new Person("Lydia", "Hallie"); -Person.getFullName = function() { +Person.getFullName = function () { return `${this.firstName} ${this.lastName}`; }; @@ -378,7 +379,7 @@ console.log(member.getFullName()); Chúng ta không thể add thêm một thuộc tính cho một constructor giống như một object thông thường. Nếu bạn muốn add thêm thuộc tính nào đó cho tất cả các object một lần, bạn phải dùng `prototype`. Trong trường hợp này cũng vậy. ```js -Person.prototype.getFullName = function() { +Person.prototype.getFullName = function () { return `${this.firstName} ${this.lastName}`; }; ``` @@ -835,7 +836,7 @@ String.prototype.giveLydiaPizza = () => { const name = "Lydia"; -console.log(name.giveLydiaPizza()) +console.log(name.giveLydiaPizza()); ``` - A: `"Just give Lydia pizza already!"` @@ -947,9 +948,7 @@ WebAPI không thể thêm thứ gì đó vào stack cho tới khi nó được s ```html
- +
``` @@ -975,9 +974,7 @@ Phần tử sâu nhất trong các phần tử lồng nhau sẽ là target của ```html
-

- Click here! -

+

Click here!

``` @@ -1212,7 +1209,10 @@ Primitive types là `boolean`, `null`, `undefined`, `bigint`, `number`, `string` ###### 40. Output là gì? ```javascript -[[0, 1], [2, 3]].reduce( +[ + [0, 1], + [2, 3], +].reduce( (acc, cur) => { return acc.concat(cur); }, @@ -1360,7 +1360,7 @@ const secondPromise = new Promise((res, rej) => { setTimeout(res, 100, "two"); }); -Promise.race([firstPromise, secondPromise]).then(res => console.log(res)); +Promise.race([firstPromise, secondPromise]).then((res) => console.log(res)); ``` - A: `"one"` @@ -1424,7 +1424,7 @@ Chúng ta chỉ đơn thuần là thay đổi giá trị của biến `person` m ```javascript const person = { name: "Lydia", - age: 21 + age: 21, }; for (const item in person) { @@ -1504,7 +1504,7 @@ Chỉ có số đầu tiên trong chuỗi kí tự được trả về. Hệ cơ ###### 50. Output là gì? ```javascript -[1, 2, 3].map(num => { +[1, 2, 3].map((num) => { if (typeof num === "number") return; return num * 2; }); @@ -1681,7 +1681,7 @@ class Dog { } } -Dog.prototype.bark = function() { +Dog.prototype.bark = function () { console.log(`Woof I am ${this.name}`); }; @@ -1767,7 +1767,7 @@ console.log(myCounter); #### Đáp án: C -Một module khi được import sẽ là __read-only__: chúng ta sẽ không thể chỉnh sửa module đó, chỉ có bản thân module đó có thể chỉnh sửa giá trị của nó mà thôi. +Một module khi được import sẽ là **read-only**: chúng ta sẽ không thể chỉnh sửa module đó, chỉ có bản thân module đó có thể chỉnh sửa giá trị của nó mà thôi. Khi ta thay đổi giá trị cuả `myCounter`, nó sẽ throw ra một lỗi: `myCounter` là _read-only_ và không thể thay đổi. @@ -1909,7 +1909,7 @@ Thêm nữa, các thuộc tính được thêm bởi `defineProperty` là mặc const settings = { username: "lydiahallie", level: 19, - health: 90 + health: 90, }; const data = JSON.stringify(settings, ["level", "health"]); @@ -1943,7 +1943,7 @@ Nếu replacer là _function_, hàm này sẽ được gọi trên từng thuộ let num = 10; const increaseNumber = () => num++; -const increasePassedNumber = number => number++; +const increasePassedNumber = (number) => number++; const num1 = increaseNumber(); const num2 = increasePassedNumber(num1); @@ -2000,9 +2000,9 @@ Trong ES6 thì chúng ta có thể khởi tạo tham số với giá trị mặc Chú ý một điều là đối số sẽ được xét giá trị tại _call time_! Có nghĩa là mỗi khi chúng ta gọi hàm, một _object mới_ sẽ được tạo ra. Chúng ta gọi hàm `multiply` hai lần mà không truyền vào đối số nào cả: `x` sẽ nhận giá trị mặc định `{ number: 10 }`. Sau đó chúng ta sẽ ghi ra giá trị là `20`. -Lần gọi thứ ba chúng ta truyền vào một đối số: chính là `value`. Toán tử `*=` chính là cách viết gọn của `x.number = x.number * 2`: chúng ta thay đổi giá trị của `x.number`, và ghi ra giá trị `20`. +Lần gọi thứ ba chúng ta truyền vào một đối số: chính là `value`. Toán tử `*=` chính là cách viết gọn của `x.number = x.number * 2`: chúng ta thay đổi giá trị của `x.number`, và ghi ra giá trị `20`. -Tại lần gọi thứ tư, chúng ta truyền vào `value` một lần nữa. `x.number` trước đó đã bị thay đổi thành `20`, nên `x.number *= 2` sẽ ghi ra `40`. +Tại lần gọi thứ tư, chúng ta truyền vào `value` một lần nữa. `x.number` trước đó đã bị thay đổi thành `20`, nên `x.number *= 2` sẽ ghi ra `40`.

@@ -2025,17 +2025,18 @@ Tại lần gọi thứ tư, chúng ta truyền vào `value` một lần nữa. #### Đáp án: D -Đối số đầu tiên của hàm `reduce` chính là _accumulator_ (tổng tích lũy), trong trường hợp này là `x`. Đối số thứ 2 chính là _giá trị hiện tại_, tức `y`. Với hàm reduce, ta sẽ gọi callback trên mỗi phần tử của mảng, cứ vậy cho tới khi ra đến một giá trị cuối cùng. +Đối số đầu tiên của hàm `reduce` chính là _accumulator_ (tổng tích lũy), trong trường hợp này là `x`. Đối số thứ 2 chính là _giá trị hiện tại_, tức `y`. Với hàm reduce, ta sẽ gọi callback trên mỗi phần tử của mảng, cứ vậy cho tới khi ra đến một giá trị cuối cùng. Trong trường hợp này, chúng ta không trả về bất cứ giá trị nào cả, mà đơn thuần chỉ là ghi ra giá trị của _tổng tích lũy_ và _giá trị hiện tại_ mà thôi. Giá trị của tổng tích lũy chính là giá trị được hàm callback trả về tại vòng lặp trước đó. Nếu ta không đặt giá trị khởi tạo cho đối số trong hàm `reduce`, thì tổng tích lũy sẽ chính bằng giá trị đầu tiên tại lời gọi đầu tiên. -Trong lời gọi đầu tiên, tổng tích lũy (`x`) là `1`, và giá trị hiện tại (`y`) là `2`. Chúng ta không trả về giá trị cho hàm callback, mà đơn thuần chỉ ghi chúng ta, vậy nên `1` và `2` được ghi ra. +Trong lời gọi đầu tiên, tổng tích lũy (`x`) là `1`, và giá trị hiện tại (`y`) là `2`. Chúng ta không trả về giá trị cho hàm callback, mà đơn thuần chỉ ghi chúng ta, vậy nên `1` và `2` được ghi ra. -Nếu ta không trả về giá trị trong một function, thì nó sẽ mặc định trả về là `undefined`. Do đó trong lời gọi tiếp theo tổng tích lũy sẽ là `undefined`, và giá trị hiện tại là `3`. `undefined` và `3` sẽ được ghi ra. +Nếu ta không trả về giá trị trong một function, thì nó sẽ mặc định trả về là `undefined`. Do đó trong lời gọi tiếp theo tổng tích lũy sẽ là `undefined`, và giá trị hiện tại là `3`. `undefined` và `3` sẽ được ghi ra. Tiếp tục như vậy, trong lời gọi thứ tư thì tổng tích lũy sẽ vẫn là `undefined`, giá trị hiện tại là `4`. `undefined` và `4` sẽ được ghi ra. +

@@ -2051,7 +2052,7 @@ class Dog { }; class Labrador extends Dog { - // 1 + // 1 constructor(name, size) { this.size = size; } @@ -2065,7 +2066,7 @@ class Labrador extends Dog { super(name); this.size = size; } - // 4 + // 4 constructor(name, size) { this.name = name; this.size = size; @@ -2086,9 +2087,10 @@ class Labrador extends Dog { Trong class dẫn xuất, ta không thể truy cập từ khóa `this` trước khi gọi `super`. Nếu bạn chạy thử, nó sẽ throw ra một `ReferenceError`, do đó 1 và 4 sẽ throw ra reference error. -Với việc gọi `super`, chúng ta đã gọi hàm constructor của class cha với tham số truyền vào. Trong trường hợp này, class cha nhận `name` làm đối số trong constructor, do đó chúng cần đưa `name` vào hàm `super`. +Với việc gọi `super`, chúng ta đã gọi hàm constructor của class cha với tham số truyền vào. Trong trường hợp này, class cha nhận `name` làm đối số trong constructor, do đó chúng cần đưa `name` vào hàm `super`. `Labrador` class nhận vào hai đối số, `name` vì nó kế thừa `Dog`, và `size` - một thuộc tính của `Labrador` class. Cả hai đều cần thiết để đưa vào trong constructor của class `Labrador`, do đó cách khởi tạo đúng là 2. +

@@ -2098,12 +2100,12 @@ Với việc gọi `super`, chúng ta đã gọi hàm constructor của class ch ```javascript // index.js -console.log('running index.js'); -import { sum } from './sum.js'; +console.log("running index.js"); +import { sum } from "./sum.js"; console.log(sum(1, 2)); // sum.js -console.log('running sum.js'); +console.log("running sum.js"); export const sum = (a, b) => a + b; ``` @@ -2119,7 +2121,7 @@ export const sum = (a, b) => a + b; Với `import`, tất cả các module import vào đều sẽ được _pre-parsed_ (đánh giá trước). Có nghĩa là những module được import vào sẽ được _chạy trước_, còn code trong file sẽ _chạy sau_. -Đó chính là điều khác biệt giữa `require()` trong CommonJS và `import`! Với `require()`, ta có thể load các dependencies tại bất cứ khi nào ta cần. Nếu ta sử dụng `require` thay thế cho `import` thì `running index.js`, `running sum.js`, `3` sẽ được ghi ra. +Đó chính là điều khác biệt giữa `require()` trong CommonJS và `import`! Với `require()`, ta có thể load các dependencies tại bất cứ khi nào ta cần. Nếu ta sử dụng `require` thay thế cho `import` thì `running index.js`, `running sum.js`, `3` sẽ được ghi ra.

@@ -2144,7 +2146,7 @@ console.log(Symbol('foo') === Symbol('foo'))**** #### Đáp án: A -Mỗi Symbol là một thứ hoàn toàn khác biệt. Giá trị truyền vào làm đối số trong Symbol chỉ đơn thuần là phần giải thích cho Symbol đó mà thôi, và nó không liên quan gì tới giá trị của Symbol đó cả. Chúng ta kiểm tra tính bằng nhau của hai Symbol hoàn toàn khác biệt: `Symbol('foo')` thứ nhất, và `Symbol('foo')` thứ hai. Mỗi giá trị đều là riêng biệt và duy nhất, nên `Symbol('foo') === Symbol('foo')` sẽ trả về `false`. +Mỗi Symbol là một thứ hoàn toàn khác biệt. Giá trị truyền vào làm đối số trong Symbol chỉ đơn thuần là phần giải thích cho Symbol đó mà thôi, và nó không liên quan gì tới giá trị của Symbol đó cả. Chúng ta kiểm tra tính bằng nhau của hai Symbol hoàn toàn khác biệt: `Symbol('foo')` thứ nhất, và `Symbol('foo')` thứ hai. Mỗi giá trị đều là riêng biệt và duy nhất, nên `Symbol('foo') === Symbol('foo')` sẽ trả về `false`.

@@ -2154,15 +2156,15 @@ Mỗi Symbol là một thứ hoàn toàn khác biệt. Giá trị truyền vào ###### 69. Output là gì? ```javascript -const name = "Lydia Hallie" -console.log(name.padStart(13)) -console.log(name.padStart(2)) +const name = "Lydia Hallie"; +console.log(name.padStart(13)); +console.log(name.padStart(2)); ``` - A: `"Lydia Hallie"`, `"Lydia Hallie"` - B: `" Lydia Hallie"`, `" Lydia Hallie"` (`"[13x whitespace]Lydia Hallie"`, `"[2x whitespace]Lydia Hallie"`) - C: `" Lydia Hallie"`, `"Lydia Hallie"` (`"[1x whitespace]Lydia Hallie"`, `"Lydia Hallie"`) -- D: `"Lydia Hallie"`, `"Lyd"`, +- D: `"Lydia Hallie"`, `"Lyd"`,
Đáp án

@@ -2237,7 +2239,9 @@ Khi ta gọi `game.next("Yes").value`, `yield` trước đó sẽ được thay

--- -**** + +--- + ###### 72. Output là gì? ```javascript @@ -2430,7 +2434,7 @@ Hàm `sum` luôn trả về giá trị giống nhau. Nếu ta đưa vào `1` và ```javascript const add = () => { const cache = {}; - return num => { + return (num) => { if (num in cache) { return `From cache! ${cache[num]}`; } else { @@ -2475,21 +2479,21 @@ Tại lần gọi thứ ba, ta đưa vào `5 * 2`, tức `10` vào hàm. Tiếp ###### 79. Output là gì? ```javascript -const myLifeSummedUp = ["☕", "💻", "🍷", "🍫"] +const myLifeSummedUp = ["☕", "💻", "🍷", "🍫"]; for (let item in myLifeSummedUp) { - console.log(item) + console.log(item); } for (let item of myLifeSummedUp) { - console.log(item) + console.log(item); } ``` - A: `0` `1` `2` `3` and `"☕"` ` "💻"` `"🍷"` `"🍫"` - B: `"☕"` ` "💻"` `"🍷"` `"🍫"` and `"☕"` ` "💻"` `"🍷"` `"🍫"` - C: `"☕"` ` "💻"` `"🍷"` `"🍫"` and `0` `1` `2` `3` -- D: `0` `1` `2` `3` and `{0: "☕", 1: "💻", 2: "🍷", 3: "🍫"}` +- D: `0` `1` `2` `3` and `{0: "☕", 1: "💻", 2: "🍷", 3: "🍫"}`
Đáp án

@@ -2512,14 +2516,14 @@ Với vòng lặp _for-of_, chúng ta sẽ duyệt qua các phần tử của m ###### 80. Output là gì? ```javascript -const list = [1 + 2, 1 * 2, 1 / 2] -console.log(list) +const list = [1 + 2, 1 * 2, 1 / 2]; +console.log(list); ``` - A: `["1 + 2", "1 * 2", "1 / 2"]` - B: `["12", 2, 0.5]` - C: `[3, 2, 0.5]` -- D: `[1, 1, 1]` +- D: `[1, 1, 1]`

Đáp án

@@ -2528,7 +2532,7 @@ console.log(list) Mảng có thể nhận bất cứ giá trị nào. Số, chuỗi, objects, mảng khác, null, boolean, undefined, và nhiều dạng biểu thức nữa như ngày tháng, hàm, và các tính toán. -Giá trị của phần tử chính là giá trị trả về. `1 + 2` trả về `3`, `1 * 2` trả về `2`, và `1 / 2` trả về `0.5`. +Giá trị của phần tử chính là giá trị trả về. `1 + 2` trả về `3`, `1 * 2` trả về `2`, và `1 / 2` trả về `0.5`.

@@ -2539,16 +2543,16 @@ Giá trị của phần tử chính là giá trị trả về. `1 + 2` trả v ```javascript function sayHi(name) { - return `Hi there, ${name}` + return `Hi there, ${name}`; } -console.log(sayHi()) +console.log(sayHi()); ``` - A: `Hi there, ` - B: `Hi there, undefined` - C: `Hi there, null` -- D: `ReferenceError` +- D: `ReferenceError`
Đáp án

@@ -2571,21 +2575,21 @@ Trong trường hợp này, nếu ta không đưa giá trị nào vào hoặc đ ###### 82. Output là gì? ```javascript -var status = "😎" +var status = "😎"; setTimeout(() => { - const status = "😍" + const status = "😍"; const data = { status: "🥑", getStatus() { - return this.status - } - } + return this.status; + }, + }; - console.log(data.getStatus()) - console.log(data.getStatus.call(this)) -}, 0) + console.log(data.getStatus()); + console.log(data.getStatus.call(this)); +}, 0); ``` - A: `"🥑"` and `"😍"` @@ -2612,13 +2616,13 @@ Với phương thức `call`, chúng ta thay đổi tham chiếu mà `this` tr ```javascript const person = { name: "Lydia", - age: 21 -} + age: 21, +}; -let city = person.city -city = "Amsterdam" +let city = person.city; +city = "Amsterdam"; -console.log(person) +console.log(person); ``` - A: `{ name: "Lydia", age: 21 }` @@ -2631,13 +2635,13 @@ console.log(person) #### Đáp án: A -Chúng ta set biến `city` bằng với giá trị của thuộc tính `city` của object `person`. Nhưng object này không có thuộc tính nào là `city` cả, nên giá trị của biến `city` sẽ là `undefined`. +Chúng ta set biến `city` bằng với giá trị của thuộc tính `city` của object `person`. Nhưng object này không có thuộc tính nào là `city` cả, nên giá trị của biến `city` sẽ là `undefined`. Chú ý là chúng ta _không tham chiếu_ tới bản thân object `person`! Chúng ta chỉ đơn giản là set giá trị của biến `city` bằng với giá trị của thuộc tính `city` trong object `person` mà thôi. Sau đó chúng ta set biến `city` bằng với chuỗi `"Amsterdam"`. Điều này không hề ảnh hưởng gì tới object person vì không có tham chiếu nào ở đây cả. -Do đó khi ghi object `person` ra, Tất cả các thuộc tính vẫn như cũ không hề thay đổi gì cả. +Do đó khi ghi object `person` ra, Tất cả các thuộc tính vẫn như cũ không hề thay đổi gì cả.

@@ -2649,15 +2653,15 @@ Do đó khi ghi object `person` ra, Tất cả các thuộc tính vẫn như cũ ```javascript function checkAge(age) { if (age < 18) { - const message = "Sorry, you're too young." + const message = "Sorry, you're too young."; } else { - const message = "Yay! You're old enough!" + const message = "Yay! You're old enough!"; } - return message + return message; } -console.log(checkAge(21)) +console.log(checkAge(21)); ``` - A: `"Sorry, you're too young."` @@ -2680,15 +2684,15 @@ Biến số được khai báo với các từ khóa như `const` hay `let` đ ###### 85. Những thông tin nào sẽ được ghi ra? ```javascript -fetch('https://www.website.com/api/user/1') - .then(res => res.json()) - .then(res => console.log(res)) +fetch("https://www.website.com/api/user/1") + .then((res) => res.json()) + .then((res) => console.log(res)); ``` - A: The result of the `fetch` method. - B: The result of the second invocation of the `fetch` method. - C: The result of the callback in the previous `.then()`. -- D: It would always be undefined. +- D: It would always be undefined.
Đáp án

@@ -2736,7 +2740,7 @@ Bằng cách set `hasName` bằng với `name`, chúng ta set `hasName` bằng v ###### 87. Output là gì? ```javascript -console.log("I want pizza"[0]) +console.log("I want pizza"[0]); ``` - A: `"""` @@ -2762,10 +2766,10 @@ Chú ý là phương thức này không hoạt động với IE7 trở xuống. ```javascript function sum(num1, num2 = num1) { - console.log(num1 + num2) + console.log(num1 + num2); } -sum(10) +sum(10); ``` - A: `NaN` @@ -2780,7 +2784,7 @@ sum(10) Ta có thể set giá trị mặc định của một tham số là tham số khác trong hàm, miễn là tham số đó được khai báo _trước_ tham số mặc định. Chúng ta đưa `10` vào hàm `sum`. Nếu hàm `sum` chỉ nhận 1 đối số, nó có nghĩa là giá trị của `num2` không được đưa vào, nên nó sẽ lấy giá trị mặc định là giá trị của `num1` đã được đưa vào, hay chính là `10` trong trường hợp này. Khi này `num1 + num2` trả về `20`. -Nếu chúng ta thử set một giá trị mặc định của tham số bằng với giá trị của tham số khai báo _sau_ (về bên phải), giá trị của tham số đó sẽ không được khởi tạo và dẫn đến throw ra lỗi. +Nếu chúng ta thử set một giá trị mặc định của tham số bằng với giá trị của tham số khai báo _sau_ (về bên phải), giá trị của tham số đó sẽ không được khởi tạo và dẫn đến throw ra lỗi.

@@ -2790,14 +2794,14 @@ Nếu chúng ta thử set một giá trị mặc định của tham số bằng ###### 89. Output là gì? ```javascript -// module.js -export default () => "Hello world" -export const name = "Lydia" +// module.js +export default () => "Hello world"; +export const name = "Lydia"; -// index.js -import * as data from "./module" +// index.js +import * as data from "./module"; -console.log(data) +console.log(data); ``` - A: `{ default: function default(), name: "Lydia" }` @@ -2810,9 +2814,9 @@ console.log(data) #### Đáp án: A -Cú pháp `import * as data` sẽ import _tất cả những gì được export_ từ `module.js` vào trong `index.js` và lưu trữ dưới một object có tên là `data`. Trong file `module.js`, có hai thứ được export ra: default export và một named export. Default export là một hàm trả về chuỗi `"Hello World"`, và named export là một biến `name` nhận giá trị là chuỗi `"Lydia"`. +Cú pháp `import * as data` sẽ import _tất cả những gì được export_ từ `module.js` vào trong `index.js` và lưu trữ dưới một object có tên là `data`. Trong file `module.js`, có hai thứ được export ra: default export và một named export. Default export là một hàm trả về chuỗi `"Hello World"`, và named export là một biến `name` nhận giá trị là chuỗi `"Lydia"`. -Do đó `data` object có thuộc tính `default` cho default export, các thuộc tính khác sẽ có tên chính là tên của named exports và giá trị đi kèm. +Do đó `data` object có thuộc tính `default` cho default export, các thuộc tính khác sẽ có tên chính là tên của named exports và giá trị đi kèm.

@@ -2824,12 +2828,12 @@ Do đó `data` object có thuộc tính `default` cho default export, các thu ```javascript class Person { constructor(name) { - this.name = name + this.name = name; } } -const member = new Person("John") -console.log(typeof member) +const member = new Person("John"); +console.log(typeof member); ``` - A: `"class"` @@ -2846,11 +2850,11 @@ Classes chỉ đơn thuần là `syntactical sugar` (cú pháp đặc biệt) c ```javascript function Person() { - this.name = name + this.name = name; } ``` -Gọi một constructor với từ khóa `new` sẽ tạo ra một instance của class `Person`, `typeof` sẽ trả về là `"object"` cho các instance. Do đó `typeof member` trả về `"object"`. +Gọi một constructor với từ khóa `new` sẽ tạo ra một instance của class `Person`, `typeof` sẽ trả về là `"object"` cho các instance. Do đó `typeof member` trả về `"object"`.

@@ -2860,9 +2864,9 @@ Gọi một constructor với từ khóa `new` sẽ tạo ra một instance củ ###### 91. Output là gì? ```javascript -let newList = [1, 2, 3].push(4) +let newList = [1, 2, 3].push(4); -console.log(newList.push(5)) +console.log(newList.push(5)); ``` - A: `[1, 2, 3, 4, 5]` @@ -2875,7 +2879,7 @@ console.log(newList.push(5)) #### Đáp án: D -Hàm `.push` trả về _độ dài mới_ của mảng, chứ không phải bản thân mảng đó! Bằng cách set `newList` bằng với `[1, 2, 3].push(4)`, ta đã set cho `newList` giá trị là `4` - tức độ dài của mảng lúc này. +Hàm `.push` trả về _độ dài mới_ của mảng, chứ không phải bản thân mảng đó! Bằng cách set `newList` bằng với `[1, 2, 3].push(4)`, ta đã set cho `newList` giá trị là `4` - tức độ dài của mảng lúc này. Sau đó chúng ta tiến hành `.push` trên `newList`. Vì `newList` là một số thông thường, ta không thể dùng `.push` được, nên sẽ throw ra một TypeError. @@ -2888,17 +2892,18 @@ Sau đó chúng ta tiến hành `.push` trên `newList`. Vì `newList` là một ```javascript function giveLydiaPizza() { - return "Here is pizza!" + return "Here is pizza!"; } -const giveLydiaChocolate = () => "Here's chocolate... now go hit the gym already." +const giveLydiaChocolate = () => + "Here's chocolate... now go hit the gym already."; -console.log(giveLydiaPizza.prototype) -console.log(giveLydiaChocolate.prototype) +console.log(giveLydiaPizza.prototype); +console.log(giveLydiaChocolate.prototype); ``` -- A: `{ constructor: ...}` `{ constructor: ...}` -- B: `{}` `{ constructor: ...}` +- A: `{ constructor: ...}` `{ constructor: ...}` +- B: `{}` `{ constructor: ...}` - C: `{ constructor: ...}` `{}` - D: `{ constructor: ...}` `undefined` @@ -2907,7 +2912,7 @@ console.log(giveLydiaChocolate.prototype) #### Đáp án: D -Hàm thông thường giống như `giveLydiaPizza`, sẽ có thuộc tính `prototype` là một object (prototype object) với một thuộc tính là `constructor`. Còn `arrow functions` giống như `giveLydiaChocolate`thì không có thuộc tính `prototype` này. `undefined` trả về khi ta truy cập thuộc tính `prototype` bằng cách gọi `giveLydiaChocolate.prototype`. +Hàm thông thường giống như `giveLydiaPizza`, sẽ có thuộc tính `prototype` là một object (prototype object) với một thuộc tính là `constructor`. Còn `arrow functions` giống như `giveLydiaChocolate`thì không có thuộc tính `prototype` này. `undefined` trả về khi ta truy cập thuộc tính `prototype` bằng cách gọi `giveLydiaChocolate.prototype`.

@@ -2919,16 +2924,16 @@ Hàm thông thường giống như `giveLydiaPizza`, sẽ có thuộc tính `pro ```javascript const person = { name: "Lydia", - age: 21 -} + age: 21, +}; for (const [x, y] of Object.entries(person)) { - console.log(x, y) + console.log(x, y); } ``` - A: `name` `Lydia` và `age` `21` -- B: `["name", "Lydia"]` và `["age", 21]` +- B: `["name", "Lydia"]` và `["age", 21]` - C: `["name", "age"]` và `undefined` - D: `Error` @@ -2939,9 +2944,9 @@ for (const [x, y] of Object.entries(person)) { `Object.entries(person)` sẽ trả về một mảng của mảng, bao gồm các key và các object: -`[ [ 'name', 'Lydia' ], [ 'age', 21 ] ]` +`[ [ 'name', 'Lydia' ], [ 'age', 21 ] ]` -Khí sử dụng `for-of`, chúng ta sẽ duyệt qua từng thành phần của mảng, trong trường hợp này chính là những mảng con. Đồng thời tiến hành gán giá trị luôn trong vongf lặp for-of, bằng cách sử dụng `const [x, y]`. Khi này `x` sẽ là phần tử đầu tiên trong mảng con, `y` chính là phần tử thứ hai trong mảng con. +Khí sử dụng `for-of`, chúng ta sẽ duyệt qua từng thành phần của mảng, trong trường hợp này chính là những mảng con. Đồng thời tiến hành gán giá trị luôn trong vongf lặp for-of, bằng cách sử dụng `const [x, y]`. Khi này `x` sẽ là phần tử đầu tiên trong mảng con, `y` chính là phần tử thứ hai trong mảng con. Mảng con đầu tiên là `[ "name", "Lydia" ]`, nên `x` sẽ là `"name"`, và `y` sẽ là `"Lydia"`, và được ghi ra. Mảng con thứ hai là `[ "age", 21 ]`, nên `x` sẽ là `"age"`, và `y` sẽ là `21`, và được ghi ra. @@ -2962,7 +2967,7 @@ getItems(["banana", "apple"], "pear", "orange") ``` - A: `["banana", "apple", "pear", "orange"]` -- B: `[["banana", "apple"], "pear", "orange"]` +- B: `[["banana", "apple"], "pear", "orange"]` - C: `["banana", "apple", ["pear"], "orange"]` - D: `SyntaxError` @@ -2971,17 +2976,18 @@ getItems(["banana", "apple"], "pear", "orange") #### Đáp án: D -`...args` là cú pháp tham số cuối cùng. Giá trị của tham số cuối cùng chính là toàn bộ các đối số còn lại, **và nó là tham số cuối cùng duy nhất**! Trong trường hợp này, tham số cuối cùng lại là tham số thứ hai. Điều đó là không thể được, và sẽ throw ra một lỗi cú pháp. +`...args` là cú pháp tham số cuối cùng. Giá trị của tham số cuối cùng chính là toàn bộ các đối số còn lại, **và nó là tham số cuối cùng duy nhất**! Trong trường hợp này, tham số cuối cùng lại là tham số thứ hai. Điều đó là không thể được, và sẽ throw ra một lỗi cú pháp. ```javascript function getItems(fruitList, favoriteFruit, ...args) { - return [...fruitList, ...args, favoriteFruit] + return [...fruitList, ...args, favoriteFruit]; } -getItems(["banana", "apple"], "pear", "orange") +getItems(["banana", "apple"], "pear", "orange"); ``` Nếu ta code như thế này thì lại đúng. Giá trị trả về sẽ là `[ 'banana', 'apple', 'orange', 'pear' ]` +

@@ -2991,17 +2997,14 @@ Nếu ta code như thế này thì lại đúng. Giá trị trả về sẽ là ```javascript function nums(a, b) { - if - (a > b) - console.log('a is bigger') - else - console.log('b is bigger') - return - a + b + if (a > b) console.log("a is bigger"); + else console.log("b is bigger"); + return; + a + b; } -console.log(nums(4, 2)) -console.log(nums(1, 2)) +console.log(nums(4, 2)); +console.log(nums(1, 2)); ``` - A: `a is bigger`, `6` và `b is bigger`, `3` @@ -3014,13 +3017,13 @@ console.log(nums(1, 2)) #### Đáp án: B -Với JavaScript, ta _không bắt buộc_ phải viết dấu chấm phẩy (`;`), JavaScript engine sẽ tự động thêm vào sau mỗi câu lệnh. Nó gọi là **Automatic Semicolon Insertion**. Một câu lệnh có thể là khai báo biến, hoặc từ khóa như `throw`, `return`, `break`, vv. +Với JavaScript, ta _không bắt buộc_ phải viết dấu chấm phẩy (`;`), JavaScript engine sẽ tự động thêm vào sau mỗi câu lệnh. Nó gọi là **Automatic Semicolon Insertion**. Một câu lệnh có thể là khai báo biến, hoặc từ khóa như `throw`, `return`, `break`, vv. Ở đây ta sử dụng câu lệnh `return` ở một dòng và giá trị `a + b` ở một _dòng khác_. Tuy nhiên do khác dòng nên JS engine không thể biết đâu là giá trị ta thực sự muốn trả về. Thay vì thế, nó sẽ tự động thêm vào dấu chấm phẩy ngay sau `return` giống như này: ```javascript - return; - a + b +return; +a + b; ``` Có nghĩa là `a + b` sẽ không bao giờ được thực hiện, vì hàm đã được `return` rồi. Do không giá trị nào được trả về, nên giá trị trả về của hàm sẽ là `undefined`. Lưu ý là sẽ không tự động thêm dấu chấm phẩy ngay sau `if/else` đâu nhé! @@ -3035,18 +3038,18 @@ Có nghĩa là `a + b` sẽ không bao giờ được thực hiện, vì hàm đ ```javascript class Person { constructor() { - this.name = "Lydia" + this.name = "Lydia"; } } Person = class AnotherPerson { constructor() { - this.name = "Sarah" + this.name = "Sarah"; } -} +}; -const member = new Person() -console.log(member.name) +const member = new Person(); +console.log(member.name); ``` - A: `"Lydia"` @@ -3070,11 +3073,11 @@ Chúng ta có thể set một class với giá trị là một classes/function ```javascript const info = { - [Symbol('a')]: 'b' -} + [Symbol("a")]: "b", +}; -console.log(info) -console.log(Object.keys(info)) +console.log(info); +console.log(Object.keys(info)); ``` - A: `{Symbol('a'): 'b'}` và `["{Symbol('a')"]` @@ -3121,13 +3124,13 @@ console.log(getUser(user)) Hàm `getList` nhận vào một mảng các đối số, và tiến hành xử lý mảng đó luôn khi đưa vào hàm: - `[x, ...y] = [1, 2, 3, 4]` +`[x, ...y] = [1, 2, 3, 4]` - Với việc sử dụng cú pháp tham số cuối cùng `...y`, chúng ta đưa toàn bộ "những đối số còn lại" vào một mảng y. Trong trường hợp này đó là mảng gồm các phần tử `2`, `3` và `4`. Do đó giá trị của `y` lúc này chính là mảng `[2, 3, 4]`. Giá trị của `x` là `1`, nên khi ghi `[x, y]` ra, kết quả sẽ là `[1, [2, 3, 4]]`. +Với việc sử dụng cú pháp tham số cuối cùng `...y`, chúng ta đưa toàn bộ "những đối số còn lại" vào một mảng y. Trong trường hợp này đó là mảng gồm các phần tử `2`, `3` và `4`. Do đó giá trị của `y` lúc này chính là mảng `[2, 3, 4]`. Giá trị của `x` là `1`, nên khi ghi `[x, y]` ra, kết quả sẽ là `[1, [2, 3, 4]]`. Hàm `getUser` nhận vào một object. Với cú pháp arrow function, chúng ta sẽ không phải viết trong ngoặc nhọn `{}` nữa nếu ta chỉ muốn đơn thuần trả về giá trị. Tuy nhiên, nếu ta muốn trả về một _object_ t arrow function, ta sẽ phải viết chúng trong dấu ngoặc tròn `()`, nếu không thì sẽ không có giá trị nào được trả về! Ví dụ như sau: -```const getUser = user => ({ name: user.name, age: user.age })``` +`const getUser = user => ({ name: user.name, age: user.age })` Do không giá trị nào được trả về, kết quả sẽ là `undefined`. @@ -3139,9 +3142,9 @@ Do không giá trị nào được trả về, kết quả sẽ là `undefined`. ###### 99. Output là gì? ```javascript -const name = "Lydia" +const name = "Lydia"; -console.log(name()) +console.log(name()); ``` - A: `SyntaxError` @@ -3154,11 +3157,11 @@ console.log(name()) #### Đáp án: C -Biến `name` có giá trị là một chuỗi, không phải hàm, vì thế không thể gọi được. +Biến `name` có giá trị là một chuỗi, không phải hàm, vì thế không thể gọi được. TypeErrors sẽ được throw ra nếu một giá trị không được sử dụng đúng kiểu. JavaScript muốn `name` là một hàm khi ta tiến hành gọi nó. Nhưng nó là chuỗi, nên sẽ throw ra một TypeError. -SyntaxErrors sẽ được throw khi ta viết code không đúng cú pháp của JavaScript, ví dụ thay vì `return` ta viết `retrun`. +SyntaxErrors sẽ được throw khi ta viết code không đúng cú pháp của JavaScript, ví dụ thay vì `return` ta viết `retrun`. ReferenceErrors sẽ được throw ra khi Javascript không thể tìm được tham chiếu nào đến giá trị mà ta đang cố truy cập. @@ -3172,8 +3175,8 @@ ReferenceErrors sẽ được throw ra khi Javascript không thể tìm được ```javascript // 🎉✨ Đây là câu hỏi thứ 100 của tôi! ✨🎉 -const output = `${[] && 'Im'}possible! -You should${'' && `n't`} see a therapist after so much JavaScript lol` +const output = `${[] && "Im"}possible! +You should${"" && `n't`} see a therapist after so much JavaScript lol`; ``` - A: `possible! You should see a therapist after so much JavaScript lol` @@ -3198,11 +3201,11 @@ You should${'' && `n't`} see a therapist after so much JavaScript lol` ###### 101. Output là gì? ```javascript -const one = (false || {} || null) -const two = (null || false || "") -const three = ([] || 0 || true) +const one = false || {} || null; +const two = null || false || ""; +const three = [] || 0 || true; -console.log(one, two, three) +console.log(one, two, three); ``` - A: `false` `null` `[]` @@ -3231,20 +3234,20 @@ Với phép toán `||`, ta sẽ trả về giá trị truethy đầu tiên. Nế ###### 102. Output là gì? ```javascript -const myPromise = () => Promise.resolve('I have resolved!') +const myPromise = () => Promise.resolve("I have resolved!"); function firstFunction() { - myPromise().then(res => console.log(res)) - console.log('second') + myPromise().then((res) => console.log(res)); + console.log("second"); } async function secondFunction() { - console.log(await myPromise()) - console.log('second') + console.log(await myPromise()); + console.log("second"); } -firstFunction() -secondFunction() +firstFunction(); +secondFunction(); ``` - A: `I have resolved!`, `second` và `I have resolved!`, `second` @@ -3261,11 +3264,11 @@ Có thể tưởng tượng đơn giản cách promise thực thi như sau: _bâ Dù chúng ta có thể sử dụng giá trị thu được bằng cú pháp `.then`, hoặc sử dụng cặp cú pháp `await/async`, nhưng, cách chúng hoạt động là khác nhau. -Trong `firstFunction`, chúng ta đưa promise qua một bên chờ cho nó tính toán xong, và vẫn tiếp tục chạy những code tiếp sau đó, theo đó `console.log('second')` sẽ được chạy. Sau đó promise được hoàn thành trả về giá trị `I have resolved`, giá trị này sẽ được log ra khi call stack trở nên rỗng. +Trong `firstFunction`, chúng ta đưa promise qua một bên chờ cho nó tính toán xong, và vẫn tiếp tục chạy những code tiếp sau đó, theo đó `console.log('second')` sẽ được chạy. Sau đó promise được hoàn thành trả về giá trị `I have resolved`, giá trị này sẽ được log ra khi call stack trở nên rỗng. Với từ khóa `await` trong `secondFunction`, ta đã tạm dừng một hàm bất đồng bộ cho tới khi chúng trả về giá trị, sau đó ta mới đi tiếp đến các câu lệnh tiếp theo. -Do đó nó sẽ chờ cho tới khi `myPromise` được hoàn thành và trả về giá trị `I have resolved`, sau đó chúng ta sẽ chạy tiếp câu lệnh tiếp theo in ra `second`. +Do đó nó sẽ chờ cho tới khi `myPromise` được hoàn thành và trả về giá trị `I have resolved`, sau đó chúng ta sẽ chạy tiếp câu lệnh tiếp theo in ra `second`.

@@ -3275,14 +3278,14 @@ Do đó nó sẽ chờ cho tới khi `myPromise` được hoàn thành và trả ###### 103. Output là gì? ```javascript -const set = new Set() +const set = new Set(); -set.add(1) -set.add("Lydia") -set.add({ name: "Lydia" }) +set.add(1); +set.add("Lydia"); +set.add({ name: "Lydia" }); for (let item of set) { - console.log(item + 2) + console.log(item + 2); } ``` @@ -3296,11 +3299,11 @@ for (let item of set) { #### Đáp án: C -Phép toán `+` không chỉ dùng để cộng các số, mà nó còn dùng để nối chuỗi nữa. Mỗi khi Javascript engine gặp một giá trị trong phép toán không phải dạng số, nó sẽ chuyển các số trong phép toán đó sang dạng chuỗi. +Phép toán `+` không chỉ dùng để cộng các số, mà nó còn dùng để nối chuỗi nữa. Mỗi khi Javascript engine gặp một giá trị trong phép toán không phải dạng số, nó sẽ chuyển các số trong phép toán đó sang dạng chuỗi. Phép toán đầu tiên item là một số `1`, nên `1 + 2` trả về 3. -Ở phép toán thứ hai, item là một chuỗi `"Lydia"`. trong khi đó `2` là một số, nên `2` sẽ bị chuyển sang dạng chuỗi, sau khi nối vào ta có chuỗi `"Lydia2"`. +Ở phép toán thứ hai, item là một chuỗi `"Lydia"`. trong khi đó `2` là một số, nên `2` sẽ bị chuyển sang dạng chuỗi, sau khi nối vào ta có chuỗi `"Lydia2"`. Ở phép toán thứ ba, `{ name: "Lydia" }` là một object. Tuy nhiên dù có là object hay gì đi nữa thì nó cũng sẽ bị chuyển sang dạng chuỗi. Đối với object thì khi chuyển sang dạng chuỗi nó sẽ trở thành `"[object Object]"`. `"[object Object]"` nối với `"2"` trở thành `"[object Object]2"`. @@ -3312,7 +3315,7 @@ Phép toán đầu tiên item là một số `1`, nên `1 + 2` trả về 3. ###### 104. Output là gì? ```javascript -Promise.resolve(5) +Promise.resolve(5); ``` - A: `5` @@ -3327,7 +3330,7 @@ Promise.resolve(5) Ta có thể truyền vào giá trị bất kì cho `Promise.resolve`, dù có là promise hay không promise. Bản thân nó sẽ là một hàm trả về một promise với giá trị đã được resolved. -Trong trường hợp này ta đưa vào giá trị `5`. Nó sẽ trả về một resolved promise với giá trị `5`. +Trong trường hợp này ta đưa vào giá trị `5`. Nó sẽ trả về một resolved promise với giá trị `5`.

@@ -3339,15 +3342,15 @@ Trong trường hợp này ta đưa vào giá trị `5`. Nó sẽ trả về m ```javascript function compareMembers(person1, person2 = person) { if (person1 !== person2) { - console.log("Not the same!") + console.log("Not the same!"); } else { - console.log("They are the same!") + console.log("They are the same!"); } } -const person = { name: "Lydia" } +const person = { name: "Lydia" }; -compareMembers(person) +compareMembers(person); ``` - A: `Not the same!` @@ -3360,7 +3363,7 @@ compareMembers(person) #### Đáp án: B -Object sẽ được truyền vào hàm theo reference. Khi chúng ta nói so sánh strict equal (`===`), nghĩa là ta đang so sánh các reference của chúng. +Object sẽ được truyền vào hàm theo reference. Khi chúng ta nói so sánh strict equal (`===`), nghĩa là ta đang so sánh các reference của chúng. Ta set giá trị mặc định của `person2` là object `person`, và đưa object `person` vào làm giá trị cho đối số `person1`. @@ -3380,11 +3383,11 @@ const colorConfig = { green: true, black: true, yellow: false, -} +}; -const colors = ["pink", "red", "blue"] +const colors = ["pink", "red", "blue"]; -console.log(colorConfig.colors[1]) +console.log(colorConfig.colors[1]); ``` - A: `true` @@ -3397,11 +3400,11 @@ console.log(colorConfig.colors[1]) #### Đáp án: D -Trong Javascript ta có hai cách để truy cập thuộc tính của một object: sử dụng ngoặc vuông `[]`, hoặc sử dụng chấm `.`. Trong trương hợp này chúng ta sử dụng chấm (`colorConfig.colors`) thay cho ngoặc vuông (`colorConfig["colors"]`). +Trong Javascript ta có hai cách để truy cập thuộc tính của một object: sử dụng ngoặc vuông `[]`, hoặc sử dụng chấm `.`. Trong trương hợp này chúng ta sử dụng chấm (`colorConfig.colors`) thay cho ngoặc vuông (`colorConfig["colors"]`). -Với cách sử dụng chấm, Javascript sẽ tìm kiếm một thuộc tính có tên chính xác như tên ta đưa vào. Trong trường hợp này nó là thuộc tính `colors` trong object `colorConfig` Tuy nhiên trong object này không có thuộc tính nào tên là `colors`, nên nó sẽ trả về `undefined`. Sau đó chúng ta cố truy cậ vào thuộc tính 1 của nó bằng cách gọi `[1]`. Chúng ta không thể làm như vậy trên giá trị `undefined`, nên nó sẽ trả về `TypeError`: `Cannot read property '1' of undefined`. +Với cách sử dụng chấm, Javascript sẽ tìm kiếm một thuộc tính có tên chính xác như tên ta đưa vào. Trong trường hợp này nó là thuộc tính `colors` trong object `colorConfig` Tuy nhiên trong object này không có thuộc tính nào tên là `colors`, nên nó sẽ trả về `undefined`. Sau đó chúng ta cố truy cậ vào thuộc tính 1 của nó bằng cách gọi `[1]`. Chúng ta không thể làm như vậy trên giá trị `undefined`, nên nó sẽ trả về `TypeError`: `Cannot read property '1' of undefined`. -Javascript thông dịch theo câu lệnh. Khi ta sử dụng ngoặc vuông, Nnó sẽ tìm mở ngoặc đầu tiên `[` và tiếp tục cho tới khi gặp đóng ngoặc tương ứng `]`. Chỉ khi đó nó mới đánh giá câu lệnh. Nếu chúng ta sử dụng cú pháp `colorConfig[colors[1]]`, nó sẽ trả về giá trị của thuộc tính `red` trong object `colorConfig`. +Javascript thông dịch theo câu lệnh. Khi ta sử dụng ngoặc vuông, Nnó sẽ tìm mở ngoặc đầu tiên `[` và tiếp tục cho tới khi gặp đóng ngoặc tương ứng `]`. Chỉ khi đó nó mới đánh giá câu lệnh. Nếu chúng ta sử dụng cú pháp `colorConfig[colors[1]]`, nó sẽ trả về giá trị của thuộc tính `red` trong object `colorConfig`.

@@ -3411,7 +3414,7 @@ Javascript thông dịch theo câu lệnh. Khi ta sử dụng ngoặc vuông, Nn ###### 107. Ouput là gì? ```javascript -console.log('❤️' === '❤️') +console.log("❤️" === "❤️"); ``` - A: `true` @@ -3422,7 +3425,7 @@ console.log('❤️' === '❤️') #### Đáp án: A -Về cơ bản, emoji vẫn là các ký tự unicode mà thôi. Mã unicode cho hình trái tim là `"U+2764 U+FE0F"`. Chúng luôn luôn là một, nên phép toán đơn giản trả về `true`. +Về cơ bản, emoji vẫn là các ký tự unicode mà thôi. Mã unicode cho hình trái tim là `"U+2764 U+FE0F"`. Chúng luôn luôn là một, nên phép toán đơn giản trả về `true`.

@@ -3432,19 +3435,19 @@ Về cơ bản, emoji vẫn là các ký tự unicode mà thôi. Mã unicode cho ###### 108. Phép toán nào sau đây làm thay đổi mảng gốc? ```javascript -const emojis = ['✨', '🥑', '😍'] +const emojis = ["✨", "🥑", "😍"]; -emojis.map(x => x + '✨') -emojis.filter(x => x !== '🥑') -emojis.find(x => x !== '🥑') -emojis.reduce((acc, cur) => acc + '✨') -emojis.slice(1, 2, '✨') -emojis.splice(1, 2, '✨') +emojis.map((x) => x + "✨"); +emojis.filter((x) => x !== "🥑"); +emojis.find((x) => x !== "🥑"); +emojis.reduce((acc, cur) => acc + "✨"); +emojis.slice(1, 2, "✨"); +emojis.splice(1, 2, "✨"); ``` - A: `All of them` - B: `map` `reduce` `slice` `splice` -- C: `map` `slice` `splice` +- C: `map` `slice` `splice` - D: `splice`
Đáp án @@ -3452,7 +3455,7 @@ emojis.splice(1, 2, '✨') #### Đáp án: D -Với `splice`, ta thay đổi mảng gốc bằng cách thêm sửa xóa các phần tử. Trong trường hợp này ta xóa 2 phần tử kể từ index 1 (ta xóa `'🥑'` và `'😍'`) và thêm vào ✨ emoji. +Với `splice`, ta thay đổi mảng gốc bằng cách thêm sửa xóa các phần tử. Trong trường hợp này ta xóa 2 phần tử kể từ index 1 (ta xóa `'🥑'` và `'😍'`) và thêm vào ✨ emoji. `map`, `filter` và `slice` trả về một mảng mới, `find` trả về một phần tử, và `reduce` trả về giá trị tích lũy. @@ -3464,17 +3467,17 @@ Với `splice`, ta thay đổi mảng gốc bằng cách thêm sửa xóa các p ###### 109. Output là gì? ```javascript -const food = ['🍕', '🍫', '🥑', '🍔'] -const info = { favoriteFood: food[0] } +const food = ["🍕", "🍫", "🥑", "🍔"]; +const info = { favoriteFood: food[0] }; -info.favoriteFood = '🍝' +info.favoriteFood = "🍝"; -console.log(food) +console.log(food); ``` - A: `['🍕', '🍫', '🥑', '🍔']` - B: `['🍝', '🍫', '🥑', '🍔']` -- C: `['🍝', '🍕', '🍫', '🥑', '🍔']` +- C: `['🍝', '🍕', '🍫', '🥑', '🍔']` - D: `ReferenceError`
Đáp án @@ -3494,7 +3497,7 @@ Bản thân mảng `food` không hề thay đổi, do giá trị của `favorite ###### 110. Phép toán này dùng để làm gì? ```javascript -JSON.parse() +JSON.parse(); ``` - A: Parse JSON thành một giá trị JavaScript @@ -3507,22 +3510,22 @@ JSON.parse() #### Đáp án: A -Với phương thức `JSON.parse()`, ta sẽ parse một chuỗi JSON thành một giá trị JavaScript. +Với phương thức `JSON.parse()`, ta sẽ parse một chuỗi JSON thành một giá trị JavaScript. Ví dụ: ```javascript // Chuyển một số thành một chuỗi JSON, sau đó parse chuỗi JSON đó để trả về một giá trị JavaScript: -const jsonNumber = JSON.stringify(4) // '4' -JSON.parse(jsonNumber) // 4 +const jsonNumber = JSON.stringify(4); // '4' +JSON.parse(jsonNumber); // 4 // Chuyển một mảng thành một chuỗi JSON, sau đó parse chuỗi JSON để trả về một giá trị JavaScript: -const jsonArray = JSON.stringify([1, 2, 3]) // '[1, 2, 3]' -JSON.parse(jsonArray) // [1, 2, 3] +const jsonArray = JSON.stringify([1, 2, 3]); // '[1, 2, 3]' +JSON.parse(jsonArray); // [1, 2, 3] // Chuyển một object thành một chuỗi JSON, sau đó parse chuỗi JSON để trả về một giá trị JavaScript: -const jsonArray = JSON.stringify({ name: "Lydia" }) // '{"name":"Lydia"}' -JSON.parse(jsonArray) // { name: 'Lydia' } +const jsonArray = JSON.stringify({ name: "Lydia" }); // '{"name":"Lydia"}' +JSON.parse(jsonArray); // { name: 'Lydia' } ```

@@ -3530,17 +3533,17 @@ JSON.parse(jsonArray) // { name: 'Lydia' } --- -###### 111. Ouput là gì? +###### 111. Ouput là gì? ```javascript -let name = 'Lydia' +let name = "Lydia"; function getName() { - console.log(name) - let name = 'Sarah' + console.log(name); + let name = "Sarah"; } -getName() +getName(); ``` - A: Lydia @@ -3553,20 +3556,20 @@ getName() #### Đáp án: D -Mỗi hàm sẽ có một _context thực thi_ (hay _scope_) của riêng nó. Hàm `getName` đầu tiên sẽ tìm trong context của nó (scope) để tìm xem có biến nào tên là `name` hay không. Trong trường hợp này, hàm `getName` có biến `name` được khai báo với từ khóa `let`, giá trị là `'Sarah'`. +Mỗi hàm sẽ có một _context thực thi_ (hay _scope_) của riêng nó. Hàm `getName` đầu tiên sẽ tìm trong context của nó (scope) để tìm xem có biến nào tên là `name` hay không. Trong trường hợp này, hàm `getName` có biến `name` được khai báo với từ khóa `let`, giá trị là `'Sarah'`. -Một biến được khai báo với từ khóa `let` (hoặc `const`) sẽ được `hoisted`, nhưng không giống như `var`, nó sẽ không được _khởi tạo_. Nó sẽ không thể truy cập được trước dòng ta khai báo (initialize). Nó được gọi là "temporal dead zone". Khi ta cố truy cập một biến trước khi nó được khai báo, JavaScript sẽ throw ra `ReferenceError`. +Một biến được khai báo với từ khóa `let` (hoặc `const`) sẽ được `hoisted`, nhưng không giống như `var`, nó sẽ không được _khởi tạo_. Nó sẽ không thể truy cập được trước dòng ta khai báo (initialize). Nó được gọi là "temporal dead zone". Khi ta cố truy cập một biến trước khi nó được khai báo, JavaScript sẽ throw ra `ReferenceError`. -Nếu ta không khai báo biến `name` bên trong hàm `getName`, thì Javascript engine sẽ tiếp tục tìm kiếm trong _scope chain_. Nó sẽ tìm thấy ở scope phía ngoài một biến `name` với giá trị là `Lydia`. Trong trường hợp này nó sẽ log ra `Lydia`. +Nếu ta không khai báo biến `name` bên trong hàm `getName`, thì Javascript engine sẽ tiếp tục tìm kiếm trong _scope chain_. Nó sẽ tìm thấy ở scope phía ngoài một biến `name` với giá trị là `Lydia`. Trong trường hợp này nó sẽ log ra `Lydia`. ```javascript -let name = 'Lydia' +let name = "Lydia"; function getName() { - console.log(name) + console.log(name); } -getName() // Lydia +getName(); // Lydia ```

@@ -3578,18 +3581,18 @@ getName() // Lydia ```javascript function* generatorOne() { - yield ['a', 'b', 'c']; + yield ["a", "b", "c"]; } function* generatorTwo() { - yield* ['a', 'b', 'c']; + yield* ["a", "b", "c"]; } -const one = generatorOne() -const two = generatorTwo() +const one = generatorOne(); +const two = generatorTwo(); -console.log(one.next().value) -console.log(two.next().value) +console.log(one.next().value); +console.log(two.next().value); ``` - A: `a` and `a` @@ -3607,17 +3610,17 @@ Với từ khóa `yield`, ta sẽ trả về các giá trị trong một `genera Trong `generatorOne`, ta trả về toàn bộ mảng `['a', 'b', 'c']` sử dụng từ khóa `yield`. Giá trị của thuộc tính `value` trong object thu được bởi phương thức `next` trong `one` (`one.next().value`) là toàn bộ mảng `['a', 'b', 'c']`. ```javascript -console.log(one.next().value) // ['a', 'b', 'c'] -console.log(one.next().value) // undefined +console.log(one.next().value); // ['a', 'b', 'c'] +console.log(one.next().value); // undefined ``` -Trong `generatorTwo`, ta sử dụng từ khóa `yield*`. Có nghĩa là giá trị đầu tiên mà `two` trả về là giá trị đầu tiên trong `iterator`. Trong trường hợp này `iterator` của chúng ta là mảng `['a', 'b', 'c']`. Giá trị đầu tiên của mảng là `a`, nên lần đầu tiên khi ta gọi `two.next().value`, `a` sẽ được trả về. +Trong `generatorTwo`, ta sử dụng từ khóa `yield*`. Có nghĩa là giá trị đầu tiên mà `two` trả về là giá trị đầu tiên trong `iterator`. Trong trường hợp này `iterator` của chúng ta là mảng `['a', 'b', 'c']`. Giá trị đầu tiên của mảng là `a`, nên lần đầu tiên khi ta gọi `two.next().value`, `a` sẽ được trả về. ```javascript -console.log(two.next().value) // 'a' -console.log(two.next().value) // 'b' -console.log(two.next().value) // 'c' -console.log(two.next().value) // undefined +console.log(two.next().value); // 'a' +console.log(two.next().value); // 'b' +console.log(two.next().value); // 'c' +console.log(two.next().value); // undefined ```

@@ -3628,7 +3631,7 @@ console.log(two.next().value) // undefined ###### 113. Output là gì? ```javascript -console.log(`${(x => x)('I love')} to program`) +console.log(`${((x) => x)("I love")} to program`); ``` - A: `I love to program` @@ -3641,7 +3644,7 @@ console.log(`${(x => x)('I love')} to program`) #### Đáp án: A -Biểu thức bên trong chuỗi template (tức chuỗi nằm trong hai dấu ``, gọi là `template literals`) sẽ được đánh giá trước. Sau đó kết quả của biểu thức sẽ được đưa vào chuỗi, trong trường hợp này biểu thức là `(x => x)('I love')`. Chúng ta truyền giá trị đối số `'I love'` cho một arrow function `x => x`. `x` lúc này là `'I love'`, và trả về chính nó. Cuối cùng kết quả của chuỗi là `I love to program`. +Biểu thức bên trong chuỗi template (tức chuỗi nằm trong hai dấu ``, gọi là `template literals`) sẽ được đánh giá trước. Sau đó kết quả của biểu thức sẽ được đưa vào chuỗi, trong trường hợp này biểu thức là `(x => x)('I love')`. Chúng ta truyền giá trị đối số `'I love'`cho một arrow function`x => x`. `x`lúc này là`'I love'`, và trả về chính nó. Cuối cùng kết quả của chuỗi là `I love to program`.

@@ -3653,11 +3656,11 @@ Biểu thức bên trong chuỗi template (tức chuỗi nằm trong hai dấu ` ```javascript let config = { alert: setInterval(() => { - console.log('Alert!') - }, 1000) -} + console.log("Alert!"); + }, 1000), +}; -config = null +config = null; ``` - A: Callback `setInterval` sẽ không được gọi @@ -3680,17 +3683,17 @@ Thông thường khi ta set một object bằng `null`, thì object này sẽ đ ###### 115. Những hàm nào sẽ trả về `'Hello world!'`? ```javascript -const myMap = new Map() -const myFunc = () => 'greeting' +const myMap = new Map(); +const myFunc = () => "greeting"; -myMap.set(myFunc, 'Hello world!') +myMap.set(myFunc, "Hello world!"); //1 -myMap.get('greeting') +myMap.get("greeting"); //2 -myMap.get(myFunc) +myMap.get(myFunc); //3 -myMap.get(() => 'greeting') +myMap.get(() => "greeting"); ``` - A: 1 @@ -3703,7 +3706,7 @@ myMap.get(() => 'greeting') #### Đáp án: B -Khi ta thêm vào một cặp key/value với từ khóa `set`, key sẽ là đối số đầu tiên đưa vào trong hàm `set` function, và value sẽ là đối số thứ hai.Trong trường hơp này key chính là _hàm_ `() => 'greeting'`, value là `'Hello world'`. `myMap` trở thành `{ () => 'greeting' => 'Hello world!' }`. +Khi ta thêm vào một cặp key/value với từ khóa `set`, key sẽ là đối số đầu tiên đưa vào trong hàm `set` function, và value sẽ là đối số thứ hai.Trong trường hơp này key chính là _hàm_ `() => 'greeting'`, value là `'Hello world'`. `myMap` trở thành `{ () => 'greeting' => 'Hello world!' }`. 1 sai, vì key là `() => 'greeting'` chứ không phải là `'greeting'`. 3 sai, vì khi chúng ta đưa một hàm vào làm đối số trong phương thức `get`, nó sẽ được đưa vào dưới dạng _reference_. Function vốn là object, do đó 2 hàm sẽ không bao giờ là `strictly equal`, mặc dù chúng có trông giống nhau đi chăng nữa thì chúng vẫn trỏ đến các vùng nhớ khác nhau. @@ -3718,19 +3721,19 @@ Khi ta thêm vào một cặp key/value với từ khóa `set`, key sẽ là đ ```javascript const person = { name: "Lydia", - age: 21 -} + age: 21, +}; -const changeAge = (x = { ...person }) => x.age += 1 +const changeAge = (x = { ...person }) => (x.age += 1); const changeAgeAndName = (x = { ...person }) => { - x.age += 1 - x.name = "Sarah" -} + x.age += 1; + x.name = "Sarah"; +}; -changeAge(person) -changeAgeAndName() +changeAge(person); +changeAgeAndName(); -console.log(person) +console.log(person); ``` - A: `{name: "Sarah", age: 22}` @@ -3743,7 +3746,7 @@ console.log(person) #### Đáp án: C -Cả hai hàm `changeAge` và `changeAgeAndName` đều có tham số mặc định - nó là một _bản copy_ mới của object `{ ...person }`. Object này sẽ copy tất cả những cặp key/values bên trong object `person`. +Cả hai hàm `changeAge` và `changeAgeAndName` đều có tham số mặc định - nó là một _bản copy_ mới của object `{ ...person }`. Object này sẽ copy tất cả những cặp key/values bên trong object `person`. Đầu tiên, chúng ta gọi hàm `changeAge` và đưa chính object `person` vào làm đối số. Hàm này sẽ tăng giá trị của thuộc tính `age` lên 1. `person` lúc này là `{ name: "Lydia", age: 22 }`. @@ -3758,7 +3761,7 @@ Sau đó, chúng ta gọi hàm `changeAgeAndName` tuy nhiên không đưa vào ```javascript function sumValues(x, y, z) { - return x + y + z; + return x + y + z; } ``` @@ -3809,15 +3812,15 @@ Với phép toán `+=`, Ta tăng giá trị của `num` lên `1`. `num` có giá ```javascript const person = { - firstName: "Lydia", - lastName: "Hallie", - pet: { - name: "Mara", - breed: "Dutch Tulip Hound" - }, - getFullName() { - return `${this.firstName} ${this.lastName}`; - } + firstName: "Lydia", + lastName: "Hallie", + pet: { + name: "Mara", + breed: "Dutch Tulip Hound", + }, + getFullName() { + return `${this.firstName} ${this.lastName}`; + }, }; console.log(person.pet?.name); @@ -3857,9 +3860,9 @@ Với phép toán optional chaining `?.`, chúng ta sẽ không cần phải che const groceries = ["banana", "apple", "peanuts"]; if (groceries.indexOf("banana")) { - console.log("We have to buy bananas!"); + console.log("We have to buy bananas!"); } else { - console.log(`We don't have to buy bananas!`); + console.log(`We don't have to buy bananas!`); } ``` @@ -3884,10 +3887,10 @@ Ta đưa một điều kiện `groceries.indexOf("banana")` vào câu lệnh `if ```javascript const config = { - languages: [], - set language(lang) { - return this.languages.push(lang); - } + languages: [], + set language(lang) { + return this.languages.push(lang); + }, }; console.log(config.language); @@ -3941,9 +3944,9 @@ console.log(!typeof name === "string"); ###### 123. Output là gì? ```javascript -const add = x => y => z => { - console.log(x, y, z); - return x + y + z; +const add = (x) => (y) => (z) => { + console.log(x, y, z); + return x + y + z; }; add(4)(5)(6); @@ -3970,16 +3973,16 @@ Hàm `add` trả về một arrow function, arrow function này lại trả về ```javascript async function* range(start, end) { - for (let i = start; i <= end; i++) { - yield Promise.resolve(i); - } + for (let i = start; i <= end; i++) { + yield Promise.resolve(i); + } } (async () => { - const gen = range(1, 3); - for await (const item of gen) { - console.log(item); - } + const gen = range(1, 3); + for await (const item of gen) { + console.log(item); + } })(); ``` @@ -4004,7 +4007,7 @@ Generator `range` trả về một async object với các promise tương ứng ```javascript const myFunc = ({ x, y, z }) => { - console.log(x, y, z); + console.log(x, y, z); }; myFunc(1, 2, 3); @@ -4127,8 +4130,8 @@ Với phương thức `isNaN`, ta đơn thuần chỉ check xem giá trị đưa const randomValue = 21; function getInfo() { - console.log(typeof randomValue); - const randomValue = "Lydia Hallie"; + console.log(typeof randomValue); + const randomValue = "Lydia Hallie"; } getInfo(); @@ -4157,13 +4160,13 @@ Một biến được khai báo với từ khóa `const` sẽ không thể truy const myPromise = Promise.resolve("Woah some cool data"); (async () => { - try { - console.log(await myPromise); - } catch { - throw new Error(`Oops didn't work`); - } finally { - console.log("Oh finally!"); - } + try { + console.log(await myPromise); + } catch { + throw new Error(`Oops didn't work`); + } finally { + console.log("Oh finally!"); + } })(); ``` @@ -4213,13 +4216,13 @@ Với phương thức `flat`, ta có thể tạo một mảng mới với các p ```javascript class Counter { - constructor() { - this.count = 0; - } + constructor() { + this.count = 0; + } - increment() { - this.count++; - } + increment() { + this.count++; + } } const counterOne = new Counter(); @@ -4263,16 +4266,16 @@ Ta gọi hàm `counterTwo.increment()` để tăng `count` lên `3`. Sau đó ch const myPromise = Promise.resolve(Promise.resolve("Promise!")); function funcOne() { - myPromise.then(res => res).then(res => console.log(res)); - setTimeout(() => console.log("Timeout!", 0)); - console.log("Last line!"); + myPromise.then((res) => res).then((res) => console.log(res)); + setTimeout(() => console.log("Timeout!", 0)); + console.log("Last line!"); } async function funcTwo() { - const res = await myPromise; - console.log(await res); - setTimeout(() => console.log("Timeout!", 0)); - console.log("Last line!"); + const res = await myPromise; + console.log(await res); + setTimeout(() => console.log("Timeout!", 0)); + console.log("Last line!"); } funcOne(); @@ -4309,7 +4312,7 @@ Ta tiếp tục thực thi dòng cuối cùng của `funcTwo`, trả về `Last ```javascript // sum.js export default function sum(x) { - return x + x; + return x + x; } // index.js @@ -4366,8 +4369,8 @@ Ta có thể gọi hàm này bằng cách sử dụng `sum.default` ```javascript const handler = { - set: () => console.log("Added a new property!"), - get: () => console.log("Accessed a property!") + set: () => console.log("Added a new property!"), + get: () => console.log("Accessed a property!"), }; const person = new Proxy({}, handler); @@ -4430,10 +4433,10 @@ Tuy nhiên ta vẫn có thể _thay đổi_ các thuộc tính cũ. ```javascript const person = { - name: "Lydia Hallie", - address: { - street: "100 Main St" - } + name: "Lydia Hallie", + address: { + street: "100 Main St", + }, }; Object.freeze(person); @@ -4461,10 +4464,10 @@ Tuy nhiên trên thực tế đây chỉ là đóng băng _nông_ (_shallowly_) ###### 138. Output là gì? ```javascript -const add = x => x + x; +const add = (x) => x + x; function myFunc(num = 2, value = add(num)) { - console.log(num, value); + console.log(num, value); } myFunc(); @@ -4494,21 +4497,21 @@ Sau đó ta gọi hàm `myFunc(3)`, khi này `3` sẽ là giá trị của `num` ```javascript class Counter { - #number = 10 + #number = 10; increment() { - this.#number++ + this.#number++; } getNum() { - return this.#number + return this.#number; } } -const counter = new Counter() -counter.increment() +const counter = new Counter(); +counter.increment(); -console.log(counter.#number) +console.log(counter.#number); ``` - A: `10` @@ -4532,20 +4535,20 @@ Với cú pháp ES2020, ta có thể thêm các thuộc tính private vào class ```javascript const teams = [ - { name: "Team 1", members: ["Paul", "Lisa"] }, - { name: "Team 2", members: ["Laura", "Tim"] } + { name: "Team 1", members: ["Paul", "Lisa"] }, + { name: "Team 2", members: ["Laura", "Tim"] }, ]; function* getMembers(members) { - for (let i = 0; i < members.length; i++) { - yield members[i]; - } + for (let i = 0; i < members.length; i++) { + yield members[i]; + } } function* getTeams(teams) { - for (let i = 0; i < teams.length; i++) { - // ✨ SOMETHING IS MISSING HERE ✨ - } + for (let i = 0; i < teams.length; i++) { + // ✨ SOMETHING IS MISSING HERE ✨ + } } const obj = getTeams(teams); @@ -4570,20 +4573,19 @@ Nếu ta dùng `yield`, `return yield`, hay `return`, toàn bộ generator sẽ

- --- ###### 141. Output là gì? ```javascript const person = { - name: "Lydia Hallie", - hobbies: ["coding"] + name: "Lydia Hallie", + hobbies: ["coding"], }; function addHobby(hobby, hobbies = person.hobbies) { - hobbies.push(hobby); - return hobbies; + hobbies.push(hobby); + return hobbies; } addHobby("running", []); @@ -4622,16 +4624,16 @@ Sau khi thêm `dancing` và `baking`, giá trị của `person.hobbies` là `["c ```javascript class Bird { - constructor() { - console.log("I'm a bird. 🦢"); - } + constructor() { + console.log("I'm a bird. 🦢"); + } } class Flamingo extends Bird { - constructor() { - console.log("I'm pink. 🌸"); - super(); - } + constructor() { + console.log("I'm pink. 🌸"); + super(); + } } const pet = new Flamingo(); @@ -4716,11 +4718,11 @@ Mặc định ta không thể duyệt qua được object. Trừ phi nó đượ let count = 0; const nums = [0, 1, 2, 3]; -nums.forEach(num => { - if (num) count += 1 -}) +nums.forEach((num) => { + if (num) count += 1; +}); -console.log(count) +console.log(count); ``` - A: 1 @@ -4744,12 +4746,12 @@ Câu lệnh `if` trong vòng lập `forEach` kiểm tra giá trị của `num` l ```javascript function getFruit(fruits) { - console.log(fruits?.[1]?.[1]) + console.log(fruits?.[1]?.[1]); } -getFruit([['🍊', '🍌'], ['🍍']]) -getFruit() -getFruit([['🍍'], ['🍊', '🍌']]) +getFruit([["🍊", "🍌"], ["🍍"]]); +getFruit(); +getFruit([["🍍"], ["🍊", "🍌"]]); ``` - A: `null`, `undefined`, 🍌 @@ -4766,7 +4768,7 @@ Phép toán `?` cho phép ta truy cập giá trị bên trong của object. Chú Trước tiên, chúng ta thử in ra phần tử thứ hai trong mảng con `['🍍']` của `[['🍊', '🍌'], ['🍍']]`. Mảng con này chỉ chứa một phần tử, nghĩa là không có phần tử nào với thứ tự là `1`, và trả về `undefined`. -Sau đó, ta gọi hàm `getFruits` khi không truyền vào một đối số nào, nghĩa là `fruits` có giá trị mặc định là `undefined`. Vì ta truyền phần tử mang thứ tự `1` của `fruits`, nó trả về `undefined` do phần tử này không tồn tại. +Sau đó, ta gọi hàm `getFruits` khi không truyền vào một đối số nào, nghĩa là `fruits` có giá trị mặc định là `undefined`. Vì ta truyền phần tử mang thứ tự `1` của `fruits`, nó trả về `undefined` do phần tử này không tồn tại. Cuối cùng, ta thử in ra phần tử thứ hai trong mảng con `['🍊', '🍌']` của mảng `['🍍'], ['🍊', '🍌']`. Phần tử mang thứ tự `1` bên trong mảng con này là `🍌` sẽ được in ra. @@ -4779,19 +4781,19 @@ Cuối cùng, ta thử in ra phần tử thứ hai trong mảng con `['🍊', ' ```javascript class Calc { - constructor() { - this.count = 0 - } + constructor() { + this.count = 0; + } - increase() { - this.count ++ - } + increase() { + this.count++; + } } -const calc = new Calc() -new Calc().increase() +const calc = new Calc(); +new Calc().increase(); -console.log(calc.count) +console.log(calc.count); ``` - A: `0` @@ -4815,25 +4817,25 @@ Ta set biến `calc` bằng một instance mới của `Calc` class. Sau đó ta ```javascript const user = { - email: "e@mail.com", - password: "12345" -} + email: "e@mail.com", + password: "12345", +}; const updateUser = ({ email, password }) => { - if (email) { - Object.assign(user, { email }) - } + if (email) { + Object.assign(user, { email }); + } - if (password) { - user.password = password - } + if (password) { + user.password = password; + } - return user -} + return user; +}; -const updatedUser = updateUser({ email: "new@email.com" }) +const updatedUser = updateUser({ email: "new@email.com" }); -console.log(updatedUser === user) +console.log(updatedUser === user); ``` - A: `false` @@ -4856,13 +4858,13 @@ Hàm `updateUser` thay đổi các giá trị của thuộc tính `email` và `p ###### 149. Output là gi? ```javascript -const fruit = ['🍌', '🍊', '🍎'] +const fruit = ["🍌", "🍊", "🍎"]; -fruit.slice(0, 1) -fruit.splice(0, 1) -fruit.unshift('🍇') +fruit.slice(0, 1); +fruit.splice(0, 1); +fruit.unshift("🍇"); -console.log(fruit) +console.log(fruit); ``` - A: `['🍌', '🍊', '🍎']` @@ -4886,13 +4888,13 @@ Trước tiên, ta gọi hàm `slice` trên mảng fruit. Hàm slice không thay ```javascript const animals = {}; -let dog = { emoji: '🐶' } -let cat = { emoji: '🐈' } +let dog = { emoji: "🐶" }; +let cat = { emoji: "🐈" }; -animals[dog] = { ...dog, name: "Mara" } -animals[cat] = { ...cat, name: "Sara" } +animals[dog] = { ...dog, name: "Mara" }; +animals[cat] = { ...cat, name: "Sara" }; -console.log(animals[dog]) +console.log(animals[dog]); ``` - A: `{ emoji: "🐶", name: "Mara" }` @@ -4909,7 +4911,7 @@ Các keys của object được chuyển thành các chuỗi. Do giá trị của `dog` là một object, `animals[dog]` thực sự nghĩa là ta tạo ra một thuộc tính mới gọi là `"object Object"` bằng với object mới. `animals["object Object"]` lúc này bằng với `{ emoji: "🐶", name: "Mara"}`. -`cat` cũng là một object, nên `animals[cat]` thực sự nghĩa là ta thay đổi giá trị của `animals[``"``object Object``"``]` bằng thuộc tính cat mới. +`cat` cũng là một object, nên `animals[cat]` thực sự nghĩa là ta thay đổi giá trị của ` animals[``"``object Object``"``] ` bằng thuộc tính cat mới. Khi in ra `animals[dog]`, hoặc thực chất là `animals["object Object"]` vì thay `dog` object bằng một chuỗi thì nó trả về `"object Object"`, ta nhận được `{ emoji: "🐈", name: "Sara" }`. @@ -4922,14 +4924,14 @@ Khi in ra `animals[dog]`, hoặc thực chất là `animals["object Object"]` v ```javascript const user = { - email: "my@email.com", - updateEmail: email => { - this.email = email - } -} + email: "my@email.com", + updateEmail: (email) => { + this.email = email; + }, +}; -user.updateEmail("new@email.com") -console.log(user.email) +user.updateEmail("new@email.com"); +console.log(user.email); ``` - A: `my@email.com` @@ -4952,20 +4954,20 @@ Hàm `updateEmail` là một cú pháp arrow function và nó không gắn với ###### 152. Output là gì? ```javascript -const promise1 = Promise.resolve('First') -const promise2 = Promise.resolve('Second') -const promise3 = Promise.reject('Third') -const promise4 = Promise.resolve('Fourth') +const promise1 = Promise.resolve("First"); +const promise2 = Promise.resolve("Second"); +const promise3 = Promise.reject("Third"); +const promise4 = Promise.resolve("Fourth"); const runPromises = async () => { - const res1 = await Promise.all([promise1, promise2]) - const res2 = await Promise.all([promise3, promise4]) - return [res1, res2] -} + const res1 = await Promise.all([promise1, promise2]); + const res2 = await Promise.all([promise3, promise4]); + return [res1, res2]; +}; runPromises() - .then(res => console.log(res)) - .catch(err => console.log(err)) + .then((res) => console.log(res)) + .catch((err) => console.log(err)); ``` - A: `[['First', 'Second'], ['Fourth']]` @@ -4985,16 +4987,19 @@ Hàm `Promise.all` trả về những promise truyền vào song song nhau. Nế --- -###### 153. Giá trị nào của `method` sẽ được trả về với log `{ name: "Lydia", age: 22 }`? +###### 153. Giá trị nào của `method` sẽ được trả về với log `{ name: "Lydia", age: 22 }`? ```javascript -const keys = ["name", "age"] -const values = ["Lydia", 22] +const keys = ["name", "age"]; +const values = ["Lydia", 22]; -const method = /* ?? */ -Object[method](keys.map((_, i) => { - return [keys[i], values[i]] -})) // { name: "Lydia", age: 22 } +const method = + /* ?? */ + Object[method]( + keys.map((_, i) => { + return [keys[i], values[i]]; + }) + ); // { name: "Lydia", age: 22 } ``` - A: `entries` @@ -5019,18 +5024,18 @@ Theo như trên thì ta tạo ra một mảng gồm những mảng con chứa đ ###### 154. Output là gì? ```javascript -const createMember = ({ email, address = {}}) => { - const validEmail = /.+\@.+\..+/.test(email) - if (!validEmail) throw new Error("Valid email pls") +const createMember = ({ email, address = {} }) => { + const validEmail = /.+\@.+\..+/.test(email); + if (!validEmail) throw new Error("Valid email pls"); - return { - email, - address: address ? address : null - } -} + return { + email, + address: address ? address : null, + }; +}; -const member = createMember({ email: "my@email.com" }) -console.log(member) +const member = createMember({ email: "my@email.com" }); +console.log(member); ``` - A: `{ email: "my@email.com", address: null }` @@ -5053,13 +5058,13 @@ Giá trị mặc định của `address` là một object rỗng `{}`. Khi ta ch ###### 155. Output là gì? ```javascript -let randomValue = { name: "Lydia" } -randomValue = 23 +let randomValue = { name: "Lydia" }; +randomValue = 23; if (!typeof randomValue === "string") { - console.log("It's not a string!") + console.log("It's not a string!"); } else { - console.log("Yay it's a string!") + console.log("Yay it's a string!"); } ``` From e2ee9c02709dd4940b4cf12a9e33ee149f8a42bc Mon Sep 17 00:00:00 2001 From: alexb017 Date: Mon, 21 Aug 2023 03:08:42 +0300 Subject: [PATCH 167/193] Added the questions from 1-10 --- ro-RO/README.ro.md | 322 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 322 insertions(+) diff --git a/ro-RO/README.ro.md b/ro-RO/README.ro.md index 3205d61c..5c36813e 100644 --- a/ro-RO/README.ro.md +++ b/ro-RO/README.ro.md @@ -47,3 +47,325 @@ Nu ezita să mă contactezi! 😊
--- + +###### 1. Care este rezultatul? + +```javascript +function sayHi() { + console.log(name); + console.log(age); + var name = "Lydia"; + let age = 21; +} + +sayHi(); +``` + +- A: `Lydia` și `undefined` +- B: `Lydia` și `ReferenceError` +- C: `ReferenceError` și `21` +- D: `undefined` și `ReferenceError` + +
Răspuns +

+ +#### Răspuns: D + +În interiorul funcției, mai întâi declarăm variabila `name` cu cuvântul cheie `var`. Acest lucru înseamnă că variabila este hoisted (spațiul de memorie este configurat în faza de creare) cu valoarea implicită `undefined`, până când ajungem efectiv la linia în care definim variabila. Nu am definit încă variabila pe linia în care încercăm să înregistrăm variabila `name`, așa că aceasta păstrează încă valoarea `undefined`. + +Variabilele create cu cuvântul cheie `let` (și `const`) sunt hoisted, dar, spre deosebire de `var`, nu sunt inițializate. Acestea nu sunt accesibile înainte de linia în care le declarăm (initializăm). Aceasta se numește zona moartă temporală (temporal dead zone). Atunci când încercăm să accesăm variabilele înainte de a fi declarate, JavaScript aruncă o excepție de tip `ReferenceError`. + +

+
+ +--- + +###### 2. Care este rezultatul? + +```javascript +for (var i = 0; i < 3; i++) { + setTimeout(() => console.log(i), 1); +} + +for (let i = 0; i < 3; i++) { + setTimeout(() => console.log(i), 1); +} +``` + +- A: `0 1 2` și `0 1 2` +- B: `0 1 2` și `3 3 3` +- C: `3 3 3` și `0 1 2` + +
Răspuns +

+ +#### Răspuns: C + +Datorită cozii de evenimente din JavaScript, funcția de callback `setTimeout` este apelată _după_ ce bucla a fost executată. Deoarece variabila `i` din prima buclă a fost declarată folosind cuvântul cheie `var`, această valoare a fost globală. În timpul buclei, am incrementat valoarea lui `i` cu `1` de fiecare dată, folosind operatorul unary `++`. Până când funcția de callback `setTimeout` a fost invocată, `i` era egal cu `3` în primul exemplu. + +În cea de-a doua buclă, variabila `i` a fost declarată folosind cuvântul cheie `let`: variabilele declarate cu cuvântul cheie `let` (și `const`) sunt cu scop la nivel de bloc (un bloc este orice între `{ }`). În fiecare iterație, `i` va avea o valoare nouă, iar fiecare valoare este în cadrul buclei. + +

+
+ +--- + +###### 3. Care este rezultatul? + +```javascript +const shape = { + radius: 10, + diameter() { + return this.radius * 2; + }, + perimeter: () => 2 * Math.PI * this.radius, +}; + +console.log(shape.diameter()); +console.log(shape.perimeter()); +``` + +- A: `20` și `62.83185307179586` +- B: `20` și `NaN` +- C: `20` și `63` +- D: `NaN` și `63` + +
Răspuns +

+ +#### Răspuns: B + +Rețineți că valoarea lui `diameter` este o funcție obișnuită, în timp ce valoarea lui `perimeter` este o funcție arrow. + +Cu funcțiile arrow, cuvântul cheie `this` se referă la contextul său curent de încadrare, spre deosebire de funcțiile obișnuite! Acest lucru înseamnă că atunci când apelăm `perimeter`, acesta nu se referă la obiectul formei, ci la încadrarea sa curentă (de exemplu, fereastra). + +Nu există nicio valoare `radius` pe acel obiect, ceea ce returnează `NaN`. + +

+
+ +--- + +###### 4. Care este rezultatul? + +```javascript ++true; +!"Lydia"; +``` + +- A: `1` și `false` +- B: `false` și `NaN` +- C: `false` și `false` + +
Răspuns +

+ +#### Răspuns: A + +Operatorul unary plus încearcă să convertească un operand într-un număr. `true` este `1`, și `false` este `0`. + +Șirul de caractere `'Lydia'` este o valoare adevărată. Ceea ce întrebăm de fapt, este "este această valoare adevărată falsă?". Acest lucru returnează `false`. + +

+
+ +--- + +###### 5. Care este rezultatul? + +```javascript +const bird = { + size: "small", +}; + +const mouse = { + name: "Mickey", + small: true, +}; +``` + +- A: `mouse.bird.size` nu este valid +- B: `mouse[bird.size]` nu este valid +- C: `mouse[bird["size"]]` nu este valid +- D: Toate sunt valide + +
Răspuns +

+ +#### Răspuns: A + +În JavaScript, toate cheile obiectelor sunt șiruri de caractere (cu excepția simbolurilor). Chiar dacă nu le _tipizăm_ ca șiruri de caractere, ele sunt întotdeauna convertite în șiruri de caractere în fundal. + +avaScript interpretează (sau dezambalează) instrucțiunile. Atunci când folosim notația cu paranteze pătrate, vede prima paranteză pătrată de deschidere `[` și continuă până când găsește paranteza pătrată de închidere `]`. Doar atunci va evalua instrucțiunea. + +`mouse[bird.size]`: Întâi evaluează `bird.size`, care este `"small"`. `mouse["small"]` returnează `true` + +Cu toate acestea, cu notația cu punct, acest lucru nu se întâmplă. `mouse` nu are o cheie numită `bird`, ceea ce înseamnă că `mouse.bird` este `undefined`. Apoi, cerem `size` folosind notația cu punct: `mouse.bird.size`. Deoarece `mouse.bird` este `undefined`, de fapt cerem `undefined.size`. Acest lucru nu este valid și va arunca o eroare similară cu `Cannot read property "size" of undefined` (Nu se poate citi proprietatea "size" a unei valori nedefinite). + +

+
+ +--- + +###### 6. Care este rezultatul? + +```javascript +let c = { greeting: "Hey!" }; +let d; + +d = c; +c.greeting = "Hello"; +console.log(d.greeting); +``` + +- A: `Hello` +- B: `Hey!` +- C: `undefined` +- D: `ReferenceError` +- E: `TypeError` + +
Răspuns +

+ +#### Răspuns: A + +În JavaScript, toate obiectele interacționează prin _referință_ atunci când sunt setate ca egale între ele. + +Mai întâi, variabila `c` deține o valoare care face referire la un obiect. Ulterior, atribuim variabilei `d` aceeași referință pe care o are `c` la obiect. + + + +Când modifici un obiect, le modifici pe toate. + +

+
+ +--- + +###### 7. Care este rezultatul? + +```javascript +let a = 3; +let b = new Number(3); +let c = 3; + +console.log(a == b); +console.log(a === b); +console.log(b === c); +``` + +- A: `true` `false` `true` +- B: `false` `false` `true` +- C: `true` `false` `false` +- D: `false` `true` `true` + +
Răspuns +

+ +#### Răspuns: C + +`new Number()` este un constructor de funcții încorporat. Deși arată ca un număr, nu este într-adevăr un număr: are o mulțime de funcționalități suplimentare și este un obiect. + +Atunci când folosim operatorul `==` (operatorul de egalitate), acesta verifică doar dacă au aceeași _valuare_. Ambele au valoarea `3`, șa că returnează `true`. + +Cu toate acestea, atunci când folosim operatorul `===` (operatorul de egalitate strictă), atât valoarea, cât _și_ tipul trebuie să fie la fel. Nu sunt: `new Number()` nu este un număr, este un **object**. Ambele returnează `false.` + +

+
+ +--- + +###### 8. Care este rezultatul? + +```javascript +class Chameleon { + static colorChange(newColor) { + this.newColor = newColor; + return this.newColor; + } + + constructor({ newColor = "green" } = {}) { + this.newColor = newColor; + } +} + +const freddie = new Chameleon({ newColor: "purple" }); +console.log(freddie.colorChange("orange")); +``` + +- A: `orange` +- B: `purple` +- C: `green` +- D: `TypeError` + +
Răspuns +

+ +#### Răspuns: D + +Funcția `colorChange` este statică. Metodele statice sunt concepute să existe doar pe constructorul în care sunt create și nu pot fi transmise către niciun copil sau apelate pe instanțele clasei. Deoarece `freddie` este o instanță a clasei Chameleon, funcția nu poate fi apelată pe aceasta. Se aruncă o eroare de tip `TypeError`. + +

+
+ +--- + +###### 9. Care este rezultatul? + +```javascript +let greeting; +greetign = {}; // Typo! +console.log(greetign); +``` + +- A: `{}` +- B: `ReferenceError: greetign is not defined` +- C: `undefined` + +
Răspuns +

+ +#### Răspuns: A + +Se afișează obiectul, deoarece tocmai am creat un obiect gol pe obiectul global! Atunci când am greșit și am scris `greeting` în loc de `greetign`, interpretorul JavaScript a văzut efectiv acest lucru ca: + +1. `global.greetign = {}` în Node.js +2. `window.greetign = {}`, `frames.greetign = {}` și `self.greetign` în browser-e. +3. `self.greetign` în web workers. +4. `globalThis.greetign` în toate mediile. + +Pentru a evita acest lucru, putem folosi `"use strict"`. Acest lucru se asigură că ai declarat o variabilă înainte de a-i atribui o valoare. + +

+
+ +--- + +###### 10. Ce se întâmplă când facem asta? + +```javascript +function bark() { + console.log("Woof!"); +} + +bark.animal = "dog"; +``` + +- A: Nimic, este absolut în regulă! +- B: `SyntaxError`. Nu poți adăuga proprietăți la o funcție în acest fel. +- C: `"Woof"` este înregistrat. +- D: `ReferenceError` + +
Răspuns +

+ +#### Răspuns: A + +Acest lucru este posibil în JavaScript, deoarece funcțiile sunt obiecte! (Totul, în afară de tipurile primitive, sunt obiecte) + +O funcție este un tip special de obiect. Codul pe care îl scrii tu însuți nu este funcția efectivă. Funcția este un obiect cu proprietăți. Această proprietate este invocabilă. + +

+
+ +--- From 242ce5c7667fafffaf507c9ed12fabdcc2a8a38c Mon Sep 17 00:00:00 2001 From: alexb017 Date: Tue, 22 Aug 2023 02:25:16 +0300 Subject: [PATCH 168/193] fix repo the way it was This reverts commit d8f096396becd18256123479e42c7a0290b52771. --- README.md | 624 ++++++++++++++-------------- ar-AR/README_AR.md | 362 +++++++---------- bs-BS/README-bs_BS.md | 249 ++++++------ de-DE/README.md | 925 +++++++++++++++++++++--------------------- es-ES/README-ES.md | 495 +++++++++++----------- fr-FR/README_fr-FR.md | 44 +- id-ID/README.md | 546 +++++++++++++------------ it-IT/README.md | 654 +++++++++++++++-------------- ja-JA/README-ja_JA.md | 375 ++++++++--------- ko-KR/README-ko_KR.md | 514 ++++++++++++----------- nl-NL/README.md | 619 ++++++++++++++-------------- pl-PL/README.md | 126 +++--- pt-BR/README_pt_BR.md | 116 +++--- ro-RO/README.ro.md | 371 ----------------- ru-RU/README.md | 825 +++++++++++++++++++------------------ sq-KS/README_sq_KS.md | 653 +++++++++++++++-------------- th-TH/README.md | 385 +++++++++--------- tr-TR/README-tr_TR.md | 316 +++++++-------- uk-UA/README.md | 35 +- vi-VI/README-vi.md | 829 +++++++++++++++++++------------------ 20 files changed, 4300 insertions(+), 4763 deletions(-) delete mode 100644 ro-RO/README.ro.md diff --git a/README.md b/README.md index 031b0f72..97cde89e 100644 --- a/README.md +++ b/README.md @@ -10,11 +10,10 @@ From basic to advanced: test how well you know JavaScript, refresh your knowledg Feel free to reach out to me! 😊
Instagram || Twitter || LinkedIn || Blog - -| Feel free to use them in a project! 😃 I would _really_ appreciate a reference to this repo, I create the questions and explanations (yes I'm sad lol) and the community helps me so much to maintain and improve it! 💪🏼 Thank you and have fun! | -| ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| Feel free to use them in a project! 😃 I would _really_ appreciate a reference to this repo, I create the questions and explanations (yes I'm sad lol) and the community helps me so much to maintain and improve it! 💪🏼 Thank you and have fun! | +|---| --- @@ -34,7 +33,6 @@ Feel free to reach out to me! 😊
- [🇳🇱 Nederlands](./nl-NL/README.md) - [🇵🇱 Polski](./pl-PL/README.md) - [🇧🇷 Português Brasil](./pt-BR/README_pt_BR.md) -- [🇷o Română](./ro-RO/README.ro.md) - [🇷🇺 Русский](./ru-RU/README.md) - [🇽🇰 Shqip](./sq-KS/README_sq_KS.md) - [🇹🇭 ไทย](./th-TH/README-th_TH.md) @@ -55,7 +53,7 @@ Feel free to reach out to me! 😊
function sayHi() { console.log(name); console.log(age); - var name = "Lydia"; + var name = 'Lydia'; let age = 21; } @@ -151,7 +149,7 @@ There is no value `radius` on that object, which returns `NaN`. ```javascript +true; -!"Lydia"; +!'Lydia'; ``` - A: `1` and `false` @@ -176,11 +174,11 @@ The string `'Lydia'` is a truthy value. What we're actually asking, is "is this ```javascript const bird = { - size: "small", + size: 'small', }; const mouse = { - name: "Mickey", + name: 'Mickey', small: true, }; ``` @@ -211,11 +209,11 @@ However, with dot notation, this doesn't happen. `mouse` does not have a key cal ###### 6. What's the output? ```javascript -let c = { greeting: "Hey!" }; +let c = { greeting: 'Hey!' }; let d; d = c; -c.greeting = "Hello"; +c.greeting = 'Hello'; console.log(d.greeting); ``` @@ -285,13 +283,13 @@ class Chameleon { return this.newColor; } - constructor({ newColor = "green" } = {}) { + constructor({ newColor = 'green' } = {}) { this.newColor = newColor; } } -const freddie = new Chameleon({ newColor: "purple" }); -console.log(freddie.colorChange("orange")); +const freddie = new Chameleon({ newColor: 'purple' }); +console.log(freddie.colorChange('orange')); ``` - A: `orange` @@ -346,10 +344,10 @@ In order to avoid this, we can use `"use strict"`. This makes sure that you have ```javascript function bark() { - console.log("Woof!"); + console.log('Woof!'); } -bark.animal = "dog"; +bark.animal = 'dog'; ``` - A: Nothing, this is totally fine! @@ -379,8 +377,8 @@ function Person(firstName, lastName) { this.lastName = lastName; } -const member = new Person("Lydia", "Hallie"); -Person.getFullName = function () { +const member = new Person('Lydia', 'Hallie'); +Person.getFullName = function() { return `${this.firstName} ${this.lastName}`; }; @@ -397,12 +395,12 @@ console.log(member.getFullName()); #### Answer: A -In JavaScript, functions are objects, and therefore, the method `getFullName` gets added to the constructor function object itself. For that reason, we can call `Person.getFullName()`, but `member.getFullName` throws a `TypeError`. +In JavaScript, functions are objects, and therefore, the method `getFullName` gets added to the constructor function object itself. For that reason, we can call `Person.getFullName()`, but `member.getFullName` throws a `TypeError`. If you want a method to be available to all object instances, you have to add it to the prototype property: ```js -Person.prototype.getFullName = function () { +Person.prototype.getFullName = function() { return `${this.firstName} ${this.lastName}`; }; ``` @@ -420,8 +418,8 @@ function Person(firstName, lastName) { this.lastName = lastName; } -const lydia = new Person("Lydia", "Hallie"); -const sarah = Person("Sarah", "Smith"); +const lydia = new Person('Lydia', 'Hallie'); +const sarah = Person('Sarah', 'Smith'); console.log(lydia); console.log(sarah); @@ -491,7 +489,7 @@ function sum(a, b) { return a + b; } -sum(1, "2"); +sum(1, '2'); ``` - A: `NaN` @@ -558,7 +556,7 @@ function getPersonInfo(one, two, three) { console.log(three); } -const person = "Lydia"; +const person = 'Lydia'; const age = 21; getPersonInfo`${person} is ${age} years old`; @@ -585,9 +583,9 @@ If you use tagged template literals, the value of the first argument is always a ```javascript function checkAge(data) { if (data === { age: 18 }) { - console.log("You are an adult!"); + console.log('You are an adult!'); } else if (data == { age: 18 }) { - console.log("You are still an adult."); + console.log('You are still an adult.'); } else { console.log(`Hmm.. You don't have an age I guess`); } @@ -647,7 +645,7 @@ The rest parameter (`...args`) lets us "collect" all remaining arguments into an ```javascript function getAge() { - "use strict"; + 'use strict'; age = 21; console.log(age); } @@ -675,7 +673,7 @@ With `"use strict"`, you can make sure that you don't accidentally declare globa ###### 21. What's the value of `sum`? ```javascript -const sum = eval("10*10+5"); +const sum = eval('10*10+5'); ``` - A: `105` @@ -698,7 +696,7 @@ const sum = eval("10*10+5"); ###### 22. How long is cool_secret accessible? ```javascript -sessionStorage.setItem("cool_secret", 123); +sessionStorage.setItem('cool_secret', 123); ``` - A: Forever, the data doesn't get lost. @@ -751,12 +749,12 @@ You cannot do this with `let` or `const` since they're block-scoped. ###### 24. What's the output? ```javascript -const obj = { 1: "a", 2: "b", 3: "c" }; +const obj = { 1: 'a', 2: 'b', 3: 'c' }; const set = new Set([1, 2, 3, 4, 5]); -obj.hasOwnProperty("1"); +obj.hasOwnProperty('1'); obj.hasOwnProperty(1); -set.has("1"); +set.has('1'); set.has(1); ``` @@ -782,7 +780,7 @@ It doesn't work that way for a set. There is no `'1'` in our set: `set.has('1')` ###### 25. What's the output? ```javascript -const obj = { a: "one", b: "two", a: "three" }; +const obj = { a: 'one', b: 'two', a: 'three' }; console.log(obj); ``` @@ -851,12 +849,12 @@ The `continue` statement skips an iteration if a certain condition returns `true ```javascript String.prototype.giveLydiaPizza = () => { - return "Just give Lydia pizza already!"; + return 'Just give Lydia pizza already!'; }; -const name = "Lydia"; +const name = 'Lydia'; -console.log(name.giveLydiaPizza()); +console.log(name.giveLydiaPizza()) ``` - A: `"Just give Lydia pizza already!"` @@ -880,8 +878,8 @@ console.log(name.giveLydiaPizza()); ```javascript const a = {}; -const b = { key: "b" }; -const c = { key: "c" }; +const b = { key: 'b' }; +const c = { key: 'c' }; a[b] = 123; a[c] = 456; @@ -913,9 +911,9 @@ Then, we log `a[b]`, which is actually `a["[object Object]"]`. We just set that ###### 30. What's the output? ```javascript -const foo = () => console.log("First"); -const bar = () => setTimeout(() => console.log("Second")); -const baz = () => console.log("Third"); +const foo = () => console.log('First'); +const bar = () => setTimeout(() => console.log('Second')); +const baz = () => console.log('Third'); bar(); foo(); @@ -968,7 +966,9 @@ This is where an event loop starts to work. An **event loop** looks at the stack ```html
- +
``` @@ -994,7 +994,9 @@ The deepest nested element that caused the event is the target of the event. You ```html
-

Click here!

+

+ Click here! +

``` @@ -1018,7 +1020,7 @@ If we click `p`, we see two logs: `p` and `div`. During event propagation, there ###### 33. What's the output? ```javascript -const person = { name: "Lydia" }; +const person = { name: 'Lydia' }; function sayHi(age) { return `${this.name} is ${age}`; @@ -1068,6 +1070,7 @@ console.log(typeof sayHi()); #### Answer: B The `sayHi` function returns the returned value of the immediately invoked function expression (IIFE). This function returned `0`, which is type `"number"`. + FYI: `typeof` can return the following list of values: `undefined`, `boolean`, `number`, `bigint`, `string`, `symbol`, `function` and `object`. Note that `typeof null` returns `"object"`.

@@ -1080,8 +1083,8 @@ FYI: `typeof` can return the following list of values: `undefined`, `boolean`, ` ```javascript 0; new Number(0); -(""); -(" "); +(''); +(' '); new Boolean(false); undefined; ``` @@ -1230,14 +1233,11 @@ What differentiates a primitive from an object is that primitives do not have an ###### 40. What's the output? ```javascript -[ - [0, 1], - [2, 3], -].reduce( +[[0, 1], [2, 3]].reduce( (acc, cur) => { return acc.concat(cur); }, - [1, 2] + [1, 2], ); ``` @@ -1264,7 +1264,7 @@ Then, `[1, 2, 0, 1]` is `acc` and `[2, 3]` is `cur`. We concatenate them, and ge ```javascript !!null; -!!""; +!!''; !!1; ``` @@ -1292,7 +1292,7 @@ Then, `[1, 2, 0, 1]` is `acc` and `[2, 3]` is `cur`. We concatenate them, and ge ###### 42. What does the `setInterval` method return in the browser? ```javascript -setInterval(() => console.log("Hi"), 1000); +setInterval(() => console.log('Hi'), 1000); ``` - A: a unique id @@ -1315,7 +1315,7 @@ It returns a unique id. This id can be used to clear that interval with the `cle ###### 43. What does this return? ```javascript -[..."Lydia"]; +[...'Lydia']; ``` - A: `["L", "y", "d", "i", "a"]` @@ -1374,14 +1374,14 @@ Then, we invoke the function again with the `next()` method. It starts to contin ```javascript const firstPromise = new Promise((res, rej) => { - setTimeout(res, 500, "one"); + setTimeout(res, 500, 'one'); }); const secondPromise = new Promise((res, rej) => { - setTimeout(res, 100, "two"); + setTimeout(res, 100, 'two'); }); -Promise.race([firstPromise, secondPromise]).then((res) => console.log(res)); +Promise.race([firstPromise, secondPromise]).then(res => console.log(res)); ``` - A: `"one"` @@ -1404,7 +1404,7 @@ When we pass multiple promises to the `Promise.race` method, it resolves/rejects ###### 46. What's the output? ```javascript -let person = { name: "Lydia" }; +let person = { name: 'Lydia' }; const members = [person]; person = null; @@ -1444,7 +1444,7 @@ We are only modifying the value of the `person` variable, and not the first elem ```javascript const person = { - name: "Lydia", + name: 'Lydia', age: 21, }; @@ -1473,7 +1473,7 @@ With a `for-in` loop, we can iterate through object keys, in this case `name` an ###### 48. What's the output? ```javascript -console.log(3 + 4 + "5"); +console.log(3 + 4 + '5'); ``` - A: `"345"` @@ -1500,7 +1500,7 @@ Operator associativity is the order in which the compiler evaluates the expressi ###### 49. What's the value of `num`? ```javascript -const num = parseInt("7*6", 10); +const num = parseInt('7*6', 10); ``` - A: `42` @@ -1525,8 +1525,8 @@ Only the first numbers in the string is returned. Based on the _radix_ (the seco ###### 50. What's the output? ```javascript -[1, 2, 3].map((num) => { - if (typeof num === "number") return; +[1, 2, 3].map(num => { + if (typeof num === 'number') return; return num * 2; }); ``` @@ -1554,12 +1554,12 @@ However, we don’t return a value. When we don’t return a value from the func ```javascript function getInfo(member, year) { - member.name = "Lydia"; - year = "1998"; + member.name = 'Lydia'; + year = '1998'; } -const person = { name: "Sarah" }; -const birthYear = "1997"; +const person = { name: 'Sarah' }; +const birthYear = '1997'; getInfo(person, birthYear); @@ -1591,15 +1591,15 @@ The value of `person` is an object. The argument `member` has a (copied) referen ```javascript function greeting() { - throw "Hello world!"; + throw 'Hello world!'; } function sayHi() { try { const data = greeting(); - console.log("It worked!", data); + console.log('It worked!', data); } catch (e) { - console.log("Oh no an error:", e); + console.log('Oh no an error:', e); } } @@ -1629,8 +1629,8 @@ With the `catch` statement, we can specify what to do if an exception is thrown ```javascript function Car() { - this.make = "Lamborghini"; - return { make: "Maserati" }; + this.make = 'Lamborghini'; + return { make: 'Maserati' }; } const myCar = new Car(); @@ -1704,11 +1704,11 @@ class Dog { } } -Dog.prototype.bark = function () { +Dog.prototype.bark = function() { console.log(`Woof I am ${this.name}`); }; -const pet = new Dog("Mara"); +const pet = new Dog('Mara'); pet.bark(); @@ -1773,7 +1773,7 @@ export default counter; ```javascript // index.js -import myCounter from "./counter"; +import myCounter from './counter'; myCounter += 1; @@ -1802,7 +1802,7 @@ When we try to increment the value of `myCounter`, it throws an error: `myCounte ###### 58. What's the output? ```javascript -const name = "Lydia"; +const name = 'Lydia'; age = 21; console.log(delete name); @@ -1873,7 +1873,7 @@ This means that the value of `y` is equal to the first value in the array, which ###### 60. What's the output? ```javascript -const user = { name: "Lydia", age: 21 }; +const user = { name: 'Lydia', age: 21 }; const admin = { admin: true, ...user }; console.log(admin); @@ -1899,9 +1899,9 @@ It's possible to combine objects using the spread operator `...`. It lets you cr ###### 61. What's the output? ```javascript -const person = { name: "Lydia" }; +const person = { name: 'Lydia' }; -Object.defineProperty(person, "age", { value: 21 }); +Object.defineProperty(person, 'age', { value: 21 }); console.log(person); console.log(Object.keys(person)); @@ -1930,12 +1930,12 @@ Properties added using the `defineProperty` method are immutable by default. You ```javascript const settings = { - username: "lydiahallie", + username: 'lydiahallie', level: 19, health: 90, }; -const data = JSON.stringify(settings, ["level", "health"]); +const data = JSON.stringify(settings, ['level', 'health']); console.log(data); ``` @@ -1966,7 +1966,7 @@ If the replacer is a _function_, this function gets called on every property in let num = 10; const increaseNumber = () => num++; -const increasePassedNumber = (number) => number++; +const increasePassedNumber = number => number++; const num1 = increaseNumber(); const num2 = increasePassedNumber(num1); @@ -2123,12 +2123,12 @@ The `Labrador` class receives two arguments, `name` since it extends `Dog`, and ```javascript // index.js -console.log("running index.js"); -import { sum } from "./sum.js"; +console.log('running index.js'); +import { sum } from './sum.js'; console.log(sum(1, 2)); // sum.js -console.log("running sum.js"); +console.log('running sum.js'); export const sum = (a, b) => a + b; ``` @@ -2156,7 +2156,7 @@ This is a difference between `require()` in CommonJS and `import`! With `require ```javascript console.log(Number(2) === Number(2)); console.log(Boolean(false) === Boolean(false)); -console.log(Symbol("foo") === Symbol("foo")); +console.log(Symbol('foo') === Symbol('foo')); ``` - A: `true`, `true`, `false` @@ -2179,7 +2179,7 @@ Every Symbol is entirely unique. The purpose of the argument passed to the Symbo ###### 69. What's the output? ```javascript -const name = "Lydia Hallie"; +const name = 'Lydia Hallie'; console.log(name.padStart(13)); console.log(name.padStart(2)); ``` @@ -2206,7 +2206,7 @@ If the argument passed to the `padStart` method is smaller than the length of th ###### 70. What's the output? ```javascript -console.log("🥑" + "💻"); +console.log('🥑' + '💻'); ``` - A: `"🥑💻"` @@ -2230,11 +2230,11 @@ With the `+` operator, you can concatenate strings. In this case, we are concate ```javascript function* startGame() { - const answer = yield "Do you love JavaScript?"; - if (answer !== "Yes") { + const answer = yield 'Do you love JavaScript?'; + if (answer !== 'Yes') { return "Oh wow... Guess we're done here"; } - return "JavaScript loves you back ❤️"; + return 'JavaScript loves you back ❤️'; } const game = startGame(); @@ -2302,7 +2302,7 @@ In this case, the string is `Hello\nworld`, which gets logged. ```javascript async function getData() { - return await Promise.resolve("I made it!"); + return await Promise.resolve('I made it!'); } const data = getData(); @@ -2339,7 +2339,7 @@ function addToList(item, list) { return list.push(item); } -const result = addToList("apple", ["banana"]); +const result = addToList('apple', ['banana']); console.log(result); ``` @@ -2399,7 +2399,7 @@ Since `shape` is frozen, and since the value of `x` is not an object, we cannot ###### 76. What's the output? ```javascript -const { firstName: myName } = { firstName: "Lydia" }; +const { firstName: myName } = { firstName: 'Lydia' }; console.log(firstName); ``` @@ -2417,7 +2417,7 @@ console.log(firstName); By using [destructuring assignment](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment) syntax we can unpack values from arrays, or properties from objects, into distinct variables: ```javascript -const { firstName } = { firstName: "Lydia" }; +const { firstName } = { firstName: 'Lydia' }; // ES5 version: // var firstName = { firstName: 'Lydia' }.firstName; @@ -2427,7 +2427,7 @@ console.log(firstName); // "Lydia" Also, a property can be unpacked from an object and assigned to a variable with a different name than the object property: ```javascript -const { firstName: myName } = { firstName: "Lydia" }; +const { firstName: myName } = { firstName: 'Lydia' }; // ES5 version: // var myName = { firstName: 'Lydia' }.firstName; @@ -2440,11 +2440,12 @@ Therefore, `firstName` does not exist as a variable, thus attempting to access i **Note:** Be aware of the `global scope` properties: ```javascript -const { name: myName } = { name: "Lydia" }; +const { name: myName } = { name: 'Lydia' }; console.log(myName); // "lydia" console.log(name); // "" ----- Browser e.g. Chrome console.log(name); // ReferenceError: name is not defined ----- NodeJS + ``` Whenever Javascript is unable to find a variable within the _current scope_, it climbs up the [Scope chain](https://github.com/getify/You-Dont-Know-JS/blob/2nd-ed/scope-closures/ch3.md) and searches for it and if it reaches the top-level scope, aka **Global scope**, and still doesn't find it, it will throw a `ReferenceError`. @@ -2488,7 +2489,7 @@ The `sum` function always returns the same result. If we pass `1` and `2`, it wi ```javascript const add = () => { const cache = {}; - return (num) => { + return num => { if (num in cache) { return `From cache! ${cache[num]}`; } else { @@ -2533,7 +2534,7 @@ The third time, we pass `5 * 2` to the function which gets evaluated to `10`. Th ###### 79. What is the output? ```javascript -const myLifeSummedUp = ["☕", "💻", "🍷", "🍫"]; +const myLifeSummedUp = ['☕', '💻', '🍷', '🍫']; for (let item in myLifeSummedUp) { console.log(item); @@ -2629,13 +2630,13 @@ In this case, if we didn't pass a value or if we passed `undefined`, `name` woul ###### 82. What is the output? ```javascript -var status = "😎"; +var status = '😎'; setTimeout(() => { - const status = "😍"; + const status = '😍'; const data = { - status: "🥑", + status: '🥑', getStatus() { return this.status; }, @@ -2669,12 +2670,12 @@ With the `call` method, we can change the object to which the `this` keyword ref ```javascript const person = { - name: "Lydia", + name: 'Lydia', age: 21, }; let city = person.city; -city = "Amsterdam"; +city = 'Amsterdam'; console.log(person); ``` @@ -2738,9 +2739,9 @@ Variables with the `const` and `let` keyword are _block-scoped_. A block is anyt ###### 85. What kind of information would get logged? ```javascript -fetch("https://www.website.com/api/user/1") - .then((res) => res.json()) - .then((res) => console.log(res)); +fetch('https://www.website.com/api/user/1') + .then(res => res.json()) + .then(res => console.log(res)); ``` - A: The result of the `fetch` method. @@ -2794,7 +2795,7 @@ By setting `hasName` equal to `name`, you set `hasName` equal to whatever value ###### 87. What's the output? ```javascript -console.log("I want pizza"[0]); +console.log('I want pizza'[0]); ``` - A: `"""` @@ -2849,11 +2850,11 @@ If you're trying to set a default parameter's value equal to a parameter which i ```javascript // module.js -export default () => "Hello world"; -export const name = "Lydia"; +export default () => 'Hello world'; +export const name = 'Lydia'; // index.js -import * as data from "./module"; +import * as data from './module'; console.log(data); ``` @@ -2886,7 +2887,7 @@ class Person { } } -const member = new Person("John"); +const member = new Person('John'); console.log(typeof member); ``` @@ -2946,7 +2947,7 @@ Then, we try to use the `.push` method on `newList`. Since `newList` is the nume ```javascript function giveLydiaPizza() { - return "Here is pizza!"; + return 'Here is pizza!'; } const giveLydiaChocolate = () => @@ -2977,7 +2978,7 @@ Regular functions, such as the `giveLydiaPizza` function, have a `prototype` pro ```javascript const person = { - name: "Lydia", + name: 'Lydia', age: 21, }; @@ -3037,7 +3038,7 @@ function getItems(fruitList, favoriteFruit, ...args) { return [...fruitList, ...args, favoriteFruit]; } -getItems(["banana", "apple"], "pear", "orange"); +getItems(['banana', 'apple'], 'pear', 'orange'); ``` The above example works. This returns the array `[ 'banana', 'apple', 'orange', 'pear' ]` @@ -3051,9 +3052,9 @@ The above example works. This returns the array `[ 'banana', 'apple', 'orange', ```javascript function nums(a, b) { - if (a > b) console.log("a is bigger"); - else console.log("b is bigger"); - return; + if (a > b) console.log('a is bigger'); + else console.log('b is bigger'); + return a + b; } @@ -3092,13 +3093,13 @@ This means that `a + b` is never reached, since a function stops running after t ```javascript class Person { constructor() { - this.name = "Lydia"; + this.name = 'Lydia'; } } Person = class AnotherPerson { constructor() { - this.name = "Sarah"; + this.name = 'Sarah'; } }; @@ -3127,7 +3128,7 @@ We can set classes equal to other classes/function constructors. In this case, w ```javascript const info = { - [Symbol("a")]: "b", + [Symbol('a')]: 'b', }; console.log(info); @@ -3182,7 +3183,7 @@ The `getList` function receives an array as its argument. Between the parenthese With the rest parameter `...y`, we put all "remaining" arguments in an array. The remaining arguments are `2`, `3` and `4` in this case. The value of `y` is an array, containing all the rest parameters. The value of `x` is equal to `1` in this case, so when we log `[x, y]`, `[1, [2, 3, 4]]` gets logged. -The `getUser` function receives an object. With arrow functions, we don't _have_ to write curly brackets if we just return one value. However, if you want to instantly return an _object_ from an arrow function, you have to write it between parentheses, otherwise everything between the two braces will be interpreted as a block statement. In this case the code between the braces is not a valid JavaScript code, so a `SyntaxError` gets thrown. +The `getUser` function receives an object. With arrow functions, we don't _have_ to write curly brackets if we just return one value. However, if you want to instantly return an _object_ from an arrow function, you have to write it between parentheses, otherwise everything between the two braces will be interpreted as a block statement. In this case the code between the braces is not a valid JavaScript code, so a `SyntaxError` gets thrown. The following function would have returned an object: @@ -3196,7 +3197,7 @@ The following function would have returned an object: ###### 99. What's the output? ```javascript -const name = "Lydia"; +const name = 'Lydia'; console.log(name()); ``` @@ -3228,8 +3229,8 @@ ReferenceErrors get thrown when JavaScript isn't able to find a reference to a v ```javascript // 🎉✨ This is my 100th question! ✨🎉 -const output = `${[] && "Im"}possible! -You should${"" && `n't`} see a therapist after so much JavaScript lol`; +const output = `${[] && 'Im'}possible! +You should${'' && `n't`} see a therapist after so much JavaScript lol`; ``` - A: `possible! You should see a therapist after so much JavaScript lol` @@ -3255,7 +3256,7 @@ You should${"" && `n't`} see a therapist after so much JavaScript lol`; ```javascript const one = false || {} || null; -const two = null || false || ""; +const two = null || false || ''; const three = [] || 0 || true; console.log(one, two, three); @@ -3287,16 +3288,16 @@ With the `||` operator, we can return the first truthy operand. If all values ar ###### 102. What's the value of output? ```javascript -const myPromise = () => Promise.resolve("I have resolved!"); +const myPromise = () => Promise.resolve('I have resolved!'); function firstFunction() { - myPromise().then((res) => console.log(res)); - console.log("second"); + myPromise().then(res => console.log(res)); + console.log('second'); } async function secondFunction() { console.log(await myPromise()); - console.log("second"); + console.log('second'); } firstFunction(); @@ -3334,8 +3335,8 @@ This means that it waited for the `myPromise` to resolve with the value `I have const set = new Set(); set.add(1); -set.add("Lydia"); -set.add({ name: "Lydia" }); +set.add('Lydia'); +set.add({ name: 'Lydia' }); for (let item of set) { console.log(item + 2); @@ -3395,13 +3396,13 @@ In this case, we just passed the numerical value `5`. It returns a resolved prom ```javascript function compareMembers(person1, person2 = person) { if (person1 !== person2) { - console.log("Not the same!"); + console.log('Not the same!'); } else { - console.log("They are the same!"); + console.log('They are the same!'); } } -const person = { name: "Lydia" }; +const person = { name: 'Lydia' }; compareMembers(person); ``` @@ -3440,7 +3441,7 @@ const colorConfig = { yellow: false, }; -const colors = ["pink", "red", "blue"]; +const colors = ['pink', 'red', 'blue']; console.log(colorConfig.colors[1]); ``` @@ -3469,7 +3470,7 @@ JavaScript interprets (or unboxes) statements. When we use bracket notation, it ###### 107. What's its value? ```javascript -console.log("❤️" === "❤️"); +console.log('❤️' === '❤️'); ``` - A: `true` @@ -3490,14 +3491,14 @@ Under the hood, emojis are unicodes. The unicodes for the heart emoji is `"U+276 ###### 108. Which of these methods modifies the original array? ```javascript -const emojis = ["✨", "🥑", "😍"]; +const emojis = ['✨', '🥑', '😍']; -emojis.map((x) => x + "✨"); -emojis.filter((x) => x !== "🥑"); -emojis.find((x) => x !== "🥑"); -emojis.reduce((acc, cur) => acc + "✨"); -emojis.slice(1, 2, "✨"); -emojis.splice(1, 2, "✨"); +emojis.map(x => x + '✨'); +emojis.filter(x => x !== '🥑'); +emojis.find(x => x !== '🥑'); +emojis.reduce((acc, cur) => acc + '✨'); +emojis.slice(1, 2, '✨'); +emojis.splice(1, 2, '✨'); ``` - A: `All of them` @@ -3522,10 +3523,10 @@ With `splice` method, we modify the original array by deleting, replacing or add ###### 109. What's the output? ```javascript -const food = ["🍕", "🍫", "🥑", "🍔"]; +const food = ['🍕', '🍫', '🥑', '🍔']; const info = { favoriteFood: food[0] }; -info.favoriteFood = "🍝"; +info.favoriteFood = '🍝'; console.log(food); ``` @@ -3579,7 +3580,7 @@ const jsonArray = JSON.stringify([1, 2, 3]); // '[1, 2, 3]' JSON.parse(jsonArray); // [1, 2, 3] // Stringifying an object into valid JSON, then parsing the JSON string to a JavaScript value: -const jsonArray = JSON.stringify({ name: "Lydia" }); // '{"name":"Lydia"}' +const jsonArray = JSON.stringify({ name: 'Lydia' }); // '{"name":"Lydia"}' JSON.parse(jsonArray); // { name: 'Lydia' } ``` @@ -3591,11 +3592,11 @@ JSON.parse(jsonArray); // { name: 'Lydia' } ###### 111. What's the output? ```javascript -let name = "Lydia"; +let name = 'Lydia'; function getName() { console.log(name); - let name = "Sarah"; + let name = 'Sarah'; } getName(); @@ -3618,7 +3619,7 @@ Variables with the `let` keyword (and `const`) are hoisted, but unlike `var`, do If we wouldn't have declared the `name` variable within the `getName` function, the javascript engine would've looked down the _scope chain_. The outer scope has a variable called `name` with the value of `Lydia`. In that case, it would've logged `Lydia`. ```javascript -let name = "Lydia"; +let name = 'Lydia'; function getName() { console.log(name); @@ -3636,11 +3637,11 @@ getName(); // Lydia ```javascript function* generatorOne() { - yield ["a", "b", "c"]; + yield ['a', 'b', 'c']; } function* generatorTwo() { - yield* ["a", "b", "c"]; + yield* ['a', 'b', 'c']; } const one = generatorOne(); @@ -3686,7 +3687,7 @@ console.log(two.next().value); // undefined ###### 113. What's the output? ```javascript -console.log(`${((x) => x)("I love")} to program`); +console.log(`${(x => x)('I love')} to program`); ``` - A: `I love to program` @@ -3711,7 +3712,7 @@ Expressions within template literals are evaluated first. This means that the st ```javascript let config = { alert: setInterval(() => { - console.log("Alert!"); + console.log('Alert!'); }, 1000), }; @@ -3728,9 +3729,9 @@ config = null; #### Answer: C -Normally when we set objects equal to `null`, those objects get _garbage collected_ as there is no reference anymore to that object. However, since the callback function within `setInterval` is an arrow function (thus bound to the `config` object), the callback function still holds a reference to the `config` object. -As long as there is a reference, the object won't get garbage collected. -Since this is an interval, setting `config` to `null` or `delete`-ing `config.alert` won't garbage-collect the interval, so the interval will still be called. +Normally when we set objects equal to `null`, those objects get _garbage collected_ as there is no reference anymore to that object. However, since the callback function within `setInterval` is an arrow function (thus bound to the `config` object), the callback function still holds a reference to the `config` object. +As long as there is a reference, the object won't get garbage collected. +Since this is an interval, setting `config` to `null` or `delete`-ing `config.alert` won't garbage-collect the interval, so the interval will still be called. It should be cleared with `clearInterval(config.alert)` to remove it from memory. Since it was not cleared, the `setInterval` callback function will still get invoked every 1000ms (1s). @@ -3743,16 +3744,16 @@ Since it was not cleared, the `setInterval` callback function will still get inv ```javascript const myMap = new Map(); -const myFunc = () => "greeting"; +const myFunc = () => 'greeting'; -myMap.set(myFunc, "Hello world!"); +myMap.set(myFunc, 'Hello world!'); //1 -myMap.get("greeting"); +myMap.get('greeting'); //2 myMap.get(myFunc); //3 -myMap.get(() => "greeting"); +myMap.get(() => 'greeting'); ``` - A: 1 @@ -3779,14 +3780,14 @@ When adding a key/value pair using the `set` method, the key will be the value o ```javascript const person = { - name: "Lydia", + name: 'Lydia', age: 21, }; const changeAge = (x = { ...person }) => (x.age += 1); const changeAgeAndName = (x = { ...person }) => { x.age += 1; - x.name = "Sarah"; + x.name = 'Sarah'; }; changeAge(person); @@ -3845,7 +3846,7 @@ With the spread operator `...`, we can _spread_ iterables to individual elements ```javascript let num = 1; -const list = ["🥳", "🤠", "🥰", "🤪"]; +const list = ['🥳', '🤠', '🥰', '🤪']; console.log(list[(num += 1)]); ``` @@ -3871,11 +3872,11 @@ With the `+=` operand, we're incrementing the value of `num` by `1`. `num` had t ```javascript const person = { - firstName: "Lydia", - lastName: "Hallie", + firstName: 'Lydia', + lastName: 'Hallie', pet: { - name: "Mara", - breed: "Dutch Tulip Hound", + name: 'Mara', + breed: 'Dutch Tulip Hound', }, getFullName() { return `${this.firstName} ${this.lastName}`; @@ -3913,10 +3914,10 @@ With the optional chaining operator `?.`, we no longer have to explicitly check ###### 120. What's the output? ```javascript -const groceries = ["banana", "apple", "peanuts"]; +const groceries = ['banana', 'apple', 'peanuts']; -if (groceries.indexOf("banana")) { - console.log("We have to buy bananas!"); +if (groceries.indexOf('banana')) { + console.log('We have to buy bananas!'); } else { console.log(`We don't have to buy bananas!`); } @@ -3972,10 +3973,10 @@ The `language` method is a `setter`. Setters don't hold an actual value, their p ###### 122. What's the output? ```javascript -const name = "Lydia Hallie"; +const name = 'Lydia Hallie'; -console.log(!typeof name === "object"); -console.log(!typeof name === "string"); +console.log(!typeof name === 'object'); +console.log(!typeof name === 'string'); ``` - A: `false` `true` @@ -4000,7 +4001,7 @@ console.log(!typeof name === "string"); ###### 123. What's the output? ```javascript -const add = (x) => (y) => (z) => { +const add = x => y => z => { console.log(x, y, z); return x + y + z; }; @@ -4090,20 +4091,20 @@ myFunc(1, 2, 3); ```javascript function getFine(speed, amount) { - const formattedSpeed = new Intl.NumberFormat("en-US", { - style: "unit", - unit: "mile-per-hour", + const formattedSpeed = new Intl.NumberFormat('en-US', { + style: 'unit', + unit: 'mile-per-hour' }).format(speed); - const formattedAmount = new Intl.NumberFormat("en-US", { - style: "currency", - currency: "USD", + const formattedAmount = new Intl.NumberFormat('en-US', { + style: 'currency', + currency: 'USD' }).format(amount); return `The driver drove ${formattedSpeed} and has to pay ${formattedAmount}`; } -console.log(getFine(130, 300)); +console.log(getFine(130, 300)) ``` - A: The driver drove 130 and has to pay 300 @@ -4126,8 +4127,8 @@ With the `Intl.NumberFormat` method, we can format numeric values to any locale. ###### 127. What's the output? ```javascript -const spookyItems = ["👻", "🎃", "🕸"]; -({ item: spookyItems[3] } = { item: "💀" }); +const spookyItems = ['👻', '🎃', '🕸']; +({ item: spookyItems[3] } = { item: '💀' }); console.log(spookyItems); ``` @@ -4152,7 +4153,7 @@ By destructuring objects, we can unpack values from the right-hand object, and a ###### 128. What's the output? ```javascript -const name = "Lydia Hallie"; +const name = 'Lydia Hallie'; const age = 21; console.log(Number.isNaN(name)); @@ -4188,7 +4189,7 @@ const randomValue = 21; function getInfo() { console.log(typeof randomValue); - const randomValue = "Lydia Hallie"; + const randomValue = 'Lydia Hallie'; } getInfo(); @@ -4214,7 +4215,7 @@ Variables declared with the `const` keyword are not referenceable before their i ###### 130. What's the output? ```javascript -const myPromise = Promise.resolve("Woah some cool data"); +const myPromise = Promise.resolve('Woah some cool data'); (async () => { try { @@ -4222,7 +4223,7 @@ const myPromise = Promise.resolve("Woah some cool data"); } catch { throw new Error(`Oops didn't work`); } finally { - console.log("Oh finally!"); + console.log('Oh finally!'); } })(); ``` @@ -4247,7 +4248,7 @@ In the `try` block, we're logging the awaited value of the `myPromise` variable: ###### 131. What's the output? ```javascript -const emojis = ["🥑", ["✨", "✨", ["🍕", "🍕"]]]; +const emojis = ['🥑', ['✨', '✨', ['🍕', '🍕']]]; console.log(emojis.flat(1)); ``` @@ -4320,19 +4321,19 @@ We invoke `counterTwo.increment()`, which sets `count` to `3`. Then, we log the ###### 133. What's the output? ```javascript -const myPromise = Promise.resolve(Promise.resolve("Promise")); +const myPromise = Promise.resolve(Promise.resolve('Promise')); function funcOne() { - setTimeout(() => console.log("Timeout 1!"), 0); - myPromise.then((res) => res).then((res) => console.log(`${res} 1!`)); - console.log("Last line 1!"); + setTimeout(() => console.log('Timeout 1!'), 0); + myPromise.then(res => res).then(res => console.log(`${res} 1!`)); + console.log('Last line 1!'); } async function funcTwo() { const res = await myPromise; - console.log(`${res} 2!`); - setTimeout(() => console.log("Timeout 2!"), 0); - console.log("Last line 2!"); + console.log(`${res} 2!`) + setTimeout(() => console.log('Timeout 2!'), 0); + console.log('Last line 2!'); } funcOne(); @@ -4353,7 +4354,7 @@ First, we invoke `funcOne`. On the first line of `funcOne`, we call the _asynchr Then we call the `myPromise` promise, which is an _asynchronous_ operation. -Both the promise and the timeout are asynchronous operations, the function keeps on running while it's busy completing the promise and handling the `setTimeout` callback. This means that `Last line 1!` gets logged first, since this is not an asynchonous operation. +Both the promise and the timeout are asynchronous operations, the function keeps on running while it's busy completing the promise and handling the `setTimeout` callback. This means that `Last line 1!` gets logged first, since this is not an asynchonous operation. Since the callstack is not empty yet, the `setTimeout` function and promise in `funcOne` cannot get added to the callstack yet. @@ -4377,7 +4378,7 @@ export default function sum(x) { } // index.js -import * as sum from "./sum"; +import * as sum from './sum'; ``` - A: `sum(4)` @@ -4394,12 +4395,12 @@ With the asterisk `*`, we import all exported values from that file, both defaul ```javascript // info.js -export const name = "Lydia"; +export const name = 'Lydia'; export const age = 21; -export default "I love JavaScript"; +export default 'I love JavaScript'; // index.js -import * as info from "./info"; +import * as info from './info'; console.log(info); ``` @@ -4430,13 +4431,13 @@ We can invoke this function, by calling `sum.default` ```javascript const handler = { - set: () => console.log("Added a new property!"), - get: () => console.log("Accessed a property!"), + set: () => console.log('Added a new property!'), + get: () => console.log('Accessed a property!'), }; const person = new Proxy({}, handler); -person.name = "Lydia"; +person.name = 'Lydia'; person.name; ``` @@ -4466,7 +4467,7 @@ Then, we access a property value on the proxy object, the `get` property on the ###### 136. Which of the following will modify the `person` object? ```javascript -const person = { name: "Lydia Hallie" }; +const person = { name: 'Lydia Hallie' }; Object.seal(person); ``` @@ -4494,9 +4495,9 @@ However, you can still modify the value of existing properties. ```javascript const person = { - name: "Lydia Hallie", + name: 'Lydia Hallie', address: { - street: "100 Main St", + street: '100 Main St', }, }; @@ -4525,7 +4526,7 @@ However, it only _shallowly_ freezes the object, meaning that only _direct_ prop ###### 138. What's the output? ```javascript -const add = (x) => x + x; +const add = x => x + x; function myFunc(num = 2, value = add(num)) { console.log(num, value); @@ -4558,21 +4559,21 @@ Then, we invoked `myFunc(3)` and passed the value `3` as the value for the argum ```javascript class Counter { - #number = 10; + #number = 10 increment() { - this.#number++; + this.#number++ } getNum() { - return this.#number; + return this.#number } } -const counter = new Counter(); -counter.increment(); +const counter = new Counter() +counter.increment() -console.log(counter.#number); +console.log(counter.#number) ``` - A: `10` @@ -4596,8 +4597,8 @@ In ES2020, we can add private variables in classes by using the `#`. We cannot a ```javascript const teams = [ - { name: "Team 1", members: ["Paul", "Lisa"] }, - { name: "Team 2", members: ["Laura", "Tim"] }, + { name: 'Team 1', members: ['Paul', 'Lisa'] }, + { name: 'Team 2', members: ['Laura', 'Tim'] }, ]; function* getMembers(members) { @@ -4640,8 +4641,8 @@ If we would've written `yield`, `return yield`, or `return`, the entire generato ```javascript const person = { - name: "Lydia Hallie", - hobbies: ["coding"], + name: 'Lydia Hallie', + hobbies: ['coding'], }; function addHobby(hobby, hobbies = person.hobbies) { @@ -4649,9 +4650,9 @@ function addHobby(hobby, hobbies = person.hobbies) { return hobbies; } -addHobby("running", []); -addHobby("dancing"); -addHobby("baking", person.hobbies); +addHobby('running', []); +addHobby('dancing'); +addHobby('baking', person.hobbies); console.log(person.hobbies); ``` @@ -4720,11 +4721,11 @@ We create the variable `pet` which is an instance of the `Flamingo` class. When ###### 143. Which of the options result(s) in an error? ```javascript -const emojis = ["🎄", "🎅🏼", "🎁", "⭐"]; +const emojis = ['🎄', '🎅🏼', '🎁', '⭐']; -/* 1 */ emojis.push("🦌"); +/* 1 */ emojis.push('🦌'); /* 2 */ emojis.splice(0, 2); -/* 3 */ emojis = [...emojis, "🥂"]; +/* 3 */ emojis = [...emojis, '🥂']; /* 4 */ emojis.length = 0; ``` @@ -4779,11 +4780,11 @@ Objects aren't iterable by default. An iterable is an iterable if the iterator p let count = 0; const nums = [0, 1, 2, 3]; -nums.forEach((num) => { - if (num) count += 1; -}); +nums.forEach(num => { + if (num) count += 1 +}) -console.log(count); +console.log(count) ``` - A: 1 @@ -4807,12 +4808,12 @@ The `if` condition within the `forEach` loop checks whether the value of `num` i ```javascript function getFruit(fruits) { - console.log(fruits?.[1]?.[1]); + console.log(fruits?.[1]?.[1]) } -getFruit([["🍊", "🍌"], ["🍍"]]); -getFruit(); -getFruit([["🍍"], ["🍊", "🍌"]]); +getFruit([['🍊', '🍌'], ['🍍']]) +getFruit() +getFruit([['🍍'], ['🍊', '🍌']]) ``` - A: `null`, `undefined`, 🍌 @@ -4825,11 +4826,11 @@ getFruit([["🍍"], ["🍊", "🍌"]]); #### Answer: D -The `?` allows us to optionally access deeper nested properties within objects. We're trying to log the item on index `1` within the subarray that's on index `1` of the `fruits` array. If the subarray on index `1` in the `fruits` array doesn't exist, it'll simply return `undefined`. If the subarray on index `1` in the `fruits` array exists, but this subarray doesn't have an item on its `1` index, it'll also return `undefined`. +The `?` allows us to optionally access deeper nested properties within objects. We're trying to log the item on index `1` within the subarray that's on index `1` of the `fruits` array. If the subarray on index `1` in the `fruits` array doesn't exist, it'll simply return `undefined`. If the subarray on index `1` in the `fruits` array exists, but this subarray doesn't have an item on its `1` index, it'll also return `undefined`. First, we're trying to log the second item in the `['🍍']` subarray of `[['🍊', '🍌'], ['🍍']]`. This subarray only contains one item, which means there is no item on index `1`, and returns `undefined`. -Then, we're invoking the `getFruits` function without passing a value as an argument, which means that `fruits` has a value of `undefined` by default. Since we're conditionally chaining the item on index `1` of`fruits`, it returns `undefined` since this item on index `1` does not exist. +Then, we're invoking the `getFruits` function without passing a value as an argument, which means that `fruits` has a value of `undefined` by default. Since we're conditionally chaining the item on index `1` of`fruits`, it returns `undefined` since this item on index `1` does not exist. Lastly, we're trying to log the second item in the `['🍊', '🍌']` subarray of `['🍍'], ['🍊', '🍌']`. The item on index `1` within this subarray is `🍌`, which gets logged. @@ -4842,19 +4843,19 @@ Lastly, we're trying to log the second item in the `['🍊', '🍌']` subarray o ```javascript class Calc { - constructor() { - this.count = 0; - } + constructor() { + this.count = 0 + } - increase() { - this.count++; - } + increase() { + this.count ++ + } } -const calc = new Calc(); -new Calc().increase(); +const calc = new Calc() +new Calc().increase() -console.log(calc.count); +console.log(calc.count) ``` - A: `0` @@ -4878,25 +4879,25 @@ We set the variable `calc` equal to a new instance of the `Calc` class. Then, we ```javascript const user = { - email: "e@mail.com", - password: "12345", -}; + email: "e@mail.com", + password: "12345" +} const updateUser = ({ email, password }) => { - if (email) { - Object.assign(user, { email }); - } + if (email) { + Object.assign(user, { email }) + } - if (password) { - user.password = password; - } + if (password) { + user.password = password + } - return user; -}; + return user +} -const updatedUser = updateUser({ email: "new@email.com" }); +const updatedUser = updateUser({ email: "new@email.com" }) -console.log(updatedUser === user); +console.log(updatedUser === user) ``` - A: `false` @@ -4919,13 +4920,13 @@ The `updateUser` function updates the values of the `email` and `password` prope ###### 149. What's the output? ```javascript -const fruit = ["🍌", "🍊", "🍎"]; +const fruit = ['🍌', '🍊', '🍎'] -fruit.slice(0, 1); -fruit.splice(0, 1); -fruit.unshift("🍇"); +fruit.slice(0, 1) +fruit.splice(0, 1) +fruit.unshift('🍇') -console.log(fruit); +console.log(fruit) ``` - A: `['🍌', '🍊', '🍎']` @@ -4940,7 +4941,7 @@ console.log(fruit); First, we invoke the `slice` method on the fruit array. The slice method does not modify the original array, but returns the value that it sliced off the array: the banana emoji. Then, we invoke the `splice` method on the fruit array. The splice method does modify the original array, which means that the fruit array now consists of `['🍊', '🍎']`. -At last, we invoke the `unshift` method on the `fruit` array, which modifies the original array by adding the provided value, ‘🍇’ in this case, as the first element in the array. The fruit array now consists of `['🍇', '🍊', '🍎']`. +At last, we invoke the `unshift` method on the `fruit` array, which modifies the original array by adding the provided value, ‘🍇’ in this case, as the first element in the array. The fruit array now consists of `['🍇', '🍊', '🍎']`.

@@ -4951,13 +4952,13 @@ At last, we invoke the `unshift` method on the `fruit` array, which modifies the ```javascript const animals = {}; -let dog = { emoji: "🐶" }; -let cat = { emoji: "🐈" }; +let dog = { emoji: '🐶' } +let cat = { emoji: '🐈' } -animals[dog] = { ...dog, name: "Mara" }; -animals[cat] = { ...cat, name: "Sara" }; +animals[dog] = { ...dog, name: "Mara" } +animals[cat] = { ...cat, name: "Sara" } -console.log(animals[dog]); +console.log(animals[dog]) ``` - A: `{ emoji: "🐶", name: "Mara" }` @@ -4970,11 +4971,11 @@ console.log(animals[dog]); #### Answer: B -Object keys are converted to strings. +Object keys are converted to strings. -Since the value of `dog` is an object, `animals[dog]` actually means that we’re creating a new property called `"object Object"` equal to the new object. `animals["object Object"]` is now equal to `{ emoji: "🐶", name: "Mara"}`. +Since the value of `dog` is an object, `animals[dog]` actually means that we’re creating a new property called `"object Object"` equal to the new object. `animals["object Object"]` is now equal to `{ emoji: "🐶", name: "Mara"}`. -`cat` is also an object, which means that `animals[cat]` actually means that we’re overwriting the value of `animals["object Object"]` with the new cat properties. +`cat` is also an object, which means that `animals[cat]` actually means that we’re overwriting the value of `animals["object Object"]` with the new cat properties. Logging `animals[dog]`, or actually `animals["object Object"]` since converting the `dog` object to a string results `"object Object"`, returns the `{ emoji: "🐈", name: "Sara" }`. @@ -4987,14 +4988,14 @@ Logging `animals[dog]`, or actually `animals["object Object"]` since converting ```javascript const user = { - email: "my@email.com", - updateEmail: (email) => { - this.email = email; - }, -}; + email: "my@email.com", + updateEmail: email => { + this.email = email + } +} -user.updateEmail("new@email.com"); -console.log(user.email); +user.updateEmail("new@email.com") +console.log(user.email) ``` - A: `my@email.com` @@ -5007,7 +5008,7 @@ console.log(user.email); #### Answer: A -The `updateEmail` function is an arrow function, and is not bound to the `user` object. This means that the `this` keyword is not referring to the `user` object, but refers to the global scope in this case. The value of `email` within the `user` object does not get updated. When logging the value of `user.email`, the original value of `my@email.com` gets returned. +The `updateEmail` function is an arrow function, and is not bound to the `user` object. This means that the `this` keyword is not referring to the `user` object, but refers to the global scope in this case. The value of `email` within the `user` object does not get updated. When logging the value of `user.email`, the original value of `my@email.com` gets returned.

@@ -5017,20 +5018,20 @@ The `updateEmail` function is an arrow function, and is not bound to the `user` ###### 152. What's the output? ```javascript -const promise1 = Promise.resolve("First"); -const promise2 = Promise.resolve("Second"); -const promise3 = Promise.reject("Third"); -const promise4 = Promise.resolve("Fourth"); +const promise1 = Promise.resolve('First') +const promise2 = Promise.resolve('Second') +const promise3 = Promise.reject('Third') +const promise4 = Promise.resolve('Fourth') const runPromises = async () => { - const res1 = await Promise.all([promise1, promise2]); - const res2 = await Promise.all([promise3, promise4]); - return [res1, res2]; -}; + const res1 = await Promise.all([promise1, promise2]) + const res2 = await Promise.all([promise3, promise4]) + return [res1, res2] +} runPromises() - .then((res) => console.log(res)) - .catch((err) => console.log(err)); + .then(res => console.log(res)) + .catch(err => console.log(err)) ``` - A: `[['First', 'Second'], ['Fourth']]` @@ -5043,26 +5044,23 @@ runPromises() #### Answer: D -The `Promise.all` method runs the passed promises in parallel. If one promise fails, the `Promise.all` method _rejects_ with the value of the rejected promise. In this case, `promise3` rejected with the value `"Third"`. We’re catching the rejected value in the chained `catch` method on the `runPromises` invocation to catch any errors within the `runPromises` function. Only `"Third"` gets logged, since `promise3` rejected with this value. +The `Promise.all` method runs the passed promises in parallel. If one promise fails, the `Promise.all` method _rejects_ with the value of the rejected promise. In this case, `promise3` rejected with the value `"Third"`. We’re catching the rejected value in the chained `catch` method on the `runPromises` invocation to catch any errors within the `runPromises` function. Only `"Third"` gets logged, since `promise3` rejected with this value.

--- -###### 153. What should the value of `method` be to log `{ name: "Lydia", age: 22 }`? +###### 153. What should the value of `method` be to log `{ name: "Lydia", age: 22 }`? ```javascript -const keys = ["name", "age"]; -const values = ["Lydia", 22]; +const keys = ["name", "age"] +const values = ["Lydia", 22] -const method = - /* ?? */ - Object[method]( - keys.map((_, i) => { - return [keys[i], values[i]]; - }) - ); // { name: "Lydia", age: 22 } +const method = /* ?? */ +Object[method](keys.map((_, i) => { + return [keys[i], values[i]] +})) // { name: "Lydia", age: 22 } ``` - A: `entries` @@ -5075,7 +5073,7 @@ const method = #### Answer: C -The `fromEntries` method turns a 2d array into an object. The first element in each subarray will be the key, and the second element in each subarray will be the value. In this case, we’re mapping over the `keys` array, which returns an array which first element is the item on the key array on the current index, and the second element is the item of the values array on the current index. +The `fromEntries` method turns a 2d array into an object. The first element in each subarray will be the key, and the second element in each subarray will be the value. In this case, we’re mapping over the `keys` array, which returns an array which first element is the item on the key array on the current index, and the second element is the item of the values array on the current index. This creates an array of subarrays containing the correct keys and values, which results in `{ name: "Lydia", age: 22 }` @@ -5087,18 +5085,18 @@ This creates an array of subarrays containing the correct keys and values, which ###### 154. What's the output? ```javascript -const createMember = ({ email, address = {} }) => { - const validEmail = /.+\@.+\..+/.test(email); - if (!validEmail) throw new Error("Valid email pls"); +const createMember = ({ email, address = {}}) => { + const validEmail = /.+\@.+\..+/.test(email) + if (!validEmail) throw new Error("Valid email pls") - return { - email, - address: address ? address : null, - }; -}; + return { + email, + address: address ? address : null + } +} -const member = createMember({ email: "my@email.com" }); -console.log(member); +const member = createMember({ email: "my@email.com" }) +console.log(member) ``` - A: `{ email: "my@email.com", address: null }` @@ -5121,13 +5119,13 @@ The default value of `address` is an empty object `{}`. When we set the variable ###### 155. What's the output? ```javascript -let randomValue = { name: "Lydia" }; -randomValue = 23; +let randomValue = { name: "Lydia" } +randomValue = 23 if (!typeof randomValue === "string") { - console.log("It's not a string!"); + console.log("It's not a string!") } else { - console.log("Yay it's a string!"); + console.log("Yay it's a string!") } ``` diff --git a/ar-AR/README_AR.md b/ar-AR/README_AR.md index 9c1210e2..6d5638e7 100644 --- a/ar-AR/README_AR.md +++ b/ar-AR/README_AR.md @@ -1,14 +1,16 @@ + +
# قائــمة أسئلة جافا سكريبت (مستوى متقدم) - أقوم بنشر عدة أسئلة جافاسكريبت بصورة يومية على حسابي في [انستغرام](https://www.instagram.com/theavocoder/). تتدرج الأسئلة إبتداءا من المستوى الأساسي أو البسيط الى المستوى المتقدم لإختبار مدى معرفتك بلغة الجافا سكريبت, قم بمراجعة و إنعاش معرفتك باللغة قليلا, أو قم بالتجهيز لمقابلة عمل لوظيفة مبرمج عن طريق هذه الأسئلة! أقوم بتحديث هذا المستودع أسبوعيا بإضافة المزيد من الأسئلة. :muscle: :rocket: -الأجوبة توجد في الجزء المطوي بالأسفل أدناه تحت كل سؤال على حدة, فقط قم بالضغط على كلمة الإجابة لكي تحصل على الإجابة, حظا موفقا :heart: + +الأجوبة توجد في الجزء المطوي بالأسفل أدناه تحت كل سؤال على حدة, فقط قم بالضغط على كلمة الإجابة لكي تحصل على الإجابة, حظا موفقا :heart: اللغات المتوفرة: @@ -25,7 +27,6 @@ - [🇳🇱 Nederlands](../nl-NL/README.md) - [🇵🇱 Polski](../pl-PL/README.md) - [🇧🇷 Português Brasil](../pt-BR/README_pt_BR.md) -- [🇷o Română](../ro-RO/README.ro.md) - [🇷🇺 Русский](../ru-RU/README.md) - [🇽🇰 Shqip](../sq-KS/README_sq_KS.md) - [🇹🇭 ไทย](../th-TH/README-th_TH.md) @@ -36,7 +37,8 @@ - [🇹🇼 繁體中文](../zh-TW/README_zh-TW.md)
---- +____________ + 1. ماهو الناتج ؟ @@ -62,10 +64,10 @@ sayHi();
الإجابة هي الخيار الرابع : D -في داخل الدالة, قمنا أولا بتعريف المتغير `name` مع الكلمة المفتاحية `var`. و هذا يعني ان المتغير قد حصلت له عملية hoisting والتي تعني انه قد تم حجز مساحة لهذا المتغير في هذه اللحظة مع قيمة مبدئية و التي هي `undefined` إلى ان نقوم فعليا بتعريف قيمة له لاحقا. +في داخل الدالة, قمنا أولا بتعريف المتغير `name` مع الكلمة المفتاحية `var`. و هذا يعني ان المتغير قد حصلت له عملية hoisting والتي تعني انه قد تم حجز مساحة لهذا المتغير في هذه اللحظة مع قيمة مبدئية و التي هي `undefined` إلى ان نقوم فعليا بتعريف قيمة له لاحقا. لم نقم بتعريف المتغير `name` بعد عندما قمنا بطباعته في السطر الاول من الدالة, لهذا لايزال يحمل القيمة `undefined`. -
-المتغيرات التي تم تعريفها بجانب الكلمات المفتاحية `let` و `const` يتم عمل عملية hoisting لها أيضا, ولكن على عكس المتغيرات التي يتم تعريفها بجانب الكلمة المفتاحية `var`, لا يتم تعريفها او الوصول اليها مالم نقم بإضافة قيمة لها فعليا. و يسمى هذا بال"temporal dead zone".عندما نحاول الوصول الى المتغيرات من النوع `let`قبل ان يتم تعريفها, نتحصل على الخطأ التالي `ReferenceError`. +
+المتغيرات التي تم تعريفها بجانب الكلمات المفتاحية `let` و `const` يتم عمل عملية hoisting لها أيضا, ولكن على عكس المتغيرات التي يتم تعريفها بجانب الكلمة المفتاحية `var`, لا يتم تعريفها او الوصول اليها مالم نقم بإضافة قيمة لها فعليا. و يسمى هذا بال"temporal dead zone".عندما نحاول الوصول الى المتغيرات من النوع `let`قبل ان يتم تعريفها, نتحصل على الخطأ التالي `ReferenceError`.

@@ -95,8 +97,8 @@ for (let i = 0; i < 3; i++) {
الإجابة هي الخيار الثالث: C -بسبب ترتيب تسلسل الأحداث في الجافا سكريبت, دالة `setTimeout` والتي هي دالة من نوع callbackقد تم استدعائها بعد ان تم تنفيذ ال loop. بماأن المتغير `i` في الloop الاولى قد تم تعريفه عن طريق الكلمة المفتاحية `var` فإن هذه القيمة هي global. أثناء تنفيذ هذه ال loop قد تم إضافة 1 الى المتغير `var` في كل دورة باستخدام العملية `++`. بنهاية الدورة و عندما تم استدعاء الدالة `setTimeout` كانت قيمة المتغير `i` قد أصبحت تساوي `3` في المثال الأول. -في الloop الثانية ,تم تعريف المتغير `i` باستخدام الكلمة المفتاحية `let` المتغيرات التي يتم تعريفها باستخدام الكلمات المفتاحية `let` و `const` هي متغيرات تنتمي فقط للBlock الذي تم تعريفها بداخله, والذي هو بين القوسين, أثناءتنفيذ الloop, سنقوم بالتحصل على قيمة جديدة للمتغير `i` في نهاية كل دورة , وأي قيمة تكون منتمية للScope بداخل الloop. +بسبب ترتيب تسلسل الأحداث في الجافا سكريبت, دالة `setTimeout` والتي هي دالة من نوع callbackقد تم استدعائها بعد ان تم تنفيذ ال loop. بماأن المتغير `i` في الloop الاولى قد تم تعريفه عن طريق الكلمة المفتاحية `var` فإن هذه القيمة هي global. أثناء تنفيذ هذه ال loop قد تم إضافة 1 الى المتغير `var` في كل دورة باستخدام العملية `++`. بنهاية الدورة و عندما تم استدعاء الدالة `setTimeout` كانت قيمة المتغير `i` قد أصبحت تساوي `3` في المثال الأول. +في الloop الثانية ,تم تعريف المتغير `i` باستخدام الكلمة المفتاحية `let` المتغيرات التي يتم تعريفها باستخدام الكلمات المفتاحية `let` و `const` هي متغيرات تنتمي فقط للBlock الذي تم تعريفها بداخله, والذي هو بين القوسين, أثناءتنفيذ الloop, سنقوم بالتحصل على قيمة جديدة للمتغير `i` في نهاية كل دورة , وأي قيمة تكون منتمية للScope بداخل الloop.

@@ -112,7 +114,7 @@ const shape = { diameter() { return this.radius * 2; }, - perimeter: () => 2 * Math.PI * this.radius, + perimeter: () => 2 * Math.PI * this.radius }; shape.diameter(); @@ -134,13 +136,14 @@ shape.perimeter(); لا توجد قيمة `radius` في ذلك ال object لهذا يقوم بإرجاع القيمة `undefined`. +

--- -4. ماهو الناتج؟ +4. ماهو الناتج؟ ```javascript +true; @@ -157,24 +160,23 @@ shape.perimeter(); الجواب هو الخيار الأول : A عملية الزيادة الأحادية هنا وجدت لكي تقوم بتحويل المعامل الى رقم, `true` هي `1` , و `false` هي `0`. - المتغير من نوع string `'Lydia'` هو قيمة صدقية أو حقيقية, بمعنى أنها تساوي `true` . السؤال الذي نقوم بطرحه هنا, هو هل هذه القيمة الصدقية هي قيمة غير صدقية؟ اي تساوي `false`؟ لهذا نتحصل على الجواب `false`. - + المتغير من نوع string `'Lydia'` هو قيمة صدقية أو حقيقية, بمعنى أنها تساوي `true` . السؤال الذي نقوم بطرحه هنا, هو هل هذه القيمة الصدقية هي قيمة غير صدقية؟ اي تساوي `false`؟ لهذا نتحصل على الجواب `false`.

--- -5. أي الإجابات هو إجابة صحيحة؟ +5. أي الإجابات هو إجابة صحيحة؟ ```javascript const bird = { - size: "small", + size: "small" }; const mouse = { name: "Mickey", - small: true, + small: true }; ``` @@ -188,21 +190,20 @@ const mouse = {
الجواب هو الخيار الأول: A -في لغة الجافا سكريبت, جميع مفاتيح الobjects هي من النوع string. الا اذا كانت عبارة عن symbol. حتى ولو أننا في بعض المرات لانقوم بوضع نوعها على انها string بصورة صريحة, ولكنها دائما يتم تحويلها الى نوع string وراء الكواليس. +في لغة الجافا سكريبت, جميع مفاتيح الobjects هي من النوع string. الا اذا كانت عبارة عن symbol. حتى ولو أننا في بعض المرات لانقوم بوضع نوعها على انها string بصورة صريحة, ولكنها دائما يتم تحويلها الى نوع string وراء الكواليس. -لغة الجافاسكريبت تقوم بترجمةال statements.عندما نقوم باستعمال ال bracket notation, تقوم الجافا سكريبت اولا برؤية أول فتحة للقوس `[` و تقوم بالمتابعة الى ان تجد قفلة هذا القوس `]`.فقط عندما تصل الى قفلة القوس حتى تقوم بتقييم ال statement و من ثم معالجتها. +لغة الجافاسكريبت تقوم بترجمةال statements.عندما نقوم باستعمال ال bracket notation, تقوم الجافا سكريبت اولا برؤية أول فتحة للقوس `[` و تقوم بالمتابعة الى ان تجد قفلة هذا القوس `]`.فقط عندما تصل الى قفلة القوس حتى تقوم بتقييم ال statement و من ثم معالجتها. `mouse[bird.size]`: اولا تقوم بتقييم`bird.size`, والتي هي تساوي `"small"`. `mouse["small"]` تقوم بإرجاع`true` -ولكن في المقابل, عندما نقوم بإستخدام ال dot notation,لا يتم معالجة الأمر هكذا. `mouse` ليس لديها مفتاح يسمى `bird`, و هذا يعني أن `mouse.bird` هي قيمة `undefined`. بالتالي نقوم بالسؤال عن ال`size` بإستخدام ال dot notation: للسؤال عن قيمة `mouse.bird.size`. -وبما أن `mouse.bird`قيمتها `undefined` ف نحن فعليا نقوم بالسؤال عن `undefined.size` و التي هي بالتأكيد غير صحيحة و غير صالحة و ستقوم بإرجاع error مشابه ل `Cannot read property "size" of undefined`. - +ولكن في المقابل, عندما نقوم بإستخدام ال dot notation,لا يتم معالجة الأمر هكذا. `mouse` ليس لديها مفتاح يسمى `bird`, و هذا يعني أن `mouse.bird` هي قيمة `undefined`. بالتالي نقوم بالسؤال عن ال`size` بإستخدام ال dot notation: للسؤال عن قيمة `mouse.bird.size`. +وبما أن `mouse.bird`قيمتها `undefined` ف نحن فعليا نقوم بالسؤال عن `undefined.size` و التي هي بالتأكيد غير صحيحة و غير صالحة و ستقوم بإرجاع error مشابه ل `Cannot read property "size" of undefined`.

--- -6. ماهو الناتج؟ +6. ماهو الناتج؟ ```javascript let c = { greeting: "Hey!" }; @@ -230,7 +231,7 @@ console.log(d.greeting); -لذا, عندما تقوم بتغيير object واحد , انت فعليا تقوم بتغيير جميع الobjects. +لذا, عندما تقوم بتغيير object واحد , انت فعليا تقوم بتغيير جميع الobjects.

@@ -260,13 +261,13 @@ console.log(b === c);
الجواب هو الخيار الثالث: C -`new Number()` هي دالة من نوع built-in function constructer. على الرغم من أنها تبدو كرقم, ولكنها في الحقيقة ليس رقم, هي عبارة عن object ولديها العديد العديد من المميزات. - +`new Number()` هي دالة من نوع built-in function constructer. على الرغم من أنها تبدو كرقم, ولكنها في الحقيقة ليس رقم, هي عبارة عن object ولديها العديد العديد من المميزات. + عندما نقوم بإستخدام العلامة او العامل `==`, هي تقوم فقط بالتحقق من إذا ماكان لديها same _value_.كلا الطرفين قيمتهم تساوي `3` لهذا تقوم بإرجاع `true`. -و لكن على الرغم من هذا, عندما نقوم بإستخدام العملية أو المعامل `===`, كلا القيمة _and_ النوع يجب ان يكونا نفس الشيء. +و لكن على الرغم من هذا, عندما نقوم بإستخدام العملية أو المعامل `===`, كلا القيمة _and_ النوع يجب ان يكونا نفس الشيء. -هي ليست `new Number()` هي ليست عبارة عن رقم, هي عبارة عن **object** , وكلاهما سيقومان بإرجاع `false.` +هي ليست `new Number()` هي ليست عبارة عن رقم, هي عبارة عن **object** , وكلاهما سيقومان بإرجاع `false.`

@@ -274,7 +275,7 @@ console.log(b === c); --- -8. ماهو الناتج؟ +8. ماهو الناتج؟ ```javascript class Chameleon { @@ -302,8 +303,7 @@ console.log(freddie.colorChange("orange"));
الجواب هو الخيار الرابع: D -الدالة `colorChange` هي دالة static, و الدوال التي هي من نوع static هي دوال صممت لكي يتم استخدامها فقط في الconstructor الذي تم تعريفها به, و ليس من الممكن ان يتم تمريرها او استخدامها من قبل اي مكون children. بما أن `freddie` هي متغير children فإن الدالة لم يتم تمريرها اليه و هي غير متوفرة في ال instant من `freddie` لذا نتحصل على الخطأ `TypeError` . - +الدالة `colorChange` هي دالة static, و الدوال التي هي من نوع static هي دوال صممت لكي يتم استخدامها فقط في الconstructor الذي تم تعريفها به, و ليس من الممكن ان يتم تمريرها او استخدامها من قبل اي مكون children. بما أن `freddie` هي متغير children فإن الدالة لم يتم تمريرها اليه و هي غير متوفرة في ال instant من `freddie` لذا نتحصل على الخطأ `TypeError` .

@@ -327,17 +327,16 @@ console.log(greetign);
الجواب هو الخيار الأول : A -تقوم بعمل log على الconsole ل object. و لأننا قمنا بإنشاء object فارغ في global object! عندما قمنا بالخطأ بطباعة `greetign` بدل ان نقوم بطباعتها بصورة صحيحة هكذا `greeting`, هنا قام مترجم الجافاسكريبت بترجمة الآتي `global.greetign = {}` أو `window.greetign = {}` في المتصفح. - -لكي نتجنب حدوث مثل هذه الحالة, بإمكاننا إستخدام `"use strict"`. بفعل هذه الخطوة ستتأكد من أنك قد عرفت المتغير قبل ان تساويه بأي شي آخر. +تقوم بعمل log على الconsole ل object. و لأننا قمنا بإنشاء object فارغ في global object! عندما قمنا بالخطأ بطباعة `greetign` بدل ان نقوم بطباعتها بصورة صحيحة هكذا `greeting`, هنا قام مترجم الجافاسكريبت بترجمة الآتي `global.greetign = {}` أو `window.greetign = {}` في المتصفح. +لكي نتجنب حدوث مثل هذه الحالة, بإمكاننا إستخدام `"use strict"`. بفعل هذه الخطوة ستتأكد من أنك قد عرفت المتغير قبل ان تساويه بأي شي آخر.

--- -10. ما الذي يحدث عندما نقوم بعمل الآتي؟ + 10. ما الذي يحدث عندما نقوم بعمل الآتي؟ ```javascript function bark() { @@ -360,7 +359,6 @@ bark.animal = "dog"; هذا ممكن في لغة الجافاسكريبت, لأن الدوال هي عبارة عن objects, (كل شيء بداخل الأنواع التي هي primitive هو عبارة عن object) الدالة هي عبارة عن نوع خاص من الobjects, الكود الذي تقوم بكتابته بنفسك هو ليس بالدالة الفعلية, الدالة هي object لديه خصائص. و هذه الخاصية قابلة للمناداة -

@@ -376,7 +374,7 @@ function Person(firstName, lastName) { } const member = new Person("Lydia", "Hallie"); -Person.getFullName = function () { +Person.getFullName = function() { return `${this.firstName} ${this.lastName}`; }; @@ -394,11 +392,10 @@ console.log(member.getFullName()); الجواب هو الخيار الأول: A ليس بإمكانك اضافة الخصائص ل constructor كما تقوم بإضافة الخصائص للobjects. إذا أردت أن تضيف مميزات لكل الobjects مرة واحدة, سيجب عليك أن تقوم بإستخدام الprototype. لذا في هذه الحالة, - ```js -Person.prototype.getFullName = function () { +Person.prototype.getFullName = function() { return `${this.firstName} ${this.lastName}`; }; ``` @@ -437,10 +434,9 @@ console.log(sarah);
الجواب هو الخيار الأول: A -للمتغير `sarah` لم نقم بإستخدام الكلمة المفتاحية `new`, عندإستخدام الكلمة المفتاحية `new` ف هي تشير الى ال object الخالي او الفارغ الذي قمنا بإنشاءه, و لكن اذا لم تقم بإضافة`new` ف هي ستشير الى ال **global object**!. - -نحن نقول بأن `this.firstName` تساوي `"Sarah"` و `this.lastName` تساوي `"Smith"`. ماقمنا بفعله حقا هنا, هو أنه قمنا بتعريف `global.firstName = 'Sarah'` و `global.lastName = 'Smith'`. المتغير `sarah` لا يظل `undefined`. +للمتغير `sarah` لم نقم بإستخدام الكلمة المفتاحية `new`, عندإستخدام الكلمة المفتاحية `new` ف هي تشير الى ال object الخالي او الفارغ الذي قمنا بإنشاءه, و لكن اذا لم تقم بإضافة`new` ف هي ستشير الى ال **global object**!. +نحن نقول بأن `this.firstName` تساوي `"Sarah"` و `this.lastName` تساوي `"Smith"`. ماقمنا بفعله حقا هنا, هو أنه قمنا بتعريف `global.firstName = 'Sarah'` و `global.lastName = 'Smith'`. المتغير `sarah` لا يظل `undefined`.

@@ -461,7 +457,7 @@ console.log(sarah);
الجواب هو الخيار الرابع: D -أثناء مرحلة ال**capturing**, الevent تمر عبر العناصر العليا, أي العناصر الآباء إلى أن تصل الى العنصر المقصود أو المراد, حينها تتمكن من الوصول الى العنصر **target** , و حينها تبدأ عملية ال **bubbling**. +أثناء مرحلة ال**capturing**, الevent تمر عبر العناصر العليا, أي العناصر الآباء إلى أن تصل الى العنصر المقصود أو المراد, حينها تتمكن من الوصول الى العنصر **target** , و حينها تبدأ عملية ال **bubbling**. @@ -483,8 +479,7 @@ console.log(sarah);
الجواب هو الخيار الثاني: B -جميع الobjects لديها prototypes, عدا ال objects من نوع **base object**. الobject من نوع base object هو عبارة عن object تم إنشاءه من قبل المستخدم, أو تم إنشاءه عن طريق إستخدام الكلمة المفتاحية `new`. الbase object لديه حق الوصول الى بعض ال methods و الخصائص. مثال: `.toString`. هذا هو السبب الذي يمكنك من إستخدام built-in JavaScript methods, مثل هذه ال methods جميعها متاحة في ال ptototype, على الرغم من أن لغة الجافا سكريبت ليس بإمكانها أن تجدها بصورة مباشرة من الobject الذي قمت أنت بإنشاءه, و لكنها تذهب الى سلسلة الprototype حيث بإمكانها ان تجده هناك, مما يجعله قابل للوصول من قبلك, أي بإمكانك أن تصل إليه. - +جميع الobjects لديها prototypes, عدا ال objects من نوع **base object**. الobject من نوع base object هو عبارة عن object تم إنشاءه من قبل المستخدم, أو تم إنشاءه عن طريق إستخدام الكلمة المفتاحية `new`. الbase object لديه حق الوصول الى بعض ال methods و الخصائص. مثال: `.toString`. هذا هو السبب الذي يمكنك من إستخدام built-in JavaScript methods, مثل هذه ال methods جميعها متاحة في ال ptototype, على الرغم من أن لغة الجافا سكريبت ليس بإمكانها أن تجدها بصورة مباشرة من الobject الذي قمت أنت بإنشاءه, و لكنها تذهب الى سلسلة الprototype حيث بإمكانها ان تجده هناك, مما يجعله قابل للوصول من قبلك, أي بإمكانك أن تصل إليه.

@@ -511,10 +506,9 @@ sum(1, "2");
الجواب هو الخيار الثالث: C -لغة الجافاسكريبت هي لغة **dynamically typed language** بمعنى أننا لا نقوم بتعريف نوع معين للمتغيرات, المتغيرات بصورة أوتوماتيكية يتم تحويلها الى أنواع أخرى بدون أن تعرف أنت ذلك, وهذا يسمى ب _implicit type coercion_. **Coercion** تعني بأنك تقوم بالتحويل من نوع الى آخر. - -في هذا المثال, لغة الجافاسكريبت تقوم بتحويل الرقم `1` الى string, لكي تستطيع الدالةأن تقوم بعملها و تتمكن من إرجاع قيمة. أثناء قيام عملية إضافةالمتغير من النوع number و الذي هو (`1`) و المتغير من النوع string والذي هو (`'2'`), الرقم تم التعامل معه ك string, بهذه الطريقة سنتمكن من عمل عملية concatenate للمتغيرين من نوع string ك مثال `"Hello" + "World"`, لهذا مايحدث هنا هو عبارة عن `"1" + "2"` و الذي بدوره يقوم بإرجاع `"12"`. +لغة الجافاسكريبت هي لغة **dynamically typed language** بمعنى أننا لا نقوم بتعريف نوع معين للمتغيرات, المتغيرات بصورة أوتوماتيكية يتم تحويلها الى أنواع أخرى بدون أن تعرف أنت ذلك, وهذا يسمى ب _implicit type coercion_. **Coercion** تعني بأنك تقوم بالتحويل من نوع الى آخر. +في هذا المثال, لغة الجافاسكريبت تقوم بتحويل الرقم `1` الى string, لكي تستطيع الدالةأن تقوم بعملها و تتمكن من إرجاع قيمة. أثناء قيام عملية إضافةالمتغير من النوع number و الذي هو (`1`) و المتغير من النوع string والذي هو (`'2'`), الرقم تم التعامل معه ك string, بهذه الطريقة سنتمكن من عمل عملية concatenate للمتغيرين من نوع string ك مثال `"Hello" + "World"`, لهذا مايحدث هنا هو عبارة عن `"1" + "2"` و الذي بدوره يقوم بإرجاع `"12"`.

@@ -547,8 +541,8 @@ console.log(number); ال **prefix** العامل الأحادي `++`: -1. تقوم بزيادة القيمة(number الآن تساوي `2`) -2. تقوم بإٍرجاع القيمة (هذه ترجع `2`) +1. تقوم بزيادة القيمة(number الآن تساوي `2`) +2. تقوم بإٍرجاع القيمة (هذه ترجع `2`) هذا يقوم بإرجاع `0 2 2`. @@ -558,7 +552,7 @@ console.log(number); --- -17.ماهو الناتج؟ +17.ماهو الناتج؟ ```javascript function getPersonInfo(one, two, three) { @@ -582,8 +576,7 @@ getPersonInfo`${person} is ${age} years old`;
الجواب هو الخيار الثاني: B -اذا قمت بإستخدام tagged template literals, فإن قيمة ال argument الأول هي دائما عبارة عن array والذي نوع قيمها عبارة عن string, ماتبقى من الarguments تتحصل على القيم من الpassed expressions. - +اذا قمت بإستخدام tagged template literals, فإن قيمة ال argument الأول هي دائما عبارة عن array والذي نوع قيمها عبارة عن string, ماتبقى من الarguments تتحصل على القيم من الpassed expressions.

@@ -615,11 +608,11 @@ checkAge({ age: 18 });
الجواب هو الخيار الثالث: C -عندما نقوم بإختبار المساواة أو التساوي بين طرفين, ال primitives يتم مقارنتها عن طريق قيمها, بينما ال objects يتم مقارنتها عن طريق الreference الذي يتبع لها, لغة الجافاسكريبت تتحقق عن إذا ماكان الrefrence الذي يتبع لobject يشير الى نفس الموقع في الذاكرة. +عندما نقوم بإختبار المساواة أو التساوي بين طرفين, ال primitives يتم مقارنتها عن طريق قيمها, بينما ال objects يتم مقارنتها عن طريق الreference الذي يتبع لها, لغة الجافاسكريبت تتحقق عن إذا ماكان الrefrence الذي يتبع لobject يشير الى نفس الموقع في الذاكرة. -لدينا هنا اثنان من ال objects والتي نقوم بعمل مقارنة بينهما, واللذان بدورهما ليس لديهما ذلك, الobject الذي قمنا بتمريره ك parameter يشير الى موقع مختلف في الذاكرة من الموقع الذي يشير اليه الobject الثاني و الذي تم استخدامه للتحق من شرط المساواة. +لدينا هنا اثنان من ال objects والتي نقوم بعمل مقارنة بينهما, واللذان بدورهما ليس لديهما ذلك, الobject الذي قمنا بتمريره ك parameter يشير الى موقع مختلف في الذاكرة من الموقع الذي يشير اليه الobject الثاني و الذي تم استخدامه للتحق من شرط المساواة. -لهذا كلا من `{ age: 18 } === { age: 18 }` و `{ age: 18 } == { age: 18 }` يرجعان `false`. +لهذا كلا من `{ age: 18 } === { age: 18 }` و `{ age: 18 } == { age: 18 }` يرجعان `false`.

@@ -647,15 +640,14 @@ getAge(21);
الجواب هو الخيار الثالث: C -العامل spread `...args` يقوم بإرجاع array مع arguments. الarray هي object, لذا فإن `typeof args` تقوم بإرجاع `"object"`. - +العامل spread `...args` يقوم بإرجاع array مع arguments. الarray هي object, لذا فإن `typeof args` تقوم بإرجاع `"object"`.

--- -20. ماهو الناتج؟ +20. ماهو الناتج؟ ```javascript function getAge() { @@ -677,8 +669,7 @@ getAge();
الجواب هو الخيار الثالث: C -بإستخدام `"use strict"`, يمكنك التأكد بأنك لن تقوم عن طريق الخطأ بتعريف global variables. نحن لم نقم قط بتعريف المتغير `age`, و بما أننا قمنا بإستخدام `"use strict"` ستقوم بإرجاع reference error. اذا لم نقم بإستخدام `"use strict"` لكانت قد أدت المطلوب, بما أن الخاصية `age` تم إضافتها لل global object. - +بإستخدام `"use strict"`, يمكنك التأكد بأنك لن تقوم عن طريق الخطأ بتعريف global variables. نحن لم نقم قط بتعريف المتغير `age`, و بما أننا قمنا بإستخدام `"use strict"` ستقوم بإرجاع reference error. اذا لم نقم بإستخدام `"use strict"` لكانت قد أدت المطلوب, بما أن الخاصية `age` تم إضافتها لل global object.

@@ -687,7 +678,7 @@ getAge();
21. ماهي القيمة التي تحملها `sum`؟ -
+
```javascript const sum = eval("10*10+5"); @@ -703,8 +694,7 @@ const sum = eval("10*10+5");
الجواب هو الخيار الأول : A -`eval` تقوم بتقييم الكود الذي تم تمريره ك string. إذا كان عبارة عن expression كما في هذه الحالة, فإنها تقوم بتقييم ال expression. ال expression هو `10 * 10 + 5`. و هذا بدوره يقوم بإرجاع الرقم `105`. - +`eval` تقوم بتقييم الكود الذي تم تمريره ك string. إذا كان عبارة عن expression كما في هذه الحالة, فإنها تقوم بتقييم ال expression. ال expression هو `10 * 10 + 5`. و هذا بدوره يقوم بإرجاع الرقم `105`.

@@ -718,7 +708,6 @@ const sum = eval("10*10+5"); ```javascript sessionStorage.setItem("cool_secret", 123); ``` -
A - الى الأبد, فالبيانات لايمكن أن تفقد. @@ -728,7 +717,6 @@ B - عندما يقوم المستخدم بقفل ال tab. C - عندما يقوم المستخدم بقفل نافذه المتصفح , ليس فقط الtab. D - عندما يقوم المستخدم بقفل جهاز الكمبيوتر. -
الإجابة @@ -736,17 +724,16 @@ D - عندما يقوم المستخدم بقفل جهاز الكمبيوتر.
الجواب هو الخيار الثاني: B -البيانات التي يتم تخزينها في `sessionStorage` يتم فقدها بعد قفل ال tab. - -إذا قمت بإستخدام `localStorage`, البيانات ستكون مخزنة هناك الى الأبد, و لكن اذا قمت بإستثناء ان تقوم بمناداة الدالة Clear كما في التالي `localStorage.clear()` عندها ستفقد هذه البيانات.: +البيانات التي يتم تخزينها في `sessionStorage` يتم فقدها بعد قفل ال tab. +إذا قمت بإستخدام `localStorage`, البيانات ستكون مخزنة هناك الى الأبد, و لكن اذا قمت بإستثناء ان تقوم بمناداة الدالة Clear كما في التالي `localStorage.clear()` عندها ستفقد هذه البيانات.:

--- -23. ماهو الناتج؟ +23. ماهو الناتج؟ ```javascript var num = 8; @@ -765,10 +752,9 @@ console.log(num);
الجواب هو الخيار الثاني: B -مع الكلمة المفتاحية `var` بإمكانك تريف عدد من المتغيرات تحمل نفس الإسم, و المتغير سيقوم بأخذ آخر قيمة تمت إضافتها اليه. - -ليس بإمكانك أن تفعل هذا مع `let` أو `const` بما أن الكلمتان المفتاحيتان عبارة عن block-scoped, بمعنى أن القيمة ستكون متاحة في نطاق الBlock الذي تم تعريفها به. +مع الكلمة المفتاحية `var` بإمكانك تريف عدد من المتغيرات تحمل نفس الإسم, و المتغير سيقوم بأخذ آخر قيمة تمت إضافتها اليه. +ليس بإمكانك أن تفعل هذا مع `let` أو `const` بما أن الكلمتان المفتاحيتان عبارة عن block-scoped, بمعنى أن القيمة ستكون متاحة في نطاق الBlock الذي تم تعريفها به.

@@ -797,17 +783,16 @@ set.has(1);
الجواب هو الخيار الثالث: C -كل مفاتيح ال object (عدا الSymbols)هي عبارة عن strings وراء الكواليس, حتى لو لم تقم بكتابة ذلك صراحة بنفسك ك string, لهذا دائما `obj.hasOwnProperty('1')` تقوم بإرجاع القيمة true. - -ولكنها لا تعمل بهذا الشكل مع set, ليس هنالك `'1'` من ضمن set, لهذا `set.has('1')` تقوم بإرجاع `false`, لديها القيمة الرقمية `1` أي من النوع number, `set.has(1)` تقوم بإرجاع `true`. +كل مفاتيح ال object (عدا الSymbols)هي عبارة عن strings وراء الكواليس, حتى لو لم تقم بكتابة ذلك صراحة بنفسك ك string, لهذا دائما `obj.hasOwnProperty('1')` تقوم بإرجاع القيمة true. +ولكنها لا تعمل بهذا الشكل مع set, ليس هنالك `'1'` من ضمن set, لهذا `set.has('1')` تقوم بإرجاع `false`, لديها القيمة الرقمية `1` أي من النوع number, `set.has(1)` تقوم بإرجاع `true`.

--- -25. ماهو الناتج؟ +25. ماهو الناتج؟ ```javascript const obj = { a: "one", b: "two", a: "three" }; @@ -837,7 +822,7 @@ console.log(obj); - A: true - B: false -- C: تعتمد على +- C: تعتمد على
الإجابة

@@ -845,10 +830,9 @@ console.log(obj); الجواب هو الخيارالأول: A سياق التنفيذ الأساسي هو سياق تنفيذ الglobal, وهي الشيء الذي يمكن الوصول إليه من أي مكان في الكود الذي ببرنامجك. -

- + --- @@ -871,8 +855,7 @@ for (let i = 1; i < 5; i++) {
الجواب هو الخيار الثالث: C -العبارة `continue` تقوم بتخطي دورة التكرار إذا وجد شرط معين يقوم بإرجاع `true`. - +العبارة `continue` تقوم بتخطي دورة التكرار إذا وجد شرط معين يقوم بإرجاع `true`.

@@ -888,7 +871,7 @@ String.prototype.giveLydiaPizza = () => { const name = "Lydia"; -console.log(name.giveLydiaPizza()); +console.log(name.giveLydiaPizza()) ``` - A: `"Just give Lydia pizza already!"` @@ -901,15 +884,14 @@ console.log(name.giveLydiaPizza());
الجواب هو الخيار الأول : A -`String` هي built-in constructor, و لهذا سنتمكن من إضافة خصائص لها. لقد قمت بإضافة method للprototype الخاص ب `String`. Primitive strings يتمتحويلهم بصورة اوتوماتيكية الى objects من نوع string, و التي بدورها تم انشائها عن طريق دالة ال string prototype, لهذا جميع الstrings و التي هي string objects لديها حق الوصول الى الmethod. - +`String` هي built-in constructor, و لهذا سنتمكن من إضافة خصائص لها. لقد قمت بإضافة method للprototype الخاص ب `String`. Primitive strings يتمتحويلهم بصورة اوتوماتيكية الى objects من نوع string, و التي بدورها تم انشائها عن طريق دالة ال string prototype, لهذا جميع الstrings و التي هي string objects لديها حق الوصول الى الmethod.

--- -29. ماهو الناتج؟ +29. ماهو الناتج؟ ```javascript const a = {}; @@ -932,13 +914,12 @@ console.log(a[b]);
الجواب هو الخيار الثاني : B -مفاتيح ال object يتم تحويلها اوتوماتيكيا الى strings. نحن نحاول أن نقوم بجعل object عبارة عن مفتاح للobject `a`, و الذي يحمل القيمة `123`. +مفاتيح ال object يتم تحويلها اوتوماتيكيا الى strings. نحن نحاول أن نقوم بجعل object عبارة عن مفتاح للobject `a`, و الذي يحمل القيمة `123`. و لكن, عندما نقوم بمحاول جعل object الى نوع string, سيصبح `"[object Object]"`. لذا ما نحاول أن نقوله هنا, هو أن `a["object Object"] = 123`. -إذا, سنحاول أن نفعل هذا مرة أخرى , `c` هو object آخر سنقوم بتحويله الى string بصورة صريحة, لذا `a["object Object"] = 456`. - -إذاَ, نحن نقوم بعمل log ل `a[b]`, و التي هي في الحقيقة `a["object Object"]`. و نحن قبل قليل قمنا بوضع قيمتها التي تساوي `456`, لذا ستقوم بإرجاع `456`. +إذا, سنحاول أن نفعل هذا مرة أخرى , `c` هو object آخر سنقوم بتحويله الى string بصورة صريحة, لذا `a["object Object"] = 456`. +إذاَ, نحن نقوم بعمل log ل `a[b]`, و التي هي في الحقيقة `a["object Object"]`. و نحن قبل قليل قمنا بوضع قيمتها التي تساوي `456`, لذا ستقوم بإرجاع `456`.

@@ -969,17 +950,17 @@ baz(); لدينا الدالة `setTimeout` والتي تم استدعائها أولا, و لكن تم الخروج منها آخراً. -هذا لأن في المتصفح, ليس لدينا محرَك من نوع runtime, أيضا لدينا مايعرف ب `WebAPI`. هذا ال`WebAPI` يقوم بإعطائنا الدالة `setTimeout` لكي نبدأ بها, على سبيل المثال: DOM. +هذا لأن في المتصفح, ليس لدينا محرَك من نوع runtime, أيضا لدينا مايعرف ب `WebAPI`. هذا ال`WebAPI` يقوم بإعطائنا الدالة `setTimeout` لكي نبدأ بها, على سبيل المثال: DOM. بعد ان يتم ارسال و البدء بتنفيذ ال _callback_ الى الWebAPI, الدالة `setTimeout` نفسها (ليس ال callback!) يتم اخراجها من الstack. -الآن, `foo` يتم إدخالها و البدء بتنفيذها, بينما `"First"` يتم تسجيل دخولها. +الآن, `foo` يتم إدخالها و البدء بتنفيذها, بينما `"First"` يتم تسجيل دخولها. -`foo` يتم إخراجها من ال stack, بينما `baz` يتم إدخالها و البدأ بتنفيذها. `"Third"` يتم تسجيل دخولها. +`foo` يتم إخراجها من ال stack, بينما `baz` يتم إدخالها و البدأ بتنفيذها. `"Third"` يتم تسجيل دخولها. @@ -987,19 +968,17 @@ baz(); -هنا تحديدا المكان الذي تبدأ فيه الloop بالعمل. +هنا تحديدا المكان الذي تبدأ فيه الloop بالعمل. ال **event loop** تنظر الى الstack و ال task queue, إذا كانت الstack خاوية, فهي تقوم بأخذ أول شيء في الqueue. و تقوم بإدخاله الى stack. -`bar` يتم إدخالها و البدأ بتنفيذها, `"Second"` يتم تسجيل دخولها, و من ثم إخراجها من الstack. - +`bar` يتم إدخالها و البدأ بتنفيذها, `"Second"` يتم تسجيل دخولها, و من ثم إخراجها من الstack.

--- -
31. ماهو ال event.target عندما نقوم بالضغط على الزر
@@ -1007,12 +986,14 @@ baz(); ```html
- +
``` -- A: الخارجي `div` +- A: الخارجي `div` - B: الداخلي `div` - C: `button` - D: array تحتوي على جميع العناصرالمتداخلة. @@ -1022,8 +1003,7 @@ baz();
الجواب هو الخيار الثالث: C -العنصر المتداخل الأعمق الذي تسبب بتنفيذ الevent هو العنصر الذي يستهدفه هذا الevent, بإمكانك إيقاف ال bubbling عن طريق `event.stopPropagation`. - +العنصر المتداخل الأعمق الذي تسبب بتنفيذ الevent هو العنصر الذي يستهدفه هذا الevent, بإمكانك إيقاف ال bubbling عن طريق `event.stopPropagation`.

@@ -1036,7 +1016,9 @@ baz(); ```html
-

Click here!

+

+ Click here! +

``` @@ -1050,8 +1032,7 @@ baz();
الجواب هو الخيار الأول: A -إذا قمنا بالضغط على `p` سنرى إثنان من الlogs, ألا و هما `p` و `div`, أثناء عملية event propagation, هنالك ثلاث مراحل: الا وهي capturing, target و bubbling. بصورة افتراضية, الevent handlers يتم تنفيذهم في مرحلة الbubbling (إلا في حال أنك قمت بضبط قيمة `useCapture` ل `true` ). هي تتسلسل ابتداءا من أعمق عنصر متداخل تصاعدا الى الأقل عمقاً. - +إذا قمنا بالضغط على `p` سنرى إثنان من الlogs, ألا و هما `p` و `div`, أثناء عملية event propagation, هنالك ثلاث مراحل: الا وهي capturing, target و bubbling. بصورة افتراضية, الevent handlers يتم تنفيذهم في مرحلة الbubbling (إلا في حال أنك قمت بضبط قيمة `useCapture` ل `true` ). هي تتسلسل ابتداءا من أعمق عنصر متداخل تصاعدا الى الأقل عمقاً.

@@ -1081,10 +1062,9 @@ sayHi.bind(person, 21);
الجواب هو الخيار الرابع: D -في الحالتين, بإمكاننا تمرير ال object الذي نود أن تشير اليه الكلمة المفتاحية `this`, ولكن, `.call` هي أيضا تم تنفيذها حالا. +في الحالتين, بإمكاننا تمرير ال object الذي نود أن تشير اليه الكلمة المفتاحية `this`, ولكن, `.call` هي أيضا تم تنفيذها حالا. `.bind.` تقوم بإرجاع نسخة من الدالة, ولكن مع سياق محدد, لذا هي لا يتم تنفيذها حالاً. -

@@ -1111,10 +1091,9 @@ console.log(typeof sayHi());
الجواب هو الخيار الثاني: B -دالة `sayHi` تقوم بإرجاع القيمة المرجعة من الدالة المناداة في اللحظة (IIFE). هذه الدالة تقوم بإرجاع `0`, و الذي نوعه عبارة عن `"number"`. - -لمعلوماتك: لدينا فقط سبعة أنواع من ال built-in و هي : `null`, `undefined`, `boolean`, `number`, `string`, `object`, و `symbol`, و `bigint`.`"function"` هي ليست نوع, وبما أن الدوال عبارة عن objects, ف هي ليست من النوع `"object"`. +دالة `sayHi` تقوم بإرجاع القيمة المرجعة من الدالة المناداة في اللحظة (IIFE). هذه الدالة تقوم بإرجاع `0`, و الذي نوعه عبارة عن `"number"`. +لمعلوماتك: لدينا فقط سبعة أنواع من ال built-in و هي : `null`, `undefined`, `boolean`, `number`, `string`, `object`, و `symbol`, و `bigint`.`"function"` هي ليست نوع, وبما أن الدوال عبارة عن objects, ف هي ليست من النوع `"object"`.

@@ -1151,7 +1130,7 @@ undefined; - `''` (empty string) - `false` -Function constructors, مثل `new Number` و `new Boolean` هي قيم صحيحية. +Function constructors, مثل `new Number` و `new Boolean` هي قيم صحيحية.

@@ -1207,7 +1186,6 @@ console.log(numbers); `[1, 2, 3, 7 x empty, 11]` وذلك يعتمد على المكان الذي قمت فيه بتشغيل البرنامج ( هو مختلف لكل متصفح, node, ...الخ) -

@@ -1242,10 +1220,9 @@ console.log(numbers); النطاق أو الblock `catch`يستقبل ال arguemnt الذي يساوي `x`, هذا ليس نفس القيمة `x` عندما قمنا بتمرير الarguments, هذا المتغير `x` هو متغير block-scoped, أي يتم التعامل معه أو مناداته فقط بداخل الblock الذي تم تعريفه به. -لاحقا, قمنا بضبط القيمة `1` لهذا المتغير من نوع block-scoped, وقمنا أيضا بضبط قيمة للمتغير `y`. الآن نحن نقوم بطباعة قيمة المتغير الذي من نوع block-scoped و الذي هو `x` عن طريق الlog, و الذي هو يساوي `1`. - -بخارج نطاق ال`catch` block, `x` هي لاتزال `undefined`, و قيمة ال `y` تساوي `2`. عندما نريد طباعة قيمة ال x عن طريق الlog خارج نطاق ال `catch` block, فهي تقوم بإرجاع `undefined`, و ال `y` تقوم بإرجاع `2`. +لاحقا, قمنا بضبط القيمة `1` لهذا المتغير من نوع block-scoped, وقمنا أيضا بضبط قيمة للمتغير `y`. الآن نحن نقوم بطباعة قيمة المتغير الذي من نوع block-scoped و الذي هو `x` عن طريق الlog, و الذي هو يساوي `1`. +بخارج نطاق ال`catch` block, `x` هي لاتزال `undefined`, و قيمة ال `y` تساوي `2`. عندما نريد طباعة قيمة ال x عن طريق الlog خارج نطاق ال `catch` block, فهي تقوم بإرجاع `undefined`, و ال `y` تقوم بإرجاع `2`.

@@ -1266,23 +1243,19 @@ console.log(numbers); لغة الجافاسكريبت لديها فقط primitive types و objects. -نقصد بال Primitive types: `boolean`, `null`, `undefined`, `bigint`, `number`, `string`, و `symbol`. - -مايميز ال primitive من ال object هو أن ال primitives ليس لديها أي خصائص أو methods; ولكنك ستلاحظ أن `'foo'.toUpperCase()`يتم تقييمها ومعالجتها الى `'FOO'`و لا نتحصل على الخطأ `TypeError`. هذا لأنه عندما تحاول الوصول الى خاصية أو method لمتغير من من نوع primitive مثل ال string, فإن لغة الجافاسكريبت ستقوم بشكل ضمني بعمل wrap لل object بإستخدام واحدة من ال wrapper Classes, أي مانعنيه `String`, و لاحقا بصورة مباشرة يقوم بالتخلص من الwrapper, بعد أن يتم تقييم و تنفيذ الexpression. جميع الprimitives, ماعدا `null` و `undefined` تقوم بعمل هذه العملية. +نقصد بال Primitive types: `boolean`, `null`, `undefined`, `bigint`, `number`, `string`, و `symbol`. +مايميز ال primitive من ال object هو أن ال primitives ليس لديها أي خصائص أو methods; ولكنك ستلاحظ أن `'foo'.toUpperCase()`يتم تقييمها ومعالجتها الى `'FOO'`و لا نتحصل على الخطأ `TypeError`. هذا لأنه عندما تحاول الوصول الى خاصية أو method لمتغير من من نوع primitive مثل ال string, فإن لغة الجافاسكريبت ستقوم بشكل ضمني بعمل wrap لل object بإستخدام واحدة من ال wrapper Classes, أي مانعنيه `String`, و لاحقا بصورة مباشرة يقوم بالتخلص من الwrapper, بعد أن يتم تقييم و تنفيذ الexpression. جميع الprimitives, ماعدا `null` و `undefined` تقوم بعمل هذه العملية.

--- -40. ماهو الناتج؟ +40. ماهو الناتج؟ ```javascript -[ - [0, 1], - [2, 3], -].reduce( +[[0, 1], [2, 3]].reduce( (acc, cur) => { return acc.concat(cur); }, @@ -1302,8 +1275,7 @@ console.log(numbers); `[1, 2]` هي القيمة المبدئية.هذه القيمة هي التي بدأنا بها, و هي القيمة الأولى ل `acc`. أثناء الدورة الأولى`acc` تساوي `[1,2]` و `cur` تساوي `[0, 1]`, عندما نقوم بدمجهما سويا عن طريق concat يصبح لدينا الناتج `[1, 2, 0, 1]`. -إذاً, `[1, 2, 0, 1]` هي `acc` و `[2, 3]` هي `cur`. نقوم بدمجهما سوية و نتحصل على `[1, 2, 0, 1, 2, 3]`. - +إذاً, `[1, 2, 0, 1]` هي `acc` و `[2, 3]` هي `cur`. نقوم بدمجهما سوية و نتحصل على `[1, 2, 0, 1, 2, 3]`.

@@ -1330,29 +1302,27 @@ console.log(numbers); `null` قيمة خطئية. -`!null` تقوم بإرجاع `true`. +`!null` تقوم بإرجاع `true`. `!true` تقوم بإرجاع `false`. - ---- - +********* + `""` قيمة خطئية. -`!""`تقوم بإرجاع `true`. +`!""`تقوم بإرجاع `true`. `!true` تقوم بإرجاع `false`. - ---- - +********* + `1` قيمة صحيحية. `!1` تقوم بإرجاع `false`. -`!false` تقوم بإرجاع `true`. +`!false` تقوم بإرجاع `true`.

- + --- @@ -1368,10 +1338,11 @@ setInterval(() => console.log("Hi"), 1000);
A - رقم فريد أو متفرد id + + + B - قيمة محددة لل milliseconds -B - قيمة محددة لل milliseconds - -C - الدالة التي تم تمريرها + C - الدالة التي تم تمريرها `undefined` - D @@ -1382,15 +1353,14 @@ C - الدالة التي تم تمريرها
الجواب هو الخيار الأول: A -تقوم بإرجاع ال id الفريد, هذا الid يمكن استخدامه لكي يقوم بتصفير عداد الفترات المفصلة أي الinterval عن طريق استخدام الدالة `clearInterval()` - +تقوم بإرجاع ال id الفريد, هذا الid يمكن استخدامه لكي يقوم بتصفير عداد الفترات المفصلة أي الinterval عن طريق استخدام الدالة `clearInterval()`

--- -43. مالذي يتم ارجاعه بعد تنفيذ الكود أدناه؟ +43. مالذي يتم ارجاعه بعد تنفيذ الكود أدناه؟ ```javascript [..."Lydia"]; @@ -1407,7 +1377,6 @@ C - الدالة التي تم تمريرها الجواب هو الخيار الأول: A الstring هي تكرارية, و عملية الspread (...) تقوم بتحويل اي حرف تم فيه تنفيذ فئة تكرارية الى عنصر منفرد واحد. -

@@ -1438,12 +1407,11 @@ console.log(gen.next().value);
الجواب هو الخيار الثالث: C -الدوال العادية ليس بإمكانها ان تتوقف في وسط التنفيذ بعد أن يتم مناداتها, و لكن الدوال من نوع generator من الممكن أن يتم ايقافها وسط التنفيذ, و لاحقا يتم مواصلة تنفيذها من حيث المكان الذي توقفت به. في كل مرة تواجه فيها الدالة من نوع generator الكلمة المفتاحية `yield`, فإن الدالة تخضع أو تستسلم للقيمة المحددة بعدها. مع ملاحظة أن الدالة من نوع generator في هذه الحالة, لاتقوم بإرجاع القيمة, بل تخضع لتلك القيمة. +الدوال العادية ليس بإمكانها ان تتوقف في وسط التنفيذ بعد أن يتم مناداتها, و لكن الدوال من نوع generator من الممكن أن يتم ايقافها وسط التنفيذ, و لاحقا يتم مواصلة تنفيذها من حيث المكان الذي توقفت به. في كل مرة تواجه فيها الدالة من نوع generator الكلمة المفتاحية `yield`, فإن الدالة تخضع أو تستسلم للقيمة المحددة بعدها. مع ملاحظة أن الدالة من نوع generator في هذه الحالة, لاتقوم بإرجاع القيمة, بل تخضع لتلك القيمة. أولا, نقوم بإنشاء الدالة من نوع generator مع وجود المتغير `i` مساوي ل `10`. نقوم بمناداة الدالةمن نوع generator باستخدام الدالة `next()`. في المرة الأولى التي ننادي فيها الدالة من نوع generator, فإن ال `i` تساوي `10`. هي تواجه الكلمة المفتاحية `yield`, فتخضع لقيمة ال `i`. الدالة generator في هذه اللحظة تم توقيفها مؤقتا, و القيمة `10` تم طباعتها عن طريق log. -اذاً, نقوم بمناداة الدالة مرة أخرى عن طريق الدالة `next()`, هي تبدأ لتواصل من المكان الذي تم توقفيها فيه مؤقتا سابقاً, و ماتزال قيمة `i` تساوي `10`. الآن هي تواجه الكلمة المفتاحية `yield` التالية, و تواجه `i * 2`. `i` تساوي `10`,لهذا تقوم بإرجاع `10 * 2` و التي هي تساوي `20`, و هذا سيوصلنا للنتيجة `10, 20`. - +اذاً, نقوم بمناداة الدالة مرة أخرى عن طريق الدالة `next()`, هي تبدأ لتواصل من المكان الذي تم توقفيها فيه مؤقتا سابقاً, و ماتزال قيمة `i` تساوي `10`. الآن هي تواجه الكلمة المفتاحية `yield` التالية, و تواجه `i * 2`. `i` تساوي `10`,لهذا تقوم بإرجاع `10 * 2` و التي هي تساوي `20`, و هذا سيوصلنا للنتيجة `10, 20`.

@@ -1461,7 +1429,7 @@ const secondPromise = new Promise((res, rej) => { setTimeout(res, 100, "two"); }); -Promise.race([firstPromise, secondPromise]).then((res) => console.log(res)); +Promise.race([firstPromise, secondPromise]).then(res => console.log(res)); ``` - A: `"one"` @@ -1474,8 +1442,7 @@ Promise.race([firstPromise, secondPromise]).then((res) => console.log(res));
الجواب هو الخيار الثاني: B -عندما نقوم بتمرير عدد من الpromises للدالة `Promise.race`. فهي تقوم برفض أو فصل الpromise الاولى. للدالة `setTimeout` نحن نقوم بتمرير timer: 500ms لل promise الأولى و التي هي (`firstPromise`), و 100ms اي 100ملي ثانية للpromise الثانية والتي هي (`secondPromise`) هذا يعني ان ال `secondPromise` يتم فصلها اولاً مع القيمة `'two'`. `res` الآن تحمل قيمة `'two'`, وهي التي تم طباعتها عن طريق الlog. - +عندما نقوم بتمرير عدد من الpromises للدالة `Promise.race`. فهي تقوم برفض أو فصل الpromise الاولى. للدالة `setTimeout` نحن نقوم بتمرير timer: 500ms لل promise الأولى و التي هي (`firstPromise`), و 100ms اي 100ملي ثانية للpromise الثانية والتي هي (`secondPromise`) هذا يعني ان ال `secondPromise` يتم فصلها اولاً مع القيمة `'two'`. `res` الآن تحمل قيمة `'two'`, وهي التي تم طباعتها عن طريق الlog.

@@ -1502,7 +1469,7 @@ console.log(members);
الجواب هو الخيار الرابع: D -أولا, نقوم بتعريف المتغير `person` مع قيمة عبارة عن object لديه الخاصية `name`. +أولا, نقوم بتعريف المتغير `person` مع قيمة عبارة عن object لديه الخاصية `name`. @@ -1511,12 +1478,11 @@ console.log(members); -ثم , نقوم بضبط قمية المتغير `person` بقيمة تساوي `null`. +ثم , نقوم بضبط قمية المتغير `person` بقيمة تساوي `null`. -نحن فقط نقوم بتعديل قيمة المتغير `person`, وليس أول عنصر في ال array, بما أن ذلك العنصر لديه refrence منسوخ من ال object. أول عنصر في `members` لا يزال لديه refrence للobject الأصلي. و عندما نقوم بطباع الarray `members` عن طريق الlog, فإن العنصر الأول لايزال يحمل قيمة الobject, و التي سيتم طباعتها عن طريق log. - +نحن فقط نقوم بتعديل قيمة المتغير `person`, وليس أول عنصر في ال array, بما أن ذلك العنصر لديه refrence منسوخ من ال object. أول عنصر في `members` لا يزال لديه refrence للobject الأصلي. و عندما نقوم بطباع الarray `members` عن طريق الlog, فإن العنصر الأول لايزال يحمل قيمة الobject, و التي سيتم طباعتها عن طريق log.

@@ -1528,7 +1494,7 @@ console.log(members); ```javascript const person = { name: "Lydia", - age: 21, + age: 21 }; for (const item in person) { @@ -1546,8 +1512,7 @@ for (const item in person) {
الجواب هو الخيار الثاني: B -بإستخدام `for-in` التكرارية, بامكاننا أن نصل الى جميع المفاتيح التي تخص object معين. في هذه الحالة `name` و `age`. ماوراء الكواليس, مفاتيح ال objects هي عبارة عن strings (إذا لم تكن هذه المفاتيح عبارة عن symbol), في أي حلقة من الحلقات التكرارية, نقوم بضبط القيمة `item`مساوية للمفتاح الحالي الذي هي تتكرر فيه اوعنده. أولا `item` تساوي `name`, و يتم طباعتها عن طريق الlog, ثم `item` تساوي `age` و التي ايضا تم طباعتها عن طريق الlog. - +بإستخدام `for-in` التكرارية, بامكاننا أن نصل الى جميع المفاتيح التي تخص object معين. في هذه الحالة `name` و `age`. ماوراء الكواليس, مفاتيح ال objects هي عبارة عن strings (إذا لم تكن هذه المفاتيح عبارة عن symbol), في أي حلقة من الحلقات التكرارية, نقوم بضبط القيمة `item`مساوية للمفتاح الحالي الذي هي تتكرر فيه اوعنده. أولا `item` تساوي `name`, و يتم طباعتها عن طريق الlog, ثم `item` تساوي `age` و التي ايضا تم طباعتها عن طريق الlog.

@@ -1570,12 +1535,11 @@ console.log(3 + 4 + "5");
الجواب هو الخيار الثاني: B -Operator associativity او ترابطية العامل هي الترتيب أو التسلسل الذي يقيم به الcompiler ال expressions, ف هو إما أن يكون من اليسار الى اليمين أو من اليمين الى اليسار. هذا يحدث فقط إذا كان جميع الoperators لديها نفس الأسبقية. لدينا فقط نوع واحد من الoperator ألا و هو `+`. بالإضافة الى التالي, الترابطية هي من اليسار الى اليمين. +Operator associativity او ترابطية العامل هي الترتيب أو التسلسل الذي يقيم به الcompiler ال expressions, ف هو إما أن يكون من اليسار الى اليمين أو من اليمين الى اليسار. هذا يحدث فقط إذا كان جميع الoperators لديها نفس الأسبقية. لدينا فقط نوع واحد من الoperator ألا و هو `+`. بالإضافة الى التالي, الترابطية هي من اليسار الى اليمين. `3 + 4` يتم تقييمها أولا. هذا مايعطينا الناتج الذي هو عبارة عن الرقم `7`. -`7 + '5'` تقوم بإرجاع الناتج `"75"` بسبب عملية ال coercion وهي العمليةالتي تقوم بالتحويل من نوع الى آخر, لغة الجافاسكريبت تقوم بتحويل الرقم `7` الى النوع string, أنظرالى السؤال رقم 15 في الأعلى. بإمكاننا عمل concatenate لمتغيرين من النوع string بإستخدام العملية `+`. `"7" + "5"` سترجع الناتج `"75"`. - +`7 + '5'` تقوم بإرجاع الناتج `"75"` بسبب عملية ال coercion وهي العمليةالتي تقوم بالتحويل من نوع الى آخر, لغة الجافاسكريبت تقوم بتحويل الرقم `7` الى النوع string, أنظرالى السؤال رقم 15 في الأعلى. بإمكاننا عمل concatenate لمتغيرين من النوع string بإستخدام العملية `+`. `"7" + "5"` سترجع الناتج `"75"`.

@@ -1600,10 +1564,9 @@ const num = parseInt("7*6", 10);
الجواب هو الخيار الثالث: C -فقط الأرقام الأولى في الstring يتم إرجاعها. بناءاً على _radix_ (الargument الثاني لكي يتم تحديدنوعية الرقم الذي نود أن نقوم بعمل parse له الى: base 10, hexadecimal, octal, binary, الخ. ). تقوم `parseInt` بالتحقق عن إذا ماكانت الحروف في الstring صالحة. و بمجرد أن تجد حرف غير صالح في ال radix, ف هي تقوم بإيقاف عملية الparsing مباشرة و تتجاهل الحروف التي تليه. - -`*` ليست رقم صالح. هي فقط تقوم بعمل parse ل `"7"` الى عدد عشري `7`. `num` الآن تحمل القيمة `7`. +فقط الأرقام الأولى في الstring يتم إرجاعها. بناءاً على _radix_ (الargument الثاني لكي يتم تحديدنوعية الرقم الذي نود أن نقوم بعمل parse له الى: base 10, hexadecimal, octal, binary, الخ. ). تقوم `parseInt` بالتحقق عن إذا ماكانت الحروف في الstring صالحة. و بمجرد أن تجد حرف غير صالح في ال radix, ف هي تقوم بإيقاف عملية الparsing مباشرة و تتجاهل الحروف التي تليه. +`*` ليست رقم صالح. هي فقط تقوم بعمل parse ل `"7"` الى عدد عشري `7`. `num` الآن تحمل القيمة `7`.

@@ -1613,7 +1576,7 @@ const num = parseInt("7*6", 10); 50. ماهو الناتج؟ ```javascript -[1, 2, 3].map((num) => { +[1, 2, 3].map(num => { if (typeof num === "number") return; return num * 2; }); @@ -1629,10 +1592,9 @@ const num = parseInt("7*6", 10);
الجواب هو الخيار الثالث: C -عندما يتم عمل mapping لل array, فإن قيمة `num` ستساوي قيمة العنصر الذي يتم حاليا المرور به, فكما نعرف أن الmapping يدور على جميع عناصر الarray. في هذه الحالة, العناصر عبارة عن أرقام, لهذا فإن شرط ال if statement `typeof num === "number"` يقوم بإرجاع `true`. دالة map تقوم بإنشاء array جديدة, و إدخال القيم المرجعة من الدالة في هذه الarray. - -ولكن, لا نقوم بإرجاع قيمة. عندما لا نقوم بإرجاع قيمة من الدالة, فإن الدالة تقوم بإرجاع `undefined`. لكل عنصرٍ في الarray, فإن نطاق الدالة او نعني الfunction block يتم مناداته, لهذا لأي عنصر نقوم بإرجاع `undefined`. +عندما يتم عمل mapping لل array, فإن قيمة `num` ستساوي قيمة العنصر الذي يتم حاليا المرور به, فكما نعرف أن الmapping يدور على جميع عناصر الarray. في هذه الحالة, العناصر عبارة عن أرقام, لهذا فإن شرط ال if statement `typeof num === "number"` يقوم بإرجاع `true`. دالة map تقوم بإنشاء array جديدة, و إدخال القيم المرجعة من الدالة في هذه الarray. +ولكن, لا نقوم بإرجاع قيمة. عندما لا نقوم بإرجاع قيمة من الدالة, فإن الدالة تقوم بإرجاع `undefined`. لكل عنصرٍ في الarray, فإن نطاق الدالة او نعني الfunction block يتم مناداته, لهذا لأي عنصر نقوم بإرجاع `undefined`.

@@ -1669,8 +1631,7 @@ console.log(person, birthYear); المتغير `birthYear` لديه refrence للقيمة `"1997"`. الargument `year` أيضا لديه refrence للقيمة `"1997"`, لكنها ليست نفس القيمة التي `birthYear` لديها refrence لها. عندما نقوم بتحديث قيمة `year` عن طريق ضبط `year` تساوي ل `"1998"`, نحن فقط نقوم بتحديث قيمة `year`. `birthYear` لا تزال تساوي `"1997"`. -قيمة `person` هي object. الargument `member` لديه نسخة refrence لنفس الobject. عندما نقوم بتعديل او تحديث خاصية للobject `member`و الذي لديه refrence لها, فإن قيمة `person` ستتعدل و تتغير أيضا,بما أن كلاهما لديهما refrence لنفس الobject. الخصائص `person` و `name` هما الأىن مساويان للقيمة `"Lydia"`. - +قيمة `person` هي object. الargument `member` لديه نسخة refrence لنفس الobject. عندما نقوم بتعديل او تحديث خاصية للobject `member`و الذي لديه refrence لها, فإن قيمة `person` ستتعدل و تتغير أيضا,بما أن كلاهما لديهما refrence لنفس الobject. الخصائص `person` و `name` هما الأىن مساويان للقيمة `"Lydia"`.

@@ -1706,17 +1667,16 @@ sayHi();
الجواب هو الخيار الرابع: D -مع عبارة `throw` , بإمكاننا إنشاء errors حسب الطلب, أي ليست كا الإخطاء العامة في اللغة, بإستخدام هذه العبارة بإمكانك أن تضع exception, الexception يمكن أن يكون : string, number, boolean أو object. في هذه الحالة, الexcption لدينا هو ال string `'Hello world'`. - -مع عبارة `catch`, بإمكاننا ان نحدد ما الذي يتوجب فعله عندما يتم وضع أو إلقاء الexception في نطاق ال `try`. تم إلقاء أو وضع exception: الstring `'Hello world'`. `e` الآن تساوي تلك الstring,log. هذا سيعطينا النتيجة `'Oh an error: Hello world'`. +مع عبارة `throw` , بإمكاننا إنشاء errors حسب الطلب, أي ليست كا الإخطاء العامة في اللغة, بإستخدام هذه العبارة بإمكانك أن تضع exception, الexception يمكن أن يكون : string, number, boolean أو object. في هذه الحالة, الexcption لدينا هو ال string `'Hello world'`. +مع عبارة `catch`, بإمكاننا ان نحدد ما الذي يتوجب فعله عندما يتم وضع أو إلقاء الexception في نطاق ال `try`. تم إلقاء أو وضع exception: الstring `'Hello world'`. `e` الآن تساوي تلك الstring,log. هذا سيعطينا النتيجة `'Oh an error: Hello world'`.

--- -53. ماهو الناتج؟ +53. ماهو الناتج؟ ```javascript function Car() { @@ -1738,8 +1698,7 @@ console.log(myCar.make);
الجواب هو الخيار الثاني: B -عندما تقوم بإرجاع خاصية, فإن قيمة هذه الخاصية هي تساوي القيمة المرجعة, ليس القيمة التي تم ضبطها في دالة الconstructor. نقوم بإرجاع ال string `"Maserati"`, لذا فإن `myCar.make` تساوي `"Maserati"`. - +عندما تقوم بإرجاع خاصية, فإن قيمة هذه الخاصية هي تساوي القيمة المرجعة, ليس القيمة التي تم ضبطها في دالة الconstructor. نقوم بإرجاع ال string `"Maserati"`, لذا فإن `myCar.make` تساوي `"Maserati"`.

@@ -1767,8 +1726,7 @@ console.log(typeof y);
الجواب هو الخيار الأول : A -`let x = y = 10;` هي في الحقيقة إختصار ل: - +`let x = y = 10;` هي في الحقيقة إختصار ل:
```javascript @@ -1778,12 +1736,11 @@ let x = y;
-عندما نقوم بضبط قيمة`y` لكي تساوي `10`, فنحن فعليا نقوم بإضافة الخاصية `y` للglobal object. (`window` في المتصفح, `global` في Node). في المتصفح, `window.y` الآن تساوي `10`. +عندما نقوم بضبط قيمة`y` لكي تساوي `10`, فنحن فعليا نقوم بإضافة الخاصية `y` للglobal object. (`window` في المتصفح, `global` في Node). في المتصفح, `window.y` الآن تساوي `10`. ثم, عندما نقوم بتعريف المتغير `x` بالقيمة `y` و التي هي في الحقيقة تساوي `10`. المتغيرات التي يتم تعريفها بالكلمة المفتاحية `let`هي متغيرات block scoped, أي يتم التعامل معها في النطاق الذي تم تعريفها فيه فقط, الدالة المناداة حاليا في هذه الحالة أي immediately-invoked function (IIFE). عندما نقوم بإستخدام العملية `typeof`, فإن المعامل `x` ليس معرف, نحن نحاول الوصول الى `x` خارج النطاق الذي تم تعريفه بها. هذا يعني أن `x` ليست معرفة. المتغيرات التي لم يتم وضع قيمة لها أو لم يتم تعريفها هي من النوع `"undefined"`. `console.log(typeof x)` تقوم بإرجاع `"undefined"`. -ولكن, نحن قمنا بإنشاء و تعريف global variable `y` عندما قمنا بضبط قيمة `y` لتساوي `10`. هذه القيمة يمكن الوصول إليها من أي مكان في البرنامج. `y` هي معرفة, و لديها قيمة من النوع `"number"`. `console.log(typeof y)` تقوم بإرجاع `"number"`. - +ولكن, نحن قمنا بإنشاء و تعريف global variable `y` عندما قمنا بضبط قيمة `y` لتساوي `10`. هذه القيمة يمكن الوصول إليها من أي مكان في البرنامج. `y` هي معرفة, و لديها قيمة من النوع `"number"`. `console.log(typeof y)` تقوم بإرجاع `"number"`.

@@ -1799,7 +1756,7 @@ class Dog { } } -Dog.prototype.bark = function () { +Dog.prototype.bark = function() { console.log(`Woof I am ${this.name}`); }; @@ -1822,10 +1779,9 @@ pet.bark();
الجواب هو الخيار الأول: A -بإمكاننا مسح خصائص object معين عن طريق استخدام الكلمة المفتاحية `delete`, أيضا يمكن فعل هذا في ال prototype. بمسح خاصية معينة من الprototype, فهي سيتم مسحها وبالتالي لن تكون موجودة في سلسلة الprototype. في هذه الحالة فإن الدالة `bark` لن تكون موجودة بعد الآن في الprototype بعد `delete Dog.prototype.bark`, ولكن بالرغم من هذا فنحن نحاول الوصول إليها. - -عندما نحاول أن ننادي شيئا ما في دالة و هو ليس موجود في هذه الدالة, فإننا سنتحصل على الخطأ `TypeError`, و في هذه الحالة `TypeError: pet.bark is not a function` بما أن `pet.bark` هي `undefined`. +بإمكاننا مسح خصائص object معين عن طريق استخدام الكلمة المفتاحية `delete`, أيضا يمكن فعل هذا في ال prototype. بمسح خاصية معينة من الprototype, فهي سيتم مسحها وبالتالي لن تكون موجودة في سلسلة الprototype. في هذه الحالة فإن الدالة `bark` لن تكون موجودة بعد الآن في الprototype بعد `delete Dog.prototype.bark`, ولكن بالرغم من هذا فنحن نحاول الوصول إليها. +عندما نحاول أن ننادي شيئا ما في دالة و هو ليس موجود في هذه الدالة, فإننا سنتحصل على الخطأ `TypeError`, و في هذه الحالة `TypeError: pet.bark is not a function` بما أن `pet.bark` هي `undefined`.

@@ -1850,10 +1806,9 @@ console.log(set);
الجواب هو الخيار الرابع: D -ال object `Set` هو مجموعة من القيم الفريدة, أي القيمة بإمكانها أن تتواجد مرة واحدة فقط في المجموعة. - -نقوم بتمرير التكراري أي نعني الiterable `[1, 1, 2, 3, 4]` بوجود قيمة مكررة ألا وهي `1` . بما أننا لا يمكن أن نضع قيمة واحدة مرتين في مجموعة, فإن واحدة من القيم المكررة سيتم إزالتها, و سيكون الناتج: `{1, 2, 3, 4}`. +ال object `Set` هو مجموعة من القيم الفريدة, أي القيمة بإمكانها أن تتواجد مرة واحدة فقط في المجموعة. +نقوم بتمرير التكراري أي نعني الiterable `[1, 1, 2, 3, 4]` بوجود قيمة مكررة ألا وهي `1` . بما أننا لا يمكن أن نضع قيمة واحدة مرتين في مجموعة, فإن واحدة من القيم المكررة سيتم إزالتها, و سيكون الناتج: `{1, 2, 3, 4}`.

@@ -1889,8 +1844,7 @@ console.log(myCounter); هنا يوجد لدينا module مستورد وهو قابل للقراءة فقط, ليس بإمكانك تعديل او تحديث الmodule المستورد, أي imported module. فقط الmodule الذي قام بتصديره هو القادر على تغيير قيمته. -عندما نحاول أن نزيد قيمة المتغير `myCounter`, سنتحصل على الخطأ `myCounter` هو قابل للقراءة فقط و ليس من الممكن تعديله. - +عندما نحاول أن نزيد قيمة المتغير `myCounter`, سنتحصل على الخطأ `myCounter` هو قابل للقراءة فقط و ليس من الممكن تعديله.

@@ -1917,10 +1871,9 @@ console.log(delete age);
الجواب هو الخيار الأول: A -العامل `delete` تقوم بإرجاع قيمة boolen و هي `true` عندما تتم عملية المسح بنجاح, خلاف ذلك ستقوم بإرجاع `false`, ولكن المتغيرات المعرفة بالكلمات المفتاحية `var`, `const` أو `let` ليس بالإمكان مسحها بإستخدام العامل `delete`. - -المتغير `name` تم تعريفه باستخدام الكلمة المفتاحية `const`, لهذا فإن عملية مسحه لم تتم بنجاح, وتم إرجاع القيمة `false`, عندما نقوم بضبط المتغير `age` ليساوي القيمة `21` فإننا فعليا نقوم بإضافة خاصية تسمى `age` للglobal object. بإمكانك أن تمسح خصائص من الobjects بنجاح بإستخدام هذه الطريقة , أيضا الglobal objects, لذا فإن `delete age` تقوم بإرجاع `true`. +العامل `delete` تقوم بإرجاع قيمة boolen و هي `true` عندما تتم عملية المسح بنجاح, خلاف ذلك ستقوم بإرجاع `false`, ولكن المتغيرات المعرفة بالكلمات المفتاحية `var`, `const` أو `let` ليس بالإمكان مسحها بإستخدام العامل `delete`. +المتغير `name` تم تعريفه باستخدام الكلمة المفتاحية `const`, لهذا فإن عملية مسحه لم تتم بنجاح, وتم إرجاع القيمة `false`, عندما نقوم بضبط المتغير `age` ليساوي القيمة `21` فإننا فعليا نقوم بإضافة خاصية تسمى `age` للglobal object. بإمكانك أن تمسح خصائص من الobjects بنجاح بإستخدام هذه الطريقة , أيضا الglobal objects, لذا فإن `delete age` تقوم بإرجاع `true`.

@@ -1945,8 +1898,7 @@ console.log(y);
الجواب هو الخيار الثالث: C -بإمكاننا إستخراج أو استخلاص القيم من arrays أو من objects عن طريق إستخدام الdestructing, على سبيل المثال: - +بإمكاننا إستخراج أو استخلاص القيم من arrays أو من objects عن طريق إستخدام الdestructing, على سبيل المثال:
```javascript @@ -1956,8 +1908,7 @@ console.log(y);
-قيمة `a` الآن تساوي `1`, و قيمة `b` الآن تساوي `2`. ماقمنا بفعله حقاً في هذا السؤال هو: - +قيمة `a` الآن تساوي `1`, و قيمة `b` الآن تساوي `2`. ماقمنا بفعله حقاً في هذا السؤال هو:
```javascript @@ -1967,8 +1918,7 @@ console.log(y);
-هذا يعني أن قيمة `y` هي مساوية للقيمة الأولى في الarray, والتي هي عبارة عن نوع رقم يساوي `1`, عندما نقوم بطباعة `y` عن طريق الlog, فإن القيمة `1` هي التي يتم إرجاعها. - +هذا يعني أن قيمة `y` هي مساوية للقيمة الأولى في الarray, والتي هي عبارة عن نوع رقم يساوي `1`, عندما نقوم بطباعة `y` عن طريق الlog, فإن القيمة `1` هي التي يتم إرجاعها.

@@ -1994,8 +1944,7 @@ console.log(admin);
الجواب هو الخيار الثاني: B -من الممكن دمج الobjects بإستخدام العامل spread `...`. هي تمكنك من إنشاء نسخ من أزواج ال key/value أي أزواج المفاتيح و القيم التي تنتمي الى object معين, و إضافتهم الى object آخر. في هذه الحالة, نحن نقوم بعمل نسخ من الobject `user`, و من ثم إضافتهم الى ال obejct `admin`. ال object `admin` الآن يتضمن نسخ عبارة عن أزواج مفاتيح و قيم, و هذا ما سبب في إعطاء النتيجة `{ admin: true, name: "Lydia", age: 21 }`. - +من الممكن دمج الobjects بإستخدام العامل spread `...`. هي تمكنك من إنشاء نسخ من أزواج ال key/value أي أزواج المفاتيح و القيم التي تنتمي الى object معين, و إضافتهم الى object آخر. في هذه الحالة, نحن نقوم بعمل نسخ من الobject `user`, و من ثم إضافتهم الى ال obejct `admin`. ال object `admin` الآن يتضمن نسخ عبارة عن أزواج مفاتيح و قيم, و هذا ما سبب في إعطاء النتيجة `{ admin: true, name: "Lydia", age: 21 }`.

@@ -2023,10 +1972,9 @@ console.log(Object.keys(person));
الجواب هو الخيار الثاني: B -مع إستخدام `defineProperty` method, بإمكاننا إضافة خصائص جديدة لobject معين,أو تعديل خصائصه الحالية,. عندما نقوم بإضافة خاصية لobject بإستخدام `defineProperty` method, ف هي بطبيعة الحال ليست enumerable. ال `Object.keys` method تقوم بإرجاع جميع أسامي الخصائص من object معين و التي هي جميعها enumerable, في هذه الحالة `"name"` فقط. - -الخصائص التي تم إضافتها بإستخدام `defineProperty` method هي بطبيعة الحال غير قابلة للتغيير أو التعديل. بإمكانك عمل override بإستخدام الخصائص `writable`, `configurable` و `enumerable`. بهذه الطريقة, ال `defineProperty` method ستعطيك تحكم أكثر بكثير على الخصائص التي قمت بإضافتها الى object معين. +مع إستخدام `defineProperty` method, بإمكاننا إضافة خصائص جديدة لobject معين,أو تعديل خصائصه الحالية,. عندما نقوم بإضافة خاصية لobject بإستخدام `defineProperty` method, ف هي بطبيعة الحال ليست enumerable. ال `Object.keys` method تقوم بإرجاع جميع أسامي الخصائص من object معين و التي هي جميعها enumerable, في هذه الحالة `"name"` فقط. +الخصائص التي تم إضافتها بإستخدام `defineProperty` method هي بطبيعة الحال غير قابلة للتغيير أو التعديل. بإمكانك عمل override بإستخدام الخصائص `writable`, `configurable` و `enumerable`. بهذه الطريقة, ال `defineProperty` method ستعطيك تحكم أكثر بكثير على الخصائص التي قمت بإضافتها الى object معين.

@@ -2039,7 +1987,7 @@ console.log(Object.keys(person)); const settings = { username: "lydiahallie", level: 19, - health: 90, + health: 90 }; const data = JSON.stringify(settings, ["level", "health"]); @@ -2056,12 +2004,11 @@ console.log(data);
الجواب هو الخيار الأول : A -ال argument الثاني من `JSON.stringify` هو replacer أي حالٍ محل شيء آخر, الreplacer إما أن يكون دالة أو يكون array, و سيمكنك من التحكم في كيفية و ماهية امكانية عمل stringified للقيم, أي تحويلها الى string. +ال argument الثاني من `JSON.stringify` هو replacer أي حالٍ محل شيء آخر, الreplacer إما أن يكون دالة أو يكون array, و سيمكنك من التحكم في كيفية و ماهية امكانية عمل stringified للقيم, أي تحويلها الى string. -إذا كان الreplacer هو عبارة عن array, فإن الخصائص التي أساميها مضمنة في الarray هي فقط التي يمكن إضافتها الى ال JSON string. في هذه الحالة, الخصائص التي تحمل الأسامي `"level"` و `"health"` فقط هي المضمنة, `"username"` غير مضمنة. `data` الآن تساوي `"{"level":19, "health":90}"`. - -إذا كان الreplacer عبارة عن دالة, فإن هذه الدالة يتم مناداتها عند أي خاصية في الobject أنت تقوم بعمل stringifying لها.القيمة المرجعة من هذه الدالة ستكون قيمة الخاصية عندما تم إضافتها ل JSON string. إذا كانت القيمة `undefined`, فإن هذه الخاصية سيتم إستبعادها من الJSON string. +إذا كان الreplacer هو عبارة عن array, فإن الخصائص التي أساميها مضمنة في الarray هي فقط التي يمكن إضافتها الى ال JSON string. في هذه الحالة, الخصائص التي تحمل الأسامي `"level"` و `"health"` فقط هي المضمنة, `"username"` غير مضمنة. `data` الآن تساوي `"{"level":19, "health":90}"`. +إذا كان الreplacer عبارة عن دالة, فإن هذه الدالة يتم مناداتها عند أي خاصية في الobject أنت تقوم بعمل stringifying لها.القيمة المرجعة من هذه الدالة ستكون قيمة الخاصية عندما تم إضافتها ل JSON string. إذا كانت القيمة `undefined`, فإن هذه الخاصية سيتم إستبعادها من الJSON string.

@@ -2074,7 +2021,7 @@ console.log(data); let num = 10; const increaseNumber = () => num++; -const increasePassedNumber = (number) => number++; +const increasePassedNumber = number => number++; const num1 = increaseNumber(); const num2 = increasePassedNumber(num1); @@ -2093,10 +2040,9 @@ console.log(num2);
الجواب هو الخيار الأول : A -العامل الأحادي `++` يقوم أولا بإرجاع قيمة المعامل, ثم يقوم بزيادة قيمة هذا المعامل. قيمة `num1` تساوي `10`, و بما أن دالة `increaseNumber` أولا تقوم بإرجاع قيمة `num` و التي هي تساوي `10`, و تقوم بزيادة قيمة `num` لاحقاً فقط. - -`num2` تساوي`10`, وبما أننا نقوم بتمرير `num1` ل `increasePassedNumber`. فإن `number` تساوي `10` والتي هي قيمة`num1`. مجدداً, العامل الأحادي `++`, أولاً يقوم بإرجاع قيمة المعامل, و من ثم زيادة قيمة المعامل. قيمة `number` تساوي`10`, إذاً `num2` تساوي `10`. +العامل الأحادي `++` يقوم أولا بإرجاع قيمة المعامل, ثم يقوم بزيادة قيمة هذا المعامل. قيمة `num1` تساوي `10`, و بما أن دالة `increaseNumber` أولا تقوم بإرجاع قيمة `num` و التي هي تساوي `10`, و تقوم بزيادة قيمة `num` لاحقاً فقط. +`num2` تساوي`10`, وبما أننا نقوم بتمرير `num1` ل `increasePassedNumber`. فإن `number` تساوي `10` والتي هي قيمة`num1`. مجدداً, العامل الأحادي `++`, أولاً يقوم بإرجاع قيمة المعامل, و من ثم زيادة قيمة المعامل. قيمة `number` تساوي`10`, إذاً `num2` تساوي `10`.

diff --git a/bs-BS/README-bs_BS.md b/bs-BS/README-bs_BS.md index 2ff41568..65ee11f7 100644 --- a/bs-BS/README-bs_BS.md +++ b/bs-BS/README-bs_BS.md @@ -1,9 +1,8 @@ # Popis (naprednih) JavaScript pitanja - ======================================= Svakodnevno postavljam JavaScript pitanja s višestrukim izborom na moj -[Instagram](https://www.instagram.com/theavocoder), koja također objavljujem +[Instagram](https://www.instagram.com/theavocoder), koja također objavljujem ovdje! Od osnovnog do naprednog: testirajte koliko dobro znate JavaScript, osvježite svoj @@ -26,7 +25,6 @@ kliknite na njih da biste ih proširili. Sretno :heart: - [🇳🇱 Nederlands](../nl-NL/README.md) - [🇵🇱 Polski](../pl-PL/README.md) - [🇧🇷 Português Brasil](../pt-BR/README_pt_BR.md) -- [🇷o Română](../ro-RO/README.ro.md) - [🇷🇺 Русский](../ru-RU/README.md) - [🇽🇰 Shqip](../sq-KS/README_sq_KS.md) - [🇹🇭 ไทย](../th-TH/README-th_TH.md) @@ -36,7 +34,7 @@ kliknite na njih da biste ih proširili. Sretno :heart: - [🇨🇳 简体中文](../zh-CN/README-zh_CN.md) - [🇹🇼 繁體中文](../zh-TW/README_zh-TW.md) ---- +* * * * * ###### 1. Što je izlaz? @@ -77,7 +75,7 @@ JavaScript izbacuje `ReferenceError`.

---- +* * * * * ###### 2. Što je izlaz? @@ -101,7 +99,7 @@ for (let i = 0; i < 3; i++) { #### Odgovor: C Zbog reda događaja u JavaScriptu, povratni poziv `setTimeout` -function se zove \* nakon što je izvršena petlja. Od +function se zove * nakon što je izvršena petlja. Od varijabla `i` u prvoj petlji je deklarirana pomoću ključne riječi` var`, ta je vrijednost bila globalna. Tijekom petlje povećavamo vrijednost `i` svaki put '1', koristeći unarni operator `++`. Do vremena @@ -116,7 +114,7 @@ block-scoped (blok je sve između `{}`). Tijekom svake iteracije,

---- +* * * * * ###### 3. Što je izlaz? @@ -126,7 +124,7 @@ const shape = { diameter() { return this.radius * 2; }, - perimeter: () => 2 * Math.PI * this.radius, + perimeter: () => 2 * Math.PI * this.radius }; shape.diameter(); @@ -156,7 +154,7 @@ Na tom objektu nema vrijednosti `radius` koja vraća` undefined`.

---- +* * * * * ###### 4. Što je izlaz? @@ -183,18 +181,18 @@ Niz '' Lydia '' je istinita vrijednost. Ono što zapravo tražimo jest

---- +* * * * * ###### 5. Koja je istina? ```javascript const bird = { - size: "small", + size: "small" }; const mouse = { name: "Mickey", - small: true, + small: true }; ``` @@ -209,7 +207,7 @@ const mouse = { #### Odgovor: A U JavaScriptu su svi key-evi objekta stringovi (osim ako to nije simbol). Čak -iako ih možda ne _ upisujemo kao _ nizove, oni se uvijek pretvaraju +iako ih možda ne * upisujemo kao * nizove, oni se uvijek pretvaraju u String ispod "haube". JavaScript tumači (ili odlaže) izjave. Kada koristimo zagradu @@ -230,7 +228,8 @@ To nije valjano, a bit će u pitanju pogreška slična onoj

---- +* * * * * + ###### 6. Što je izlaz? @@ -254,7 +253,7 @@ console.log(d.greeting); #### Odgovor: A -U JavaScriptu, svi objekti međusobno djeluju _referencom_ kada ih postavljaju +U JavaScriptu, svi objekti međusobno djeluju *referencom* kada ih postavljaju jednaki. Prvo, varijabla `c` sadrži vrijednost objekta. Kasnije dodijelimo `d` @@ -267,7 +266,7 @@ Kada promijenite jedan objekt, mijenjate ih sve.

---- +* * * * * ###### 7. Što je izlaz? @@ -281,10 +280,10 @@ console.log(a === b); console.log(b === c); ``` -- A: ` true`` false ` `true` -- B: ` false`` false ` `true` -- C: ` true`` false ` `false` -- D: ` false`` true ` `true` +- A: `true`` false` `true` +- B: `false`` false` `true` +- C: `true`` false` `false` +- D: `false`` true` `true`
Odgovor

@@ -296,16 +295,16 @@ kao broj, to zapravo nije broj: ima gomilu ekstra dodataka pa je zbog toga objekt. Kada koristimo `==` operator, on samo provjerava ima li isti -_vrijednost_. Obje imaju vrijednost `3`, pa se vraća 'true'. +*vrijednost*. Obje imaju vrijednost `3`, pa se vraća 'true'. -Međutim, kada koristimo `===` operator, obje vrijednosti _ i _ trebaju biti +Međutim, kada koristimo `===` operator, obje vrijednosti * i * trebaju biti iste. To nije: `new Number ()` nije broj, to je ** objekt **. Oba vraćaju "false"

---- +* * * * * ###### 8. Što je izlaz? @@ -336,7 +335,7 @@ freddie.colorChange("orange"); #### Odgovor: D function `colorChange` je statična. Namijenjene su statičkim metodama -žive samo na konstruktoru u kojem su stvoreni i ne mogu biti proslijeđeni +žive samo na konstruktoru u kojem su stvoreni i ne mogu biti proslijeđeni bilo kojem childu. Budući da je `freddie` child, function je nije proslijeđena, i nije dostupan na `freddie` instanci: a Izbačen je `TypeError`. @@ -344,7 +343,7 @@ Izbačen je `TypeError`.

---- +* * * * * ###### 9. Što je izlaz? @@ -352,6 +351,7 @@ Izbačen je `TypeError`. let greeting; greetign = {}; // Typo! console.log(greetign); + ``` - A: `{}` @@ -374,7 +374,7 @@ da ste deklarirali varijablu prije nego je postavite na bilo što.

---- +* * * * * ###### 10. Što se događa kada učinimo ovo? @@ -406,7 +406,7 @@ Ova nekretnina je nepovratna.

---- +* * * * * ###### 11. Kakav je rezultat? @@ -417,7 +417,7 @@ function Person(firstName, lastName) { } const member = new Person("Lydia", "Hallie"); -Person.getFullName = function () { +Person.getFullName = function() { return `${this.firstName} ${this.lastName}`; }; @@ -427,7 +427,7 @@ console.log(member.getFullName()); - A: `TypeError` - B: `SyntaxError` - C: "Lydia Hallie" -- D: ` undefined`` undefined ` +- D: `undefined`` undefined`
Odgovor

@@ -454,7 +454,7 @@ scopa za svaku instancu. Umjesto toga, ako ga samo dodamo prototipu, mi

---- +* * * * * ###### 12. Što je izlaz? @@ -473,10 +473,10 @@ console.log(sarah); - A: `Person {ime:" Lydia ", prezime:" Hallie "} i` undefined` - B: `Person {ime:" Lydia ", prezime:" Hallie "} i - `Person {ime:" Sarah ", prezime:" Smith "}` + `Person {ime:" Sarah ", prezime:" Smith "}` - C: `Person {ime:" Lydia ", prezime:" Hallie "}` i `{}` - D: `Person {ime:" Lydia ", prezime:" Hallie "} i - `ReferenceError` + `ReferenceError`
Odgovor

@@ -495,7 +495,7 @@ sam je ostavljen 'undefined'.

---- +* * * * * ###### 13. Koje su tri faze propagiranja događaja? @@ -504,6 +504,7 @@ sam je ostavljen 'undefined'. - C: Target > Bubbling > Capturing - D: Capturing > Target > Bubbling +
Odgovor

@@ -518,11 +519,11 @@ i ** bubbling **.

---- +* * * * * ###### 14. Svi objekti imaju prototipove. -- Istinito +- Istinito - B: lažno
Odgovor @@ -540,7 +541,7 @@ nalazi ga tamo, što ga čini dostupnim.

---- +* * * * * ###### 15. Što je izlaz? @@ -564,20 +565,20 @@ sum(1, "2"); JavaScript je ** dinamički upisani jezik **: ne navodimo što vrste su određene varijable. Vrijednosti se mogu automatski pretvoriti u -drugi tip bez vašeg znanja, koji se zove _ implicitni tip -prisila _. ** Prisila ** pretvara iz jednog tipa u drugi. +drugi tip bez vašeg znanja, koji se zove * implicitni tip +prisila *. ** Prisila ** pretvara iz jednog tipa u drugi. U ovom primjeru JavaScript pretvara broj `1` u niz, u kako bi function imala smisla i vratila vrijednost. Tijekom dodavanje numeričkog tipa (`1`) i tipa niza (` '2'`), broja se tretira kao niz. Možemo slično spojiti -"" Zdravo "+" Svijet "` , tako da se ovdje događa `````````````````` -vraća `" 12 "`. +"" Zdravo "+" Svijet "`, tako da se ovdje događa `````````````````` +vraća `" 12 "`.

---- +* * * * * ###### 16. Što je izlaz? @@ -588,10 +589,10 @@ console.log(++number); console.log(number); ``` -- A: ` 1`` 1 ` `2` -- B: ` 1`` 2 ` `2` -- C: ` 0`` 2 ` `2` -- D: ` 0`` 1 ` `2` +- A: `1`` 1` `2` +- B: `1`` 2` `2` +- C: `0`` 2` `2` +- D: `0`` 1` `2`
Odgovor

@@ -613,7 +614,7 @@ Ovo vraća `0 2 2`.

---- +* * * * * ###### 17. Što je izlaz? @@ -646,7 +647,7 @@ vrijednosti prošlih izraza!

---- +* * * * * ###### 18. Što je izlaz? @@ -673,8 +674,8 @@ checkAge({ age: 18 }); #### Odgovor: C -Prilikom ispitivanja jednakosti, primitivi se uspoređuju prema njihovoj _ vrijednosti _, dok -objekti se uspoređuju prema njihovoj _ referenci _. JavaScript provjerava ako +Prilikom ispitivanja jednakosti, primitivi se uspoređuju prema njihovoj * vrijednosti *, dok +objekti se uspoređuju prema njihovoj * referenci *. JavaScript provjerava ako objekti imaju referencu na isto mjesto u memoriji. Dva predmeta koje uspoređujemo nemaju: objekt mi @@ -687,11 +688,12 @@ Zato i `{age: 18} === {age: 18}` i

---- +* * * * * ###### 19. Što je izlaz? ```javascript + function getAge(...args) { console.log(typeof args); } @@ -715,7 +717,7 @@ array je objekt, pa `typeof args` vraća` `objekt '`

---- +* * * * * ###### 20. Što je izlaz? @@ -739,16 +741,16 @@ getAge(); #### Odgovor: C -Sa `use strict '', možete se uvjeriti da nije slučajno +Sa `` use strict '', možete se uvjeriti da nije slučajno deklarisana globalna varijabla. Nikada nismo objavili varijablu "age" i -budući da koristimo` use strict '', ona će načiniti referentnu pogrešku. Ako mi +budući da koristimo `` use strict '', ona će načiniti referentnu pogrešku. Ako mi nije koristio "" strict ", to bi išlo od vlasništva `age` bi se dodao u globalni objekt.

---- +* * * * * ###### 21. Što je vrijednost `suma '? @@ -773,16 +775,15 @@ kao u ovom slučaju, on ocjenjuje izraz. Izraz je

---- +* * * * * -###### 22. Koliko dugo je cool \ \_secret dostupan? +###### 22. Koliko dugo je cool \ _secret dostupan? ```javascript sessionStorage.setItem("cool_secret", 123); ``` O: Podaci se zauvijek ne gube. - - B: Kada korisnik zatvori karticu. - C: Kada korisnik zatvori cijeli preglednik, ne samo karticu. - D: Kada korisnik isključi svoje računalo. @@ -792,7 +793,7 @@ O: Podaci se zauvijek ne gube. #### Odgovor: B -Podaci spremljeni u `sessionStorage` se uklanjaju nakon zatvaranja _ tab _. +Podaci spremljeni u `sessionStorage` se uklanjaju nakon zatvaranja * tab *. Ako ste koristili `localStorage`, podaci bi bili tamo zauvijek, osim ako na primjer, `localStorage.clear ()` je pozvan. @@ -800,7 +801,7 @@ na primjer, `localStorage.clear ()` je pozvan.

---- +* * * * * ###### 23. Što je izlaz? @@ -829,7 +830,7 @@ To ne možete učiniti s `let` ili` const` jer su blokirani.

---- +* * * * * ###### 24. Što je izlaz? @@ -843,10 +844,10 @@ set.has("1"); set.has(1); ``` -- A: ` false`` true ` ` false`` true ` -- B: ` false`` true ` ` true`` true ` -- C: ` true`` true ` ` false`` true ` -- D: ` true`` true ` ` true`` true ` +- A: `false`` true` `false`` true` +- B: `false`` true` `true`` true` +- C: `true`` true` `false`` true` +- D: `true`` true` `true`` true`
Odgovor

@@ -864,7 +865,7 @@ To ne radi tako za skup. U našem setu ne postoji "1":

---- +* * * * * ###### 25. Što je izlaz? @@ -889,11 +890,11 @@ i dalje će biti na prvom mjestu, ali s posljednjom navedenom vrijednošću.

---- +* * * * * ###### 26. Globalni kontekst izvođenja JavaScripta za vas stvara dvije stvari: globalni objekt i "ovu" ključnu riječ. -- Istina +- Istina - B: lažno - C: to ovisi @@ -908,7 +909,7 @@ dostupno svugdje u vašem kodu.

---- +* * * * * ###### 27. Što je izlaz? @@ -917,12 +918,13 @@ for (let i = 1; i < 5; i++) { if (i === 3) continue; console.log(i); } + ``` -- A: ` 1`` 2 ` -- B: ` 1`` 2 ` `3` -- C: ` 1`` 2 ` `4` -- D: ` 1`` 3 ` `4` +- A: `1`` 2` +- B: `1`` 2` `3` +- C: `1`` 2` `4` +- D: `1`` 3` `4`
Odgovor

@@ -935,7 +937,7 @@ vraća "true".

---- +* * * * * ###### 28. Što je izlaz? @@ -946,10 +948,10 @@ String.prototype.giveLydiaPizza = () => { const name = "Lydia"; -console.log(name.giveLydiaPizza()); +console.log(name.giveLydiaPizza()) ``` -- A: `Već daj Lizijinu pizzu!` +- A: `` Već daj Lizijinu pizzu! `` - B: `TypeError: nije function` - C: `SyntaxError` - D: `undefined` @@ -968,7 +970,7 @@ način!

---- +* * * * * ###### 29. Što je izlaz? @@ -1007,7 +1009,7 @@ da na `456`, tako da se vraća` 456`.

---- +* * * * * ###### 30. Što je izlaz? @@ -1021,10 +1023,10 @@ foo(); baz(); ``` -- A: ` Prvi`` Drugi ` `Treći` -- B: ` Prvi`` Treći ` `Drugi` -- C: ` Drugi`` Prvi ` `Treći` -- D: ` Drugi`` Treći ` `Prvi` +- A: `Prvi`` Drugi` `Treći` +- B: `Prvi`` Treći` `Drugi` +- C: `Drugi`` Prvi` `Treći` +- D: `Drugi`` Treći` `Prvi`
Odgovor

@@ -1038,7 +1040,7 @@ To je zato što u preglednicima nemamo samo runtime engine, mi također imaju nešto što se zove "WebAPI". "WebAPI" nam daje `setTimeout` function za početak, i na primjer DOM. -Nakon što je _ callback _ preusmjeren na WebAPI, function `setTimeout` +Nakon što je * callback * preusmjeren na WebAPI, function `setTimeout` sam (ali ne i povratni poziv!) iskače iz stog. @@ -1054,11 +1056,11 @@ prijavljeni. WebAPI ne može jednostavno dodati stvari u stog kad god je spreman. Umjesto toga, on povlači funkciju povratnog poziva u nešto što se zove -_red_. +*red*. -Ovo je mjesto gdje petlja događaja počinje raditi. \*\* ** krug događaja ** gleda +Ovo je mjesto gdje petlja događaja počinje raditi. ** ** krug događaja ** gleda red i red za zadatke. Ako je stog prazan, uzima prvi stvar u redu i gura je u stog. @@ -1070,7 +1072,7 @@ stog.

---- +* * * * * ###### 31. Što je event.target kada kliknete na gumb? @@ -1102,7 +1104,7 @@ događaj. Možete zaustaviti mjehuriće 'event.stopPropagation'

---- +* * * * * ###### 32. Kada kliknete na paragraf, što je zapisani izlaz? @@ -1114,8 +1116,8 @@ događaj. Možete zaustaviti mjehuriće 'event.stopPropagation'
``` -- A: ` p`` div ` -- B: ` div`` p ` +- A: `p`` div` +- B: `div`` p` - C: p - D: "div" @@ -1133,7 +1135,7 @@ van.

---- +* * * * * ###### 33. Što je izlaz? @@ -1148,10 +1150,10 @@ sayHi.call(person, 21); sayHi.bind(person, 21); ``` -- A: ` undefined is 21`` Lydia je 21 ` +- A: `undefined is 21`` Lydia je 21` - B: function funkcije -- C: ` Lydia je 21`` Lydia je 21 ` -- D: ` Lydia je 21`` function ` +- C: `Lydia je 21`` Lydia je 21` +- D: `Lydia je 21`` function`
Odgovor

@@ -1159,15 +1161,15 @@ sayHi.bind(person, 21); #### Odgovor: D S oba, možemo proslijediti objekt kojem želimo ključnu riječ "this" -odnosi se na. Međutim, `.call` se također _ izvršava odmah _! +odnosi se na. Međutim, `.call` se također * izvršava odmah *! -`.bind.` vraća _ copy _ funkcije, ali s vezanim kontekstom! To +`.bind.` vraća * copy * funkcije, ali s vezanim kontekstom! To se ne izvršava odmah.

---- +* * * * * ###### 34. Što je izlaz? @@ -1194,13 +1196,13 @@ pozvana function (IIFE). Ova function vratila je `0`, što je tip ` "Broj"`. FYI: postoji samo 7 ugrađenih tipova: `null`,` undefined`, `boolean`, -"broj", "niz", "objekt" i "simbol". `function '' nije tip, -budući da su funkcije objekti, to je tipa` objekta '`. +"broj", "niz", "objekt" i "simbol". `` function '' nije tip, +budući da su funkcije objekti, to je tipa `` objekta '`.

---- +* * * * * ###### 35. Koja od ovih vrijednosti su neistinite? @@ -1214,8 +1216,8 @@ undefined; ``` - A: `0`,` ```,` undefined` -- B: `0`,`new Number (0)`,`''`,`new Boolean (false)`,` undefined ' -- C: `0`,`''`,`new Boolean (false)`,` undefined` +- B: `0`,` new Number (0) `,` '' `,` new Boolean (false) `,` undefined ' +- C: `0`,` '' `,` new Boolean (false) `,` undefined` - D: Svi su oni lažni
Odgovor @@ -1237,12 +1239,13 @@ Konstruktori function, kao što su 'new Number' i 'new Boolean' su istiniti.

---- +* * * * * ###### 36. Što je izlaz? ```javascript console.log(typeof typeof 1); + ``` - A: `" broj " @@ -1260,7 +1263,7 @@ console.log(typeof typeof 1);

---- +* * * * * ###### 37. Što je izlaz? @@ -1292,7 +1295,7 @@ itd)

---- +* * * * * ###### 38. Što je izlaz? @@ -1310,10 +1313,10 @@ itd) })(); ``` -- A: ` 1`` undefined `` 2 ` -- B: ` undefined`` undefined ` `undefined` -- C: ` 1`` 1 ` `2` -- D: ` 1`` undefined ` `undefined` +- A: `1`` undefined `` 2` +- B: `undefined`` undefined` `undefined` +- C: `1`` 1` `2` +- D: `1`` undefined` `undefined`
Odgovor

@@ -1328,13 +1331,13 @@ varijable `y '. Sada, zapisujemo blok-scoped varijablu `x`, koja je jednako "1". Izvan 'catch' bloka, `x 'je i dalje` undefined`, a `y` je` 2`. -Kada želimo `console.log (x)`izvan`catch`bloka, to -vraća`undefined` i` y`vraća`2`. +Kada želimo `console.log (x)` izvan `catch` bloka, to +vraća `undefined` i` y` vraća `2`.

---- +* * * * * ###### 39. Sve u JavaScriptu je ili ... @@ -1355,7 +1358,8 @@ Primitivni tipovi su "boolean", "null", "undefined", "bigint", "number", Ono što razlikuje primitiv od objekta je to što primitivci to ne čine imaju bilo kakva svojstva ili metode; međutim, to ćete primijetiti -`'foo'.toUpperCase ()` vrednuje za' 'FOO'`i ne rezultira a`TypeError`. To je zato što kada pokušate pristupiti svojstvu ili metodi +`'foo'.toUpperCase ()` vrednuje za' 'FOO'` i ne rezultira a +`TypeError`. To je zato što kada pokušate pristupiti svojstvu ili metodi na primitivnom poput stringa, JavaScript će implicitet omotati objekt koristeći jednu od klasa omotača, tj. `String ', a zatim odmah odbacite omotač nakon što se izraz procijeni. Svi primitivci @@ -1364,15 +1368,12 @@ osim "null" i "undefined" pokazuju ovo ponašanje.

---- +* * * * * ###### 40. Što je izlaz? ```javascript -[ - [0, 1], - [2, 3], -].reduce( +[[0, 1], [2, 3]].reduce( (acc, cur) => { return acc.concat(cur); }, @@ -1392,7 +1393,7 @@ osim "null" i "undefined" pokazuju ovo ponašanje. "[1, 2]" je naša početna vrijednost. To je vrijednost s kojom počinjemo i vrijednost prvog `acc`. Tijekom prvog kruga, "acc" je "[1,2]", -i `cur` je`[0, 1]`. Spojimo ih, što rezultira +i `cur` je` [0, 1] `. Spojimo ih, što rezultira `[1, 2, 0, 1]`. Tada je `[1, 2, 0, 1]` `acc` i` [2, 3] `````. Ulančavamo se @@ -1401,7 +1402,7 @@ i dobiti `[1, 2, 0, 1, 2, 3]`

---- +* * * * * ###### 41. Što je izlaz? @@ -1411,10 +1412,10 @@ i dobiti `[1, 2, 0, 1, 2, 3]` !!1; ``` -- A: ` false`` true ` `false` -- B: ` false`` false ` `true` -- C: ` false`` true ` `true` -- D: ` true`` true ` `false` +- A: `false`` true` `false` +- B: `false`` false` `true` +- C: `false`` true` `true` +- D: `true`` true` `false`
Odgovor

@@ -1430,7 +1431,7 @@ i dobiti `[1, 2, 0, 1, 2, 3]`

---- +* * * * * ###### 42. Što se vraća metoda `setInterval`? @@ -1454,7 +1455,7 @@ Vraća jedinstveni ID. Taj se ID može koristiti za brisanje tog intervala

---- +* * * * * ###### 43. Što se to vraća? diff --git a/de-DE/README.md b/de-DE/README.md index a9dbd381..10145050 100644 --- a/de-DE/README.md +++ b/de-DE/README.md @@ -10,11 +10,10 @@ Von einfach bis fortgeschritten: teste, wie gut du JavaScript kennst, frische de Kontaktiert mich, wenn ihr möchtet! 😊
Instagram || Twitter || LinkedIn || Blog - -| Benutzt die Fragen und Lösungen in einem Projekt! 😃 Ich würde mich _sehr_ freuen, wenn ihr dieses Repo verlinkt. Ich erstelle die Fragen und antworten (ja, ich bin traurig, lol) und die Community hilft mir unglaublich dabei, das ganze zu pflegen und verbessern! 💪🏼 Danke und habt Spaß! | -| ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| Benutzt die Fragen und Lösungen in einem Projekt! 😃 Ich würde mich _sehr_ freuen, wenn ihr dieses Repo verlinkt. Ich erstelle die Fragen und antworten (ja, ich bin traurig, lol) und die Community hilft mir unglaublich dabei, das ganze zu pflegen und verbessern! 💪🏼 Danke und habt Spaß! | +|---| @@ -36,7 +35,6 @@ Kontaktiert mich, wenn ihr möchtet! 😊
- [🇳🇱 Nederlands](../nl-NL/README.md) - [🇵🇱 Polski](../pl-PL/README.md) - [🇧🇷 Português Brasil](../pt-BR/README_pt_BR.md) -- [🇷o Română](../ro-RO/README.ro.md) - [🇷🇺 Русский](../ru-RU/README.md) - [🇽🇰 Shqip](../sq-KS/README_sq_KS.md) - [🇹🇭 ไทย](../th-TH/README-th_TH.md) @@ -55,19 +53,19 @@ Kontaktiert mich, wenn ihr möchtet! 😊
```javascript function sayHi() { - console.log(name); - console.log(age); - var name = "Lydia"; - let age = 21; + console.log(name); + console.log(age); + var name = "Lydia"; + let age = 21; } sayHi(); ``` -- A: `Lydia` und `undefined` -- B: `Lydia` und `ReferenceError` -- C: `ReferenceError` und `21` -- D: `undefined` und `ReferenceError` +- A: `Lydia` und `undefined` +- B: `Lydia` und `ReferenceError` +- C: `ReferenceError` und `21` +- D: `undefined` und `ReferenceError`
Antwort

@@ -87,17 +85,17 @@ Variablen mit dem `let` (oder `const`) Keyword werden ebenfalls gehoisted, aber ```javascript for (var i = 0; i < 3; i++) { - setTimeout(() => console.log(i), 1); + setTimeout(() => console.log(i), 1); } for (let i = 0; i < 3; i++) { - setTimeout(() => console.log(i), 1); + setTimeout(() => console.log(i), 1); } ``` -- A: `0 1 2` und `0 1 2` -- B: `0 1 2` und `3 3 3` -- C: `3 3 3` und `0 1 2` +- A: `0 1 2` und `0 1 2` +- B: `0 1 2` und `3 3 3` +- C: `3 3 3` und `0 1 2`

Antwort

@@ -117,21 +115,21 @@ In der zweiten Schleife wurde die Variable `i` mit dem `let` Keyword definiert: ```javascript const shape = { - radius: 10, - diameter() { - return this.radius * 2; - }, - perimeter: () => 2 * Math.PI * this.radius, + radius: 10, + diameter() { + return this.radius * 2; + }, + perimeter: () => 2 * Math.PI * this.radius, }; shape.diameter(); shape.perimeter(); ``` -- A: `20` und `62.83185307179586` -- B: `20` und `NaN` -- C: `20` und `63` -- D: `NaN` und `63` +- A: `20` und `62.83185307179586` +- B: `20` und `NaN` +- C: `20` und `63` +- D: `NaN` und `63`

Antwort

@@ -156,9 +154,9 @@ Es gibt keinen Wert `radius` in dem Object, daher wird `undefined` zurückgegebe !"Lydia"; ``` -- A: `1` und `false` -- B: `false` und `NaN` -- C: `false` und `false` +- A: `1` und `false` +- B: `false` und `NaN` +- C: `false` und `false`

Antwort

@@ -178,19 +176,19 @@ Der String `'Lydia'` ist truthy. Was wir eigentlich fragen ist: "ist dieser trut ```javascript const bird = { - size: "small", + size: "small", }; const mouse = { - name: "Mickey", - small: true, + name: "Mickey", + small: true, }; ``` -- A: `mouse.bird.size` ist nicht korrekt -- B: `mouse[bird.size]` ist nicht korrekt -- C: `mouse[bird["size"]]` ist nicht korrekt -- D: Keine der Antworten ist korrekt. +- A: `mouse.bird.size` ist nicht korrekt +- B: `mouse[bird.size]` ist nicht korrekt +- C: `mouse[bird["size"]]` ist nicht korrekt +- D: Keine der Antworten ist korrekt.

Antwort

@@ -221,11 +219,11 @@ c.greeting = "Hello"; console.log(d.greeting); ``` -- A: `Hello` -- B: `Hey` -- C: `undefined` -- D: `ReferenceError` -- E: `TypeError` +- A: `Hello` +- B: `Hey` +- C: `undefined` +- D: `ReferenceError` +- E: `TypeError`

Antwort

@@ -257,10 +255,10 @@ console.log(a === b); console.log(b === c); ``` -- A: `true` `false` `true` -- B: `false` `false` `true` -- C: `true` `false` `false` -- D: `false` `true` `true` +- A: `true` `false` `true` +- B: `false` `false` `true` +- C: `true` `false` `false` +- D: `false` `true` `true`

Antwort

@@ -282,24 +280,24 @@ Wenn wir aber `===` nutzen müssen sowohl der Wert _als auch_ der Typ übereinst ```javascript class Chameleon { - static colorChange(newColor) { - this.newColor = newColor; - return this.newColor; - } - - constructor({ newColor = "green" } = {}) { - this.newColor = newColor; - } + static colorChange(newColor) { + this.newColor = newColor; + return this.newColor; + } + + constructor({ newColor = "green" } = {}) { + this.newColor = newColor; + } } const freddie = new Chameleon({ newColor: "purple" }); freddie.colorChange("orange"); ``` -- A: `orange` -- B: `purple` -- C: `green` -- D: `TypeError` +- A: `orange` +- B: `purple` +- C: `green` +- D: `TypeError`

Antwort

@@ -321,9 +319,9 @@ greetign = {}; // Typo! console.log(greetign); ``` -- A: `{}` -- B: `ReferenceError: greetign is not defined` -- C: `undefined` +- A: `{}` +- B: `ReferenceError: greetign is not defined` +- C: `undefined`

Antwort

@@ -343,16 +341,16 @@ Um das zu verhindern, können wir `"use strict"` verwenden. Das stellt sicher, d ```javascript function bark() { - console.log("Woof!"); + console.log("Woof!"); } bark.animal = "dog"; ``` -- A: Nichts, das ist absolut in Ordnung. -- B: `SyntaxError`. Man kann einer Funktion keine Properties in der Form zuweisen. -- C: `undefined` -- D: `ReferenceError` +- A: Nichts, das ist absolut in Ordnung. +- B: `SyntaxError`. Man kann einer Funktion keine Properties in der Form zuweisen. +- C: `undefined` +- D: `ReferenceError`

Antwort

@@ -372,22 +370,22 @@ Eine Funktion ist ein spezieller Typ eines Objekts. Der Code, den wir schreiben ```javascript function Person(firstName, lastName) { - this.firstName = firstName; - this.lastName = lastName; + this.firstName = firstName; + this.lastName = lastName; } const member = new Person("Lydia", "Hallie"); -Person.getFullName = function () { - return `${this.firstName} ${this.lastName}`; +Person.getFullName = function() { + return `${this.firstName} ${this.lastName}`; }; console.log(member.getFullName()); ``` -- A: `TypeError` -- B: `SyntaxError` -- C: `Lydia Hallie` -- D: `undefined` `undefined` +- A: `TypeError` +- B: `SyntaxError` +- C: `Lydia Hallie` +- D: `undefined` `undefined`

Antwort

@@ -397,8 +395,8 @@ console.log(member.getFullName()); Man kann keine Properties einem Constructor zuweisen, wie es bei normalen Objects der Fall ist. Wenn man ein Feature allen Objects zugleich zuweisen möchte, muss man den Prototype verwenden. In diesem Fall also: ```js -Person.prototype.getFullName = function () { - return `${this.firstName} ${this.lastName}`; +Person.prototype.getFullName = function() { + return `${this.firstName} ${this.lastName}`; }; ``` @@ -414,8 +412,8 @@ Stattdessen haben wir sie nur dem Prototype zugewiesen, sodass sie nur an einer ```javascript function Person(firstName, lastName) { - this.firstName = firstName; - this.lastName = lastName; + this.firstName = firstName; + this.lastName = lastName; } const lydia = new Person("Lydia", "Hallie"); @@ -425,10 +423,10 @@ console.log(lydia); console.log(sarah); ``` -- A: `Person {firstName: "Lydia", lastName: "Hallie"}` und `undefined` -- B: `Person {firstName: "Lydia", lastName: "Hallie"}` und `Person {firstName: "Sarah", lastName: "Smith"}` -- C: `Person {firstName: "Lydia", lastName: "Hallie"}` und `{}` -- D:`Person {firstName: "Lydia", lastName: "Hallie"}` und `ReferenceError` +- A: `Person {firstName: "Lydia", lastName: "Hallie"}` und `undefined` +- B: `Person {firstName: "Lydia", lastName: "Hallie"}` und `Person {firstName: "Sarah", lastName: "Smith"}` +- C: `Person {firstName: "Lydia", lastName: "Hallie"}` und `{}` +- D:`Person {firstName: "Lydia", lastName: "Hallie"}` und `ReferenceError`

Antwort

@@ -446,10 +444,10 @@ Wir haben `this.firstName` den Wert `"Sarah"` zugewiesen und `this.lastName` den ###### 13. Was sind die drei Phasen der Event Propagation? -- A: Target > Capturing > Bubbling -- B: Bubbling > Target > Capturing -- C: Target > Bubbling > Capturing -- D: Capturing > Target > Bubbling +- A: Target > Capturing > Bubbling +- B: Bubbling > Target > Capturing +- C: Target > Bubbling > Capturing +- D: Capturing > Target > Bubbling

Antwort

@@ -467,8 +465,8 @@ Während der **capturing** Phase geht das Event durch die Elternelemente bis hin ###### 14. Alle Objekte haben Prototypes. -- A: wahr -- B: falsch +- A: wahr +- B: falsch

Antwort

@@ -486,16 +484,16 @@ Alle Objekte haben Prototypes, außer dem **Basis Objekt**. Das Basis Objekt hat ```javascript function sum(a, b) { - return a + b; + return a + b; } sum(1, "2"); ``` -- A: `NaN` -- B: `TypeError` -- C: `"12"` -- D: `3` +- A: `NaN` +- B: `TypeError` +- C: `"12"` +- D: `3`

Antwort

@@ -520,10 +518,10 @@ console.log(++number); console.log(number); ``` -- A: `1` `1` `2` -- B: `1` `2` `2` -- C: `0` `2` `2` -- D: `0` `1` `2` +- A: `1` `1` `2` +- B: `1` `2` `2` +- C: `0` `2` `2` +- D: `0` `1` `2`

Antwort

@@ -551,9 +549,9 @@ Der Output ist daher `0 2 2`. ```javascript function getPersonInfo(one, two, three) { - console.log(one); - console.log(two); - console.log(three); + console.log(one); + console.log(two); + console.log(three); } const person = "Lydia"; @@ -562,9 +560,9 @@ const age = 21; getPersonInfo`${person} is ${age} years old`; ``` -- A: `"Lydia"` `21` `["", " is ", " years old"]` -- B: `["", " is ", " years old"]` `"Lydia"` `21` -- C: `"Lydia"` `["", " is ", " years old"]` `21` +- A: `"Lydia"` `21` `["", " is ", " years old"]` +- B: `["", " is ", " years old"]` `"Lydia"` `21` +- C: `"Lydia"` `["", " is ", " years old"]` `21`

Antwort

@@ -582,21 +580,21 @@ Wenn man Template Literals verwendet ist das erste Argument immer ein Array der ```javascript function checkAge(data) { - if (data === { age: 18 }) { - console.log("You are an adult!"); - } else if (data == { age: 18 }) { - console.log("You are still an adult."); - } else { - console.log(`Hmm.. You don't have an age I guess`); - } + if (data === { age: 18 }) { + console.log("You are an adult!"); + } else if (data == { age: 18 }) { + console.log("You are still an adult."); + } else { + console.log(`Hmm.. You don't have an age I guess`); + } } checkAge({ age: 18 }); ``` -- A: `You are an adult!` -- B: `You are still an adult.` -- C: `Hmm.. You don't have an age I guess` +- A: `You are an adult!` +- B: `You are still an adult.` +- C: `Hmm.. You don't have an age I guess`

Antwort

@@ -618,16 +616,16 @@ Deshalb werfen sowohl `{ age: 18 } === { age: 18 }` als auch `{ age: 18 } == { a ```javascript function getAge(...args) { - console.log(typeof args); + console.log(typeof args); } getAge(21); ``` -- A: `"number"` -- B: `"array"` -- C: `"object"` -- D: `"NaN"` +- A: `"number"` +- B: `"array"` +- C: `"object"` +- D: `"NaN"`

Antwort

@@ -645,18 +643,18 @@ Der Spread Operator (`...args`) gibt ein Array mit Argumenten zurück. Ein Array ```javascript function getAge() { - "use strict"; - age = 21; - console.log(age); + "use strict"; + age = 21; + console.log(age); } getAge(); ``` -- A: `21` -- B: `undefined` -- C: `ReferenceError` -- D: `TypeError` +- A: `21` +- B: `undefined` +- C: `ReferenceError` +- D: `TypeError`

Antwort

@@ -676,10 +674,10 @@ Durch `"use strict"` kann man sicher stellen, dass man nicht versehentlich globa const sum = eval("10*10+5"); ``` -- A: `105` -- B: `"105"` -- C: `TypeError` -- D: `"10*10+5"` +- A: `105` +- B: `"105"` +- C: `TypeError` +- D: `"10*10+5"`

Antwort

@@ -699,10 +697,10 @@ const sum = eval("10*10+5"); sessionStorage.setItem("cool_secret", 123); ``` -- A: Für immer, der Wert geht nicht verloren. -- B: Wenn der User den Tab schließt. -- C: Wenn der User den Browser schließt, nicht nur den Tab. -- D: Wenn der User den Computer neu startet. +- A: Für immer, der Wert geht nicht verloren. +- B: Wenn der User den Tab schließt. +- C: Wenn der User den Browser schließt, nicht nur den Tab. +- D: Wenn der User den Computer neu startet.

Antwort

@@ -727,10 +725,10 @@ var num = 10; console.log(num); ``` -- A: `8` -- B: `10` -- C: `SyntaxError` -- D: `ReferenceError` +- A: `8` +- B: `10` +- C: `SyntaxError` +- D: `ReferenceError`

Antwort

@@ -758,10 +756,10 @@ set.has("1"); set.has(1); ``` -- A: `false` `true` `false` `true` -- B: `false` `true` `true` `true` -- C: `true` `true` `false` `true` -- D: `true` `true` `true` `true` +- A: `false` `true` `false` `true` +- B: `false` `true` `true` `true` +- C: `true` `true` `false` `true` +- D: `true` `true` `true` `true`

Antwort

@@ -784,10 +782,10 @@ const obj = { a: "one", b: "two", a: "three" }; console.log(obj); ``` -- A: `{ a: "one", b: "two" }` -- B: `{ b: "two", a: "three" }` -- C: `{ a: "three", b: "two" }` -- D: `SyntaxError` +- A: `{ a: "one", b: "two" }` +- B: `{ b: "two", a: "three" }` +- C: `{ a: "three", b: "two" }` +- D: `SyntaxError`

Antwort

@@ -803,9 +801,9 @@ Wenn man zwei Keys mit dem selben Namen hat, wird der erste Key ersetzt. Er wird ###### 26. Der JavaScript Global Execution Context erstellt zwei Dinge: das globale Objekt und das "this" Keyword. -- A: wahr -- B: falsch -- C: kommt darauf an +- A: wahr +- B: falsch +- C: kommt darauf an

Antwort

@@ -823,15 +821,15 @@ Der Base Execution Context entspricht dem Global Execution Context und ist über ```javascript for (let i = 1; i < 5; i++) { - if (i === 3) continue; - console.log(i); + if (i === 3) continue; + console.log(i); } ``` -- A: `1` `2` -- B: `1` `2` `3` -- C: `1` `2` `4` -- D: `1` `3` `4` +- A: `1` `2` +- B: `1` `2` `3` +- C: `1` `2` `4` +- D: `1` `3` `4`

Antwort

@@ -849,18 +847,18 @@ for (let i = 1; i < 5; i++) { ```javascript String.prototype.giveLydiaPizza = () => { - return "Just give Lydia pizza already!"; + return "Just give Lydia pizza already!"; }; const name = "Lydia"; -console.log(name.giveLydiaPizza()); +console.log(name.giveLydiaPizza()) ``` -- A: `"Just give Lydia pizza already!"` -- B: `TypeError: not a function` -- C: `SyntaxError` -- D: `undefined` +- A: `"Just give Lydia pizza already!"` +- B: `TypeError: not a function` +- C: `SyntaxError` +- D: `undefined`

Antwort

@@ -887,10 +885,10 @@ a[c] = 456; console.log(a[b]); ``` -- A: `123` -- B: `456` -- C: `undefined` -- D: `ReferenceError` +- A: `123` +- B: `456` +- C: `undefined` +- D: `ReferenceError`

Antwort

@@ -920,10 +918,10 @@ foo(); baz(); ``` -- A: `First` `Second` `Third` -- B: `First` `Third` `Second` -- C: `Second` `First` `Third` -- D: `Second` `Third` `First` +- A: `First` `Second` `Third` +- B: `First` `Third` `Second` +- C: `Second` `First` `Third` +- D: `Second` `Third` `First`

Antwort

@@ -965,16 +963,18 @@ Das ist, wo die Event Loop ins Spiel kommt. Die **Event Loop** betrachtet den St ```html

-
- -
+
+ +
``` -- A: Äußerer `div` -- B: Innerer `div` -- C: `button` -- D: Ein Array mit allen genesteten Elementen +- A: Äußerer `div` +- B: Innerer `div` +- C: `button` +- D: Ein Array mit allen genesteten Elementen
Antwort

@@ -992,14 +992,16 @@ Das am tiefsten genestete Element, welches das Event auslöst ist das Event Targ ```html

-

Click here!

+

+ Click here! +

``` -- A: `p` `div` -- B: `div` `p` -- C: `p` -- D: `div` +- A: `p` `div` +- B: `div` `p` +- C: `p` +- D: `div`
Antwort

@@ -1019,17 +1021,17 @@ Wenn wir auf den Paragraph klicken, sehen wir zwei logs: `p` und `div`. Während const person = { name: "Lydia" }; function sayHi(age) { - console.log(`${this.name} is ${age}`); + console.log(`${this.name} is ${age}`); } sayHi.call(person, 21); sayHi.bind(person, 21); ``` -- A: `undefined is 21` `Lydia is 21` -- B: `function` `function` -- C: `Lydia is 21` `Lydia is 21` -- D: `Lydia is 21` `function` +- A: `undefined is 21` `Lydia is 21` +- B: `function` `function` +- C: `Lydia is 21` `Lydia is 21` +- D: `Lydia is 21` `function`

Antwort

@@ -1049,16 +1051,16 @@ In beiden Fällen können wir das Objekt weiter reichen, auf welches sich das `t ```javascript function sayHi() { - return (() => 0)(); + return (() => 0)(); } typeof sayHi(); ``` -- A: `"object"` -- B: `"number"` -- C: `"function"` -- D: `"undefined"` +- A: `"object"` +- B: `"number"` +- C: `"function"` +- D: `"undefined"`

Antwort

@@ -1085,10 +1087,10 @@ new Boolean(false); undefined; ``` -- A: `0`, `''`, `undefined` -- B: `0`, `new Number(0)`, `''`, `new Boolean(false)`, `undefined` -- C: `0`, `''`, `new Boolean(false)`, `undefined` -- D: Alle sind falsy +- A: `0`, `''`, `undefined` +- B: `0`, `new Number(0)`, `''`, `new Boolean(false)`, `undefined` +- C: `0`, `''`, `new Boolean(false)`, `undefined` +- D: Alle sind falsy

Antwort

@@ -1097,12 +1099,12 @@ undefined; Es gibt nur 6 falsy typen: -- `undefined` -- `null` -- `NaN` -- `0` -- `''` (leerer String) -- `false` +- `undefined` +- `null` +- `NaN` +- `0` +- `''` (leerer String) +- `false` Funktions-Constructor, wie `new Number` und `new Boolean` sind truthy. @@ -1117,10 +1119,10 @@ Funktions-Constructor, wie `new Number` und `new Boolean` sind truthy. console.log(typeof typeof 1); ``` -- A: `"number"` -- B: `"string"` -- C: `"object"` -- D: `"undefined"` +- A: `"number"` +- B: `"string"` +- C: `"object"` +- D: `"undefined"`

Antwort

@@ -1143,10 +1145,10 @@ numbers[10] = 11; console.log(numbers); ``` -- A: `[1, 2, 3, 7 x null, 11]` -- B: `[1, 2, 3, 11]` -- C: `[1, 2, 3, 7 x empty, 11]` -- D: `SyntaxError` +- A: `[1, 2, 3, 7 x null, 11]` +- B: `[1, 2, 3, 11]` +- C: `[1, 2, 3, 7 x empty, 11]` +- D: `SyntaxError`

Antwort

@@ -1168,22 +1170,22 @@ abhängig davon wo das Array ausgeführt wird (die Ausgabe ist unterschiedlich f ```javascript (() => { - let x, y; - try { - throw new Error(); - } catch (x) { - (x = 1), (y = 2); - console.log(x); - } - console.log(x); - console.log(y); + let x, y; + try { + throw new Error(); + } catch (x) { + (x = 1), (y = 2); + console.log(x); + } + console.log(x); + console.log(y); })(); ``` -- A: `1` `undefined` `2` -- B: `undefined` `undefined` `undefined` -- C: `1` `1` `2` -- D: `1` `undefined` `undefined` +- A: `1` `undefined` `2` +- B: `undefined` `undefined` `undefined` +- C: `1` `1` `2` +- D: `1` `undefined` `undefined`

Antwort

@@ -1203,10 +1205,10 @@ Außerhalb des `catch` Blocks ist `x` noch immer `undefined` und `y` ist `2`. We ###### 39. Alles in JavaScript ist entweder ein ... -- A: Primitive oder Object -- B: Function oder Object -- C: Fangfrage: nur Objects! -- D: Number oder Object +- A: Primitive oder Object +- B: Function oder Object +- C: Fangfrage: nur Objects! +- D: Number oder Object

Antwort

@@ -1227,21 +1229,18 @@ Was einen primitiven Typ von einem Objekt unterscheidet ist, dass Primitive kein ###### 40. Was wird ausgegeben? ```javascript -[ - [0, 1], - [2, 3], -].reduce( - (acc, cur) => { - return acc.concat(cur); - }, - [1, 2] +[[0, 1], [2, 3]].reduce( + (acc, cur) => { + return acc.concat(cur); + }, + [1, 2], ); ``` -- A: `[0, 1, 2, 3, 1, 2]` -- B: `[6, 1, 2]` -- C: `[1, 2, 0, 1, 2, 3]` -- D: `[1, 2, 6]` +- A: `[0, 1, 2, 3, 1, 2]` +- B: `[6, 1, 2]` +- C: `[1, 2, 0, 1, 2, 3]` +- D: `[1, 2, 6]`

Antwort

@@ -1265,10 +1264,10 @@ Dann entspricht `acc` gleich `[1, 2, 0, 1]` und `cur` ist gleich `[2, 3]`. Wir v !!1; ``` -- A: `false` `true` `false` -- B: `false` `false` `true` -- C: `false` `true` `true` -- D: `true` `true` `false` +- A: `false` `true` `false` +- B: `false` `false` `true` +- C: `false` `true` `true` +- D: `true` `true` `false`

Antwort

@@ -1292,10 +1291,10 @@ Dann entspricht `acc` gleich `[1, 2, 0, 1]` und `cur` ist gleich `[2, 3]`. Wir v setInterval(() => console.log("Hi"), 1000); ``` -- A: Eine unique id -- B: Die definierte Anzahl von Millisekunden -- C: Die Callback Function -- D: `undefined` +- A: Eine unique id +- B: Die definierte Anzahl von Millisekunden +- C: Die Callback Function +- D: `undefined`

Antwort

@@ -1315,10 +1314,10 @@ Es gibt eine unique id zurück. Diese id kann zum Beispiel verwendet werden um d [..."Lydia"]; ``` -- A: `["L", "y", "d", "i", "a"]` -- B: `["Lydia"]` -- C: `[[], "Lydia"]` -- D: `[["L", "y", "d", "i", "a"]]` +- A: `["L", "y", "d", "i", "a"]` +- B: `["Lydia"]` +- C: `[[], "Lydia"]` +- D: `[["L", "y", "d", "i", "a"]]`

Antwort

@@ -1378,7 +1377,7 @@ const secondPromise = new Promise((res, rej) => { setTimeout(res, 100, "two"); }); -Promise.race([firstPromise, secondPromise]).then((res) => console.log(res)); +Promise.race([firstPromise, secondPromise]).then(res => console.log(res)); ``` - A: `"one"` @@ -1442,7 +1441,7 @@ Wir ändern nur den Wert der Variable `person` und nicht das erste Element im Ar ```javascript const person = { name: "Lydia", - age: 21, + age: 21 }; for (const item in person) { @@ -1522,7 +1521,7 @@ Nur die erste Zahl im String wird ausgegeben. Aufgrund des _radix_ (das zweite A ###### 50. Was wird ausgegeben? ```javascript -[1, 2, 3].map((num) => { +[1, 2, 3].map(num => { if (typeof num === "number") return; return num * 2; }); @@ -1688,6 +1687,7 @@ Da wir die Variable `y` aber global erstellt haben ist ihr Wert `10` auch hier v

+ --- ###### 55. Was wird ausgegeben? @@ -1699,7 +1699,7 @@ class Dog { } } -Dog.prototype.bark = function () { +Dog.prototype.bark = function() { console.log(`Woof I am ${this.name}`); }; @@ -1814,7 +1814,7 @@ console.log(delete age); #### Antwort: A -Der `delete` Operator gibt einen Boolean Wert zurück: `true` bei erfolgreichem entfernen, oder andernfalls `false`. Variablen, die mit `var`, `let` oder `const` deklariert werden, können andererseits nicht mit `delete` entfernt werden. +Der `delete` Operator gibt einen Boolean Wert zurück: `true` bei erfolgreichem entfernen, oder andernfalls `false`. Variablen, die mit `var`, `let` oder `const` deklariert werden, können andererseits nicht mit `delete` entfernt werden. Der Wert von `name` wurde mit `const` deklariert, weshalb `delete` nicht möglich ist und `false` zurückgegeben wird. Als wir `age` den Wert `21` zugewiesen haben, haben wir eine Property `age` zum globalen Objekt hinzugefügt. Diese Properties kann man mit `delete` entfernen, sodass `delete age` `true` zurückgibt. @@ -1927,7 +1927,7 @@ Properties, die mit `defineProperty` erstellt wurden sind standardmäßig unver const settings = { username: "lydiahallie", level: 19, - health: 90, + health: 90 }; const data = JSON.stringify(settings, ["level", "health"]); @@ -1961,7 +1961,7 @@ Wenn der Replacer eine _Funktion_ ist, so wird diese Funktion für jede Property let num = 10; const increaseNumber = () => num++; -const increasePassedNumber = (number) => number++; +const increasePassedNumber = number => number++; const num1 = increaseNumber(); const num2 = increasePassedNumber(num1); @@ -1987,6 +1987,8 @@ Der unäre Operator `++` _gibt zuerst_ den Wert des Operanden aus und _erhöht d

+ + --- ###### 64. Was wird ausgegeben? @@ -2054,7 +2056,6 @@ Beim ersten Call ist der Akkumulator (`x`) gleich `1` und der aktuelle Wert (`y` Wenn wir keinen Wert einer Funktion ausgeben wird `undefined` ausgegeben. Beim nächsten Call ist der Akkumulator daher `undefined` und der aktuelle Wert ist `3`. `undefined` und `3` werden geloggt. Beim vierten Call geben wir wieder nichts aus, sodass der Akkumulator wieder `undefined` ist und der aktuelle Wert `4`. `undefined` und `4` werden geloggt. -

@@ -2108,7 +2109,6 @@ In einer abgeleiteten Klasse kann das `this` Keyword nicht aufgerufen werden, be Mit dem `super` Keyword können wir den Constructor der Elternklasse mit gegebenen Argumenten aufrufen. Der Constructor der Elternklasse erhält das `name` Argument, sodass wir `name` an `super` übergeben müssen. Die `Dog` Klasse erhält zwei Argumente, `name` da es `Animal` erweitert und `size` als extra Property der `Dog` Klasse. Beide müssen an die Constructor Funktion von `Dog` übergeben werden, was nur bei Constructor 2 richtig ist. -

@@ -2149,9 +2149,9 @@ Das ist der große Unterschied zwischen `require()` in CommonJS und `import`. Mi ###### 68. Was wird ausgegeben? ```javascript -console.log(Number(2) === Number(2)); -console.log(Boolean(false) === Boolean(false)); -console.log(Symbol("foo") === Symbol("foo")); +console.log(Number(2) === Number(2)) +console.log(Boolean(false) === Boolean(false)) +console.log(Symbol('foo') === Symbol('foo')) ``` - A: `true`, `true`, `false` @@ -2174,9 +2174,9 @@ Jedes Symbol ist eindeutig. Der Sinn des Argumentes, welches an das Symbol weite ###### 69. Was wird ausgegeben? ```javascript -const name = "Lydia Hallie"; -console.log(name.padStart(13)); -console.log(name.padStart(2)); +const name = "Lydia Hallie" +console.log(name.padStart(13)) +console.log(name.padStart(2)) ``` - A: `"Lydia Hallie"`, `"Lydia Hallie"` @@ -2451,7 +2451,7 @@ Die `sum` Funktion gibt daher immer das gleiche Ergebnis aus. Wenn wir `1` und ` ```javascript const add = () => { const cache = {}; - return (num) => { + return num => { if (num in cache) { return `From cache! ${cache[num]}`; } else { @@ -2496,21 +2496,21 @@ Beim dritten Mal geben wir `5 * 2` als Argument in die Funktion ein, was `10` er ###### 79. Was wird ausgegeben? ```javascript -const myLifeSummedUp = ["☕", "💻", "🍷", "🍫"]; +const myLifeSummedUp = ["☕", "💻", "🍷", "🍫"] for (let item in myLifeSummedUp) { - console.log(item); + console.log(item) } for (let item of myLifeSummedUp) { - console.log(item); + console.log(item) } ``` - A: `0` `1` `2` `3` und `"☕"` ` "💻"` `"🍷"` `"🍫"` - B: `"☕"` ` "💻"` `"🍷"` `"🍫"` und `"☕"` ` "💻"` `"🍷"` `"🍫"` - C: `"☕"` ` "💻"` `"🍷"` `"🍫"` und `0` `1` `2` `3` -- D: `0` `1` `2` `3` und `{0: "☕", 1: "💻", 2: "🍷", 3: "🍫"}` +- D: `0` `1` `2` `3` und `{0: "☕", 1: "💻", 2: "🍷", 3: "🍫"}`
Antwort

@@ -2533,14 +2533,14 @@ Mit einer _for-of_ Schleife können wir über **wiederholbare** Elemente iterier ###### 80. Was wird ausgegeben? ```javascript -const list = [1 + 2, 1 * 2, 1 / 2]; -console.log(list); +const list = [1 + 2, 1 * 2, 1 / 2] +console.log(list) ``` - A: `["1 + 2", "1 * 2", "1 / 2"]` - B: `["12", 2, 0.5]` - C: `[3, 2, 0.5]` -- D: `[1, 1, 1]` +- D: `[1, 1, 1]`

Antwort

@@ -2560,16 +2560,16 @@ Das Element ist gleich dem ausgegebenen Wert. `1 + 2` ergibt `3`, `1 * 2` ergibt ```javascript function sayHi(name) { - return `Hi there, ${name}`; + return `Hi there, ${name}` } -console.log(sayHi()); +console.log(sayHi()) ``` - A: `Hi there, ` - B: `Hi there, undefined` - C: `Hi there, null` -- D: `ReferenceError` +- D: `ReferenceError`

Antwort

@@ -2592,21 +2592,21 @@ In diesem Fall, falls wir kein Argument oder `undefined` eingeben ist `name` imm ###### 82. Was wird ausgegeben? ```javascript -var status = "😎"; +var status = "😎" setTimeout(() => { - const status = "😍"; + const status = "😍" const data = { status: "🥑", getStatus() { - return this.status; - }, - }; + return this.status + } + } - console.log(data.getStatus()); - console.log(data.getStatus.call(this)); -}, 0); + console.log(data.getStatus()) + console.log(data.getStatus.call(this)) +}, 0) ``` - A: `"🥑"` und `"😍"` @@ -2623,6 +2623,7 @@ Der Wert des `this` Keywords hängt davon ab, wo es verwendet wird. In einer **M Mit der `call` Methode können wir das Objekt, auf welches sich das `this` Keyword bezieht ändern. In **Funktionen** bezieht sich `this` auf das _Objekt, zu dem die Funktion gehört_. Wir erklären die `setTimeout` Funktion im _globalen Objekt_, sodass sich `this` in `setTimeout` auf das _globale Objekt_ bezieht. Im globalen Objekt gibt es _status_ mit dem Wert `"😎"`, was geloggt wird. +

@@ -2633,13 +2634,13 @@ Mit der `call` Methode können wir das Objekt, auf welches sich das `this` Keywo ```javascript const person = { name: "Lydia", - age: 21, -}; + age: 21 +} -let city = person.city; -city = "Amsterdam"; +let city = person.city +city = "Amsterdam" -console.log(person); +console.log(person) ``` - A: `{ name: "Lydia", age: 21 }` @@ -2670,15 +2671,15 @@ Wenn wir `person` loggen bekommen wir daher das unveränderte Objekt angezeigt. ```javascript function checkAge(age) { if (age < 18) { - const message = "Sorry, you're too young."; + const message = "Sorry, you're too young." } else { - const message = "Yay! You're old enough!"; + const message = "Yay! You're old enough!" } - return message; + return message } -console.log(checkAge(21)); +console.log(checkAge(21)) ``` - A: `"Sorry, you're too young."` @@ -2701,9 +2702,9 @@ Variablen mit dem `const` und `let` Keyword sind _block-scoped_. Ein Block ist a ###### 85. Welche Information wird geloggt? ```javascript -fetch("https://www.website.com/api/user/1") - .then((res) => res.json()) - .then((res) => console.log(res)); +fetch('https://www.website.com/api/user/1') + .then(res => res.json()) + .then(res => console.log(res)) ``` - A: Das Ergebnis der `fetch` Methode. @@ -2748,16 +2749,16 @@ Wenn wir `hasName` gleich `name` setzen, so beinhaltet `hasName` den Wert von `n `new Boolean(true)` gibt einen Objekt Wrapper aus, nicht ein Boolean ansich. `name.length` gibt die Länge des Arguments aus, nicht den Boolean Wert. -

+ --- ###### 87. Was wird ausgegeben? ```javascript -console.log("I want pizza"[0]); +console.log("I want pizza"[0]) ``` - A: `"""` @@ -2783,10 +2784,10 @@ Diese Methode funktioniert nicht in IE7 und davor. Hier muss `.charAt()` verwend ```javascript function sum(num1, num2 = num1) { - console.log(num1 + num2); + console.log(num1 + num2) } -sum(10); +sum(10) ``` - A: `NaN` @@ -2812,13 +2813,13 @@ Wenn man den Wert des Standard Paramenters gleich dem Parameter setztm der _dana ```javascript // module.js -export default () => "Hello world"; -export const name = "Lydia"; +export default () => "Hello world" +export const name = "Lydia" // index.js -import * as data from "./module"; +import * as data from "./module" -console.log(data); +console.log(data) ``` - A: `{ default: function default(), name: "Lydia" }` @@ -2845,12 +2846,12 @@ Das `data` Objekt hat eine Standard Property für alle Standard Exporte, andere ```javascript class Person { constructor(name) { - this.name = name; + this.name = name } } -const member = new Person("John"); -console.log(typeof member); +const member = new Person("John") +console.log(typeof member) ``` - A: `"class"` @@ -2867,7 +2868,7 @@ Klassen sind syntaktischer Zucker für Funktionskontruktoren. Das Equivalent der ```javascript function Person() { - this.name = name; + this.name = name } ``` @@ -2881,9 +2882,9 @@ Das Aufrufen eines Funktionskonstruktors mit `new` hat zur Folge, dass eine Inst ###### 91. Was wird ausgegeben? ```javascript -let newList = [1, 2, 3].push(4); +let newList = [1, 2, 3].push(4) -console.log(newList.push(5)); +console.log(newList.push(5)) ``` - A: `[1, 2, 3, 4, 5]` @@ -2909,14 +2910,13 @@ Dann versuchen wir die `.push` Methode auf `newList` anzuwenden. Da `newList` de ```javascript function giveLydiaPizza() { - return "Here is pizza!"; + return "Here is pizza!" } -const giveLydiaChocolate = () => - "Here's chocolate... now go hit the gym already."; +const giveLydiaChocolate = () => "Here's chocolate... now go hit the gym already." -console.log(giveLydiaPizza.prototype); -console.log(giveLydiaChocolate.prototype); +console.log(giveLydiaPizza.prototype) +console.log(giveLydiaChocolate.prototype) ``` - A: `{ constructor: ...}` `{ constructor: ...}` @@ -2941,11 +2941,11 @@ Reguläre Funktionen wie `giveLydiaPizza` haben eine `prototype` Property, die e ```javascript const person = { name: "Lydia", - age: 21, -}; + age: 21 +} for (const [x, y] of Object.entries(person)) { - console.log(x, y); + console.log(x, y) } ``` @@ -2997,14 +2997,13 @@ getItems(["banana", "apple"], "pear", "orange") ```javascript function getItems(fruitList, favoriteFruit, ...args) { - return [...fruitList, ...args, favoriteFruit]; + return [...fruitList, ...args, favoriteFruit] } -getItems(["banana", "apple"], "pear", "orange"); +getItems(["banana", "apple"], "pear", "orange") ``` Dieses Beispiel würde funktionieren und `[ 'banana', 'apple', 'orange', 'pear' ]` ausgeben. -

@@ -3014,14 +3013,17 @@ Dieses Beispiel würde funktionieren und `[ 'banana', 'apple', 'orange', 'pear' ```javascript function nums(a, b) { - if (a > b) console.log("a is bigger"); - else console.log("b is bigger"); - return; - a + b; + if + (a > b) + console.log('a is bigger') + else + console.log('b is bigger') + return + a + b } -console.log(nums(4, 2)); -console.log(nums(1, 2)); +console.log(nums(4, 2)) +console.log(nums(1, 2)) ``` - A: `a is bigger`, `6` und `b is bigger`, `3` @@ -3039,8 +3041,8 @@ In JavaScript muss das Semikolon _nicht_ explizit gesetzt werden, allerdings set In unserem Beispiel haben wir ein `return` Statement gefolgt von einem anderen Wert `a + b` auf der _nächsten Zeile_. Da es eine neue Zeile ist, weiß JavaScript nicht, dass das der Wert ist, den wir eigentlich ausgeben wollten. Stattdessen wird automatisch ein Semikolon nach `return` gesetzt, was man wiefolgt lesen kann: ```javascript -return; -a + b; + return; + a + b ``` Das bedeutet, dass `a + b` nie erreicht wird, da die Funktion auf der Zeile davor mit dem `return` Keyword endet. Wenn wie hier kein Wert ausgegeben wird, gibt die Funktion `undefined` aus. @@ -3056,18 +3058,18 @@ Bedenke: Semikolons werden **nicht** automatisch nach `if/else` Statements geset ```javascript class Person { constructor() { - this.name = "Lydia"; + this.name = "Lydia" } } Person = class AnotherPerson { constructor() { - this.name = "Sarah"; + this.name = "Sarah" } -}; +} -const member = new Person(); -console.log(member.name); +const member = new Person() +console.log(member.name) ``` - A: `"Lydia"` @@ -3091,11 +3093,11 @@ Wir können Klassen gleich anderen Klassen oder Funktions Konstruktoren setzen. ```javascript const info = { - [Symbol("a")]: "b", -}; + [Symbol('a')]: 'b' +} -console.log(info); -console.log(Object.keys(info)); +console.log(info) +console.log(Object.keys(info)) ``` - A: `{Symbol('a'): 'b'}` und `["{Symbol('a')"]` @@ -3143,13 +3145,13 @@ console.log(getUser(user)) Die `getList` Funktion bekommt ein Array als Argument zugewiesen. Zwischen den Klammern der `getList` Funktion wird das Array direkt destrukturiert. Man könnte das auch wiefolgt sehen: -`[x, ...y] = [1, 2, 3, 4]` + `[x, ...y] = [1, 2, 3, 4]` Mit dem Rest Parameter `...y` packen wir alle übrigen Argumente in ein Array. Die übrigen Argumente sind in dem Fall `2`, `3` und `4`. Der Wert von `y` ist ein Array mit den restlichen Parametern. Der Wert von `x` ist gleich `1` sodass `[1, [2, 3, 4]]` geloggt wird. Die `getUser` Funktion bekommt ein Objekt zugewiesen. Bei Arrow Funktionen müssen wir keine geschweiften Klammern verwenden, wenn wir nur einen Wert ausgeben. Wenn wir aber ein _Objekt_ von einer Arrow Funktion ausgeben lassen möchten, so muss dieses zwischen Klammern stehen, ansonsten wird nichts ausgegeben. Die folgende Funktion hätte ein Objekt ausgegeben: -`const getUser = user => ({ name: user.name, age: user.age })` +```const getUser = user => ({ name: user.name, age: user.age })``` Da kein Wert ausgegeben wird, gibt die Funktion `undefined` aus. @@ -3161,9 +3163,9 @@ Da kein Wert ausgegeben wird, gibt die Funktion `undefined` aus. ###### 99. Was wird ausgegeben? ```javascript -const name = "Lydia"; +const name = "Lydia" -console.log(name()); +console.log(name()) ``` - A: `SyntaxError` @@ -3194,8 +3196,8 @@ ReferenceErrors werden ausgeworfen, wenn JavaScript eine Referenz zu einem Wert ```javascript // 🎉✨ Das ist unsere 100. Frage! ✨🎉 -const output = `${[] && "Im"}possible! -You should${"" && `n't`} see a therapist after so much JavaScript lol`; +const output = `${[] && 'Im'}possible! +You should${'' && `n't`} see a therapist after so much JavaScript lol` ``` - A: `possible! You should see a therapist after so much JavaScript lol` @@ -3220,11 +3222,11 @@ You should${"" && `n't`} see a therapist after so much JavaScript lol`; ###### 101. Was wird ausgegeben? ```javascript -const one = false || {} || null; -const two = null || false || ""; -const three = [] || 0 || true; +const one = (false || {} || null) +const two = (null || false || "") +const three = ([] || 0 || true) -console.log(one, two, three); +console.log(one, two, three) ``` - A: `false` `null` `[]` @@ -3253,16 +3255,16 @@ Mit dem `||` Operator geben wir den ersten truthy Operand aus. Wenn alle Werte f ###### 102. What's the value of output? ```javascript -const myPromise = () => Promise.resolve("I have resolved!"); +const myPromise = () => Promise.resolve('I have resolved!') function firstFunction() { - myPromise().then((res) => console.log(res)); - console.log("second"); + myPromise().then(res => console.log(res)) + console.log('second') } async function secondFunction() { - console.log(await myPromise()); - console.log("second"); + console.log(await myPromise()) + console.log('second') } ``` @@ -3295,14 +3297,14 @@ Das bedeutet, dass auf `myPromise` gewartet und dann der Wert `I have resolved` ###### 103. Was wird ausgegeben? ```javascript -const set = new Set(); +const set = new Set() -set.add(1); -set.add("Lydia"); -set.add({ name: "Lydia" }); +set.add(1) +set.add("Lydia") +set.add({ name: "Lydia" }) for (let item of set) { - console.log(item + 2); + console.log(item + 2) } ``` @@ -3332,7 +3334,7 @@ Der zweite Wert hingegen ist der String `"Lydia"`. `"Lydia"` ist ein String und ###### 104. Was wird ausgegeben? ```javascript -Promise.resolve(5); +Promise.resolve(5) ``` - A: `5` @@ -3359,15 +3361,15 @@ In diesem Fall haben wir nur die Zahl `5` übergeben und diese wird genauso ausg ```javascript function compareMembers(person1, person2 = person) { if (person1 !== person2) { - console.log("Not the same!"); + console.log("Not the same!") } else { - console.log("They are the same!"); + console.log("They are the same!") } } -const person = { name: "Lydia" }; +const person = { name: "Lydia" } -compareMembers(person); +compareMembers(person) ``` - A: `Not the same!` @@ -3402,11 +3404,11 @@ const colorConfig = { green: true, black: true, yellow: false, -}; +} -const colors = ["pink", "red", "blue"]; +const colors = ["pink", "red", "blue"] -console.log(colorConfig.colors[1]); +console.log(colorConfig.colors[1]) ``` - A: `true` @@ -3433,7 +3435,7 @@ JavaScript interpretiert Statements. Wenn wir Klammern-Notation verwenden wird d ###### 107. Was wird ausgegeben? ```javascript -console.log("❤️" === "❤️"); +console.log('❤️' === '❤️') ``` - A: `true` @@ -3454,14 +3456,14 @@ Emojis sind im Endeffekt nur Unicodes. Der Unicode für das Herz Emoji ist `"U+2 ###### 108. Welche Methode verändert das ursprüngliche Array? ```javascript -const emojis = ["✨", "🥑", "😍"]; +const emojis = ['✨', '🥑', '😍'] -emojis.map((x) => x + "✨"); -emojis.filter((x) => x !== "🥑"); -emojis.find((x) => x !== "🥑"); -emojis.reduce((acc, cur) => acc + "✨"); -emojis.slice(1, 2, "✨"); -emojis.splice(1, 2, "✨"); +emojis.map(x => x + '✨') +emojis.filter(x => x !== '🥑') +emojis.find(x => x !== '🥑') +emojis.reduce((acc, cur) => acc + '✨') +emojis.slice(1, 2, '✨') +emojis.splice(1, 2, '✨') ``` - A: `All of them` @@ -3481,17 +3483,18 @@ Mit der `splice` Methode ändern wir das ursprüngliche Array durch löschen, er

+ --- ###### 109. Was wird ausgegeben? ```javascript -const food = ["🍕", "🍫", "🥑", "🍔"]; -const info = { favoriteFood: food[0] }; +const food = ['🍕', '🍫', '🥑', '🍔'] +const info = { favoriteFood: food[0] } -info.favoriteFood = "🍝"; +info.favoriteFood = '🍝' -console.log(food); +console.log(food) ``` - A: `['🍕', '🍫', '🥑', '🍔']` @@ -3516,7 +3519,7 @@ Dann ändern wir den Wert von `favoriteFood` am `info` Objekt. Das `food` Array ###### 110. Was macht diese Methode? ```javascript -JSON.parse(); +JSON.parse() ``` - A: Parsed JSON in einen JavaScript Wert @@ -3533,16 +3536,16 @@ Mit der `JSON.parse()` Methode können wir einen JSON String zu einem JavaScript ```javascript // Stringifying a number into valid JSON, then parsing the JSON string to a JavaScript value: -const jsonNumber = JSON.stringify(4); // '4' -JSON.parse(jsonNumber); // 4 +const jsonNumber = JSON.stringify(4) // '4' +JSON.parse(jsonNumber) // 4 // Stringifying an array value into valid JSON, then parsing the JSON string to a JavaScript value: -const jsonArray = JSON.stringify([1, 2, 3]); // '[1, 2, 3]' -JSON.parse(jsonArray); // [1, 2, 3] +const jsonArray = JSON.stringify([1, 2, 3]) // '[1, 2, 3]' +JSON.parse(jsonArray) // [1, 2, 3] // Stringifying an object into valid JSON, then parsing the JSON string to a JavaScript value: -const jsonArray = JSON.stringify({ name: "Lydia" }); // '{"name":"Lydia"}' -JSON.parse(jsonArray); // { name: 'Lydia' } +const jsonArray = JSON.stringify({ name: "Lydia" }) // '{"name":"Lydia"}' +JSON.parse(jsonArray) // { name: 'Lydia' } ```

@@ -3553,14 +3556,14 @@ JSON.parse(jsonArray); // { name: 'Lydia' } ###### 111. Was wird ausgegeben? ```javascript -let name = "Lydia"; +let name = 'Lydia' function getName() { - console.log(name); - let name = "Sarah"; + console.log(name) + let name = 'Sarah' } -getName(); +getName() ``` - A: Lydia @@ -3580,13 +3583,13 @@ Variablen mit dem `let` und `const` Keyword werden gehoisted, aber entgegen `var Hätten wir die `name` Variable nicht innerhalb `getName` deklariert, so hätte JavaScript außerhalb der Funktion in der _Scope-Kette_ weitergesucht. Der äußere Scope beinhaltet ebenfalls eine Variable `name` mit dem Wert `'Lydia'`. In diesem Fall wäre `Lydia` geloggt worden. ```javascript -let name = "Lydia"; +let name = 'Lydia' function getName() { - console.log(name); + console.log(name) } -getName(); // Lydia +getName() // Lydia ```

@@ -3598,18 +3601,18 @@ getName(); // Lydia ```javascript function* generatorOne() { - yield ["a", "b", "c"]; + yield ['a', 'b', 'c']; } function* generatorTwo() { - yield* ["a", "b", "c"]; + yield* ['a', 'b', 'c']; } -const one = generatorOne(); -const two = generatorTwo(); +const one = generatorOne() +const two = generatorTwo() -console.log(one.next().value); -console.log(two.next().value); +console.log(one.next().value) +console.log(two.next().value) ``` - A: `a` and `a` @@ -3627,17 +3630,17 @@ Mit dem `yield` Keyword, halten wir Werte in einer Generator-Funktion. Mit dem ` In `generatorOne` halten wir das gesamte Array `['a', 'b', 'c']` mit dem `yield` Keyword. Der Wert von `value` am Objekt gibt die `next` Methode an `one` (`one.next().value`) aus, was dem gesamten Array entspricht: `['a', 'b', 'c']`. ```javascript -console.log(one.next().value); // ['a', 'b', 'c'] -console.log(one.next().value); // undefined +console.log(one.next().value) // ['a', 'b', 'c'] +console.log(one.next().value) // undefined ``` In `generatorTwo` verwenden wir das `yield*` Keyword. Das bedeutet, dass der erste gehaltene Wert von `two` gleich dem ersten gehaltenen Wert ist. Das ist das Array `['a', 'b', 'c']`. Der erste gehaltene Wert ist `a`, was ausgegeben wird. ```javascript -console.log(two.next().value); // 'a' -console.log(two.next().value); // 'b' -console.log(two.next().value); // 'c' -console.log(two.next().value); // undefined +console.log(two.next().value) // 'a' +console.log(two.next().value) // 'b' +console.log(two.next().value) // 'c' +console.log(two.next().value) // undefined ```

@@ -3648,7 +3651,7 @@ console.log(two.next().value); // undefined ###### 113. Was wird ausgegeben? ```javascript -console.log(`${((x) => x)("I love")} to program`); +console.log(`${(x => x)('I love')} to program`) ``` - A: `I love to program` @@ -3738,19 +3741,19 @@ Beim Setzen eines Key/Wert Paars mit der `set` Methode wird der Key als erstes A ```javascript const person = { name: "Lydia", - age: 21, -}; + age: 21 +} -const changeAge = (x = { ...person }) => (x.age += 1); +const changeAge = (x = { ...person }) => x.age += 1 const changeAgeAndName = (x = { ...person }) => { - x.age += 1; - x.name = "Sarah"; -}; + x.age += 1 + x.name = "Sarah" +} -changeAge(person); -changeAgeAndName(); +changeAge(person) +changeAgeAndName() -console.log(person); +console.log(person) ``` - A: `{name: "Sarah", age: 22}` @@ -3778,7 +3781,7 @@ Dann führen wir `changeAgeAndName` aus, allerdings ohne Parameter. Stattdessen ```javascript function sumValues(x, y, z) { - return x + y + z; + return x + y + z; } ``` @@ -3829,15 +3832,15 @@ Mit dem`+=` Operanden erhöhen wir den Wert von `num` um `1`. `num` hatte den ur ```javascript const person = { - firstName: "Lydia", - lastName: "Hallie", - pet: { - name: "Mara", - breed: "Dutch Tulip Hound", - }, - getFullName() { - return `${this.firstName} ${this.lastName}`; - }, + firstName: "Lydia", + lastName: "Hallie", + pet: { + name: "Mara", + breed: "Dutch Tulip Hound" + }, + getFullName() { + return `${this.firstName} ${this.lastName}`; + } }; console.log(person.pet?.name); @@ -3874,9 +3877,9 @@ Mit den optionalen Kettenoperator `?.` müssen wir nicht mehr prüfen, ob die ti const groceries = ["banana", "apple", "peanuts"]; if (groceries.indexOf("banana")) { - console.log("We have to buy bananas!"); + console.log("We have to buy bananas!"); } else { - console.log(`We don't have to buy bananas!`); + console.log(`We don't have to buy bananas!`); } ``` @@ -3901,10 +3904,10 @@ Wir haben die Kondition `groceries.indexOf("banana")` an das if-Statement überg ```javascript const config = { - languages: [], - set language(lang) { - return this.languages.push(lang); - }, + languages: [], + set language(lang) { + return this.languages.push(lang); + } }; console.log(config.language); @@ -3958,9 +3961,9 @@ console.log(!typeof name === "string"); ###### 123. Was ist der Output?? ```javascript -const add = (x) => (y) => (z) => { - console.log(x, y, z); - return x + y + z; +const add = x => y => z => { + console.log(x, y, z); + return x + y + z; }; add(4)(5)(6); @@ -3987,16 +3990,16 @@ Die `add` Funktion gibt eine Arrow Funktion zurück, welche eine Arrow Funktion ```javascript async function* range(start, end) { - for (let i = start; i <= end; i++) { - yield Promise.resolve(i); - } + for (let i = start; i <= end; i++) { + yield Promise.resolve(i); + } } (async () => { - const gen = range(1, 3); - for await (const item of gen) { - console.log(item); - } + const gen = range(1, 3); + for await (const item of gen) { + console.log(item); + } })(); ``` @@ -4021,7 +4024,7 @@ Die Generator-Funktion `range` gibt ein asynchrones Objekt mit Promisen für jed ```javascript const myFunc = ({ x, y, z }) => { - console.log(x, y, z); + console.log(x, y, z); }; myFunc(1, 2, 3); @@ -4048,20 +4051,20 @@ myFunc(1, 2, 3); ```javascript function getFine(speed, amount) { - const formattedSpeed = new Intl.NumberFormat("en-US", { - style: "unit", - unit: "mile-per-hour", + const formattedSpeed = new Intl.NumberFormat('en-US', { + style: 'unit', + unit: 'mile-per-hour' }).format(speed); - const formattedAmount = new Intl.NumberFormat("en-US", { - style: "currency", - currency: "USD", + const formattedAmount = new Intl.NumberFormat('en-US', { + style: 'currency', + currency: 'USD' }).format(amount); return `The driver drove ${formattedSpeed} and has to pay ${formattedAmount}`; } -console.log(getFine(130, 300)); +console.log(getFine(130, 300)) ``` - A: The driver drove 130 and has to pay 300 @@ -4084,8 +4087,8 @@ Mit der Methode `Intl.NumberFormat` können wir einen numerischen Wert in einen ###### 127. Was ist der Output? ```javascript -const spookyItems = ["👻", "🎃", "🕸"]; -({ item: spookyItems[3] } = { item: "💀" }); +const spookyItems = ['👻', '🎃', '🕸']; +({ item: spookyItems[3] } = { item: '💀' }); console.log(spookyItems); ``` @@ -4110,7 +4113,7 @@ Durch die destrukturierende Zuweisung können wir Werte des Ojekts von der recht ###### 128. Was ist der Output? ```javascript -const name = "Lydia Hallie"; +const name = 'Lydia Hallie'; const age = 21; console.log(Number.isNaN(name)); @@ -4130,7 +4133,7 @@ console.log(isNaN(age)); #### Antwort: C -Mit der Methode `Number.isNaN` kann geprüft werden, ob der übergebene Parameter vom Typ _Number_ mit Wert `NaN` ist. `name` ist kein numerischer Wert, deswegen ist der Rückgabewert von `Number.isNaN(name)` in diesem Fall `false`. `age` ist zwar ein numerischer Wert, aber nicht gleich `NaN`, weswegen `Number.isNaN(age)` `false` ausgibt. +Mit der Methode `Number.isNaN` kann geprüft werden, ob der übergebene Parameter vom Typ _Number_ mit Wert `NaN` ist. `name` ist kein numerischer Wert, deswegen ist der Rückgabewert von `Number.isNaN(name)` in diesem Fall `false`. `age` ist zwar ein numerischer Wert, aber nicht gleich `NaN`, weswegen `Number.isNaN(age)` `false` ausgibt. Die Methode `isNaN` prüft, ob der Eingabeparameter nicht vom Typ _Number_ ist. `name` ist ein String, darum gibt `isNaN(name)` `true` zurück. `age` ist ein numerischer Wert, weswegen `isNaN(age)` `false` ausgibt. @@ -4146,7 +4149,7 @@ const randomValue = 21; function getInfo() { console.log(typeof randomValue); - const randomValue = "Lydia Hallie"; + const randomValue = 'Lydia Hallie'; } getInfo(); @@ -4172,7 +4175,7 @@ Variablen die mit `const` deklariert werden, können nicht vor ihrer Initialisie ###### 130. Was ist der Output? ```javascript -const myPromise = Promise.resolve("Woah some cool data"); +const myPromise = Promise.resolve('Woah some cool data'); (async () => { try { @@ -4180,7 +4183,7 @@ const myPromise = Promise.resolve("Woah some cool data"); } catch { throw new Error(`Oops didn't work`); } finally { - console.log("Oh finally!"); + console.log('Oh finally!'); } })(); ``` @@ -4205,7 +4208,7 @@ Im `try`-Block loggen wir den mit dem `await`-Operator den Wert der Variable `my ###### 131. Was ist der Output? ```javascript -const emojis = ["🥑", ["✨", "✨", ["🍕", "🍕"]]]; +const emojis = ['🥑', ['✨', '✨', ['🍕', '🍕']]]; console.log(emojis.flat(1)); ``` @@ -4278,19 +4281,19 @@ Wir rufen nun `counterTwo.increment()` auf, wodurch der Wert von `count` auf `3` ###### 133. Was ist der Output? ```javascript -const myPromise = Promise.resolve(Promise.resolve("Promise!")); +const myPromise = Promise.resolve(Promise.resolve('Promise!')); function funcOne() { - myPromise.then((res) => res).then((res) => console.log(res)); - setTimeout(() => console.log("Timeout!", 0)); - console.log("Last line!"); + myPromise.then(res => res).then(res => console.log(res)); + setTimeout(() => console.log('Timeout!', 0)); + console.log('Last line!'); } async function funcTwo() { const res = await myPromise; console.log(await res); - setTimeout(() => console.log("Timeout!", 0)); - console.log("Last line!"); + setTimeout(() => console.log('Timeout!', 0)); + console.log('Last line!'); } funcOne(); @@ -4318,4 +4321,4 @@ Die nächste Zeile ist die _asynchrone_ Funktion `setTimeout`, deren Callback an Wir kommen zur letzten Zeile in `funcTwo`, die `Last line!` in der Console ausgibt. Da `funcTwo` abgearbeitet und aus dem Call Stack entfernt wurde, ist der Call Stack leer. Die wartenden Callbacks (`() => console.log("Timeout!")` aus `funcOne` und `() => console.log("Timeout!")` aus `funcTwo`) werden dem Call Stack nacheinander hinzugefügt. Der erste Callback loggt `Timeout!` und wird aus dem Stack entfernt. Anschließend loggt der zweite Callback `Timeout!` und wird aus dem Stack entfernt. Somit ist das Ergebnis `Last line! Promise! Promise! Last line! Timeout! Timeout!`

-
+
\ No newline at end of file diff --git a/es-ES/README-ES.md b/es-ES/README-ES.md index 577e66f0..5c3ddc40 100644 --- a/es-ES/README-ES.md +++ b/es-ES/README-ES.md @@ -1,16 +1,17 @@ -# Lista de preguntas (avanzadas) de JavaScript -Publico diariamente preguntas de opción múltiple en JavaScript en mi [Instagram](https://www.instagram.com/theavocoder), ¡que también publicaré aquí! +# Lista de preguntas (avanzadas) de JavaScript -Desde lo básico a lo avanzado: comprueba si realmente conoces _Javascript_, actualiza tus conocimientos o simplemente prepárate para tu próxima entrevista 💪 🚀 Actualizaré este repo semanalmente con nuevas preguntas. - -Las respuestas se encuentran en las secciones contraídas debajo de las preguntas, simplemente haz clic en ellas para expandirlas. Buena suerte ❤️ + Publico diariamente preguntas de opción múltiple en JavaScript en mi [Instagram](https://www.instagram.com/theavocoder), ¡que también publicaré aquí! + + Desde lo básico a lo avanzado: comprueba si realmente conoces _Javascript_, actualiza tus conocimientos o simplemente prepárate para tu próxima entrevista 💪 🚀 Actualizaré este repo semanalmente con nuevas preguntas. + + Las respuestas se encuentran en las secciones contraídas debajo de las preguntas, simplemente haz clic en ellas para expandirlas. Buena suerte ❤️ ¿Quieres recibir un email cada vez que agregue más preguntas?
✨✉Suscríbete a las actualizaciones por email✉✨ -Lista de lenguajes disponibles: +Lista de lenguajes disponibles: - [🇸🇦 العربية](../ar-AR/README_AR.md) - [🇪🇬 اللغة العامية](../ar-EG/README_ar-EG.md) - [🇧🇦 Bosanski](../bs-BS/README-bs_BS.md) @@ -24,7 +25,6 @@ Lista de lenguajes disponibles: - [🇳🇱 Nederlands](../nl-NL/README.md) - [🇵🇱 Polski](../pl-PL/README.md) - [🇧🇷 Português Brasil](../pt-BR/README_pt_BR.md) -- [🇷o Română](../ro-RO/README.ro.md) - [🇷🇺 Русский](../ru-RU/README.md) - [🇽🇰 Shqip](../sq-KS/README_sq_KS.md) - [🇹🇭 ไทย](../th-TH/README-th_TH.md) @@ -34,6 +34,7 @@ Lista de lenguajes disponibles: - [🇨🇳 简体中文](../zh-CN/README-zh_CN.md) - [🇹🇼 繁體中文](../zh-TW/README_zh-TW.md) + --- ###### 1. ¿Qué devuelve la siguiente función? @@ -62,7 +63,6 @@ sayHi(); Dentro de la función, primero declaramos la variable `name` con la palabra reservada ` var`. Esto significa que la variable se _eleva_ (el espacio de memoria se configura durante la fase de creación. Hace referencia al termino [hoisting](https://developer.mozilla.org/es/docs/Glossary/Hoisting)) con el valor predeterminado de `indefinido`, hasta que realmente llegamos a la línea donde definimos la variable. Aún no hemos definido la variable en la línea donde intentamos registrar la variable `name`, por lo que aún mantiene el valor de` undefined`. Las variables con la palabra clave `let` (y` const`) se _elevan_, pero a diferencia de `var`, no se inicializa . No son accesibles antes de la línea que los declaramos (inicializamos). Esto se llama la ["zona muerta temporal"](https://wesbos.com/temporal-dead-zone/). Cuando intentamos acceder a las variables antes de que se declaren, JavaScript lanza un `ReferenceError` -

@@ -106,7 +106,7 @@ const shape = { diameter() { return this.radius * 2; }, - perimeter: () => 2 * Math.PI * this.radius, + perimeter: () => 2 * Math.PI * this.radius }; shape.diameter(); @@ -163,12 +163,12 @@ En el segundo caso la cadena `'Lydia'` es un valor verdadero. Lo que realmente e ```javascript const bird = { - size: "small", + size: "small" }; const mouse = { name: "Mickey", - small: true, + small: true }; ``` @@ -186,7 +186,7 @@ En JavaScript, todas las _keys_ son cadenas (a menos que sea un símbolo). A pes JavaScript interpreta declaraciones. Cuando usamos la notación de corchetes, ve el corchete de apertura `[` y continúa hasta que encuentra el corchete de cierre `]`. Solo de esta manera se evaluará la afirmación. -`mouse [bird.size]`: Primero evalúa `bird.size`, que es`"small"`. `mouse ["small"]` devuelve `true` +`mouse [bird.size]`: Primero evalúa `bird.size`, que es` "small" `. `mouse ["small"]` devuelve `true` Sin embargo, con la notación de puntos, esto no sucede. `mouse` no tiene una clave llamada` bird`, lo que significa que `mouse.bird` es` undefined`. Luego, pedimos el `tamaño` usando la notación de puntos:` mouse.bird.size`. Como `mouse.bird` es` undefined`, en realidad estamos preguntando `undefined.size`. Esto no es válido y generará un error similar `al Cannot read property "size" of undefined` @@ -363,7 +363,7 @@ function Person(firstName, lastName) { const member = new Person("Lydia", "Hallie"); Person.getFullName = function () { return `${this.firstName} ${this.lastName}`; -}; +} console.log(member.getFullName()); ``` @@ -420,7 +420,7 @@ console.log(sarah); Para `sarah`, no usamos la palabra reservada `new`. Cuando se usa `new`, se refiere al nuevo objeto vacío que creamos. Sin embargo, si no se agrega `new', se refiere al **objeto global**! -En el ejemplo `this.firstName` equivale a `"Sarah"` y `this.lastName` equivale a `"Smith"`. Lo que realmente hicimos fue definir `global.firstName = `Sarah'`y`global.lastName = `Smith'`. La misma `sarah` se deja `indefinida`. +En el ejemplo `this.firstName` equivale a `"Sarah"` y `this.lastName` equivale a `"Smith"`. Lo que realmente hicimos fue definir `global.firstName = `Sarah'` y `global.lastName = `Smith'`. La misma `sarah` se deja `indefinida`.

@@ -487,7 +487,7 @@ sum(1, "2"); JavaScript es un **lenguaje dinámicamente tipado** o de tipado débil, esto significa que no es necesario declarar el tipo de variable antes de usarla pues será determinado automáticamente cuando el programa comience a ser procesado. Los valores se pueden convertir automáticamente en otro tipo sin que se sepa, esto se llama denomina _implicit type coercion_ (Más info [aquí](https://medium.com/@ManuCastrillonM/entendiendo-la-coerci%C3%B3n-en-javascript-bc202d22d23f)). **La coerción es la conversión de un tipo a otro.** -En este ejemplo, JavaScript convierte el número `1` en una cadena, para que la función tenga sentido y devuelva un valor. Durante la suma de un tipo numérico (`1`) y un tipo de cadena (`'2'`), el número se trata como una cadena. Podemos concatenar cadenas como ` "Hello" + "World"``, así que lo que está pasando aquí es `"1" + "2"`que devuelve`"12"` +En este ejemplo, JavaScript convierte el número `1` en una cadena, para que la función tenga sentido y devuelva un valor. Durante la suma de un tipo numérico (`1`) y un tipo de cadena (`'2'`), el número se trata como una cadena. Podemos concatenar cadenas como `"Hello" + "World"``, así que lo que está pasando aquí es `"1" + "2"` que devuelve `"12"`

@@ -554,8 +554,8 @@ getPersonInfo`${person} is ${age} years old`; #### Respuesta correcta: B -_Tagged templates_ es un caso de uso de [template literals](https://codeburst.io/javascript-template-literals-tag-functions-for-beginners-758a041160e1). Una _plantilla etiquetada_ es una llamada de función que utiliza una plantilla literal de la que obtener sus argumentos. Si se usan literales de plantillas etiquetadas, el valor del primer argumento es siempre una matriz de los valores de las cadenas. El resto de los argumentos obtienen los valores de las expresiones pasadas. +_Tagged templates_ es un caso de uso de [template literals](https://codeburst.io/javascript-template-literals-tag-functions-for-beginners-758a041160e1). Una _plantilla etiquetada_ es una llamada de función que utiliza una plantilla literal de la que obtener sus argumentos. Si se usan literales de plantillas etiquetadas, el valor del primer argumento es siempre una matriz de los valores de las cadenas. El resto de los argumentos obtienen los valores de las expresiones pasadas.

@@ -755,6 +755,7 @@ Todas las claves de un objeto (excepto los símbolos) actúan como cadenas, incl No funciona así para un conjunto. No hay un "1" en nuestro set: `set.has('1')` devuelve `falso`. Tiene el tipo numérico `1`, `set.has(1)` devuelve `true`. +

@@ -820,8 +821,7 @@ for (let i = 1; i < 5; i++) {

#### Respuesta correcta: C - -La sentencia `continue` omite una iteración si una cierta condición, en este caso `(i === 3)`, devuelve `true`. +La sentencia `continue` omite una iteración si una cierta condición, en este caso `(i === 3)`, devuelve `true`.

@@ -837,7 +837,7 @@ String.prototype.giveLydiaPizza = () => { const name = "Lydia"; -console.log(name.giveLydiaPizza()); +console.log(name.giveLydiaPizza()) ``` - A: `"Just give Lydia pizza already!"` @@ -921,7 +921,7 @@ Después de que la _callback_ es empujada a la WebAPI, la función `setTimeout` -Ahora, `foo` es invocado, y `"First"` está siendo registrado. +Ahora, `foo` es invocado, y ``"First"`` está siendo registrado. @@ -949,7 +949,9 @@ Se invoca el `bar`, se registra el `"Second"` y se quita de la pila. ```html
- +
``` @@ -975,7 +977,9 @@ El elemento anidado más profundo que causa el evento es el destino de ese event ```html
-

Click here!

+

+ Click here! +

``` @@ -1019,7 +1023,7 @@ sayHi.bind(person, 21); #### Respuesta correcta: D -En ambos podemos pasar el objeto al que queremos que se refiera la palabra reservada `this`. Sin embargo, la diferencia es que `.call` es _ejecutado inmediatamente_! +En ambos podemos pasar el objeto al que queremos que se refiera la palabra reservada `this`. Sin embargo, la diferencia es que `.call` es *ejecutado inmediatamente*! `.bind` devuelve una copia de la función, pero con un contexto enlazado. Es decir, no se ejecuta de inmediato. @@ -1087,6 +1091,7 @@ Solo hay seis valores falsos: - `''` (cadena vacía) - `false` + Los constructores de funciones, como `new Number` y `new Boolean` son correctos.

@@ -1210,10 +1215,7 @@ Lo que diferencia a un tipo primitivo de un objeto es que los primeros no tienen ###### 40. ¿Qué devuelve la siguiente función? ```javascript -[ - [0, 1], - [2, 3], -].reduce( +[[0, 1], [2, 3]].reduce( (acc, cur) => { return acc.concat(cur); }, @@ -1231,7 +1233,7 @@ Lo que diferencia a un tipo primitivo de un objeto es que los primeros no tienen #### Respuesta correcta: C -`[1, 2]` es nuestro valor inicial. Este es el valor con el que empezamos y el valor del primer `acc`. Durante la primera ronda, `acc` es`[1,2]`, y `cur` es `[0, 1]`. Los concatenamos, lo que resulta en `[1, 2, 0, 1]`. +`[1, 2]` es nuestro valor inicial. Este es el valor con el que empezamos y el valor del primer `acc`. Durante la primera ronda, `acc` es` [1,2] `, y `cur` es `[0, 1]`. Los concatenamos, lo que resulta en `[1, 2, 0, 1]`. Entonces, `[1, 2, 0, 1]` es `acc` y` [2, 3]` es `cur`. Los concatenamos, y obtenemos `[1, 2, 0, 1, 2, 3]` @@ -1361,7 +1363,7 @@ const secondPromise = new Promise((res, rej) => { setTimeout(res, 100, "two"); }); -Promise.race([firstPromise, secondPromise]).then((res) => console.log(res)); +Promise.race([firstPromise, secondPromise]).then(res => console.log(res)); ``` - A: `"one"` @@ -1425,7 +1427,7 @@ Solo estamos modificando el valor de la variable `person`, y no el primer elemen ```javascript const person = { name: "Lydia", - age: 21, + age: 21 }; for (const item in person) { @@ -1505,7 +1507,7 @@ Solo el primer número en el string es devuelto. Según en la _base_ seleccionad ###### 50. ¿Cuál es el resultado? ```javascript -[1, 2, 3].map((num) => { +[1, 2, 3].map(num => { if (typeof num === "number") return; return num * 2; }); @@ -1682,7 +1684,7 @@ class Dog { } } -Dog.prototype.bark = function () { +Dog.prototype.bark = function() { console.log(`Woof I am ${this.name}`); }; @@ -1910,7 +1912,7 @@ Las propiedades añadidas usando el método `defineProperty` son inmutables por const settings = { username: "lydiahallie", level: 19, - health: 90, + health: 90 }; const data = JSON.stringify(settings, ["level", "health"]); @@ -1944,7 +1946,7 @@ Si el reemplazador es una _función_, esta función es llamada en cada propiedad let num = 10; const increaseNumber = () => num++; -const increasePassedNumber = (number) => number++; +const increasePassedNumber = number => number++; const num1 = increaseNumber(); const num2 = increasePassedNumber(num1); @@ -2034,7 +2036,7 @@ El valor del acumulador es igual al valor previamente devuelto por la función d En la primera llamada, el acumulador (`x`) es `1`, y el valor actual (`y`) es `2`. No devolvemos desde la función de callback, mostramos por consola el acumulador y el valor actual: se muestra `1` y `2`. -Si no devuelves un valor de una función, se devuelve `undefined`. En la siguiente llamada, el acumulador es `undefined`, y el valor actual es `3`. Se muestra por consola `undefined` y `3`. +Si no devuelves un valor de una función, se devuelve `undefined`. En la siguiente llamada, el acumulador es `undefined`, y el valor actual es `3`. Se muestra por consola `undefined` y `3`. En la cuarta llamada, otra vez no devolvemos desde la función de callback. El acumulador es una vez más `undefined`, y el valor actual es `4`. Se muestra por consola `undefined` y `4`. @@ -2053,7 +2055,7 @@ class Dog { }; class Labrador extends Dog { - // 1 + // 1 constructor(name, size) { this.size = size; } @@ -2067,7 +2069,7 @@ class Labrador extends Dog { super(name); this.size = size; } - // 4 + // 4 constructor(name, size) { this.name = name; this.size = size; @@ -2101,12 +2103,12 @@ La clase `Labrador` recibe dos argumentos, `name` porque extiende de `Dog`, y `s ```javascript // index.js -console.log("running index.js"); -import { sum } from "./sum.js"; +console.log('running index.js'); +import { sum } from './sum.js'; console.log(sum(1, 2)); // sum.js -console.log("running sum.js"); +console.log('running sum.js'); export const sum = (a, b) => a + b; ``` @@ -2122,7 +2124,7 @@ export const sum = (a, b) => a + b; Con `import`, todos los módulos importados son _pre-convertidos_. Esto significa que los módulos importados son ejecutados _primero_, y el código en el fichero que importa el módulo se ejecuta _después_. -¡Esto es una diferencia existente entre `require()` en CommonJS e `import`! Con `require()`, puedes cargar dependencias bajo demanda mientras el código está siendo ejecutado. Si hubiéramos usado `require` en lugar de `import`, se habría mostrado por consola `running index.js`, `running sum.js`, `3`. +¡Esto es una diferencia existente entre `require()` en CommonJS e `import`! Con `require()`, puedes cargar dependencias bajo demanda mientras el código está siendo ejecutado. Si hubiéramos usado `require` en lugar de `import`, se habría mostrado por consola `running index.js`, `running sum.js`, `3`.

@@ -2132,9 +2134,9 @@ Con `import`, todos los módulos importados son _pre-convertidos_. Esto signific ###### 68. ¿Cuál es el resultado? ```javascript -console.log(Number(2) === Number(2)); -console.log(Boolean(false) === Boolean(false)); -console.log(Symbol("foo") === Symbol("foo")); +console.log(Number(2) === Number(2)) +console.log(Boolean(false) === Boolean(false)) +console.log(Symbol('foo') === Symbol('foo')) ``` - A: `true`, `true`, `false` @@ -2157,15 +2159,15 @@ Cada Symbol es completamente único. El propósito del argumento pasado a Symbol ###### 69. ¿Cuál es el resultado? ```javascript -const name = "Lydia Hallie"; -console.log(name.padStart(13)); -console.log(name.padStart(2)); +const name = "Lydia Hallie" +console.log(name.padStart(13)) +console.log(name.padStart(2)) ``` - A: `"Lydia Hallie"`, `"Lydia Hallie"` - B: `" Lydia Hallie"`, `" Lydia Hallie"` (`"[13 espacios en blanco]Lydia Hallie"`, `"[2 espacios en blanco]Lydia Hallie"`) - C: `" Lydia Hallie"`, `"Lydia Hallie"` (`"[1 espacio en blanco]Lydia Hallie"`, `"Lydia Hallie"`) -- D: `"Lydia Hallie"`, `"Lyd"`, +- D: `"Lydia Hallie"`, `"Lyd"`,
Solución

@@ -2433,7 +2435,7 @@ La función `sum` siempre devuelve el mismo resultado. Si pasamos `1` y `2`, _si ```javascript const add = () => { const cache = {}; - return (num) => { + return num => { if (num in cache) { return `From cache! ${cache[num]}`; } else { @@ -2478,21 +2480,21 @@ La tercera vez, pasamos `5 * 2` a la función, que se evalúa como `10`. El obje ###### 79. ¿Cuál es el resultado? ```javascript -const myLifeSummedUp = ["☕", "💻", "🍷", "🍫"]; +const myLifeSummedUp = ["☕", "💻", "🍷", "🍫"] for (let item in myLifeSummedUp) { - console.log(item); + console.log(item) } for (let item of myLifeSummedUp) { - console.log(item); + console.log(item) } ``` - A: `0` `1` `2` `3` y `"☕"` ` "💻"` `"🍷"` `"🍫"` - B: `"☕"` ` "💻"` `"🍷"` `"🍫"` y `"☕"` ` "💻"` `"🍷"` `"🍫"` - C: `"☕"` ` "💻"` `"🍷"` `"🍫"` y `0` `1` `2` `3` -- D: `0` `1` `2` `3` y `{0: "☕", 1: "💻", 2: "🍷", 3: "🍫"}` +- D: `0` `1` `2` `3` y `{0: "☕", 1: "💻", 2: "🍷", 3: "🍫"}`

Solución

@@ -2515,14 +2517,14 @@ Con un bucle _for-of_, podemos iterar sobre **iterables**. Un array es un iterab ###### 80. ¿Cuál es el resultado? ```javascript -const list = [1 + 2, 1 * 2, 1 / 2]; -console.log(list); +const list = [1 + 2, 1 * 2, 1 / 2] +console.log(list) ``` - A: `["1 + 2", "1 * 2", "1 / 2"]` - B: `["12", 2, 0.5]` - C: `[3, 2, 0.5]` -- D: `[1, 1, 1]` +- D: `[1, 1, 1]`

Solución

@@ -2542,16 +2544,16 @@ El elemento será igual al valor retornado. `1 + 2` devuelve `3`, `1 * 2` devuel ```javascript function sayHi(name) { - return `Hi there, ${name}`; + return `Hi there, ${name}` } -console.log(sayHi()); +console.log(sayHi()) ``` - A: `Hi there, ` - B: `Hi there, undefined` - C: `Hi there, null` -- D: `ReferenceError` +- D: `ReferenceError`

Solución

@@ -2574,21 +2576,21 @@ En ese caso, si no pasáramos un valor o si pasáramos `undefined`, `name` siemp ###### 82. ¿Cuál es el resultado? ```javascript -var status = "😎"; +var status = "😎" setTimeout(() => { - const status = "😍"; + const status = "😍" const data = { status: "🥑", getStatus() { - return this.status; - }, - }; + return this.status + } + } - console.log(data.getStatus()); - console.log(data.getStatus.call(this)); -}, 0); + console.log(data.getStatus()) + console.log(data.getStatus.call(this)) +}, 0) ``` - A: `"🥑"` y `"😍"` @@ -2615,13 +2617,13 @@ Con el método `call`, podemos cambiar el objeto al cual `this` referencia. En * ```javascript const person = { name: "Lydia", - age: 21, -}; + age: 21 +} -let city = person.city; -city = "Amsterdam"; +let city = person.city +city = "Amsterdam" -console.log(person); +console.log(person) ``` - A: `{ name: "Lydia", age: 21 }` @@ -2652,15 +2654,15 @@ Cuando se muestra por consola el objeto `person`, se devuelve el objeto sin modi ```javascript function checkAge(age) { if (age < 18) { - const message = "Sorry, you're too young."; + const message = "Sorry, you're too young." } else { - const message = "Yay! You're old enough!"; + const message = "Yay! You're old enough!" } - return message; + return message } -console.log(checkAge(21)); +console.log(checkAge(21)) ``` - A: `"Sorry, you're too young."` @@ -2683,15 +2685,15 @@ Las variables con `const` y `let` tienen _alcance de bloque_. Un bloque es cualq ###### 85. ¿Qué tipo de información se mostrará por consola? ```javascript -fetch("https://www.website.com/api/user/1") - .then((res) => res.json()) - .then((res) => console.log(res)); +fetch('https://www.website.com/api/user/1') + .then(res => res.json()) + .then(res => console.log(res)) ``` - A: El resultado del método `fetch`. - B: El resultado de la segunda invocación del método `fetch`. - C: El resultado de callback en el `.then()` anterior. -- D: Sería siempre `undefined`. +- D: Sería siempre `undefined`.

Solución

@@ -2739,7 +2741,7 @@ Asignándole a `hasName` el valor de `name`, asignas a `hasName` cualquier valor ###### 87. ¿Cuál es el resultado? ```javascript -console.log("I want pizza"[0]); +console.log("I want pizza"[0]) ``` - A: `"""` @@ -2765,10 +2767,10 @@ Observa que este método no está soportado en IE7 y versiones anteriores. En es ```javascript function sum(num1, num2 = num1) { - console.log(num1 + num2); + console.log(num1 + num2) } -sum(10); +sum(10) ``` - A: `NaN` @@ -2793,14 +2795,14 @@ Si estuvieras intentando asignar un valor por defecto a un parámetro igual a ot ###### 89. ¿Cuál es el resultado? ```javascript -// module.js -export default () => "Hello world"; -export const name = "Lydia"; +// module.js +export default () => "Hello world" +export const name = "Lydia" -// index.js -import * as data from "./module"; +// index.js +import * as data from "./module" -console.log(data); +console.log(data) ``` - A: `{ default: function default(), name: "Lydia" }` @@ -2827,12 +2829,12 @@ El objeto `data` tiene una propiedad `default` para la exportación por defecto, ```javascript class Person { constructor(name) { - this.name = name; + this.name = name } } -const member = new Person("John"); -console.log(typeof member); +const member = new Person("John") +console.log(typeof member) ``` - A: `"class"` @@ -2849,11 +2851,11 @@ Las clases son azúcar sintáctico para los constructores de funciones. El equiv ```javascript function Person() { - this.name = name; + this.name = name } ``` -Llamar a un constructor de funciones con `new` crea una instancia de `Person`, `typeof` devuelve `"object"` con una instancia. `typeof member` devuelve `"object"`. +Llamar a un constructor de funciones con `new` crea una instancia de `Person`, `typeof` devuelve `"object"` con una instancia. `typeof member` devuelve `"object"`.

@@ -2863,9 +2865,9 @@ Llamar a un constructor de funciones con `new` crea una instancia de `Person`, ` ###### 91. ¿Cuál es el resultado? ```javascript -let newList = [1, 2, 3].push(4); +let newList = [1, 2, 3].push(4) -console.log(newList.push(5)); +console.log(newList.push(5)) ``` - A: `[1, 2, 3, 4, 5]` @@ -2891,18 +2893,17 @@ Después, intentamos usar el método `.push` en `newList`. Como `newList` es el ```javascript function giveLydiaPizza() { - return "Here is pizza!"; + return "Here is pizza!" } -const giveLydiaChocolate = () => - "Here's chocolate... now go hit the gym already."; +const giveLydiaChocolate = () => "Here's chocolate... now go hit the gym already." -console.log(giveLydiaPizza.prototype); -console.log(giveLydiaChocolate.prototype); +console.log(giveLydiaPizza.prototype) +console.log(giveLydiaChocolate.prototype) ``` -- A: `{ constructor: ...}` `{ constructor: ...}` -- B: `{}` `{ constructor: ...}` +- A: `{ constructor: ...}` `{ constructor: ...}` +- B: `{}` `{ constructor: ...}` - C: `{ constructor: ...}` `{}` - D: `{ constructor: ...}` `undefined` @@ -2923,16 +2924,16 @@ Las funciones regulares, como la función `giveLydiaPizza`, tienen la propiedad ```javascript const person = { name: "Lydia", - age: 21, -}; + age: 21 +} for (const [x, y] of Object.entries(person)) { - console.log(x, y); + console.log(x, y) } ``` - A: `name` `Lydia` y `age` `21` -- B: `["name", "Lydia"]` y `["age", 21]` +- B: `["name", "Lydia"]` y `["age", 21]` - C: `["name", "age"]` y `undefined` - D: `Error` @@ -2943,7 +2944,7 @@ for (const [x, y] of Object.entries(person)) { `Object.entries(person)` devuelve un array de arrays anidados, conteniendo claves y objetos: -`[ [ 'name', 'Lydia' ], [ 'age', 21 ] ]` +`[ [ 'name', 'Lydia' ], [ 'age', 21 ] ]` Usando el bucle `for-of`, podemos iterar sobre cada elemento en el array, los subarrays en este caso. Podemos desestructurar los subarrays instantáneamente en el bucle for-of, usando `const [x, y]`. `x` es igual al primer elemento del subarray, `y` es igual al segundo elemento en el subarray. @@ -2967,7 +2968,7 @@ getItems(["banana", "apple"], "pear", "orange") ``` - A: `["banana", "apple", "pear", "orange"]` -- B: `[["banana", "apple"], "pear", "orange"]` +- B: `[["banana", "apple"], "pear", "orange"]` - C: `["banana", "apple", ["pear"], "orange"]` - D: `SyntaxError` @@ -2980,14 +2981,13 @@ getItems(["banana", "apple"], "pear", "orange") ```javascript function getItems(fruitList, favoriteFruit, ...args) { - return [...fruitList, ...args, favoriteFruit]; + return [...fruitList, ...args, favoriteFruit] } -getItems(["banana", "apple"], "pear", "orange"); +getItems(["banana", "apple"], "pear", "orange") ``` El ejemplo de arriba sí que funciona. Devuelve el array `[ 'banana', 'apple', 'orange', 'pear' ]` -

@@ -2997,14 +2997,17 @@ El ejemplo de arriba sí que funciona. Devuelve el array `[ 'banana', 'apple', ' ```javascript function nums(a, b) { - if (a > b) console.log("a is bigger"); - else console.log("b is bigger"); - return; - a + b; + if + (a > b) + console.log('a is bigger') + else + console.log('b is bigger') + return + a + b } -console.log(nums(4, 2)); -console.log(nums(1, 2)); +console.log(nums(4, 2)) +console.log(nums(1, 2)) ``` - A: `a is bigger`, `6` y `b is bigger`, `3` @@ -3017,13 +3020,13 @@ console.log(nums(1, 2)); #### Answer: B -En JavaScript, no _tenemos_ que escribir el punto y coma (`;`) de forma explicita, sin embargo el motor de JavaScript todavía las añade al final de cada sentencia. Esto se denomina **Insercción automática de punto y coma**. Una sentencia puede ser, por ejemplo, variables, o palabras clave como `throw`, `return`, `break`, etc. +En JavaScript, no _tenemos_ que escribir el punto y coma (`;`) de forma explicita, sin embargo el motor de JavaScript todavía las añade al final de cada sentencia. Esto se denomina **Insercción automática de punto y coma**. Una sentencia puede ser, por ejemplo, variables, o palabras clave como `throw`, `return`, `break`, etc. Aqui, escribimos una sentencia `return`, y otra sentencia de valor `a + b` en una _nueva línea_. Sin embargo, como es una línea nueva, el motor no sabe que en realidad es el valor que queríamos devolver. En cambio, añadió automáticamente un punto y coma después de `return`. Puedes ver esto como: ```javascript -return; -a + b; + return; + a + b ``` Esto significa que nunca se alcanza `a + b`, ya que una función deja de ejecutarse después de la palabra clave` return`. Si no se devuelve ningún valor, como aquí, la función devuelve `undefined`. ¡Ten en cuenta que no hay inserción automática después de las sentencias `if/else`! @@ -3038,18 +3041,18 @@ Esto significa que nunca se alcanza `a + b`, ya que una función deja de ejecuta ```javascript class Person { constructor() { - this.name = "Lydia"; + this.name = "Lydia" } } Person = class AnotherPerson { constructor() { - this.name = "Sarah"; + this.name = "Sarah" } -}; +} -const member = new Person(); -console.log(member.name); +const member = new Person() +console.log(member.name) ``` - A: `"Lydia"` @@ -3073,11 +3076,11 @@ Podemos establecer clases iguales a otros constructures de clases/funciones. En ```javascript const info = { - [Symbol("a")]: "b", -}; + [Symbol('a')]: 'b' +} -console.log(info); -console.log(Object.keys(info)); +console.log(info) +console.log(Object.keys(info)) ``` - A: `{Symbol('a'): 'b'}` y `["{Symbol('a')"]` @@ -3124,13 +3127,13 @@ console.log(getUser(user)) La función `getList` recibe un array argumento. Entre los paréntesis de la función `getList`, desestructuramos este array de inmediato. Podrías ver esto como: -`[x, ...y] = [1, 2, 3, 4]` + `[x, ...y] = [1, 2, 3, 4]` Con el parámetro rest `...y`, ponemos todos los argumentos "restantes" en un array. Los argumentos restantes son `2`, `3` and `4` en este caso. El valor de `y` es un array, conteniendo todos los parámetros restantes. El valor de `x` es igual a `1` en este caso, por la tanto cuando registramos `[x, y]`, se imprime `[1, [2, 3, 4]]`. -La función `getUser` recibe un objeto. Con las funciones flecha, no _tenemos_ que escribir llaves cuando simplemente devolvemos un valor. Sin embargo, si quieres devolver un _objeto_ desde una función llave, tienes que escribir el objeto entre paréntesis, ¡de otra manera no se devuelve ningún valor! La siguiente función habría devuelto un objeto: + La función `getUser` recibe un objeto. Con las funciones flecha, no _tenemos_ que escribir llaves cuando simplemente devolvemos un valor. Sin embargo, si quieres devolver un _objeto_ desde una función llave, tienes que escribir el objeto entre paréntesis, ¡de otra manera no se devuelve ningún valor! La siguiente función habría devuelto un objeto: -`const getUser = user => ({ name: user.name, age: user.age })` +```const getUser = user => ({ name: user.name, age: user.age })``` Como no se devuelve ningún valor en este caso, la función devuelve `undefined`. @@ -3142,9 +3145,9 @@ Como no se devuelve ningún valor en este caso, la función devuelve `undefined` ###### 99. ¿Cuál es el resultado? ```javascript -const name = "Lydia"; +const name = "Lydia" -console.log(name()); +console.log(name()) ``` - A: `SyntaxError` @@ -3157,11 +3160,11 @@ console.log(name()); #### Answer: C -La variable `name` contiene el valor de una cadena, que no es una función, por lo tanto no puede invocar. +La variable `name` contiene el valor de una cadena, que no es una función, por lo tanto no puede invocar. Se genera una excepción de tipo TypeError cuando un valor no es del tipo esperado. JavaScript esperaba que `name` fuera una función ya que estamos intentando invocarla. Era una cadena sin embargo, por lo tanto se lanza una excepción del tipo TypeError: name is not a function! -Se lanzan errores del tipo SyntaxError cuando has escrito algo que no es válido JavaScript, pro ejemplo cuando has escrito `return` como `retrun`. +Se lanzan errores del tipo SyntaxError cuando has escrito algo que no es válido JavaScript, pro ejemplo cuando has escrito `return` como `retrun`. Se lanzan errores del tipo ReferenceError cuando JavaScript no puede encontrar una referencia a un valor al que estás intentando acceder.

@@ -3174,8 +3177,8 @@ Se lanzan errores del tipo ReferenceError cuando JavaScript no puede encontrar u ```javascript // 🎉✨ This is my 100th question! ✨🎉 -const output = `${[] && "Im"}possible! -You should${"" && `n't`} see a therapist after so much JavaScript lol`; +const output = `${[] && 'Im'}possible! +You should${'' && `n't`} see a therapist after so much JavaScript lol` ``` - A: `possible! You should see a therapist after so much JavaScript lol` @@ -3200,11 +3203,11 @@ You should${"" && `n't`} see a therapist after so much JavaScript lol`; ###### 101. ¿Cuál es el valor de la salida? ```javascript -const one = false || {} || null; -const two = null || false || ""; -const three = [] || 0 || true; +const one = (false || {} || null) +const two = (null || false || "") +const three = ([] || 0 || true) -console.log(one, two, three); +console.log(one, two, three) ``` - A: `false` `null` `[]` @@ -3233,20 +3236,20 @@ Con el operador `||`, podemos devolver el primer operando verdadero. Si todos lo ###### 102. ¿Cuál es el valor de la salida? ```javascript -const myPromise = () => Promise.resolve("I have resolved!"); +const myPromise = () => Promise.resolve('I have resolved!') function firstFunction() { - myPromise().then((res) => console.log(res)); - console.log("second"); + myPromise().then(res => console.log(res)) + console.log('second') } async function secondFunction() { - console.log(await myPromise()); - console.log("second"); + console.log(await myPromise()) + console.log('second') } -firstFunction(); -secondFunction(); +firstFunction() +secondFunction() ``` - A: `I have resolved!`, `second` y `I have resolved!`, `second` @@ -3261,13 +3264,13 @@ secondFunction(); Con una promesa, básicamente decimos _Quiero ejecutar esta función, pero la dejaré a un lado por ahora mientras se está ejecutando, ya que esto puede llevar un tiempo. Solo cuando se resuelve (o se rechaza) un cierto valor, y cuando la pila de llamadas está vacía, quiero usar este valor._ -Podemos obtener este valor con las palabras clave `.then` y `await` en una función `async`. Aunque podemos obtener el valor de una promesa tanto con `.then` como con` wait ', funcionan de manera un poco diferente. +Podemos obtener este valor con las palabras clave `.then` y `await` en una función `async`. Aunque podemos obtener el valor de una promesa tanto con `.then` como con` wait ', funcionan de manera un poco diferente. -En la función `firstFunction`, dejamos (de algún modo) a un lado la función myPromise mientras se estaba ejecutando, y seguimos ejecutando el otro código, que es `console.log('second')` en este caso. Luego, la función se resolvió con la cadena `I have resolved`, que luego se imprimió una vez que pila de llamadas quedó vacía. +En la función `firstFunction`, dejamos (de algún modo) a un lado la función myPromise mientras se estaba ejecutando, y seguimos ejecutando el otro código, que es `console.log('second')` en este caso. Luego, la función se resolvió con la cadena `I have resolved`, que luego se imprimió una vez que pila de llamadas quedó vacía. Con la palabra clave await en `secondFunction`, literalmente hacemos una pausa en la ejecución de una función asíncrona hasta que el valor se haya resuelto antes de pasar a la siguiente línea de código. -Esto significa que se esperó a que `myPromise` resolviera con el valor `I have resolved`, y solo una vez que eso sucedió, pasamos a la siguiente línea: `second` que se imprime. +Esto significa que se esperó a que `myPromise` resolviera con el valor `I have resolved`, y solo una vez que eso sucedió, pasamos a la siguiente línea: `second` que se imprime.

@@ -3277,14 +3280,14 @@ Esto significa que se esperó a que `myPromise` resolviera con el valor `I have ###### 103. ¿Cuál es el valor de la salida? ```javascript -const set = new Set(); +const set = new Set() -set.add(1); -set.add("Lydia"); -set.add({ name: "Lydia" }); +set.add(1) +set.add("Lydia") +set.add({ name: "Lydia" }) for (let item of set) { - console.log(item + 2); + console.log(item + 2) } ``` @@ -3298,11 +3301,11 @@ for (let item of set) { #### Answer: C -El operador `+` no solo se usa para sumar valores numéricos, sino que también podemos usarlo para concatenar cadenas. Cada vez que el motor de JavaScript ve que uno o más valores no son un número, coerce el número en una cadena. +El operador `+` no solo se usa para sumar valores numéricos, sino que también podemos usarlo para concatenar cadenas. Cada vez que el motor de JavaScript ve que uno o más valores no son un número, coerce el número en una cadena. El primero es `1`, que es un valor numérico. `1 + 2` devuelve el número 3. -Sin embargo, el segundo es la cadena `"Lydia"`. `"Lydia"` es una cadena y `2` es un número: `2` coerce a una cadena. `"Lydia"` y `"2"` son concatenados, cuyo resultado es la cadena `"Lydia2"`. +Sin embargo, el segundo es la cadena `"Lydia"`. `"Lydia"` es una cadena y `2` es un número: `2` coerce a una cadena. `"Lydia"` y `"2"` son concatenados, cuyo resultado es la cadena `"Lydia2"`. `{ name: "Lydia" }` es un objeto. Ni un número ni un objeto son una cadena, así que se convierten a cadena ambos. Cada vez que convertimos un objeto estandar, se convierte en `"[Object object]"`. `"[Object object]"` concatenado con `"2"` resulta en `"[Object object]2"`. @@ -3314,7 +3317,7 @@ Sin embargo, el segundo es la cadena `"Lydia"`. `"Lydia"` es una cadena y `2` es ###### 104. ¿Cuál es el valor? ```javascript -Promise.resolve(5); +Promise.resolve(5) ``` - A: `5` @@ -3329,7 +3332,7 @@ Promise.resolve(5); Podemos pasar cualquier tipo de valor que queramos a `Promise.resolve`, ya sea una promesa o no promesa. El método en sí mismo devuelve una promesa con el valor resuelto (``). Si pasas una función estandar, será una promesa resuelta con un valor normal. Si pasas una promesa, será una promesa resuelta con el valor resuelto de esa promesa pasada. -En este caso, acabamos de pasar el valor numérico `5`. Devuelve una promesa resuelta con el valor `5`. +En este caso, acabamos de pasar el valor numérico `5`. Devuelve una promesa resuelta con el valor `5`.

@@ -3341,15 +3344,15 @@ En este caso, acabamos de pasar el valor numérico `5`. Devuelve una promesa res ```javascript function compareMembers(person1, person2 = person) { if (person1 !== person2) { - console.log("Not the same!"); + console.log("Not the same!") } else { - console.log("They are the same!"); + console.log("They are the same!") } } -const person = { name: "Lydia" }; +const person = { name: "Lydia" } -compareMembers(person); +compareMembers(person) ``` - A: `Not the same!` @@ -3362,13 +3365,13 @@ compareMembers(person); #### Answer: B -Los objetos se pasan por referencia. Cuando verificamos la igualdad estricta de los objetos (`===`), estamos comparando sus referencias. +Los objetos se pasan por referencia. Cuando verificamos la igualdad estricta de los objetos (`===`), estamos comparando sus referencias. Establecemos el valor por defecto para `person2` igual al objeto `person`, y pasamos el objeto `person` como el valor de `person1`. Esto significa que ambos valores tienen una referencia al mismo punto en la memoria, por lo tanto, son iguales. -El bloque de código en la instrucción `else` se ejecuta, y se imprime `They are the same!`. +El bloque de código en la instrucción `else` se ejecuta, y se imprime `They are the same!`.

@@ -3384,11 +3387,11 @@ const colorConfig = { green: true, black: true, yellow: false, -}; +} -const colors = ["pink", "red", "blue"]; +const colors = ["pink", "red", "blue"] -console.log(colorConfig.colors[1]); +console.log(colorConfig.colors[1]) ``` - A: `true` @@ -3401,11 +3404,11 @@ console.log(colorConfig.colors[1]); #### Answer: D -En JavaScript, tenemos dos formas de acceder a las propiedades de un objeto: notación por corchetes o notación por punto. En este ejemplo, usamos la notación por punto (`colorConfig.colors`) en lugar de la notación por corchetes (`colorConfig["colors"]`). +En JavaScript, tenemos dos formas de acceder a las propiedades de un objeto: notación por corchetes o notación por punto. En este ejemplo, usamos la notación por punto (`colorConfig.colors`) en lugar de la notación por corchetes (`colorConfig["colors"]`). Con la notación por punto, JavaScript intenta encontrar la propiedad en el objeto con ese nombre exacto. En este ejemplo, JavaScript intenta encontrar una propiedad llamada `colors` en el objeto `colorConfig`. No hay propiedad llamada `colors`, por lo que devuelve `undefined`. Luego, intentamos acceder al valor del primer elemento usando `[1]`. No podemos hacer esto en un valor que sea `undefined`, por lo que lanza una expeción `TypeError`: `Cannot read property '1' of undefined`. -JavaScript interpreta (o descompone) las sentencias. Cuando usamos la notación por corchetes, ve el primer corchete de apertura `[` y continúa hasta que encuentra el corchete de cierre `]`. Solo entonces, evaluará la declaración. Si hubiéramos utilizado `colorConfig[colors[1]]`, habría devuelto el valor de la propiedad `red` del objeto `colorConfig`. +JavaScript interpreta (o descompone) las sentencias. Cuando usamos la notación por corchetes, ve el primer corchete de apertura `[` y continúa hasta que encuentra el corchete de cierre `]`. Solo entonces, evaluará la declaración. Si hubiéramos utilizado `colorConfig[colors[1]]`, habría devuelto el valor de la propiedad `red` del objeto `colorConfig`.

@@ -3415,7 +3418,7 @@ JavaScript interpreta (o descompone) las sentencias. Cuando usamos la notación ###### 107. ¿Cuál es el valor? ```javascript -console.log("❤️" === "❤️"); +console.log('❤️' === '❤️') ``` - A: `true` @@ -3426,7 +3429,7 @@ console.log("❤️" === "❤️"); #### Answer: A -Bajo el capó, los emojis son caracteres unicode. Los valores unicode para el emoji del corazón son `"U+2764 U+FE0F"`. Estos son siempre los mismos para los mismos emojis, por lo que estamos comparando dos cadenas iguales entre sí, lo que devuelve verdadero. +Bajo el capó, los emojis son caracteres unicode. Los valores unicode para el emoji del corazón son `"U+2764 U+FE0F"`. Estos son siempre los mismos para los mismos emojis, por lo que estamos comparando dos cadenas iguales entre sí, lo que devuelve verdadero.

@@ -3436,19 +3439,19 @@ Bajo el capó, los emojis son caracteres unicode. Los valores unicode para el em ###### 108. ¿Cuál de estos métodos modifica el array original? ```javascript -const emojis = ["✨", "🥑", "😍"]; +const emojis = ['✨', '🥑', '😍'] -emojis.map((x) => x + "✨"); -emojis.filter((x) => x !== "🥑"); -emojis.find((x) => x !== "🥑"); -emojis.reduce((acc, cur) => acc + "✨"); -emojis.slice(1, 2, "✨"); -emojis.splice(1, 2, "✨"); +emojis.map(x => x + '✨') +emojis.filter(x => x !== '🥑') +emojis.find(x => x !== '🥑') +emojis.reduce((acc, cur) => acc + '✨') +emojis.slice(1, 2, '✨') +emojis.splice(1, 2, '✨') ``` - A: `All of them` - B: `map` `reduce` `slice` `splice` -- C: `map` `slice` `splice` +- C: `map` `slice` `splice` - D: `splice`
Solución @@ -3456,7 +3459,7 @@ emojis.splice(1, 2, "✨"); #### Answer: D -Con el método `splice`, modificamos el array original eliminando, reemplazando o agregando elementos. En este caso, eliminamos 2 elementos desde el índice 1 (eliminamos `'🥑'` y `'😍'`) y agregamos el emoji ✨ en su lugar. +Con el método `splice`, modificamos el array original eliminando, reemplazando o agregando elementos. En este caso, eliminamos 2 elementos desde el índice 1 (eliminamos `'🥑'` y `'😍'`) y agregamos el emoji ✨ en su lugar. `map`, `filter` y `slice` devuelven un nuevo array, `find` devuelve un elemento, y `reduce` devuelve un valor reducido. @@ -3468,17 +3471,17 @@ Con el método `splice`, modificamos el array original eliminando, reemplazando ###### 109. ¿Cuál es el resultado? ```javascript -const food = ["🍕", "🍫", "🥑", "🍔"]; -const info = { favoriteFood: food[0] }; +const food = ['🍕', '🍫', '🥑', '🍔'] +const info = { favoriteFood: food[0] } -info.favoriteFood = "🍝"; +info.favoriteFood = '🍝' -console.log(food); +console.log(food) ``` - A: `['🍕', '🍫', '🥑', '🍔']` - B: `['🍝', '🍫', '🥑', '🍔']` -- C: `['🍝', '🍕', '🍫', '🥑', '🍔']` +- C: `['🍝', '🍕', '🍫', '🥑', '🍔']` - D: `ReferenceError`
Solución @@ -3486,7 +3489,7 @@ console.log(food); #### Answer: A -Establecemos el valor de la propiedad `favoriteFood` en el objeto` info` igual a la cadena con el emoji de la pizza, `'🍕'`. Una cadena es un tipo de dato primitivo. En JavaScript, los tipos de datos primitivos actúan por referencia +Establecemos el valor de la propiedad `favoriteFood` en el objeto` info` igual a la cadena con el emoji de la pizza, `'🍕'`. Una cadena es un tipo de dato primitivo. En JavaScript, los tipos de datos primitivos actúan por referencia En JavaScript, los tipos de datos primitivos (todo aquello que no es un objeto) interactúan por _valor_. En este caso, establecemos el valor de la propiedad `favoriteFood` en el objeto` info` igual al valor del primer elemento en el array `food`, la cadena del emoji de la pizza en este caso (`'🍕'`). Una cadena es un tipo de datos primitivo e interactúa por valor (consulte mi [artículo](https://www.theavocoder.com/complete-javascript/2018/12/21/by-value-vs-by-reference) si estás interesado en aprender más) @@ -3500,7 +3503,7 @@ Luego, cambiamos el valor de la propiedad `favoriteFood` en el objeto` info`. El ###### 110. ¿Qué hace este método? ```javascript -JSON.parse(); +JSON.parse() ``` - A: Parses JSON to a JavaScript value @@ -3513,20 +3516,20 @@ JSON.parse(); #### Answer: A -Con el método `JSON.parse()`, podemos convertir la cadena de texto en formato JSON a un valor en JavaScript. +Con el método `JSON.parse()`, podemos convertir la cadena de texto en formato JSON a un valor en JavaScript. ```javascript // Stringifying a number into valid JSON, then parsing the JSON string to a JavaScript value: -const jsonNumber = JSON.stringify(4); // '4' -JSON.parse(jsonNumber); // 4 +const jsonNumber = JSON.stringify(4) // '4' +JSON.parse(jsonNumber) // 4 // Stringifying an array value into valid JSON, then parsing the JSON string to a JavaScript value: -const jsonArray = JSON.stringify([1, 2, 3]); // '[1, 2, 3]' -JSON.parse(jsonArray); // [1, 2, 3] +const jsonArray = JSON.stringify([1, 2, 3]) // '[1, 2, 3]' +JSON.parse(jsonArray) // [1, 2, 3] // Stringifying an object into valid JSON, then parsing the JSON string to a JavaScript value: -const jsonArray = JSON.stringify({ name: "Lydia" }); // '{"name":"Lydia"}' -JSON.parse(jsonArray); // { name: 'Lydia' } +const jsonArray = JSON.stringify({ name: "Lydia" }) // '{"name":"Lydia"}' +JSON.parse(jsonArray) // { name: 'Lydia' } ```

@@ -3534,17 +3537,17 @@ JSON.parse(jsonArray); // { name: 'Lydia' } --- -###### 111. ¿Cuál es el resultado? +###### 111. ¿Cuál es el resultado? ```javascript -let name = "Lydia"; +let name = 'Lydia' function getName() { - console.log(name); - let name = "Sarah"; + console.log(name) + let name = 'Sarah' } -getName(); +getName() ``` - A: Lydia @@ -3557,20 +3560,20 @@ getName(); #### Answer: D -Cada función tiene su propio _contexto de ejecución_ (o _ámbito_). La función `getName` primero mira dentro de su propio contexto (ámbito) para ver si contiene la variable `name` a la que estamos intentando acceder. En este caso, la función `getName` contiene su propia variable `name`: declaramos la variable `name` con la palabra clave` let`, y con el valor de `'Sarah'`. +Cada función tiene su propio _contexto de ejecución_ (o _ámbito_). La función `getName` primero mira dentro de su propio contexto (ámbito) para ver si contiene la variable `name` a la que estamos intentando acceder. En este caso, la función `getName` contiene su propia variable `name`: declaramos la variable `name` con la palabra clave` let`, y con el valor de `'Sarah'`. -Las variables con la palabra clave `let` (y `const`) se mueven al comienzo (hoisting), pero a diferencia de `var`, no se inicializan. No son accesibles antes de la línea en la que las declaramos (inicializamos). Esto se llama la "zona muerta temporal". Cuando intentamos acceder a las variables antes de que se declaren, JavaScript genera una excepción del tipo `ReferenceError`. +Las variables con la palabra clave `let` (y `const`) se mueven al comienzo (hoisting), pero a diferencia de `var`, no se inicializan. No son accesibles antes de la línea en la que las declaramos (inicializamos). Esto se llama la "zona muerta temporal". Cuando intentamos acceder a las variables antes de que se declaren, JavaScript genera una excepción del tipo `ReferenceError`. -Si no hubiéramos declarado la variable `name` dentro de la función `getName`, el motor de JavaScript habría mirado hacia abajo _ámbito encadenado_. El alcance externo tiene una variable llamada `name` con el valor de `Lydia`. En ese caso, habría imprimido `Lydia`. +Si no hubiéramos declarado la variable `name` dentro de la función `getName`, el motor de JavaScript habría mirado hacia abajo _ámbito encadenado_. El alcance externo tiene una variable llamada `name` con el valor de `Lydia`. En ese caso, habría imprimido `Lydia`. ```javascript -let name = "Lydia"; +let name = 'Lydia' function getName() { - console.log(name); + console.log(name) } -getName(); // Lydia +getName() // Lydia ```

@@ -3582,18 +3585,18 @@ getName(); // Lydia ```javascript function* generatorOne() { - yield ["a", "b", "c"]; + yield ['a', 'b', 'c']; } function* generatorTwo() { - yield* ["a", "b", "c"]; + yield* ['a', 'b', 'c']; } -const one = generatorOne(); -const two = generatorTwo(); +const one = generatorOne() +const two = generatorTwo() -console.log(one.next().value); -console.log(two.next().value); +console.log(one.next().value) +console.log(two.next().value) ``` - A: `a` y `a` @@ -3611,17 +3614,17 @@ Con la palabra clave `yield`, cedemos valores en una función generadora. Con la En la función `generatorOne`, cedemos todo el array `['a', 'b', 'c']` usando la palabra clave `yield`. El valor de la propiedad `value` en el objeto devuelto por el método `next` en `one` (`one.next().value`) es igual a todo el array `['a', 'b', 'c']`. ```javascript -console.log(one.next().value); // ['a', 'b', 'c'] -console.log(one.next().value); // undefined +console.log(one.next().value) // ['a', 'b', 'c'] +console.log(one.next().value) // undefined ``` -En la función `generatorTwo`, usamos la palabra clave `yield*`. Esto significa que el primer valor cedido de `two` es igual al primer valor cedido en el iterador. El iterador es el array `['a', 'b', 'c']`. El primer valor producido es `a`, por lo que la primera vez que llamamos a `two.next().value`, se devuelve `a`. +En la función `generatorTwo`, usamos la palabra clave `yield*`. Esto significa que el primer valor cedido de `two` es igual al primer valor cedido en el iterador. El iterador es el array `['a', 'b', 'c']`. El primer valor producido es `a`, por lo que la primera vez que llamamos a `two.next().value`, se devuelve `a`. ```javascript -console.log(two.next().value); // 'a' -console.log(two.next().value); // 'b' -console.log(two.next().value); // 'c' -console.log(two.next().value); // undefined +console.log(two.next().value) // 'a' +console.log(two.next().value) // 'b' +console.log(two.next().value) // 'c' +console.log(two.next().value) // undefined ```

@@ -3632,7 +3635,7 @@ console.log(two.next().value); // undefined ###### 113. ¿Cuál es el resultado? ```javascript -console.log(`${((x) => x)("I love")} to program`); +console.log(`${(x => x)('I love')} to program`) ``` - A: `I love to program` @@ -3645,7 +3648,7 @@ console.log(`${((x) => x)("I love")} to program`); #### Answer: A -Las expresiones dentro de las plantillas de cadena de texto se evalúan primero. Esto significa que la cadena contendrá el valor devuelto de la expresión, la función invocada inmediatamente `(x => x)('I love')` en este caso. Pasamos el valor `'I love'` como argumento para la función de flecha `x => x`. `x` es igual a `'I love'`, que se devuelve tal cual. Esto da como resultado `I love to program`. +Las expresiones dentro de las plantillas de cadena de texto se evalúan primero. Esto significa que la cadena contendrá el valor devuelto de la expresión, la función invocada inmediatamente `(x => x)('I love')` en este caso. Pasamos el valor `'I love'` como argumento para la función de flecha `x => x`. `x` es igual a `'I love'`, que se devuelve tal cual. Esto da como resultado `I love to program`.

@@ -3657,11 +3660,11 @@ Las expresiones dentro de las plantillas de cadena de texto se evalúan primero. ```javascript let config = { alert: setInterval(() => { - console.log("Alert!"); - }, 1000), -}; + console.log('Alert!') + }, 1000) +} -config = null; +config = null ``` - A: The `setInterval` callback won't be invoked @@ -3684,17 +3687,17 @@ Normalmente, cuando establecemos objetos iguales a `null`, esos objetos se recog ###### 115. ¿Qué método(s) devolverá el valor `'Hello world!'`? ```javascript -const myMap = new Map(); -const myFunc = () => "greeting"; +const myMap = new Map() +const myFunc = () => 'greeting' -myMap.set(myFunc, "Hello world!"); +myMap.set(myFunc, 'Hello world!') //1 -myMap.get("greeting"); +myMap.get('greeting') //2 -myMap.get(myFunc); +myMap.get(myFunc) //3 -myMap.get(() => "greeting"); +myMap.get(() => 'greeting') ``` - A: 1 @@ -3707,10 +3710,10 @@ myMap.get(() => "greeting"); #### Answer: B -Al agregar un par clave/valor utilizando el método `set`, la clave será el valor del primer argumento pasado a la función `set`, y el valor será el segundo argumento pasado a la función `set`. La clave es la _función_ `() => 'greeting'` en este caso, y el valor `'Hello world'`. `myMap` ahora es `{ () => 'greeting' => 'Hello world!' }`. +Al agregar un par clave/valor utilizando el método `set`, la clave será el valor del primer argumento pasado a la función `set`, y el valor será el segundo argumento pasado a la función `set`. La clave es la _función_ `() => 'greeting'` en este caso, y el valor `'Hello world'`. `myMap` ahora es `{ () => 'greeting' => 'Hello world!' }`. 1 es incorrecto, ya que la clave no es `'greeting'` sino `() => 'greeting'`. -3 es incorrecto, ya que estamos creando una nueva función pasándola como parámetro al método `get`. El objeto interactúa por _referencia_. Las funciones son objetos, por eso dos funciones nunca son estrictamente iguales, aunque sean idénticas: tienen una referencia a un punto diferente en la memoria. +3 es incorrecto, ya que estamos creando una nueva función pasándola como parámetro al método `get`. El objeto interactúa por _referencia_. Las funciones son objetos, por eso dos funciones nunca son estrictamente iguales, aunque sean idénticas: tienen una referencia a un punto diferente en la memoria.

@@ -3722,19 +3725,19 @@ Al agregar un par clave/valor utilizando el método `set`, la clave será el val ```javascript const person = { name: "Lydia", - age: 21, -}; + age: 21 +} -const changeAge = (x = { ...person }) => (x.age += 1); +const changeAge = (x = { ...person }) => x.age += 1 const changeAgeAndName = (x = { ...person }) => { - x.age += 1; - x.name = "Sarah"; -}; + x.age += 1 + x.name = "Sarah" +} -changeAge(person); -changeAgeAndName(); +changeAge(person) +changeAgeAndName() -console.log(person); +console.log(person) ``` - A: `{name: "Sarah", age: 22}` @@ -3747,7 +3750,7 @@ console.log(person); #### Answer: C -Tanto las funciones `changeAge` como `changeAgeAndName` tienen un parámetro por defecto, a saber, un objeto _nuevo_ creado `{ ...person }`. Este objeto tiene copias de todos los pares clave/valor en el objeto `person`. +Tanto las funciones `changeAge` como `changeAgeAndName` tienen un parámetro por defecto, a saber, un objeto _nuevo_ creado `{ ...person }`. Este objeto tiene copias de todos los pares clave/valor en el objeto `person`. Primero, invocamos la función `changeAge` y le pasamos el objeto `person` como argumento. Esta función aumenta el valor de la propiedad `age` en 1. `person` ahora es `{name: "Lydia", age: 22}`. diff --git a/fr-FR/README_fr-FR.md b/fr-FR/README_fr-FR.md index cbdbee30..cce10323 100644 --- a/fr-FR/README_fr-FR.md +++ b/fr-FR/README_fr-FR.md @@ -19,7 +19,6 @@ Les réponses se trouvent dans les sections repliées en dessous des questions, - [🇳🇱 Nederlands](../nl-NL/README.md) - [🇵🇱 Polski](../pl-PL/README.md) - [🇧🇷 Português Brasil](../pt-BR/README_pt_BR.md) -- [🇷o Română](../ro-RO/README.ro.md) - [🇷🇺 Русский](../ru-RU/README.md) - [🇽🇰 Shqip](../sq-KS/README_sq_KS.md) - [🇹🇭 ไทย](../th-TH/README-th_TH.md) @@ -101,7 +100,7 @@ const shape = { diameter() { return this.radius * 2; }, - perimeter: () => 2 * Math.PI * this.radius, + perimeter: () => 2 * Math.PI * this.radius }; shape.diameter(); @@ -158,12 +157,12 @@ La chaîne de caractère `'Lydia'` est une valeur considérée comme vraie _(tru ```javascript const bird = { - size: "small", + size: "small" }; const mouse = { name: "Mickey", - small: true, + small: true }; ``` @@ -359,7 +358,7 @@ function Person(firstName, lastName) { } const member = new Person("Lydia", "Hallie"); -Person.getFullName = function () { +Person.getFullName = function() { return `${this.firstName} ${this.lastName}`; }; @@ -379,7 +378,7 @@ console.log(member.getFullName()); Vous ne pouvez pas ajouter de propriétés à un constructeur comme pour des objets normaux. Si vous voulez ajouter une fonctionnalité pour tous les objets en une fois, vous devez utiliser le prototype. Donc dans ce cas, ```js -Person.prototype.getFullName = function () { +Person.prototype.getFullName = function() { return `${this.firstName} ${this.lastName}`; }; ``` @@ -835,7 +834,7 @@ String.prototype.giveLydiaPizza = () => { const name = "Lydia"; -console.log(name.giveLydiaPizza()); +console.log(name.giveLydiaPizza()) ``` - A: `"Just give Lydia pizza already!"` @@ -947,7 +946,9 @@ C'est ici qu'une boucle d'événement commence à fonctionner. La **boucle d'év ```html
- +
``` @@ -973,7 +974,9 @@ L'élément imbriqué le plus profond qui a provoqué l'événement est la cible ```html
-

Click here!

+

+ Click here! +

``` @@ -1198,7 +1201,7 @@ JavaScript n'a que des types et des objets primitifs. Les types primitifs sont `boolean`, `null`, `undefined`, `bigint`, `number`, `string` et `symbol`. -Ce qui différencie une primitive d'un objet, c'est que les primitives n'ont aucune propriété ou méthode. Cependant, vous remarquerez que `'foo'.toUpperCase()` est évalué à `'FOO'` et n'entraîne pas de `TypeError`. En effet, lorsque vous essayez d'accéder à une propriété ou à une méthode sur une primitive telle qu'une chaîne, JavaScript encapsule implicitement l'objet à l'aide de l'une des classes d'encapsulation, à savoir `String`, puis supprime immédiatement l'encapsulation après l'évaluation de l'expression. Toutes les primitives à l'exception de `null` et` undefined` présentent ce comportement. +Ce qui différencie une primitive d'un objet, c'est que les primitives n'ont aucune propriété ou méthode. Cependant, vous remarquerez que `'foo'.toUpperCase()` est évalué à `'FOO'` et n'entraîne pas de `TypeError`. En effet, lorsque vous essayez d'accéder à une propriété ou à une méthode sur une primitive telle qu'une chaîne, JavaScript encapsule implicitement l'objet à l'aide de l'une des classes d'encapsulation, à savoir `String`, puis supprime immédiatement l'encapsulation après l'évaluation de l'expression. Toutes les primitives à l'exception de `null` et` undefined` présentent ce comportement.

@@ -1208,10 +1211,7 @@ Ce qui différencie une primitive d'un objet, c'est que les primitives n'ont auc ###### 40. Quelle est la sortie ? ```javascript -[ - [0, 1], - [2, 3], -].reduce( +[[0, 1], [2, 3]].reduce( (acc, cur) => { return acc.concat(cur); }, @@ -1359,7 +1359,7 @@ const secondPromise = new Promise((res, rej) => { setTimeout(res, 100, "two"); }); -Promise.race([firstPromise, secondPromise]).then((res) => console.log(res)); +Promise.race([firstPromise, secondPromise]).then(res => console.log(res)); ``` - A: `"one"` @@ -1423,7 +1423,7 @@ Nous modifions seulement la valeur de la variable `person`, et non le premier é ```javascript const person = { name: "Lydia", - age: 21, + age: 21 }; for (const item in person) { @@ -1503,7 +1503,7 @@ Seuls les premiers nombres de la chaîne sont renvoyés. Basé sur la base dix ( ###### 50. Quelle est la sortie ? ```javascript -[1, 2, 3].map((num) => { +[1, 2, 3].map(num => { if (typeof num === "number") return; return num * 2; }); @@ -1680,7 +1680,7 @@ class Dog { } } -Dog.prototype.bark = function () { +Dog.prototype.bark = function() { console.log(`Woof I am ${this.name}`); }; @@ -1908,7 +1908,7 @@ Les propriétés ajoutées à l'aide de la méthode `defineProperty` sont immuab const settings = { username: "lydiahallie", level: 19, - health: 90, + health: 90 }; const data = JSON.stringify(settings, ["level", "health"]); @@ -1942,7 +1942,7 @@ Si le remplaçant est une _fonction_, cette fonction est appelée sur chaque pro let num = 10; const increaseNumber = () => num++; -const increasePassedNumber = (number) => number++; +const increasePassedNumber = number => number++; const num1 = increaseNumber(); const num2 = increasePassedNumber(num1); @@ -1963,7 +1963,7 @@ console.log(num2); L'opérateur arithmétique `++` _renvoie en premier_ la valeur de l'opérande, _puis incrémente_ la valeur de l'opérande. La valeur de `num1` est égale à `10`, puisque la fonction `increaseNumber` renvoie d'abord la valeur de `num`, qui correspond à `10`, et augmente la valeur de `num` par la suite. -`num2` est égal à `10`, puisque nous avons passé `num1` à la commande `increasePassedNumber`. `number` est égal à `10` (la valeur de `num1`). Encore une fois, l'opérateur arithmétique `++` _renvoie d'abord_ la valeur de l'opérande, puis incrémente\_ la valeur de l'opérande. La valeur de `nombre` est `10`, donc `num2` est égal à `10`. +`num2` est égal à `10`, puisque nous avons passé `num1` à la commande `increasePassedNumber`. `number` est égal à `10` (la valeur de `num1`). Encore une fois, l'opérateur arithmétique `++` _renvoie d'abord_ la valeur de l'opérande, puis incrémente_ la valeur de l'opérande. La valeur de `nombre` est `10`, donc `num2` est égal à `10`.

@@ -1997,7 +1997,7 @@ multiply(value); Dans ES6, nous pouvons initialiser les paramètres avec une valeur par défaut. La valeur du paramètre sera la valeur par défaut, si aucune autre valeur n'a été passée à la fonction, ou si la valeur du paramètre est `"undefined"`. Dans ce cas, nous répartissons les propriétés de l'objet `value` dans un nouvel objet, donc `x` a la valeur par défaut `{number: 10}`. -L'argument par défaut est évalué at _call time_! Chaque fois que nous appelons la fonction, un a _new_ object créé. Nous invoquons la fonction `multiply` les deux premières fois sans passer de valeur: `x` a la valeur par défaut `{number: 10}`. Nous enregistrons ensuite la valeur multipliée de ce nombre, qui est `20`. +L'argument par défaut est évalué at _call time_! Chaque fois que nous appelons la fonction, un a _new_ object créé. Nous invoquons la fonction `multiply` les deux premières fois sans passer de valeur: `x` a la valeur par défaut `{number: 10}`. Nous enregistrons ensuite la valeur multipliée de ce nombre, qui est `20`. La troisième fois que nous invoquons multiplier, nous passons un argument: l'objet appelé `value`. L'opérateur `* =` est en fait un raccourci pour `x.number = x.number * 2`: nous modifions la valeur de `x.number`, et enregistrons la valeur multipliée `20`. diff --git a/id-ID/README.md b/id-ID/README.md index 3da87c42..26a566cc 100644 --- a/id-ID/README.md +++ b/id-ID/README.md @@ -1,10 +1,10 @@

Pertanyaan JavaScript

---- + --- -Saya post pertanyaan pilihan ganda ke [Instagram](https://www.instagram.com/theavocoder) **stories** saya, yang saya post juga di sini ! update terakhir: December 24th + Saya post pertanyaan pilihan ganda ke [Instagram](https://www.instagram.com/theavocoder) **stories** saya, yang saya post juga di sini ! update terakhir: December 24th -Mulai tingkat dasar ke mahir: tes seberapa paham kamu tentang javascript, segarkan sedikit pengetahuan kamu, atau bersiap-siap untuk coding interview kamu! :muscle: :rocket: Saya update repo ini secara berkala dengan pertanyaan baru. Saya masukkan jawaban dibagian yang **tersembunyi** di bawah pertanyaan, cukup klik pada bagian itu untuk menampilkannya. Pertanyaan ini hanya untuk bersenang-senang, Semoga berhasil :heart: + Mulai tingkat dasar ke mahir: tes seberapa paham kamu tentang javascript, segarkan sedikit pengetahuan kamu, atau bersiap-siap untuk coding interview kamu! :muscle: :rocket: Saya update repo ini secara berkala dengan pertanyaan baru. Saya masukkan jawaban dibagian yang **tersembunyi** di bawah pertanyaan, cukup klik pada bagian itu untuk menampilkannya. Pertanyaan ini hanya untuk bersenang-senang, Semoga berhasil :heart: Jangan sungkan untuk terhubung dengan saya! 😊
Instagram || Twitter || LinkedIn || Blog @@ -29,7 +29,6 @@ Jangan sungkan untuk terhubung dengan saya! 😊
- [🇳🇱 Nederlands](../nl-NL/README.md) - [🇵🇱 Polski](../pl-PL/README.md) - [🇧🇷 Português Brasil](../pt-BR/README_pt_BR.md) -- [🇷o Română](../ro-RO/README.ro.md) - [🇷🇺 Русский](../ru-RU/README.md) - [🇽🇰 Shqip](../sq-KS/README_sq_KS.md) - [🇹🇭 ไทย](../th-TH/README-th_TH.md) @@ -50,7 +49,7 @@ Jangan sungkan untuk terhubung dengan saya! 😊
function sayHi() { console.log(name); console.log(age); - var name = "Lydia"; + var name = 'Lydia'; let age = 21; } @@ -70,7 +69,6 @@ sayHi(); Di dalam function, kita membuat sebuah variabel `name` dan variabel tersebut di deklarasikan menggunakan `var`. Artinya variable tersebut di hoisting (dalam fase pembuatan ini menggunakan memory penyimpanan) dengan isi standar-nya `undefined`, saat javascript mengeksekusi baris code pembuatan variabel-nya. variabel `name` isinya masih undefined, jadi isi dari variabel tersebut `undefined` Mendeklarasikan varibel menggunakan `let` (dan `const`) juga terkena hoisting, tidak seperti `var`, variabel declaration `let` dan `const` tidak ditentukan isi standar-nya. `let` dan `const` tidak bisa diakses sebelum di tentukan dulu isi-nya. Kejadian ini disebut "temporal dead zone". Saat kita mencoba memanggil variabel yang belum ditentukan isi-nya, Javascript mengeluarkan error `ReferenceError`. -

@@ -97,10 +95,9 @@ for (let i = 0; i < 3; i++) { #### Jawaban: C -Karena antrean peristiwa di JavaScript, fungsi callback `setTimeout` disebut _after_ loop telah dijalankan. Karena variabel `i` di loop pertama dideklarasikan menggunakan kata kunci` var`, nilai ini adalah global. Selama perulangan, kita menambah nilai `i` sebesar `1` setiap kali, menggunakan operator unary`++`. Pada saat fungsi callback `setTimeout` dipanggil,` i` sama dengan `3` di contoh pertama. +Karena antrean peristiwa di JavaScript, fungsi callback `setTimeout` disebut _after_ loop telah dijalankan. Karena variabel `i` di loop pertama dideklarasikan menggunakan kata kunci` var`, nilai ini adalah global. Selama perulangan, kita menambah nilai `i` sebesar `1` setiap kali, menggunakan operator unary` ++ `. Pada saat fungsi callback `setTimeout` dipanggil,` i` sama dengan `3` di contoh pertama. Pada perulangan kedua, variabel `i` dideklarasikan menggunakan kata kunci` let`: variabel yang dideklarasikan dengan kata kunci `let` (dan` const`) memiliki cakupan blok (blok adalah apa saja di antara `{}`). Selama setiap iterasi, `i` akan memiliki nilai baru, dan setiap nilai dicakup di dalam loop. -

@@ -146,7 +143,7 @@ Tidak ada nilai 'radius' pada objek itu, yang mengembalikan 'tidak ditentukan'. ```javascript +true; -!"Lydia"; +!'Lydia'; ``` - A: `1` dan `false` @@ -160,7 +157,8 @@ Tidak ada nilai 'radius' pada objek itu, yang mengembalikan 'tidak ditentukan'. Tia unary plus mencoba mengonversi operan menjadi angka. `true` adalah` 1`, dan `false` adalah` 0`. -String "'Lydia'`adalah nilai yang benar. Apa yang sebenarnya kami tanyakan adalah "apakah nilai kebenaran ini salah?". Ini mengembalikan`salah`. +String "'Lydia'` adalah nilai yang benar. Apa yang sebenarnya kami tanyakan adalah "apakah nilai kebenaran ini salah?". Ini mengembalikan `salah`. +

@@ -171,11 +169,11 @@ String "'Lydia'`adalah nilai yang benar. Apa yang sebenarnya kami tanyakan adala ```javascript const bird = { - size: "small", + size: 'small', }; const mouse = { - name: "Mickey", + name: 'Mickey', small: true, }; ``` @@ -189,7 +187,6 @@ const mouse = {

#### Jawaban: A - Pada JavaScript, semua kunci objek adalah string (kecuali jika itu berupa Simbol). Meskipun kita mungkin tidak mengetiknya sebagai string, tetap saja mereka selalu berubah menjadi string didalamnya. JavaScript menginterpretasikan (atau membuka) pernyataan-pernyataan. Saat kita menggunakan notasi kurung siku, ia melihat kurung buka pertama `[` dan terus berjalan sampai menemukan kurung tutup `]`. Baru setelah itu akan mengevaluasi pernyataannya. `mouse[bird.size]`: Pertama, ini mengevaluasi `bird.size`, yang mana `"small"`. `mouse["small"]` mengembalikan nilai `true`. @@ -204,11 +201,11 @@ Namun, dengan notasi dot (.), hal ini tidak terjadi. `mouse` tidak memiliki kunc ###### 6. Apa yang akan tampil? ```javascript -let c = { greeting: "Hey!" }; +let c = { greeting: 'Hey!' }; let d; d = c; -c.greeting = "Hello"; +c.greeting = 'Hello'; console.log(d.greeting); ``` @@ -278,13 +275,13 @@ class Chameleon { return this.newColor; } - constructor({ newColor = "green" } = {}) { + constructor({ newColor = 'green' } = {}) { this.newColor = newColor; } } -const freddie = new Chameleon({ newColor: "purple" }); -console.log(freddie.colorChange("orange")); +const freddie = new Chameleon({ newColor: 'purple' }); +console.log(freddie.colorChange('orange')); ``` - A: `orange` @@ -334,10 +331,10 @@ Untuk menghindari hal ini, kita bisa menggunakan `" use strict "`. Ini memastika ```javascript function bark() { - console.log("Woof!"); + console.log('Woof!'); } -bark.animal = "dog"; +bark.animal = 'dog'; ``` - A: Nothing, this is totally fine! @@ -367,8 +364,8 @@ function Person(firstName, lastName) { this.lastName = lastName; } -const member = new Person("Lydia", "Hallie"); -Person.getFullName = function () { +const member = new Person('Lydia', 'Hallie'); +Person.getFullName = function() { return `${this.firstName} ${this.lastName}`; }; @@ -388,7 +385,7 @@ console.log(member.getFullName()); Anda tidak dapat menambahkan properti ke constructor seperti yang Anda lakukan dengan objek biasa. Jika Anda ingin menambahkan fitur ke semua objek sekaligus, Anda harus menggunakan prototipe sebagai gantinya. Jadi dalam kasus ini: ```js -Person.prototype.getFullName = function () { +Person.prototype.getFullName = function() { return `${this.firstName} ${this.lastName}`; }; ``` @@ -408,8 +405,8 @@ function Person(firstName, lastName) { this.lastName = lastName; } -const lydia = new Person("Lydia", "Hallie"); -const sarah = Person("Sarah", "Smith"); +const lydia = new Person('Lydia', 'Hallie'); +const sarah = Person('Sarah', 'Smith'); console.log(lydia); console.log(sarah); @@ -479,7 +476,7 @@ function sum(a, b) { return a + b; } -sum(1, "2"); +sum(1, '2'); ``` - A: `NaN` @@ -546,7 +543,7 @@ function getPersonInfo(one, two, three) { console.log(three); } -const person = "Lydia"; +const person = 'Lydia'; const age = 21; getPersonInfo`${person} is ${age} years old`; @@ -573,9 +570,9 @@ Jika Anda menggunakan literal template yang diberi tag, nilai argumen pertama se ```javascript function checkAge(data) { if (data === { age: 18 }) { - console.log("You are an adult!"); + console.log('You are an adult!'); } else if (data == { age: 18 }) { - console.log("You are still an adult."); + console.log('You are still an adult.'); } else { console.log(`Hmm.. You don't have an age I guess`); } @@ -635,7 +632,7 @@ Parameter sisanya (`... args`.) Memungkinkan kita "mengumpulkan" semua argumen y ```javascript function getAge() { - "use strict"; + 'use strict'; age = 21; console.log(age); } @@ -663,7 +660,7 @@ Dengan `" use strict "`, Anda dapat memastikan bahwa Anda tidak mendeklarasikan ###### 21. What's value of `sum`? ```javascript -const sum = eval("10*10+5"); +const sum = eval('10*10+5'); ``` - A: `105` @@ -686,7 +683,7 @@ const sum = eval("10*10+5"); ###### 22. Sampai berapa lama kah cool_secret dapat diakses? ```javascript -sessionStorage.setItem("cool_secret", 123); +sessionStorage.setItem('cool_secret', 123); ``` - A: Selamanya, data tersebut tidak akan hilang. @@ -739,12 +736,12 @@ Anda tidak dapat melakukan ini dengan `let` atau `const` karena mereka block-sco ###### 24. Apa yang akan tampil? ```javascript -const obj = { 1: "a", 2: "b", 3: "c" }; +const obj = { 1: 'a', 2: 'b', 3: 'c' }; const set = new Set([1, 2, 3, 4, 5]); -obj.hasOwnProperty("1"); +obj.hasOwnProperty('1'); obj.hasOwnProperty(1); -set.has("1"); +set.has('1'); set.has(1); ``` @@ -770,7 +767,7 @@ It doesn't work that way for a set. There is no `'1'` in our set: `set.has('1')` ###### 25. Apa yang akan tampil? ```javascript -const obj = { a: "one", b: "two", a: "three" }; +const obj = { a: 'one', b: 'two', a: 'three' }; console.log(obj); ``` @@ -839,12 +836,12 @@ Pernyataan `continue` melewatkan iterasi jika kondisi tertentu mengembalikan `tr ```javascript String.prototype.giveLydiaPizza = () => { - return "Just give Lydia pizza already!"; + return 'Just give Lydia pizza already!'; }; -const name = "Lydia"; +const name = 'Lydia'; -console.log(name.giveLydiaPizza()); +console.log(name.giveLydiaPizza()) ``` - A: `"Just give Lydia pizza already!"` @@ -868,8 +865,8 @@ console.log(name.giveLydiaPizza()); ```javascript const a = {}; -const b = { key: "b" }; -const c = { key: "c" }; +const b = { key: 'b' }; +const c = { key: 'c' }; a[b] = 123; a[c] = 456; @@ -901,9 +898,9 @@ Then, we log `a[b]`, which is actually `a["object Object"]`. We just set that to ###### 30. Apa yang akan tampil? ```javascript -const foo = () => console.log("First"); -const bar = () => setTimeout(() => console.log("Second")); -const baz = () => console.log("Third"); +const foo = () => console.log('First'); +const bar = () => setTimeout(() => console.log('Second')); +const baz = () => console.log('Third'); bar(); foo(); @@ -956,7 +953,9 @@ Di sinilah serangkaian acara mulai bekerja. Sebuah **event loop** (putaran kejad ```html

- +
``` @@ -982,7 +981,9 @@ The deepest nested element that caused the event is the target of the event. You ```html
-

Click here!

+

+ Click here! +

``` @@ -1006,7 +1007,7 @@ If we click `p`, we see two logs: `p` and `div`. During event propagation, there ###### 33. Apa yang akan tampil? ```javascript -const person = { name: "Lydia" }; +const person = { name: 'Lydia' }; function sayHi(age) { return `${this.name} is ${age}`; @@ -1069,8 +1070,8 @@ FYI: there are only 7 built-in types: `null`, `undefined`, `boolean`, `number`, ```javascript 0; new Number(0); -(""); -(" "); +(''); +(' '); new Boolean(false); undefined; ``` @@ -1217,14 +1218,11 @@ What differentiates a primitive from an object is that primitives do not have an ###### 40. Apa yang akan tampil? ```javascript -[ - [0, 1], - [2, 3], -].reduce( +[[0, 1], [2, 3]].reduce( (acc, cur) => { return acc.concat(cur); }, - [1, 2] + [1, 2], ); ``` @@ -1251,7 +1249,7 @@ Then, `[1, 2, 0, 1]` is `acc` and `[2, 3]` is `cur`. We concatenate them, and ge ```javascript !!null; -!!""; +!!''; !!1; ``` @@ -1279,7 +1277,7 @@ Then, `[1, 2, 0, 1]` is `acc` and `[2, 3]` is `cur`. We concatenate them, and ge ###### 42. What does the `setInterval` method return in the browser? ```javascript -setInterval(() => console.log("Hi"), 1000); +setInterval(() => console.log('Hi'), 1000); ``` - A: a unique id @@ -1302,7 +1300,7 @@ Itu adalah mengembalikan sebuah id unik. id unik dapat digunakan untuk menghapus ###### 43. What does this return? ```javascript -[..."Lydia"]; +[...'Lydia']; ``` - A: `["L", "y", "d", "i", "a"]` @@ -1361,14 +1359,14 @@ Then, we invoke the function again with the `next()` method. It starts to contin ```javascript const firstPromise = new Promise((res, rej) => { - setTimeout(res, 500, "one"); + setTimeout(res, 500, 'one'); }); const secondPromise = new Promise((res, rej) => { - setTimeout(res, 100, "two"); + setTimeout(res, 100, 'two'); }); -Promise.race([firstPromise, secondPromise]).then((res) => console.log(res)); +Promise.race([firstPromise, secondPromise]).then(res => console.log(res)); ``` - A: `"one"` @@ -1391,7 +1389,7 @@ When we pass multiple promises to the `Promise.race` method, it resolves/rejects ###### 46. Apa yang akan tampil? ```javascript -let person = { name: "Lydia" }; +let person = { name: 'Lydia' }; const members = [person]; person = null; @@ -1431,7 +1429,7 @@ We are only modifying the value of the `person` variable, and not the first elem ```javascript const person = { - name: "Lydia", + name: 'Lydia', age: 21, }; @@ -1460,7 +1458,7 @@ With a `for-in` loop, we can iterate through object keys, in this case `name` an ###### 48. Apa yang akan tampil? ```javascript -console.log(3 + 4 + "5"); +console.log(3 + 4 + '5'); ``` - A: `"345"` @@ -1487,7 +1485,7 @@ Operator associativity is the order in which the compiler evaluates the expressi ###### 49. What's the value of `num`? ```javascript -const num = parseInt("7*6", 10); +const num = parseInt('7*6', 10); ``` - A: `42` @@ -1512,8 +1510,8 @@ Only the first numbers in the string is returned. Based on the _radix_ (the seco ###### 50. What's the output`? ```javascript -[1, 2, 3].map((num) => { - if (typeof num === "number") return; +[1, 2, 3].map(num => { + if (typeof num === 'number') return; return num * 2; }); ``` @@ -1541,12 +1539,12 @@ However, we don’t return a value. When we don’t return a value from the func ```javascript function getInfo(member, year) { - member.name = "Lydia"; - year = "1998"; + member.name = 'Lydia'; + year = '1998'; } -const person = { name: "Sarah" }; -const birthYear = "1997"; +const person = { name: 'Sarah' }; +const birthYear = '1997'; getInfo(person, birthYear); @@ -1578,15 +1576,15 @@ The value of `person` is an object. The argument `member` has a (copied) referen ```javascript function greeting() { - throw "Hello world!"; + throw 'Hello world!'; } function sayHi() { try { const data = greeting(); - console.log("It worked!", data); + console.log('It worked!', data); } catch (e) { - console.log("Oh no an error:", e); + console.log('Oh no an error:', e); } } @@ -1616,8 +1614,8 @@ With the `catch` statement, we can specify what to do if an exception is thrown ```javascript function Car() { - this.make = "Lamborghini"; - return { make: "Maserati" }; + this.make = 'Lamborghini'; + return { make: 'Maserati' }; } const myCar = new Car(); @@ -1689,11 +1687,11 @@ class Dog { } } -Dog.prototype.bark = function () { +Dog.prototype.bark = function() { console.log(`Woof I am ${this.name}`); }; -const pet = new Dog("Mara"); +const pet = new Dog('Mara'); pet.bark(); @@ -1758,7 +1756,7 @@ export default counter; ```javascript // index.js -import myCounter from "./counter"; +import myCounter from './counter'; myCounter += 1; @@ -1779,6 +1777,7 @@ Modul yang diimpor adalah _read-only_: Anda tidak dapat mengubah modul yang diim Ketika kita mencoba untuk menambah nilai `myCounter`, itu melemparkan kesalahan: `myCounter` adalah baca-saja dan tidak dapat dimodifikasi. +

@@ -1787,7 +1786,7 @@ Ketika kita mencoba untuk menambah nilai `myCounter`, itu melemparkan kesalahan: ###### 58. Apa yang akan tampil? ```javascript -const name = "Lydia"; +const name = 'Lydia'; age = 21; console.log(delete name); @@ -1858,7 +1857,7 @@ This means that the value of `y` is equal to the first value in the array, which ###### 60. Apa yang akan tampil? ```javascript -const user = { name: "Lydia", age: 21 }; +const user = { name: 'Lydia', age: 21 }; const admin = { admin: true, ...user }; console.log(admin); @@ -1884,9 +1883,9 @@ It's possible to combine objects using the spread operator `...`. It lets you cr ###### 61. Apa yang akan tampil? ```javascript -const person = { name: "Lydia" }; +const person = { name: 'Lydia' }; -Object.defineProperty(person, "age", { value: 21 }); +Object.defineProperty(person, 'age', { value: 21 }); console.log(person); console.log(Object.keys(person)); @@ -1915,12 +1914,12 @@ Properties added using the `defineProperty` method are immutable by default. You ```javascript const settings = { - username: "lydiahallie", + username: 'lydiahallie', level: 19, health: 90, }; -const data = JSON.stringify(settings, ["level", "health"]); +const data = JSON.stringify(settings, ['level', 'health']); console.log(data); ``` @@ -1951,7 +1950,7 @@ If the replacer is a _function_, this function gets called on every property in let num = 10; const increaseNumber = () => num++; -const increasePassedNumber = (number) => number++; +const increasePassedNumber = number => number++; const num1 = increaseNumber(); const num2 = increasePassedNumber(num1); @@ -2107,12 +2106,12 @@ The `Labrador` class receives two arguments, `name` since it extends `Dog`, and ```javascript // index.js -console.log("running index.js"); -import { sum } from "./sum.js"; +console.log('running index.js'); +import { sum } from './sum.js'; console.log(sum(1, 2)); // sum.js -console.log("running sum.js"); +console.log('running sum.js'); export const sum = (a, b) => a + b; ``` @@ -2140,7 +2139,7 @@ This is a difference between `require()` in CommonJS and `import`! With `require ```javascript console.log(Number(2) === Number(2)); console.log(Boolean(false) === Boolean(false)); -console.log(Symbol("foo") === Symbol("foo")); +console.log(Symbol('foo') === Symbol('foo')); ``` - A: `true`, `true`, `false` @@ -2163,7 +2162,7 @@ Every Symbol is entirely unique. The purpose of the argument passed to the Symbo ###### 69. Apa yang akan tampil? ```javascript -const name = "Lydia Hallie"; +const name = 'Lydia Hallie'; console.log(name.padStart(13)); console.log(name.padStart(2)); ``` @@ -2190,7 +2189,7 @@ If the argument passed to the `padStart` method is smaller than the length of th ###### 70. Apa yang akan tampil? ```javascript -console.log("🥑" + "💻"); +console.log('🥑' + '💻'); ``` - A: `"🥑💻"` @@ -2214,11 +2213,11 @@ With the `+` operator, you can concatenate strings. In this case, we are concate ```javascript function* startGame() { - const answer = yield "Do you love JavaScript?"; - if (answer !== "Yes") { + const answer = yield 'Do you love JavaScript?'; + if (answer !== 'Yes') { return "Oh wow... Guess we're gone here"; } - return "JavaScript loves you back ❤️"; + return 'JavaScript loves you back ❤️'; } const game = startGame(); @@ -2286,7 +2285,7 @@ In this case, the string is `Hello\nworld`, which gets logged. ```javascript async function getData() { - return await Promise.resolve("I made it!"); + return await Promise.resolve('I made it!'); } const data = getData(); @@ -2323,7 +2322,7 @@ function addToList(item, list) { return list.push(item); } -const result = addToList("apple", ["banana"]); +const result = addToList('apple', ['banana']); console.log(result); ``` @@ -2383,7 +2382,7 @@ Since `shape` is frozen, and since the value of `x` is not an object, we cannot ###### 76. Apa yang akan tampil? ```javascript -const { name: myName } = { name: "Lydia" }; +const { name: myName } = { name: 'Lydia' }; console.log(name); ``` @@ -2439,7 +2438,7 @@ The `sum` function always returns the same result. If we pass `1` and `2`, it wi ```javascript const add = () => { const cache = {}; - return (num) => { + return num => { if (num in cache) { return `From cache! ${cache[num]}`; } else { @@ -2484,7 +2483,7 @@ The third time, we pass `5 * 2` to the function which gets evaluated to `10`. Th ###### 79. What is the output? ```javascript -const myLifeSummedUp = ["☕", "💻", "🍷", "🍫"]; +const myLifeSummedUp = ['☕', '💻', '🍷', '🍫']; for (let item in myLifeSummedUp) { console.log(item); @@ -2580,13 +2579,13 @@ Pada kasus ini, juka kita tidak mengisi nilai atau mengisi `undefined`, `name` a ###### 82. What is the output? ```javascript -var status = "😎"; +var status = '😎'; setTimeout(() => { - const status = "😍"; + const status = '😍'; const data = { - status: "🥑", + status: '🥑', getStatus() { return this.status; }, @@ -2620,12 +2619,12 @@ With the `call` method, we can change the object to which the `this` keyword ref ```javascript const person = { - name: "Lydia", + name: 'Lydia', age: 21, }; let city = person.city; -city = "Amsterdam"; +city = 'Amsterdam'; console.log(person); ``` @@ -2689,9 +2688,9 @@ Variables with the `const` and `let` keyword are _block-scoped_. A block is anyt ###### 85. What kind of information would get logged? ```javascript -fetch("https://www.website.com/api/user/1") - .then((res) => res.json()) - .then((res) => console.log(res)); +fetch('https://www.website.com/api/user/1') + .then(res => res.json()) + .then(res => console.log(res)) ``` - A: The result of the `fetch` method. @@ -2745,7 +2744,7 @@ By setting `hasName` equal to `name`, you set `hasName` equal to whatever value ###### 87. Apa yang akan tampil? ```javascript -console.log("I want pizza"[0]); +console.log('I want pizza'[0]); ``` - A: `"""` @@ -2800,11 +2799,11 @@ If you're trying to set a default parameter's value equal to a parameter which i ```javascript // module.js -export default () => "Hello world"; -export const name = "Lydia"; +export default () => 'Hello world'; +export const name = 'Lydia'; // index.js -import * as data from "./module"; +import * as data from './module'; console.log(data); ``` @@ -2837,7 +2836,7 @@ class Person { } } -const member = new Person("John"); +const member = new Person('John'); console.log(typeof member); ``` @@ -2897,7 +2896,7 @@ Then, we try to use the `.push` method on `newList`. Since `newList` is the nume ```javascript function giveLydiaPizza() { - return "Here is pizza!"; + return 'Here is pizza!'; } const giveLydiaChocolate = () => @@ -2928,7 +2927,7 @@ Regular functions, such as the `giveLydiaPizza` function, have a `prototype` pro ```javascript const person = { - name: "Lydia", + name: 'Lydia', age: 21, }; @@ -2988,7 +2987,7 @@ function getItems(fruitList, favoriteFruit, ...args) { return [...fruitList, ...args, favoriteFruit]; } -getItems(["banana", "apple"], "pear", "orange"); +getItems(['banana', 'apple'], 'pear', 'orange'); ``` The above example works. This returns the array `[ 'banana', 'apple', 'orange', 'pear' ]` @@ -3002,8 +3001,8 @@ The above example works. This returns the array `[ 'banana', 'apple', 'orange', ```javascript function nums(a, b) { - if (a > b) console.log("a is bigger"); - else console.log("b is bigger"); + if (a > b) console.log('a is bigger'); + else console.log('b is bigger'); return; a + b; } @@ -3043,13 +3042,13 @@ This means that `a + b` is never reached, since a function stops running after t ```javascript class Person { constructor() { - this.name = "Lydia"; + this.name = 'Lydia'; } } Person = class AnotherPerson { constructor() { - this.name = "Sarah"; + this.name = 'Sarah'; } }; @@ -3078,7 +3077,7 @@ Kita dapat mengatur kelas yang sama dengan kelas / fungsi konstruktor lainnya. D ```javascript const info = { - [Symbol("a")]: "b", + [Symbol('a')]: 'b', }; console.log(info); @@ -3097,7 +3096,7 @@ console.log(Object.keys(info)); Simbol bukanlah merupakan suatu _enumerable_. Metode Object.keys akan mengembalikan semua properti kunci _enumerable_ pada sebuah objek. Simbol tidak akan terlihat, dan array kosong dikembalikan. Saat mencatat seluruh objek, semua properti akan terlihat, bahkan yang bukan non-enumerable. -Ini adalah salah satu dari banyak kualitas simbol: Disamping selain mewakili nilai yang sepenuhnya unik (yang mencegah terjadinya benturan nama yang tidak disengaja pada objek, misalnya saat bekerja dengan 2 library yang ingin menambahkan properti ke objek yang sama), anda juga dapat "menyembunyikan" properti pada objek dengan cara ini (meskipun tidak seluruhnya. Anda masih dapat mengakses simbol menggunakan metode `Object.getOwnPropertySymbols()`). +Ini adalah salah satu dari banyak kualitas simbol: Disamping selain mewakili nilai yang sepenuhnya unik (yang mencegah terjadinya benturan nama yang tidak disengaja pada objek, misalnya saat bekerja dengan 2 library yang ingin menambahkan properti ke objek yang sama), anda juga dapat "menyembunyikan" properti pada objek dengan cara ini (meskipun tidak seluruhnya. Anda masih dapat mengakses simbol menggunakan metode `Object.getOwnPropertySymbols()`).

@@ -3131,7 +3130,7 @@ Fungsi `getList` menerima array sebagai argumennya. Di antara tanda kurung pada `[x, ...y] = [1, 2, 3, 4]` -Dengan parameter sisa `...y`, kita akan meletakkan semua argumen "yang tersisa" dalam array. Dalam kasus ini argumen yang tersisa adalah `2`, `3` dan `4`. Nilai dari `y` merupakan suatu array, yang berisi semua parameter lainnya. Pada kasus ini nilai dari `x` sama dengan `1`, jadi saat kita mencatat `[x, y]`, maka catatannya `[1, [2, 3, 4]]`. +Dengan parameter sisa `...y`, kita akan meletakkan semua argumen "yang tersisa" dalam array. Dalam kasus ini argumen yang tersisa adalah `2`, `3` dan `4`. Nilai dari `y` merupakan suatu array, yang berisi semua parameter lainnya. Pada kasus ini nilai dari `x` sama dengan `1`, jadi saat kita mencatat `[x, y]`, maka catatannya `[1, [2, 3, 4]]`. Fungsi `getUser` menerima sebuah objek. Dengan fungsi tanda panah, kita tidak _perlu_ menulis tanda kurung kurawal jika hanya mengembalikan satu nilai. Namun, jika anda mengembalikan nilai _object_ dari fungsi tanda panah, Anda harus menuliskannya di antara tanda kurung, jika tidak maka tidak ada nilai yang dikembalikan! Fungsi berikut akan mengembalikan sebuah objek: @@ -3147,7 +3146,7 @@ Karena tidak ada nilai yang dikembalikan dalam kasus ini, maka fungsi akan menge ###### 99. Apa yang akan tampil? ```javascript -const name = "Lydia"; +const name = 'Lydia'; console.log(name()); ``` @@ -3179,8 +3178,8 @@ ReferenceErrors muncul ketika JavaScript tidak dapat menemukan nilai referensi k ```javascript // 🎉✨ This is my 100th question! ✨🎉 -const output = `${[] && "Im"}possible! -You should${"" && `n't`} see a therapist after so much JavaScript lol`; +const output = `${[] && 'Im'}possible! +You should${'' && `n't`} see a therapist after so much JavaScript lol`; ``` - A: `possible! You should see a therapist after so much JavaScript lol` @@ -3206,7 +3205,7 @@ You should${"" && `n't`} see a therapist after so much JavaScript lol`; ```javascript const one = false || {} || null; -const two = null || false || ""; +const two = null || false || ''; const three = [] || 0 || true; console.log(one, two, three); @@ -3238,16 +3237,16 @@ With the `||` operator, we can return the first truthy operand. If all values ar ###### 102. What's the value of output? ```javascript -const myPromise = () => Promise.resolve("I have resolved!"); +const myPromise = () => Promise.resolve('I have resolved!'); function firstFunction() { - myPromise().then((res) => console.log(res)); - console.log("second"); + myPromise().then(res => console.log(res)); + console.log('second'); } async function secondFunction() { console.log(await myPromise()); - console.log("second"); + console.log('second'); } firstFunction(); @@ -3285,8 +3284,8 @@ This means that it waited for the `myPromise` to resolve with the value `I have const set = new Set(); set.add(1); -set.add("Lydia"); -set.add({ name: "Lydia" }); +set.add('Lydia'); +set.add({ name: 'Lydia' }); for (let item of set) { console.log(item + 2); @@ -3346,13 +3345,13 @@ In this case, we just passed the numerical value `5`. It returns a resolved prom ```javascript function compareMembers(person1, person2 = person) { if (person1 !== person2) { - console.log("Not the same!"); + console.log('Not the same!'); } else { - console.log("They are the same!"); + console.log('They are the same!'); } } -const person = { name: "Lydia" }; +const person = { name: 'Lydia' }; compareMembers(person); ``` @@ -3391,7 +3390,7 @@ const colorConfig = { yellow: false, }; -const colors = ["pink", "red", "blue"]; +const colors = ['pink', 'red', 'blue']; console.log(colorConfig.colors[1]); ``` @@ -3420,7 +3419,7 @@ JavaScript interprets (or unboxes) statements. When we use bracket notation, it ###### 107. Apakah hasil nilai dibawah ini ? ```javascript -console.log("❤️" === "❤️"); +console.log('❤️' === '❤️'); ``` - A: `true` @@ -3473,10 +3472,10 @@ Metode `splice`, akan memodifikasi array aslinya dengan cara menghapus, menggant ###### 109. Apa yang akan tampil? ```javascript -const food = ["🍕", "🍫", "🥑", "🍔"]; +const food = ['🍕', '🍫', '🥑', '🍔']; const info = { favoriteFood: food[0] }; -info.favoriteFood = "🍝"; +info.favoriteFood = '🍝'; console.log(food); ``` @@ -3530,7 +3529,7 @@ const jsonArray = JSON.stringify([1, 2, 3]); // '[1, 2, 3]' JSON.parse(jsonArray); // [1, 2, 3] // Stringifying an object into valid JSON, then parsing the JSON string to a JavaScript value: -const jsonArray = JSON.stringify({ name: "Lydia" }); // '{"name":"Lydia"}' +const jsonArray = JSON.stringify({ name: 'Lydia' }); // '{"name":"Lydia"}' JSON.parse(jsonArray); // { name: 'Lydia' } ``` @@ -3542,11 +3541,11 @@ JSON.parse(jsonArray); // { name: 'Lydia' } ###### 111. Apa yang akan tampil? ```javascript -let name = "Lydia"; +let name = 'Lydia'; function getName() { console.log(name); - let name = "Sarah"; + let name = 'Sarah'; } getName(); @@ -3569,7 +3568,7 @@ Variables with the `let` keyword (and `const`) are hoisted, but unlike `var`, do If we wouldn't have declared the `name` variable within the `getName` function, the javascript engine would've looked down the _scope chain_. The outer scope has a variable called `name` with the value of `Lydia`. In that case, it would've logged `Lydia`. ```javascript -let name = "Lydia"; +let name = 'Lydia'; function getName() { console.log(name); @@ -3587,11 +3586,11 @@ getName(); // Lydia ```javascript function* generatorOne() { - yield ["a", "b", "c"]; + yield ['a', 'b', 'c']; } function* generatorTwo() { - yield* ["a", "b", "c"]; + yield* ['a', 'b', 'c']; } const one = generatorOne(); @@ -3637,7 +3636,7 @@ console.log(two.next().value); // undefined ###### 113. Apa yang akan tampil? ```javascript -console.log(`${((x) => x)("I love")} to program`); +console.log(`${(x => x)('I love')} to program`); ``` - A: `I love to program` @@ -3662,7 +3661,7 @@ Expressions within template literals are evaluated first. This means that the st ```javascript let config = { alert: setInterval(() => { - console.log("Alert!"); + console.log('Alert!'); }, 1000), }; @@ -3690,16 +3689,16 @@ Normally when we set objects equal to `null`, those objects get _garbage collect ```javascript const myMap = new Map(); -const myFunc = () => "greeting"; +const myFunc = () => 'greeting'; -myMap.set(myFunc, "Hello world!"); +myMap.set(myFunc, 'Hello world!'); //1 -myMap.get("greeting"); +myMap.get('greeting'); //2 myMap.get(myFunc); //3 -myMap.get(() => "greeting"); +myMap.get(() => 'greeting'); ``` - A: 1 @@ -3726,14 +3725,14 @@ When adding a key/value pair using the `set` method, the key will be the value o ```javascript const person = { - name: "Lydia", + name: 'Lydia', age: 21, }; const changeAge = (x = { ...person }) => (x.age += 1); const changeAgeAndName = (x = { ...person }) => { x.age += 1; - x.name = "Sarah"; + x.name = 'Sarah'; }; changeAge(person); @@ -3792,7 +3791,7 @@ With the spread operator `...`, we can _spread_ iterables to individual elements ```javascript let num = 1; -const list = ["🥳", "🤠", "🥰", "🤪"]; +const list = ['🥳', '🤠', '🥰', '🤪']; console.log(list[(num += 1)]); ``` @@ -3818,11 +3817,11 @@ With the `+=` operand, we're incrementing the value of `num` by `1`. `num` had t ```javascript const person = { - firstName: "Lydia", - lastName: "Hallie", + firstName: 'Lydia', + lastName: 'Hallie', pet: { - name: "Mara", - breed: "Dutch Tulip Hound", + name: 'Mara', + breed: 'Dutch Tulip Hound', }, getFullName() { return `${this.firstName} ${this.lastName}`; @@ -3860,10 +3859,10 @@ With the optional chaining operator `?.`, we no longer have to explicitly check ###### 120. Apa yang akan tampil? ```javascript -const groceries = ["banana", "apple", "peanuts"]; +const groceries = ['banana', 'apple', 'peanuts']; -if (groceries.indexOf("banana")) { - console.log("We have to buy bananas!"); +if (groceries.indexOf('banana')) { + console.log('We have to buy bananas!'); } else { console.log(`We don't have to buy bananas!`); } @@ -3919,10 +3918,10 @@ The `language` method is a `setter`. Setters don't hold an actual value, their p ###### 122. Apa yang akan tampil? ```javascript -const name = "Lydia Hallie"; +const name = 'Lydia Hallie'; -console.log(!typeof name === "object"); -console.log(!typeof name === "string"); +console.log(!typeof name === 'object'); +console.log(!typeof name === 'string'); ``` - A: `false` `true` @@ -3947,7 +3946,7 @@ console.log(!typeof name === "string"); ###### 123. Apa yang akan tampil? ```javascript -const add = (x) => (y) => (z) => { +const add = x => y => z => { console.log(x, y, z); return x + y + z; }; @@ -4073,8 +4072,8 @@ With the `Intl.NumberFormat` method, we can format numeric values to any locale. ###### 127. Apa yang akan tampil? ```javascript -const spookyItems = ["👻", "🎃", "🕸"]; -({ item: spookyItems[3] } = { item: "💀" }); +const spookyItems = ['👻', '🎃', '🕸']; +({ item: spookyItems[3] } = { item: '💀' }); console.log(spookyItems); ``` @@ -4099,7 +4098,7 @@ By destructuring objects, we can unpack values from the right-hand object, and a ###### 128. Apa yang akan tampil? ```javascript -const name = "Lydia Hallie"; +const name = 'Lydia Hallie'; const age = 21; console.log(Number.isNaN(name)); @@ -4135,7 +4134,7 @@ const randomValue = 21; function getInfo() { console.log(typeof randomValue); - const randomValue = "Lydia Hallie"; + const randomValue = 'Lydia Hallie'; } getInfo(); @@ -4161,7 +4160,7 @@ Variables declared with the `const` keyword are not referencable before their in ###### 130. Apa yang akan tampil? ```javascript -const myPromise = Promise.resolve("Woah some cool data"); +const myPromise = Promise.resolve('Woah some cool data'); (async () => { try { @@ -4169,7 +4168,7 @@ const myPromise = Promise.resolve("Woah some cool data"); } catch { throw new Error(`Oops didn't work`); } finally { - console.log("Oh finally!"); + console.log('Oh finally!'); } })(); ``` @@ -4194,7 +4193,7 @@ In the `try` block, we're logging the awaited value of the `myPromise` variable: ###### 131. Apa yang akan tampil? ```javascript -const emojis = ["🥑", ["✨", "✨", ["🍕", "🍕"]]]; +const emojis = ['🥑', ['✨', '✨', ['🍕', '🍕']]]; console.log(emojis.flat(1)); ``` @@ -4267,19 +4266,19 @@ We invoke the `counterTwo.increment()`, which sets the `count` to `3`. Then, we ###### 133. Apa yang akan tampil? ```javascript -const myPromise = Promise.resolve(Promise.resolve("Promise!")); +const myPromise = Promise.resolve(Promise.resolve('Promise!')); function funcOne() { - myPromise.then((res) => res).then((res) => console.log(res)); - setTimeout(() => console.log("Timeout!", 0)); - console.log("Last line!"); + myPromise.then(res => res).then(res => console.log(res)); + setTimeout(() => console.log('Timeout!', 0)); + console.log('Last line!'); } async function funcTwo() { const res = await myPromise; console.log(await res); - setTimeout(() => console.log("Timeout!", 0)); - console.log("Last line!"); + setTimeout(() => console.log('Timeout!', 0)); + console.log('Last line!'); } funcOne(); @@ -4320,7 +4319,7 @@ export default function sum(x) { } // index.js -import * as sum from "./sum"; +import * as sum from './sum'; ``` - A: `sum(4)` @@ -4337,12 +4336,12 @@ With the asterisk `*`, we import all exported values from that file, both defaul ```javascript // info.js -export const name = "Lydia"; +export const name = 'Lydia'; export const age = 21; -export default "I love JavaScript"; +export default 'I love JavaScript'; // index.js -import * as info from "./info"; +import * as info from './info'; console.log(info); ``` @@ -4373,13 +4372,13 @@ We can invoke this function, by calling `sum.default` ```javascript const handler = { - set: () => console.log("Added a new property!"), - get: () => console.log("Accessed a property!"), + set: () => console.log('Added a new property!'), + get: () => console.log('Accessed a property!'), }; const person = new Proxy({}, handler); -person.name = "Lydia"; +person.name = 'Lydia'; person.name; ``` @@ -4409,7 +4408,7 @@ Then, we access a property value on the proxy object, the `get` property on the ###### 136. Which of the following will modify the `person` object? ```javascript -const person = { name: "Lydia Hallie" }; +const person = { name: 'Lydia Hallie' }; Object.seal(person); ``` @@ -4437,9 +4436,9 @@ However, you can still modify the value of existing properties. ```javascript const person = { - name: "Lydia Hallie", + name: 'Lydia Hallie', address: { - street: "100 Main St", + street: '100 Main St', }, }; @@ -4469,9 +4468,9 @@ However, it only _shallowly_ freezes the object, meaning that only _direct_ prop ```javascript const person = { - name: "Lydia Hallie", + name: 'Lydia Hallie', address: { - street: "100 Main St", + street: '100 Main St', }, }; @@ -4500,7 +4499,7 @@ However, it only _shallowly_ freezes the object, meaning that only _direct_ prop ###### 139. Apa yang akan tampil? ```javascript -const add = (x) => x + x; +const add = x => x + x; function myFunc(num = 2, value = add(num)) { console.log(num, value); @@ -4533,21 +4532,21 @@ Then, we invoked `myFunc(3)` and passed the value `3` as the value for the argum ```javascript class Counter { - #number = 10; + #number = 10 increment() { - this.#number++; + this.#number++ } getNum() { - return this.#number; + return this.#number } } -const counter = new Counter(); -counter.increment(); +const counter = new Counter() +counter.increment() -console.log(counter.#number); +console.log(counter.#number) ``` - A: `10` @@ -4571,8 +4570,8 @@ In ES2020, we can add private variables in classes by using the `#`. We cannot a ```javascript const teams = [ - { name: "Team 1", members: ["Paul", "Lisa"] }, - { name: "Team 2", members: ["Laura", "Tim"] }, + { name: 'Team 1', members: ['Paul', 'Lisa'] }, + { name: 'Team 2', members: ['Laura', 'Tim'] }, ]; function* getMembers(members) { @@ -4615,8 +4614,8 @@ Jika kita telah menulis `yield`, `return yield`, atau `return`, maka seluruh fun ```javascript const person = { - name: "Lydia Hallie", - hobbies: ["coding"], + name: 'Lydia Hallie', + hobbies: ['coding'], }; function addHobby(hobby, hobbies = person.hobbies) { @@ -4624,9 +4623,9 @@ function addHobby(hobby, hobbies = person.hobbies) { return hobbies; } -addHobby("running", []); -addHobby("dancing"); -addHobby("baking", person.hobbies); +addHobby('running', []); +addHobby('dancing'); +addHobby('baking', person.hobbies); console.log(person.hobbies); ``` @@ -4695,11 +4694,11 @@ Kita membuat variabel `pet` yang merupakan turunan dari class `Flamingo`. Saat k ###### 144. Manakah dari pilihan di bawah ini yang salah? ```javascript -const emojis = ["🎄", "🎅🏼", "🎁", "⭐"]; +const emojis = ['🎄', '🎅🏼', '🎁', '⭐']; -/* 1 */ emojis.push("🦌"); +/* 1 */ emojis.push('🦌'); /* 2 */ emojis.splice(0, 2); -/* 3 */ emojis = [...emojis, "🥂"]; +/* 3 */ emojis = [...emojis, '🥂']; /* 4 */ emojis.length = 0; ``` @@ -4742,7 +4741,7 @@ const person = { #### Jawaban: C Objek tidak dapat diulang secara default. Sebuah iterable adalah sebuah iterable jika protokol iterator ada. Kita dapat menambahkan ini secara manual dengan menambahkan simbol iterator -`[Symbol.iterator]`, dimana harus mengembalikan objek generator, sebagai contoh dengan membuat fungsi generator `*[Symbol.iterator]() {}`. Fungsi generator ini harus menghasilkan `Object.values` dari objek `person` jika kita mau mengembalikan array `["Lydia Hallie", 21]`: `yield* Object.values(this)`. + `[Symbol.iterator]`, dimana harus mengembalikan objek generator, sebagai contoh dengan membuat fungsi generator `*[Symbol.iterator]() {}`. Fungsi generator ini harus menghasilkan `Object.values` dari objek `person` jika kita mau mengembalikan array `["Lydia Hallie", 21]`: `yield* Object.values(this)`.

@@ -4755,11 +4754,11 @@ Objek tidak dapat diulang secara default. Sebuah iterable adalah sebuah iterable let count = 0; const nums = [0, 1, 2, 3]; -nums.forEach((num) => { - if (num) count += 1; -}); +nums.forEach(num => { + if (num) count += 1 +}) -console.log(count); +console.log(count) ``` - A: 1 @@ -4783,19 +4782,19 @@ Pernyataan `if` didalam perulangan `forEach` akan mengecek apakah nilai dari `nu ```javascript class Calc { - constructor() { - this.count = 0; - } + constructor() { + this.count = 0 + } - increase() { - this.count++; - } + increase() { + this.count ++ + } } -const calc = new Calc(); -new Calc().increase(); +const calc = new Calc() +new Calc().increase() -console.log(calc.count); +console.log(calc.count) ``` - A: `0` @@ -4819,25 +4818,25 @@ Kami mengatur variabel `calc` sama dengan instance baru dari class `Calc`. Kemud ```javascript const user = { - email: "e@mail.com", - password: "12345", -}; + email: "e@mail.com", + password: "12345" +} const updateUser = ({ email, password }) => { - if (email) { - Object.assign(user, { email }); - } + if (email) { + Object.assign(user, { email }) + } - if (password) { - user.password = password; - } + if (password) { + user.password = password + } - return user; -}; + return user +} -const updatedUser = updateUser({ email: "new@email.com" }); +const updatedUser = updateUser({ email: "new@email.com" }) -console.log(updatedUser === user); +console.log(updatedUser === user) ``` - A: `false` @@ -4858,13 +4857,12 @@ Fungsi `updateUser` memperbarui nilai properti `email` dan `password` pada pengg --- ###### 149. Apa hasilnya? - ```javascript -const fruit = ["🍌", "🍊", "🍎"]; +const fruit = ['🍌', '🍊', '🍎'] -fruit.slice(0, 1); -fruit.splice(0, 1); -fruit.unshift("🍇"); +fruit.slice(0, 1) +fruit.splice(0, 1) +fruit.unshift('🍇') ``` - A: `['🍌', '🍊', '🍎']` @@ -4890,13 +4888,13 @@ Akhirnya, kita memanggil metode `unshift` pada array `fruit`, yang memodifikasi ```javascript const animals = {}; -let dog = { emoji: "🐶" }; -let cat = { emoji: "🐈" }; +let dog = { emoji: '🐶' } +let cat = { emoji: '🐈' } -animals[dog] = { ...dog, name: "Mara" }; -animals[cat] = { ...cat, name: "Sara" }; +animals[dog] = { ...dog, name: "Mara" } +animals[cat] = { ...cat, name: "Sara" } -console.log(animals[dog]); +console.log(animals[dog]) ``` - A: `{ emoji: "🐶", name: "Mara" }` @@ -4911,9 +4909,9 @@ console.log(animals[dog]); Kunci objek diubah menjadi string. -Karena nilai `dog` adalah sebuah objek, `animals[dog]`sebenarnya berarti kita membuat properti baru bernama `"object Object"`yang sama dengan objek baru. `animals["object Object"]` sekarang sama dengan `{ emoji: "🐶", name: "Mara"}`. +Karena nilai `dog` adalah sebuah objek, `animals[dog]`sebenarnya berarti kita membuat properti baru bernama `"object Object"`yang sama dengan objek baru. `animals["object Object"]` sekarang sama dengan `{ emoji: "🐶", name: "Mara"}`. -`cat` juga merupakan objek, yang berarti bahwa `animals[cat]` sebenarnya berarti bahwa kami menimpa nilai ` animals[``"``object Object``"``] ` dengan properti cat yang baru. +`cat` juga merupakan objek, yang berarti bahwa `animals[cat]` sebenarnya berarti bahwa kami menimpa nilai `animals[``"``object Object``"``]` dengan properti cat yang baru. Mencatat `animals[dog]`, atau sebenarnya `animals["object Object"]` karena mengonversi objek `dog` menjadi string menghasilkan `"object Object"`, mengembalikan `{emoji: "🐈", nama: "Sara"}`. @@ -4926,10 +4924,10 @@ Mencatat `animals[dog]`, atau sebenarnya `animals["object Object"]` karena mengo ```javascript const user = { - email: "my@email.com", - updateEmail: (email) => { - this.email = email; - }, + email: "my@email.com", + updateEmail: (email) => { + this.email = email; + }, }; user.updateEmail("new@email.com"); @@ -4956,20 +4954,20 @@ Fungsi `updateEmail` adalah fungsi panah, dan tidak terikat ke objek `user`. Art ###### 152. Apa hasilnya? ```javascript -const promise1 = Promise.resolve("First"); -const promise2 = Promise.resolve("Second"); -const promise3 = Promise.reject("Third"); -const promise4 = Promise.resolve("Fourth"); +const promise1 = Promise.resolve('First') +const promise2 = Promise.resolve('Second') +const promise3 = Promise.reject('Third') +const promise4 = Promise.resolve('Fourth') const runPromises = async () => { - const res1 = await Promise.all([promise1, promise2]); - const res2 = await Promise.all([promise3, promise4]); - return [res1, res2]; -}; + const res1 = await Promise.all([promise1, promise2]); + const res2 = await Promise.all([promise3, promise4]); + return [res1, res2]; +} runPromises() - .then((res) => console.log(res)) - .catch((err) => console.log(err)); + .then(res => console.log(res)) + .catch(err => console.log(err)) ``` - A: `[['First', 'Second'], ['Fourth']]` @@ -5026,18 +5024,18 @@ Ini membuat array subarray yang berisi kunci dan nilai yang benar, yang menghasi ###### 154. Apa hasilnya? ```javascript -const createMember = ({ email, address = {} }) => { - const validEmail = /.+\@.+\..+/.test(email); - if (!validEmail) throw new Error("Valid email pls"); +const createMember = ({ email, address = {}}) => { + const validEmail = /.+\@.+\..+/.test(email) + if (!validEmail) throw new Error("Valid email pls") - return { - email, - address: address ? address : null, - }; -}; + return { + email, + address: address ? address : null + } +} -const member = createMember({ email: "my@email.com" }); -console.log(member); +const member = createMember({ email: "my@email.com" }) +console.log(member) ``` - A: `{ email: "my@email.com", address: null }` @@ -5060,13 +5058,13 @@ Nilai default dari `address` adalah objek kosong `{}`. Saat kita menyetel variab ###### 155. Apa hasilnya? ```javascript -let randomValue = { name: "Lydia" }; -randomValue = 23; +let randomValue = { name: "Lydia" } +randomValue = 23 if (!typeof randomValue === "string") { - console.log("It's not a string!"); + console.log("It's not a string!") } else { - console.log("Yay it's a string!"); + console.log("Yay it's a string!") } ``` diff --git a/it-IT/README.md b/it-IT/README.md index 8b116031..71b71ca5 100644 --- a/it-IT/README.md +++ b/it-IT/README.md @@ -8,12 +8,13 @@ Da base ad avanzato: metti alla prova quanto conosci JavaScript, rinfresca un po' le tue conoscenze o preparati per il tuo colloquio di programmazione! :muscle: :rocket: Aggiorno regolarmente questo repository con nuove domande. Ho aggiunto le risposte nelle **sezioni compresse** sotto le domande, cliccaci sopra per espanderle. È solo per divertimento, buona fortuna! :heart: + Sentiti libero di contattarmi! 😊
Instagram || Twitter || LinkedIn || Blog - -| Sentiti libero di usarli in un progetto! 😃 Apprezzerei _molto_ un riferimento a questa repository, creo le domande e le spiegazioni (sì, sono triste lol) e la community mi aiuta tantissimo a mantenerlo e migliorarlo! 💪🏼 Grazie e buon divertimento! | +| Sentiti libero di usarli in un progetto! 😃 Apprezzerei _molto_ un riferimento a questa repository, creo le domande e le spiegazioni (sì, sono triste lol) e la community mi aiuta tantissimo a mantenerlo e migliorarlo! 💪🏼 Grazie e buon divertimento! | + Traduzione a cura di: Lucia Cenetiempo |---| @@ -36,7 +37,6 @@ Traduzione a cura di: Lucia Cenetie - [🇳🇱 Nederlands](../nl-NL/README.md) - [🇵🇱 Polski](../pl-PL/README.md) - [🇧🇷 Português Brasil](../pt-BR/README_pt_BR.md) -- [🇷o Română](../ro-RO/README.ro.md) - [🇷🇺 Русский](../ru-RU/README.md) - [🇽🇰 Shqip](../sq-KS/README_sq_KS.md) - [🇹🇭 ไทย](../th-TH/README-th_TH.md) @@ -57,7 +57,7 @@ Traduzione a cura di: Lucia Cenetie function sayHi() { console.log(name); console.log(age); - var name = "Lydia"; + var name = 'Lydia'; let age = 21; } @@ -75,8 +75,8 @@ sayHi(); #### Risposta: D -All'interno della funzione, dichiariamo prima la variabile `name` con la parola chiave `var`. Ciò significa che la variabile viene sollevata all'interno del codice (ovvero lo spazio di memoria viene impostato durante la fase di creazione) e viene inizializzata con il valore predefinito di `undefined`, finché non arriviamo effettivamente alla riga in cui la definiamo. -Al momento in cui proviamo ad eseguire il log della variabile `name` non l'abbiamo ancora dichiarata, quindi mantiene il valore di `undefined`. +All'interno della funzione, dichiariamo prima la variabile `name` con la parola chiave `var`. Ciò significa che la variabile viene sollevata all'interno del codice (ovvero lo spazio di memoria viene impostato durante la fase di creazione) e viene inizializzata con il valore predefinito di `undefined`, finché non arriviamo effettivamente alla riga in cui la definiamo. +Al momento in cui proviamo ad eseguire il log della variabile `name` non l'abbiamo ancora dichiarata, quindi mantiene il valore di `undefined`. Le variabili dichiarate con la chiave `let` (o `const`) vengono sollevate, ma a differenza delle variabili dichiarate con `var`, non vengono inizializzate. Per questo motivo non sono accessibili prima della loro dichiarazione (dove le inizializzaimo). Questa è chiamata "temporal dead zone". Quando proviamo ad accedere alle variabili prima che vengano dichiarate, JavaScript genera un `ReferenceError`. @@ -155,7 +155,7 @@ Non troviamo quindi alcun valore `radius` in quell'oggetto e quindi viene restit ```javascript +true; -!"Lydia"; +!'Lydia'; ``` - A: `1` and `false` @@ -180,11 +180,11 @@ La stringa `'Lydia'` è un valore veritiero. Quello che in realtà ci stiamo chi ```javascript const bird = { - size: "small", + size: 'small', }; const mouse = { - name: "Mickey", + name: 'Mickey', small: true, }; ``` @@ -215,11 +215,11 @@ Con l'utilizzo del punto questo non accade perché `mouse` non ha una chiave chi ###### 6. Qual è l'output? ```javascript -let c = { greeting: "Hey!" }; +let c = { greeting: 'Hey!' }; let d; d = c; -c.greeting = "Hello"; +c.greeting = 'Hello'; console.log(d.greeting); ``` @@ -289,13 +289,13 @@ class Chameleon { return this.newColor; } - constructor({ newColor = "green" } = {}) { + constructor({ newColor = 'green' } = {}) { this.newColor = newColor; } } -const freddie = new Chameleon({ newColor: "purple" }); -console.log(freddie.colorChange("orange")); +const freddie = new Chameleon({ newColor: 'purple' }); +console.log(freddie.colorChange('orange')); ``` - A: `orange` @@ -347,10 +347,10 @@ Per evitare ciò, possiamo usare `"use strict"`. Questo assicura di aver dichiar ```javascript function bark() { - console.log("Woof!"); + console.log('Woof!'); } -bark.animal = "dog"; +bark.animal = 'dog'; ``` - A: Niente, va benissimo! @@ -380,8 +380,8 @@ function Person(firstName, lastName) { this.lastName = lastName; } -const member = new Person("Lydia", "Hallie"); -Person.getFullName = function () { +const member = new Person('Lydia', 'Hallie'); +Person.getFullName = function() { return `${this.firstName} ${this.lastName}`; }; @@ -402,8 +402,9 @@ In JavaScript, le funzioni sono oggetti e quindi il metodo `getFullName` viene a Se vuoi che un metodo sia disponibile per tutte le istanze dell'oggetto, devi aggiungerlo alla proprietà del prototipo: + ```js -Person.prototype.getFullName = function () { +Person.prototype.getFullName = function() { return `${this.firstName} ${this.lastName}`; }; ``` @@ -421,8 +422,8 @@ function Person(firstName, lastName) { this.lastName = lastName; } -const lydia = new Person("Lydia", "Hallie"); -const sarah = Person("Sarah", "Smith"); +const lydia = new Person('Lydia', 'Hallie'); +const sarah = Person('Sarah', 'Smith'); console.log(lydia); console.log(sarah); @@ -492,7 +493,7 @@ function sum(a, b) { return a + b; } -sum(1, "2"); +sum(1, '2'); ``` - A: `NaN` @@ -543,7 +544,7 @@ Utilizzando l'operatore unario come **prefisso** `++number` succede che: 1. Incrementa prima il valore (il numero è ora `2`) 2. Restituisce subito dopo il valore già incrementato (`2`) -Quindi il nostro log sarà `0 2 2`. +Quindi il nostro log sarà `0 2 2`.

@@ -559,7 +560,7 @@ function getPersonInfo(one, two, three) { console.log(three); } -const person = "Lydia"; +const person = 'Lydia'; const age = 21; getPersonInfo`${person} is ${age} years old`; @@ -574,7 +575,7 @@ getPersonInfo`${person} is ${age} years old`; #### Risposta: B -Utilizzando i template literals, il valore del primo argomento sarà un array di valori della stringa. Gli altri argomenti prenderanno i valori dell'espressione passata. +Utilizzando i template literals, il valore del primo argomento sarà un array di valori della stringa. Gli altri argomenti prenderanno i valori dell'espressione passata.

@@ -586,9 +587,9 @@ Utilizzando i template literals, il valore del primo argomento sarà un array di ```javascript function checkAge(data) { if (data === { age: 18 }) { - console.log("You are an adult!"); + console.log('You are an adult!'); } else if (data == { age: 18 }) { - console.log("You are still an adult."); + console.log('You are still an adult.'); } else { console.log(`Hmm.. You don't have an age I guess`); } @@ -648,7 +649,7 @@ Il parametro rest (`...args`) ci permette di "collettare" tutti gli argomenti in ```javascript function getAge() { - "use strict"; + 'use strict'; age = 21; console.log(age); } @@ -676,7 +677,7 @@ Con `"use strict"`, puoi assicurarti di non dichiarare variabili globali per sba ###### 21. Qual è il valore di `sum`? ```javascript -const sum = eval("10*10+5"); +const sum = eval('10*10+5'); ``` - A: `105` @@ -699,7 +700,7 @@ const sum = eval("10*10+5"); ###### 22. Per quanto tempo cool_secret è accessibile? ```javascript -sessionStorage.setItem("cool_secret", 123); +sessionStorage.setItem('cool_secret', 123); ``` - A: Per sempre, i dati non vanno persi. @@ -752,12 +753,12 @@ Non puoi farlo con `let` o `const` poiché sono block-scoped. ###### 24. Qual è l'output? ```javascript -const obj = { 1: "a", 2: "b", 3: "c" }; +const obj = { 1: 'a', 2: 'b', 3: 'c' }; const set = new Set([1, 2, 3, 4, 5]); -obj.hasOwnProperty("1"); +obj.hasOwnProperty('1'); obj.hasOwnProperty(1); -set.has("1"); +set.has('1'); set.has(1); ``` @@ -783,7 +784,7 @@ Per i set non funziona allo stesso modo degli oggetti. Non c'è alcun `'1'` nel ###### 25. Qual è l'output? ```javascript -const obj = { a: "one", b: "two", a: "three" }; +const obj = { a: 'one', b: 'two', a: 'three' }; console.log(obj); ``` @@ -852,12 +853,12 @@ L'istruzione `continue` salta un'iterazione se una certa condizione restituisce ```javascript String.prototype.giveLydiaPizza = () => { - return "Just give Lydia pizza already!"; + return 'Just give Lydia pizza already!'; }; -const name = "Lydia"; +const name = 'Lydia'; -console.log(name.giveLydiaPizza()); +console.log(name.giveLydiaPizza()) ``` - A: `"Just give Lydia pizza already!"` @@ -870,7 +871,7 @@ console.log(name.giveLydiaPizza()); #### Risposta: A -`String` è un costruttore built-in, a cui possiamo aggiungere proprietà. In questo caso è stato appena aggiunto un metodo al suo prototipo. +`String` è un costruttore built-in, a cui possiamo aggiungere proprietà. In questo caso è stato appena aggiunto un metodo al suo prototipo. Le stringhe primitive vengono automaticamente convertite in un oggetto stringa, generato dalla string prototype function. Quindi, tutte le stringhe hanno accesso a quel metodo!

@@ -882,8 +883,8 @@ Le stringhe primitive vengono automaticamente convertite in un oggetto stringa, ```javascript const a = {}; -const b = { key: "b" }; -const c = { key: "c" }; +const b = { key: 'b' }; +const c = { key: 'c' }; a[b] = 123; a[c] = 456; @@ -915,9 +916,9 @@ Quindi, quando facciamo console.log di `a[b]`, che in realtà è `a["[object Obj ###### 30. Qual è l'output? ```javascript -const foo = () => console.log("First"); -const bar = () => setTimeout(() => console.log("Second")); -const baz = () => console.log("Third"); +const foo = () => console.log('First'); +const bar = () => setTimeout(() => console.log('Second')); +const baz = () => console.log('Third'); bar(); foo(); @@ -970,7 +971,9 @@ La WebAPI non può semplicemente aggiungere elementi allo stack ogni volta che ```html
- +
``` @@ -996,7 +999,9 @@ L'elemento annidato più in profondità è quello che ha causato l'evento ed è ```html
-

Click here!

+

+ Click here! +

``` @@ -1020,7 +1025,7 @@ Se clicchiamo su `p`, vediamo due log: `p` e `div`. Durante la propagazione dell ###### 33. Qual è l'output? ```javascript -const person = { name: "Lydia" }; +const person = { name: 'Lydia' }; function sayHi(age) { return `${this.name} is ${age}`; @@ -1083,8 +1088,8 @@ Ci sono solo 7 tipi built-in: `null`, `undefined`, `boolean`, `number`, `string` ```javascript 0; new Number(0); -(""); -(" "); +(''); +(' '); new Boolean(false); undefined; ``` @@ -1233,14 +1238,11 @@ Ciò che differenzia un tipo primitivo da un oggetto è che i primitivi non hann ###### 40. Qual è l'output? ```javascript -[ - [0, 1], - [2, 3], -].reduce( +[[0, 1], [2, 3]].reduce( (acc, cur) => { return acc.concat(cur); }, - [1, 2] + [1, 2], ); ``` @@ -1257,7 +1259,6 @@ Ciò che differenzia un tipo primitivo da un oggetto è che i primitivi non hann `[1, 2]` rappresenta il nostro valore interno. Ovvero il valore con cui iniziamo e il valore del primo `acc`. Durante il primo round, `acc` è `[1,2]` e `cur` è `[0, 1]`. Li concateniamo ottenendo `[1, 2, 0, 1]`. A questo punto `acc` corrisponderà a `[1, 2, 0, 1]` e `cur` sarà ancora `[2, 3]`. Li concateniamo e otteniamo `[1, 2, 0, 1, 2, 3]` -

@@ -1267,7 +1268,7 @@ A questo punto `acc` corrisponderà a `[1, 2, 0, 1]` e `cur` sarà ancora `[2, 3 ```javascript !!null; -!!""; +!!''; !!1; ``` @@ -1295,7 +1296,7 @@ A questo punto `acc` corrisponderà a `[1, 2, 0, 1]` e `cur` sarà ancora `[2, 3 ###### 42. Cosa restituisce il metodo `setInterval` nel browser? ```javascript -setInterval(() => console.log("Hi"), 1000); +setInterval(() => console.log('Hi'), 1000); ``` - A: un ID univoco @@ -1318,7 +1319,7 @@ Restituisce un ID univoco. Questo id può essere usato per cancellare quell'inte ###### 43. Cosa restituisce? ```javascript -[..."Lydia"]; +[...'Lydia']; ``` - A: `["L", "y", "d", "i", "a"]` @@ -1377,14 +1378,14 @@ Invochiamo di nuovo la funzione con il metodo `next()`. Inizia a continuare da d ```javascript const firstPromise = new Promise((res, rej) => { - setTimeout(res, 500, "one"); + setTimeout(res, 500, 'one'); }); const secondPromise = new Promise((res, rej) => { - setTimeout(res, 100, "two"); + setTimeout(res, 100, 'two'); }); -Promise.race([firstPromise, secondPromise]).then((res) => console.log(res)); +Promise.race([firstPromise, secondPromise]).then(res => console.log(res)); ``` - A: `"one"` @@ -1407,7 +1408,7 @@ Quando passiamo più promises al metodo `Promise.race`, questo risolve/rifiuta l ###### 46. Qual è l'output? ```javascript -let person = { name: "Lydia" }; +let person = { name: 'Lydia' }; const members = [person]; person = null; @@ -1447,7 +1448,7 @@ Stiamo modificando solo il valore della variabile `person`, e non il primo eleme ```javascript const person = { - name: "Lydia", + name: 'Lydia', age: 21, }; @@ -1476,7 +1477,7 @@ Con il ciclo `for-in`, possiamo iterare le chiavi degli oggetti, in questo caso ###### 48. Qual è l'output? ```javascript -console.log(3 + 4 + "5"); +console.log(3 + 4 + '5'); ``` - A: `"345"` @@ -1503,7 +1504,7 @@ L'associazione è l'ordine in cui il compilatore valuta le espressioni, da sinis ###### 49. Qual è il valore di `num`? ```javascript -const num = parseInt("7*6", 10); +const num = parseInt('7*6', 10); ``` - A: `42` @@ -1528,8 +1529,8 @@ Viene restituito solo il primo valore della stringa. In base alla _radice_ (ovve ###### 50. Qual è l'output? ```javascript -[1, 2, 3].map((num) => { - if (typeof num === "number") return; +[1, 2, 3].map(num => { + if (typeof num === 'number') return; return num * 2; }); ``` @@ -1557,12 +1558,12 @@ Tuttavia, non ritorniamo un valore. Quando non ritorniamo un valore dalla funzio ```javascript function getInfo(member, year) { - member.name = "Lydia"; - year = "1998"; + member.name = 'Lydia'; + year = '1998'; } -const person = { name: "Sarah" }; -const birthYear = "1997"; +const person = { name: 'Sarah' }; +const birthYear = '1997'; getInfo(person, birthYear); @@ -1584,7 +1585,6 @@ Gli argomenti vengono passati come _valori_, a meno che il loro valore non sia u La variabile `birthYear` ha un riferimento al valore `"1997"`. Anche l'argomento `year` fa riferimento al valore `"1997"`, ma non è lo stesso valore a cui fa riferimento `birthYear`. Quando aggiorniamo il valore di `year` impostando `year` uguale a `"1998"`, stiamo solo aggiornando il valore di `year`. `birthYear` è ancora uguale a `"1997"`. Il valore di `person` è un oggetto. L'argomento `member` ha un riferimento (copiato) dello stesso oggetto. Quando modifichiamo una proprietà dell'oggetto a cui `member` fa riferimento, verrà modificato anche il valore di `person`, poiché entrambi hanno un riferimento allo stesso oggetto. La proprietà `name` di `person` è ora uguale al valore `"Lydia"` -

@@ -1594,15 +1594,15 @@ Il valore di `person` è un oggetto. L'argomento `member` ha un riferimento (cop ```javascript function greeting() { - throw "Hello world!"; + throw 'Hello world!'; } function sayHi() { try { const data = greeting(); - console.log("It worked!", data); + console.log('It worked!', data); } catch (e) { - console.log("Oh no an error:", e); + console.log('Oh no an error:', e); } } @@ -1632,8 +1632,8 @@ Con l'istruzione `catch`, possiamo specificare cosa fare se viene generata un'ec ```javascript function Car() { - this.make = "Lamborghini"; - return { make: "Maserati" }; + this.make = 'Lamborghini'; + return { make: 'Maserati' }; } const myCar = new Car(); @@ -1705,11 +1705,11 @@ class Dog { } } -Dog.prototype.bark = function () { +Dog.prototype.bark = function() { console.log(`Woof I am ${this.name}`); }; -const pet = new Dog("Mara"); +const pet = new Dog('Mara'); pet.bark(); @@ -1774,7 +1774,7 @@ export default counter; ```javascript // index.js -import myCounter from "./counter"; +import myCounter from './counter'; myCounter += 1; @@ -1803,7 +1803,7 @@ Quando proviamo ad incrementare il valore di `myCounter`, viene generato un erro ###### 58. Qual è l'output? ```javascript -const name = "Lydia"; +const name = 'Lydia'; age = 21; console.log(delete name); @@ -1874,7 +1874,7 @@ Questo significa che il valore di `y` è uguale al primo valore nell'array, che ###### 60. Qual è l'output? ```javascript -const user = { name: "Lydia", age: 21 }; +const user = { name: 'Lydia', age: 21 }; const admin = { admin: true, ...user }; console.log(admin); @@ -1900,9 +1900,9 @@ console.log(admin); ###### 61. Qual è l'output? ```javascript -const person = { name: "Lydia" }; +const person = { name: 'Lydia' }; -Object.defineProperty(person, "age", { value: 21 }); +Object.defineProperty(person, 'age', { value: 21 }); console.log(person); console.log(Object.keys(person)); @@ -1931,12 +1931,12 @@ Le proprietà aggiunte usando il metodo `defineProperty` sono immutabili per imp ```javascript const settings = { - username: "lydiahallie", + username: 'lydiahallie', level: 19, health: 90, }; -const data = JSON.stringify(settings, ["level", "health"]); +const data = JSON.stringify(settings, ['level', 'health']); console.log(data); ``` @@ -1967,7 +1967,7 @@ Se il replacer è una _funzione_, questa funzione viene chiamata su ogni proprie let num = 10; const increaseNumber = () => num++; -const increasePassedNumber = (number) => number++; +const increasePassedNumber = number => number++; const num1 = increaseNumber(); const num2 = increasePassedNumber(num1); @@ -2049,7 +2049,7 @@ La quarta volta, passiamo di nuovo l'oggetto `value`, in questo caso `x.number` #### Risposta: D -Il primo argomento che il metodo `reduce` riceve è l'_accumulatore_, in questo caso `x`. Il secondo argomento è il _valore corrente_ `y`. +Il primo argomento che il metodo `reduce` riceve è l'_accumulatore_, in questo caso `x`. Il secondo argomento è il _valore corrente_ `y`. Con il metodo reduce, eseguiamo una funzione di callback su ogni elemento dell'array, che alla fine potrebbe risultare in un singolo valore. In questo esempio, non stiamo restituendo alcun valore, stiamo semplicemente loggando i valori dell'accumulatore e il valore corrente. @@ -2061,7 +2061,6 @@ Alla prima chiamata, l'accumulatore (`x`) è `1` e il valore corrente (`y`) è ` Se non restituisci un valore da una funzione questa restituisce `undefined`. Alla chiamata successiva, l'accumulatore è `undefined` e il valore corrente è "3". `undefined` e `3` vengono loggati. Alla quarta chiamata, di nuovo non facciamo un return dalla funzione di callback. L'accumulatore è di nuovo `undefined` e il valore corrente è "4". `undefined` e `4` vengono loggati. -

@@ -2125,12 +2124,12 @@ La classe `Labrador` riceve due argomenti, `name` poiché estende `Dog`, e `size ```javascript // index.js -console.log("running index.js"); -import { sum } from "./sum.js"; +console.log('running index.js'); +import { sum } from './sum.js'; console.log(sum(1, 2)); // sum.js -console.log("running sum.js"); +console.log('running sum.js'); export const sum = (a, b) => a + b; ``` @@ -2158,7 +2157,7 @@ Questa è una delle differenze tra `require()` in CommonJS e `import`. Con `requ ```javascript console.log(Number(2) === Number(2)); console.log(Boolean(false) === Boolean(false)); -console.log(Symbol("foo") === Symbol("foo")); +console.log(Symbol('foo') === Symbol('foo')); ``` - A: `true`, `true`, `false` @@ -2181,7 +2180,7 @@ Ogni Simbolo è unico. Lo scopo dell'argomento passato a Symbol è di dargli una ###### 69. Qual è l'output? ```javascript -const name = "Lydia Hallie"; +const name = 'Lydia Hallie'; console.log(name.padStart(13)); console.log(name.padStart(2)); ``` @@ -2208,7 +2207,7 @@ Se l'argomento passato al metodo `padStart` è inferiore alla lunghezza dell'arr ###### 70. Qual è l'output? ```javascript -console.log("🥑" + "💻"); +console.log('🥑' + '💻'); ``` - A: `"🥑💻"` @@ -2232,11 +2231,11 @@ Con l'operatore `+` puoi concatenare stringhe. In questo caso, stiamo concatenan ```javascript function* startGame() { - const answer = yield "Do you love JavaScript?"; - if (answer !== "Yes") { + const answer = yield 'Do you love JavaScript?'; + if (answer !== 'Yes') { return "Oh wow... Guess we're gone here"; } - return "JavaScript loves you back ❤️"; + return 'JavaScript loves you back ❤️'; } const game = startGame(); @@ -2304,7 +2303,7 @@ In questo caso, è la stringa `Hello\nworld` che viene loggata. ```javascript async function getData() { - return await Promise.resolve("I made it!"); + return await Promise.resolve('I made it!'); } const data = getData(); @@ -2341,7 +2340,7 @@ function addToList(item, list) { return list.push(item); } -const result = addToList("apple", ["banana"]); +const result = addToList('apple', ['banana']); console.log(result); ``` @@ -2355,10 +2354,10 @@ console.log(result); #### Risposta: B -Il metodo `.push()` restituisce la _lunghezza_ del nuovo array! -Inizialmente, l'array conteneva un solo elemento (la stringa `"banana"`) e aveva una lunghezza di `1`. Dopo aver aggiunto la stringa `"apple"` allo stesso array, questo contiene due elementi e ha una lunghezza di `2` +Il metodo `.push()` restituisce la _lunghezza_ del nuovo array! +Inizialmente, l'array conteneva un solo elemento (la stringa `"banana"`) e aveva una lunghezza di `1`. Dopo aver aggiunto la stringa `"apple"` allo stesso array, questo contiene due elementi e ha una lunghezza di `2` -Attraverso la funzione `addToList`, il metodo `push` modifica l'array originale. +Attraverso la funzione `addToList`, il metodo `push` modifica l'array originale. Per restituire l'_array_ dalla funzione invece della _lunghezza dell'array_, serve fare un return di `list` dopo aver inserito l'`item`.

@@ -2391,10 +2390,10 @@ console.log(shape); `Object.freeze` rende impossibile aggiungere, rimuovere o modificare le proprietà di un oggetto (a meno che il valore della proprietà non sia un altro oggetto). -Quando creiamo la variabile `shape` e la impostiamo come all'oggetto congelato `box`, anche `shape` si riferisce ad un oggetto congelato. +Quando creiamo la variabile `shape` e la impostiamo come all'oggetto congelato `box`, anche `shape` si riferisce ad un oggetto congelato. Puoi controllare se un oggetto è congelato usando `Object.isFrozen`. In questo caso, `Object.isFrozen(shape)` restituisce true, poiché la variabile `shape` ha un riferimento a un oggetto congelato. -Poiché `shape` è congelata, e poiché il valore di `x` non è un oggetto, non possiamo modificare la proprietà `x`. +Poiché `shape` è congelata, e poiché il valore di `x` non è un oggetto, non possiamo modificare la proprietà `x`. `x` è ancora uguale a `10` e `{ x: 10, y: 20 }` viene loggato.

@@ -2405,7 +2404,7 @@ Poiché `shape` è congelata, e poiché il valore di `x` non è un oggetto, non ###### 76. Qual è l'output? ```javascript -const { name: myName } = { name: "Lydia" }; +const { name: myName } = { name: 'Lydia' }; console.log(name); ``` @@ -2461,7 +2460,7 @@ La funzione `sum` restituisce sempre lo stesso risultato. Se le passiamo `1` e ` ```javascript const add = () => { const cache = {}; - return (num) => { + return num => { if (num in cache) { return `From cache! ${cache[num]}`; } else { @@ -2488,13 +2487,13 @@ console.log(addFunction(5 * 2)); #### Risposta: C -La funzione `add` è una funzione _memoizzata_. Con la memorizzazione, possiamo memorizzare nella cache i risultati di una funzione per velocizzarne l'esecuzione. +La funzione `add` è una funzione _memoizzata_. Con la memorizzazione, possiamo memorizzare nella cache i risultati di una funzione per velocizzarne l'esecuzione. In questo caso, creiamo un oggetto `cache` che memorizza i valori precedentemente restituiti. Se chiamiamo di nuovo la funzione `addFunction` con lo stesso argomento, prima controlla se ha già ottenuto quel valore nella sua cache, in tal caso, verrà restituito il valore della cache, consentendo di risparmiare tempo di esecuzione. Altrimenti, se non è memorizzato nella cache, calcolerà il valore e lo memorizzerà in seguito. -Chiamiamo la funzione `addFunction` tre volte con lo stesso valore: alla prima chiamata, il valore della funzione quando `num` è uguale a `10` non è ancora memorizzato nella cache. -La condizione dell'istruzione if `num in cache` restituisce `false`, e il blocco else viene eseguito: `Calculated! 20` viene loggato e il valore del risultato viene aggiunto all'oggetto cache. +Chiamiamo la funzione `addFunction` tre volte con lo stesso valore: alla prima chiamata, il valore della funzione quando `num` è uguale a `10` non è ancora memorizzato nella cache. +La condizione dell'istruzione if `num in cache` restituisce `false`, e il blocco else viene eseguito: `Calculated! 20` viene loggato e il valore del risultato viene aggiunto all'oggetto cache. `cache` ora è uguale a `{ 10: 20 }`. La seconda volta, l'oggetto `cache` contiene il valore che viene restituito per `10`. La condizione dell'istruzione if `num in cache` restituisce `true` e `'From cache! 20'` viene loggato. @@ -2509,7 +2508,7 @@ La terza volta, passiamo `5 * 2` alla funzione che viene valutata a `10`. L'ogge ###### 79. Qual è l'output? ```javascript -const myLifeSummedUp = ["☕", "💻", "🍷", "🍫"]; +const myLifeSummedUp = ['☕', '💻', '🍷', '🍫']; for (let item in myLifeSummedUp) { console.log(item); @@ -2605,13 +2604,13 @@ In questo caso, se non abbiamo passato un valore o se abbiamo passato `undefined ###### 82. Qual è l'output? ```javascript -var status = "😎"; +var status = '😎'; setTimeout(() => { - const status = "😍"; + const status = '😍'; const data = { - status: "🥑", + status: '🥑', getStatus() { return this.status; }, @@ -2645,12 +2644,12 @@ Con il metodo `call` possiamo cambiare l'oggetto a cui fa riferimento la parola ```javascript const person = { - name: "Lydia", + name: 'Lydia', age: 21, }; let city = person.city; -city = "Amsterdam"; +city = 'Amsterdam'; console.log(person); ``` @@ -2714,9 +2713,9 @@ Le variabili con la chiave `const` e `let` sono _block-scoped_. Un blocco è qua ###### 85. Che tipo di informazioni verrebbero loggate? ```javascript -fetch("https://www.website.com/api/user/1") - .then((res) => res.json()) - .then((res) => console.log(res)); +fetch('https://www.website.com/api/user/1') + .then(res => res.json()) + .then(res => console.log(res)); ``` - A: Il risultato del metodo `fetch`. @@ -2754,7 +2753,7 @@ function getName(name) { #### Risposta: A -Con `!!name`, determiniamo se il valore di `name` è vero o falso. Se il nome è vero, cosa che vogliamo testare, `!name` restituisce `false`. +Con `!!name`, determiniamo se il valore di `name` è vero o falso. Se il nome è vero, cosa che vogliamo testare, `!name` restituisce `false`. `!false` (che è `!!name`) restituisce `true`. Impostando `hasName` uguale a `name`, imposti `hasName` uguale a qualsiasi valore passato alla funzione `getName`, non il valore booleano `true`. @@ -2771,7 +2770,7 @@ Impostando `hasName` uguale a `name`, imposti `hasName` uguale a qualsiasi valor ###### 87. Qual è l'output? ```javascript -console.log("I want pizza"[0]); +console.log('I want pizza'[0]); ``` - A: `"""` @@ -2816,7 +2815,6 @@ sum(10); È possibile impostare il valore di un parametro predefinito uguale a un altro parametro della funzione, purché sia stato definito _prima_ del parametro predefinito. Passiamo il valore `10` alla funzione `sum`. Se la funzione `sum` riceve solo 1 argomento, significa che il valore di `num2` non è passato e il valore di `num1` è uguale al valore passato `10` in questo caso. Il valore predefinito di `num2` è il valore di `num1`, che è `10`. `num1 + num2` restituisce `20`. Se stai cercando di impostare il valore di un parametro predefinito uguale a un parametro che è definito _dopo_ (a destra), il valore del parametro non è stato ancora inizializzato, il che genererà un errore. -

@@ -2826,11 +2824,11 @@ Se stai cercando di impostare il valore di un parametro predefinito uguale a un ```javascript // module.js -export default () => "Hello world"; -export const name = "Lydia"; +export default () => 'Hello world'; +export const name = 'Lydia'; // index.js -import * as data from "./module"; +import * as data from './module'; console.log(data); ``` @@ -2863,7 +2861,7 @@ class Person { } } -const member = new Person("John"); +const member = new Person('John'); console.log(typeof member); ``` @@ -2923,7 +2921,7 @@ Quindi quando proviamo a usare il metodo `.push` su `newList` poiché `newList` ```javascript function giveLydiaPizza() { - return "Here is pizza!"; + return 'Here is pizza!'; } const giveLydiaChocolate = () => @@ -2944,7 +2942,6 @@ console.log(giveLydiaChocolate.prototype); #### Risposta: D Le funzioni regolari, come la funzione `giveLydiaPizza`, hanno una proprietà `prototipo`, che è un oggetto (prototype object) con un `costruttore`. Tuttavia, le arrow functions, come la funzione `giveLydiaChocolate`, non hanno una proprietà `prototype`. Viene quindi restituito `undefined` quando si tenta di accedere alla proprietà `prototype` usando `giveLydiaChocolate.prototype`. -

@@ -2954,7 +2951,7 @@ Le funzioni regolari, come la funzione `giveLydiaPizza`, hanno una proprietà `p ```javascript const person = { - name: "Lydia", + name: 'Lydia', age: 21, }; @@ -3014,7 +3011,7 @@ function getItems(fruitList, favoriteFruit, ...args) { return [...fruitList, ...args, favoriteFruit]; } -getItems(["banana", "apple"], "pear", "orange"); +getItems(['banana', 'apple'], 'pear', 'orange'); ``` L'esempio qui sopra invece funziona e restituisce l'array `[ 'banana', 'apple', 'orange', 'pear' ]` @@ -3028,9 +3025,9 @@ L'esempio qui sopra invece funziona e restituisce l'array `[ 'banana', 'apple', ```javascript function nums(a, b) { - if (a > b) console.log("a is bigger"); - else console.log("b is bigger"); - return; + if (a > b) console.log('a is bigger'); + else console.log('b is bigger'); + return a + b; } @@ -3048,10 +3045,10 @@ console.log(nums(1, 2)); #### Risposta: B -In JavaScript, non _è necessario_ scrivere il punto e virgola (`;`) in modo esplicito poiché il motore JavaScript li aggiunge comunque dopo le istruzioni. +In JavaScript, non _è necessario_ scrivere il punto e virgola (`;`) in modo esplicito poiché il motore JavaScript li aggiunge comunque dopo le istruzioni. Questo procedimento è chiamato **Automatic Semicolon Insertion**. Un'istruzione può ad esempio essere una variabile o parole chiave come `throw`, `return`, `break`, ecc. -Qui, abbiamo scritto un'istruzione di `return` e un altro valore `a + b` su una _nuova riga_. Tuttavia, trattandosi di una nuova linea, il motore non sa che in realtà è il valore che volevamo restituire. Invece, ha aggiunto automaticamente un punto e virgola dopo `return`. +Qui, abbiamo scritto un'istruzione di `return` e un altro valore `a + b` su una _nuova riga_. Tuttavia, trattandosi di una nuova linea, il motore non sa che in realtà è il valore che volevamo restituire. Invece, ha aggiunto automaticamente un punto e virgola dopo `return`. Potresti considerare ad esempio: @@ -3060,7 +3057,7 @@ return; a + b; ``` -`a + b` non viene mai raggiunto, poiché la funzione smette di funzionare dopo la parola chiave `return`. +`a + b` non viene mai raggiunto, poiché la funzione smette di funzionare dopo la parola chiave `return`. Se non viene restituito alcun valore, come qui, la funzione restituisce `undefined`. Nota: non c'è un inserimento automatico dopo le istruzioni `if/else`!

@@ -3073,13 +3070,13 @@ Se non viene restituito alcun valore, come qui, la funzione restituisce `undefin ```javascript class Person { constructor() { - this.name = "Lydia"; + this.name = 'Lydia'; } } Person = class AnotherPerson { constructor() { - this.name = "Sarah"; + this.name = 'Sarah'; } }; @@ -3097,7 +3094,7 @@ console.log(member.name); #### Risposta: B -Possiamo impostare classi uguali ad altre classi/costruttori di funzioni. In questo caso, impostiamo `Person` uguale a `AnotherPerson`. Il name su questo costruttore è `Sarah`, quindi la proprietà del nome di`Person` sulla nuova istanza `member` è `"Sarah"`. +Possiamo impostare classi uguali ad altre classi/costruttori di funzioni. In questo caso, impostiamo `Person` uguale a `AnotherPerson`. Il name su questo costruttore è `Sarah`, quindi la proprietà del nome di`Person` sulla nuova istanza `member` è `"Sarah"`.

@@ -3108,7 +3105,7 @@ Possiamo impostare classi uguali ad altre classi/costruttori di funzioni. In que ```javascript const info = { - [Symbol("a")]: "b", + [Symbol('a')]: 'b', }; console.log(info); @@ -3161,7 +3158,7 @@ La funzione `getList` riceve un array come argomento. Tra le parentesi della fun `[x, ...y] = [1, 2, 3, 4]` -Con il parametro rest `...y`, mettiamo tutti gli argomenti "rimanenti" in un array. Gli argomenti rimanenti sono `2`, `3` e `4` in questo caso. +Con il parametro rest `...y`, mettiamo tutti gli argomenti "rimanenti" in un array. Gli argomenti rimanenti sono `2`, `3` e `4` in questo caso. Il valore di `y` è un array, contenente tutti i parametri rimanenti. Il valore di `x` è uguale a `1` in questo caso, quindi quando facciamo un console.log di `[x, y]`, viene loggato `[1, [2, 3, 4]]`. La funzione `getUser` riceve un oggetto. Con le arrow functions, non _è necessario_ scrivere parentesi graffe se restituiamo solo un valore. Tuttavia, se vuoi restituire istantaneamente un _oggetto_ da una arrow function, devi scriverlo tra parentesi tonde, altrimenti tutto ciò che si trova tra le due parentesi graffe verrà interpretato come un'istruzione di blocco. In questo caso il codice tra parentesi non è un codice JavaScript valido, quindi viene generato un `SyntaxError`. @@ -3178,7 +3175,7 @@ La seguente funzione avrebbe restituito un oggetto: ###### 99. Qual è l'output? ```javascript -const name = "Lydia"; +const name = 'Lydia'; console.log(name()); ``` @@ -3210,8 +3207,8 @@ I ReferenceErrors vengono generati quando JavaScript non è in grado di trovare ```javascript // 🎉✨ This is my 100th question! ✨🎉 -const output = `${[] && "Im"}possible! -You should${"" && `n't`} see a therapist after so much JavaScript lol`; +const output = `${[] && 'Im'}possible! +You should${'' && `n't`} see a therapist after so much JavaScript lol`; ``` - A: `possible! You should see a therapist after so much JavaScript lol` @@ -3237,7 +3234,7 @@ You should${"" && `n't`} see a therapist after so much JavaScript lol`; ```javascript const one = false || {} || null; -const two = null || false || ""; +const two = null || false || ''; const three = [] || 0 || true; console.log(one, two, three); @@ -3269,16 +3266,16 @@ Con l'operatore `||` possiamo restituire il primo operando veritiero. Se tutti i ###### 102. Qual è il valore dell'output? ```javascript -const myPromise = () => Promise.resolve("I have resolved!"); +const myPromise = () => Promise.resolve('I have resolved!'); function firstFunction() { - myPromise().then((res) => console.log(res)); - console.log("second"); + myPromise().then(res => console.log(res)); + console.log('second'); } async function secondFunction() { console.log(await myPromise()); - console.log("second"); + console.log('second'); } firstFunction(); @@ -3316,8 +3313,8 @@ Ciò significa che ha aspettato che `myPromise` si risolvesse con il valore `I h const set = new Set(); set.add(1); -set.add("Lydia"); -set.add({ name: "Lydia" }); +set.add('Lydia'); +set.add({ name: 'Lydia' }); for (let item of set) { console.log(item + 2); @@ -3377,13 +3374,13 @@ In questo caso, abbiamo appena passato il valore numerico `5`. Restituisce una p ```javascript function compareMembers(person1, person2 = person) { if (person1 !== person2) { - console.log("Not the same!"); + console.log('Not the same!'); } else { - console.log("They are the same!"); + console.log('They are the same!'); } } -const person = { name: "Lydia" }; +const person = { name: 'Lydia' }; compareMembers(person); ``` @@ -3422,7 +3419,7 @@ const colorConfig = { yellow: false, }; -const colors = ["pink", "red", "blue"]; +const colors = ['pink', 'red', 'blue']; console.log(colorConfig.colors[1]); ``` @@ -3451,7 +3448,7 @@ JavaScript interpreta (o decomprime) le istruzioni. Quando usiamo la notazione t ###### 107. Qual è il suo valore? ```javascript -console.log("❤️" === "❤️"); +console.log('❤️' === '❤️'); ``` - A: `true` @@ -3472,14 +3469,14 @@ Le emoji sono unicode. L'unicode per l'emoji del cuore è `"U+2764 U+FE0F"`. Que ###### 108. Quale di questi metodi modifica l'array originale? ```javascript -const emojis = ["✨", "🥑", "😍"]; +const emojis = ['✨', '🥑', '😍']; -emojis.map((x) => x + "✨"); -emojis.filter((x) => x !== "🥑"); -emojis.find((x) => x !== "🥑"); -emojis.reduce((acc, cur) => acc + "✨"); -emojis.slice(1, 2, "✨"); -emojis.splice(1, 2, "✨"); +emojis.map(x => x + '✨'); +emojis.filter(x => x !== '🥑'); +emojis.find(x => x !== '🥑'); +emojis.reduce((acc, cur) => acc + '✨'); +emojis.slice(1, 2, '✨'); +emojis.splice(1, 2, '✨'); ``` - A: `All of them` @@ -3495,7 +3492,6 @@ emojis.splice(1, 2, "✨"); Con il metodo `splice` modifichiamo l'array originale cancellando, sostituendo o aggiungendo elementi. In questo caso, abbiamo rimosso 2 elementi dall'indice 1 (abbiamo rimosso `'🥑'` e `'😍'`) e aggiunto invece l'emoji ✨. `map`, `filter` e `slice` restituiscono un nuovo array, `find` restituisce un elemento e `reduce` restituisce un valore ridotto. -

@@ -3504,10 +3500,10 @@ Con il metodo `splice` modifichiamo l'array originale cancellando, sostituendo o ###### 109. Qual è l'output? ```javascript -const food = ["🍕", "🍫", "🥑", "🍔"]; +const food = ['🍕', '🍫', '🥑', '🍔']; const info = { favoriteFood: food[0] }; -info.favoriteFood = "🍝"; +info.favoriteFood = '🍝'; console.log(food); ``` @@ -3527,7 +3523,6 @@ Impostiamo il valore della proprietà `favoriteFood` sull'oggetto `info` uguale In JavaScript, i tipi di dati primitivi (tutto ciò che non è un oggetto) interagiscono per _value_. In questo caso, impostiamo il valore della proprietà `favoriteFood` sull'oggetto `info` uguale al valore del primo elemento nell'array `food`, in questo caso la stringa con l'emoji della pizza (`'🍕'`). Una stringa è un tipo di dati primitivo e interagisce per valore (vedi il mio [blogpost](https://www.theavocoder.com/complete-javascript/2018/12/21/by-value-vs-by-reference) se sei interessato a saperne di più). Quindi, cambiamo il valore della proprietà `favoriteFood` sull'oggetto `info`. L'array `food` non è cambiato, poiché il valore di `favoriteFood` era semplicemente una _copia_ del valore del primo elemento nell'array e non ha un riferimento allo stesso punto in memoria dell'elemento su ` food[0]`. Quando logghiamo food, è ancora l'array originale, `['🍕', '🍫', '🥑', '🍔']`. -

@@ -3561,7 +3556,7 @@ const jsonArray = JSON.stringify([1, 2, 3]); // '[1, 2, 3]' JSON.parse(jsonArray); // [1, 2, 3] // Stringhiamo un object in un JSON valido, quindi analizziamo la stringa JSON come valore JavaScript: -const jsonArray = JSON.stringify({ name: "Lydia" }); // '{"name":"Lydia"}' +const jsonArray = JSON.stringify({ name: 'Lydia' }); // '{"name":"Lydia"}' JSON.parse(jsonArray); // { name: 'Lydia' } ``` @@ -3573,11 +3568,11 @@ JSON.parse(jsonArray); // { name: 'Lydia' } ###### 111. Qual è l'output? ```javascript -let name = "Lydia"; +let name = 'Lydia'; function getName() { console.log(name); - let name = "Sarah"; + let name = 'Sarah'; } getName(); @@ -3600,7 +3595,7 @@ Le variabili con la chiave `let` (e `const`) vengono sollevate, ma a differenza Se non avessimo dichiarato la variabile `name` all'interno della funzione `getName`, JavaScript avrebbe esaminato la _scope chain_. Lo scope esterno ha una variabile chiamata `name` con il valore di `Lydia`. In tal caso, avrebbe loggato "Lydia". ```javascript -let name = "Lydia"; +let name = 'Lydia'; function getName() { console.log(name); @@ -3618,11 +3613,11 @@ getName(); // Lydia ```javascript function* generatorOne() { - yield ["a", "b", "c"]; + yield ['a', 'b', 'c']; } function* generatorTwo() { - yield* ["a", "b", "c"]; + yield* ['a', 'b', 'c']; } const one = generatorOne(); @@ -3668,7 +3663,7 @@ console.log(two.next().value); // undefined ###### 113. Qual è l'output? ```javascript -console.log(`${((x) => x)("I love")} to program`); +console.log(`${(x => x)('I love')} to program`); ``` - A: `I love to program` @@ -3693,7 +3688,7 @@ Le espressioni all'interno dei template literals vengono valutate per prime. Ci ```javascript let config = { alert: setInterval(() => { - console.log("Alert!"); + console.log('Alert!'); }, 1000), }; @@ -3725,16 +3720,16 @@ Dal momento che non è stato cancellato, la funzione di callback `setInterval` v ```javascript const myMap = new Map(); -const myFunc = () => "greeting"; +const myFunc = () => 'greeting'; -myMap.set(myFunc, "Hello world!"); +myMap.set(myFunc, 'Hello world!'); //1 -myMap.get("greeting"); +myMap.get('greeting'); //2 myMap.get(myFunc); //3 -myMap.get(() => "greeting"); +myMap.get(() => 'greeting'); ``` - A: 1 @@ -3761,14 +3756,14 @@ Quando si aggiunge una coppia chiave/valore usando il metodo `set`, la chiave sa ```javascript const person = { - name: "Lydia", + name: 'Lydia', age: 21, }; const changeAge = (x = { ...person }) => (x.age += 1); const changeAgeAndName = (x = { ...person }) => { x.age += 1; - x.name = "Sarah"; + x.name = 'Sarah'; }; changeAge(person); @@ -3792,7 +3787,6 @@ Entrambe le funzioni `changeAge` e `changeAgeAndName` hanno un parametro predefi Per prima cosa, invochiamo la funzione `changeAge` e passiamo l'oggetto `person` come argomento. Questa funzione aumenta il valore della proprietà `age` di 1. `person` ora è `{ name: "Lydia", age: 22 }`. Quindi, invochiamo la funzione `changeAgeAndName`, tuttavia non passiamo un parametro. Invece, il valore di `x` è uguale a un _nuovo_ oggetto: `{ ...person }`. Poiché si tratta di un nuovo oggetto, non influisce sui valori delle proprietà sull'oggetto `person`. `person` è ancora uguale a `{ name: "Lydia", age: 22 }`. -

@@ -3827,7 +3821,7 @@ Con l'operatore spread `...`, possiamo _distribuire_ gli iterabili come singoli ```javascript let num = 1; -const list = ["🥳", "🤠", "🥰", "🤪"]; +const list = ['🥳', '🤠', '🥰', '🤪']; console.log(list[(num += 1)]); ``` @@ -3853,11 +3847,11 @@ Con l'operando `+=`, stiamo incrementando il valore di `num` di `1`. `num` aveva ```javascript const person = { - firstName: "Lydia", - lastName: "Hallie", + firstName: 'Lydia', + lastName: 'Hallie', pet: { - name: "Mara", - breed: "Dutch Tulip Hound", + name: 'Mara', + breed: 'Dutch Tulip Hound', }, getFullName() { return `${this.firstName} ${this.lastName}`; @@ -3895,10 +3889,10 @@ Con l'operatore di concatenamento opzionale `?.`, non è più necessario verific ###### 120. Qual è l'output? ```javascript -const groceries = ["banana", "apple", "peanuts"]; +const groceries = ['banana', 'apple', 'peanuts']; -if (groceries.indexOf("banana")) { - console.log("We have to buy bananas!"); +if (groceries.indexOf('banana')) { + console.log('We have to buy bananas!'); } else { console.log(`We don't have to buy bananas!`); } @@ -3954,10 +3948,10 @@ Il metodo `language` è un `setter`. I setter non detengono un valore effettivo, ###### 122. Qual è l'output? ```javascript -const name = "Lydia Hallie"; +const name = 'Lydia Hallie'; -console.log(!typeof name === "object"); -console.log(!typeof name === "string"); +console.log(!typeof name === 'object'); +console.log(!typeof name === 'string'); ``` - A: `false` `true` @@ -3973,7 +3967,6 @@ console.log(!typeof name === "string"); `typeof name` restituisce `"string"`. La stringa `"string"` è un valore veritiero, quindi `!typeof name` restituisce il valore booleano `false`. `false === "object"` e `false === "string"` restituiscono entrambi `false`. (Se volessimo verificare se il tipo era (non)uguale a un certo tipo, avremmo dovuto scrivere `!==` invece di `!typeof`) -

@@ -3982,7 +3975,7 @@ console.log(!typeof name === "string"); ###### 123. Qual è l'output? ```javascript -const add = (x) => (y) => (z) => { +const add = x => y => z => { console.log(x, y, z); return x + y + z; }; @@ -4000,7 +3993,7 @@ add(4)(5)(6); #### Risposta: A -La funzione `add` restituisce una arrow function, che restituisce una arrow function, che restituisce arrow function (mi segui ancora?). +La funzione `add` restituisce una arrow function, che restituisce una arrow function, che restituisce arrow function (mi segui ancora?). La prima funzione riceve un argomento `x` con il valore di `4`. Invochiamo la seconda funzione, che riceve un argomento `y` con il valore `5`. Quindi invochiamo la terza funzione, che riceve un argomento `z` con il valore `6`. Quando si tenta di accedere ai valori `x`, `y` e `z` all'interno dell'ultima arrow function, il motore JS risale la catena dell'ambito per trovare i valori per `x` e `y`. Questo restituisce `4` `5` `6`.

@@ -4073,20 +4066,20 @@ myFunc(1, 2, 3); ```javascript function getFine(speed, amount) { - const formattedSpeed = new Intl.NumberFormat("en-US", { - style: "unit", - unit: "mile-per-hour", + const formattedSpeed = new Intl.NumberFormat('en-US', { + style: 'unit', + unit: 'mile-per-hour' }).format(speed); - const formattedAmount = new Intl.NumberFormat("en-US", { - style: "currency", - currency: "USD", + const formattedAmount = new Intl.NumberFormat('en-US', { + style: 'currency', + currency: 'USD' }).format(amount); return `The driver drove ${formattedSpeed} and has to pay ${formattedAmount}`; } -console.log(getFine(130, 300)); +console.log(getFine(130, 300)) ``` - A: The driver drove 130 and has to pay 300 @@ -4109,8 +4102,8 @@ Con il metodo `Intl.NumberFormat`, possiamo formattare i valori numerici in qual ###### 127. Qual è l'output? ```javascript -const spookyItems = ["👻", "🎃", "🕸"]; -({ item: spookyItems[3] } = { item: "💀" }); +const spookyItems = ['👻', '🎃', '🕸']; +({ item: spookyItems[3] } = { item: '💀' }); console.log(spookyItems); ``` @@ -4135,7 +4128,7 @@ Destrutturando gli oggetti, possiamo decomprimere i valori dall'oggetto di destr ###### 128. Qual è l'output? ```javascript -const name = "Lydia Hallie"; +const name = 'Lydia Hallie'; const age = 21; console.log(Number.isNaN(name)); @@ -4158,7 +4151,6 @@ console.log(isNaN(age)); Con il metodo `Number.isNaN`, puoi controllare se il valore passato è un _valore numerico_ e uguale a `NaN`. `name` non è un valore numerico, quindi `Number.isNaN(name)` restituisce `false`. `age` è un valore numerico, ma non è uguale a `NaN`, quindi `Numero.isNaN(age)` restituisce `false`. Con il metodo `isNaN`, puoi verificare se il valore che passi non è un numero. `name` non è un numero, quindi `isNaN(name)` restituisce true. `age` è un numero, quindi `isNaN(age)` restituisce `false`. -

@@ -4171,7 +4163,7 @@ const randomValue = 21; function getInfo() { console.log(typeof randomValue); - const randomValue = "Lydia Hallie"; + const randomValue = 'Lydia Hallie'; } getInfo(); @@ -4188,7 +4180,6 @@ getInfo(); #### Risposta: D Le variabili dichiarate con la chiave `const` non sono referenziabili prima della loro inizializzazione: questa viene chiamata _temporal dead zone_. Nella funzione `getInfo`, la variabile `randomValue` ha lo scopo nell'ambito funzionale di `getInfo`. Nella riga in cui vogliamo registrare il valore di `typeof randomValue`, la variabile `randomValue` non è ancora inizializzata: viene lanciato un `ReferenceError`! Il motore non è andato giù per la catena dell'ambito poiché abbiamo dichiarato la variabile `randomValue` nella funzione `getInfo`. -

@@ -4197,7 +4188,7 @@ Le variabili dichiarate con la chiave `const` non sono referenziabili prima dell ###### 130. Qual è l'output? ```javascript -const myPromise = Promise.resolve("Woah some cool data"); +const myPromise = Promise.resolve('Woah some cool data'); (async () => { try { @@ -4205,7 +4196,7 @@ const myPromise = Promise.resolve("Woah some cool data"); } catch { throw new Error(`Oops didn't work`); } finally { - console.log("Oh finally!"); + console.log('Oh finally!'); } })(); ``` @@ -4230,7 +4221,7 @@ Nel blocco `try`, stiamo loggando il valore atteso della variabile `myPromise`: ###### 131. Qual è l'output? ```javascript -const emojis = ["🥑", ["✨", "✨", ["🍕", "🍕"]]]; +const emojis = ['🥑', ['✨', '✨', ['🍕', '🍕']]]; console.log(emojis.flat(1)); ``` @@ -4246,7 +4237,6 @@ console.log(emojis.flat(1)); #### Risposta: B Con il metodo `flat`, possiamo creare un nuovo array appiattito. La profondità dell'array appiattito dipende dal valore che passiamo. In questo caso, abbiamo passato il valore `1` (cosa che non dovevamo fare, questo è il valore predefinito), il che significa che solo gli array sulla prima profondità verranno concatenati. `['🥑']` e `['✨', '✨', ['🍕', '🍕']]` in questo caso. Concatenando questi due array si ottengono `['🥑', '✨', '✨', ['🍕', '🍕']]`. -

@@ -4303,19 +4293,19 @@ Invochiamo `counterTwo.increment()`, che imposta `count` su `3`. Quindi, logghia ###### 133. Qual è l'output? ```javascript -const myPromise = Promise.resolve(Promise.resolve("Promise")); +const myPromise = Promise.resolve(Promise.resolve('Promise')); function funcOne() { - setTimeout(() => console.log("Timeout 1!"), 0); - myPromise.then((res) => res).then((res) => console.log(`${res} 1!`)); - console.log("Last line 1!"); + setTimeout(() => console.log('Timeout 1!'), 0); + myPromise.then(res => res).then(res => console.log(`${res} 1!`)); + console.log('Last line 1!'); } async function funcTwo() { const res = await myPromise; - console.log(`${res} 2!`); - setTimeout(() => console.log("Timeout 2!"), 0); - console.log("Last line 2!"); + console.log(`${res} 2!`) + setTimeout(() => console.log('Timeout 2!'), 0); + console.log('Last line 2!'); } funcOne(); @@ -4345,7 +4335,6 @@ In `funcTwo`, la variabile `res` ottiene `Promise` perché `Promise.resolve(Prom Quindi lo stack di chiamate è vuoto. Le promise sono _microattività_, quindi vengono risolte per prime quando lo stack di chiamate è vuoto, quindi `Promise 1!` viene registrato. Ora, da quando `funcTwo` è uscito dallo stack delle chiamate, lo stack delle chiamate è vuoto. Le callback in attesa nella coda (`() => console.log("Timeout 1!")` da `funcOne`, e `() => console.log("Timeout 2!")` da `funcTwo`) vengono aggiunti allo stack di chiamate uno per uno. Il primo callback registra `Timeout 1!` e viene eliminato dallo stack. Quindi, il secondo callback registra `Timeout 2!` e viene eliminato dallo stack. -

@@ -4360,7 +4349,7 @@ export default function sum(x) { } // index.js -import * as sum from "./sum"; +import * as sum from './sum'; ``` - A: `sum(4)` @@ -4377,12 +4366,12 @@ Con l'asterisco `*`, importiamo tutti i valori esportati da quel file, sia prede ```javascript // info.js -export const name = "Lydia"; +export const name = 'Lydia'; export const age = 21; -export default "I love JavaScript"; +export default 'I love JavaScript'; // index.js -import * as info from "./info"; +import * as info from './info'; console.log(info); ``` @@ -4413,13 +4402,13 @@ Possiamo invocare questa funzione, chiamando `sum.default` ```javascript const handler = { - set: () => console.log("Added a new property!"), - get: () => console.log("Accessed a property!"), + set: () => console.log('Added a new property!'), + get: () => console.log('Accessed a property!'), }; const person = new Proxy({}, handler); -person.name = "Lydia"; +person.name = 'Lydia'; person.name; ``` @@ -4449,7 +4438,7 @@ Quindi, accediamo a un valore di proprietà sull'oggetto proxy, la proprietà `g ###### 136. Quale delle seguenti opzioni modificherà l'oggetto `persona`? ```javascript -const person = { name: "Lydia Hallie" }; +const person = { name: 'Lydia Hallie' }; Object.seal(person); ``` @@ -4477,9 +4466,9 @@ Tuttavia, puoi comunque modificare il valore delle proprietà esistenti. ```javascript const person = { - name: "Lydia Hallie", + name: 'Lydia Hallie', address: { - street: "100 Main St", + street: '100 Main St', }, }; @@ -4508,7 +4497,7 @@ Tuttavia, blocca solo _poco profondamente_ l'oggetto, il che significa che solo ###### 138. Qual è l'output? ```javascript -const add = (x) => x + x; +const add = x => x + x; function myFunc(num = 2, value = add(num)) { console.log(num, value); @@ -4530,7 +4519,7 @@ myFunc(3); Per prima cosa, abbiamo invocato `myFunc()` senza passare alcun argomento. Dal momento che non abbiamo passato argomenti, `num` e `value` hanno i loro valori predefiniti: num è `2` e `value` il valore restituito dalla funzione `add`. Alla funzione `add`, passiamo `num` come argomento, che aveva il valore di `2`. `add` restituisce `4`, che è il valore di `value`. -Quindi, abbiamo invocato `myFunc(3)` e passato il valore `3` come valore per l'argomento `num`. Non abbiamo passato un argomento per `value`. +Quindi, abbiamo invocato `myFunc(3)` e passato il valore `3` come valore per l'argomento `num`. Non abbiamo passato un argomento per `value`. Poiché non abbiamo passato un valore per l'argomento `value`, ha ottenuto il valore predefinito: il valore restituito dalla funzione `add`. Ad `add` passiamo `num`, che ha il valore di `3`. `add` restituisce `6`, che è il valore di `value`.

@@ -4542,21 +4531,21 @@ Poiché non abbiamo passato un valore per l'argomento `value`, ha ottenuto il va ```javascript class Counter { - #number = 10; + #number = 10 increment() { - this.#number++; + this.#number++ } getNum() { - return this.#number; + return this.#number } } -const counter = new Counter(); -counter.increment(); +const counter = new Counter() +counter.increment() -console.log(counter.#number); +console.log(counter.#number) ``` - A: `10` @@ -4580,8 +4569,8 @@ In ES2020, possiamo aggiungere variabili private nelle classi usando `#`. Non po ```javascript const teams = [ - { name: "Team 1", members: ["Paul", "Lisa"] }, - { name: "Team 2", members: ["Laura", "Tim"] }, + { name: 'Team 1', members: ['Paul', 'Lisa'] }, + { name: 'Team 2', members: ['Laura', 'Tim'] }, ]; function* getMembers(members) { @@ -4624,8 +4613,8 @@ Se avessimo scritto `yield`, `return yield` o `return`, l'intera funzione del ge ```javascript const person = { - name: "Lydia Hallie", - hobbies: ["coding"], + name: 'Lydia Hallie', + hobbies: ['coding'], }; function addHobby(hobby, hobbies = person.hobbies) { @@ -4633,9 +4622,9 @@ function addHobby(hobby, hobbies = person.hobbies) { return hobbies; } -addHobby("running", []); -addHobby("dancing"); -addHobby("baking", person.hobbies); +addHobby('running', []); +addHobby('dancing'); +addHobby('baking', person.hobbies); console.log(person.hobbies); ``` @@ -4694,7 +4683,7 @@ const pet = new Flamingo(); #### Risposta: B -Creiamo la variabile `pet` che è un'istanza della classe `Flamingo`. Quando istanziamo questa istanza, il `constructor` su `Flamingo` viene chiamato. Per prima cosa, `"I'm pink. 🌸"` viene loggato, dopodiché chiamiamo `super()`. +Creiamo la variabile `pet` che è un'istanza della classe `Flamingo`. Quando istanziamo questa istanza, il `constructor` su `Flamingo` viene chiamato. Per prima cosa, `"I'm pink. 🌸"` viene loggato, dopodiché chiamiamo `super()`. `super()` chiama il costruttore della classe genitore, `Bird`. Il costruttore in `Bird` viene chiamato e registra `"I'm a bird. 🦢"`. @@ -4706,11 +4695,11 @@ Creiamo la variabile `pet` che è un'istanza della classe `Flamingo`. Quando ist ###### 143. Quale delle opzioni genera un errore? ```javascript -const emojis = ["🎄", "🎅🏼", "🎁", "⭐"]; +const emojis = ['🎄', '🎅🏼', '🎁', '⭐']; -/* 1 */ emojis.push("🦌"); +/* 1 */ emojis.push('🦌'); /* 2 */ emojis.splice(0, 2); -/* 3 */ emojis = [...emojis, "🥂"]; +/* 3 */ emojis = [...emojis, '🥂']; /* 4 */ emojis.length = 0; ``` @@ -4752,7 +4741,7 @@ const person = { #### Risposta: C -Gli oggetti non sono iterabili per impostazione predefinita. Un iterabile è un iterabile se è presente il protocollo iteratore. +Gli oggetti non sono iterabili per impostazione predefinita. Un iterabile è un iterabile se è presente il protocollo iteratore. Possiamo aggiungerlo manualmente aggiungendo il simbolo dell'iteratore `[Symbol.iterator]`, che deve restituire un oggetto generatore, ad esempio trasformandolo in una funzione del generatore `*[Symbol.iterator]() {}`. Questa funzione di generazione deve fornire gli `Object.values` dell'oggetto `person` se vogliamo che restituisca l'array `["Lydia Hallie", 21]`: `yield* Object.values(this)`.

@@ -4766,11 +4755,11 @@ Possiamo aggiungerlo manualmente aggiungendo il simbolo dell'iteratore `[Symbol. let count = 0; const nums = [0, 1, 2, 3]; -nums.forEach((num) => { - if (num) count += 1; -}); +nums.forEach(num => { + if (num) count += 1 +}) -console.log(count); +console.log(count) ``` - A: 1 @@ -4794,12 +4783,12 @@ La condizione `if` all'interno del ciclo `forEach` controlla se il valore di `nu ```javascript function getFruit(fruits) { - console.log(fruits?.[1]?.[1]); + console.log(fruits?.[1]?.[1]) } -getFruit([["🍊", "🍌"], ["🍍"]]); -getFruit(); -getFruit([["🍍"], ["🍊", "🍌"]]); +getFruit([['🍊', '🍌'], ['🍍']]) +getFruit() +getFruit([['🍍'], ['🍊', '🍌']]) ``` - A: `null`, `undefined`, 🍌 @@ -4819,7 +4808,6 @@ Innanzitutto, stiamo cercando di registrare il secondo elemento nel sottoarray ` Quindi, stiamo invocando la funzione `getFruits` senza passare un valore come argomento, il che significa che `fruits` ha un valore di `undefined` per impostazione predefinita. Poiché stiamo concatenando condizionatamente l'elemento sull'indice `1` di `fruits`, restituisce `undefined` poiché questo elemento sull'indice `1` non esiste. Infine, stiamo cercando di registrare il secondo elemento nel sottoarray `['🍊', '🍌']` di `['🍍'], ['🍊', '🍌']`. L'elemento nell'indice `1` all'interno di questo sottoarray è `🍌`, che viene registrato. -

@@ -4829,19 +4817,19 @@ Infine, stiamo cercando di registrare il secondo elemento nel sottoarray `['🍊 ```javascript class Calc { - constructor() { - this.count = 0; - } + constructor() { + this.count = 0 + } - increase() { - this.count++; - } + increase() { + this.count ++ + } } -const calc = new Calc(); -new Calc().increase(); +const calc = new Calc() +new Calc().increase() -console.log(calc.count); +console.log(calc.count) ``` - A: `0` @@ -4855,7 +4843,6 @@ console.log(calc.count); #### Risposta: A Impostiamo la variabile `calc` uguale a una nuova istanza della classe `Calc`. Quindi, istanziamo una nuova `Calc` e invochiamo il metodo `increase` su questa istanza. Poiché la proprietà count è all'interno del costruttore della classe `Calc`, la proprietà count non è condivisa sul prototipo di `Calc`. Ciò significa che il valore di count non è stato aggiornato per l'istanza a cui punta il calc, count è ancora `0`. -

@@ -4865,25 +4852,25 @@ Impostiamo la variabile `calc` uguale a una nuova istanza della classe `Calc`. Q ```javascript const user = { - email: "e@mail.com", - password: "12345", -}; + email: "e@mail.com", + password: "12345" +} const updateUser = ({ email, password }) => { - if (email) { - Object.assign(user, { email }); - } + if (email) { + Object.assign(user, { email }) + } - if (password) { - user.password = password; - } + if (password) { + user.password = password + } - return user; -}; + return user +} -const updatedUser = updateUser({ email: "new@email.com" }); +const updatedUser = updateUser({ email: "new@email.com" }) -console.log(updatedUser === user); +console.log(updatedUser === user) ``` - A: `false` @@ -4906,13 +4893,13 @@ La funzione `updateUser` aggiorna i valori delle proprietà `email` e `password` ###### 149. Qual è l'output? ```javascript -const fruit = ["🍌", "🍊", "🍎"]; +const fruit = ['🍌', '🍊', '🍎'] -fruit.slice(0, 1); -fruit.splice(0, 1); -fruit.unshift("🍇"); +fruit.slice(0, 1) +fruit.splice(0, 1) +fruit.unshift('🍇') -console.log(fruit); +console.log(fruit) ``` - A: `['🍌', '🍊', '🍎']` @@ -4938,13 +4925,13 @@ Infine, invochiamo il metodo `unshift` sull'array `fruit`, che modifica l'array ```javascript const animals = {}; -let dog = { emoji: "🐶" }; -let cat = { emoji: "🐈" }; +let dog = { emoji: '🐶' } +let cat = { emoji: '🐈' } -animals[dog] = { ...dog, name: "Mara" }; -animals[cat] = { ...cat, name: "Sara" }; +animals[dog] = { ...dog, name: "Mara" } +animals[cat] = { ...cat, name: "Sara" } -console.log(animals[dog]); +console.log(animals[dog]) ``` - A: `{ emoji: "🐶", name: "Mara" }` @@ -4959,12 +4946,12 @@ console.log(animals[dog]); Le chiavi degli oggetti vengono convertite in stringhe. -Poiché il valore di `dog` è un oggetto, `animals[dog]` significa in realtà che stiamo creando una nuova proprietà chiamata `"object Object"` uguale al nuovo oggetto. +Poiché il valore di `dog` è un oggetto, `animals[dog]` significa in realtà che stiamo creando una nuova proprietà chiamata `"object Object"` uguale al nuovo oggetto. `animals["object Object"]` è ora uguale a `{ emoji: "🐶", name: "Mara"}`. Anche `cat` è un oggetto, il che significa che `animals[cat]` in realtà stiamo sovrascrivendo il valore di `animals["object Object"]` con le nuove proprietà cat. -Loggando `animals[dog]`, o effettivamente `animals["object Object"]`, poiché la conversione dell'oggetto `dog` in una stringa risulta `"object Object"`, restituisce `{ emoji: "🐈", name: "Sara" }`. +Loggando `animals[dog]`, o effettivamente `animals["object Object"]`, poiché la conversione dell'oggetto `dog` in una stringa risulta `"object Object"`, restituisce `{ emoji: "🐈", name: "Sara" }`.

@@ -4975,14 +4962,14 @@ Loggando `animals[dog]`, o effettivamente `animals["object Object"]`, poiché la ```javascript const user = { - email: "my@email.com", - updateEmail: (email) => { - this.email = email; - }, -}; + email: "my@email.com", + updateEmail: email => { + this.email = email + } +} -user.updateEmail("new@email.com"); -console.log(user.email); +user.updateEmail("new@email.com") +console.log(user.email) ``` - A: `my@email.com` @@ -5005,20 +4992,20 @@ La funzione `updateEmail` è una arrow function e non è legata all'oggetto `use ###### 152. Qual è l'output? ```javascript -const promise1 = Promise.resolve("First"); -const promise2 = Promise.resolve("Second"); -const promise3 = Promise.reject("Third"); -const promise4 = Promise.resolve("Fourth"); +const promise1 = Promise.resolve('First') +const promise2 = Promise.resolve('Second') +const promise3 = Promise.reject('Third') +const promise4 = Promise.resolve('Fourth') const runPromises = async () => { - const res1 = await Promise.all([promise1, promise2]); - const res2 = await Promise.all([promise3, promise4]); - return [res1, res2]; -}; + const res1 = await Promise.all([promise1, promise2]) + const res2 = await Promise.all([promise3, promise4]) + return [res1, res2] +} runPromises() - .then((res) => console.log(res)) - .catch((err) => console.log(err)); + .then(res => console.log(res)) + .catch(err => console.log(err)) ``` - A: `[['First', 'Second'], ['Fourth']]` @@ -5038,19 +5025,16 @@ Il metodo `Promise.all` esegue le promise passate in parallelo. Se una promise f --- -###### 153. Quale dovrebbe essere il valore di `method` per loggare `{nome: "Lydia", età: 22}`? +###### 153. Quale dovrebbe essere il valore di `method` per loggare ` {nome: "Lydia", età: 22} `? ```javascript -const keys = ["name", "age"]; -const values = ["Lydia", 22]; +const keys = ["name", "age"] +const values = ["Lydia", 22] -const method = - /* ?? */ - Object[method]( - keys.map((_, i) => { - return [keys[i], values[i]]; - }) - ); // { name: "Lydia", age: 22 } +const method = /* ?? */ +Object[method](keys.map((_, i) => { + return [keys[i], values[i]] +})) // { name: "Lydia", age: 22 } ``` - A: `entries` @@ -5075,18 +5059,18 @@ Questo crea una matrice di sottoarray contenenti le chiavi e i valori corretti, ###### 154. Qual è l'output? ```javascript -const createMember = ({ email, address = {} }) => { - const validEmail = /.+\@.+\..+/.test(email); - if (!validEmail) throw new Error("Valid email pls"); +const createMember = ({ email, address = {}}) => { + const validEmail = /.+\@.+\..+/.test(email) + if (!validEmail) throw new Error("Valid email pls") - return { - email, - address: address ? address : null, - }; -}; + return { + email, + address: address ? address : null + } +} -const member = createMember({ email: "my@email.com" }); -console.log(member); +const member = createMember({ email: "my@email.com" }) +console.log(member) ``` - A: `{ email: "my@email.com", address: null }` @@ -5109,13 +5093,13 @@ Il valore predefinito di `address` è un oggetto vuoto `{}`. Quando abbiamo impo ###### 155. Qual è l'output? ```javascript -let randomValue = { name: "Lydia" }; -randomValue = 23; +let randomValue = { name: "Lydia" } +randomValue = 23 if (!typeof randomValue === "string") { - console.log("It's not a string!"); + console.log("It's not a string!") } else { - console.log("Yay it's a string!"); + console.log("Yay it's a string!") } ``` diff --git a/ja-JA/README-ja_JA.md b/ja-JA/README-ja_JA.md index 6fcf3655..1cc85d76 100644 --- a/ja-JA/README-ja_JA.md +++ b/ja-JA/README-ja_JA.md @@ -1,13 +1,13 @@ -# JavaScript (高度な) 問題集 +# JavaScript (高度な) 問題集 -私は毎日、JavaScript に関する選択問題を [Instagram](https://www.instagram.com/theavocoder)に投稿していますが、ここにも投稿します。 +私は毎日、JavaScriptに関する選択問題を [Instagram](https://www.instagram.com/theavocoder)に投稿していますが、ここにも投稿します。 -初級から上級まで: JavaScript の知識のテストを行ったり、知識を少し深めたり、コーディング面接の準備をしてください。:muscle: :rocket: 私はこのレポを毎週新しい質問で更新します。Last update: June 29th +初級から上級まで: JavaScriptの知識のテストを行ったり、知識を少し深めたり、コーディング面接の準備をしてください。:muscle: :rocket: 私はこのレポを毎週新しい質問で更新します。Last update: June 29th 答えは質問の下の折りたたまれたセクションにあります、クリックすればそれを広げられます。幸運を祈ります。:heart: -利用可能な言語リスト: +利用可能な言語リスト: - [🇸🇦 العربية](../ar-AR/README_AR.md) - [🇪🇬 اللغة العامية](../ar-EG/README_ar-EG.md) - [🇧🇦 Bosanski](../bs-BS/README-bs_BS.md) @@ -21,7 +21,6 @@ - [🇳🇱 Nederlands](../nl-NL/README.md) - [🇵🇱 Polski](../pl-PL/README.md) - [🇧🇷 Português Brasil](../pt-BR/README_pt_BR.md) -- [🇷o Română](../ro-RO/README.ro.md) - [🇷🇺 Русский](../ru-RU/README.md) - [🇽🇰 Shqip](../sq-KS/README_sq_KS.md) - [🇹🇭 ไทย](../th-TH/README-th_TH.md) @@ -56,13 +55,13 @@ sayHi(); #### 答え: D -関数内で、まず `var`キーワードを使って `name`変数を宣言します。これは、変数が定義されている行に実際に到達するまで、変数がデフォルト値の `undefined`で初期化される(作成時にメモリ空間が設定される)ことを意味します。 +関数内で、まず `var`キーワードを使って `name`変数を宣言します。これは、変数が定義されている行に実際に到達するまで、変数がデフォルト値の `undefined`で初期化される(作成時にメモリ空間が設定される)ことを意味します。 `name`変数をログ出力を実行している行では、まだ変数を定義していませんので、`undefined`の値を保持しています。 `let`キーワード(または`const`)を持つ変数は持ち上げられますが、 `var`とは異なり、初期化されません。それらを宣言(初期化)する行の前にはアクセスできません。これは"temporal dead zone"と呼ばれます。 -宣言される前に変数にアクセスしようとすると、JavaScript は `ReferenceError`を投げます。 +宣言される前に変数にアクセスしようとすると、JavaScriptは `ReferenceError`を投げます。

@@ -90,9 +89,9 @@ for (let i = 0; i < 3; i++) { #### 答え: C -JavaScript のイベントキューのため、`setTimeout`コールバック関数はループが実行された後に呼び出されます。最初のループの変数 `i`は`var`キーワードを使って宣言されているので、この値はグローバル変数となります。ループの間、単項演算子 `++`を使用して、毎回 `i`の値を`1`ずつインクリメントしました。 最初の例では `setTimeout`コールバック関数が呼び出されるまでに`i`は`3`となりました。 +JavaScriptのイベントキューのため、`setTimeout`コールバック関数はループが実行された後に呼び出されます。最初のループの変数 `i`は`var`キーワードを使って宣言されているので、この値はグローバル変数となります。ループの間、単項演算子 `++`を使用して、毎回 `i`の値を`1`ずつインクリメントしました。 最初の例では `setTimeout`コールバック関数が呼び出されるまでに`i`は`3`となりました。 -2 番目のループでは、変数 `i`が `let`キーワードを使って宣言されました。 `let`(または`const`)キーワードで宣言された変数はブロックスコープです(ブロックは `{}`の間のものです)。それぞれの繰り返しの間、 `i`は新しい値を持ち、それぞれの値はループの内側にあります。 +2番目のループでは、変数 `i`が `let`キーワードを使って宣言されました。 `let`(または`const`)キーワードで宣言された変数はブロックスコープです(ブロックは `{}`の間のものです)。それぞれの繰り返しの間、 `i`は新しい値を持ち、それぞれの値はループの内側にあります。

@@ -107,7 +106,7 @@ const shape = { diameter() { return this.radius * 2; }, - perimeter: () => 2 * Math.PI * this.radius, + perimeter: () => 2 * Math.PI * this.radius }; shape.diameter(); @@ -126,7 +125,7 @@ shape.perimeter(); `diameter`の値は正則関数であり、`perimeter`の値はアロー関数です。 -アロー関数では、`this`キーワードは通常の関数とは異なり、現在の周囲の範囲を参照します。これは、`perimeter`関数を呼ぶと、shape オブジェクトではなく、その周囲の範囲(例えば window)を参照することを意味します。 +アロー関数では、`this`キーワードは通常の関数とは異なり、現在の周囲の範囲を参照します。これは、`perimeter`関数を呼ぶと、shapeオブジェクトではなく、その周囲の範囲(例えば window)を参照することを意味します。 そのオブジェクトには`radius`という値はなく、`undefined`を返します。 @@ -153,7 +152,7 @@ shape.perimeter(); 単項プラスは、オペランドを数値に変換しようとします。`true`は`1`、`false`は`0`です -文字列「Lydia」は truthy value です。ここで求めているのは、「この truthy value は、falsy なのか」ということです。これは `false`を返します。 +文字列「Lydia」は truthy valueです。ここで求めているのは、「このtruthy valueは、falsyなのか」ということです。これは `false`を返します。

@@ -164,12 +163,12 @@ shape.perimeter(); ```javascript const bird = { - size: "small", + size: "small" }; const mouse = { name: "Mickey", - small: true, + small: true }; ``` @@ -183,15 +182,15 @@ const mouse = { #### 答え: A -JavaScript では、すべてのオブジェクトキーは文字列です(Symbol でない限り)。たとえそれを文字列として入力していなくても、それらは常にフードの下で文字列に変換されます。 +JavaScriptでは、すべてのオブジェクトキーは文字列です(Symbolでない限り)。たとえそれを文字列として入力していなくても、それらは常にフードの下で文字列に変換されます。 -JavaScript は、ステートメントを解釈(または、ボックス解除)します。大括弧表記を使用すると、最初の左大括弧 `[`を見て、右大括弧 `]`が見つかるまで進みます。その時だけ、そのステートメントを評価します。 +JavaScriptは、ステートメントを解釈(または、ボックス解除)します。大括弧表記を使用すると、最初の左大括弧 `[`を見て、右大括弧 `]`が見つかるまで進みます。その時だけ、そのステートメントを評価します。 `mouse [bird.size]`: まず最初に、`bird.size`が評価されます。これは文字列の `"small"`となります。 `mouse["small"]`は、`true`を返します。 しかし、ドット表記では、これは起こりません。 `mouse`は`bird`と呼ばれるキーを持っていません。 つまり`mouse.bird`は`undefined`となります。 -また、ドット表記を使って `size`を求めます: `mouse.bird.size`。 mouse.bird は未定義なので、実際には undefined.size を要求しています。これは有効ではないので、`Cannot read property "size" of undefined`ような、エラーをスローします。 +また、ドット表記を使って `size`を求めます: `mouse.bird.size`。 mouse.birdは未定義なので、実際にはundefined.sizeを要求しています。これは有効ではないので、`Cannot read property "size" of undefined`ような、エラーをスローします。

@@ -222,13 +221,13 @@ console.log(d.greeting); #### 答え: A -JavaScript では、すべてのオブジェクトは互いに等しく設定すると参照によって相互作用します。 +JavaScriptでは、すべてのオブジェクトは互いに等しく設定すると参照によって相互作用します。 まず、変数`c`は、オブジェクトに対する値を保持します。その後、`c`オブジェクトに対して持っている値と同じ参照で`d`に代入します。 -1 つのオブジェクトを変更すると、それらすべてが変更されます。 +1つのオブジェクトを変更すると、それらすべてが変更されます。

@@ -261,7 +260,7 @@ console.log(b === c); `==`演算子を使うとき、同じ値を持っているかどうか? をチェックするだけとなります。それらは両方とも`3`の値を持っているので、それは`true`を返します。 -しかし、`===`演算子を使う時は、値と型は同じであるべきです。 そうでないので: `new Number()`は数値ではなく、**オブジェクト**となります。なので、両方とも false を返します。 +しかし、`===`演算子を使う時は、値と型は同じであるべきです。 そうでないので: `new Number()`は数値ではなく、**オブジェクト**となります。なので、両方ともfalseを返します。

@@ -322,7 +321,7 @@ console.log(greetign); #### 答え: A -グローバルオブジェクトに、空のオブジェクトを作成したばかりなので、オブジェクトはログ出力されます。`greeting`を`greetign`と誤って入力した場合、JS インタプリタは実際にこれを `global.greetign = {}`(またはブラウザの `window.greetign = {}`)と見なします。 +グローバルオブジェクトに、空のオブジェクトを作成したばかりなので、オブジェクトはログ出力されます。`greeting`を`greetign`と誤って入力した場合、JSインタプリタは実際にこれを `global.greetign = {}`(またはブラウザの `window.greetign = {}`)と見なします。 これを避けるために、"use strict"を使用する事ができます。これにより、変数を何かに設定する前に、変数宣言したことを確認できます。 @@ -351,7 +350,7 @@ bark.animal = "dog"; #### 答え: A -関数はオブジェクトとなるので、これは JavaScript で可能です。(プリミティブ型以外はすべてオブジェクトです。) +関数はオブジェクトとなるので、これはJavaScriptで可能です。(プリミティブ型以外はすべてオブジェクトです。) 関数は特別な種類のオブジェクトです。自分で書いたコードは実際の機能ではありません。関数はプロパティを持つオブジェクトです。よって、このプロパティは呼び出し可能となります。 @@ -369,7 +368,7 @@ function Person(firstName, lastName) { } const member = new Person("Lydia", "Hallie"); -Person.getFullName = function () { +Person.getFullName = function() { return `${this.firstName} ${this.lastName}`; }; @@ -389,7 +388,7 @@ console.log(member.getFullName()); 通常のオブジェクトのようにコンストラクタにプロパティを追加することはできません。一度にすべてのオブジェクトに機能を追加したい場合は、代わりにプロトタイプを使用する必要があります。だからこの場合は、 ```js -Person.prototype.getFullName = function () { +Person.prototype.getFullName = function() { return `${this.firstName} ${this.lastName}`; }; ``` @@ -398,7 +397,7 @@ Person.prototype.getFullName = function () { その場合、多くのメモリスペースを浪費する事でしょう。なぜならそれらはまだその特性を持ち、それは各インスタンスのためにメモリスペースを消費するからです。 -その代わりに、プロトタイプに追加するだけであれば、メモリ内の 1 箇所に配置するだけで、すべてのユーザーがアクセスできます。 +その代わりに、プロトタイプに追加するだけであれば、メモリ内の1箇所に配置するだけで、すべてのユーザーがアクセスできます。

@@ -441,7 +440,7 @@ console.log(sarah); --- -###### 13. イベント伝播の 3 つの段階はどれですか? +###### 13. イベント伝播の3つの段階はどれですか? - A: Target > Capturing > Bubbling - B: Bubbling > Target > Capturing @@ -474,9 +473,9 @@ console.log(sarah); **基本オブジェクト**を除き、すべてのオブジェクトにプロトタイプがあります。ベースオブジェクトは`.toString`のようないくつかのメソッドとプロパティにアクセスできます。 -これが、組み込みの JavaScript メソッドを使用できる理由です。このような方法はすべてプロトタイプで利用できます。 +これが、組み込みのJavaScriptメソッドを使用できる理由です。このような方法はすべてプロトタイプで利用できます。 -JavaScript はそれをあなたのオブジェクト上で直接見つけることはできませんが、プロトタイプチェーンをたどり、見つけます。 +JavaScriptはそれをあなたのオブジェクト上で直接見つけることはできませんが、プロトタイプチェーンをたどり、見つけます。

@@ -503,9 +502,9 @@ sum(1, "2"); #### 答え: C -JavaScript は、**動的に型付けされた言語**です。: 特定の変数がどんな型であるかは指定しません。知らないうちに、値が自動的に別の型に変換されることがあります。この事を`implicit type coercion`と呼ばれてます。 **Coercion**は、ある型から別の型に変換しています。 +JavaScriptは、**動的に型付けされた言語**です。: 特定の変数がどんな型であるかは指定しません。知らないうちに、値が自動的に別の型に変換されることがあります。この事を`implicit type coercion`と呼ばれてます。 **Coercion**は、ある型から別の型に変換しています。 -この例では、関数が意味を成して値を返すために、JavaScript は数字の`1`を文字列に変換します。数値型(`1`)と 文字列型(`'2'`)の追加中は、数字は文字列として扱われます。 +この例では、関数が意味を成して値を返すために、JavaScriptは数字の`1`を文字列に変換します。数値型(`1`)と 文字列型(`'2'`)の追加中は、数字は文字列として扱われます。 `"Hello"+"World"`のように文字列を連結することができるので、ここで起こっているのは`"1"+"2"`で、これは `"12"`を返します。 @@ -535,11 +534,13 @@ console.log(number); **接尾辞** 単項演算子 `++`: -1.値を返す(これは`0`を返す) 2.値を増やす(number は現在`1`です) +1.値を返す(これは`0`を返す) +2.値を増やす(numberは現在`1`です) **接頭辞** 単項演算子 `++`: -1.値を増やす(数値は 2 になります) 2.値を返す(これは`2`を返します) +1.値を増やす(数値は2になります) +2.値を返す(これは`2`を返します) これは`0 2 2`を返します。 @@ -604,9 +605,9 @@ checkAge({ age: 18 }); #### 答え: C -等価性をテストするとき、プリミティブはそれらの値によって比較され、オブジェクトはそれらの参照によって比較されます。 JavaScript は、オブジェクトがメモリ内の同じ場所への参照を持っているかどうかを確認します。 +等価性をテストするとき、プリミティブはそれらの値によって比較され、オブジェクトはそれらの参照によって比較されます。 JavaScriptは、オブジェクトがメモリ内の同じ場所への参照を持っているかどうかを確認します。 -比較している 2 つのオブジェクトにはそれがありません。パラメータとして渡したオブジェクトが、等価性を確認するために使用したオブジェクトとは異なるメモリ内の場所を参照しています。 +比較している2つのオブジェクトにはそれがありません。パラメータとして渡したオブジェクトが、等価性を確認するために使用したオブジェクトとは異なるメモリ内の場所を参照しています。 これが `{ age: 18 } === { age: 18 }`と、`{ age: 18 } == { age: 18 }`の両方が、`false`を返す理由です。 @@ -664,7 +665,7 @@ getAge(); #### 答え: C -`"use strict"`を使うと、誤ってグローバル変数を宣言しないようにすることができます。変数`age`を宣言したことは一度もありませんし、`"use strict"`を使っているので参照エラーになります。 +`"use strict"`を使うと、誤ってグローバル変数を宣言しないようにすることができます。変数`age`を宣言したことは一度もありませんし、`"use strict"`を使っているので参照エラーになります。 `"use strict"`を使用しなかった場合は、プロパティ`age`がグローバルオブジェクトに追加されたことになるので、それは機能します。 @@ -673,7 +674,7 @@ getAge(); --- -###### 21. sum の値は何? +###### 21. sumの値は何? ```javascript const sum = eval("10*10+5"); @@ -696,7 +697,7 @@ const sum = eval("10*10+5"); --- -###### 22. cool_secret は、どのくらいの期間アクセス可能ですか? +###### 22. cool_secretは、どのくらいの期間アクセス可能ですか? ```javascript sessionStorage.setItem("cool_secret", 123); @@ -771,9 +772,9 @@ set.has(1); #### 答え: C -すべてのオブジェクトキー(Symbols を除く)は、文字列として自分で入力しなくても、内部では文字列です。これが、`obj.hasOwnProperty('1')`も ​​true を返す理由です。 +すべてのオブジェクトキー(Symbolsを除く)は、文字列として自分で入力しなくても、内部では文字列です。これが、`obj.hasOwnProperty('1')`も​​trueを返す理由です。 -set ではそうはいきません。上記の set には`'1'` はありません: `set.has('1')`は、`false`を返します。数値型`1`の`set.has(1)`は、`true`を返します。 +setではそうはいきません。上記のsetには`'1'` はありません: `set.has('1')`は、`false`を返します。数値型`1`の`set.has(1)`は、`true`を返します。

@@ -797,14 +798,14 @@ console.log(obj); #### 答え: C -同じ名前のキーが 2 つある場合、最初の位置にあるキーは置き換えられ、最後に指定された値になります。 +同じ名前のキーが2つある場合、最初の位置にあるキーは置き換えられ、最後に指定された値になります。

--- -###### 26. JavaScript の global execution context は、2 つを作成します。: それはグローバルオブジェクトと "this"キーワードです。 +###### 26. JavaScriptのglobal execution contextは、2つを作成します。: それはグローバルオブジェクトと "this"キーワードです。 - A: true - B: false @@ -815,7 +816,7 @@ console.log(obj); #### 答え: A -基本的な execution context は、グローバルな実行コンテキストです。それはあなたのコードの至る所でアクセス可能なものです。 +基本的なexecution contextは、グローバルな実行コンテキストです。それはあなたのコードの至る所でアクセス可能なものです。

@@ -857,7 +858,7 @@ String.prototype.giveLydiaPizza = () => { const name = "Lydia"; -console.log(name.giveLydiaPizza()); +console.log(name.giveLydiaPizza()) ``` - A: `"Just give Lydia pizza already!"` @@ -904,9 +905,9 @@ console.log(a[b]); #### 答え: B -オブジェクトキーは自動的に文字列に変換されます。オブジェクト a のキーとして、値 123 で設定しようとしています。 +オブジェクトキーは自動的に文字列に変換されます。オブジェクトaのキーとして、値123で設定しようとしています。 -しかし、オブジェクトを文字列化すると、それは`"[object Object]"`​​ になってしまいます。なので、ここで行っているのは、 `a["object Object"] = 123`です。 +しかし、オブジェクトを文字列化すると、それは`"[object Object]"`​​になってしまいます。なので、ここで行っているのは、 `a["object Object"] = 123`です。 その後、同じことをもう一度試みています。`c`は暗黙のうちに文字列化している別のオブジェクトです。そのため、`a["object Object"] = 456`となります。 @@ -941,9 +942,9 @@ baz(); `setTimeout`関数があり、それを最初に呼び出したのですが、それは最後にログ出力されました。 -これは、ブラウザにはランタイムエンジンがあるだけでなく、`WebAPI`と呼ばれるものもあるからです。`WebAPI`は最初に`setTimeout`関数を与えてくれます。例えば DOM です。 +これは、ブラウザにはランタイムエンジンがあるだけでなく、`WebAPI`と呼ばれるものもあるからです。`WebAPI`は最初に`setTimeout`関数を与えてくれます。例えばDOMです。 -callback が WebAPI にプッシュされた後、`setTimeout`関数自体(コールバックではありません!)がスタックからポップされます。 +callbackがWebAPIにプッシュされた後、`setTimeout`関数自体(コールバックではありません!)がスタックからポップされます。 @@ -955,11 +956,11 @@ callback が WebAPI にプッシュされた後、`setTimeout`関数自体(コ -WebAPI は、準備が整ったときにスタックに、なにかを追加することはできません。代わりに、コールバック関数を`queue`と呼ばれるものにプッシュします。 +WebAPIは、準備が整ったときにスタックに、なにかを追加することはできません。代わりに、コールバック関数を`queue`と呼ばれるものにプッシュします。 -event loop が機能し始めるところです。 **event loop**はスタックとタスクキューを調べます。スタックが空の場合は、キューの最初のものを取り出し、それをスタックにプッシュします。 +event loopが機能し始めるところです。 **event loop**はスタックとタスクキューを調べます。スタックが空の場合は、キューの最初のものを取り出し、それをスタックにプッシュします。 @@ -970,12 +971,14 @@ event loop が機能し始めるところです。 **event loop**はスタック --- -###### 31.ボタンをクリックしたときの event.target は何ですか? +###### 31.ボタンをクリックしたときのevent.targetは何ですか? ```html
- +
``` @@ -997,11 +1000,14 @@ event loop が機能し始めるところです。 **event loop**はスタック --- -###### 32. p 要素をクリックすると、ログ出力はどうなりますか。 + +###### 32. p要素をクリックすると、ログ出力はどうなりますか。 ```html
-

Click here!

+

+ Click here! +

``` @@ -1015,7 +1021,7 @@ event loop が機能し始めるところです。 **event loop**はスタック #### 答え: A -`p`をクリックすると、`p`と`div`の 2 つのログが表示されます。イベント伝播中は、キャプチャ、ターゲット、バブリングの 3 つのフェーズがあります。 +`p`をクリックすると、`p`と`div`の2つのログが表示されます。イベント伝播中は、キャプチャ、ターゲット、バブリングの3つのフェーズがあります。 デフォルトでは、イベントハンドラはバブリング段階で実行されます(`useCapture`を`true`に設定しない限り)。最も深くネストした要素から外側に向かって進みます。 @@ -1078,14 +1084,14 @@ typeof sayHi(); `sayHi`関数は、即時呼び出し関数式(IIFE)の戻り値を返します。この関数は`0`を返しました。それは`"number"`型です。 -参考:7 つの組み込み型しかありません: `null`, `undefined`, `boolean`, `number`, `string`, `object`, `symbol`, そして `bigint`。関数はオブジェクトなので、`"function"`型ではなく`"object"`型です。 +参考:7つの組み込み型しかありません: `null`, `undefined`, `boolean`, `number`, `string`, `object`, `symbol`, そして `bigint`。関数はオブジェクトなので、`"function"`型ではなく`"object"`型です。

--- -###### 35. これらの値のどれが falsy ですか? +###### 35. これらの値のどれがfalsyですか? ```javascript 0; @@ -1099,14 +1105,14 @@ undefined; - A: `0`, `''`, `undefined` - B: `0`, `new Number(0)`, `''`, `new Boolean(false)`, `undefined` - C: `0`, `''`, `new Boolean(false)`, `undefined` -- D: これらすべて falsy +- D: これらすべてfalsy
答え

#### 答え: A -falsy の値は 6 つだけです。 +falsyの値は6つだけです。 - `undefined` - `null` @@ -1115,7 +1121,7 @@ falsy の値は 6 つだけです。 - `''` (empty string) - `false` -`new Number`や、`new Boolean`のような関数コンストラクタは truthy です。 +`new Number`や、`new Boolean`のような関数コンストラクタはtruthyです。

@@ -1165,11 +1171,11 @@ console.log(numbers); #### 答え: C -配列の長さを超える値を配列内の要素に設定すると、JavaScript では、"empty slots"と呼ばれるものを作成します。これらは実際には、`undefined`の値を持ちますが、あなたは以下のようなものを見るでしょう +配列の長さを超える値を配列内の要素に設定すると、JavaScriptでは、"empty slots"と呼ばれるものを作成します。これらは実際には、`undefined`の値を持ちますが、あなたは以下のようなものを見るでしょう `[1, 2, 3, 7 x empty, 11]` -実行場所によって異なります(browser、node などによって異なります)。 +実行場所によって異なります(browser、nodeなどによって異なります)。

@@ -1206,18 +1212,18 @@ console.log(numbers); 後に、このブロックスコープ変数を`1`に設定し、変数`y`の値を設定します。ここで、ブロックスコープ変数`x`をログ出力します。これは`1`となります。 -`catch`ブロック以外では、`x`は未定義、`y`は 2 です。 `catch`ブロックの外側で`console.log(x)`した場合は、`undefined`を返し、`y`は`2`を返します。 +`catch`ブロック以外では、`x`は未定義、`y`は2です。 `catch`ブロックの外側で`console.log(x)`した場合は、`undefined`を返し、`y`は`2`を返します。

--- -###### 39. JavaScript のすべてはどちらかです... +###### 39. JavaScriptのすべてはどちらかです... - A: primitive か object - B: function か object -- C: ひっかけ問題! objects のみ +- C: ひっかけ問題! objectsのみ - D: number か object
答え @@ -1225,13 +1231,13 @@ console.log(numbers); #### 答え: A -JavaScript にはプリミティブ型とオブジェクトしかありません。 +JavaScriptにはプリミティブ型とオブジェクトしかありません。 プリミティブ型は、`boolean`, `null`, `undefined`, `bigint`, `number`, `string`, そして`symbol`です。 プリミティブとオブジェクトを区別するのは、プリミティブにはプロパティもメソッドもないということです。 -ただし、`'foo'.toUpperCase()`は`'FOO'`と評価され、`TypeError`にはなりません。これは、文字列のようなプリミティブのプロパティやメソッドにアクセスしようとすると、JavaScript がラッパークラスの 1 つ、すなわち`String`を使ってオブジェクトを暗黙的にラップし、式が評価された後ラッパーを直ちに破棄するためです。 +ただし、`'foo'.toUpperCase()`は`'FOO'`と評価され、`TypeError`にはなりません。これは、文字列のようなプリミティブのプロパティやメソッドにアクセスしようとすると、JavaScriptがラッパークラスの1つ、すなわち`String`を使ってオブジェクトを暗黙的にラップし、式が評価された後ラッパーを直ちに破棄するためです。 `null`と`undefined`を除くすべてのプリミティブはこの振る舞いをします。 @@ -1243,10 +1249,7 @@ JavaScript にはプリミティブ型とオブジェクトしかありません ###### 40. 何が出力されるでしょうか? ```javascript -[ - [0, 1], - [2, 3], -].reduce( +[[0, 1], [2, 3]].reduce( (acc, cur) => { return acc.concat(cur); }, @@ -1291,24 +1294,25 @@ JavaScript にはプリミティブ型とオブジェクトしかありません #### 答え: B -`null`は falsy です。`!null`は`true`を返します。`!true`は`false`を返します。 +`null`はfalsyです。`!null`は`true`を返します。`!true`は`false`を返します。 -`""`は falsy です。`!""`は`true`を返します。`!true`は`false`を返します。 +`""`はfalsyです。`!""`は`true`を返します。`!true`は`false`を返します。 -`1`は truthy です。`!1`は`false`を返します。`!false`は`true`を返します。 +`1`はtruthyです。`!1`は`false`を返します。`!false`は`true`を返します。

--- + ###### 42. `setInterval`メソッドはブラウザに何を返しますか? ```javascript setInterval(() => console.log("Hi"), 1000); ``` -- A: ユニーク id +- A: ユニークid - B: 指定されたミリ秒数 - C: 渡された関数 - D: `undefined` @@ -1318,7 +1322,7 @@ setInterval(() => console.log("Hi"), 1000); #### 答え: A -一意の ID を返します。この ID は `clearInterval()`関数で、その間隔をクリアするために使うことができます。 +一意のIDを返します。このIDは `clearInterval()`関数で、その間隔をクリアするために使うことができます。

@@ -1341,7 +1345,7 @@ setInterval(() => console.log("Hi"), 1000); #### 答え: A -文字列はイテラブルです。スプレッド演算子は、イテラブルのすべての文字を 1 つの要素にマッピングします。 +文字列はイテラブルです。スプレッド演算子は、イテラブルのすべての文字を1つの要素にマッピングします。

@@ -1398,7 +1402,7 @@ const secondPromise = new Promise((res, rej) => { setTimeout(res, 100, "two"); }); -Promise.race([firstPromise, secondPromise]).then((res) => console.log(res)); +Promise.race([firstPromise, secondPromise]).then(res => console.log(res)); ``` - A: `"one"` @@ -1413,7 +1417,7 @@ Promise.race([firstPromise, secondPromise]).then((res) => console.log(res)); 複数のプロミスを`Promise.race`メソッドに渡した時、"resolves/rejects"は、"最初"のプロミスの"resolves/rejects"を行います。 -`setTimeout`メソッドには、タイマーを渡します: 最初のプロミスには 500ms(`firstPromise`)、2 番目のプロミスには 100ms(`secondPromise`)。 +`setTimeout`メソッドには、タイマーを渡します: 最初のプロミスには500ms(`firstPromise`)、2番目のプロミスには100ms(`secondPromise`)。 これは、`secondPromise`が最初に`'two'`の値で解決されることを意味します。`res`は`'two'`の値を保持するようになり、ログ出力されます。 @@ -1457,7 +1461,7 @@ console.log(members); その要素はオブジェクトへの異なる(コピーされた)参照を持っているので、`person`変数の値を変更するだけで配列の最初の要素は変更されません。 `members`の最初の要素はまだ元のオブジェクトへの参照を保持しています。 - + `members`配列をログ出力したとき、最初の要素はまだオブジェクトの値を保持しているので、それがログ出力されます。

@@ -1470,7 +1474,7 @@ console.log(members); ```javascript const person = { name: "Lydia", - age: 21, + age: 21 }; for (const item in person) { @@ -1513,18 +1517,18 @@ console.log(3 + 4 + "5"); #### 答え: B -演算子結合性は、コンパイラーが式を評価する順序(左から右または右から左)となります。これは、すべての演算子が同じ優先順位を持つ場合にのみ発生します。演算子の種類は 1 つだけです: `+`。さらに、結合性は左から右です。 +演算子結合性は、コンパイラーが式を評価する順序(左から右または右から左)となります。これは、すべての演算子が同じ優先順位を持つ場合にのみ発生します。演算子の種類は1つだけです: `+`。さらに、結合性は左から右です。 `3 + 4`が最初に評価されます。これは数字の`7`になります。 -`7 + '5'`は、強制的に`"75"`になります。 JavaScript では、数字の`7`を文字列に変換します。質問 15 を参照してください。2 つの文字列を演算子の`+`を使って連結することができます。よって、`"7" + "5"`は、`"75"`になります。 +`7 + '5'`は、強制的に`"75"`になります。 JavaScriptでは、数字の`7`を文字列に変換します。質問15を参照してください。2つの文字列を演算子の`+`を使って連結することができます。よって、`"7" + "5"`は、`"75"`になります。

--- -###### 49. num の値は何ですか? +###### 49. numの値は何ですか? ```javascript const num = parseInt("7*6", 10); @@ -1540,9 +1544,9 @@ const num = parseInt("7*6", 10); #### 答え: C -文字列の最初の数字だけが返されます。"基数"(解析する数値の種類を指定するための 2 番目の引数: 基数 10, 16 進数, 8 進数, 2 進数など)に基づいて、`parseInt`は文字列内の文字が有効かどうかをチェックします。基数の中で有効な数字ではない文字に出会うと、構文解析を停止して次の文字を無視します。 +文字列の最初の数字だけが返されます。"基数"(解析する数値の種類を指定するための2番目の引数: 基数10, 16進数, 8進数, 2進数など)に基づいて、`parseInt`は文字列内の文字が有効かどうかをチェックします。基数の中で有効な数字ではない文字に出会うと、構文解析を停止して次の文字を無視します。 -`*`は、有効な数字ではありません。`"7"`を、10 進数の`7`に解析するだけです。そのまま num は`7`の値を保持します。 +`*`は、有効な数字ではありません。`"7"`を、10進数の`7`に解析するだけです。そのままnumは`7`の値を保持します。

@@ -1552,7 +1556,7 @@ const num = parseInt("7*6", 10); ###### 50. 何が出力されるでしょうか? ```javascript -[1, 2, 3].map((num) => { +[1, 2, 3].map(num => { if (typeof num === "number") return; return num * 2; }); @@ -1568,7 +1572,7 @@ const num = parseInt("7*6", 10); #### 答え: C -配列をマッピングするとき、`num`の値に代入されるのは、ループで渡ってくる要素となります。この場合、要素は数値なので、if ステートメント `typeof num === "number"`の条件は`true`を返します。 map 関数は新しい配列を作成して関数から返された値を挿入します。 +配列をマッピングするとき、`num`の値に代入されるのは、ループで渡ってくる要素となります。この場合、要素は数値なので、ifステートメント `typeof num === "number"`の条件は`true`を返します。 map関数は新しい配列を作成して関数から返された値を挿入します。 ただし、値は返されません。関数から値を返さないと、関数は`undefined`を返します。配列内のすべての要素に対して関数ブロックが呼び出されるので、各要素に対して`undefined`を返します。 @@ -1603,7 +1607,7 @@ console.log(person, birthYear); #### 答え: A -値がオブジェクトでない限り、引数は"値"によって渡され、その後、"参照"によって渡されます。 `birthYear`はオブジェクトではなく文字列なので、値で渡されます。引数を値で渡すと、その値の"コピー"が作成されます(質問 46 を参照)。 +値がオブジェクトでない限り、引数は"値"によって渡され、その後、"参照"によって渡されます。 `birthYear`はオブジェクトではなく文字列なので、値で渡されます。引数を値で渡すと、その値の"コピー"が作成されます(質問46を参照)。 変数`birthYear`は、値`"1997"`への参照を持ちます。引数`year`は、値`"1997"`も参照していますが、それは`birthYear`が参照しているのと同じ値ではありません。`year`に`"1998"`を代入することによって`year`の値を更新したとしても、`year`の値を更新するだけです。`birthYear`はまだ`"1997"`となります。 @@ -1711,15 +1715,15 @@ y = 10; let x = y; ``` -`y`に`10`を代入すると、実際にはグローバルオブジェクトにプロパティ`y`が追加されます(ブラウザでは`window`、node では`global`)。ブラウザでは、`window.y`は`10`となりました。 +`y`に`10`を代入すると、実際にはグローバルオブジェクトにプロパティ`y`が追加されます(ブラウザでは`window`、nodeでは`global`)。ブラウザでは、`window.y`は`10`となりました。 -それから、変数`x`を`10`である値`y`で宣言します。`let`キーワードで宣言された変数は"ブロックスコープ"となり、宣言されたブロック内でのみ定義されます。この場合は即時関数(IIFE)となります。 +それから、変数`x`を`10`である値`y`で宣言します。`let`キーワードで宣言された変数は"ブロックスコープ"となり、宣言されたブロック内でのみ定義されます。この場合は即時関数(IIFE)となります。 `typeof`演算子使用時、オペランド`x`は定義されていません: 宣言されているブロックの外側で`x`にアクセスしようとしています。これは`x`が定義されていないことを意味します。 値が割り当てられていない、または宣言されていない値は`"undefined"`型となります。なので`console.log(typeof x)`は`"undefined"`を返します。 -y に関しては、`y`に`10`を代入するときにグローバル変数`y`を作成しました。この値は、コード内のどこからでもアクセスできます。`y`が定義されていて、`"number"`型の値を保持します。よって`console.log(typeof y)`は`"number"`を返します。 +yに関しては、`y`に`10`を代入するときにグローバル変数`y`を作成しました。この値は、コード内のどこからでもアクセスできます。`y`が定義されていて、`"number"`型の値を保持します。よって`console.log(typeof y)`は`"number"`を返します。

@@ -1733,7 +1737,7 @@ class Dog { } } -Dog.prototype.bark = function () { +Dog.prototype.bark = function() { console.log(`Woof I am ${this.name}`); }; @@ -1785,9 +1789,10 @@ console.log(set); #### 答え: D + `Set`オブジェクトは _unique_ の値の集合です: 値は集合の中で一度だけ現れることができます -値`1`が重複したイテラブル`[1、1、2、3、4]`を渡しました。セット内に同じ値を 2 つ持つことはできないので、そのうちの 1 つが削除され`{1、2、3、4}`となります。 +値`1`が重複したイテラブル`[1、1、2、3、4]`を渡しました。セット内に同じ値を2つ持つことはできないので、そのうちの1つが削除され`{1、2、3、4}`となります。

@@ -1850,9 +1855,9 @@ console.log(delete age); #### 答え: A -`delete`演算子は、ブール値を返します: 正常に削除された場合は true、それ以外の場合は false を返します。`var`, `const`または`let`キーワードで宣言された変数は`delete`演算子を使って削除することはできません。 +`delete`演算子は、ブール値を返します: 正常に削除された場合はtrue、それ以外の場合はfalseを返します。`var`, `const`または`let`キーワードで宣言された変数は`delete`演算子を使って削除することはできません。 -`name`変数は`const`キーワードで宣言されているので、削除は成功しません: `false`が返されます。 +`name`変数は`const`キーワードで宣言されているので、削除は成功しません: `false`が返されます。 `age`を`21`に設定すると、実際にはグローバルオブジェクトに`age`というプロパティを追加されました。グローバルオブジェクトからもプロパティを削除することができますので、`delete age`は`true`を返します。 @@ -1952,7 +1957,7 @@ console.log(Object.keys(person)); #### 答え: B -`defineProperty`メソッドを使うと、オブジェクトに新しいプロパティを追加したり、既存のプロパティを修正することができます。 `defineProperty`メソッドを使ってオブジェクトにプロパティを追加すると、それらはデフォルトでは _列挙できません_。 +`defineProperty`メソッドを使うと、オブジェクトに新しいプロパティを追加したり、既存のプロパティを修正することができます。 `defineProperty`メソッドを使ってオブジェクトにプロパティを追加すると、それらはデフォルトでは _列挙できません_。 `Object.keys`メソッドはオブジェクトから全ての _enumerable_ (列挙可能)なプロパティ名を返します。上記の場合は`"name"`だけとなります。 @@ -1969,7 +1974,7 @@ console.log(Object.keys(person)); const settings = { username: "lydiahallie", level: 19, - health: 90, + health: 90 }; const data = JSON.stringify(settings, ["level", "health"]); @@ -1986,11 +1991,11 @@ console.log(data); #### 答え: A -`JSON.stringify`の 2 番目の引数は _replacer_ です。replacer は、関数または配列のいずれかにすることができ、値を文字列化する対象とその方法を制御できます。 +`JSON.stringify`の2番目の引数は _replacer_ です。replacerは、関数または配列のいずれかにすることができ、値を文字列化する対象とその方法を制御できます。 -replacer が _array_ の場合、名前が配列に含まれるプロパティのみが JSON 文字列に追加されます。上記の場合、`"level"`と`"health"`という名前のプロパティだけが含まれ、`"username"`は除外されます。`data`は`"{" level ":19、" health ":90}"`となります。 +replacerが _array_ の場合、名前が配列に含まれるプロパティのみがJSON文字列に追加されます。上記の場合、`"level"`と`"health"`という名前のプロパティだけが含まれ、`"username"`は除外されます。`data`は`"{" level ":19、" health ":90}"`となります。 -replacer が _function_ の場合、この関数は文字列化しているオブジェクト内のすべてのプロパティに対して呼び出されます。この関数から返される値は、JSON 文字列に追加されたときのプロパティの値になり、値が`undefined`の場合、このプロパティは JSON 文字列から除外されます。 +replacerが _function_ の場合、この関数は文字列化しているオブジェクト内のすべてのプロパティに対して呼び出されます。この関数から返される値は、JSON文字列に追加されたときのプロパティの値になり、値が`undefined`の場合、このプロパティはJSON文字列から除外されます。

@@ -2003,7 +2008,7 @@ replacer が _function_ の場合、この関数は文字列化しているオ let num = 10; const increaseNumber = () => num++; -const increasePassedNumber = (number) => number++; +const increasePassedNumber = number => number++; const num1 = increaseNumber(); const num2 = increasePassedNumber(num1); @@ -2056,17 +2061,18 @@ multiply(value); #### 答え: C -ES6 では、パラメータをデフォルト値で初期化できます。値が関数に渡されていない場合やパラメータの値が `"undefined"`の場合、パラメータの値はデフォルト値になります。上記の場合、`value`オブジェクトのプロパティを新しいオブジェクトに分割代入されるので、`x`のデフォルト値は`{number:10}`になります。 + +ES6では、パラメータをデフォルト値で初期化できます。値が関数に渡されていない場合やパラメータの値が `"undefined"`の場合、パラメータの値はデフォルト値になります。上記の場合、`value`オブジェクトのプロパティを新しいオブジェクトに分割代入されるので、`x`のデフォルト値は`{number:10}`になります。 デフォルトの引数は、_呼び出し時_ に評価されます。関数を呼び出すたびに、_新しい_ オブジェクトが作成されます。 -最初に値を渡さずに 2 回、`multiply`関数を呼び出します: `x`のデフォルト値は `{number:10}`となり、その数の乗算された値、つまり `20`を出力します。 +最初に値を渡さずに2回、`multiply`関数を呼び出します: `x`のデフォルト値は `{number:10}`となり、その数の乗算された値、つまり `20`を出力します。 -3 回目の multiply を呼び出すとき、引数を渡します: `value`というオブジェクトです。 +3回目のmultiplyを呼び出すとき、引数を渡します: `value`というオブジェクトです。 `*=`演算子は`x.number = x.number * 2`の省略形となります: `x.number`の値は乗算した値に修正され、`20`を出力します。 -4 回目は、`value`オブジェクトをもう一度渡します。`x.number`は以前は`20`に修正されているので、`x.number *= 2`は`40`を出力します。 +4回目は、`value`オブジェクトをもう一度渡します。`x.number`は以前は`20`に修正されているので、`x.number *= 2`は`40`を出力します。

@@ -2089,7 +2095,8 @@ ES6 では、パラメータをデフォルト値で初期化できます。値 #### 答え: D -`reduce`メソッドが受け取る最初の引数は _アキュムレータ_ となります。この場合は`x`です。 2 番目の引数は、_現在の値_ `y`です。 reduce メソッドでは、配列内のすべての要素に対してコールバック関数を実行します。これにより、最終的に 1 つの値が得られます。 + +`reduce`メソッドが受け取る最初の引数は _アキュムレータ_ となります。この場合は`x`です。 2番目の引数は、_現在の値_ `y`です。 reduceメソッドでは、配列内のすべての要素に対してコールバック関数を実行します。これにより、最終的に1つの値が得られます。 上記の例では、値を返していません。単にアキュムレータの値と現在の値を記録しています。 @@ -2099,14 +2106,14 @@ ES6 では、パラメータをデフォルト値で初期化できます。値 関数から値を返さなければ、`undefined`を返します。次の呼び出しでは、アキュムレータは`undefined`で、現在の値は`3`です。`undefined`と`3`が出力されます。 -4 回目の呼び出しでも、コールバック関数からは戻りません。アキュムレータもまた`undefined`であり、現在の値は`4`となり、`undefined`と`4`が出力されます。 +4回目の呼び出しでも、コールバック関数からは戻りません。アキュムレータもまた`undefined`であり、現在の値は`4`となり、`undefined`と`4`が出力されます。

--- -###### 66. どのコンストラクタを使えば `Dog` class を継承できるでしょうか? +###### 66. どのコンストラクタを使えば `Dog` classを継承できるでしょうか? ```javascript class Dog { @@ -2116,7 +2123,7 @@ class Dog { }; class Labrador extends Dog { - // 1 + // 1 constructor(name, size) { this.size = size; } @@ -2130,7 +2137,7 @@ class Labrador extends Dog { super(name); this.size = size; } - // 4 + // 4 constructor(name, size) { this.name = name; this.size = size; @@ -2149,14 +2156,13 @@ class Labrador extends Dog { #### 答え: B -派生クラスでは、`super`を呼び出す前に、`this`キーワードにアクセスすることはできません。そうしようとすると、ReferenceError がスローされます: 1 と 4 は参照エラーをスローします。 +派生クラスでは、`super`を呼び出す前に、`this`キーワードにアクセスすることはできません。そうしようとすると、ReferenceErrorがスローされます: 1と4は参照エラーをスローします。 `super`キーワードを使って、与えられた引数で、その親クラスのコンストラクタを呼び出します。親のコンストラクタは`name`引数を受け取るので、`name`を`super`に渡す必要があります。 -`Labrador`クラスは 2 つの引数、`Dog`を拡張するための`name`と、`Labrador`クラスの追加のプロパティとしての`size`を受け取ります。 - -両方とも`Labrador`のコンストラクタ関数に渡す必要があります。これはコンストラクタ 2 を使って正しく実行されます。 +`Labrador`クラスは2つの引数、`Dog`を拡張するための`name`と、`Labrador`クラスの追加のプロパティとしての`size`を受け取ります。 +両方とも`Labrador`のコンストラクタ関数に渡す必要があります。これはコンストラクタ2を使って正しく実行されます。

@@ -2166,12 +2172,12 @@ class Labrador extends Dog { ```javascript // index.js -console.log("running index.js"); -import { sum } from "./sum.js"; +console.log('running index.js'); +import { sum } from './sum.js'; console.log(sum(1, 2)); // sum.js -console.log("running sum.js"); +console.log('running sum.js'); export const sum = (a, b) => a + b; ``` @@ -2187,9 +2193,9 @@ export const sum = (a, b) => a + b; `import`キーワードを使うと、全てのインポートされたモジュールは _事前解析_ されます。これは、インポートされたモジュールが _最初_ に実行され、_その後_ モジュールをインポートしたファイル内のコードが実行されることを意味します。 -これは CommonJS の`require()`と`import`の違いです。`require()`を使うと、コードが実行されている間に依存関係をオンデマンドでロードすることができます。 +これはCommonJSの`require()`と`import`の違いです。`require()`を使うと、コードが実行されている間に依存関係をオンデマンドでロードすることができます。 -`import`の代わりに`require`を使用したとしたら、`running index.js`, `running sum.js`, `3`が出力されているはずです。 +`import`の代わりに`require`を使用したとしたら、`running index.js`, `running sum.js`, `3`が出力されているはずです。

@@ -2199,9 +2205,9 @@ export const sum = (a, b) => a + b; ###### 68. 何が出力されるでしょうか? ```javascript -console.log(Number(2) === Number(2)); -console.log(Boolean(false) === Boolean(false)); -console.log(Symbol("foo") === Symbol("foo")); +console.log(Number(2) === Number(2)) +console.log(Boolean(false) === Boolean(false)) +console.log(Symbol('foo') === Symbol('foo')) ``` - A: `true`, `true`, `false` @@ -2214,9 +2220,9 @@ console.log(Symbol("foo") === Symbol("foo")); #### 答え: A -すべてのシンボルは完全にユニークです。シンボルに渡される引数の目的は、シンボルに説明を与えることです。Symbol の値は渡された引数に依存しません。 +すべてのシンボルは完全にユニークです。シンボルに渡される引数の目的は、シンボルに説明を与えることです。Symbolの値は渡された引数に依存しません。 -等価性をテストしているので、2 つのまったく新しいシンボルを作成します: 最初の`Symbol('foo')`と、2 番目の`Symbol('foo')`です。これら 2 つの値は一意であり、互いに等しくはありません、なので`Symbol('foo') === Symbol('foo')`は`false`を返します。 +等価性をテストしているので、2つのまったく新しいシンボルを作成します: 最初の`Symbol('foo')`と、2番目の`Symbol('foo')`です。これら2つの値は一意であり、互いに等しくはありません、なので`Symbol('foo') === Symbol('foo')`は`false`を返します。

@@ -2226,22 +2232,22 @@ console.log(Symbol("foo") === Symbol("foo")); ###### 69. 何が出力されるでしょうか? ```javascript -const name = "Lydia Hallie"; -console.log(name.padStart(13)); -console.log(name.padStart(2)); +const name = "Lydia Hallie" +console.log(name.padStart(13)) +console.log(name.padStart(2)) ``` - A: `"Lydia Hallie"`, `"Lydia Hallie"` - B: `" Lydia Hallie"`, `" Lydia Hallie"` (`"[13x whitespace]Lydia Hallie"`, `"[2x whitespace]Lydia Hallie"`) - C: `" Lydia Hallie"`, `"Lydia Hallie"` (`"[1x whitespace]Lydia Hallie"`, `"Lydia Hallie"`) -- D: `"Lydia Hallie"`, `"Lyd"`, +- D: `"Lydia Hallie"`, `"Lyd"`,
答え

#### 答え: C -`padStart`メソッドを使うと、文字列の先頭にパディングを追加できます。このメソッドに渡される値は、パディングとともに文字列の長さの _合計_ です。文字列`"Lydia Hallie"`の長さは`12`です。 `name.padStart(13)`は、12 + 1 が 13 であるため、文字列の先頭に 1 スペースを挿入されます。 +`padStart`メソッドを使うと、文字列の先頭にパディングを追加できます。このメソッドに渡される値は、パディングとともに文字列の長さの _合計_ です。文字列`"Lydia Hallie"`の長さは`12`です。 `name.padStart(13)`は、12 + 1が13であるため、文字列の先頭に1スペースを挿入されます。 `padStart`メソッドに渡された引数が、配列の長さよりも小さい場合、パディングは追加されません。 @@ -2266,6 +2272,7 @@ console.log("🥑" + "💻"); #### 答え: A + `+`演算子を使うと、文字列を連結することができます。この場合、文字列`"🥑"`を文字列`"💻"`と連結して、結果として`"🥑💻"`となります。

@@ -2273,7 +2280,7 @@ console.log("🥑" + "💻"); --- -###### 71. console.log ステートメントの後にコメントアウトされている値を、ログ出力する方法を教えてください。 +###### 71. console.logステートメントの後にコメントアウトされている値を、ログ出力する方法を教えてください。 ```javascript function* startGame() { @@ -2301,11 +2308,11 @@ console.log(/* 2 */); // JavaScript loves you back ❤️ ジェネレータ関数は、`yield`キーワードを見るとその実行を「一時停止」します。まず、関数に文字列 "Do you love JavaScript?" を返させる必要があります。これは `game.next().value`を呼び出すことによって行うことができます。 -最初の`yield`キーワードが見つかるまで、すべての行が実行されます。関数内の最初の行に`yield`キーワードがあります: 実行は最初の yield で停止します! _これは変数 `answer`がまだ定義されていないことを意味します!_ +最初の`yield`キーワードが見つかるまで、すべての行が実行されます。関数内の最初の行に`yield`キーワードがあります: 実行は最初のyieldで停止します! _これは変数 `answer`がまだ定義されていないことを意味します!_ -`game.next("Yes").value`を呼び出すと、前の`yield`は`next()`関数に渡されたパラメータの値、この場合は`"Yes"`に置き換えられます。変数`answer`の値は現在`"Yes"`となります。 +`game.next("Yes").value`を呼び出すと、前の`yield`は`next()`関数に渡されたパラメータの値、この場合は`"Yes"`に置き換えられます。変数`answer`の値は現在`"Yes"`となります。 -if-statemnet の条件は`false`を返し、`JavaScript loves you back ❤️`が、出力されます。 +if-statemnetの条件は`false`を返し、`JavaScript loves you back ❤️`が、出力されます。

@@ -2368,7 +2375,7 @@ console.log(data); #### 答え: C -非同期関数は常に、promise を返します。`await`は promise が解決されるのを待たなければなりません: `getData()`を呼び出すと、`data`は保留中の promise が返されます。 +非同期関数は常に、promiseを返します。`await`はpromiseが解決されるのを待たなければなりません: `getData()`を呼び出すと、`data`は保留中のpromiseが返されます。 解決した値`"I made it"`にアクセスしたい場合は、`data`に対して`.then()`メソッドを使用することができます: @@ -2402,10 +2409,10 @@ console.log(result); #### 答え: B -`.push()`メソッドは新しい配列の長さを返します。以前は、配列は 1 つの要素(文字列 `" banana "`)を含み、長さは `1`でした。文字列 `" apple "`を配列に追加した後、配列は 2 つの要素を含み、長さは `2`になります。これは `addToList`関数から返されます。 +`.push()`メソッドは新しい配列の長さを返します。以前は、配列は1つの要素(文字列 `" banana "`)を含み、長さは `1`でした。文字列 `" apple "`を配列に追加した後、配列は2つの要素を含み、長さは `2`になります。これは `addToList`関数から返されます。 The `.push()` method returns the _length_ of the new array! Previously, the array contained one element (the string `"banana"`) and had a length of `1`. After adding the string `"apple"` to the array, the array contains two elements, and has a length of `2`. This gets returned from the `addToList` function. -`push`メソッドは元の配列を修正します。配列の長さではなく関数から配列を返したい場合は、item をプッシュした後に list を返すべきです。 +`push`メソッドは元の配列を修正します。配列の長さではなく関数から配列を返したい場合は、itemをプッシュした後にlistを返すべきです。 The `push` method modifies the original array. If you wanted to return the _array_ from the function rather than the _length of the array_, you should have returned `list` after pushing `item` to it.

@@ -2440,7 +2447,7 @@ console.log(shape); 変数`shape`を作成し、フリーズしたオブジェクト`box`に代入すると、`shape`はフリーズしたオブジェクトとなります。オブジェクトがフリーズしているかどうかは `Object.isFrozen`を使って確認できます。 -この場合、変数`shape`はフリーズしたオブジェクトへの参照を持っているので、`Object.isFrozen(shape)`は true を返します。 +この場合、変数`shape`はフリーズしたオブジェクトへの参照を持っているので、`Object.isFrozen(shape)`はtrueを返します。 `shape`はフリーズされており、`x`の値はオブジェクトではないので、プロパティ`x`を変更することはできません。 @@ -2471,9 +2478,9 @@ console.log(name); 右側のオブジェクトからプロパティ`name`をアンパックするとき、その値`"Lydia"`を`myName`という名前の変数に代入します。 -`{name:myName}`を使って、右側の `name`プロパティの値で`myName`という新しい変数を作りたいことを JavaScript に伝えます。 +`{name:myName}`を使って、右側の `name`プロパティの値で`myName`という新しい変数を作りたいことをJavaScriptに伝えます。 -定義されていない変数`name`を出力しようとしているので、ReferenceError が投げられます。 +定義されていない変数`name`を出力しようとしているので、ReferenceErrorが投げられます。

@@ -2510,7 +2517,7 @@ function sum(a, b) { ```javascript const add = () => { const cache = {}; - return (num) => { + return num => { if (num in cache) { return `From cache! ${cache[num]}`; } else { @@ -2541,15 +2548,15 @@ console.log(addFunction(5 * 2)); 同じ引数を指定してもう一度`addFunction`関数を呼び出すと、最初にキャッシュ内でその値がすでに取得されているかどうかを調べます。 -この場合、caches の値が返され、実行時間が短縮されます。そうでなくキャッシュされていなければ、値を計算した後にそれを格納します。 +この場合、cachesの値が返され、実行時間が短縮されます。そうでなくキャッシュされていなければ、値を計算した後にそれを格納します。 -同じ値で 3 回`addFunction`関数を呼び出します: 最初の呼び出しでは、`num`に`10`を代入した時、関数の値はまだキャッシュされていません。 +同じ値で3回`addFunction`関数を呼び出します: 最初の呼び出しでは、`num`に`10`を代入した時、関数の値はまだキャッシュされていません。 -if ステートメントの`num in cache`の条件は`false`を返し、else ブロックが実行されます: `Calculated! 20`が出力され、結果の値がキャッシュオブジェクトに追加されます。 `cache`は現在 `{ 10: 20 }`となります。 +ifステートメントの`num in cache`の条件は`false`を返し、elseブロックが実行されます: `Calculated! 20`が出力され、結果の値がキャッシュオブジェクトに追加されます。 `cache`は現在 `{ 10: 20 }`となります。 -2 回目は、`cache`オブジェクトは`10`に対して返される値を含みます。 if ステートメントの`num in cache`の条件は`true`となり、`'From cache! 20'`を返します。 よって`'From cache! 20'`が出力されます。 +2回目は、`cache`オブジェクトは`10`に対して返される値を含みます。 ifステートメントの`num in cache`の条件は`true`となり、`'From cache! 20'`を返します。 よって`'From cache! 20'`が出力されます。 -3 回目は、`10`に評価される関数に`5 * 2`を渡します。`cache`オブジェクトは`10`に対して返される値を含みます。if ステートメントの`num in cache`の条件は`true`となり、`'From cache! 20'`を返します。 よって`'From cache! 20'`が出力されます。 +3回目は、`10`に評価される関数に`5 * 2`を渡します。`cache`オブジェクトは`10`に対して返される値を含みます。ifステートメントの`num in cache`の条件は`true`となり、`'From cache! 20'`を返します。 よって`'From cache! 20'`が出力されます。

@@ -2559,21 +2566,21 @@ if ステートメントの`num in cache`の条件は`false`を返し、else ブ ###### 79. 何が出力されるでしょうか? ```javascript -const myLifeSummedUp = ["☕", "💻", "🍷", "🍫"]; +const myLifeSummedUp = ["☕", "💻", "🍷", "🍫"] for (let item in myLifeSummedUp) { - console.log(item); + console.log(item) } for (let item of myLifeSummedUp) { - console.log(item); + console.log(item) } ``` - A: `0` `1` `2` `3` and `"☕"` ` "💻"` `"🍷"` `"🍫"` - B: `"☕"` ` "💻"` `"🍷"` `"🍫"` and `"☕"` ` "💻"` `"🍷"` `"🍫"` - C: `"☕"` ` "💻"` `"🍷"` `"🍫"` and `0` `1` `2` `3` -- D: `0` `1` `2` `3` and `{0: "☕", 1: "💻", 2: "🍷", 3: "🍫"}` +- D: `0` `1` `2` `3` and `{0: "☕", 1: "💻", 2: "🍷", 3: "🍫"}`
答え

@@ -2598,14 +2605,14 @@ _for-of_ ループを使うと、**反復可能オブジェクト**を繰り返 ###### 80. 何が出力されるでしょうか? ```javascript -const list = [1 + 2, 1 * 2, 1 / 2]; -console.log(list); +const list = [1 + 2, 1 * 2, 1 / 2] +console.log(list) ``` - A: `["1 + 2", "1 * 2", "1 / 2"]` - B: `["12", 2, 0.5]` - C: `[3, 2, 0.5]` -- D: `[1, 1, 1]` +- D: `[1, 1, 1]`

答え

@@ -2625,16 +2632,16 @@ console.log(list); ```javascript function sayHi(name) { - return `Hi there, ${name}`; + return `Hi there, ${name}` } -console.log(sayHi()); +console.log(sayHi()) ``` - A: `Hi there, ` - B: `Hi there, undefined` - C: `Hi there, null` -- D: `ReferenceError` +- D: `ReferenceError`

答え

@@ -2643,7 +2650,7 @@ console.log(sayHi()); 関数に値が渡されていない限り、引数はデフォルトで`undefined`の値を持ちます。上記の場合、`name`引数に値を渡さなかったので、`name`は`undefined`となり出力されます。 -ES6 では、このデフォルトの`undefined`値を、デフォルトパラメータで上書きすることができます。例: +ES6では、このデフォルトの`undefined`値を、デフォルトパラメータで上書きすることができます。例: `function sayHi(name = "Lydia") { ... }` @@ -2657,21 +2664,21 @@ ES6 では、このデフォルトの`undefined`値を、デフォルトパラ ###### 82. 何が出力されるでしょうか? ```javascript -var status = "😎"; +var status = "😎" setTimeout(() => { - const status = "😍"; + const status = "😍" const data = { status: "🥑", getStatus() { - return this.status; - }, - }; + return this.status + } + } - console.log(data.getStatus()); - console.log(data.getStatus.call(this)); -}, 0); + console.log(data.getStatus()) + console.log(data.getStatus.call(this)) +}, 0) ``` - A: `"🥑"` and `"😍"` @@ -2688,7 +2695,7 @@ setTimeout(() => { メソッドは`data`オブジェクトに属しているので、`this`は `data`オブジェクトを参照します。 `this.status`をログ出力すると、`data`オブジェクトの`status`プロパティの`"🥑"`がログ出力されます。 -`call`メソッドを使うと、`this`キーワードが参照するオブジェクトを変更することができます。 **関数**では、`this`キーワードは _その関数が属するオブジェクトを参照します_ 。 +`call`メソッドを使うと、`this`キーワードが参照するオブジェクトを変更することができます。 **関数**では、`this`キーワードは _その関数が属するオブジェクトを参照します_ 。 _グローバルオブジェクトで_ `setTimeout`関数を宣言したので、`setTimeout`関数内では、 `this`キーワードは _グローバルオブジェクト_ を参照します。 @@ -2704,13 +2711,13 @@ _グローバルオブジェクトで_ `setTimeout`関数を宣言したので ```javascript const person = { name: "Lydia", - age: 21, -}; + age: 21 +} -let city = person.city; -city = "Amsterdam"; +let city = person.city +city = "Amsterdam" -console.log(person); +console.log(person) ``` - A: `{ name: "Lydia", age: 21 }` @@ -2727,7 +2734,7 @@ console.log(person); 我々は`person`オブジェクト自身を参照して _いない_ ことに注意してください。`person`オブジェクトの`city`プロパティを、変数`city`に代入するだけです。 -それから、`city`に、文字列`"Amsterdam"`を代入しますこれは person オブジェクトを変更しません: そのオブジェクトへの参照はありません。 +それから、`city`に、文字列`"Amsterdam"`を代入しますこれは personオブジェクトを変更しません: そのオブジェクトへの参照はありません。 `person`オブジェクトをログ出力するとき、未修正のオブジェクトが返されます。 @@ -2741,15 +2748,15 @@ console.log(person); ```javascript function checkAge(age) { if (age < 18) { - const message = "Sorry, you're too young."; + const message = "Sorry, you're too young." } else { - const message = "Yay! You're old enough!"; + const message = "Yay! You're old enough!" } - return message; + return message } -console.log(checkAge(21)); +console.log(checkAge(21)) ``` - A: `"Sorry, you're too young."` @@ -2762,7 +2769,7 @@ console.log(checkAge(21)); #### 答え: C -`const`と`let`キーワードを持つ変数は _ブロックスコープ_ です。ブロックは中括弧(`{ }`)で囲まれたものです。上記の場合、if/else ステートメントが中括弧となります。宣言されたブロックの外側で変数を参照することはできません。ReferenceError がスローされます。 +`const`と`let`キーワードを持つ変数は _ブロックスコープ_ です。ブロックは中括弧(`{ }`)で囲まれたものです。上記の場合、if/elseステートメントが中括弧となります。宣言されたブロックの外側で変数を参照することはできません。ReferenceError がスローされます。

@@ -2772,29 +2779,29 @@ console.log(checkAge(21)); ###### 85. どのような情報が出力されますか? ```javascript -fetch("https://www.website.com/api/user/1") - .then((res) => res.json()) - .then((res) => console.log(res)); +fetch('https://www.website.com/api/user/1') + .then(res => res.json()) + .then(res => console.log(res)) ``` - A: `fetch`メソッドの結果 -- B: 2 回目の `fetch`メソッド呼び出しの結果 +- B: 2回目の `fetch`メソッド呼び出しの結果 - C: 前の`.then()`でのコールバックの結果 -- D: 常に undefined. +- D: 常に undefined.
答え

#### 答え: C -2 番目の`.then`の`res`の値は、前の`.then`の戻り値と同じとなります。値が次のハンドラに渡されるように、`.then`を連鎖させることができます。 +2番目の`.then`の`res`の値は、前の`.then`の戻り値と同じとなります。値が次のハンドラに渡されるように、`.then`を連鎖させることができます。

--- -###### 86. 引数として true を渡すことができない場合、どのオプションが`hasName`を`true`に設定するための方法ですか? +###### 86. 引数としてtrueを渡すことができない場合、どのオプションが`hasName`を`true`に設定するための方法ですか? ```javascript function getName(name) { @@ -2812,7 +2819,7 @@ function getName(name) { #### 答え: A -`!!name`を使って、`name`の値が、truthy か falsey かを判断します。name が truthy であり、これをテストしたい場合、`!name`は`false`を返します。`!false`(これは実際には`!!name`です)は`true`を返します。 +`!!name`を使って、`name`の値が、truthyか falseyかを判断します。nameがtruthyであり、これをテストしたい場合、`!name`は`false`を返します。`!false`(これは実際には`!!name`です)は`true`を返します。 `hasName`に`name`を代入することで、`getName`関数に渡されたどんな値も`hasName`に代入されます。ブール値`true`は設定できません。 diff --git a/ko-KR/README-ko_KR.md b/ko-KR/README-ko_KR.md index ef2d94e1..13651a7c 100644 --- a/ko-KR/README-ko_KR.md +++ b/ko-KR/README-ko_KR.md @@ -34,7 +34,6 @@ - [🇳🇱 Nederlands](../nl-NL/README.md) - [🇵🇱 Polski](../pl-PL/README.md) - [🇧🇷 Português Brasil](../pt-BR/README_pt_BR.md) -- [🇷o Română](../ro-RO/README.ro.md) - [🇷🇺 Русский](../ru-RU/README.md) - [🇽🇰 Shqip](../sq-KS/README_sq_KS.md) - [🇹🇭 ไทย](../th-TH/README-th_TH.md) @@ -55,7 +54,7 @@ function sayHi() { console.log(name); console.log(age); - var name = "Lydia"; + var name = 'Lydia'; let age = 21; } @@ -151,7 +150,7 @@ console.log(shape.perimeter()); ```javascript +true; -!"Lydia"; +!'Lydia'; ``` - A: `1` 그리고 `false` @@ -176,11 +175,11 @@ console.log(shape.perimeter()); ```javascript const bird = { - size: "small", + size: 'small', }; const mouse = { - name: "Mickey", + name: 'Mickey', small: true, }; ``` @@ -211,11 +210,11 @@ JavaScript는 문장을 해석(또는 분)해요. 대괄호 표기를 사용하 ###### 6. 무엇이 출력 될까요? ```javascript -let c = { greeting: "Hey!" }; +let c = { greeting: 'Hey!' }; let d; d = c; -c.greeting = "Hello"; +c.greeting = 'Hello'; console.log(d.greeting); ``` @@ -230,7 +229,7 @@ console.log(d.greeting); #### 답: A -JavaScript에서 모든 객체는 서로를 동일하게 설정하면 *참조*로 상호작용해요. +JavaScript에서 모든 객체는 서로를 동일하게 설정하면 _참조_로 상호작용해요. 우선, 변수 `c`는 객체에 대한 값을 갖고 있어요. 그 후 `c`가 객체에 가지고 있는 것과 동일한 참조를 `d`에 할당해요. @@ -285,13 +284,13 @@ class Chameleon { return this.newColor; } - constructor({ newColor = "green" } = {}) { + constructor({ newColor = 'green' } = {}) { this.newColor = newColor; } } -const freddie = new Chameleon({ newColor: "purple" }); -console.log(freddie.colorChange("orange")); +const freddie = new Chameleon({ newColor: 'purple' }); +console.log(freddie.colorChange('orange')); ``` - A: `orange` @@ -341,10 +340,10 @@ console.log(greetign); ```javascript function bark() { - console.log("Woof!"); + console.log('Woof!'); } -bark.animal = "dog"; +bark.animal = 'dog'; ``` - A: 별일 없어요, 이건 완전히 괜찮아요! @@ -374,7 +373,7 @@ function Person(firstName, lastName) { this.lastName = lastName; } -const member = new Person("Lydia", "Hallie"); +const member = new Person('Lydia', 'Hallie'); Person.getFullName = function () { return `${this.firstName} ${this.lastName}`; }; @@ -415,8 +414,8 @@ function Person(firstName, lastName) { this.lastName = lastName; } -const lydia = new Person("Lydia", "Hallie"); -const sarah = Person("Sarah", "Smith"); +const lydia = new Person('Lydia', 'Hallie'); +const sarah = Person('Sarah', 'Smith'); console.log(lydia); console.log(sarah); @@ -486,7 +485,7 @@ function sum(a, b) { return a + b; } -sum(1, "2"); +sum(1, '2'); ``` - A: `NaN` @@ -553,7 +552,7 @@ function getPersonInfo(one, two, three) { console.log(three); } -const person = "Lydia"; +const person = 'Lydia'; const age = 21; getPersonInfo`${person} is ${age} years old`; @@ -580,9 +579,9 @@ getPersonInfo`${person} is ${age} years old`; ```javascript function checkAge(data) { if (data === { age: 18 }) { - console.log("You are an adult!"); + console.log('You are an adult!'); } else if (data == { age: 18 }) { - console.log("You are still an adult."); + console.log('You are still an adult.'); } else { console.log(`Hmm.. You don't have an age I guess`); } @@ -642,7 +641,7 @@ rest 파라미터 (`...args`)는 남아있는 모든 인수을 하나의 배열 ```javascript function getAge() { - "use strict"; + 'use strict'; age = 21; console.log(age); } @@ -670,7 +669,7 @@ getAge(); ###### 21. `sum`의 값은 무엇일까요? ```javascript -const sum = eval("10*10+5"); +const sum = eval('10*10+5'); ``` - A: `105` @@ -693,7 +692,7 @@ const sum = eval("10*10+5"); ###### 22. cool_secret에 몇 시간이나 접근이 가능할까요? ```javascript -sessionStorage.setItem("cool_secret", 123); +sessionStorage.setItem('cool_secret', 123); ``` - A: 영원히, 데이터는 사라지지 않아요. @@ -746,12 +745,12 @@ console.log(num); ###### 24. 무엇이 출력 될까요? ```javascript -const obj = { 1: "a", 2: "b", 3: "c" }; +const obj = { 1: 'a', 2: 'b', 3: 'c' }; const set = new Set([1, 2, 3, 4, 5]); -obj.hasOwnProperty("1"); +obj.hasOwnProperty('1'); obj.hasOwnProperty(1); -set.has("1"); +set.has('1'); set.has(1); ``` @@ -777,7 +776,7 @@ set에서는 동작하지 않아요. set에는 `'1'`이 없어요: `set.has('1') ###### 25. 무엇이 출력 될까요? ```javascript -const obj = { a: "one", b: "two", a: "three" }; +const obj = { a: 'one', b: 'two', a: 'three' }; console.log(obj); ``` @@ -846,12 +845,12 @@ for (let i = 1; i < 5; i++) { ```javascript String.prototype.giveLydiaPizza = () => { - return "Just give Lydia pizza already!"; + return 'Just give Lydia pizza already!'; }; -const name = "Lydia"; +const name = 'Lydia'; -console.log(name.giveLydiaPizza()); +console.log(name.giveLydiaPizza()) ``` - A: `"Just give Lydia pizza already!"` @@ -875,8 +874,8 @@ console.log(name.giveLydiaPizza()); ```javascript const a = {}; -const b = { key: "b" }; -const c = { key: "c" }; +const b = { key: 'b' }; +const c = { key: 'c' }; a[b] = 123; a[c] = 456; @@ -908,9 +907,9 @@ console.log(a[b]); ###### 30. 무엇이 출력 될까요? ```javascript -const foo = () => console.log("First"); -const bar = () => setTimeout(() => console.log("Second")); -const baz = () => console.log("Third"); +const foo = () => console.log('First'); +const bar = () => setTimeout(() => console.log('Second')); +const baz = () => console.log('Third'); bar(); foo(); @@ -1013,7 +1012,7 @@ WebAPI는 준비가 될 때마다 stack에 항목을 추가할 수 없어요. ###### 33. 무엇이 출력 될까요? ```javascript -const person = { name: "Lydia" }; +const person = { name: 'Lydia' }; function sayHi(age) { console.log(`${this.name} is ${age}`); @@ -1076,8 +1075,8 @@ console.log(typeof sayHi()); ```javascript 0; new Number(0); -(""); -(" "); +(''); +(' '); new Boolean(false); undefined; ``` @@ -1260,7 +1259,7 @@ JavaScript는 원시형과 객체만 가지고 있어요. ```javascript !!null; -!!""; +!!''; !!1; ``` @@ -1288,7 +1287,7 @@ JavaScript는 원시형과 객체만 가지고 있어요. ###### 42. `setInterval` 메소드는 브라우저에게 무엇을 반환 할까요? ```javascript -setInterval(() => console.log("Hi"), 1000); +setInterval(() => console.log('Hi'), 1000); ``` - A: 유니크한 id @@ -1311,7 +1310,7 @@ setInterval(() => console.log("Hi"), 1000); ###### 43. 이것은 무엇을 반환할까요? ```javascript -[..."Lydia"]; +[...'Lydia']; ``` - A: `["L", "y", "d", "i", "a"]` @@ -1370,11 +1369,11 @@ console.log(gen.next().value); ```javascript const firstPromise = new Promise((res, rej) => { - setTimeout(res, 500, "one"); + setTimeout(res, 500, 'one'); }); const secondPromise = new Promise((res, rej) => { - setTimeout(res, 100, "two"); + setTimeout(res, 100, 'two'); }); Promise.race([firstPromise, secondPromise]).then((res) => console.log(res)); @@ -1400,7 +1399,7 @@ Promise.race([firstPromise, secondPromise]).then((res) => console.log(res)); ###### 46. 무엇이 출력 될까요? ```javascript -let person = { name: "Lydia" }; +let person = { name: 'Lydia' }; const members = [person]; person = null; @@ -1421,7 +1420,7 @@ console.log(members); -그 후, `members`라는 변수를 선언해요. 배열의 첫 번째 요소에 `person` 변수의 값을 대입해요. 서로를 같게 설정하면 *참조*로 상호작용해요. 어떤 변수에서 다른 변수로 참조를 할당하면, 그 참조의 _복사본_ 을 만들어요. (그들은 _같은_ 참조를 가지고 있지 않다는 것을 유의하세요!) +그 후, `members`라는 변수를 선언해요. 배열의 첫 번째 요소에 `person` 변수의 값을 대입해요. 서로를 같게 설정하면 _참조_로 상호작용해요. 어떤 변수에서 다른 변수로 참조를 할당하면, 그 참조의 _복사본_ 을 만들어요. (그들은 _같은_ 참조를 가지고 있지 않다는 것을 유의하세요!) @@ -1440,7 +1439,7 @@ console.log(members); ```javascript const person = { - name: "Lydia", + name: 'Lydia', age: 21, }; @@ -1469,7 +1468,7 @@ for (const item in person) { ###### 48. 무엇이 출력 될까요? ```javascript -console.log(3 + 4 + "5"); +console.log(3 + 4 + '5'); ``` - A: `"345"` @@ -1496,7 +1495,7 @@ console.log(3 + 4 + "5"); ###### 49. `num`의 값은 무엇일까요? ```javascript -const num = parseInt("7*6", 10); +const num = parseInt('7*6', 10); ``` - A: `42` @@ -1522,7 +1521,7 @@ const num = parseInt("7*6", 10); ```javascript [1, 2, 3].map((num) => { - if (typeof num === "number") return; + if (typeof num === 'number') return; return num * 2; }); ``` @@ -1550,12 +1549,12 @@ const num = parseInt("7*6", 10); ```javascript function getInfo(member, year) { - member.name = "Lydia"; - year = "1998"; + member.name = 'Lydia'; + year = '1998'; } -const person = { name: "Sarah" }; -const birthYear = "1997"; +const person = { name: 'Sarah' }; +const birthYear = '1997'; getInfo(person, birthYear); @@ -1587,15 +1586,15 @@ console.log(person, birthYear); ```javascript function greeting() { - throw "Hello world!"; + throw 'Hello world!'; } function sayHi() { try { const data = greeting(); - console.log("It worked!", data); + console.log('It worked!', data); } catch (e) { - console.log("Oh no an error:", e); + console.log('Oh no an error:', e); } } @@ -1625,8 +1624,8 @@ sayHi(); ```javascript function Car() { - this.make = "Lamborghini"; - return { make: "Maserati" }; + this.make = 'Lamborghini'; + return { make: 'Maserati' }; } const myCar = new Car(); @@ -1702,7 +1701,7 @@ Dog.prototype.bark = function () { console.log(`Woof I am ${this.name}`); }; -const pet = new Dog("Mara"); +const pet = new Dog('Mara'); pet.bark(); @@ -1767,7 +1766,7 @@ export default counter; ```javascript // index.js -import myCounter from "./counter"; +import myCounter from './counter'; myCounter += 1; @@ -1867,7 +1866,7 @@ console.log(y); ###### 60. 무엇이 출력 될까요? ```javascript -const user = { name: "Lydia", age: 21 }; +const user = { name: 'Lydia', age: 21 }; const admin = { admin: true, ...user }; console.log(admin); @@ -1893,9 +1892,9 @@ spread 연산자 `...` 를 사용해 객체를 결합할 수 있어요. 이것 ###### 61. 무엇이 출력 될까요? ```javascript -const person = { name: "Lydia" }; +const person = { name: 'Lydia' }; -Object.defineProperty(person, "age", { value: 21 }); +Object.defineProperty(person, 'age', { value: 21 }); console.log(person); console.log(Object.keys(person)); @@ -1924,12 +1923,12 @@ console.log(Object.keys(person)); ```javascript const settings = { - username: "lydiahallie", + username: 'lydiahallie', level: 19, health: 90, }; -const data = JSON.stringify(settings, ["level", "health"]); +const data = JSON.stringify(settings, ['level', 'health']); console.log(data); ``` @@ -1960,7 +1959,7 @@ replacer가 _함수_ 라면, 문자열로 변환 할 객체의 모든 속성에 let num = 10; const increaseNumber = () => num++; -const increasePassedNumber = (number) => number++; +const increasePassedNumber = number => number++; const num1 = increaseNumber(); const num2 = increasePassedNumber(num1); @@ -2117,12 +2116,12 @@ class Labrador extends Dog { ```javascript // index.js -console.log("running index.js"); -import { sum } from "./sum.js"; +console.log('running index.js'); +import { sum } from './sum.js'; console.log(sum(1, 2)); // sum.js -console.log("running sum.js"); +console.log('running sum.js'); export const sum = (a, b) => a + b; ``` @@ -2150,7 +2149,7 @@ export const sum = (a, b) => a + b; ```javascript console.log(Number(2) === Number(2)); console.log(Boolean(false) === Boolean(false)); -console.log(Symbol("foo") === Symbol("foo")); +console.log(Symbol('foo') === Symbol('foo')); ``` - A: `true`, `true`, `false` @@ -2173,7 +2172,7 @@ console.log(Symbol("foo") === Symbol("foo")); ###### 69. 무엇이 출력 될까요? ```javascript -const name = "Lydia Hallie"; +const name = 'Lydia Hallie'; console.log(name.padStart(13)); console.log(name.padStart(2)); ``` @@ -2200,7 +2199,7 @@ console.log(name.padStart(2)); ###### 70. 무엇이 출력 될까요? ```javascript -console.log("🥑" + "💻"); +console.log('🥑' + '💻'); ``` - A: `"🥑💻"` @@ -2224,11 +2223,11 @@ console.log("🥑" + "💻"); ```javascript function* startGame() { - const answer = yield "Do you love JavaScript?"; - if (answer !== "Yes") { + const answer = yield 'Do you love JavaScript?'; + if (answer !== 'Yes') { return "Oh wow... Guess we're gone here"; } - return "JavaScript loves you back ❤️"; + return 'JavaScript loves you back ❤️'; } const game = startGame(); @@ -2296,7 +2295,7 @@ console.log(String.raw`Hello\nworld`); ```javascript async function getData() { - return await Promise.resolve("I made it!"); + return await Promise.resolve('I made it!'); } const data = getData(); @@ -2333,7 +2332,7 @@ function addToList(item, list) { return list.push(item); } -const result = addToList("apple", ["banana"]); +const result = addToList('apple', ['banana']); console.log(result); ``` @@ -2393,7 +2392,7 @@ console.log(shape); ###### 76. 무엇이 출력 될까요? ```javascript -const { name: myName } = { name: "Lydia" }; +const { name: myName } = { name: 'Lydia' }; console.log(name); ``` @@ -2494,7 +2493,7 @@ console.log(addFunction(5 * 2)); ###### 79. 무엇이 출력 될까요? ```javascript -const myLifeSummedUp = ["☕", "💻", "🍷", "🍫"]; +const myLifeSummedUp = ['☕', '💻', '🍷', '🍫']; for (let item in myLifeSummedUp) { console.log(item); @@ -2590,13 +2589,13 @@ ES6에서, 기본값 `undefined` 값을 기본값 매개변수로 덮어쓸 수 ###### 82. 무엇이 출력 될까요? ```javascript -var status = "😎"; +var status = '😎'; setTimeout(() => { - const status = "😍"; + const status = '😍'; const data = { - status: "🥑", + status: '🥑', getStatus() { return this.status; }, @@ -2630,12 +2629,12 @@ setTimeout(() => { ```javascript const person = { - name: "Lydia", + name: 'Lydia', age: 21, }; let city = person.city; -city = "Amsterdam"; +city = 'Amsterdam'; console.log(person); ``` @@ -2699,7 +2698,7 @@ console.log(checkAge(21)); ###### 85. 어떤 종류의 정보가 출력될까요? ```javascript -fetch("https://www.website.com/api/user/1") +fetch('https://www.website.com/api/user/1') .then((res) => res.json()) .then((res) => console.log(res)); ``` @@ -2755,7 +2754,7 @@ function getName(name) { ###### 87. 무엇이 출력 될까요? ```javascript -console.log("I want pizza"[0]); +console.log('I want pizza'[0]); ``` - A: `"""` @@ -2810,11 +2809,11 @@ sum(10); ```javascript // module.js -export default () => "Hello world"; -export const name = "Lydia"; +export default () => 'Hello world'; +export const name = 'Lydia'; // index.js -import * as data from "./module"; +import * as data from './module'; console.log(data); ``` @@ -2847,7 +2846,7 @@ class Person { } } -const member = new Person("John"); +const member = new Person('John'); console.log(typeof member); ``` @@ -2907,7 +2906,7 @@ console.log(newList.push(5)); ```javascript function giveLydiaPizza() { - return "Here is pizza!"; + return 'Here is pizza!'; } const giveLydiaChocolate = () => @@ -2938,7 +2937,7 @@ console.log(giveLydiaChocolate.prototype); ```javascript const person = { - name: "Lydia", + name: 'Lydia', age: 21, }; @@ -2998,7 +2997,7 @@ function getItems(fruitList, favoriteFruit, ...args) { return [...fruitList, ...args, favoriteFruit]; } -getItems(["banana", "apple"], "pear", "orange"); +getItems(['banana', 'apple'], 'pear', 'orange'); ``` 위의 예시는 동작해요. 배열 `[ 'banana', 'apple', 'orange', 'pear' ]`을 반환해요. @@ -3012,8 +3011,8 @@ getItems(["banana", "apple"], "pear", "orange"); ```javascript function nums(a, b) { - if (a > b) console.log("a is bigger"); - else console.log("b is bigger"); + if (a > b) console.log('a is bigger'); + else console.log('b is bigger'); return; a + b; } @@ -3053,13 +3052,13 @@ a + b; ```javascript class Person { constructor() { - this.name = "Lydia"; + this.name = 'Lydia'; } } Person = class AnotherPerson { constructor() { - this.name = "Sarah"; + this.name = 'Sarah'; } }; @@ -3088,7 +3087,7 @@ console.log(member.name); ```javascript const info = { - [Symbol("a")]: "b", + [Symbol('a')]: 'b', }; console.log(info); @@ -3157,7 +3156,7 @@ rest 파라미터를 사용해 `...y`에 모든 "남은" 인수을 배열에 넣 ###### 99. 무엇이 출력 될까요? ```javascript -const name = "Lydia"; +const name = 'Lydia'; console.log(name()); ``` @@ -3189,8 +3188,8 @@ ReferenceErrors는 JavaScript가 접근하려고 하는 값의 참조를 찾을 ```javascript // 🎉✨ 이번이 내 100번째 질문이에요! ✨🎉 -const output = `${[] && "Im"}possible! -You should${"" && `n't`} see a therapist after so much JavaScript lol`; +const output = `${[] && 'Im'}possible! +You should${'' && `n't`} see a therapist after so much JavaScript lol`; ``` - A: `possible! You should see a therapist after so much JavaScript lol` @@ -3216,7 +3215,7 @@ You should${"" && `n't`} see a therapist after so much JavaScript lol`; ```javascript const one = false || {} || null; -const two = null || false || ""; +const two = null || false || ''; const three = [] || 0 || true; console.log(one, two, three); @@ -3248,16 +3247,16 @@ console.log(one, two, three); ###### 102. 무엇이 출력 될까요? ```javascript -const myPromise = () => Promise.resolve("I have resolved!"); +const myPromise = () => Promise.resolve('I have resolved!'); function firstFunction() { myPromise().then((res) => console.log(res)); - console.log("second"); + console.log('second'); } async function secondFunction() { console.log(await myPromise()); - console.log("second"); + console.log('second'); } firstFunction(); @@ -3295,8 +3294,8 @@ promise를 사용하면, 기본적으로 _이 함수를 실행하고 싶지만, const set = new Set(); set.add(1); -set.add("Lydia"); -set.add({ name: "Lydia" }); +set.add('Lydia'); +set.add({ name: 'Lydia' }); for (let item of set) { console.log(item + 2); @@ -3356,13 +3355,13 @@ promise 또는 non-promise가 아니더라도, 어떤 유형의 값이라도 `Pr ```javascript function compareMembers(person1, person2 = person) { if (person1 !== person2) { - console.log("Not the same!"); + console.log('Not the same!'); } else { - console.log("They are the same!"); + console.log('They are the same!'); } } -const person = { name: "Lydia" }; +const person = { name: 'Lydia' }; compareMembers(person); ``` @@ -3401,7 +3400,7 @@ const colorConfig = { yellow: false, }; -const colors = ["pink", "red", "blue"]; +const colors = ['pink', 'red', 'blue']; console.log(colorConfig.colors[1]); ``` @@ -3430,7 +3429,7 @@ JavaScript 문장을 해석(또는 참조형 변수를 원시 데이터 타입 ###### 107. 값은 무엇일까요? ```javascript -console.log("❤️" === "❤️"); +console.log('❤️' === '❤️'); ``` - A: `true` @@ -3451,14 +3450,14 @@ console.log("❤️" === "❤️"); ###### 108. 다음 중 원본 배열을 수정하는 method는 무엇일까요? ```javascript -const emojis = ["✨", "🥑", "😍"]; +const emojis = ['✨', '🥑', '😍']; -emojis.map((x) => x + "✨"); -emojis.filter((x) => x !== "🥑"); -emojis.find((x) => x !== "🥑"); -emojis.reduce((acc, cur) => acc + "✨"); -emojis.slice(1, 2, "✨"); -emojis.splice(1, 2, "✨"); +emojis.map((x) => x + '✨'); +emojis.filter((x) => x !== '🥑'); +emojis.find((x) => x !== '🥑'); +emojis.reduce((acc, cur) => acc + '✨'); +emojis.slice(1, 2, '✨'); +emojis.splice(1, 2, '✨'); ``` - A: `All of them` @@ -3483,10 +3482,10 @@ emojis.splice(1, 2, "✨"); ###### 109. 무엇이 출력 될까요? ```javascript -const food = ["🍕", "🍫", "🥑", "🍔"]; +const food = ['🍕', '🍫', '🥑', '🍔']; const info = { favoriteFood: food[0] }; -info.favoriteFood = "🍝"; +info.favoriteFood = '🍝'; console.log(food); ``` @@ -3540,7 +3539,7 @@ const jsonArray = JSON.stringify([1, 2, 3]); // '[1, 2, 3]' JSON.parse(jsonArray); // [1, 2, 3] // 객체를 유효한 JSON 문자열로 변환해요, 그리고 나서 JSON 문자열의 구문을 분석해 JavaScript 값으로 생성해요. -const jsonArray = JSON.stringify({ name: "Lydia" }); // '{"name":"Lydia"}' +const jsonArray = JSON.stringify({ name: 'Lydia' }); // '{"name":"Lydia"}' JSON.parse(jsonArray); // { name: 'Lydia' } ``` @@ -3552,11 +3551,11 @@ JSON.parse(jsonArray); // { name: 'Lydia' } ###### 111. 무엇이 출력 될까요? ```javascript -let name = "Lydia"; +let name = 'Lydia'; function getName() { console.log(name); - let name = "Sarah"; + let name = 'Sarah'; } getName(); @@ -3579,7 +3578,7 @@ getName(); `getName` 함수 안에 `name` 변수를 선언하지 않았다면, javaScript 엔진은 _스코프 체인_ 을 살펴봤을 거예요. 외부 범위에는 값이 `Lydia`인 `name`이라는 변수가 있어요. 이 경우 `Lydia`를 출력할 거예요. ```javascript -let name = "Lydia"; +let name = 'Lydia'; function getName() { console.log(name); @@ -3597,11 +3596,11 @@ getName(); // Lydia ```javascript function* generatorOne() { - yield ["a", "b", "c"]; + yield ['a', 'b', 'c']; } function* generatorTwo() { - yield* ["a", "b", "c"]; + yield* ['a', 'b', 'c']; } const one = generatorOne(); @@ -3647,7 +3646,7 @@ console.log(two.next().value); // undefined ###### 113. 무엇이 출력 될까요? ```javascript -console.log(`${((x) => x)("I love")} to program`); +console.log(`${((x) => x)('I love')} to program`); ``` - A: `I love to program` @@ -3672,7 +3671,7 @@ console.log(`${((x) => x)("I love")} to program`); ```javascript let config = { alert: setInterval(() => { - console.log("Alert!"); + console.log('Alert!'); }, 1000), }; @@ -3704,16 +3703,16 @@ config = null; ```javascript const myMap = new Map(); -const myFunc = () => "greeting"; +const myFunc = () => 'greeting'; -myMap.set(myFunc, "Hello world!"); +myMap.set(myFunc, 'Hello world!'); //1 -myMap.get("greeting"); +myMap.get('greeting'); //2 myMap.get(myFunc); //3 -myMap.get(() => "greeting"); +myMap.get(() => 'greeting'); ``` - A: 1 @@ -3740,14 +3739,14 @@ myMap.get(() => "greeting"); ```javascript const person = { - name: "Lydia", + name: 'Lydia', age: 21, }; const changeAge = (x = { ...person }) => (x.age += 1); const changeAgeAndName = (x = { ...person }) => { x.age += 1; - x.name = "Sarah"; + x.name = 'Sarah'; }; changeAge(person); @@ -3806,7 +3805,7 @@ function sumValues(x, y, z) { ```javascript let num = 1; -const list = ["🥳", "🤠", "🥰", "🤪"]; +const list = ['🥳', '🤠', '🥰', '🤪']; console.log(list[(num += 1)]); ``` @@ -3832,11 +3831,11 @@ console.log(list[(num += 1)]); ```javascript const person = { - firstName: "Lydia", - lastName: "Hallie", + firstName: 'Lydia', + lastName: 'Hallie', pet: { - name: "Mara", - breed: "Dutch Tulip Hound", + name: 'Mara', + breed: 'Dutch Tulip Hound', }, getFullName() { return `${this.firstName} ${this.lastName}`; @@ -3874,10 +3873,10 @@ optional chaining 연산자 `?.`를 사용하면, 더 깊이 중첩된 값이 ###### 120. 무엇이 출력 될까요? ```javascript -const groceries = ["banana", "apple", "peanuts"]; +const groceries = ['banana', 'apple', 'peanuts']; -if (groceries.indexOf("banana")) { - console.log("We have to buy bananas!"); +if (groceries.indexOf('banana')) { + console.log('We have to buy bananas!'); } else { console.log(`We don't have to buy bananas!`); } @@ -3933,10 +3932,10 @@ console.log(config.language); ###### 122. 무엇이 출력 될까요? ```javascript -const name = "Lydia Hallie"; +const name = 'Lydia Hallie'; -console.log(!typeof name === "object"); -console.log(!typeof name === "string"); +console.log(!typeof name === 'object'); +console.log(!typeof name === 'string'); ``` - A: `false` `true` @@ -4051,14 +4050,14 @@ myFunc(1, 2, 3); ```javascript function getFine(speed, amount) { - const formattedSpeed = new Intl.NumberFormat("en-US", { - style: "unit", - unit: "mile-per-hour", + const formattedSpeed = new Intl.NumberFormat('en-US', { + style: 'unit', + unit: 'mile-per-hour', }).format(speed); - const formattedAmount = new Intl.NumberFormat("en-US", { - style: "currency", - currency: "USD", + const formattedAmount = new Intl.NumberFormat('en-US', { + style: 'currency', + currency: 'USD', }).format(amount); return `The driver drove ${formattedSpeed} and has to pay ${formattedAmount}`; @@ -4087,8 +4086,8 @@ console.log(getFine(130, 300)); ###### 127. 무엇이 출력 될까요? ```javascript -const spookyItems = ["👻", "🎃", "🕸"]; -({ item: spookyItems[3] } = { item: "💀" }); +const spookyItems = ['👻', '🎃', '🕸']; +({ item: spookyItems[3] } = { item: '💀' }); console.log(spookyItems); ``` @@ -4113,7 +4112,7 @@ console.log(spookyItems); ###### 128. 무엇이 출력 될까요? ```javascript -const name = "Lydia Hallie"; +const name = 'Lydia Hallie'; const age = 21; console.log(Number.isNaN(name)); @@ -4149,7 +4148,7 @@ const randomValue = 21; function getInfo() { console.log(typeof randomValue); - const randomValue = "Lydia Hallie"; + const randomValue = 'Lydia Hallie'; } getInfo(); @@ -4175,7 +4174,7 @@ getInfo(); ###### 130. 무엇이 출력 될까요? ```javascript -const myPromise = Promise.resolve("Woah some cool data"); +const myPromise = Promise.resolve('Woah some cool data'); (async () => { try { @@ -4183,7 +4182,7 @@ const myPromise = Promise.resolve("Woah some cool data"); } catch { throw new Error(`Oops didn't work`); } finally { - console.log("Oh finally!"); + console.log('Oh finally!'); } })(); ``` @@ -4208,7 +4207,7 @@ const myPromise = Promise.resolve("Woah some cool data"); ###### 131. 무엇이 출력 될까요? ```javascript -const emojis = ["🥑", ["✨", "✨", ["🍕", "🍕"]]]; +const emojis = ['🥑', ['✨', '✨', ['🍕', '🍕']]]; console.log(emojis.flat(1)); ``` @@ -4281,19 +4280,19 @@ console.log(counterOne.count); ###### 133. 무엇이 출력 될까요? ```javascript -const myPromise = Promise.resolve(Promise.resolve("Promise!")); +const myPromise = Promise.resolve(Promise.resolve('Promise!')); function funcOne() { myPromise.then((res) => res).then((res) => console.log(res)); - setTimeout(() => console.log("Timeout!"), 0); - console.log("Last line!"); + setTimeout(() => console.log('Timeout!'), 0); + console.log('Last line!'); } async function funcTwo() { const res = await myPromise; console.log(await res); - setTimeout(() => console.log("Timeout!"), 0); - console.log("Last line!"); + setTimeout(() => console.log('Timeout!'), 0); + console.log('Last line!'); } funcOne(); @@ -4334,7 +4333,7 @@ export default function sum(x) { } // index.js -import * as sum from "./sum"; +import * as sum from './sum'; ``` - A: `sum(4)` @@ -4351,12 +4350,12 @@ import * as sum from "./sum"; ```javascript // info.js -export const name = "Lydia"; +export const name = 'Lydia'; export const age = 21; -export default "I love JavaScript"; +export default 'I love JavaScript'; // index.js -import * as info from "./info"; +import * as info from './info'; console.log(info); ``` @@ -4387,13 +4386,13 @@ console.log(info); ```javascript const handler = { - set: () => console.log("Added a new property!"), - get: () => console.log("Accessed a property!"), + set: () => console.log('Added a new property!'), + get: () => console.log('Accessed a property!'), }; const person = new Proxy({}, handler); -person.name = "Lydia"; +person.name = 'Lydia'; person.name; ``` @@ -4423,7 +4422,7 @@ Proxy 객체를 사용하면, 두번째 인수로 전달 한 객체에 사용자 ###### 136. 다음 중 어느 것이 `person` 객체를 수정 할 수 있을까요? ```javascript -const person = { name: "Lydia Hallie" }; +const person = { name: 'Lydia Hallie' }; Object.seal(person); ``` @@ -4451,9 +4450,9 @@ Object.seal(person); ```javascript const person = { - name: "Lydia Hallie", + name: 'Lydia Hallie', address: { - street: "100 Main St", + street: '100 Main St', }, }; @@ -4553,8 +4552,8 @@ ES2020에서, `#`을 사용한 private 변수를 추가 할 수 있어요. 클 ```javascript const teams = [ - { name: "Team 1", members: ["Paul", "Lisa"] }, - { name: "Team 2", members: ["Laura", "Tim"] }, + { name: 'Team 1', members: ['Paul', 'Lisa'] }, + { name: 'Team 2', members: ['Laura', 'Tim'] }, ]; function* getMembers(members) { @@ -4597,8 +4596,8 @@ obj.next(); // { value: "Lisa", done: false } ```javascript const person = { - name: "Lydia Hallie", - hobbies: ["coding"], + name: 'Lydia Hallie', + hobbies: ['coding'], }; function addHobby(hobby, hobbies = person.hobbies) { @@ -4606,9 +4605,9 @@ function addHobby(hobby, hobbies = person.hobbies) { return hobbies; } -addHobby("running", []); -addHobby("dancing"); -addHobby("baking", person.hobbies); +addHobby('running', []); +addHobby('dancing'); +addHobby('baking', person.hobbies); console.log(person.hobbies); ``` @@ -4677,11 +4676,11 @@ const pet = new Flamingo(); ###### 143. 다음 중 어느 것의 결과가 오류일까요? ```javascript -const emojis = ["🎄", "🎅🏼", "🎁", "⭐"]; +const emojis = ['🎄', '🎅🏼', '🎁', '⭐']; -/* 1 */ emojis.push("🦌"); +/* 1 */ emojis.push('🦌'); /* 2 */ emojis.splice(0, 2); -/* 3 */ emojis = [...emojis, "🥂"]; +/* 3 */ emojis = [...emojis, '🥂']; /* 4 */ emojis.length = 0; ``` @@ -4767,9 +4766,9 @@ function getFruit(fruits) { console.log(fruits?.[1]?.[1]); } -getFruit([["🍊", "🍌"], ["🍍"]]); +getFruit([['🍊', '🍌'], ['🍍']]); getFruit(); -getFruit([["🍍"], ["🍊", "🍌"]]); +getFruit([['🍍'], ['🍊', '🍌']]); ``` - A: `null`, `undefined`, 🍌 @@ -4799,19 +4798,19 @@ getFruit([["🍍"], ["🍊", "🍌"]]); ```javascript class Calc { - constructor() { - this.count = 0; - } + constructor() { + this.count = 0 + } - increase() { - this.count++; - } + increase() { + this.count ++ + } } -const calc = new Calc(); -new Calc().increase(); +const calc = new Calc() +new Calc().increase() -console.log(calc.count); +console.log(calc.count) ``` - A: `0` @@ -4835,25 +4834,25 @@ console.log(calc.count); ```javascript const user = { - email: "e@mail.com", - password: "12345", -}; + email: "e@mail.com", + password: "12345" +} const updateUser = ({ email, password }) => { - if (email) { - Object.assign(user, { email }); - } + if (email) { + Object.assign(user, { email }) + } - if (password) { - user.password = password; - } + if (password) { + user.password = password + } - return user; -}; + return user +} -const updatedUser = updateUser({ email: "new@email.com" }); +const updatedUser = updateUser({ email: "new@email.com" }) -console.log(updatedUser === user); +console.log(updatedUser === user) ``` - A: `false` @@ -4876,13 +4875,13 @@ console.log(updatedUser === user); ###### 149. 무엇이 출력 될까요? ```javascript -const fruit = ["🍌", "🍊", "🍎"]; +const fruit = ['🍌', '🍊', '🍎'] -fruit.slice(0, 1); -fruit.splice(0, 1); -fruit.unshift("🍇"); +fruit.slice(0, 1) +fruit.splice(0, 1) +fruit.unshift('🍇') -console.log(fruit); +console.log(fruit) ``` - A: `['🍌', '🍊', '🍎']` @@ -4908,13 +4907,13 @@ console.log(fruit); ```javascript const animals = {}; -let dog = { emoji: "🐶" }; -let cat = { emoji: "🐈" }; +let dog = { emoji: '🐶' } +let cat = { emoji: '🐈' } -animals[dog] = { ...dog, name: "Mara" }; -animals[cat] = { ...cat, name: "Sara" }; +animals[dog] = { ...dog, name: "Mara" } +animals[cat] = { ...cat, name: "Sara" } -console.log(animals[dog]); +console.log(animals[dog]) ``` - A: `{ emoji: "🐶", name: "Mara" }` @@ -4931,7 +4930,7 @@ console.log(animals[dog]); `dog`의 값은 객체 이므로, 사실 `animals[dog]`는 새로운 객체에 `"object Object"`라고 불리는 새로운 속성을 만든 걸 의미해요. 이제 `animals["object Object"]`는 `{ emoji: "🐶", name: "Mara"}`예요. -`cat`도 물론 객체고, 사실 `animals[cat]`은 ` animals[``"``object Object``"``] `을 새로운 속성 cat으로 덮어쓰고 있다는 것을 의미해요. +`cat`도 물론 객체고, 사실 `animals[cat]`은 `animals[``"``object Object``"``]`을 새로운 속성 cat으로 덮어쓰고 있다는 것을 의미해요. `animals[dog]` 또는 `animals["object Object"]`(`dog` 객체를 문자열로 변환한 결과는 `"object Object"`)를 출력하면, `{ emoji: "🐈", name: "Sara" }`를 반환해요. @@ -4944,14 +4943,14 @@ console.log(animals[dog]); ```javascript const user = { - email: "my@email.com", - updateEmail: (email) => { - this.email = email; - }, -}; + email: "my@email.com", + updateEmail: email => { + this.email = email + } +} -user.updateEmail("new@email.com"); -console.log(user.email); +user.updateEmail("new@email.com") +console.log(user.email) ``` - A: `my@email.com` @@ -4974,20 +4973,20 @@ console.log(user.email); ###### 152. 무엇이 출력 될까요? ```javascript -const promise1 = Promise.resolve("First"); -const promise2 = Promise.resolve("Second"); -const promise3 = Promise.reject("Third"); -const promise4 = Promise.resolve("Fourth"); +const promise1 = Promise.resolve('First') +const promise2 = Promise.resolve('Second') +const promise3 = Promise.reject('Third') +const promise4 = Promise.resolve('Fourth') const runPromises = async () => { - const res1 = await Promise.all([promise1, promise2]); - const res2 = await Promise.all([promise3, promise4]); - return [res1, res2]; -}; + const res1 = await Promise.all([promise1, promise2]) + const res2 = await Promise.all([promise3, promise4]) + return [res1, res2] +} runPromises() - .then((res) => console.log(res)) - .catch((err) => console.log(err)); + .then(res => console.log(res)) + .catch(err => console.log(err)) ``` - A: `[['First', 'Second'], ['Fourth']]` @@ -5010,16 +5009,13 @@ runPromises() ###### 153. 무엇이 `method`의 값이어야 `{ name: "Lydia", age: 22 }`를 출력할까요? ```javascript -const keys = ["name", "age"]; -const values = ["Lydia", 22]; +const keys = ["name", "age"] +const values = ["Lydia", 22] -const method = - /* ?? */ - Object[method]( - keys.map((_, i) => { - return [keys[i], values[i]]; - }) - ); // { name: "Lydia", age: 22 } +const method = /* ?? */ +Object[method](keys.map((_, i) => { + return [keys[i], values[i]] +})) // { name: "Lydia", age: 22 } ``` - A: `entries` @@ -5044,18 +5040,18 @@ const method = ###### 154. 무엇이 출력 될까요? ```javascript -const createMember = ({ email, address = {} }) => { - const validEmail = /.+\@.+\..+/.test(email); - if (!validEmail) throw new Error("Valid email pls"); +const createMember = ({ email, address = {}}) => { + const validEmail = /.+\@.+\..+/.test(email) + if (!validEmail) throw new Error("Valid email pls") - return { - email, - address: address ? address : null, - }; -}; + return { + email, + address: address ? address : null + } +} -const member = createMember({ email: "my@email.com" }); -console.log(member); +const member = createMember({ email: "my@email.com" }) +console.log(member) ``` - A: `{ email: "my@email.com", address: null }` @@ -5078,13 +5074,13 @@ console.log(member); ###### 155. 무엇이 출력 될까요? ```javascript -let randomValue = { name: "Lydia" }; -randomValue = 23; +let randomValue = { name: "Lydia" } +randomValue = 23 if (!typeof randomValue === "string") { - console.log("It's not a string!"); + console.log("It's not a string!") } else { - console.log("Yay it's a string!"); + console.log("Yay it's a string!") } ``` diff --git a/nl-NL/README.md b/nl-NL/README.md index 1852e0e0..0400e8ed 100644 --- a/nl-NL/README.md +++ b/nl-NL/README.md @@ -2,15 +2,14 @@

JavaScript Vragen

---- - -Ik plaats JavaScript meerkeuzevragen op mijn [Instagram](https://www.instagram.com/theavocoder) **stories**, welke ik ook hier zal plaatsen! Laatste update: 24 december + --- -Van beginner naar expert: test hoe goed je JavaScript kent, fris je kennis een beetje op, of bereid je voor op een sollicitatiegesprek! :muscle: :rocket: Ik zal deze repository regelmatig updaten met nieuwe vragen. Ik heb de antwoorden toegevoegd in de **ingeklapte secties** onder een vraag, zodat je er makkelijk op kan klikken om ze uit te klappen. Het is gewoon voor je plezier, veel succes! :heart: + Ik plaats JavaScript meerkeuzevragen op mijn [Instagram](https://www.instagram.com/theavocoder) **stories**, welke ik ook hier zal plaatsen! Laatste update: 24 december -Voel je vrij om contact met mij op te nemen! 😊
-Instagram || Twitter || LinkedIn || Blog + Van beginner naar expert: test hoe goed je JavaScript kent, fris je kennis een beetje op, of bereid je voor op een sollicitatiegesprek! :muscle: :rocket: Ik zal deze repository regelmatig updaten met nieuwe vragen. Ik heb de antwoorden toegevoegd in de **ingeklapte secties** onder een vraag, zodat je er makkelijk op kan klikken om ze uit te klappen. Het is gewoon voor je plezier, veel succes! :heart:
+ Voel je vrij om contact met mij op te nemen! 😊
+ Instagram || Twitter || LinkedIn || Blog --- @@ -31,7 +30,6 @@ Voel je vrij om contact met mij op te nemen! 😊
- [🇰🇷 한국어](../ko-KR/README-ko_KR.md) - [🇵🇱 Polski](../pl-PL/README.md) - [🇧🇷 Português Brasil](../pt-BR/README_pt_BR.md) -- [🇷o Română](../ro-RO/README.ro.md) - [🇷🇺 Русский](../ru-RU/README.md) - [🇽🇰 Shqip](../sq-KS/README_sq_KS.md) - [🇹🇭 ไทย](../th-TH/README-th_TH.md) @@ -116,7 +114,7 @@ const shape = { diameter() { return this.radius * 2; }, - perimeter: () => 2 * Math.PI * this.radius, + perimeter: () => 2 * Math.PI * this.radius }; console.log(shape.diameter()); @@ -173,12 +171,12 @@ De string `'Lydia'` is een truthy waarde. Wat we eigenlijk vragen, is "is deze t ```javascript const bird = { - size: "small", + size: "small" }; const mouse = { name: "Mickey", - small: true, + small: true }; ``` @@ -205,6 +203,7 @@ Echter, met de dot notatie zal dit niet gebeuren. `mouse` heeft geen propertie g --- + ###### 6. Wat is de uitkomst? ```javascript @@ -264,7 +263,7 @@ console.log(b === c); `new Number()` is een ingebouwde functie constructor. En ook al lijkt het misschien op een nummer, dat is het niet. Het is een object en bevat ten opzichte van een nummer veel extra opties. -Wanneer we de `==` operator gebruiken wordt er alleen op de _waarde_ gecheckt. Zowel `a` als `b` bevatten de waarde `3`, dus geeft dit `true` terug. +Wanneer we de `==` operator gebruiken wordt er alleen op de _waarde_ gecheckt. Zowel `a` als `b` bevatten de waarde `3`, dus geeft dit `true` terug. Echter, wanneer we de `===` operator gebruiken wordt er zowel op de _waarde_ als op het _type_ gecheckt. Omdat `new Number()` een **object** is en geen nummer zal dit `false` teruggeven. @@ -372,7 +371,7 @@ function Person(firstName, lastName) { } const member = new Person("Lydia", "Hallie"); -Person.getFullName = function () { +Person.getFullName = function() { return `${this.firstName} ${this.lastName}`; }; @@ -392,7 +391,7 @@ console.log(member.getFullName()); Je kunt geen properties toevoegen aan een instantie van een object, zoals je kan met normale objecten. Als je een feature toe wilt voegen aan alle objecten in één keer zul je dit middels de prototype van een object moeten doen. In dit geval, ```js -Person.prototype.getFullName = function () { +Person.prototype.getFullName = function() { return `${this.firstName} ${this.lastName}`; }; ``` @@ -848,7 +847,7 @@ String.prototype.giveLydiaPizza = () => { const name = "Lydia"; -console.log(name.giveLydiaPizza()); +console.log(name.giveLydiaPizza()) ``` - A: `"Just give Lydia pizza already!"` @@ -944,7 +943,7 @@ De WebAPI kan niet zomaar dingen toevoegen aan de stack. In plaats daarvan wordt -Dit is waar de event loop zijn intrede doet. Een _\*\*event loop_ naar de stack en de task queue. Als de stack leeg is pakt het het eerste ding op van de queue en zet het op de stack. +Dit is waar de event loop zijn intrede doet. Een ***event loop* naar de stack en de task queue. Als de stack leeg is pakt het het eerste ding op van de queue en zet het op de stack. @@ -960,7 +959,9 @@ Dit is waar de event loop zijn intrede doet. Een _\*\*event loop_ naar de stack ```html
- +
``` @@ -986,7 +987,9 @@ Het diepst geneste element dat het event afvuurt is de target van het event. Je ```html
-

Click here!

+

+ Click here! +

``` @@ -1221,10 +1224,7 @@ Wat primitieven onderscheidt van objecten is dat primitieven geen properties of ###### 40. Wat is de uitkomst? ```javascript -[ - [0, 1], - [2, 3], -].reduce( +[[0, 1], [2, 3]].reduce( (acc, cur) => { return acc.concat(cur); }, @@ -1349,7 +1349,6 @@ console.log(gen.next().value);

#### Antwoord: C - Reguliere functies kunnen niet worden gestopt halverwege na de aanroep. Echter, een generator functie kan wel "gestopt" worden halverwege, en later verder gaan waar ik gestopt is. Elke keer als een generator functie het keyword `yield` aantreft levert de functie de waarde op gespecificeerd achter `yield`. Let op dat een generator functie in dat geval niet de waarde _teruggeeft_, maar de waarde _oplevert_. Eerst initialiseren we de generator functie met `i`, dat gelijk is aan `10`. We roepen de generator functie aan met de `next()` methode. De eerste keer dat we de generator functie aanroepen is `i` gelijk aan `10`. De eerste `yield` wordt aangetroffen: het levert de waarde op van `i`. De generator is nu "gepauzeerd" en `10` wordt gelogd. @@ -1372,7 +1371,7 @@ const secondPromise = new Promise((res, rej) => { setTimeout(res, 100, "two"); }); -Promise.race([firstPromise, secondPromise]).then((res) => console.log(res)); +Promise.race([firstPromise, secondPromise]).then(res => console.log(res)); ``` - A: `"one"` @@ -1436,7 +1435,7 @@ We passaen alleen de waarde aan van de `person` variabele en niet van het eerste ```javascript const person = { name: "Lydia", - age: 21, + age: 21 }; for (const item in person) { @@ -1516,7 +1515,7 @@ Alleen het eerste getal in de string wordt geretourneerd. Gebaseerd op de _radix ###### 50. Wat is de uitkomst? ```javascript -[1, 2, 3].map((num) => { +[1, 2, 3].map(num => { if (typeof num === "number") return; return num * 2; }); @@ -1566,7 +1565,6 @@ console.log(person, birthYear);

#### Antwoord: A - Argumenten worden meegegeven _by value_, tenzij de waarde een object is. Dan worden ze meegegeven _by reference_. `birthYear` is een string en geen object, waardoor het dus doorgegeven wordt _by value_. Wanneer we een argument meegeven _by value_ wordt er een _copy_ aangemaakt van het argument (zie vraag 46). De variabele `birthYear` heeft een referentie naar de waarde `"1997"`. Het argument `year` heeft ook een referentie naar de waarde '"1997"', maar het is niet dezelfde waarde als waar `birthYear` een referentie naar heeft. Wanneer we de waarde van `year` veranderen naar `"1998"`, veranderen we alleen de waarde van `year`. `birthYear` is nog steeds gelijk aan `"1997"`. @@ -1693,7 +1691,7 @@ class Dog { } } -Dog.prototype.bark = function () { +Dog.prototype.bark = function() { console.log(`Woof I am ${this.name}`); }; @@ -1716,7 +1714,7 @@ pet.bark(); #### Antwoord: A -We kunnen properties verwijderen van een object als we gebruik maken van het `delete` keyword, en ook op het prototype. Bij het verwijderen van een propertie op de prototype zal het niet meer beschikbaar zijn in de prototype chain. In dit geval is de `bark()` methode niet meer beschikbaar op de protoype na `delete Dog.prototype.bark`. +We kunnen properties verwijderen van een object als we gebruik maken van het `delete` keyword, en ook op het prototype. Bij het verwijderen van een propertie op de prototype zal het niet meer beschikbaar zijn in de prototype chain. In dit geval is de `bark()` methode niet meer beschikbaar op de protoype na `delete Dog.prototype.bark`. Wanneer we iets proberen aan te roepen dat geen functie is zal er een `TypeError` gegooid worden. In dit geval `TypeError: pet.bark is not a function`, omdat `pet.bark` `undefined` is. @@ -1906,7 +1904,7 @@ console.log(Object.keys(person)); #### Antwoord: B -Met de `defineProperty` methode kunnen we properties toevoegen aan een object, of bestaande properties aanpassen. Wanneer we properties toevoegen aan een object door gebruik te maken van `defineProperty` zijn deze standaard _not enumerable_. De `Object.keys` methode geeft alle _enumerable_ propertie namen terug van een object, in dit geval alleen `"name"`. +Met de `defineProperty` methode kunnen we properties toevoegen aan een object, of bestaande properties aanpassen. Wanneer we properties toevoegen aan een object door gebruik te maken van `defineProperty` zijn deze standaard _not enumerable_. De `Object.keys` methode geeft alle _enumerable_ propertie namen terug van een object, in dit geval alleen `"name"`. Properties toegevoegd met de `defineProperty` methode zijn standaard onveranderbaar. Je kunt dit gedrag aanpassen door, in het derde argument, de `writable`, `configurable` en `enumerable` opties mee te geven. Op die manier geeft de `defineProperties` je veel controle over de properties die je wilt toevoegen aan een object. @@ -1921,7 +1919,7 @@ Properties toegevoegd met de `defineProperty` methode zijn standaard onveranderb const settings = { username: "lydiahallie", level: 19, - health: 90, + health: 90 }; const data = JSON.stringify(settings, ["level", "health"]); @@ -1955,7 +1953,7 @@ Als de replacer een _functie_ is zal die functie worden aangeroepen over elke pr let num = 10; const increaseNumber = () => num++; -const increasePassedNumber = (number) => number++; +const increasePassedNumber = number => number++; const num1 = increaseNumber(); const num2 = increasePassedNumber(num1); @@ -2011,7 +2009,7 @@ multiply(value); In ES6 kunnen we parameters initialiseren met een standaard waarde. De waarde van de parameter zal deze standaard waarde behouden zolang er geen andere waarde wordt meegegeven aan de functie, of als de waarde van de parameter `"undefined"` is. In dit geval kopiëren we de properties van het `value` object naar een nieuw object gebruikmakend van de spread operator, dus `x` heeft de standaard waarde `{ number: 10 }`. -De standaard waarde wordt geëvalueerd tijdens _call time_ (aanroeptijd)! Elke keer wanneer we de functie aanroepen wordt er een nieuw object aangemaakt. We roepen de `multiply` functie de eerste twee keer aan zonder een waarde mee te geven: `x` heeft de standaard waarde van `{ number: 10 }`. We loggen dan de vermenigvuldigde waarde van dat getal, wat `20` is. +De standaard waarde wordt geëvalueerd tijdens _call time_ (aanroeptijd)! Elke keer wanneer we de functie aanroepen wordt er een nieuw object aangemaakt. We roepen de `multiply` functie de eerste twee keer aan zonder een waarde mee te geven: `x` heeft de standaard waarde van `{ number: 10 }`. We loggen dan de vermenigvuldigde waarde van dat getal, wat `20` is. De derde keer dat we de functie `multiply` aanroepen geven we wel een waarde mee: het object genaamd `value`. De `*=` operator is eigenlijk een verkorting van `x.number = x.number * 2`: we passen de waarde van `x.number` aan en loggen de vermenigvuldigde waarde `20`. @@ -2042,11 +2040,11 @@ Het eerste argument van de `reduce` methode is de _accumulator_, in dit geval `x In dit voorbeeld geven we geen waarde terug. We loggen enkel the waarden van de accumulator en de huidige waarde. -De waarde van de accumulator is gelijk aan de vorige teruggegeven waarde van de callback functie. Als je niet de optionele `initialValue` meegeeft aan de `reduce` methode, de accumulator is gelijk aan het eerste element tijdens de eerste aanroep. +De waarde van de accumulator is gelijk aan de vorige teruggegeven waarde van de callback functie. Als je niet de optionele `initialValue` meegeeft aan de `reduce` methode, de accumulator is gelijk aan het eerste element tijdens de eerste aanroep. Tijdens de eerste aanroep is de accumulator (`x`) `1` en de huidige waarde (`y`) `2`. We geven niets terug in de callback function, we loggen de accumulator en de huidige waarde: `1` en `2` worden gelogd. -Als je niets teruggeeft in een functie, zal de functie `undefined` teruggeven. Tijdens de volgende aanroep is de accumulator `undefined` en de huidige waarde `3`. `undefined` en `3` worden gelogt. +Als je niets teruggeeft in een functie, zal de functie `undefined` teruggeven. Tijdens de volgende aanroep is de accumulator `undefined` en de huidige waarde `3`. `undefined` en `3` worden gelogt. Tijdens de vierde aanroep geven we wederom niets terug in de callback functie. De accumulator is wederom `undefined`, en de huidige waarde `4`. `undefined` en `4` worden gelogt. @@ -2065,7 +2063,7 @@ class Dog { }; class Labrador extends Dog { - // 1 + // 1 constructor(name, size) { this.size = size; } @@ -2079,7 +2077,7 @@ class Labrador extends Dog { super(name); this.size = size; } - // 4 + // 4 constructor(name, size) { this.name = name; this.size = size; @@ -2113,12 +2111,12 @@ De `Labrador` class verwacht twee argumenten, `name` omdat het een afgeleide is ```javascript // index.js -console.log("running index.js"); -import { sum } from "./sum.js"; +console.log('running index.js'); +import { sum } from './sum.js'; console.log(sum(1, 2)); // sum.js -console.log("running sum.js"); +console.log('running sum.js'); export const sum = (a, b) => a + b; ``` @@ -2144,9 +2142,9 @@ Dit is een verschil tussen `require()` in CommonJS en `import`! Met `require()` ###### 68. Wat is de uitkomst? ```javascript -console.log(Number(2) === Number(2)); -console.log(Boolean(false) === Boolean(false)); -console.log(Symbol("foo") === Symbol("foo")); +console.log(Number(2) === Number(2)) +console.log(Boolean(false) === Boolean(false)) +console.log(Symbol('foo') === Symbol('foo')) ``` - A: `true`, `true`, `false` @@ -2169,22 +2167,22 @@ Elk Symbol is volledig uniek. Het doel van het argument dat meegegeven wordt aan ###### 69. Wat is de uitkomst? ```javascript -const name = "Lydia Hallie"; -console.log(name.padStart(13)); -console.log(name.padStart(2)); +const name = "Lydia Hallie" +console.log(name.padStart(13)) +console.log(name.padStart(2)) ``` - A: `"Lydia Hallie"`, `"Lydia Hallie"` - B: `" Lydia Hallie"`, `" Lydia Hallie"` (`"[13x whitespace]Lydia Hallie"`, `"[2x whitespace]Lydia Hallie"`) - C: `" Lydia Hallie"`, `"Lydia Hallie"` (`"[1x whitespace]Lydia Hallie"`, `"Lydia Hallie"`) -- D: `"Lydia Hallie"`, `"Lyd"`, +- D: `"Lydia Hallie"`, `"Lyd"`,

Antwoord

#### Antwoord: C -Met de `padStart` methode kunnen we witruimte toevoegen aan het begin van de string. De waarde die meegegeven wordt aan de methode is de _totale_ lengte van de string, samen met de witruimte. De string `"Lydia Hallie"` heeft een lengte van `13`. `name.padStart(13)` plaatst 1 spatie toe aan het begin van de string omdat 12 + 1 = 13. +Met de `padStart` methode kunnen we witruimte toevoegen aan het begin van de string. De waarde die meegegeven wordt aan de methode is de _totale_ lengte van de string, samen met de witruimte. De string `"Lydia Hallie"` heeft een lengte van `13`. `name.padStart(13)` plaatst 1 spatie toe aan het begin van de string omdat 12 + 1 = 13. Als het argument dat we meegeven aan de `padStart` methode kleiner is dan de lengte van de string zullen er geen spaties worden toegevoegd. @@ -2445,7 +2443,7 @@ De `sum` functie geeft altijd dezelfde waarde terug. Als we `1` en `2` meegeven ```javascript const add = () => { const cache = {}; - return (num) => { + return num => { if (num in cache) { return `From cache! ${cache[num]}`; } else { @@ -2490,21 +2488,21 @@ De derde keer geven we `5 * 2` mee aan de functie wat `10` oplevert. Het `cache` ###### 79. Wat is de uitkomst? ```javascript -const myLifeSummedUp = ["☕", "💻", "🍷", "🍫"]; +const myLifeSummedUp = ["☕", "💻", "🍷", "🍫"] for (let item in myLifeSummedUp) { - console.log(item); + console.log(item) } for (let item of myLifeSummedUp) { - console.log(item); + console.log(item) } ``` - A: `0` `1` `2` `3` en `"☕"` ` "💻"` `"🍷"` `"🍫"` - B: `"☕"` ` "💻"` `"🍷"` `"🍫"` en `"☕"` ` "💻"` `"🍷"` `"🍫"` - C: `"☕"` ` "💻"` `"🍷"` `"🍫"` en `0` `1` `2` `3` -- D: `0` `1` `2` `3` en `{0: "☕", 1: "💻", 2: "🍷", 3: "🍫"}` +- D: `0` `1` `2` `3` en `{0: "☕", 1: "💻", 2: "🍷", 3: "🍫"}`

Antwoord

@@ -2527,21 +2525,21 @@ Met de _for-of_ loop kunnen we itereren over **iterables**. Een array is een ite ###### 80. Wat is de uitkomst? ```javascript -const list = [1 + 2, 1 * 2, 1 / 2]; -console.log(list); +const list = [1 + 2, 1 * 2, 1 / 2] +console.log(list) ``` - A: `["1 + 2", "1 * 2", "1 / 2"]` - B: `["12", 2, 0.5]` - C: `[3, 2, 0.5]` -- D: `[1, 1, 1]` +- D: `[1, 1, 1]`

Antwoord

#### Antwoord: C -Array elementen kunnen elke waarde bevatten. Nummers, strings, objecten, andere arrays, null, boolean waarden, undefined en andere expressies zoals datums, functies en berekeningen. +Array elementen kunnen elke waarde bevatten. Nummers, strings, objecten, andere arrays, null, boolean waarden, undefined en andere expressies zoals datums, functies en berekeningen. Het element zal gelijk zijn aan de teruggegeven waarde. `1 + 2` geeft `3` terug, `1 * 2` geeft `2` terug en `1 / 2` geeft `0.5` terug. @@ -2554,16 +2552,16 @@ Het element zal gelijk zijn aan de teruggegeven waarde. `1 + 2` geeft `3` terug, ```javascript function sayHi(name) { - return `Hi there, ${name}`; + return `Hi there, ${name}` } -console.log(sayHi()); +console.log(sayHi()) ``` - A: `Hi there, ` - B: `Hi there, undefined` - C: `Hi there, null` -- D: `ReferenceError` +- D: `ReferenceError`

Antwoord

@@ -2576,7 +2574,7 @@ In ES6 kunnen we argumenten een standaard waarde geven. Als voorbeeld: `function sayHi(name = "Lydia") { ... }` -In dit geval zal de waarde van het argument `name`, als we geen waarde meegeven aan de functie, standaard `Lydia` bevatten. +In dit geval zal de waarde van het argument `name`, als we geen waarde meegeven aan de functie, standaard `Lydia` bevatten.

@@ -2586,21 +2584,21 @@ In dit geval zal de waarde van het argument `name`, als we geen waarde meegeven ###### 82. Wat is de uitkomst? ```javascript -var status = "😎"; +var status = "😎" setTimeout(() => { - const status = "😍"; + const status = "😍" const data = { status: "🥑", getStatus() { - return this.status; - }, - }; + return this.status + } + } - console.log(data.getStatus()); - console.log(data.getStatus.call(this)); -}, 0); + console.log(data.getStatus()) + console.log(data.getStatus.call(this)) +}, 0) ``` - A: `"🥑"` en `"😍"` @@ -2627,13 +2625,13 @@ Met de `call` methode kunnen we het object veranderen waarnaar het keyword `this ```javascript const person = { name: "Lydia", - age: 21, -}; + age: 21 +} -let city = person.city; -city = "Amsterdam"; +let city = person.city +city = "Amsterdam" -console.log(person); +console.log(person) ``` - A: `{ name: "Lydia", age: 21 }` @@ -2664,15 +2662,15 @@ Wanneer we het object `person` loggen, wordt het onaangepaste object gelogd. ```javascript function checkAge(age) { if (age < 18) { - const message = "Sorry, you're too young."; + const message = "Sorry, you're too young." } else { - const message = "Yay! You're old enough!"; + const message = "Yay! You're old enough!" } - return message; + return message } -console.log(checkAge(21)); +console.log(checkAge(21)) ``` - A: `"Sorry, you're too young."` @@ -2695,9 +2693,9 @@ Variabelen gedeclareerd met de keywords `const` en `let` zijn _block-scoped_. Ee ###### 85. Welke informatie zal worden gelogd? ```javascript -fetch("https://www.website.com/api/user/1") - .then((res) => res.json()) - .then((res) => console.log(res)); +fetch('https://www.website.com/api/user/1') + .then(res => res.json()) + .then(res => console.log(res)) ``` - A: Het resultaat van de `fetch` methode. @@ -2737,7 +2735,7 @@ function getName(name) { Met `!!name` stellen we vast of de waarde van `name` truthy of falsy is. Als `name` truthy is, dit is wat we willen testen, zal `!name` `false` teruggeven. `!false` (wat `!!name` feitelijk is) geeft `true` terug. -Wanneer we `hasName` vullen met `name`, vullen we het met dat wat we meegeven aan de `getName` functie, niet de boolean waarde `true`. +Wanneer we `hasName` vullen met `name`, vullen we het met dat wat we meegeven aan de `getName` functie, niet de boolean waarde `true`. `new Boolean(true)` geeft een object wrapper terug, niet de boolean waarde zelf. @@ -2751,7 +2749,7 @@ Wanneer we `hasName` vullen met `name`, vullen we het met dat wat we meegeven aa ###### 87. Wat is de uitkomst? ```javascript -console.log("I want pizza"[0]); +console.log("I want pizza"[0]) ``` - A: `"""` @@ -2777,10 +2775,10 @@ Let op dat deze methode niet ondersteund wordt in IE7 en daaronder. In dat geval ```javascript function sum(num1, num2 = num1) { - console.log(num1 + num2); + console.log(num1 + num2) } -sum(10); +sum(10) ``` - A: `NaN` @@ -2795,7 +2793,7 @@ sum(10); Je kunt een parameters standaard waarde gelijk zetten aan een andere parameter van diezelfde functie, zolang deze definieerd is _voor_ de parameter met een standaard waarde. We geen de waarde `10` mee aan de `sum` functie. Als de `sum` functie maar één argument meekrijgt betekent dit dat de waarde van `num2` gevuld wordt met de waarde van `num1`. `10` in dit geval. De standaard waarde van `num2` is de waarde van `num1`, wat `10` is. `num1 + num2` geeft `20` terug. -Als je probeert de standaard waarde van een parameter te vullen met de waarde van een parameter welke gedefinieerd is _na_ de standaard parameter, dan is de parameter nog niet geïnitialiseerd en wordt er een error gegooid. +Als je probeert de standaard waarde van een parameter te vullen met de waarde van een parameter welke gedefinieerd is _na_ de standaard parameter, dan is de parameter nog niet geïnitialiseerd en wordt er een error gegooid.

@@ -2805,14 +2803,14 @@ Als je probeert de standaard waarde van een parameter te vullen met de waarde va ###### 89. Wat is de uitkomst? ```javascript -// module.js -export default () => "Hello world"; -export const name = "Lydia"; +// module.js +export default () => "Hello world" +export const name = "Lydia" -// index.js -import * as data from "./module"; +// index.js +import * as data from "./module" -console.log(data); +console.log(data) ``` - A: `{ default: function default(), name: "Lydia" }` @@ -2824,7 +2822,6 @@ console.log(data);

#### Antwoord: A - Met de `import * as name` syntax importeren we _alle exports_ van `module.js` bestand in het bestand `index.js` als een nieuw object met de naam `data`. In het bestand `module.js` zijn er twee exports: de standaard export en de benoemde export. De standaard export is een functie dat de string `"Hello world"` teruggeeft, en de benoemde export is de variabele `name` wat de waarde van de string `"Lydia"` bevat. Het object `data` bevat een propertie `default` voor de standaard export. Andere properties hebben de naam van de benoemde exports en hun corresponderende waarden. @@ -2839,12 +2836,12 @@ Het object `data` bevat een propertie `default` voor de standaard export. Andere ```javascript class Person { constructor(name) { - this.name = name; + this.name = name } } -const member = new Person("John"); -console.log(typeof member); +const member = new Person("John") +console.log(typeof member) ``` - A: `"class"` @@ -2861,7 +2858,7 @@ Classes zijn een syntactisch sausje voor functie constructors. Het equivalent va ```javascript function Person() { - this.name = name; + this.name = name } ``` @@ -2875,9 +2872,9 @@ Het aanroepen van de functie contructor met `new` resulteert in het creëeren va ###### 91. Wat is de uitkomst? ```javascript -let newList = [1, 2, 3].push(4); +let newList = [1, 2, 3].push(4) -console.log(newList.push(5)); +console.log(newList.push(5)) ``` - A: `[1, 2, 3, 4, 5]` @@ -2903,18 +2900,17 @@ Dan gebruiken we de `.push` methode op `newList`. Omdat `newList` nu de numeriek ```javascript function giveLydiaPizza() { - return "Here is pizza!"; + return "Here is pizza!" } -const giveLydiaChocolate = () => - "Here's chocolate... now go hit the gym already."; +const giveLydiaChocolate = () => "Here's chocolate... now go hit the gym already." -console.log(giveLydiaPizza.prototype); -console.log(giveLydiaChocolate.prototype); +console.log(giveLydiaPizza.prototype) +console.log(giveLydiaChocolate.prototype) ``` -- A: `{ constructor: ...}` `{ constructor: ...}` -- B: `{}` `{ constructor: ...}` +- A: `{ constructor: ...}` `{ constructor: ...}` +- B: `{}` `{ constructor: ...}` - C: `{ constructor: ...}` `{}` - D: `{ constructor: ...}` `undefined` @@ -2935,16 +2931,16 @@ Reguliere functies zoals de `giveLydiaPizza` functie hebben een `prototype` prop ```javascript const person = { name: "Lydia", - age: 21, -}; + age: 21 +} for (const [x, y] of Object.entries(person)) { - console.log(x, y); + console.log(x, y) } ``` - A: `name` `Lydia` en `age` `21` -- B: `["name", "Lydia"]` en `["age", 21]` +- B: `["name", "Lydia"]` en `["age", 21]` - C: `["name", "age"]` en `undefined` - D: `Error` @@ -2955,11 +2951,11 @@ for (const [x, y] of Object.entries(person)) { `Object.entries(person)` retourneert een array van geneste arrays, welke de keys en objecten bevat: -`[ [ 'name', 'Lydia' ], [ 'age', 21 ] ]` +`[ [ 'name', 'Lydia' ], [ 'age', 21 ] ]` Gebruikmakend van de `for-of` loop kunnen we itereren over elk element in de array, de subarrays in dit geval. We kunnen de subarrays direct destructureren door `const [x, y]` te gebruiken. `x` is gelijk aan het eerste element in de subarray, `y` is gelijk aan het tweede element in de subarray. -De eerste subarray wat wordt gelogd is `[ "name", "Lydia" ]`, waarbij `x` gelijk is aan `"name"` en `y` gelijk is aan `"Lydia"`. +De eerste subarray wat wordt gelogd is `[ "name", "Lydia" ]`, waarbij `x` gelijk is aan `"name"` en `y` gelijk is aan `"Lydia"`. De tweede subarray wat wordt gelogd is `[ "age", "21" ]`, waarbij `x` gelijk is aan `"age"` en `y` gelijk is aan `"21"`.

@@ -2978,7 +2974,7 @@ getItems(["banana", "apple"], "pear", "orange") ``` - A: `["banana", "apple", "pear", "orange"]` -- B: `[["banana", "apple"], "pear", "orange"]` +- B: `[["banana", "apple"], "pear", "orange"]` - C: `["banana", "apple", ["pear"], "orange"]` - D: `SyntaxError` @@ -2991,10 +2987,10 @@ getItems(["banana", "apple"], "pear", "orange") ```javascript function getItems(fruitList, favoriteFruit, ...args) { - return [...fruitList, ...args, favoriteFruit]; + return [...fruitList, ...args, favoriteFruit] } -getItems(["banana", "apple"], "pear", "orange"); +getItems(["banana", "apple"], "pear", "orange") ``` Het bovenstaande voorbeeld werkt. Dit geeft de array `[ 'banana', 'apple', 'orange', 'pear' ]` terug. @@ -3008,14 +3004,17 @@ Het bovenstaande voorbeeld werkt. Dit geeft de array `[ 'banana', 'apple', 'oran ```javascript function nums(a, b) { - if (a > b) console.log("a is bigger"); - else console.log("b is bigger"); - return; - a + b; + if + (a > b) + console.log('a is bigger') + else + console.log('b is bigger') + return + a + b } -console.log(nums(4, 2)); -console.log(nums(1, 2)); +console.log(nums(4, 2)) +console.log(nums(1, 2)) ``` - A: `a is bigger`, `6` en `b is bigger`, `3` @@ -3033,8 +3032,8 @@ In JavaScript _hoeven_ we geen puntkomma's te schrijven, alhoewel de JavaScript Hier schreven we een `return` statement en op de _nieuwe regel_ `a + b`. Maar omdat het een nieuwe regel betreft weet de engine niet wat we eigenlijk wilde retourneren. In plaats daarvan wordt er na `return` automatisch een puntkomma toegevoegd. Je kunt dit zien als: ```javascript -return; -a + b; + return; + a + b ``` Dat betekent dat `a + b` nooit bereikt zal worden, omdat de functie stopt na het keyword `return`. Als er geen waarde wordt geretourneerd, zoals nu, zal de functie `undefined` teruggeven. Let op dat er geen automatisch insertion plaatsvindt na `if/else` statements! @@ -3049,18 +3048,18 @@ Dat betekent dat `a + b` nooit bereikt zal worden, omdat de functie stopt na het ```javascript class Person { constructor() { - this.name = "Lydia"; + this.name = "Lydia" } } Person = class AnotherPerson { constructor() { - this.name = "Sarah"; + this.name = "Sarah" } -}; +} -const member = new Person(); -console.log(member.name); +const member = new Person() +console.log(member.name) ``` - A: `"Lydia"` @@ -3084,11 +3083,11 @@ We kunnen classes gelijk zetten tot andere classes/functie constructors. In dit ```javascript const info = { - [Symbol("a")]: "b", -}; + [Symbol('a')]: 'b' +} -console.log(info); -console.log(Object.keys(info)); +console.log(info) +console.log(Object.keys(info)) ``` - A: `{Symbol('a'): 'b'}` en `["{Symbol('a')"]` @@ -3135,13 +3134,13 @@ console.log(getUser(user)) De `getList` functie ontvangt een array als argument. Tussen de haakjes van de `getList` functie destructureren we deze array direct. Je kunt het zien als: -`[x, ...y] = [1, 2, 3, 4]` + `[x, ...y] = [1, 2, 3, 4]` Met de rest parameter `...y` stoppen we alle "overgebleven" argumenten in een array. De overgebleven argumenten zijn in dit geval `2`, `3` en `4`. De waarde van `y` is een array die alle rest parameters bevat. De waarde van `x` is gelijk aan `1` in dit geval, dus wanneer we `[x, y]` loggen wordt `[1, [2, 3, 4]]` gelogd. - + De `getUser` functie ontvangt een object. Met arrow functies _hoeven_ we geen accolades te gebruiken als we maar één waarde willen retourneren. Echter, als je een _object_ wilt retourneren in een arraow functie zal je het tussen haakjes moeten schrijven. Anders zal er geen waarde geretourneerd worden! De volgende functie zal wel een object geretourneerd hebben: -`const getUser = user => ({ name: user.name, age: user.age })` +```const getUser = user => ({ name: user.name, age: user.age })``` Omdat er geen waarde geretourneerd wordt in dit geval zal de functie `undefined` retourneren. @@ -3153,9 +3152,9 @@ Omdat er geen waarde geretourneerd wordt in dit geval zal de functie `undefined` ###### 99. Wat is de uitkomst? ```javascript -const name = "Lydia"; +const name = "Lydia" -console.log(name()); +console.log(name()) ``` - A: `SyntaxError` @@ -3185,8 +3184,8 @@ ReferenceErrors worden gegooid wanneer JavaScript niet in staat is een referenti ```javascript // 🎉✨ This is my 100th question! ✨🎉 -const output = `${[] && "Im"}possible! -You should${"" && `n't`} see a therapist after so much JavaScript lol`; +const output = `${[] && 'Im'}possible! +You should${'' && `n't`} see a therapist after so much JavaScript lol` ``` - A: `possible! You should see a therapist after so much JavaScript lol` @@ -3211,11 +3210,11 @@ You should${"" && `n't`} see a therapist after so much JavaScript lol`; ###### 101. Wat is de waarde van output? ```javascript -const one = false || {} || null; -const two = null || false || ""; -const three = [] || 0 || true; +const one = (false || {} || null) +const two = (null || false || "") +const three = ([] || 0 || true) -console.log(one, two, three); +console.log(one, two, three) ``` - A: `false` `null` `[]` @@ -3244,20 +3243,20 @@ Met de `||` (or) operator kunnen we de eerste truthy waarde retourneren. Als all ###### 102. Wat is de waarde van output? ```javascript -const myPromise = () => Promise.resolve("I have resolved!"); +const myPromise = () => Promise.resolve('I have resolved!') function firstFunction() { - myPromise().then((res) => console.log(res)); - console.log("second"); + myPromise().then(res => console.log(res)) + console.log('second') } async function secondFunction() { - console.log(await myPromise()); - console.log("second"); + console.log(await myPromise()) + console.log('second') } -firstFunction(); -secondFunction(); +firstFunction() +secondFunction() ``` - A: `I have resolved!`, `second` en `I have resolved!`, `second` @@ -3288,14 +3287,14 @@ Dit betekent dat het wacht tot de `myPromise` is opgelost met de waarde `I have ###### 103. Wat is de waarde van output? ```javascript -const set = new Set(); +const set = new Set() -set.add(1); -set.add("Lydia"); -set.add({ name: "Lydia" }); +set.add(1) +set.add("Lydia") +set.add({ name: "Lydia" }) for (let item of set) { - console.log(item + 2); + console.log(item + 2) } ``` @@ -3325,7 +3324,7 @@ Echter, de tweede is de string `"Lydia"`. `"Lydia"` is een string en `2` is een ###### 104. Wat is de waarde? ```javascript -Promise.resolve(5); +Promise.resolve(5) ``` - A: `5` @@ -3352,15 +3351,15 @@ In dit geval geven we alleen de numerieke waarde `5` mee. Het geeft de opgeloste ```javascript function compareMembers(person1, person2 = person) { if (person1 !== person2) { - console.log("Not the same!"); + console.log("Not the same!") } else { - console.log("They are the same!"); + console.log("They are the same!") } } -const person = { name: "Lydia" }; +const person = { name: "Lydia" } -compareMembers(person); +compareMembers(person) ``` - A: `Not the same!` @@ -3395,11 +3394,11 @@ const colorConfig = { green: true, black: true, yellow: false, -}; +} -const colors = ["pink", "red", "blue"]; +const colors = ["pink", "red", "blue"] -console.log(colorConfig.colors[1]); +console.log(colorConfig.colors[1]) ``` - A: `true` @@ -3426,7 +3425,7 @@ JavaScript interpreteert (of beter gezegd unboxed) statements. Wanneer we blokha ###### 107. Wat is de waarde? ```javascript -console.log("❤️" === "❤️"); +console.log('❤️' === '❤️') ``` - A: `true` @@ -3447,19 +3446,19 @@ Onder de motorkap zijn emojis unicodes. De unicodes voor het hart zijn `"U+2764 ###### 108. Welke van onderstaande methoden passen de originele array aan? ```javascript -const emojis = ["✨", "🥑", "😍"]; +const emojis = ['✨', '🥑', '😍'] -emojis.map((x) => x + "✨"); -emojis.filter((x) => x !== "🥑"); -emojis.find((x) => x !== "🥑"); -emojis.reduce((acc, cur) => acc + "✨"); -emojis.slice(1, 2, "✨"); -emojis.splice(1, 2, "✨"); +emojis.map(x => x + '✨') +emojis.filter(x => x !== '🥑') +emojis.find(x => x !== '🥑') +emojis.reduce((acc, cur) => acc + '✨') +emojis.slice(1, 2, '✨') +emojis.splice(1, 2, '✨') ``` - A: `All of them` - B: `map` `reduce` `slice` `splice` -- C: `map` `slice` `splice` +- C: `map` `slice` `splice` - D: `splice`
Antwoord @@ -3479,17 +3478,17 @@ Met de `splice` methode passen we de originele array aan door elementen te verwi ###### 109. Wat is de uitkomst? ```javascript -const food = ["🍕", "🍫", "🥑", "🍔"]; -const info = { favoriteFood: food[0] }; +const food = ['🍕', '🍫', '🥑', '🍔'] +const info = { favoriteFood: food[0] } -info.favoriteFood = "🍝"; +info.favoriteFood = '🍝' -console.log(food); +console.log(food) ``` - A: `['🍕', '🍫', '🥑', '🍔']` - B: `['🍝', '🍫', '🥑', '🍔']` -- C: `['🍝', '🍕', '🍫', '🥑', '🍔']` +- C: `['🍝', '🍕', '🍫', '🥑', '🍔']` - D: `ReferenceError`
Antwoord @@ -3511,7 +3510,7 @@ Daarna veranderen we de waarde van de property `favoriteFood` op het object `inf ###### 110. Wat doet onderstaande methode? ```javascript -JSON.parse(); +JSON.parse() ``` - A: Ontleedt JSON naar een JavaScript waarde @@ -3528,16 +3527,16 @@ Met de `JSON.parse()` methode kunnen we een JSON string parsen naar een JavaScri ```javascript // Stringifying een nummer naar valide JSON, daarna de JSON string parsen naar een JavaScript waarde: -const jsonNumber = JSON.stringify(4); // '4' -JSON.parse(jsonNumber); // 4 +const jsonNumber = JSON.stringify(4) // '4' +JSON.parse(jsonNumber) // 4 // Stringifying een array waarde naar een valide JSON, daarna de JSON string parsen naar een JavaScript waarde: -const jsonArray = JSON.stringify([1, 2, 3]); // '[1, 2, 3]' -JSON.parse(jsonArray); // [1, 2, 3] +const jsonArray = JSON.stringify([1, 2, 3]) // '[1, 2, 3]' +JSON.parse(jsonArray) // [1, 2, 3] // Stringifying een object naar valide JSON, daarna de JSON string parsen naar een JavaScript waarde: -const jsonArray = JSON.stringify({ name: "Lydia" }); // '{"name":"Lydia"}' -JSON.parse(jsonArray); // { name: 'Lydia' } +const jsonArray = JSON.stringify({ name: "Lydia" }) // '{"name":"Lydia"}' +JSON.parse(jsonArray) // { name: 'Lydia' } ```

@@ -3545,17 +3544,17 @@ JSON.parse(jsonArray); // { name: 'Lydia' } --- -###### 111. Wat is de uitkomst? +###### 111. Wat is de uitkomst? ```javascript -let name = "Lydia"; +let name = 'Lydia' function getName() { - console.log(name); - let name = "Sarah"; + console.log(name) + let name = 'Sarah' } -getName(); +getName() ``` - A: Lydia @@ -3575,13 +3574,13 @@ Variabelen gedeclareerd met het keyword `let` (en `const`) worden gehoisted, maa Als we de variabele `name` **niet** niet hadden gedeclareerd binnen de `getName` functie zou de JavaScript engine doorgezocht hebben door de _scope chain_. De bovenliggende scope heeft een variabele `name` met de waarde `Lydia`. In dat geval zou `Lydia` gelogged worden. ```javascript -let name = "Lydia"; +let name = 'Lydia' function getName() { - console.log(name); + console.log(name) } -getName(); // Lydia +getName() // Lydia ```

@@ -3593,18 +3592,18 @@ getName(); // Lydia ```javascript function* generatorOne() { - yield ["a", "b", "c"]; + yield ['a', 'b', 'c']; } function* generatorTwo() { - yield* ["a", "b", "c"]; + yield* ['a', 'b', 'c']; } -const one = generatorOne(); -const two = generatorTwo(); +const one = generatorOne() +const two = generatorTwo() -console.log(one.next().value); -console.log(two.next().value); +console.log(one.next().value) +console.log(two.next().value) ``` - A: `a` en `a` @@ -3622,17 +3621,17 @@ Met het keyword `yield` , we `yield` waarden in een generator functie. Met het k In `generatorOne` leveren we de volledige array `['a', 'b', 'c']` op, gebruikmakend van het keyword `yield`. De waarde van de propertie `value` op het object geretourneerd door de `next` methode op `one` (`one.next().value`) is gelijk aan de volledige array `['a', 'b', 'c']`. ```javascript -console.log(one.next().value); // ['a', 'b', 'c'] -console.log(one.next().value); // undefined +console.log(one.next().value) // ['a', 'b', 'c'] +console.log(one.next().value) // undefined ``` In `generatorTwo` gebruiken we het keyword `yield*`. Dit betekent dat de eerste opgeleverde waarde van `two` is gelijk aan de eerste opgeleverde waarde in de iterator. The iterator is de array `['a', 'b', 'c']`. De eerste opgeleverde waarde is `a`, dus de eerste keer dat we `two.next().value` aanroepen wordt `a` geretourneerd. ```javascript -console.log(two.next().value); // 'a' -console.log(two.next().value); // 'b' -console.log(two.next().value); // 'c' -console.log(two.next().value); // undefined +console.log(two.next().value) // 'a' +console.log(two.next().value) // 'b' +console.log(two.next().value) // 'c' +console.log(two.next().value) // undefined ```

@@ -3643,7 +3642,7 @@ console.log(two.next().value); // undefined ###### 113. Wat is de uitkomst? ```javascript -console.log(`${((x) => x)("I love")} to program`); +console.log(`${(x => x)('I love')} to program`) ``` - A: `I love to program` @@ -3668,11 +3667,11 @@ Expressies binnen template literals worden eerste geëvalueerd. Dit betekent dat ```javascript let config = { alert: setInterval(() => { - console.log("Alert!"); - }, 1000), -}; + console.log('Alert!') + }, 1000) +} -config = null; +config = null ``` - A: De `setInterval` callback zal niet worden aangeroepen @@ -3695,17 +3694,17 @@ Normaal als we objecten gelijk maken aan `null` worden deze objecten opgeruimd d ###### 115. Welke methode(n) zal de waarde `'Hello world!'` teruggeven? ```javascript -const myMap = new Map(); -const myFunc = () => "greeting"; +const myMap = new Map() +const myFunc = () => 'greeting' -myMap.set(myFunc, "Hello world!"); +myMap.set(myFunc, 'Hello world!') //1 -myMap.get("greeting"); +myMap.get('greeting') //2 -myMap.get(myFunc); +myMap.get(myFunc) //3 -myMap.get(() => "greeting"); +myMap.get(() => 'greeting') ``` - A: 1 @@ -3733,19 +3732,19 @@ Als een **key/value** paar wordt toegevoegd gebruikmakend van de `set` methode z ```javascript const person = { name: "Lydia", - age: 21, -}; + age: 21 +} -const changeAge = (x = { ...person }) => (x.age += 1); +const changeAge = (x = { ...person }) => x.age += 1 const changeAgeAndName = (x = { ...person }) => { - x.age += 1; - x.name = "Sarah"; -}; + x.age += 1 + x.name = "Sarah" +} -changeAge(person); -changeAgeAndName(); +changeAge(person) +changeAgeAndName() -console.log(person); +console.log(person) ``` - A: `{name: "Sarah", age: 22}` @@ -3773,7 +3772,7 @@ Dan roepen we de functie `changeAgeAndName` aan, echter geven we geen parameter ```javascript function sumValues(x, y, z) { - return x + y + z; + return x + y + z; } ``` @@ -3824,15 +3823,15 @@ Met de `+=` operator verhogen we de waarde van `num` met `1`. `num` heeft een in ```javascript const person = { - firstName: "Lydia", - lastName: "Hallie", - pet: { - name: "Mara", - breed: "Dutch Tulip Hound", - }, - getFullName() { - return `${this.firstName} ${this.lastName}`; - }, + firstName: "Lydia", + lastName: "Hallie", + pet: { + name: "Mara", + breed: "Dutch Tulip Hound" + }, + getFullName() { + return `${this.firstName} ${this.lastName}`; + } }; console.log(person.pet?.name); @@ -3855,7 +3854,7 @@ Met de _optional chaining operator_ `?.` hoeven we niet langer expliciet te chec `person.pet?.name`: `person` heeft een propertie genaamd `pet`: `person.pet` is niet _nullish_. Het heeft een propertie genaamd ``name` en retourneerd `Mara`. `person.pet?.family?.name`: `person` heeft een propertie genaamd `pet`: `person.pet` is niet _nullish_. `pet` heeft _geen_ propertie genaamd `family`, `person.pet.family` is _nullish_. De expressie geeft `undefined` terug. -`person.getFullName?.()`: `person` heeft een propertie genaamd `getFullName`: `person.getFullName()` is niet **nullish** en kan worden aangeroepen, wat `Lydia Hallie` retourneerd. +`person.getFullName?.()`: `person` heeft een propertie genaamd `getFullName`: `person.getFullName()` is niet __nullish__ en kan worden aangeroepen, wat `Lydia Hallie` retourneerd. `member.getLastName?.()`: `member` is niet gedefinieerd: `member.getLastName()` is _nullish_. The expressie geeft `undefined` terug.

@@ -3869,9 +3868,9 @@ Met de _optional chaining operator_ `?.` hoeven we niet langer expliciet te chec const groceries = ["banana", "apple", "peanuts"]; if (groceries.indexOf("banana")) { - console.log("We have to buy bananas!"); + console.log("We have to buy bananas!"); } else { - console.log(`We don't have to buy bananas!`); + console.log(`We don't have to buy bananas!`); } ``` @@ -3896,10 +3895,10 @@ We geven de conditie `groceries.indexOf("banana")` mee aan de if-statement. `gro ```javascript const config = { - languages: [], - set language(lang) { - return this.languages.push(lang); - }, + languages: [], + set language(lang) { + return this.languages.push(lang); + } }; console.log(config.language); @@ -3953,9 +3952,9 @@ console.log(!typeof name === "string"); ###### 123. Wat is de uitkomst? ```javascript -const add = (x) => (y) => (z) => { - console.log(x, y, z); - return x + y + z; +const add = x => y => z => { + console.log(x, y, z); + return x + y + z; }; add(4)(5)(6); @@ -3982,16 +3981,16 @@ De `add` functie retourneert een arrow functie, die een arrow functie retourneer ```javascript async function* range(start, end) { - for (let i = start; i <= end; i++) { - yield Promise.resolve(i); - } + for (let i = start; i <= end; i++) { + yield Promise.resolve(i); + } } (async () => { - const gen = range(1, 3); - for await (const item of gen) { - console.log(item); - } + const gen = range(1, 3); + for await (const item of gen) { + console.log(item); + } })(); ``` @@ -4016,7 +4015,7 @@ De generator functie `range` retourneert een async object met promises voor elk ```javascript const myFunc = ({ x, y, z }) => { - console.log(x, y, z); + console.log(x, y, z); }; myFunc(1, 2, 3); @@ -4140,8 +4139,8 @@ Met de `isNaN` methode kun je checken of een waarde die je meegeeft geen numerie const randomValue = 21; function getInfo() { - console.log(typeof randomValue); - const randomValue = "Lydia Hallie"; + console.log(typeof randomValue); + const randomValue = "Lydia Hallie"; } getInfo(); @@ -4170,13 +4169,13 @@ Variables declared with the `const` keyword are not referencable before their in const myPromise = Promise.resolve("Woah some cool data"); (async () => { - try { - console.log(await myPromise); - } catch { - throw new Error(`Oops didn't work`); - } finally { - console.log("Oh finally!"); - } + try { + console.log(await myPromise); + } catch { + throw new Error(`Oops didn't work`); + } finally { + console.log("Oh finally!"); + } })(); ``` @@ -4226,13 +4225,13 @@ Met de `flat` methode kunnen we een nieuwe platgemaakte array maken. De diepte v ```javascript class Counter { - constructor() { - this.count = 0; - } + constructor() { + this.count = 0; + } - increment() { - this.count++; - } + increment() { + this.count++; + } } const counterOne = new Counter(); @@ -4276,16 +4275,16 @@ We roepen `counterTwo.increment()` aan, wat `count` gelijk maakt aan `3`. Als we const myPromise = Promise.resolve(Promise.resolve("Promise!")); function funcOne() { - myPromise.then((res) => res).then((res) => console.log(res)); - setTimeout(() => console.log("Timeout!", 0)); - console.log("Last line!"); + myPromise.then(res => res).then(res => console.log(res)); + setTimeout(() => console.log("Timeout!", 0)); + console.log("Last line!"); } async function funcTwo() { - const res = await myPromise; - console.log(await res); - setTimeout(() => console.log("Timeout!", 0)); - console.log("Last line!"); + const res = await myPromise; + console.log(await res); + setTimeout(() => console.log("Timeout!", 0)); + console.log("Last line!"); } funcOne(); @@ -4302,7 +4301,7 @@ funcTwo(); #### Antwoord: D -Eerst roepen we `funcOne` aan. Op de eerste regel van `funcOne` roepen we de promise `myPromise` aan, wat een _asynchrone_ operatie is. Zolang de JavaScript engine bezig is met het afmaken van de promise wordt de rest van de functie `funcOne` uitgevoerd. De volgende regel is een _asynchrone_ `setTimeout` functie, waarvan de callback functie naar de Web API wordt gestuurd. +Eerst roepen we `funcOne` aan. Op de eerste regel van `funcOne` roepen we de promise `myPromise` aan, wat een _asynchrone_ operatie is. Zolang de JavaScript engine bezig is met het afmaken van de promise wordt de rest van de functie `funcOne` uitgevoerd. De volgende regel is een _asynchrone_ `setTimeout` functie, waarvan de callback functie naar de Web API wordt gestuurd. Zowel de promise als de timeout zijn _asynchrone_ operaties en de functie worden uitgevoerd terwijl de engine bezig is om de promise uit te voeren en de `setTimeout` callback functie af te handelen. Dit betekent dat `Last line!` als eerste wordt gelogd, omdat dit geen _asynchrone_ operatie is. Dit is de laatste regel van `funcOne`. Ondertussen wordt de promise opgelost en `Promise!` wordt gelogd. Echter, omdat we `funcTwo()` aanroepen en de callstack nog niet leeg is kan de callback van de `setTimeout` functie nog niet toegevoegd worden aan de callstack. @@ -4317,12 +4316,12 @@ We komen op de laatste regel van `funcTwo` wat `Last line!` logt naar het consol --- -###### 134. Hoe kunnen we `sum` uit `sum.js` aanroepen in `index.js`?` +###### 134. Hoe kunnen we `sum` uit `sum.js` aanroepen in `index.js`?` ```javascript // sum.js export default function sum(x) { - return x + x; + return x + x; } // index.js @@ -4379,8 +4378,8 @@ We kunnen deze functie aanvoeren door `sum.default` aan te roepen. ```javascript const handler = { - set: () => console.log("Added a new property!"), - get: () => console.log("Accessed a property!"), + set: () => console.log("Added a new property!"), + get: () => console.log("Accessed a property!") }; const person = new Proxy({}, handler); @@ -4430,7 +4429,7 @@ Object.seal(person); #### Antwoord: A -Met `Object.seal` kunnen we voorkomen dat nieuwe properties kunnen worden _toegevoegd_ of bestaande properties worden _verwijderd_. +Met `Object.seal` kunnen we voorkomen dat nieuwe properties kunnen worden _toegevoegd_ of bestaande properties worden _verwijderd_. Echter kunnen van de bestaande properties nog steeds aanpassen. @@ -4443,10 +4442,10 @@ Echter kunnen van de bestaande properties nog steeds aanpassen. ```javascript const person = { - name: "Lydia Hallie", - address: { - street: "100 Main St", - }, + name: "Lydia Hallie", + address: { + street: "100 Main St" + } }; Object.freeze(person); @@ -4474,10 +4473,10 @@ Echter wordt het object enkel _oppervlakkig_ bevroren wat betekent dat alleen _d ###### 138. Wat is de uitkomst? ```javascript -const add = (x) => x + x; +const add = x => x + x; function myFunc(num = 2, value = add(num)) { - console.log(num, value); + console.log(num, value); } myFunc(); @@ -4507,21 +4506,21 @@ Daarna roepen we de functie `myFunc(3)` aan het geven `3` meet als de waarde voo ```javascript class Counter { - #number = 10; + #number = 10 increment() { - this.#number++; + this.#number++ } getNum() { - return this.#number; + return this.#number } } -const counter = new Counter(); -counter.increment(); +const counter = new Counter() +counter.increment() -console.log(counter.#number); +console.log(counter.#number) ``` - A: `10` @@ -4545,20 +4544,20 @@ In ES2020 kunnen we private variabelen toevoegen aan classes door gebruik te mak ```javascript const teams = [ - { name: "Team 1", members: ["Paul", "Lisa"] }, - { name: "Team 2", members: ["Laura", "Tim"] }, + { name: "Team 1", members: ["Paul", "Lisa"] }, + { name: "Team 2", members: ["Laura", "Tim"] } ]; function* getMembers(members) { - for (let i = 0; i < members.length; i++) { - yield members[i]; - } + for (let i = 0; i < members.length; i++) { + yield members[i]; + } } function* getTeams(teams) { - for (let i = 0; i < teams.length; i++) { - // ✨ SOMETHING IS MISSING HERE ✨ - } + for (let i = 0; i < teams.length; i++) { + // ✨ SOMETHING IS MISSING HERE ✨ + } } const obj = getTeams(teams); @@ -4589,13 +4588,13 @@ Als we `yield`, `return yield`, of `return` hadden geschreven zou de gehele gene ```javascript const person = { - name: "Lydia Hallie", - hobbies: ["coding"], + name: "Lydia Hallie", + hobbies: ["coding"] }; function addHobby(hobby, hobbies = person.hobbies) { - hobbies.push(hobby); - return hobbies; + hobbies.push(hobby); + return hobbies; } addHobby("running", []); @@ -4634,16 +4633,16 @@ Na het pushen van `dancing` en `baking` is de waarde van `person.hobbies` gelijk ```javascript class Bird { - constructor() { - console.log("I'm a bird. 🦢"); - } + constructor() { + console.log("I'm a bird. 🦢"); + } } class Flamingo extends Bird { - constructor() { - console.log("I'm pink. 🌸"); - super(); - } + constructor() { + console.log("I'm pink. 🌸"); + super(); + } } const pet = new Flamingo(); diff --git a/pl-PL/README.md b/pl-PL/README.md index ca8e1a3b..866f4458 100644 --- a/pl-PL/README.md +++ b/pl-PL/README.md @@ -10,11 +10,10 @@ Od podstawowych do zaawansowanych: sprawdź, jak dobrze znasz JavaScript, odświ Nie krępuj się ze mną kontaktować! 😊
Instagram || Twitter || LinkedIn || Blog - -| Śmiało używaj ich w projekcie! 😃 Byłabym _bardzo_ wdzięczna za referencje do tego repozytorium, tworzę pytania i wyjaśnienia (tak, jestem smutna lol) i społeczność bardzo mi pomaga w utrzymaniu i ulepszaniu go! 💪🏼 Dziękuję i baw się dobrze! | -| ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| Śmiało używaj ich w projekcie! 😃 Byłabym _bardzo_ wdzięczna za referencje do tego repozytorium, tworzę pytania i wyjaśnienia (tak, jestem smutna lol) i społeczność bardzo mi pomaga w utrzymaniu i ulepszaniu go! 💪🏼 Dziękuję i baw się dobrze! | +|---| --- @@ -33,7 +32,6 @@ Nie krępuj się ze mną kontaktować! 😊
- [🇰🇷 한국어](./ko-KR/README-ko_KR.md) - [🇳🇱 Nederlands](./nl-NL/README.md) - [🇧🇷 Português Brasil](./pt-BR/README_pt_BR.md) -- [🇷o Română](../ro-RO/README.ro.md) - [🇷🇺 Русский](./ru-RU/README.md) - [🇽🇰 Shqip](../sq-KS/README_sq_KS.md) - [🇹🇭 ไทย](./th-TH/README-th_TH.md) @@ -54,7 +52,7 @@ Nie krępuj się ze mną kontaktować! 😊
function sayHi() { console.log(name); console.log(age); - var name = "Lydia"; + var name = 'Lydia'; let age = 21; } @@ -150,7 +148,7 @@ Na tym obiekcie nie ma wartości `radius`, co powoduje zwrócenie `NaN` (Not a N ```javascript +true; -!"Lydia"; +!'Lydia'; ``` - A: `1` and `false` @@ -175,11 +173,11 @@ Operator jednoargumentowy plus próbuje przekonwertować operand na liczbę. `tr ```javascript const bird = { - size: "small", + size: 'small', }; const mouse = { - name: "Mickey", + name: 'Mickey', small: true, }; ``` @@ -210,11 +208,11 @@ Jednakże, w przypadku notacji kropkowej, to się nie dzieje. `mouse` nie ma klu ###### 6. Jaki jest wynik? ```javascript -let c = { greeting: "Hey!" }; +let c = { greeting: 'Hey!' }; let d; d = c; -c.greeting = "Hello"; +c.greeting = 'Hello'; console.log(d.greeting); ``` @@ -284,13 +282,13 @@ class Chameleon { return this.newColor; } - constructor({ newColor = "green" } = {}) { + constructor({ newColor = 'green' } = {}) { this.newColor = newColor; } } -const freddie = new Chameleon({ newColor: "purple" }); -console.log(freddie.colorChange("orange")); +const freddie = new Chameleon({ newColor: 'purple' }); +console.log(freddie.colorChange('orange')); ``` - A: `orange` @@ -345,10 +343,10 @@ Aby temu zapobiec, możemy użyć `"use strict"`. Powoduje to, że musisz zadekl ```javascript function bark() { - console.log("Woof!"); + console.log('Woof!'); } -bark.animal = "dog"; +bark.animal = 'dog'; ``` - A: Nothing, this is totally fine! @@ -378,8 +376,8 @@ function Person(firstName, lastName) { this.lastName = lastName; } -const member = new Person("Lydia", "Hallie"); -Person.getFullName = function () { +const member = new Person('Lydia', 'Hallie'); +Person.getFullName = function() { return `${this.firstName} ${this.lastName}`; }; @@ -401,7 +399,7 @@ W JavaScript funkcje są obiektami, więc metoda `getFullName` jest dodawana do Jeśli chcesz, aby metoda była dostępna dla wszystkich instancji obiektów, musisz dodać ją do właściwości prototype: ```js -Person.prototype.getFullName = function () { +Person.prototype.getFullName = function() { return `${this.firstName} ${this.lastName}`; }; ``` @@ -419,8 +417,8 @@ function Person(firstName, lastName) { this.lastName = lastName; } -const lydia = new Person("Lydia", "Hallie"); -const sarah = Person("Sarah", "Smith"); +const lydia = new Person('Lydia', 'Hallie'); +const sarah = Person('Sarah', 'Smith'); console.log(lydia); console.log(sarah); @@ -490,7 +488,7 @@ function sum(a, b) { return a + b; } -sum(1, "2"); +sum(1, '2'); ``` - A: `NaN` @@ -536,7 +534,7 @@ Operator jednoargumentowy **Postfix** `++`: 1. Zwraca wartość (ten zwraca `0`) 2. Zwiększa wartość (liczba wynosi teraz `1`) -Operator jednoargumentowy **Prefix** `++`: +Operator jednoargumentowy **Prefix** `++`: 1. Zwiększa wartość (liczba wynosi teraz `2`) 2. Zwraca wartość (to zwraca `2`) @@ -557,7 +555,7 @@ function getPersonInfo(one, two, three) { console.log(three); } -const person = "Lydia"; +const person = 'Lydia'; const age = 21; getPersonInfo`${person} is ${age} years old`; @@ -584,9 +582,9 @@ W przypadku użycia `template strings`, wartością pierwszego argumentu jest za ```javascript function checkAge(data) { if (data === { age: 18 }) { - console.log("You are an adult!"); + console.log('You are an adult!'); } else if (data == { age: 18 }) { - console.log("You are still an adult."); + console.log('You are still an adult.'); } else { console.log(`Hmm.. You don't have an age I guess`); } @@ -646,7 +644,7 @@ Parametr reszty (`...args`) pozwala nam "zbierać" wszystkie pozostałe argument ```javascript function getAge() { - "use strict"; + 'use strict'; age = 21; console.log(age); } @@ -674,7 +672,7 @@ Dzięki `"use strict"` możesz upewnić się, że przypadkowo nie zadeklarujesz ###### 21. Jaka jest wartość `sum`? ```javascript -const sum = eval("10*10+5"); +const sum = eval('10*10+5'); ``` - A: `105` @@ -697,7 +695,7 @@ const sum = eval("10*10+5"); ###### 22. Jak długo cool_secret jest dostępny? ```javascript -sessionStorage.setItem("cool_secret", 123); +sessionStorage.setItem('cool_secret', 123); ``` - A: Dane nigdy nie zostaną utracone. @@ -750,12 +748,12 @@ Nie można tego zrobić za pomocą `let` lub `const`, ponieważ są one blokowe. ###### 24. Jaki jest wynik? ```javascript -const obj = { 1: "a", 2: "b", 3: "c" }; +const obj = { 1: 'a', 2: 'b', 3: 'c' }; const set = new Set([1, 2, 3, 4, 5]); -obj.hasOwnProperty("1"); +obj.hasOwnProperty('1'); obj.hasOwnProperty(1); -set.has("1"); +set.has('1'); set.has(1); ``` @@ -781,7 +779,7 @@ Nie działa to w ten sam sposób dla zbioru. W zbiorze nie ma klucza `'1'`:`set. ###### 25. Jaki jest wynik? ```javascript -const obj = { a: "one", b: "two", a: "three" }; +const obj = { a: 'one', b: 'two', a: 'three' }; console.log(obj); ``` @@ -850,12 +848,12 @@ Instrukcja `continue` pomija iterację, jeśli określony warunek zwróci `true` ```javascript String.prototype.giveLydiaPizza = () => { - return "Just give Lydia pizza already!"; + return 'Just give Lydia pizza already!'; }; -const name = "Lydia"; +const name = 'Lydia'; -console.log(name.giveLydiaPizza()); +console.log(name.giveLydiaPizza()) ``` - A: `"Just give Lydia pizza already!"` @@ -879,8 +877,8 @@ console.log(name.giveLydiaPizza()); ```javascript const a = {}; -const b = { key: "b" }; -const c = { key: "c" }; +const b = { key: 'b' }; +const c = { key: 'c' }; a[b] = 123; a[c] = 456; @@ -912,9 +910,9 @@ Następnie wyświetlamy w konsoli `a[b]`, co w rzeczywistości jest `a["[obiekt ###### 30. Jaki jest wynik? ```javascript -const foo = () => console.log("First"); -const bar = () => setTimeout(() => console.log("Second")); -const baz = () => console.log("Third"); +const foo = () => console.log('First'); +const bar = () => setTimeout(() => console.log('Second')); +const baz = () => console.log('Third'); bar(); foo(); @@ -967,7 +965,9 @@ W tym miejscu zaczyna działać pętla zdarzeń. **Pętla zdarzeń** patrzy na s ```html
- +
``` @@ -993,7 +993,9 @@ Najgłębiej zagnieżdżony element, który spowodował zdarzenie jest celem zda ```html
-

Click here!

+

+ Click here! +

``` @@ -1017,7 +1019,7 @@ Jeśli klikniemy `p`, zobaczymy dwa logi: `p` i `div`. Podczas propagacji zdarze ###### 33. Jaki jest wynik? ```javascript -const person = { name: "Lydia" }; +const person = { name: 'Lydia' }; function sayHi(age) { return `${this.name} is ${age}`; @@ -1067,6 +1069,7 @@ console.log(typeof sayHi()); #### Odpowiedź: B Funkcja `sayHi` zwraca zwróconą wartość natychmiast wywołanego wyrażenia funkcyjnego (IIFE). Ta funkcja zwróciła wartość `0`, która jest typu `"number"`. + FYI: `typeof` może zwrócić następującą listę wartości: `undefined`, `boolean`, `number`, `bigint`, `string`, `symbol`, `function` i `object`. Zauważ, że `typeof null` zwraca `"object"`.

@@ -1079,8 +1082,8 @@ FYI: `typeof` może zwrócić następującą listę wartości: `undefined`, `boo ```javascript 0; new Number(0); -(""); -(" "); +(''); +(' '); new Boolean(false); undefined; ``` @@ -1229,14 +1232,11 @@ To, co odróżnia prymityw od obiektu, to fakt, że prymitywy nie mają żadnych ###### 40. Jaki jest wynik? ```javascript -[ - [0, 1], - [2, 3], -].reduce( +[[0, 1], [2, 3]].reduce( (acc, cur) => { return acc.concat(cur); }, - [1, 2] + [1, 2], ); ``` @@ -1263,7 +1263,7 @@ Następnie `[1, 2, 0, 1]` to `acc`, a `[2, 3]` to `cur`. Łączymy je i otrzymuj ```javascript !!null; -!!""; +!!''; !!1; ``` @@ -1291,7 +1291,7 @@ Następnie `[1, 2, 0, 1]` to `acc`, a `[2, 3]` to `cur`. Łączymy je i otrzymuj ###### 42. Co zwraca metoda `setInterval` w przeglądarce? ```javascript -setInterval(() => console.log("Hi"), 1000); +setInterval(() => console.log('Hi'), 1000); ``` - A: unikalny identyfikator @@ -1314,7 +1314,7 @@ Zwraca unikalny identyfikator. Ten identyfikator może być użyty do wyczyszcze ###### 43. Co to zwróci? ```javascript -[..."Lydia"]; +[...'Lydia']; ``` - A: `["L", "y", "d", "i", "a"]` @@ -1373,14 +1373,14 @@ Następnie ponownie wywołujemy funkcję za pomocą metody `next()`. Kontynuuje ```javascript const firstPromise = new Promise((res, rej) => { - setTimeout(res, 500, "one"); + setTimeout(res, 500, 'one'); }); const secondPromise = new Promise((res, rej) => { - setTimeout(res, 100, "two"); + setTimeout(res, 100, 'two'); }); -Promise.race([firstPromise, secondPromise]).then((res) => console.log(res)); +Promise.race([firstPromise, secondPromise]).then(res => console.log(res)); ``` - A: `"one"` @@ -1403,7 +1403,7 @@ Kiedy przekazujemy wiele 'promise' do metody `Promise.race`, rozwiązuje ona/odr ###### 46. Jaki jest wynik? ```javascript -let person = { name: "Lydia" }; +let person = { name: 'Lydia' }; const members = [person]; person = null; @@ -1443,7 +1443,7 @@ Modyfikujemy tylko wartość zmiennej `person`, a nie pierwszy element w tablicy ```javascript const person = { - name: "Lydia", + name: 'Lydia', age: 21, }; @@ -1472,7 +1472,7 @@ Za pomocą pętli `for-in` możemy iterować po kluczach obiektów, w tym przypa ###### 48. Jaki jest wynik? ```javascript -console.log(3 + 4 + "5"); +console.log(3 + 4 + '5'); ``` - A: `"345"` @@ -1499,7 +1499,7 @@ Asocjatywność operatorów to kolejność, w jakiej kompilator ocenia wyrażeni ###### 49. Jaka jest wartość `num`? ```javascript -const num = parseInt("7*6", 10); +const num = parseInt('7*6', 10); ``` - A: `42` @@ -1524,8 +1524,8 @@ Zwracana jest tylko pierwsza liczba w łańcuchu. W oparciu o _radix_ (drugi arg ###### 50. Jaki jest wynik? ```javascript -[1, 2, 3].map((num) => { - if (typeof num === "number") return; +[1, 2, 3].map(num => { + if (typeof num === 'number') return; return num * 2; }); ``` @@ -1545,4 +1545,4 @@ Podczas mapowania tablicy, wartość `num` jest równa elementowi, nad którym a Nie zwracamy jednak żadnej wartości. Gdy nie zwracamy wartości z funkcji, funkcja zwraca `undefined`. Dla każdego elementu w tablicy wywoływany jest blok funkcji, więc dla każdego elementu zwracamy `undefined`.

-
+
\ No newline at end of file diff --git a/pt-BR/README_pt_BR.md b/pt-BR/README_pt_BR.md index a0a0a211..e59c6a6f 100644 --- a/pt-BR/README_pt_BR.md +++ b/pt-BR/README_pt_BR.md @@ -19,7 +19,6 @@ As respostas estão em seções recolhidas abaixo das questões, basta clicar ne - [🇰🇷 한국어](../ko-KR/README-ko_KR.md) - [🇳🇱 Nederlands](../nl-NL/README.md) - [🇵🇱 Polski](../pl-PL/README.md) -- [🇷o Română](../ro-RO/README.ro.md) - [🇷🇺 Русский](../ru-RU/README.md) - [🇽🇰 Shqip](../sq-KS/README_sq_KS.md) - [🇹🇭 ไทย](../th-TH/README-th_TH.md) @@ -29,6 +28,7 @@ As respostas estão em seções recolhidas abaixo das questões, basta clicar ne - [🇨🇳 简体中文](../zh-CN/README-zh_CN.md) - [🇹🇼 繁體中文](../zh-TW/README_zh-TW.md) + --- ###### 1. Qual o resultado? @@ -101,7 +101,7 @@ const shape = { diameter() { return this.radius * 2; }, - perimeter: () => 2 * Math.PI * this.radius, + perimeter: () => 2 * Math.PI * this.radius }; shape.diameter(); @@ -147,9 +147,8 @@ Não há `radius` fora de shape, então retorna `undefined`. O operador unário `+` tenta converter um operando para um número. `true` é `1`, e `false` é `0`. -A string `'Lydia'` tem valor truthy\*. O que estamos realmente perguntando é "Esse valor truthy é falsy?". Isso retorna `false`. - -###### \*Nota do tradutor: truthy é um termo único ao JavaScript que denota valores que podem ser convertidos em um booleano `True`. Sua contraparte é falsy, que são valores que podem ser convertidos em um booleano `false`. Para fins de consistência, mantenho os termos originais. +A string `'Lydia'` tem valor truthy*. O que estamos realmente perguntando é "Esse valor truthy é falsy?". Isso retorna `false`. +###### *Nota do tradutor: truthy é um termo único ao JavaScript que denota valores que podem ser convertidos em um booleano `True`. Sua contraparte é falsy, que são valores que podem ser convertidos em um booleano `false`. Para fins de consistência, mantenho os termos originais.

@@ -160,12 +159,12 @@ A string `'Lydia'` tem valor truthy\*. O que estamos realmente perguntando é "E ```javascript const bird = { - size: "small", + size: "small" }; const mouse = { name: "Mickey", - small: true, + small: true }; ``` @@ -251,7 +250,7 @@ console.log(b === c); `new Number()` é uma funcção construtura padrão do JavaScript. Ainda que parece com um número, não é realmente um número: Tem um monte de funções extras e é um objeto. -Quando usamos o operador `==`, só conferimos se ambas tem o mesmo valor. Ambas tem o valor de `3`, então retorna `true`. +Quando usamos o operador `==`, só conferimos se ambas tem o mesmo valor. Ambas tem o valor de `3`, então retorna `true`. Contudo, quando usamos o operador `===`, ambos valor e tipo tem de ser o mesmo. E não são: `new Number()` não é um número, é um **objeto**. Ambos retornam `false`. @@ -315,7 +314,7 @@ console.log(greetign); Cria o log do objeto, pois criamos um objeto vazio no objeto global! Quando erramos a digitação de `greeting` como `greetign`, o interpretador do JavaScript viu isso como `global.greetign = {}` (ou `window.greetign = {}` em um navegador). -Para evitar esse comportamento, podemos usar `"use strict"`. Isso garante que você tenha declarado uma variável antes de poder inicializá-la com algum valor. +Para evitar esse comportamento, podemos usar `"use strict"`. Isso garante que você tenha declarado uma variável antes de poder inicializá-la com algum valor.

@@ -360,7 +359,7 @@ function Person(firstName, lastName) { } const member = new Person("Lydia", "Hallie"); -Person.getFullName = function () { +Person.getFullName = function() { return `${this.firstName} ${this.lastName}`; }; @@ -382,7 +381,7 @@ Você não pode adicionar propriedades para um construtor igual aos objetos norm Então nesse caso ```js -Person.prototype.getFullName = function () { +Person.prototype.getFullName = function() { return `${this.firstName} ${this.lastName}`; }; ``` @@ -441,8 +440,7 @@ Afirmamos que `this.firstName` vale `"Sarah"` e `this.lastName` vale `"Smith"`. #### Resposta: D Durate a fase do **capturing**, o evento percorre os elementos pais até chegar no elemento algo. Isso alcança o elemento **target**, e o **bubbling** começa. - -##### \*Nota do tradutor: _bubbling_ descreve uma forma específica de propagação de eventos. Em tradução livre é "borbulhar", que indica como os eventos "sobem" a cadeia onde estão aninhados, mas prefiro por manter o original, visto que é o nome dessa forma de propagação. + ##### *Nota do tradutor: _bubbling_ descreve uma forma específica de propagação de eventos. Em tradução livre é "borbulhar", que indica como os eventos "sobem" a cadeia onde estão aninhados, mas prefiro por manter o original, visto que é o nome dessa forma de propagação. @@ -461,7 +459,7 @@ Durate a fase do **capturing**, o evento percorre os elementos pais até chegar #### Resposta: B -Todos objetos tem protótipos, exceto pelo **base object**. O base object tem acesso à alguns métodos e propriedades, como `.toString`. É o motivo de podermos usar métodos já embutidos no JavaScript! Todos métodos desse tipo já estão embutidos no protótipo. Apesar do JavaScript não encontrar algum método diretamente no seu objeto, ele percorre a cadeia de protótipos até encontrar no base, o que torna acessível para todo objeto. +Todos objetos tem protótipos, exceto pelo **base object**. O base object tem acesso à alguns métodos e propriedades, como `.toString`. É o motivo de podermos usar métodos já embutidos no JavaScript! Todos métodos desse tipo já estão embutidos no protótipo. Apesar do JavaScript não encontrar algum método diretamente no seu objeto, ele percorre a cadeia de protótipos até encontrar no base, o que torna acessível para todo objeto.

@@ -516,7 +514,7 @@ console.log(number); #### Resposta: C -O operador unário no **sufixo** `++`: +O operador unário no **sufixo** `++`: 1. Retorna o valor (retorna o valor `0`) 2. Incrementa o valor (numero agora é `1`) @@ -589,7 +587,7 @@ checkAge({ age: 18 }); #### Resposta: C -Quando testamos igualdade, primitivos são comparados por seus _valores_, enquanto objetos são comparados por suas _referências_. O JavaScript confere se os objetos tem a referência para o mesmo local na memória. +Quando testamos igualdade, primitivos são comparados por seus _valores_, enquanto objetos são comparados por suas _referências_. O JavaScript confere se os objetos tem a referência para o mesmo local na memória. Os dois objetos que estamos comparando não são assim: O objeto que passamos como parâmetro faz referência a uma posição na memória diferente daquela que o objeto que usamos para conferir a igualdade. @@ -790,7 +788,7 @@ Se temos duas chaves com o mesmo nome, a última irá substituir a primeira. Ain ###### 26. O contexto global de execução do JavaScript cria duas coisas para você: O objeto global, e a palavra-chave `this`. - A: Verdadeiro -- B: Falso +- B: Falso - C: Depende
Resposta @@ -840,7 +838,7 @@ String.prototype.giveLydiaPizza = () => { const name = "Lydia"; -console.log(name.giveLydiaPizza()); +console.log(name.giveLydiaPizza()) ``` - A: `"Just give Lydia pizza already!"` @@ -952,7 +950,9 @@ A `WebAPI` não pode simplesmente adicionar coisas ao stack sempre que ficam pro ```html
- +
``` @@ -967,7 +967,7 @@ A `WebAPI` não pode simplesmente adicionar coisas ao stack sempre que ficam pro #### Resposta: C -O elemento mais interno no aninhamento que causou o evento é o alvo do evento. Você pode parar o _bubbling_ com `event.stopPropagation`. +O elemento mais interno no aninhamento que causou o evento é o alvo do evento. Você pode parar o _bubbling_ com `event.stopPropagation`.

@@ -978,7 +978,9 @@ O elemento mais interno no aninhamento que causou o evento é o alvo do evento. ```html
-

Click here!

+

+ Click here! +

``` @@ -1053,7 +1055,7 @@ typeof sayHi(); A função `sayHi` retorna o valor retornado pela arrow function pois ela é uma IIFE (Immediately Invoked Function Expression ou Expressão de Função Invocada Imediatamente). Essa IIFE retornou `0`, que é do tipo `"number"`. -Para saber mais: Só existem 7 tipos já definidos: `null`, `undefined`, `boolean`, `number`, `string`, `object`, `symbol`, e `bigint`. `"function"` não é um tipo, uma vez que funções são objetos, elas são do tipo `"object"`. +Para saber mais: Só existem 7 tipos já definidos: `null`, `undefined`, `boolean`, `number`, `string`, `object`, `symbol`, e `bigint`. `"function"` não é um tipo, uma vez que funções são objetos, elas são do tipo `"object"`.

@@ -1213,10 +1215,7 @@ O que diferencia um primitivo de um objeto é que primitivos não possuem métod ###### 40. Qual o resultado? ```javascript -[ - [0, 1], - [2, 3], -].reduce( +[[0, 1], [2, 3]].reduce( (acc, cur) => { return acc.concat(cur); }, @@ -1279,7 +1278,7 @@ setInterval(() => console.log("Hi"), 1000); ``` - A: um id único -- B: a quantidade de millisegundos especificada +- B: a quantidade de millisegundos especificada - C: a função passada - D: `undefined` @@ -1363,7 +1362,7 @@ const secondPromise = new Promise((res, rej) => { setTimeout(res, 100, "two"); }); -Promise.race([firstPromise, secondPromise]).then((res) => console.log(res)); +Promise.race([firstPromise, secondPromise]).then(res => console.log(res)); ``` - A: `"one"` @@ -1427,7 +1426,7 @@ Estamos apenas modificando o valor da variável `person`, e não o primeiro elem ```javascript const person = { name: "Lydia", - age: 21, + age: 21 }; for (const item in person) { @@ -1507,7 +1506,7 @@ Apenas os primeiros números da string é retornado. Baseado no _radix_ (o segun ###### 50. Qual o resultado? ```javascript -[1, 2, 3].map((num) => { +[1, 2, 3].map(num => { if (typeof num === "number") return; return num * 2; }); @@ -1676,7 +1675,7 @@ class Dog { this.name = name; } } -Dog.prototype.bark = function () { +Dog.prototype.bark = function() { console.log(`Woof I am ${this.name}`); }; const pet = new Dog("Mara"); @@ -1851,6 +1850,7 @@ console.log(admin); #### Resposta: B + É possível combinar objetos usando o operador o spread operator `...`. Ele permite criar cópias dos pares de um objeto e adicioná-las a outro objeto. Nesse caso, criamos cópias do objeto `user` e as adicionamos ao objeto `admin`. O objeto `admin` agora contém os pares de chave/valor copiados, o que resulta em `{ admin: true, name: "Lydia", age: 21 }`.

@@ -1878,12 +1878,10 @@ console.log(Object.keys(person));

#### Resposta: B +Com o método `defineProperty`, podemos adicionar novas propriedades a um objeto ou modificar propriedades já existentes. Quando adicionamos uma propriedade a um objeto usando o método `defineProperty`, ela é, por padrão, _não enumerável_. O método`Object.keys` retorna todos os nomes de uma propriedade _enumerável_ de um objeto. Nesse caso, apenas `"name"`. -Com o método `defineProperty`, podemos adicionar novas propriedades a um objeto ou modificar propriedades já existentes. Quando adicionamos uma propriedade a um objeto usando o método `defineProperty`, ela é, por padrão, _não enumerável_. O método`Object.keys` retorna todos os nomes de uma propriedade _enumerável_ de um objeto. Nesse caso, apenas `"name"`. - -Propriedades adicionadas usando o método `defineProperty` são imutáveis por padrão. Você pode sobrepor esse comportamento usando as propriedade `writable`, `configurable` e `enumerable`. +Propriedades adicionadas usando o método `defineProperty` são imutáveis por padrão. Você pode sobrepor esse comportamento usando as propriedade `writable`, `configurable` e `enumerable`. Assim, o método `defineProperty` dá a você muito mais controle sobre as propriedades que você está adicionando a um objeto. -

@@ -1895,7 +1893,7 @@ Assim, o método `defineProperty` dá a você muito mais controle sobre as propr const settings = { username: "lydiahallie", level: 19, - health: 90, + health: 90 }; const data = JSON.stringify(settings, ["level", "health"]); @@ -1917,19 +1915,17 @@ O segundo argumento de `JSON.stringify` é o _substituo_. O substituto pode ser Se o substituto (replacer) for um _array_, apenas os nomes de propriedades incluídos no array serão adicionados à string JSON. Nesse caso, apenas as propriedades com os nomes `"level"` ed `"health"` são incluída, `"username"` é excluída. `data` agora é igual a `"{"level":19, "health":90}"`. Se o substituto (replacer) for uma _função_, essa função é chamada em c ada propriedade no objeto que está sendo "Stringfied". O valor retornado dessa função será o valor da propriedade quanto adicionado à string JSON. Se o valor for `undefined`, essa propriedade é excluída da string JSON. -

--- - ###### 63. Qual o resultado? ```javascript let num = 10; const increaseNumber = () => num++; -const increasePassedNumber = (number) => number++; +const increasePassedNumber = number => number++; const num1 = increaseNumber(); const num2 = increasePassedNumber(num1); @@ -1956,7 +1952,6 @@ O operador unário `++` primeiro _retorna_ o valor do operando, depois _incremen --- - ###### 64. Qual o resultado? ```javascript @@ -1994,7 +1989,6 @@ Na quarta vez, passamos o objeto `value` novamente. `x.number` foi modificado an --- - ###### 65. Qual o resultado? ```javascript @@ -2080,17 +2074,16 @@ A classe `Labrador` recebe dois argumentos, `name`, pois estende `Dog`, e `size` --- - ###### 67. Qual o resultado? ```javascript // index.js -console.log("running index.js"); -import { sum } from "./sum.js"; +console.log('running index.js'); +import { sum } from './sum.js'; console.log(sum(1, 2)); // sum.js -console.log("running sum.js"); +console.log('running sum.js'); export const sum = (a, b) => a + b; ``` @@ -2112,13 +2105,12 @@ Esta é uma diferença entre `require()` no CommonJS e `import`! Com `require()` --- - ###### 68. Qual o resultado? ```javascript console.log(Number(2) === Number(2)); console.log(Boolean(false) === Boolean(false)); -console.log(Symbol("foo") === Symbol("foo")); +console.log(Symbol('foo') === Symbol('foo')); ``` - A: `true`, `true`, `false` @@ -2137,11 +2129,10 @@ Todo símbolo (Symbol) é totalmente único. O objetivo do argumento passado ao --- - ###### 69. Qual o resultado? ```javascript -const name = "Lydia Hallie"; +const name = 'Lydia Hallie'; console.log(name.padStart(13)); console.log(name.padStart(2)); ``` @@ -2164,11 +2155,10 @@ Se o argumento passado para o método `padStart` for menor que o comprimento da --- - ###### 70. Qual o resultado? ```javascript -console.log("🥑" + "💻"); +console.log('🥑' + '💻'); ``` - A: `"🥑💻"` @@ -2192,11 +2182,11 @@ Com o operador `+`, você pode concatenar seqüências de caracteres (strings). ```javascript function* iniciarJogo() { - const resposta = yield "Você ama JavaScript?"; - if (resposta !== "Sim") { + const resposta = yield 'Você ama JavaScript?'; + if (resposta !== 'Sim') { return "Uau... Acho que entramos aqui"; } - return "O JavaScript também ama você ❤️"; + return 'O JavaScript também ama você ❤️'; } const jogo = iniciarJogo(); @@ -2259,12 +2249,11 @@ Neste caso, a string é `Hello\nworld`, que é registrada. --- - ###### 73. Qual o resultado? ```javascript async function getData() { - return await Promise.resolve("I made it!"); + return await Promise.resolve('I made it!'); } const data = getData(); @@ -2293,7 +2282,6 @@ Isso teria registrado `"Consegui!"` --- - ###### 74. Qual o resultado? ```javascript @@ -2301,7 +2289,7 @@ function addToList(item, list) { return list.push(item); } -const result = addToList("apple", ["banana"]); +const result = addToList('apple', ['banana']); console.log(result); ``` @@ -2361,7 +2349,7 @@ Como `shape` está congelado, e como o valor de `x` não é um objeto, não pode ###### 76.Qual o resultado? ```javascript -const { name: myName } = { name: "Lydia" }; +const { name: myName } = { name: 'Lydia' }; console.log(name); ``` @@ -2417,7 +2405,7 @@ A função `sum` sempre retorna o mesmo resultado. Se passarmos `1` e` 2`, ele _ ```javascript const add = () => { const cache = {}; - return (num) => { + return num => { if (num in cache) { return `From cache! ${cache[num]}`; } else { @@ -2448,7 +2436,7 @@ A função `add` é uma função _memoized_ (memorizada). Com a memorização, p Se chamarmos a função `addFunction` novamente com o mesmo argumento, ela primeiro verifica se já obteve esse valor em seu cache. Se for o caso, o valor dos caches será retornado, o que economiza tempo de execução. Caso contrário, se não estiver armazenado em cache, ele calculará o valor e o armazenará posteriormente. -Chamamos a função `addFunction` três vezes com o mesmo valor: na primeira chamada, o valor da função quando `num` é igual a `10` ainda não é armazenado em cache. A condição da instrução if `num in cache` retorna `false`, e o bloco else é executado: `Calculated! 20` é registrado e o valor do resultado é adicionado ao objeto de cache. `cache` agora se parece com`{10:20}`. +Chamamos a função `addFunction` três vezes com o mesmo valor: na primeira chamada, o valor da função quando `num` é igual a `10` ainda não é armazenado em cache. A condição da instrução if `num in cache` retorna `false`, e o bloco else é executado: `Calculated! 20` é registrado e o valor do resultado é adicionado ao objeto de cache. `cache` agora se parece com` {10:20} `. Na segunda vez, o objeto `cache` contém o valor que é retornado para `10`. A condição da instrução if `num in cache` retorna `true`, e `'From cache! 20'` é registrado. @@ -2462,7 +2450,7 @@ Na terceira vez, passamos `5 * 2` para a função que é avaliada como `10`. O o ###### 79. Qual o resultado? ```javascript -const myLifeSummedUp = ["☕", "💻", "🍷", "🍫"]; +const myLifeSummedUp = ['☕', '💻', '🍷', '🍫']; for (let item in myLifeSummedUp) { console.log(item); @@ -2487,7 +2475,7 @@ Com um loop _for-in_, podemos iterar sobre propriedades **enumeráveis​​**. `{0:" ☕ ", 1:" 💻 ", 2:" 🍷 ", 3:" 🍫 "}` -Onde as chaves são as propriedades enumeráveis. ` 0`` 1 ` ` 2`` 3 ` são registrados. +Onde as chaves são as propriedades enumeráveis. `0`` 1` `2`` 3` são registrados. Com um loop _for-of_, podemos iterar sobre **iteráveis**. Um array é um iterável. Quando iteramos sobre o array, a variável "item" é igual ao elemento sobre o qual está iterando no momento, `" ☕ "` `" 💻 "` `" 🍷 "` `" 🍫 "` são registrados. @@ -2520,4 +2508,4 @@ O elemento será igual ao valor retornado. `1 + 2` retorna` 3`, `1 * 2` retorna`

---- +--- \ No newline at end of file diff --git a/ro-RO/README.ro.md b/ro-RO/README.ro.md deleted file mode 100644 index 5c36813e..00000000 --- a/ro-RO/README.ro.md +++ /dev/null @@ -1,371 +0,0 @@ -
- -

Întrebări JavaScript

- ---- - -Postez întrebări JavaScript cu opțiuni multiple pe [Instagram](https://www.instagram.com/theavocoder) **stories**, pe care le voi posta și aici! Ultima actualizare: 12 Iunie - -De la nivel de bază la avansat: testează cât de bine cunoști JavaScript, reîmprospătează-ți puțin cunoștințele sau pregătește-te pentru interviul tău de codare! :muscle: :rocket: Actualizez acest depozit în mod regulat cu întrebări noi. Am adăugat răspunsurile în **secțiunile restrânse** de sub întrebări, pur și simplu dă clic pe ele pentru a le extinde. Este doar pentru distracție, mult noroc! :heart: - -Nu ezita să mă contactezi! 😊
-Instagram || Twitter || LinkedIn || Blog - -
- -| Simte-te liber să le folosești într-un proiect! 😃 Aș aprecia _cu adevărat_ o referință la acest depozit, eu creez întrebările și explicațiile (da, sunt tristă lol) și comunitatea mă ajută foarte mult să îl mențin și să îl îmbunătățesc! 💪🏼 Mulțumesc și distracție plăcută! | -| -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | - ---- - -
Vezi 20 de traduceri disponibile 🇸🇦🇪🇬🇧🇦🇩🇪🇪🇸🇫🇷🇮🇩🇯🇵🇰🇷🇳🇱🇧🇷🇷🇺🇹🇭🇹🇷🇺🇦🇻🇳🇨🇳🇹🇼🇽🇰 -

- -- [🇸🇦 العربية](./ar-AR/README_AR.md) -- [🇪🇬 اللغة العامية](./ar-EG/README_ar-EG.md) -- [🇧🇦 Bosanski](./bs-BS/README-bs_BS.md) -- [🇩🇪 Deutsch](./de-DE/README.md) -- [🇪🇸 Español](./es-ES/README-ES.md) -- [🇫🇷 Français](./fr-FR/README_fr-FR.md) -- [🇮🇩 Indonesia](./id-ID/README.md) -- [🇮🇹 Italiano](./it-IT/README.md) -- [🇯🇵 日本語](./ja-JA/README-ja_JA.md) -- [🇰🇷 한국어](./ko-KR/README-ko_KR.md) -- [🇳🇱 Nederlands](./nl-NL/README.md) -- [🇵🇱 Polski](./pl-PL/README.md) -- [🇧🇷 Português Brasil](./pt-BR/README_pt_BR.md) -- [🇷🇺 Русский](./ru-RU/README.md) -- [🇽🇰 Shqip](./sq-KS/README_sq_KS.md) -- [🇹🇭 ไทย](./th-TH/README-th_TH.md) -- [🇹🇷 Türkçe](./tr-TR/README-tr_TR.md) -- [🇺🇦 Українська мова](./uk-UA/README.md) -- [🇻🇳 Tiếng Việt](./vi-VI/README-vi.md) -- [🇨🇳 简体中文](./zh-CN/README-zh_CN.md) -- [🇹🇼 繁體中文](./zh-TW/README_zh-TW.md) - -

-
- ---- - -###### 1. Care este rezultatul? - -```javascript -function sayHi() { - console.log(name); - console.log(age); - var name = "Lydia"; - let age = 21; -} - -sayHi(); -``` - -- A: `Lydia` și `undefined` -- B: `Lydia` și `ReferenceError` -- C: `ReferenceError` și `21` -- D: `undefined` și `ReferenceError` - -
Răspuns -

- -#### Răspuns: D - -În interiorul funcției, mai întâi declarăm variabila `name` cu cuvântul cheie `var`. Acest lucru înseamnă că variabila este hoisted (spațiul de memorie este configurat în faza de creare) cu valoarea implicită `undefined`, până când ajungem efectiv la linia în care definim variabila. Nu am definit încă variabila pe linia în care încercăm să înregistrăm variabila `name`, așa că aceasta păstrează încă valoarea `undefined`. - -Variabilele create cu cuvântul cheie `let` (și `const`) sunt hoisted, dar, spre deosebire de `var`, nu sunt inițializate. Acestea nu sunt accesibile înainte de linia în care le declarăm (initializăm). Aceasta se numește zona moartă temporală (temporal dead zone). Atunci când încercăm să accesăm variabilele înainte de a fi declarate, JavaScript aruncă o excepție de tip `ReferenceError`. - -

-
- ---- - -###### 2. Care este rezultatul? - -```javascript -for (var i = 0; i < 3; i++) { - setTimeout(() => console.log(i), 1); -} - -for (let i = 0; i < 3; i++) { - setTimeout(() => console.log(i), 1); -} -``` - -- A: `0 1 2` și `0 1 2` -- B: `0 1 2` și `3 3 3` -- C: `3 3 3` și `0 1 2` - -
Răspuns -

- -#### Răspuns: C - -Datorită cozii de evenimente din JavaScript, funcția de callback `setTimeout` este apelată _după_ ce bucla a fost executată. Deoarece variabila `i` din prima buclă a fost declarată folosind cuvântul cheie `var`, această valoare a fost globală. În timpul buclei, am incrementat valoarea lui `i` cu `1` de fiecare dată, folosind operatorul unary `++`. Până când funcția de callback `setTimeout` a fost invocată, `i` era egal cu `3` în primul exemplu. - -În cea de-a doua buclă, variabila `i` a fost declarată folosind cuvântul cheie `let`: variabilele declarate cu cuvântul cheie `let` (și `const`) sunt cu scop la nivel de bloc (un bloc este orice între `{ }`). În fiecare iterație, `i` va avea o valoare nouă, iar fiecare valoare este în cadrul buclei. - -

-
- ---- - -###### 3. Care este rezultatul? - -```javascript -const shape = { - radius: 10, - diameter() { - return this.radius * 2; - }, - perimeter: () => 2 * Math.PI * this.radius, -}; - -console.log(shape.diameter()); -console.log(shape.perimeter()); -``` - -- A: `20` și `62.83185307179586` -- B: `20` și `NaN` -- C: `20` și `63` -- D: `NaN` și `63` - -
Răspuns -

- -#### Răspuns: B - -Rețineți că valoarea lui `diameter` este o funcție obișnuită, în timp ce valoarea lui `perimeter` este o funcție arrow. - -Cu funcțiile arrow, cuvântul cheie `this` se referă la contextul său curent de încadrare, spre deosebire de funcțiile obișnuite! Acest lucru înseamnă că atunci când apelăm `perimeter`, acesta nu se referă la obiectul formei, ci la încadrarea sa curentă (de exemplu, fereastra). - -Nu există nicio valoare `radius` pe acel obiect, ceea ce returnează `NaN`. - -

-
- ---- - -###### 4. Care este rezultatul? - -```javascript -+true; -!"Lydia"; -``` - -- A: `1` și `false` -- B: `false` și `NaN` -- C: `false` și `false` - -
Răspuns -

- -#### Răspuns: A - -Operatorul unary plus încearcă să convertească un operand într-un număr. `true` este `1`, și `false` este `0`. - -Șirul de caractere `'Lydia'` este o valoare adevărată. Ceea ce întrebăm de fapt, este "este această valoare adevărată falsă?". Acest lucru returnează `false`. - -

-
- ---- - -###### 5. Care este rezultatul? - -```javascript -const bird = { - size: "small", -}; - -const mouse = { - name: "Mickey", - small: true, -}; -``` - -- A: `mouse.bird.size` nu este valid -- B: `mouse[bird.size]` nu este valid -- C: `mouse[bird["size"]]` nu este valid -- D: Toate sunt valide - -
Răspuns -

- -#### Răspuns: A - -În JavaScript, toate cheile obiectelor sunt șiruri de caractere (cu excepția simbolurilor). Chiar dacă nu le _tipizăm_ ca șiruri de caractere, ele sunt întotdeauna convertite în șiruri de caractere în fundal. - -avaScript interpretează (sau dezambalează) instrucțiunile. Atunci când folosim notația cu paranteze pătrate, vede prima paranteză pătrată de deschidere `[` și continuă până când găsește paranteza pătrată de închidere `]`. Doar atunci va evalua instrucțiunea. - -`mouse[bird.size]`: Întâi evaluează `bird.size`, care este `"small"`. `mouse["small"]` returnează `true` - -Cu toate acestea, cu notația cu punct, acest lucru nu se întâmplă. `mouse` nu are o cheie numită `bird`, ceea ce înseamnă că `mouse.bird` este `undefined`. Apoi, cerem `size` folosind notația cu punct: `mouse.bird.size`. Deoarece `mouse.bird` este `undefined`, de fapt cerem `undefined.size`. Acest lucru nu este valid și va arunca o eroare similară cu `Cannot read property "size" of undefined` (Nu se poate citi proprietatea "size" a unei valori nedefinite). - -

-
- ---- - -###### 6. Care este rezultatul? - -```javascript -let c = { greeting: "Hey!" }; -let d; - -d = c; -c.greeting = "Hello"; -console.log(d.greeting); -``` - -- A: `Hello` -- B: `Hey!` -- C: `undefined` -- D: `ReferenceError` -- E: `TypeError` - -
Răspuns -

- -#### Răspuns: A - -În JavaScript, toate obiectele interacționează prin _referință_ atunci când sunt setate ca egale între ele. - -Mai întâi, variabila `c` deține o valoare care face referire la un obiect. Ulterior, atribuim variabilei `d` aceeași referință pe care o are `c` la obiect. - - - -Când modifici un obiect, le modifici pe toate. - -

-
- ---- - -###### 7. Care este rezultatul? - -```javascript -let a = 3; -let b = new Number(3); -let c = 3; - -console.log(a == b); -console.log(a === b); -console.log(b === c); -``` - -- A: `true` `false` `true` -- B: `false` `false` `true` -- C: `true` `false` `false` -- D: `false` `true` `true` - -
Răspuns -

- -#### Răspuns: C - -`new Number()` este un constructor de funcții încorporat. Deși arată ca un număr, nu este într-adevăr un număr: are o mulțime de funcționalități suplimentare și este un obiect. - -Atunci când folosim operatorul `==` (operatorul de egalitate), acesta verifică doar dacă au aceeași _valuare_. Ambele au valoarea `3`, șa că returnează `true`. - -Cu toate acestea, atunci când folosim operatorul `===` (operatorul de egalitate strictă), atât valoarea, cât _și_ tipul trebuie să fie la fel. Nu sunt: `new Number()` nu este un număr, este un **object**. Ambele returnează `false.` - -

-
- ---- - -###### 8. Care este rezultatul? - -```javascript -class Chameleon { - static colorChange(newColor) { - this.newColor = newColor; - return this.newColor; - } - - constructor({ newColor = "green" } = {}) { - this.newColor = newColor; - } -} - -const freddie = new Chameleon({ newColor: "purple" }); -console.log(freddie.colorChange("orange")); -``` - -- A: `orange` -- B: `purple` -- C: `green` -- D: `TypeError` - -
Răspuns -

- -#### Răspuns: D - -Funcția `colorChange` este statică. Metodele statice sunt concepute să existe doar pe constructorul în care sunt create și nu pot fi transmise către niciun copil sau apelate pe instanțele clasei. Deoarece `freddie` este o instanță a clasei Chameleon, funcția nu poate fi apelată pe aceasta. Se aruncă o eroare de tip `TypeError`. - -

-
- ---- - -###### 9. Care este rezultatul? - -```javascript -let greeting; -greetign = {}; // Typo! -console.log(greetign); -``` - -- A: `{}` -- B: `ReferenceError: greetign is not defined` -- C: `undefined` - -
Răspuns -

- -#### Răspuns: A - -Se afișează obiectul, deoarece tocmai am creat un obiect gol pe obiectul global! Atunci când am greșit și am scris `greeting` în loc de `greetign`, interpretorul JavaScript a văzut efectiv acest lucru ca: - -1. `global.greetign = {}` în Node.js -2. `window.greetign = {}`, `frames.greetign = {}` și `self.greetign` în browser-e. -3. `self.greetign` în web workers. -4. `globalThis.greetign` în toate mediile. - -Pentru a evita acest lucru, putem folosi `"use strict"`. Acest lucru se asigură că ai declarat o variabilă înainte de a-i atribui o valoare. - -

-
- ---- - -###### 10. Ce se întâmplă când facem asta? - -```javascript -function bark() { - console.log("Woof!"); -} - -bark.animal = "dog"; -``` - -- A: Nimic, este absolut în regulă! -- B: `SyntaxError`. Nu poți adăuga proprietăți la o funcție în acest fel. -- C: `"Woof"` este înregistrat. -- D: `ReferenceError` - -
Răspuns -

- -#### Răspuns: A - -Acest lucru este posibil în JavaScript, deoarece funcțiile sunt obiecte! (Totul, în afară de tipurile primitive, sunt obiecte) - -O funcție este un tip special de obiect. Codul pe care îl scrii tu însuți nu este funcția efectivă. Funcția este un obiect cu proprietăți. Această proprietate este invocabilă. - -

-
- ---- diff --git a/ru-RU/README.md b/ru-RU/README.md index 35f9e86f..17a083ab 100644 --- a/ru-RU/README.md +++ b/ru-RU/README.md @@ -10,11 +10,10 @@ Не стесняйтесь обращаться ко мне (Lydia Hallie)! 😊
Instagram || Twitter || LinkedIn || Blog - | Не стесняйтесь использовать эти примеры в проектах! 😃 Я (Lydia Hallie) была бы _действительно_ признателена за ссылку на этот репозиторий. Я добавляю вопросы и объяснения, и сообщество очень помогает мне поддерживать и улучшать все это! 💪🏼 Спасибо и приятного просмотра! | -| ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +|---| --- @@ -34,7 +33,6 @@ - [🇳🇱 Nederlands](../nl-NL/README.md) - [🇵🇱 Polski](../pl-PL/README.md) - [🇧🇷 Português Brasil](../pt-BR/README_pt_BR.md) -- [🇷o Română](../ro-RO/README.ro.md) - [🇬🇧 English](../README.md) - [🇽🇰 Shqip](../sq-KS/README_sq_KS.md) - [🇹🇭 ไทย](../th-TH/README-th_TH.md) @@ -119,7 +117,7 @@ const shape = { diameter() { return this.radius * 2; }, - perimeter: () => 2 * Math.PI * this.radius, + perimeter: () => 2 * Math.PI * this.radius }; console.log(shape.diameter()); @@ -151,7 +149,7 @@ console.log(shape.perimeter()); ```javascript +true; -!"Lydia"; +!'Lydia'; ``` - A: `1` и `false` @@ -176,12 +174,12 @@ console.log(shape.perimeter()); ```javascript const bird = { - size: "small", + size: 'small' }; const mouse = { - name: "Mickey", - small: true, + name: 'Mickey', + small: true }; ``` @@ -211,11 +209,11 @@ JavaScript интерпретирует (или распаковывает) оп ###### 6. Что будет в консоли? ```javascript -let c = { greeting: "Hey!" }; +let c = { greeting: 'Hey!' }; let d; d = c; -c.greeting = "Hello"; +c.greeting = 'Hello'; console.log(d.greeting); ``` @@ -285,13 +283,13 @@ class Chameleon { return this.newColor; } - constructor({ newColor = "green" } = {}) { + constructor({ newColor = 'green' } = {}) { this.newColor = newColor; } } -const freddie = new Chameleon({ newColor: "purple" }); -freddie.colorChange("orange"); +const freddie = new Chameleon({ newColor: 'purple' }); +freddie.colorChange('orange'); ``` - A: `orange` @@ -346,10 +344,10 @@ console.log(greetign); ```javascript function bark() { - console.log("Woof!"); + console.log('Woof!'); } -bark.animal = "dog"; +bark.animal = 'dog'; ``` - A: Ничего, всё в порядке! @@ -379,10 +377,10 @@ function Person(firstName, lastName) { this.lastName = lastName; } -const member = new Person("Lydia", "Hallie"); +const member = new Person('Lydia', 'Hallie'); Person.getFullName = function () { return `${this.firstName} ${this.lastName}`; -}; +} console.log(member.getFullName()); ``` @@ -404,7 +402,7 @@ console.log(member.getFullName()); ```js Person.prototype.getFullName = function () { return `${this.firstName} ${this.lastName}`; -}; +} ```

@@ -420,8 +418,8 @@ function Person(firstName, lastName) { this.lastName = lastName; } -const lydia = new Person("Lydia", "Hallie"); -const sarah = Person("Sarah", "Smith"); +const lydia = new Person('Lydia', 'Hallie'); +const sarah = Person('Sarah', 'Smith'); console.log(lydia); console.log(sarah); @@ -491,7 +489,7 @@ function sum(a, b) { return a + b; } -sum(1, "2"); +sum(1, '2'); ``` - A: `NaN` @@ -558,7 +556,7 @@ function getPersonInfo(one, two, three) { console.log(three); } -const person = "Lydia"; +const person = 'Lydia'; const age = 21; getPersonInfo`${person} is ${age} years old`; @@ -585,9 +583,9 @@ getPersonInfo`${person} is ${age} years old`; ```javascript function checkAge(data) { if (data === { age: 18 }) { - console.log("Ты взрослый!"); + console.log('Ты взрослый!'); } else if (data == { age: 18 }) { - console.log("Ты все еще взрослый."); + console.log('Ты все еще взрослый.'); } else { console.log(`Хмм.. Кажется, у тебя нет возраста.`); } @@ -647,7 +645,7 @@ getAge(21); ```javascript function getAge() { - "use strict"; + 'use strict'; age = 21; console.log(age); } @@ -675,7 +673,7 @@ getAge(); ###### 21. Чему будет равно `sum`? ```javascript -const sum = eval("10*10+5"); +const sum = eval('10*10+5'); ``` - A: `105` @@ -698,7 +696,7 @@ const sum = eval("10*10+5"); ###### 22. Как долго будет доступен cool_secret? ```javascript -sessionStorage.setItem("cool_secret", 123); +sessionStorage.setItem('cool_secret', 123); ``` - A: Всегда, данные не потеряются. @@ -751,12 +749,12 @@ console.log(num); ###### 24. Каким будет результат? ```javascript -const obj = { 1: "a", 2: "b", 3: "c" }; +const obj = { 1: 'a', 2: 'b', 3: 'c' }; const set = new Set([1, 2, 3, 4, 5]); -obj.hasOwnProperty("1"); +obj.hasOwnProperty('1'); obj.hasOwnProperty(1); -set.has("1"); +set.has('1'); set.has(1); ``` @@ -782,7 +780,7 @@ set.has(1); ###### 25. Что будет в консоли? ```javascript -const obj = { a: "one", b: "two", a: "three" }; +const obj = { a: 'one', b: 'two', a: 'three' }; console.log(obj); ``` @@ -851,12 +849,12 @@ for (let i = 1; i < 5; i++) { ```javascript String.prototype.giveLydiaPizza = () => { - return "Just give Lydia pizza already!"; + return 'Just give Lydia pizza already!'; }; -const name = "Lydia"; +const name = 'Lydia'; -console.log(name.giveLydiaPizza()); +console.log(name.giveLydiaPizza()) ``` - A: `"Just give Lydia pizza already!"` @@ -880,8 +878,8 @@ console.log(name.giveLydiaPizza()); ```javascript const a = {}; -const b = { key: "b" }; -const c = { key: "c" }; +const b = { key: 'b' }; +const c = { key: 'c' }; a[b] = 123; a[c] = 456; @@ -913,9 +911,9 @@ console.log(a[b]); ###### 30. Каким будет результат? ```javascript -const foo = () => console.log("First"); -const bar = () => setTimeout(() => console.log("Second")); -const baz = () => console.log("Third"); +const foo = () => console.log('First'); +const bar = () => setTimeout(() => console.log('Second')); +const baz = () => console.log('Third'); bar(); foo(); @@ -968,7 +966,9 @@ WebAPI не может добавлять содержимое в стек ко ```html
- +
``` @@ -994,7 +994,9 @@ WebAPI не может добавлять содержимое в стек ко ```html
-

Кликни меня!

+

+ Кликни меня! +

``` @@ -1018,7 +1020,7 @@ WebAPI не может добавлять содержимое в стек ко ###### 33. Что будет в консоли? ```javascript -const person = { name: "Lydia" }; +const person = { name: 'Lydia' }; function sayHi(age) { console.log(`${this.name} is ${age}`); @@ -1231,10 +1233,7 @@ console.log(numbers); ###### 40. Каким будет результат? ```javascript -[ - [0, 1], - [2, 3], -].reduce( +[[0, 1], [2, 3]].reduce( (acc, cur) => { return acc.concat(cur); }, @@ -1265,7 +1264,7 @@ console.log(numbers); ```javascript !!null; -!!""; +!!''; !!1; ``` @@ -1293,7 +1292,7 @@ console.log(numbers); ###### 42. Что возвращает метод `setInterval` в браузере? ```javascript -setInterval(() => console.log("Hi"), 1000); +setInterval(() => console.log('Hi'), 1000); ``` - A: уникальный id @@ -1316,7 +1315,7 @@ setInterval(() => console.log("Hi"), 1000); ###### 43. Каким будет результат? ```javascript -[..."Lydia"]; +[...'Lydia']; ``` - A: `["L", "y", "d", "i", "a"]` @@ -1375,14 +1374,14 @@ console.log(gen.next().value); ```javascript const firstPromise = new Promise((res, rej) => { - setTimeout(res, 500, "один"); + setTimeout(res, 500, 'один'); }); const secondPromise = new Promise((res, rej) => { - setTimeout(res, 100, "два"); + setTimeout(res, 100, 'два'); }); -Promise.race([firstPromise, secondPromise]).then((res) => console.log(res)); +Promise.race([firstPromise, secondPromise]).then(res => console.log(res)); ``` - A: `"один"` @@ -1405,7 +1404,7 @@ Promise.race([firstPromise, secondPromise]).then((res) => console.log(res)); ###### 46. Каким будет результат? ```javascript -let person = { name: "Lydia" }; +let person = { name: 'Lydia' }; const members = [person]; person = null; @@ -1445,8 +1444,8 @@ console.log(members); ```javascript const person = { - name: "Lydia", - age: 21, + name: 'Lydia', + age: 21 }; for (const item in person) { @@ -1474,7 +1473,7 @@ for (const item in person) { ###### 48. Каким будет результат? ```javascript -console.log(3 + 4 + "5"); +console.log(3 + 4 + '5'); ``` - A: `"345"` @@ -1526,8 +1525,8 @@ const num = parseInt("7*6", 10); ###### 50. Каким будет результат? ```javascript -[1, 2, 3].map((num) => { - if (typeof num === "number") return; +[1, 2, 3].map(num => { + if (typeof num === 'number') return; return num * 2; }); ``` @@ -1555,12 +1554,12 @@ const num = parseInt("7*6", 10); ```javascript function getInfo(member, year) { - member.name = "Lydia"; + member.name = 'Lydia'; year = 1998; } -const person = { name: "Sarah" }; -const birthYear = "1997"; +const person = { name: 'Sarah' }; +const birthYear = '1997'; getInfo(person, birthYear); @@ -1579,7 +1578,7 @@ console.log(person, birthYear); Аргументы передаются _значением_, если их значение не является объектом, то они передаются _ссылкой_. `birthYear` передается по значению, поскольку это строка, а не объект. Когда мы передаем аргументы по значению, создается _копия_ этого значения (см. вопрос 46). -Переменная `birthYear` имеет ссылку на значение `"1997"`. Аргумент `year` также имеет ссылку на значение`"1997"`, но это не то же самое значение, на которое имеется ссылка для `birthYear`. Когда мы обновляем значение `year`, устанавливая `year` равным `"1998"`, мы обновляем только значение `year`. `birthYear` по-прежнему равно `"1997"`. +Переменная `birthYear` имеет ссылку на значение `"1997"`. Аргумент `year` также имеет ссылку на значение` "1997" `, но это не то же самое значение, на которое имеется ссылка для `birthYear`. Когда мы обновляем значение `year`, устанавливая `year` равным `"1998"`, мы обновляем только значение `year`. `birthYear` по-прежнему равно `"1997"`. Значение `person` является объектом. Аргумент `member` имеет (скопированную) ссылку на _тот же_ объект. Когда мы изменяем свойство объекта, на который `member` ссылается, значение `person` также будет изменено, поскольку они оба имеют ссылку на один и тот же объект. Свойство `name` объекта `person` теперь равно значению `"Lydia"`. @@ -1592,15 +1591,15 @@ console.log(person, birthYear); ```javascript function greeting() { - throw "Hello world!"; + throw 'Hello world!'; } function sayHi() { try { const data = greeting(); - console.log("It worked!", data); + console.log('It worked!', data); } catch (e) { - console.log("Oh no an error:", e); + console.log('Oh no an error:', e); } } @@ -1630,8 +1629,8 @@ sayHi(); ```javascript function Car() { - this.make = "Lamborghini"; - return { make: "Maserati" }; + this.make = 'Lamborghini'; + return { make: 'Maserati' }; } const myCar = new Car(); @@ -1703,11 +1702,11 @@ class Dog { } } -Dog.prototype.bark = function () { +Dog.prototype.bark = function() { console.log(`Woof I am ${this.name}`); }; -const pet = new Dog("Mara"); +const pet = new Dog('Mara'); pet.bark(); @@ -1772,7 +1771,7 @@ export default counter; ```javascript // index.js -import myCounter from "./counter"; +import myCounter from './counter'; myCounter += 1; @@ -1801,7 +1800,7 @@ console.log(myCounter); ###### 58. Какой будет вывод? ```javascript -const name = "Lydia"; +const name = 'Lydia'; age = 21; console.log(delete name); @@ -1872,7 +1871,7 @@ console.log(y); ###### 60. Какой будет вывод? ```javascript -const user = { name: "Lydia", age: 21 }; +const user = { name: 'Lydia', age: 21 }; const admin = { admin: true, ...user }; console.log(admin); @@ -1898,9 +1897,9 @@ console.log(admin); ###### 61. Какой будет вывод? ```javascript -const person = { name: "Lydia" }; +const person = { name: 'Lydia' }; -Object.defineProperty(person, "age", { value: 21 }); +Object.defineProperty(person, 'age', { value: 21 }); console.log(person); console.log(Object.keys(person)); @@ -1929,12 +1928,12 @@ console.log(Object.keys(person)); ```javascript const settings = { - username: "lydiahallie", + username: 'lydiahallie', level: 19, - health: 90, + health: 90 }; -const data = JSON.stringify(settings, ["level", "health"]); +const data = JSON.stringify(settings, ['level', 'health']); console.log(data); ``` @@ -1965,7 +1964,7 @@ console.log(data); let num = 10; const increaseNumber = () => num++; -const increasePassedNumber = (number) => number++; +const increasePassedNumber = number => number++; const num1 = increaseNumber(); const num2 = increasePassedNumber(num1); @@ -2122,12 +2121,12 @@ class Labrador extends Dog { ```javascript // index.js -console.log("running index.js"); -import { sum } from "./sum.js"; +console.log('running index.js'); +import { sum } from './sum.js'; console.log(sum(1, 2)); // sum.js -console.log("running sum.js"); +console.log('running sum.js'); export const sum = (a, b) => a + b; ``` @@ -2153,9 +2152,9 @@ export const sum = (a, b) => a + b; ###### 68. Какой будет вывод? ```javascript -console.log(Number(2) === Number(2)); -console.log(Boolean(false) === Boolean(false)); -console.log(Symbol("foo") === Symbol("foo")); +console.log(Number(2) === Number(2)) +console.log(Boolean(false) === Boolean(false)) +console.log(Symbol('foo') === Symbol('foo')) ``` - A: `true`, `true`, `false` @@ -2178,9 +2177,9 @@ console.log(Symbol("foo") === Symbol("foo")); ###### 69. Какой будет вывод? ```javascript -const name = "Lydia Hallie"; -console.log(name.padStart(13)); -console.log(name.padStart(2)); +const name = 'Lydia Hallie' +console.log(name.padStart(13)) +console.log(name.padStart(2)) ``` - A: `"Lydia Hallie"`, `"Lydia Hallie"` @@ -2301,7 +2300,7 @@ console.log(String.raw`Hello\nworld`); ```javascript async function getData() { - return await Promise.resolve("I made it!"); + return await Promise.resolve('I made it!'); } const data = getData(); @@ -2338,7 +2337,7 @@ function addToList(item, list) { return list.push(item); } -const result = addToList("apple", ["banana"]); +const result = addToList('apple', ['banana']); console.log(result); ``` @@ -2398,7 +2397,7 @@ console.log(shape); ###### 76. Какой будет вывод? ```javascript -const { firstName: myName } = { firstName: "Lydia" }; +const { firstName: myName } = { firstName: 'Lydia' }; console.log(firstName); ``` @@ -2416,7 +2415,7 @@ console.log(firstName); Используя [деструктурирующее присваивание](https://developer.mozilla.org/ru/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment), мы можем распаковывать значения из массивов или свойства из объектов в отдельные переменные: ```javascript -const { firstName } = { firstName: "Lydia" }; +const { firstName } = { firstName: 'Lydia' }; // Версия ES5: // var firstName = { firstName: 'Lydia' }.firstName; @@ -2426,7 +2425,7 @@ console.log(firstName); // "Lydia" Также свойство можно распаковать из объекта и присвоить переменной с именем, отличным от имени свойства объекта: ```javascript -const { firstName: myName } = { firstName: "Lydia" }; +const { firstName: myName } = { firstName: 'Lydia' }; // Версия ES5: // var myName = { firstName: 'Lydia' }.firstName; @@ -2439,11 +2438,12 @@ console.log(firstName); // Тут будет ошибка Uncaught ReferenceErro **Примечание.** Помните о свойствах глобальной области видимости: ```javascript -const { name: myName } = { name: "Lydia" }; +const { name: myName } = { name: 'Lydia' }; console.log(myName); // "lydia" console.log(name); // "" ----- Браузер, например, Chrome console.log(name); // ReferenceError: name is not defined ----- NodeJS + ``` Всякий раз, когда Javascript не может найти переменную в _текущей области видимости_, то поднимается вверх по [цепочке областей видимости](https://developer.mozilla.org/ru/docs/Web/JavaScript/Closures#лексическая_область_видимости) и ищет ее на каждом уровне, и если достигает области верхнего уровня, также известной как **Глобальная область**, и все еще не находит нужной ссылки, то выдает `ReferenceError`. @@ -2487,7 +2487,7 @@ function sum(a, b) { ```javascript const add = () => { const cache = {}; - return (num) => { + return num => { if (num in cache) { return `From cache! ${cache[num]}`; } else { @@ -2532,21 +2532,21 @@ console.log(addFunction(5 * 2)); ###### 79. Какой будет вывод? ```javascript -const myLifeSummedUp = ["☕", "💻", "🍷", "🍫"]; +const myLifeSummedUp = ['☕', '💻', '🍷', '🍫'] for (let item in myLifeSummedUp) { - console.log(item); + console.log(item) } for (let item of myLifeSummedUp) { - console.log(item); + console.log(item) } ``` - A: `0` `1` `2` `3` и `"☕"` ` "💻"` `"🍷"` `"🍫"` - B: `"☕"` ` "💻"` `"🍷"` `"🍫"` и `"☕"` ` "💻"` `"🍷"` `"🍫"` - C: `"☕"` ` "💻"` `"🍷"` `"🍫"` и `0` `1` `2` `3` -- D: `0` `1` `2` `3` и `{0: "☕", 1: "💻", 2: "🍷", 3: "🍫"}` +- D: `0` `1` `2` `3` и `{0: "☕", 1: "💻", 2: "🍷", 3: "🍫"}`
Ответ

@@ -2569,14 +2569,14 @@ for (let item of myLifeSummedUp) { ###### 80. Какой будет вывод? ```javascript -const list = [1 + 2, 1 * 2, 1 / 2]; -console.log(list); +const list = [1 + 2, 1 * 2, 1 / 2] +console.log(list) ``` - A: `["1 + 2", "1 * 2", "1 / 2"]` - B: `["12", 2, 0.5]` - C: `[3, 2, 0.5]` -- D: `[1, 1, 1]` +- D: `[1, 1, 1]`

Ответ

@@ -2596,16 +2596,16 @@ console.log(list); ```javascript function sayHi(name) { - return `Hi there, ${name}`; + return `Hi there, ${name}` } -console.log(sayHi()); +console.log(sayHi()) ``` - A: `Hi there, ` - B: `Hi there, undefined` - C: `Hi there, null` -- D: `ReferenceError` +- D: `ReferenceError`

Ответ

@@ -2628,21 +2628,21 @@ console.log(sayHi()); ###### 82. Какой будет вывод? ```javascript -var status = "😎"; +var status = '😎' setTimeout(() => { - const status = "😍"; + const status = '😍' const data = { - status: "🥑", + status: '🥑', getStatus() { - return this.status; - }, - }; + return this.status + } + } - console.log(data.getStatus()); - console.log(data.getStatus.call(this)); -}, 0); + console.log(data.getStatus()) + console.log(data.getStatus.call(this)) +}, 0) ``` - A: `"🥑"` и `"😍"` @@ -2668,14 +2668,14 @@ setTimeout(() => { ```javascript const person = { - name: "Lydia", - age: 21, -}; + name: 'Lydia', + age: 21 +} -let city = person.city; -city = "Amsterdam"; +let city = person.city +city = 'Amsterdam' -console.log(person); +console.log(person) ``` - A: `{ name: "Lydia", age: 21 }` @@ -2706,15 +2706,15 @@ console.log(person); ```javascript function checkAge(age) { if (age < 18) { - const message = "Sorry, you're too young."; + const message = "Sorry, you're too young." } else { - const message = "Yay! You're old enough!"; + const message = "Yay! You're old enough!" } - return message; + return message } -console.log(checkAge(21)); +console.log(checkAge(21)) ``` - A: `"Sorry, you're too young."` @@ -2737,9 +2737,9 @@ console.log(checkAge(21)); ###### 85. Какая информация будетвыведена в лог? ```javascript -fetch("https://www.website.com/api/user/1") - .then((res) => res.json()) - .then((res) => console.log(res)); +fetch('https://www.website.com/api/user/1') + .then(res => res.json()) + .then(res => console.log(res)) ``` - A: Результат метода `fetch`. @@ -2793,7 +2793,7 @@ function getName(name) { ###### 87. Какой будет вывод? ```javascript -console.log("I want pizza"[0]); +console.log('I want pizza'[0]) ``` - A: `"""` @@ -2819,10 +2819,10 @@ console.log("I want pizza"[0]); ```javascript function sum(num1, num2 = num1) { - console.log(num1 + num2); + console.log(num1 + num2) } -sum(10); +sum(10) ``` - A: `NaN` @@ -2848,13 +2848,13 @@ sum(10); ```javascript // module.js -export default () => "Hello world"; -export const name = "Lydia"; +export default () => 'Hello world' +export const name = 'Lydia' // index.js -import * as data from "./module"; +import * as data from './module' -console.log(data); +console.log(data) ``` - A: `{ default: function default(), name: "Lydia" }` @@ -2881,12 +2881,12 @@ console.log(data); ```javascript class Person { constructor(name) { - this.name = name; + this.name = name } } -const member = new Person("John"); -console.log(typeof member); +const member = new Person('John') +console.log(typeof member) ``` - A: `"class"` @@ -2903,7 +2903,7 @@ console.log(typeof member); ```javascript function Person() { - this.name = name; + this.name = name } ``` @@ -2917,9 +2917,9 @@ function Person() { ###### 91. Какой будет вывод? ```javascript -let newList = [1, 2, 3].push(4); +let newList = [1, 2, 3].push(4) -console.log(newList.push(5)); +console.log(newList.push(5)) ``` - A: `[1, 2, 3, 4, 5]` @@ -2945,14 +2945,14 @@ console.log(newList.push(5)); ```javascript function giveLydiaPizza() { - return "Here is pizza!"; + return 'Here is pizza!' } const giveLydiaChocolate = () => - "Here's chocolate... now go hit the gym already."; + "Here's chocolate... now go hit the gym already." -console.log(giveLydiaPizza.prototype); -console.log(giveLydiaChocolate.prototype); +console.log(giveLydiaPizza.prototype) +console.log(giveLydiaChocolate.prototype) ``` - A: `{ constructor: ...}` `{ constructor: ...}` @@ -2976,12 +2976,12 @@ console.log(giveLydiaChocolate.prototype); ```javascript const person = { - name: "Lydia", - age: 21, -}; + name: 'Lydia', + age: 21 +} for (const [x, y] of Object.entries(person)) { - console.log(x, y); + console.log(x, y) } ``` @@ -3033,10 +3033,10 @@ getItems(["banana", "apple"], "pear", "orange") ```javascript function getItems(fruitList, favoriteFruit, ...args) { - return [...fruitList, ...args, favoriteFruit]; + return [...fruitList, ...args, favoriteFruit] } -getItems(["banana", "apple"], "pear", "orange"); +getItems(["banana", "apple"], "pear", "orange") ``` Приведенный выше пример работает. Это возвращает массив `[ 'banana', 'apple', 'orange', 'pear' ]` @@ -3050,14 +3050,14 @@ getItems(["banana", "apple"], "pear", "orange"); ```javascript function nums(a, b) { - if (a > b) console.log("a is bigger"); - else console.log("b is bigger"); - return; - a + b; + if (a > b) console.log('a is bigger') + else console.log('b is bigger') + return + a + b; } -console.log(nums(4, 2)); -console.log(nums(1, 2)); +console.log(nums(4, 2)) +console.log(nums(1, 2)) ``` - A: `a is bigger`, `6` and `b is bigger`, `3` @@ -3075,8 +3075,8 @@ console.log(nums(1, 2)); Здесь мы написали инструкцию `return` и другое значение `a + b` в новой строке. Однако, поскольку это новая линия, движок не знает, что это на самом деле значение, которое мы хотели бы вернуть. Вместо этого он автоматически добавляет точку с запятой после `return`. Вы можете увидеть это как: ```javascript -return; -a + b; + return; + a + b ``` Это означает, что `a + b` никогда не достигается, так как функция перестает выполняться после ключевого слова `return`. Если значение не возвращается, как здесь, функция возвращает значение `undefined`. Обратите внимание, что после операторов `if / else` автоматической вставки нет! @@ -3091,18 +3091,18 @@ a + b; ```javascript class Person { constructor() { - this.name = "Lydia"; + this.name = 'Lydia' } } Person = class AnotherPerson { constructor() { - this.name = "Sarah"; + this.name = 'Sarah' } -}; +} -const member = new Person(); -console.log(member.name); +const member = new Person() +console.log(member.name) ``` - A: `"Lydia"` @@ -3126,11 +3126,11 @@ console.log(member.name); ```javascript const info = { - [Symbol("a")]: "b", -}; + [Symbol('a')]: 'b' +} -console.log(info); -console.log(Object.keys(info)); +console.log(info) +console.log(Object.keys(info)) ``` - A: `{Symbol('a'): 'b'}` and `["{Symbol('a')"]` @@ -3185,7 +3185,7 @@ console.log(getUser(user)) Следующая функция вернула бы объект: -`const getUser = user => ({ name: user.name, age: user.age })` +```const getUser = user => ({ name: user.name, age: user.age })```

@@ -3195,9 +3195,9 @@ console.log(getUser(user)) ###### 99. Какой будет вывод? ```javascript -const name = "Lydia"; +const name = 'Lydia' -console.log(name()); +console.log(name()) ``` - A: `SyntaxError` @@ -3227,8 +3227,8 @@ ReferenceErrors генерируется, когда JavaScript не может ```javascript // 🎉✨ This is my 100th question! ✨🎉 -const output = `${[] && "Im"}possible! -You should${"" && `n't`} see a therapist after so much JavaScript lol`; +const output = `${[] && 'Im'}possible! +You should${'' && `n't`} see a therapist after so much JavaScript lol` ``` - A: `possible! You should see a therapist after so much JavaScript lol` @@ -3253,11 +3253,11 @@ You should${"" && `n't`} see a therapist after so much JavaScript lol`; ###### 101. Какое значение будет на выходе? ```javascript -const one = false || {} || null; -const two = null || false || ""; -const three = [] || 0 || true; +const one = (false || {} || null) +const two = (null || false || '') +const three = ([] || 0 || true) -console.log(one, two, three); +console.log(one, two, three) ``` - A: `false` `null` `[]` @@ -3286,20 +3286,20 @@ console.log(one, two, three); ###### 102. Какое значение будет на выходе? ```javascript -const myPromise = () => Promise.resolve("I have resolved!"); +const myPromise = () => Promise.resolve('I have resolved!') function firstFunction() { - myPromise().then((res) => console.log(res)); - console.log("second"); + myPromise().then(res => console.log(res)) + console.log('second') } async function secondFunction() { - console.log(await myPromise()); - console.log("second"); + console.log(await myPromise()) + console.log('second') } -firstFunction(); -secondFunction(); +firstFunction() +secondFunction() ``` - A: `I have resolved!`, `second` and `I have resolved!`, `second` @@ -3330,14 +3330,14 @@ secondFunction(); ###### 103. Какое значение будет на выходе? ```javascript -const set = new Set(); +const set = new Set() -set.add(1); -set.add("Lydia"); -set.add({ name: "Lydia" }); +set.add(1) +set.add('Lydia') +set.add({ name: 'Lydia' }) for (let item of set) { - console.log(item + 2); + console.log(item + 2) } ``` @@ -3367,7 +3367,7 @@ for (let item of set) { ###### 104. Чему равно значение? ```javascript -Promise.resolve(5); +Promise.resolve(5) ``` - A: `5` @@ -3394,15 +3394,15 @@ Promise.resolve(5); ```javascript function compareMembers(person1, person2 = person) { if (person1 !== person2) { - console.log("Not the same!"); + console.log('Not the same!') } else { - console.log("They are the same!"); + console.log('They are the same!') } } -const person = { name: "Lydia" }; +const person = { name: 'Lydia' } -compareMembers(person); +compareMembers(person) ``` - A: `Not the same!` @@ -3437,11 +3437,11 @@ const colorConfig = { green: true, black: true, yellow: false, -}; +} -const colors = ["pink", "red", "blue"]; +const colors = ['pink', 'red', 'blue'] -console.log(colorConfig.colors[1]); +console.log(colorConfig.colors[1]) ``` - A: `true` @@ -3468,7 +3468,7 @@ JavaScript интерпретирует (или распаковывает) оп ###### 107. Чему равно значение? ```javascript -console.log("❤️" === "❤️"); +console.log('❤️' === '❤️') ``` - A: `true` @@ -3489,19 +3489,19 @@ console.log("❤️" === "❤️"); ###### 108. Какой из этих методов модифицирует исходный массив? ```javascript -const emojis = ["✨", "🥑", "😍"]; +const emojis = ['✨', '🥑', '😍'] -emojis.map((x) => x + "✨"); -emojis.filter((x) => x !== "🥑"); -emojis.find((x) => x !== "🥑"); -emojis.reduce((acc, cur) => acc + "✨"); -emojis.slice(1, 2, "✨"); -emojis.splice(1, 2, "✨"); +emojis.map(x => x + '✨') +emojis.filter(x => x !== '🥑') +emojis.find(x => x !== '🥑') +emojis.reduce((acc, cur) => acc + '✨') +emojis.slice(1, 2, '✨') +emojis.splice(1, 2, '✨') ``` - A: `All of them` - B: `map` `reduce` `slice` `splice` -- C: `map` `slice` `splice` +- C: `map` `slice` `splice` - D: `splice`
Ответ @@ -3521,17 +3521,17 @@ emojis.splice(1, 2, "✨"); ###### 109. Какое значение будет на выходе? ```javascript -const food = ["🍕", "🍫", "🥑", "🍔"]; -const info = { favoriteFood: food[0] }; +const food = ['🍕', '🍫', '🥑', '🍔'] +const info = { favoriteFood: food[0] } -info.favoriteFood = "🍝"; +info.favoriteFood = '🍝' -console.log(food); +console.log(food) ``` - A: `['🍕', '🍫', '🥑', '🍔']` - B: `['🍝', '🍫', '🥑', '🍔']` -- C: `['🍝', '🍕', '🍫', '🥑', '🍔']` +- C: `['🍝', '🍕', '🍫', '🥑', '🍔']` - D: `ReferenceError`
Ответ @@ -3553,7 +3553,7 @@ console.log(food); ###### 110. Что делает этот метод? ```javascript -JSON.parse(); +JSON.parse() ``` - A: Разбирает JSON в значение JavaScript @@ -3570,16 +3570,16 @@ JSON.parse(); ```javascript // Преобразование числа в допустимый JSON, затем преобразование строки JSON в значение JavaScript: -const jsonNumber = JSON.stringify(4); // '4' -JSON.parse(jsonNumber); // 4 +const jsonNumber = JSON.stringify(4) // '4' +JSON.parse(jsonNumber) // 4 // Преобразование значения массива в допустимый JSON, затем разбор строки JSON в значение JavaScript: -const jsonArray = JSON.stringify([1, 2, 3]); // '[1, 2, 3]' -JSON.parse(jsonArray); // [1, 2, 3] +const jsonArray = JSON.stringify([1, 2, 3]) // '[1, 2, 3]' +JSON.parse(jsonArray) // [1, 2, 3] // Преобразование объекта в допустимый JSON, затем преобразование строки JSON в значение JavaScript: -const jsonArray = JSON.stringify({ name: "Lydia" }); // '{"name":"Lydia"}' -JSON.parse(jsonArray); // { name: 'Lydia' } +const jsonArray = JSON.stringify({ name: 'Lydia' }) // '{"name":"Lydia"}' +JSON.parse(jsonArray) // { name: 'Lydia' } ```

@@ -3587,17 +3587,17 @@ JSON.parse(jsonArray); // { name: 'Lydia' } --- -###### 111. Какое значение будет на выходе? +###### 111. Какое значение будет на выходе? ```javascript -let name = "Lydia"; +let name = 'Lydia' function getName() { - console.log(name); - let name = "Sarah"; + console.log(name) + let name = 'Sarah' } -getName(); +getName() ``` - A: Lydia @@ -3617,13 +3617,13 @@ getName(); Если бы мы не объявили переменную `name` в функции `getName`, движок javascript посмотрел бы вниз по _цепочки области действия_. Внешняя область имеет переменную с именем `name` со значением `Lydia`. В этом случае он бы записал `Lydia`. ```javascript -let name = "Lydia"; +let name = 'Lydia' function getName() { - console.log(name); + console.log(name) } -getName(); // Lydia +getName() // Lydia ```

@@ -3635,18 +3635,18 @@ getName(); // Lydia ```javascript function* generatorOne() { - yield ["a", "b", "c"]; + yield ['a', 'b', 'c']; } function* generatorTwo() { - yield* ["a", "b", "c"]; + yield* ['a', 'b', 'c']; } -const one = generatorOne(); -const two = generatorTwo(); +const one = generatorOne() +const two = generatorTwo() -console.log(one.next().value); -console.log(two.next().value); +console.log(one.next().value) +console.log(two.next().value) ``` - A: `a` and `a` @@ -3664,17 +3664,17 @@ console.log(two.next().value); В `generatorOne` мы получаем весь массив `['a', 'b', 'c']`, используя ключевое слово `yield`. Значение свойства `value` для объекта, возвращаемого методом `next` для `one` (`one.next().value`), равно всему массиву `['a', 'b', 'c']`. ```javascript -console.log(one.next().value); // ['a', 'b', 'c'] -console.log(one.next().value); // undefined +console.log(one.next().value) // ['a', 'b', 'c'] +console.log(one.next().value) // undefined ``` В файле `generatorTwo` мы используем ключевое слово `yield*`. Это означает, что первое полученное значение `two` равно первому полученному значению в итераторе. Итератор - это массив `['a', 'b', 'c']`. Первым полученным значением является `a`, поэтому в первый раз, когда мы вызываем `two.next().value`, возвращается `a`. ```javascript -console.log(two.next().value); // 'a' -console.log(two.next().value); // 'b' -console.log(two.next().value); // 'c' -console.log(two.next().value); // undefined +console.log(two.next().value) // 'a' +console.log(two.next().value) // 'b' +console.log(two.next().value) // 'c' +console.log(two.next().value) // undefined ```

@@ -3685,7 +3685,7 @@ console.log(two.next().value); // undefined ###### 113. Какое значение будет на выходе? ```javascript -console.log(`${((x) => x)("I love")} to program`); +console.log(`${(x => x)('I love')} to program`) ``` - A: `I love to program` @@ -3710,11 +3710,11 @@ console.log(`${((x) => x)("I love")} to program`); ```javascript let config = { alert: setInterval(() => { - console.log("Alert!"); - }, 1000), -}; + console.log('Alert!') + }, 1000) +} -config = null; +config = null ``` - A: обратный вызов `setInterval` не будет вызван @@ -3741,17 +3741,17 @@ config = null; ###### 115. Какие методы вернут значение `'Hello world!'`? ```javascript -const myMap = new Map(); -const myFunc = () => "greeting"; +const myMap = new Map() +const myFunc = () => 'greeting' -myMap.set(myFunc, "Hello world!"); +myMap.set(myFunc, 'Hello world!') //1 -myMap.get("greeting"); +myMap.get('greeting') //2 -myMap.get(myFunc); +myMap.get(myFunc) //3 -myMap.get(() => "greeting"); +myMap.get(() => 'greeting') ``` - A: 1 @@ -3778,20 +3778,20 @@ myMap.get(() => "greeting"); ```javascript const person = { - name: "Lydia", - age: 21, -}; + name: 'Lydia', + age: 21 +} -const changeAge = (x = { ...person }) => (x.age += 1); +const changeAge = (x = { ...person }) => x.age += 1 const changeAgeAndName = (x = { ...person }) => { - x.age += 1; - x.name = "Sarah"; -}; + x.age += 1 + x.name = 'Sarah' +} -changeAge(person); -changeAgeAndName(); +changeAge(person) +changeAgeAndName() -console.log(person); +console.log(person) ``` - A: `{name: "Sarah", age: 22}` @@ -3819,7 +3819,7 @@ console.log(person); ```javascript function sumValues(x, y, z) { - return x + y + z; + return x + y + z; } ``` @@ -3870,15 +3870,15 @@ console.log(list[(num += 1)]); ```javascript const person = { - firstName: "Lydia", - lastName: "Hallie", - pet: { - name: "Mara", - breed: "Dutch Tulip Hound", - }, - getFullName() { - return `${this.firstName} ${this.lastName}`; - }, + firstName: 'Lydia', + lastName: 'Hallie', + pet: { + name: 'Mara', + breed: 'Dutch Tulip Hound' + }, + getFullName() { + return `${this.firstName} ${this.lastName}`; + } }; console.log(person.pet?.name); @@ -3912,12 +3912,12 @@ console.log(member.getLastName?.()); ###### 120. Что будет на выходе? ```javascript -const groceries = ["banana", "apple", "peanuts"]; +const groceries = ['banana', 'apple', 'peanuts']; -if (groceries.indexOf("banana")) { - console.log("We have to buy bananas!"); +if (groceries.indexOf('banana')) { + console.log('We have to buy bananas!'); } else { - console.log(`We don't have to buy bananas!`); + console.log(`We don't have to buy bananas!`); } ``` @@ -3931,7 +3931,7 @@ if (groceries.indexOf("banana")) { #### Ответ: B -Мы передали условие `groceries.indexOf("banana")` в оператор `if`. `groceries.indexOf("banana")` возвращает `0`, что является ложным значением. Поскольку условие в операторе `if` ложно, выполняется код в блоке `else`, и в лог выводится `We don't have to buy bananas!`. +Мы передали условие `groceries.indexOf("banana")` в оператор `if`. `groceries.indexOf("banana")` возвращает `0`, что является ложным значением. Поскольку условие в операторе `if` ложно, выполняется код в блоке `else`, и в лог выводится ``We don't have to buy bananas!``.

@@ -3942,10 +3942,10 @@ if (groceries.indexOf("banana")) { ```javascript const config = { - languages: [], - set language(lang) { - return this.languages.push(lang); - }, + languages: [], + set language(lang) { + return this.languages.push(lang); + } }; console.log(config.language); @@ -3971,10 +3971,10 @@ console.log(config.language); ###### 122. Что будет на выходе? ```javascript -const name = "Lydia Hallie"; +const name = 'Lydia Hallie'; -console.log(!typeof name === "object"); -console.log(!typeof name === "string"); +console.log(!typeof name === 'object'); +console.log(!typeof name === 'string'); ``` - A: `false` `true` @@ -3999,9 +3999,9 @@ console.log(!typeof name === "string"); ###### 123. Что будет на выходе? ```javascript -const add = (x) => (y) => (z) => { - console.log(x, y, z); - return x + y + z; +const add = x => y => z => { + console.log(x, y, z); + return x + y + z; }; add(4)(5)(6); @@ -4028,16 +4028,16 @@ add(4)(5)(6); ```javascript async function* range(start, end) { - for (let i = start; i <= end; i++) { - yield Promise.resolve(i); - } + for (let i = start; i <= end; i++) { + yield Promise.resolve(i); + } } (async () => { - const gen = range(1, 3); - for await (const item of gen) { - console.log(item); - } + const gen = range(1, 3); + for await (const item of gen) { + console.log(item); + } })(); ``` @@ -4062,7 +4062,7 @@ async function* range(start, end) { ```javascript const myFunc = ({ x, y, z }) => { - console.log(x, y, z); + console.log(x, y, z); }; myFunc(1, 2, 3); @@ -4186,8 +4186,8 @@ console.log(isNaN(age)); const randomValue = 21; function getInfo() { - console.log(typeof randomValue); - const randomValue = "Lydia Hallie"; + console.log(typeof randomValue); + const randomValue = 'Lydia Hallie'; } getInfo(); @@ -4213,16 +4213,16 @@ getInfo(); ###### 130. Что будет на выходе? ```javascript -const myPromise = Promise.resolve("Woah some cool data"); +const myPromise = Promise.resolve('Woah some cool data'); (async () => { - try { - console.log(await myPromise); - } catch { - throw new Error(`Oops didn't work`); - } finally { - console.log("Oh finally!"); - } + try { + console.log(await myPromise); + } catch { + throw new Error(`Oops didn't work`); + } finally { + console.log('Oh finally!'); + } })(); ``` @@ -4246,7 +4246,7 @@ const myPromise = Promise.resolve("Woah some cool data"); ###### 131. Что будет на выходе? ```javascript -const emojis = ["🥑", ["✨", "✨", ["🍕", "🍕"]]]; +const emojis = ['🥑', ['✨', '✨', ['🍕', '🍕']]]; console.log(emojis.flat(1)); ``` @@ -4319,19 +4319,19 @@ console.log(counterOne.count); ###### 133. Что будет на выходе? ```javascript -const myPromise = Promise.resolve(Promise.resolve("Promise!")); +const myPromise = Promise.resolve(Promise.resolve('Promise!')); function funcOne() { - myPromise.then((res) => res).then((res) => console.log(res)); - setTimeout(() => console.log("Timeout!", 0)); - console.log("Last line!"); + myPromise.then(res => res).then(res => console.log(res)); + setTimeout(() => console.log('Timeout!', 0)); + console.log('Last line!'); } async function funcTwo() { const res = await myPromise; console.log(await res); - setTimeout(() => console.log("Timeout!", 0)); - console.log("Last line!"); + setTimeout(() => console.log('Timeout!', 0)); + console.log('Last line!'); } funcOne(); @@ -4376,7 +4376,7 @@ export default function sum(x) { } // index.js -import * as sum from "./sum"; +import * as sum from './sum'; ``` - A: `sum(4)` @@ -4393,12 +4393,12 @@ import * as sum from "./sum"; ```javascript // info.js -export const name = "Lydia"; +export const name = 'Lydia'; export const age = 21; -export default "I love JavaScript"; +export default 'I love JavaScript'; // index.js -import * as info from "./info"; +import * as info from './info'; console.log(info); ``` @@ -4429,13 +4429,13 @@ console.log(info); ```javascript const handler = { - set: () => console.log("Added a new property!"), - get: () => console.log("Accessed a property!"), + set: () => console.log('Added a new property!'), + get: () => console.log('Accessed a property!'), }; const person = new Proxy({}, handler); -person.name = "Lydia"; +person.name = 'Lydia'; person.name; ``` @@ -4465,7 +4465,7 @@ C помощью Proxy мы можем добавить собственное ###### 136. Какое из перечисленных действий может модифицировать объект `person`? ```javascript -const person = { name: "Lydia Hallie" }; +const person = { name: 'Lydia Hallie' }; Object.seal(person); ``` @@ -4493,9 +4493,9 @@ Object.seal(person); ```javascript const person = { - name: "Lydia Hallie", + name: 'Lydia Hallie', address: { - street: "100 Main St", + street: '100 Main St', }, }; @@ -4524,7 +4524,7 @@ Object.freeze(person); ###### 138. Что будет на выходе? ```javascript -const add = (x) => x + x; +const add = x => x + x; function myFunc(num = 2, value = add(num)) { console.log(num, value); @@ -4557,21 +4557,21 @@ myFunc(3); ```javascript class Counter { - #number = 10; + #number = 10 increment() { - this.#number++; + this.#number++ } getNum() { - return this.#number; + return this.#number } } -const counter = new Counter(); -counter.increment(); +const counter = new Counter() +counter.increment() -console.log(counter.#number); +console.log(counter.#number) ``` - A: `10` @@ -4595,8 +4595,8 @@ console.log(counter.#number); ```javascript const teams = [ - { name: "Team 1", members: ["Paul", "Lisa"] }, - { name: "Team 2", members: ["Laura", "Tim"] }, + { name: 'Team 1', members: ['Paul', 'Lisa'] }, + { name: 'Team 2', members: ['Laura', 'Tim'] }, ]; function* getMembers(members) { @@ -4639,8 +4639,8 @@ obj.next(); // { value: "Lisa", done: false } ```javascript const person = { - name: "Lydia Hallie", - hobbies: ["coding"], + name: 'Lydia Hallie', + hobbies: ['coding'], }; function addHobby(hobby, hobbies = person.hobbies) { @@ -4648,9 +4648,9 @@ function addHobby(hobby, hobbies = person.hobbies) { return hobbies; } -addHobby("running", []); -addHobby("dancing"); -addHobby("baking", person.hobbies); +addHobby('running', []); +addHobby('dancing'); +addHobby('baking', person.hobbies); console.log(person.hobbies); ``` @@ -4719,11 +4719,11 @@ const pet = new Flamingo(); ###### 143. Какой/какие из вариантов приведет к ошибке? ```javascript -const emojis = ["🎄", "🎅🏼", "🎁", "⭐"]; +const emojis = ['🎄', '🎅🏼', '🎁', '⭐']; -/* 1 */ emojis.push("🦌"); +/* 1 */ emojis.push('🦌'); /* 2 */ emojis.splice(0, 2); -/* 3 */ emojis = [...emojis, "🥂"]; +/* 3 */ emojis = [...emojis, '🥂']; /* 4 */ emojis.length = 0; ``` @@ -4778,11 +4778,11 @@ const person = { let count = 0; const nums = [0, 1, 2, 3]; -nums.forEach((num) => { - if (num) count += 1; -}); +nums.forEach(num => { + if (num) count += 1 +}) -console.log(count); +console.log(count) ``` - A: 1 @@ -4806,12 +4806,12 @@ console.log(count); ```javascript function getFruit(fruits) { - console.log(fruits?.[1]?.[1]); + console.log(fruits?.[1]?.[1]) } -getFruit([["🍊", "🍌"], ["🍍"]]); -getFruit(); -getFruit([["🍍"], ["🍊", "🍌"]]); +getFruit([['🍊', '🍌'], ['🍍']]) +getFruit() +getFruit([['🍍'], ['🍊', '🍌']]) ``` - A: `null`, `undefined`, 🍌 @@ -4841,19 +4841,19 @@ getFruit([["🍍"], ["🍊", "🍌"]]); ```javascript class Calc { - constructor() { - this.count = 0; - } + constructor() { + this.count = 0 + } - increase() { - this.count++; - } + increase() { + this.count ++ + } } -const calc = new Calc(); -new Calc().increase(); +const calc = new Calc() +new Calc().increase() -console.log(calc.count); +console.log(calc.count) ``` - A: `0` @@ -4877,25 +4877,25 @@ console.log(calc.count); ```javascript const user = { - email: "e@mail.com", - password: "12345", -}; + email: "e@mail.com", + password: "12345" +} const updateUser = ({ email, password }) => { - if (email) { - Object.assign(user, { email }); - } + if (email) { + Object.assign(user, { email }) + } - if (password) { - user.password = password; - } + if (password) { + user.password = password + } - return user; -}; + return user +} -const updatedUser = updateUser({ email: "new@email.com" }); +const updatedUser = updateUser({ email: "new@email.com" }) -console.log(updatedUser === user); +console.log(updatedUser === user) ``` - A: `false` @@ -4918,13 +4918,13 @@ console.log(updatedUser === user); ###### 149. Что будет на выходе? ```javascript -const fruit = ["🍌", "🍊", "🍎"]; +const fruit = ['🍌', '🍊', '🍎'] -fruit.slice(0, 1); -fruit.splice(0, 1); -fruit.unshift("🍇"); +fruit.slice(0, 1) +fruit.splice(0, 1) +fruit.unshift('🍇') -console.log(fruit); +console.log(fruit) ``` - A: `['🍌', '🍊', '🍎']` @@ -4950,13 +4950,13 @@ console.log(fruit); ```javascript const animals = {}; -let dog = { emoji: "🐶" }; -let cat = { emoji: "🐈" }; +let dog = { emoji: '🐶' } +let cat = { emoji: '🐈' } -animals[dog] = { ...dog, name: "Mara" }; -animals[cat] = { ...cat, name: "Sara" }; +animals[dog] = { ...dog, name: "Mara" } +animals[cat] = { ...cat, name: "Sara" } -console.log(animals[dog]); +console.log(animals[dog]) ``` - A: `{ emoji: "🐶", name: "Mara" }` @@ -4986,14 +4986,14 @@ console.log(animals[dog]); ```javascript const user = { - email: "my@email.com", - updateEmail: (email) => { - this.email = email; - }, -}; + email: "my@email.com", + updateEmail: email => { + this.email = email + } +} -user.updateEmail("new@email.com"); -console.log(user.email); +user.updateEmail("new@email.com") +console.log(user.email) ``` - A: `my@email.com` @@ -5016,20 +5016,20 @@ console.log(user.email); ###### 152. Что будет на выходе? ```javascript -const promise1 = Promise.resolve("First"); -const promise2 = Promise.resolve("Second"); -const promise3 = Promise.reject("Third"); -const promise4 = Promise.resolve("Fourth"); +const promise1 = Promise.resolve('First') +const promise2 = Promise.resolve('Second') +const promise3 = Promise.reject('Third') +const promise4 = Promise.resolve('Fourth') const runPromises = async () => { - const res1 = await Promise.all([promise1, promise2]); - const res2 = await Promise.all([promise3, promise4]); - return [res1, res2]; -}; + const res1 = await Promise.all([promise1, promise2]) + const res2 = await Promise.all([promise3, promise4]) + return [res1, res2] +} runPromises() - .then((res) => console.log(res)) - .catch((err) => console.log(err)); + .then(res => console.log(res)) + .catch(err => console.log(err)) ``` - A: `[['First', 'Second'], ['Fourth']]` @@ -5052,16 +5052,13 @@ runPromises() ###### 153. Каким должно быть значение `method` для регистрации `{ name: "Lydia", age: 22 }`? ```javascript -const keys = ["name", "age"]; -const values = ["Lydia", 22]; +const keys = ["name", "age"] +const values = ["Lydia", 22] -const method = - /* ?? */ - Object[method]( - keys.map((_, i) => { - return [keys[i], values[i]]; - }) - ); // { name: "Lydia", age: 22 } +const method = /* ?? */ +Object[method](keys.map((_, i) => { + return [keys[i], values[i]] +})) // { name: "Lydia", age: 22 } ``` - A: `entries` @@ -5086,18 +5083,18 @@ const method = ###### 154. Что будет на выходе? ```javascript -const createMember = ({ email, address = {} }) => { - const validEmail = /.+\@.+\..+/.test(email); - if (!validEmail) throw new Error("Valid email pls"); +const createMember = ({ email, address = {}}) => { + const validEmail = /.+\@.+\..+/.test(email) + if (!validEmail) throw new Error("Valid email pls") - return { - email, - address: address ? address : null, - }; -}; + return { + email, + address: address ? address : null + } +} -const member = createMember({ email: "my@email.com" }); -console.log(member); +const member = createMember({ email: "my@email.com" }) +console.log(member) ``` - A: `{ email: "my@email.com", address: null }` @@ -5120,13 +5117,13 @@ console.log(member); ###### 155. Что будет на выходе? ```javascript -let randomValue = { name: "Lydia" }; -randomValue = 23; +let randomValue = { name: "Lydia" } +randomValue = 23 if (!typeof randomValue === "string") { - console.log("It's not a string!"); + console.log("It's not a string!") } else { - console.log("Yay it's a string!"); + console.log("Yay it's a string!") } ``` diff --git a/sq-KS/README_sq_KS.md b/sq-KS/README_sq_KS.md index 8446493c..aa1eb9dc 100644 --- a/sq-KS/README_sq_KS.md +++ b/sq-KS/README_sq_KS.md @@ -10,10 +10,9 @@ Nga konceptet bazike tek ato të avancuara: testo se sa mirë e njeh JavaScript- Mos hezitoni të më kontaktoni! 😊 Instagram || Twitter || LinkedIn || Blog - -| Ndjehuni të lirë të i përdorni në projektet e juaja |😃 Do të e vlerësoja shumë referencimin tuaj në ketë repositori, unë i krijoj pyetjet dhe poashtu edhe përgjigjet (lol) dhe komuniteti me ndihmon shumë të e përmirësoj dhe të mirëmbajë! 💪🏼 Faleminderit! +| Ndjehuni të lirë të i përdorni në projektet e juaja |😃 Do të e vlerësoja shumë referencimin tuaj në ketë repositori, unë i krijoj pyetjet dhe poashtu edhe përgjigjet (lol) dhe komuniteti me ndihmon shumë të e përmirësoj dhe të mirëmbajë! 💪🏼 Faleminderit! --- @@ -33,7 +32,6 @@ Mos hezitoni të më kontaktoni! 😊 - [🇳🇱 Nederlands](../nl-NL/README.md) - [🇵🇱 Polski](../pl-PL/README.md) - [🇧🇷 Português Brasil](../pt-BR/README_pt_BR.md) -- [🇷o Română](../ro-RO/README.ro.md) - [🇷🇺 Русский](../ru-RU/README.md) - [🇽🇰 Shqip](./sq-KS/README_sq_KS.md) - [🇹🇭 ไทย](../th-TH/README-th_TH.md) @@ -48,13 +46,13 @@ Mos hezitoni të më kontaktoni! 😊 --- -###### 1. Cila është vlera e saj? +###### 1. Cila është vlera e saj? ```javascript function sayHi() { console.log(name); console.log(age); - var name = "Lydia"; + var name = 'Lydia'; let age = 21; } @@ -80,7 +78,7 @@ Variablat me fjalën kyçe `let` (dhe `const`) hoistohen, por ndryshe nga `var`, --- -###### 2. Cila është vlera e saj? +###### 2. Cila është vlera e saj? ```javascript for (var i = 0; i < 3; i++) { @@ -101,7 +99,7 @@ for (let i = 0; i < 3; i++) { #### Përgjigja: C -Për shkak të **_event queque_** në JavaScript, funksioni callback `setTimeout` thirret pas ekzekutimit të unazës. Pasi që variabla `i` në iterimin e parë u deklarua duke përdorur fjalën kyçe `var`, kjo vlerë ishte globale. Gjatë unazës, ne rritëm vlerën e `i` me `1` çdo herë, duke përdorur operatorin unar `++`. Deri në kohën që funksioni callback `setTimeout` u thirr, `i` ishte e barabartë me `3` në unazën e parë. +Për shkak të ***event queque*** në JavaScript, funksioni callback `setTimeout` thirret pas ekzekutimit të unazës. Pasi që variabla `i` në iterimin e parë u deklarua duke përdorur fjalën kyçe `var`, kjo vlerë ishte globale. Gjatë unazës, ne rritëm vlerën e `i` me `1` çdo herë, duke përdorur operatorin unar `++`. Deri në kohën që funksioni callback `setTimeout` u thirr, `i` ishte e barabartë me `3` në unazën e parë. Në unazën e dytë, variabla `i` u deklarua duke përdorur fjalën kyçe `let`: variablat e deklaruara me fjalën kyçe `let` (dhe `const`) janë të qasshme në bllok (një bllok është çdo gjë mes `{ }`). Gjatë çdo iteracioni, `i` do të ketë një vlerë të re, dhe çdo vlerë është e qasshme brenda unazës. @@ -150,7 +148,7 @@ Në funksionet shigjeta, fjala kyçe `this` referohet në qasjen në rrethinën ```javascript +true; -!"Lydia"; +!'Lydia'; ``` - A: `1` and `false` @@ -175,11 +173,11 @@ Vargu i karaktereve (stringu) `'Lydia'` konsiderohet si vlerë `true`. Çfarë n ```javascript const bird = { - size: "small", + size: 'small', }; const mouse = { - name: "Mickey", + name: 'Mickey', small: true, }; ``` @@ -210,11 +208,11 @@ Megjithatë, me notacionin pikë, kjo nuk ndodh. `mouse` nuk ka një çelës të ###### 6. Cila është vlera e saj? ```javascript -let c = { greeting: "Hey!" }; +let c = { greeting: 'Hey!' }; let d; d = c; -c.greeting = "Hello"; +c.greeting = 'Hello'; console.log(d.greeting); ``` @@ -268,7 +266,7 @@ console.log(b === c); Kur përdorim operatorin `==` (operatorin i barazimit), ai kontrollon vetëm nëse ka të njëjtën _vlerë_. Të dy kanë vlerën `3`, kështu që kthen `true`. -Megjithatë, kur përdorim operatorin `===` (operatori i barazisë strikte), të dy vlerat dhe tipi i tyre duhet të jenë të njëjta. Nuk është: `new Number()` nuk është një numër, është një **objekt**. Të dy kthejnë `false`. +Megjithatë, kur përdorim operatorin `===` (operatori i barazisë strikte), të dy vlerat dhe tipi i tyre duhet të jenë të njëjta. Nuk është: `new Number()` nuk është një numër, është një __objekt__. Të dy kthejnë `false`.

@@ -284,13 +282,13 @@ class Chameleon { return this.newColor; } - constructor({ newColor = "green" } = {}) { + constructor({ newColor = 'green' } = {}) { this.newColor = newColor; } } -const freddie = new Chameleon({ newColor: "purple" }); -console.log(freddie.colorChange("orange")); +const freddie = new Chameleon({ newColor: 'purple' }); +console.log(freddie.colorChange('orange')); ``` - A: `orange` @@ -345,10 +343,10 @@ Për të shmangur këtë, ne mund të përdorim `"use strict"`. Kjo siguron që ```javascript function bark() { - console.log("Woof!"); + console.log('Woof!'); } -bark.animal = "dog"; +bark.animal = 'dog'; ``` - A: Asgjë, gjithçka është në rregull! @@ -378,8 +376,8 @@ function Person(firstName, lastName) { this.lastName = lastName; } -const member = new Person("Lydia", "Hallie"); -Person.getFullName = function () { +const member = new Person('Lydia', 'Hallie'); +Person.getFullName = function() { return `${this.firstName} ${this.lastName}`; }; @@ -401,7 +399,7 @@ Në JavaScript, funksionet janë objekte dhe për këtë arsye metoda `getFullNa Nëse dëshironi që një metodë të jetë e qasshme për të gjitha instancat e objektit, duhet ta shtoni atë në vetinë e quajtur "prototype": ```js -Person.prototype.getFullName = function () { +Person.prototype.getFullName = function() { return `${this.firstName} ${this.lastName}`; }; ``` @@ -419,8 +417,8 @@ function Person(firstName, lastName) { this.lastName = lastName; } -const lydia = new Person("Lydia", "Hallie"); -const sarah = Person("Sarah", "Smith"); +const lydia = new Person('Lydia', 'Hallie'); +const sarah = Person('Sarah', 'Smith'); console.log(lydia); console.log(sarah); @@ -490,7 +488,7 @@ function sum(a, b) { return a + b; } -sum(1, "2"); +sum(1, '2'); ``` - A: `NaN` @@ -503,7 +501,7 @@ sum(1, "2"); #### Përgjigja: C -JavaScript është gjuhë e shkruar në mënyrë dinamike **dynamically typed language**: ne nuk specifikojmë se çfarë tipe janë variablat e caktuara. Vlerat mund të konvertohen automatikisht në një tip tjetër pa e ditur ju dhe ky proces quhet _implicit type coercion_ (shndërrimi i tipit në mënyrë të nënkuptuar). **Coercion** është shndërrimi nga një tip në një tjetër. +JavaScript është gjuhë e shkruar në mënyrë dinamike __dynamically typed language__: ne nuk specifikojmë se çfarë tipe janë variablat e caktuara. Vlerat mund të konvertohen automatikisht në një tip tjetër pa e ditur ju dhe ky proces quhet _implicit type coercion_ (shndërrimi i tipit në mënyrë të nënkuptuar). __Coercion__ është shndërrimi nga një tip në një tjetër. Në këtë shembull, JavaScript konverton numrin `1` në string, në mënyrë që për funksionin të ketë kuptim dhe të kthejë një vlerë. Përgjatë mbledhjes të një tipi number (`1`) dhe një tipi string (`'2'`), numri trajtohet si string. Ne mund ti bashkojmë stringjet si `"Hello" + "World"`, kështu që ajo që po ndodh këtu është `"1" + "2"` e cila kthen "12"`. @@ -557,7 +555,7 @@ function getPersonInfo(one, two, three) { console.log(three); } -const person = "Lydia"; +const person = 'Lydia'; const age = 21; getPersonInfo`${person} is ${age} years old`; @@ -584,9 +582,9 @@ Nëse përdorni literale të shabllonit (template literals) të etiketuar, vlera ```javascript function checkAge(data) { if (data === { age: 18 }) { - console.log("You are an adult!"); + console.log('You are an adult!'); } else if (data == { age: 18 }) { - console.log("You are still an adult."); + console.log('You are still an adult.'); } else { console.log(`Hmm.. You don't have an age I guess`); } @@ -646,7 +644,7 @@ Parametri "rest" (`...args`) na lejon të "mbledhim" të gjitha argumentet e mbe ```javascript function getAge() { - "use strict"; + 'use strict'; age = 21; console.log(age); } @@ -674,7 +672,7 @@ Me `"use strict"`, mund të siguroheni se nuk do të deklaroni variabla globale ###### 21. Sa do të jetë vlera e `sum`? ```javascript -const sum = eval("10*10+5"); +const sum = eval('10*10+5'); ``` - A: `105` @@ -697,7 +695,7 @@ const sum = eval("10*10+5"); ###### 22. Sa kohë është e qasshme cool_secret? ```javascript -sessionStorage.setItem("cool_secret", 123); +sessionStorage.setItem('cool_secret', 123); ``` - A: Përgjithmonë, e dhëna nuk humb. @@ -750,12 +748,12 @@ Ju nuk mund ta bëni këtë me 'let' ose 'const' pasi ato kanë qasje në bllok ###### 24. Cila është vlera e saj? ```javascript -const obj = { 1: "a", 2: "b", 3: "c" }; +const obj = { 1: 'a', 2: 'b', 3: 'c' }; const set = new Set([1, 2, 3, 4, 5]); -obj.hasOwnProperty("1"); +obj.hasOwnProperty('1'); obj.hasOwnProperty(1); -set.has("1"); +set.has('1'); set.has(1); ``` @@ -781,7 +779,7 @@ Nuk funksionon në këtë mënyrë për një "set". Nuk ka asnjë `'1'` në set- ###### 25. Cila është vlera e saj? ```javascript -const obj = { a: "one", b: "two", a: "three" }; +const obj = { a: 'one', b: 'two', a: 'three' }; console.log(obj); ``` @@ -850,12 +848,12 @@ Deklarata `continue` kalon një iterim nëse një kusht i caktuar kthen `true`. ```javascript String.prototype.giveLydiaPizza = () => { - return "Just give Lydia pizza already!"; + return 'Just give Lydia pizza already!'; }; -const name = "Lydia"; +const name = 'Lydia'; -console.log(name.giveLydiaPizza()); +console.log(name.giveLydiaPizza()) ``` - A: `"Just give Lydia pizza already!"` @@ -879,8 +877,8 @@ console.log(name.giveLydiaPizza()); ```javascript const a = {}; -const b = { key: "b" }; -const c = { key: "c" }; +const b = { key: 'b' }; +const c = { key: 'c' }; a[b] = 123; a[c] = 456; @@ -912,9 +910,9 @@ Pastaj ne e printojmë `a[b]` e cila është `a["[object Object]"]`. We sapo e v ###### 30. Cila është vlera e saj? ```javascript -const foo = () => console.log("First"); -const bar = () => setTimeout(() => console.log("Second")); -const baz = () => console.log("Third"); +const foo = () => console.log('First'); +const bar = () => setTimeout(() => console.log('Second')); +const baz = () => console.log('Third'); bar(); foo(); @@ -967,7 +965,9 @@ Këtu fillon të funksionojë event loop. Një **event loop** shikon "stack" dhe ```html
- +
``` @@ -993,7 +993,9 @@ Elementi më thellë i mbivendosur që shkaktoi ngjarjen është objektivi i ngj ```html
-

Click here!

+

+ Click here! +

``` @@ -1017,7 +1019,7 @@ Nëse klikojmë `p`, shohim dy dalje: `p` dhe `div`. Gjatë "event propagation", ###### 33. Cila është vlera e saj? ```javascript -const person = { name: "Lydia" }; +const person = { name: 'Lydia' }; function sayHi(age) { return `${this.name} is ${age}`; @@ -1080,8 +1082,8 @@ FYI: `typeof` mund të kthejë listën e mëposhtme të vlerave: `undefined`, `b ```javascript 0; new Number(0); -(""); -(" "); +(''); +(' '); new Boolean(false); undefined; ``` @@ -1230,14 +1232,11 @@ Ajo që e dallon një tip primitiv nga një objekt është se primitivët nuk ka ###### 40. Cila është vlera e saj? ```javascript -[ - [0, 1], - [2, 3], -].reduce( +[[0, 1], [2, 3]].reduce( (acc, cur) => { return acc.concat(cur); }, - [1, 2] + [1, 2], ); ``` @@ -1264,7 +1263,7 @@ Pastaj, `[1, 2, 0, 1]` është `acc` dhe `[2, 3]` është `cur`. I bashkojmë at ```javascript !!null; -!!""; +!!''; !!1; ``` @@ -1292,7 +1291,7 @@ Pastaj, `[1, 2, 0, 1]` është `acc` dhe `[2, 3]` është `cur`. I bashkojmë at ###### 42. Çfarë do të kthejë në browser funksioni `setInterval`? ```javascript -setInterval(() => console.log("Hi"), 1000); +setInterval(() => console.log('Hi'), 1000); ``` - A: një id unike @@ -1315,7 +1314,7 @@ Kthen një id unike. Kjo id mund të përdoret për të pastruar intervalin me f ###### 43. Çfarë do të kthehet si rezultat? ```javascript -[..."Lydia"]; +[...'Lydia']; ``` - A: `["L", "y", "d", "i", "a"]` @@ -1335,7 +1334,7 @@ Stringu është i iterueshëm. Operatori i përhapjes (spread operator) iteron --- -###### 44. Cila është vlera e saj? +###### 44. Cila është vlera e saj? ```javascript function* generator(i) { @@ -1374,14 +1373,14 @@ Pastaj, ne e thirrim funksionin përsëri me metodën `next()`. Fillon dhe vazhd ```javascript const firstPromise = new Promise((res, rej) => { - setTimeout(res, 500, "one"); + setTimeout(res, 500, 'one'); }); const secondPromise = new Promise((res, rej) => { - setTimeout(res, 100, "two"); + setTimeout(res, 100, 'two'); }); -Promise.race([firstPromise, secondPromise]).then((res) => console.log(res)); +Promise.race([firstPromise, secondPromise]).then(res => console.log(res)); ``` - A: `"one"` @@ -1404,7 +1403,7 @@ Kur i kalojmë premtime (promises) të shumta metodës `Promise.race`, ajo zgjid ###### 46. Cila është vlera e saj? ```javascript -let person = { name: "Lydia" }; +let person = { name: 'Lydia' }; const members = [person]; person = null; @@ -1444,7 +1443,7 @@ Ne po e modifikojmë vetëm vlerën e variblës `person`, dhe jo të elementit t ```javascript const person = { - name: "Lydia", + name: 'Lydia', age: 21, }; @@ -1473,7 +1472,7 @@ Me unazën `for-in`, ne mund të iterojmë përgjatë çelësave të objektit, n ###### 48. Cila është vlera e saj? ```javascript -console.log(3 + 4 + "5"); +console.log(3 + 4 + '5'); ``` - A: `"345"` @@ -1500,7 +1499,7 @@ Radha e veprimeve matematikore të operatorit është rendi në të cilin përpi ###### 49. What's the value of `num`? ```javascript -const num = parseInt("7*6", 10); +const num = parseInt('7*6', 10); ``` - A: `42` @@ -1525,8 +1524,8 @@ Kthehen vetëm numrat e parë në string. Bazuar në _radix (bazë)_ (argumenti ###### 50. Cila është vlera e saj? ```javascript -[1, 2, 3].map((num) => { - if (typeof num === "number") return; +[1, 2, 3].map(num => { + if (typeof num === 'number') return; return num * 2; }); ``` @@ -1554,12 +1553,12 @@ Megjithatë, ne nuk kthejmë një vlerë. Kur nuk kthejmë një vlerë nga funks ```javascript function getInfo(member, year) { - member.name = "Lydia"; - year = "1998"; + member.name = 'Lydia'; + year = '1998'; } -const person = { name: "Sarah" }; -const birthYear = "1997"; +const person = { name: 'Sarah' }; +const birthYear = '1997'; getInfo(person, birthYear); @@ -1591,15 +1590,15 @@ Vlera e `person` është objekt. Argumenti `member` ka referencë (të kopjuar) ```javascript function greeting() { - throw "Hello world!"; + throw 'Hello world!'; } function sayHi() { try { const data = greeting(); - console.log("It worked!", data); + console.log('It worked!', data); } catch (e) { - console.log("Oh no an error:", e); + console.log('Oh no an error:', e); } } @@ -1629,8 +1628,8 @@ Me deklaratën `catch`, ne mund të specifikojmë se çfarë të bëjmë nëse n ```javascript function Car() { - this.make = "Lamborghini"; - return { make: "Maserati" }; + this.make = 'Lamborghini'; + return { make: 'Maserati' }; } const myCar = new Car(); @@ -1704,11 +1703,11 @@ class Dog { } } -Dog.prototype.bark = function () { +Dog.prototype.bark = function() { console.log(`Woof I am ${this.name}`); }; -const pet = new Dog("Mara"); +const pet = new Dog('Mara'); pet.bark(); @@ -1773,7 +1772,7 @@ export default counter; ```javascript // index.js -import myCounter from "./counter"; +import myCounter from './counter'; myCounter += 1; @@ -1802,7 +1801,7 @@ Kur tentojmë të rrisim vlerën e `myCounter`, do të marrim një error: `myCou ###### 58. Cila është vlera e saj? ```javascript -const name = "Lydia"; +const name = 'Lydia'; age = 21; console.log(delete name); @@ -1819,7 +1818,7 @@ console.log(delete age); #### Përgjigja: A -Operatori "delete" kthen një vlerë booleane: `true` në fshirje të suksesshme, përndryshe do të kthejë `false`. Megjithatë, variablat e deklaruara me fjalën kyçe `var`, `const` ose `let` nuk mund të fshihen duke përdorur operatorin `delete`. +Operatori "delete" kthen një vlerë booleane: `true` në fshirje të suksesshme, përndryshe do të kthejë `false`. Megjithatë, variablat e deklaruara me fjalën kyçe `var`, `const` ose `let` nuk mund të fshihen duke përdorur operatorin `delete`. Variabla `name` u deklarua me fjalën kyçe `const`, kështu që fshirja e saj nuk ishte e suksesshme: u kthye `false`. Kur vendosëm `age` të barabartë me `21`, ne në fakt shtuam një veti të quajtur `age` në objektin global. Ju mund të fshini me sukses vetitë nga objektet në këtë mënyrë, gjithashtu edhe objektin global, kështu që `delete age` kthen `true`. @@ -1873,7 +1872,7 @@ Kjo do të thotë se vlera e `y` është e barabartë me vlerën e parë në arr ###### 60. Cila është vlera e saj? ```javascript -const user = { name: "Lydia", age: 21 }; +const user = { name: 'Lydia', age: 21 }; const admin = { admin: true, ...user }; console.log(admin); @@ -1899,9 +1898,9 @@ console.log(admin); ###### 61. Cila është vlera e saj? ```javascript -const person = { name: "Lydia" }; +const person = { name: 'Lydia' }; -Object.defineProperty(person, "age", { value: 21 }); +Object.defineProperty(person, 'age', { value: 21 }); console.log(person); console.log(Object.keys(person)); @@ -1930,12 +1929,12 @@ Vetitë e shtuara duke përdorur metodën `defineProperty` janë të pandryshues ```javascript const settings = { - username: "lydiahallie", + username: 'lydiahallie', level: 19, health: 90, }; -const data = JSON.stringify(settings, ["level", "health"]); +const data = JSON.stringify(settings, ['level', 'health']); console.log(data); ``` @@ -1966,7 +1965,7 @@ Nëse zëvendësuesi është një _funksion_, ky funksion thirret në çdo veti let num = 10; const increaseNumber = () => num++; -const increasePassedNumber = (number) => number++; +const increasePassedNumber = number => number++; const num1 = increaseNumber(); const num2 = increasePassedNumber(num1); @@ -1987,7 +1986,7 @@ console.log(num2); Operatori unar `++` fillimisht kthen vlerën e operandit, pastaj e rrit vlerën e tij. Vlera e `num1` është `10`, meqenëse funksioni `increaseNumber` fillimisht kthen vlerën e `num`, e cila është `10`, dhe vetëm pastaj e rrit vlerën e `num`. -`num2` është `10`, pasi ne e kaluam `num1` si argument tek `increasePassedNumber`. `number` është i barabartë me `10`(vlera e `num1`). Përsëri, operatori unar `++` _së pari kthen_ vlerën e operandit, dhe pastaj rrit vlerën e tij. Vlera e `number` është `10`, kështu që `num2` është e barabartë me `10`. +`num2` është `10`, pasi ne e kaluam `num1` si argument tek `increasePassedNumber`. `number` është i barabartë me `10`(vlera e `num1`). Përsëri, operatori unar `++` _së pari kthen_ vlerën e operandit, dhe pastaj rrit vlerën e tij. Vlera e `number` është `10`, kështu që `num2` është e barabartë me `10`.

@@ -2123,12 +2122,12 @@ Klasa `Labrador` merr dy argumente, `name` meqenëse trashëgon klasën 'Dog', d ```javascript // index.js -console.log("running index.js"); -import { sum } from "./sum.js"; +console.log('running index.js'); +import { sum } from './sum.js'; console.log(sum(1, 2)); // sum.js -console.log("running sum.js"); +console.log('running sum.js'); export const sum = (a, b) => a + b; ``` @@ -2156,7 +2155,7 @@ Ky është një dallimi në mes `require()` në CommonJS dhe `import`! Me `requi ```javascript console.log(Number(2) === Number(2)); console.log(Boolean(false) === Boolean(false)); -console.log(Symbol("foo") === Symbol("foo")); +console.log(Symbol('foo') === Symbol('foo')); ``` - A: `true`, `true`, `false` @@ -2179,7 +2178,7 @@ console.log(Symbol("foo") === Symbol("foo")); ###### 69. Cila është vlera e saj? ```javascript -const name = "Lydia Hallie"; +const name = 'Lydia Hallie'; console.log(name.padStart(13)); console.log(name.padStart(2)); ``` @@ -2206,7 +2205,7 @@ Nëse argumenti i kaluar në metodën `padStart` është më i vogël se gjatës ###### 70. Cila është vlera e saj? ```javascript -console.log("🥑" + "💻"); +console.log('🥑' + '💻'); ``` - A: `"🥑💻"` @@ -2230,11 +2229,11 @@ Me operatorin `+`, ju mund të bashkoni vargjet. Në këtë rast, ne po bashkojm ```javascript function* startGame() { - const Përgjigja = yield "Do you love JavaScript?"; - if (Përgjigja !== "Yes") { + const Përgjigja = yield 'Do you love JavaScript?'; + if (Përgjigja !== 'Yes') { return "Oh wow... Guess we're done here"; } - return "JavaScript loves you back ❤️"; + return 'JavaScript loves you back ❤️'; } const game = startGame(); @@ -2272,7 +2271,7 @@ console.log(String.raw`Hello\nworld`); - A: `Hello world!` - B: `Hello`      `world` - C: `Hello\nworld` -- D: `Hello\n`      `world` +- D: `Hello\n`      `world`
Përgjigja

@@ -2302,7 +2301,7 @@ Në këtë rast, `Hello\nworld` do të printohet. ```javascript async function getData() { - return await Promise.resolve("I made it!"); + return await Promise.resolve('I made it!'); } const data = getData(); @@ -2339,7 +2338,7 @@ function addToList(item, list) { return list.push(item); } -const result = addToList("apple", ["banana"]); +const result = addToList('apple', ['banana']); console.log(result); ``` @@ -2399,7 +2398,7 @@ Meqenëse `shape` është e ngrirë dhe meqenëse vlera e `x` nuk është një o ###### 76. Cila është vlera e saj? ```javascript -const { firstName: myName } = { firstName: "Lydia" }; +const { firstName: myName } = { firstName: 'Lydia' }; console.log(firstName); ``` @@ -2417,7 +2416,7 @@ console.log(firstName); Duke përdorur [sintaksen e funksioneve destruktuese](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment) ne mund të targetojmë vlerat nga vargjet, ose vetitë nga objektet, në variabla të veçanta: ```javascript -const { firstName } = { firstName: "Lydia" }; +const { firstName } = { firstName: 'Lydia' }; // versioni i ES5: // var firstName = { firstName: 'Lydia' }.firstName; @@ -2427,7 +2426,7 @@ console.log(firstName); // "Lydia" Gjithashtu, një veti mund të targetohet nga një objekt dhe t'i caktohet një variableje me një emër të ndryshëm nga vetia e objektit: ```javascript -const { firstName: myName } = { firstName: "Lydia" }; +const { firstName: myName } = { firstName: 'Lydia' }; // versioni i ES5: // var myName = { firstName: 'Lydia' }.firstName; @@ -2437,20 +2436,21 @@ console.log(firstName); // Uncaught ReferenceError: firstName is not defined Prandaj, `firstName` nuk ekziston si variabël, kështu që tentimi për të qasur vlerën e saj do të ngrejë një `ReferenceError`. -**Shënim:** Kujdes nga vetitë e `global scope`: +**Shënim:** Kujdes nga vetitë e `global scope`: ```javascript -const { name: myName } = { name: "Lydia" }; +const { name: myName } = { name: 'Lydia' }; console.log(myName); // "lydia" console.log(name); // "" ----- Browser psh. Chrome console.log(name); // ReferenceError: name is not defined ----- NodeJS + ``` -Kurdo që JavaScript nuk mundet të gjejë një varibël në _current scope_, ngrihet në [Scope chain](https://github.com/getify/You-Dont-Know-JS/blob/2nd-ed/scope-closures/ch3.md) dhe kërkon për të dhe në qoftëse e arrin nivelin më të lartë të shtrirjes (the top-level scope), të quajtur **Global scope**, dhe ende nuk e gjen do të ngrejë `ReferenceError`. +Kurdo që JavaScript nuk mundet të gjejë një varibël në _current scope_, ngrihet në [Scope chain](https://github.com/getify/You-Dont-Know-JS/blob/2nd-ed/scope-closures/ch3.md) dhe kërkon për të dhe në qoftëse e arrin nivelin më të lartë të shtrirjes (the top-level scope), të quajtur __Global scope__, dhe ende nuk e gjen do të ngrejë `ReferenceError`. -- Në **Browsers** si _Chrome_, `name` është _vetia e shtrirjes globale e vjetëruar_. Në këtë shembull, kodi funksionon brenda _global scope_ dhe nuk ka asnjë variabël lokale të përcaktuar nga përdoruesi për `name`, prandaj ai kërkon _variables/properties_ të paracaktuara në shtrirjen globale, në këtë rast shfletuesve, ai kërkon përmes objektit `window`, dhe do të nxjerrë vlerën [window.name](https://developer.mozilla.org/en-US/docs/Web/API/Window/name) e cila është e barabartë me një varg **bosh**. -- Në **NodeJS**, nuk ka një veçori të tillë në objektin `global`, kështu që përpjekja për të iu qasur një variable joekzistente do të ngrejë një [ReferenceError](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/Not_defined). +- Në __Browsers__ si _Chrome_, `name` është _vetia e shtrirjes globale e vjetëruar_. Në këtë shembull, kodi funksionon brenda _global scope_ dhe nuk ka asnjë variabël lokale të përcaktuar nga përdoruesi për `name`, prandaj ai kërkon _variables/properties_ të paracaktuara në shtrirjen globale, në këtë rast shfletuesve, ai kërkon përmes objektit `window`, dhe do të nxjerrë vlerën [window.name](https://developer.mozilla.org/en-US/docs/Web/API/Window/name) e cila është e barabartë me një varg __bosh__. +- Në __NodeJS__, nuk ka një veçori të tillë në objektin `global`, kështu që përpjekja për të iu qasur një variable joekzistente do të ngrejë një [ReferenceError](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/Not_defined).

@@ -2482,12 +2482,12 @@ Funksioni `sum` _gjithmonë_ kthen të njëjtin rezultat. Nëse i kalojmë `1` d --- -###### 78. Cila është vlera e saj? +###### 78. Cila është vlera e saj? ```javascript const add = () => { const cache = {}; - return (num) => { + return num => { if (num in cache) { return `From cache! ${cache[num]}`; } else { @@ -2529,10 +2529,10 @@ Herën e tretë, ne kalojmë `5 * 2` te funksioni i cili llogaritet si `10`. Obj --- -###### 79. Cila është vlera e saj? +###### 79. Cila është vlera e saj? ```javascript -const myLifeSummedUp = ["☕", "💻", "🍷", "🍫"]; +const myLifeSummedUp = ['☕', '💻', '🍷', '🍫']; for (let item in myLifeSummedUp) { console.log(item); @@ -2559,14 +2559,14 @@ Me unazën _for-in_, ne mund të iterojmë në vetitë _e numërueshme_. Në nj Ku çelësat janë vetitë e numërueshme. `0` `1` `2` `3` printohet. -Me unazën _for-of_, ne mund të iterojmë mbi **iterables**. Një array është një "iterable". Kur iterojmë mbi array, variabla "item" është e barabartë me elementin mbi të cilin po iterojmë aktualisht, "☕"` `"💻"` `"🍷"` `"🍫"` printohet. +Me unazën _for-of_, ne mund të iterojmë mbi __iterables__. Një array është një "iterable". Kur iterojmë mbi array, variabla "item" është e barabartë me elementin mbi të cilin po iterojmë aktualisht, "☕"` `"💻"` `"🍷"` `"🍫"` printohet.

--- -###### 80. Cila është vlera e saj? +###### 80. Cila është vlera e saj? ```javascript const list = [1 + 2, 1 * 2, 1 / 2]; @@ -2592,7 +2592,7 @@ Elementi do të jetë i barabartë me vlerën e kthyer. `1 + 2` kthen `3`, `1 * --- -###### 81. Cila është vlera e saj? +###### 81. Cila është vlera e saj? ```javascript function sayHi(name) { @@ -2625,16 +2625,16 @@ Në këtë rast, nëse ne nuk kalojmë ndonjë vlerë ose e kalojmë `undefined` --- -###### 82. Cila është vlera e saj? +###### 82. Cila është vlera e saj? ```javascript -var status = "😎"; +var status = '😎'; setTimeout(() => { - const status = "😍"; + const status = '😍'; const data = { - status: "🥑", + status: '🥑', getStatus() { return this.status; }, @@ -2655,25 +2655,25 @@ setTimeout(() => { #### Përgjigja: B -Vlera e fjalës kyçe `this` varet nga vendi ku e përdorni. Në një **metodë**, si metoda `getStatus`, fjala kyçe `this` i referohet _objektit që i përket metoda_. Metoda i përket objektit `data`, kështu që `this` i referohet objektit `data`. Kur printojmë `this.status`, vetia `status` në objektin `data` printohet, që është `"🥑"`. +Vlera e fjalës kyçe `this` varet nga vendi ku e përdorni. Në një __metodë__, si metoda `getStatus`, fjala kyçe `this` i referohet _objektit që i përket metoda_. Metoda i përket objektit `data`, kështu që `this` i referohet objektit `data`. Kur printojmë `this.status`, vetia `status` në objektin `data` printohet, që është `"🥑"`. -Me metodën `call`, ne mund të ndryshojmë objektin të cilit i referohet fjala kyçe `this`. Në **funksione**, fjala kyçe `this` i referohet _objektit të cilit i përket funksioni_. Ne deklaruam funksionin `setTimeout` në objektin _global_, kështu që brenda funksionit `setTimeout`, fjala kyçe `this` i referohet objektit _global_. Në objektin global, ekziston një variabël e quajtur _status_ me vlerën `"😎"`. Kur printoni `this.status`, `"😎"` printohet. +Me metodën `call`, ne mund të ndryshojmë objektin të cilit i referohet fjala kyçe `this`. Në __funksione__, fjala kyçe `this` i referohet _objektit të cilit i përket funksioni_. Ne deklaruam funksionin `setTimeout` në objektin _global_, kështu që brenda funksionit `setTimeout`, fjala kyçe `this` i referohet objektit _global_. Në objektin global, ekziston një variabël e quajtur _status_ me vlerën `"😎"`. Kur printoni `this.status`, `"😎"` printohet.

--- -###### 83. Cila është vlera e saj? +###### 83. Cila është vlera e saj? ```javascript const person = { - name: "Lydia", + name: 'Lydia', age: 21, }; let city = person.city; -city = "Amsterdam"; +city = 'Amsterdam'; console.log(person); ``` @@ -2701,7 +2701,7 @@ Kur printojmë objektin `person`. objekti i pamodifikuar kthehet. --- -###### 84. Cila është vlera e saj? +###### 84. Cila është vlera e saj? ```javascript function checkAge(age) { @@ -2737,9 +2737,9 @@ Variablat e deklaruara me fjalët kyçe `const` dhe `let` janë të qasshme vet ###### 85. Çfarë lloj informacioni do të printohet? ```javascript -fetch("https://www.website.com/api/user/1") - .then((res) => res.json()) - .then((res) => console.log(res)); +fetch('https://www.website.com/api/user/1') + .then(res => res.json()) + .then(res => console.log(res)); ``` - A: Rezultati i metodës `fetch`. @@ -2793,7 +2793,7 @@ Kur vendosim `hasName` të barabartë me `name`, ju vendosni `hasName` të barab ###### 87. Cila është vlera e saj? ```javascript -console.log("I want pizza"[0]); +console.log('I want pizza'[0]); ``` - A: `"""` @@ -2848,11 +2848,11 @@ Në qoftëse provoni të vendosni një vlerë të paradefinuar të barabartë me ```javascript // module.js -export default () => "Hello world"; -export const name = "Lydia"; +export default () => 'Hello world'; +export const name = 'Lydia'; // index.js -import * as data from "./module"; +import * as data from './module'; console.log(data); ``` @@ -2885,7 +2885,7 @@ class Person { } } -const member = new Person("John"); +const member = new Person('John'); console.log(typeof member); ``` @@ -2934,7 +2934,7 @@ console.log(newList.push(5)); Metoda `.push` kthen _gjatësinë e re_ të array, jo vetë array! Duke vendosur `newList` të barabartë me `[1, 2, 3].push(4)`, e vendosim `newList` të barabartë me gjatësinë e re të array: `4`. -Pastaj, ne provojmë të përdorim metodën `.push` në `newList`. Meqenëse `newList` është vlera numerike e `4` ne nuk mund të përdorim metodën `.push`: do të ngrihet TypeError. +Pastaj, ne provojmë të përdorim metodën `.push` në `newList`. Meqenëse `newList` është vlera numerike e `4` ne nuk mund të përdorim metodën `.push`: do të ngrihet TypeError.

@@ -2945,7 +2945,7 @@ Pastaj, ne provojmë të përdorim metodën `.push` në `newList`. Meqenëse `ne ```javascript function giveLydiaPizza() { - return "Here is pizza!"; + return 'Here is pizza!'; } const giveLydiaChocolate = () => @@ -2976,7 +2976,7 @@ Funskionet e rregullta, të tillë si funksioni `giveLydiaPizza`, kanë vetinë ```javascript const person = { - name: "Lydia", + name: 'Lydia', age: 21, }; @@ -3035,7 +3035,7 @@ function getItems(fruitList, favoriteFruit, ...args) { return [...fruitList, ...args, favoriteFruit]; } -getItems(["banana", "apple"], "pear", "orange"); +getItems(['banana', 'apple'], 'pear', 'orange'); ``` Shembulli i mësipërm funskionon. Do të kthejë array `[ 'banana', 'apple', 'orange', 'pear' ]` @@ -3049,9 +3049,9 @@ Shembulli i mësipërm funskionon. Do të kthejë array `[ 'banana', 'apple', 'o ```javascript function nums(a, b) { - if (a > b) console.log("a is bigger"); - else console.log("b is bigger"); - return; + if (a > b) console.log('a is bigger'); + else console.log('b is bigger'); + return a + b; } @@ -3069,7 +3069,7 @@ console.log(nums(1, 2)); #### Përgjigja: B -Në JavaScript, nuk e duhet të e shkruajmë pikëpresjen `;` në mënyrë eksplicite, sidoqoftë makina e JavaScript prapë i vendos ato pas deklarimeve. Kjo quhet **Automatic Semicolon Insertion** (vendosja e pikëpresjes automatikisht). Një deklaratë për shembull mund të jetë variabla, ose fjalët kyçe si `throw`, `return`, `break` etj. +Në JavaScript, nuk e duhet të e shkruajmë pikëpresjen `;` në mënyrë eksplicite, sidoqoftë makina e JavaScript prapë i vendos ato pas deklarimeve. Kjo quhet __Automatic Semicolon Insertion__ (vendosja e pikëpresjes automatikisht). Një deklaratë për shembull mund të jetë variabla, ose fjalët kyçe si `throw`, `return`, `break` etj. Në këtë rast, ne shkruajtëm deklaratën `return`, dhe vlerën tjetër `a + b` në rresht të ri. Sidoqoftë, meqenëse është rresht i ri, makina nuk e di se në të vërtetë ajo është vlera që ne po dëshirojmë të kthejmë. Në vend se të e llogarisë në atë mënyrë, në mënyrë automatike vendoset `return`. Kjo mund të shikohet edhe si kjo sintaksë: @@ -3090,13 +3090,13 @@ Kjo do të thotë se `a + b` nuk arrihet asnjëherë, meqenëse funksioni ndalon ```javascript class Person { constructor() { - this.name = "Lydia"; + this.name = 'Lydia'; } } Person = class AnotherPerson { constructor() { - this.name = "Sarah"; + this.name = 'Sarah'; } }; @@ -3125,7 +3125,7 @@ Ne mund të iu shoqërojmë klasave konstruktorët e tjerë të klasave/funksion ```javascript const info = { - [Symbol("a")]: "b", + [Symbol('a')]: 'b', }; console.log(info); @@ -3142,9 +3142,9 @@ console.log(Object.keys(info)); #### Përgjigja: D -Një Symbol nuk është i _numërueshëm_. Metoda Object.keys kthen të gjithë çelësat e \_numërueshëm në një objekt. Symbol nuk do të jetë i dukshëm, dhe një array i zbrazët do të kthehet. Kur e printojmë objektin në tërësi, të gjitha vetitë janë të dukshme, edhe ato të cilat nuk janë te numërueshme. +Një Symbol nuk është i _numërueshëm_. Metoda Object.keys kthen të gjithë çelësat e _numërueshëm në një objekt. Symbol nuk do të jetë i dukshëm, dhe një array i zbrazët do të kthehet. Kur e printojmë objektin në tërësi, të gjitha vetitë janë të dukshme, edhe ato të cilat nuk janë te numërueshme. -Kjo është vetëm një nga shumë vetitë e symbol, përveç përfaqësimit të një vlere krejtësisht unike (e cila parandalon konflikt në emërtim të objekteve, për shembull kur punoni me 2 librari që duan të shtojnë vetitë në të njëjtin objekt), ju gjithashtu mund të "fshehni" vetitë e objekteve në këtë mënyrë (edhe pse jo plotësisht. Ju mund t'i qaseni simboleve duke përdorur metodën `Object.getOwnPropertySymbols()`). +Kjo është vetëm një nga shumë vetitë e symbol, përveç përfaqësimit të një vlere krejtësisht unike (e cila parandalon konflikt në emërtim të objekteve, për shembull kur punoni me 2 librari që duan të shtojnë vetitë në të njëjtin objekt), ju gjithashtu mund të "fshehni" vetitë e objekteve në këtë mënyrë (edhe pse jo plotësisht. Ju mund t'i qaseni simboleve duke përdorur metodën `Object.getOwnPropertySymbols()`).

@@ -3194,7 +3194,7 @@ Funskioni i meposhtëm do të kthente një objekt: ###### 99. Cila është vlera e saj? ```javascript -const name = "Lydia"; +const name = 'Lydia'; console.log(name()); ``` @@ -3226,8 +3226,8 @@ ReferenceErrors ngrihen kur Javascript-i nuk është në gjendje të gjejë refe ```javascript // 🎉✨ Kjo është pytja jonë e 100! ✨🎉 -const output = `${[] && "Im"}possible! -You should${"" && `n't`} see a therapist after so much JavaScript lol`; +const output = `${[] && 'Im'}possible! +You should${'' && `n't`} see a therapist after so much JavaScript lol`; ``` - A: `possible! You should see a therapist after so much JavaScript lol` @@ -3253,7 +3253,7 @@ You should${"" && `n't`} see a therapist after so much JavaScript lol`; ```javascript const one = false || {} || null; -const two = null || false || ""; +const two = null || false || ''; const three = [] || 0 || true; console.log(one, two, three); @@ -3285,16 +3285,16 @@ Me operatorin `||`, ne mund të kthejmë vlerën e parë "truthy" të operandit. ###### 102. Cila është vlera në dalje? ```javascript -const myPromise = () => Promise.resolve("I have resolved!"); +const myPromise = () => Promise.resolve('I have resolved!'); function firstFunction() { - myPromise().then((res) => console.log(res)); - console.log("second"); + myPromise().then(res => console.log(res)); + console.log('second'); } async function secondFunction() { console.log(await myPromise()); - console.log("second"); + console.log('second'); } firstFunction(); @@ -3332,8 +3332,8 @@ Kjo do të thotë se pret për `myPromise` të zgjidhet me vlerën `I have resol const set = new Set(); set.add(1); -set.add("Lydia"); -set.add({ name: "Lydia" }); +set.add('Lydia'); +set.add({ name: 'Lydia' }); for (let item of set) { console.log(item + 2); @@ -3393,13 +3393,13 @@ Në këtë rast, ne vetëm i kaluam si argument vlerën numerike `5`. Kthen prom ```javascript function compareMembers(person1, person2 = person) { if (person1 !== person2) { - console.log("Not the same!"); + console.log('Not the same!'); } else { - console.log("They are the same!"); + console.log('They are the same!'); } } -const person = { name: "Lydia" }; +const person = { name: 'Lydia' }; compareMembers(person); ``` @@ -3416,7 +3416,7 @@ compareMembers(person); Objektet vendosen si argumente në bazë të referencës së tyre. Kur i kontrollojmë objektet me operatorin për barazim strikt (`===`), ne po kontorllojmë referencën e tyre. -Ne e paracaktuam vlerën e `person2` të barabartë me objektin `person`, dhe e kaluam objektin `person` si vlerë të `person1`. +Ne e paracaktuam vlerën e `person2` të barabartë me objektin `person`, dhe e kaluam objektin `person` si vlerë të `person1`. Kjo do të thotë që të dy vlerat kanë referencë të e njejta hapësirë memorike, dhe kështu ato janë të barabarta. @@ -3438,7 +3438,7 @@ const colorConfig = { yellow: false, }; -const colors = ["pink", "red", "blue"]; +const colors = ['pink', 'red', 'blue']; console.log(colorConfig.colors[1]); ``` @@ -3467,7 +3467,7 @@ JavaScript i interpreton deklarimet. Kur përdorim notacionin me kllapa të mëd ###### 107. Cila është vlera e saj? ```javascript -console.log("❤️" === "❤️"); +console.log('❤️' === '❤️'); ``` - A: `true` @@ -3488,14 +3488,14 @@ Në prapavijë, emoji-t janë kode të veçanta. Unikodet për emoji-t e zemrës ###### 108. Cila nga këto metoda e modifikon array origjinal? ```javascript -const emojis = ["✨", "🥑", "😍"]; +const emojis = ['✨', '🥑', '😍']; -emojis.map((x) => x + "✨"); -emojis.filter((x) => x !== "🥑"); -emojis.find((x) => x !== "🥑"); -emojis.reduce((acc, cur) => acc + "✨"); -emojis.slice(1, 2, "✨"); -emojis.splice(1, 2, "✨"); +emojis.map(x => x + '✨'); +emojis.filter(x => x !== '🥑'); +emojis.find(x => x !== '🥑'); +emojis.reduce((acc, cur) => acc + '✨'); +emojis.slice(1, 2, '✨'); +emojis.splice(1, 2, '✨'); ``` - A: `All of them` @@ -3520,10 +3520,10 @@ Me motodën `splice`, ne modifikojmë array origjinal duke fshirë, zëvendësua ###### 109. Cila është vlera e saj? ```javascript -const food = ["🍕", "🍫", "🥑", "🍔"]; +const food = ['🍕', '🍫', '🥑', '🍔']; const info = { favoriteFood: food[0] }; -info.favoriteFood = "🍝"; +info.favoriteFood = '🍝'; console.log(food); ``` @@ -3577,7 +3577,7 @@ const jsonArray = JSON.stringify([1, 2, 3]); // '[1, 2, 3]' JSON.parse(jsonArray); // [1, 2, 3] // Stringifimi i një objekti në JSON valid, pastaj parsimi i JSON stringut në një vlerë të JavaScript: -const jsonArray = JSON.stringify({ name: "Lydia" }); // '{"name":"Lydia"}' +const jsonArray = JSON.stringify({ name: 'Lydia' }); // '{"name":"Lydia"}' JSON.parse(jsonArray); // { name: 'Lydia' } ``` @@ -3589,11 +3589,11 @@ JSON.parse(jsonArray); // { name: 'Lydia' } ###### 111. Cila është vlera e saj? ```javascript -let name = "Lydia"; +let name = 'Lydia'; function getName() { console.log(name); - let name = "Sarah"; + let name = 'Sarah'; } getName(); @@ -3616,7 +3616,7 @@ Variablat me fjalën kyçe `let` (dhe `const`) ngriten (hoistoh-en), por për da Nëse nuk do të kishim deklaruar `name` brenda funksionit `getName`, makina e JavaScript do të kishte shikuar poshtë _zingjirit të shtrirjes_. Fusha e jashtme ka variabël të quajtur `name` me vlerë `Lydia`. Në këtë rast, do të kishte printuat `Lydia`. ```javascript -let name = "Lydia"; +let name = 'Lydia'; function getName() { console.log(name); @@ -3634,11 +3634,11 @@ getName(); // Lydia ```javascript function* generatorOne() { - yield ["a", "b", "c"]; + yield ['a', 'b', 'c']; } function* generatorTwo() { - yield* ["a", "b", "c"]; + yield* ['a', 'b', 'c']; } const one = generatorOne(); @@ -3684,7 +3684,7 @@ console.log(two.next().value); // undefined ###### 113. Cila është vlera e saj? ```javascript -console.log(`${((x) => x)("I love")} to program`); +console.log(`${(x => x)('I love')} to program`); ``` - A: `I love to program` @@ -3709,7 +3709,7 @@ Shprehjet brenda shablloneve literale vlerësohen së pari. Kjo do të thotë q ```javascript let config = { alert: setInterval(() => { - console.log("Alert!"); + console.log('Alert!'); }, 1000), }; @@ -3728,7 +3728,7 @@ config = null; Zakonisht kur i vendosim objektet të barabarta me `null`, ato objekte mirren nga _garbage collector_ pasi nuk ka më referencë për ato objekte. Megjithatë, meqenëse funksioni callback brenda `setInterval` është një funksion me shigjetë (pra i lidhur me objektin `config`), funksioni callback ende mban një referencë për objektin `config`. Për sa kohë ka një referencë, objekti nuk do të merret nga 'garbage collector' (menaxhuesi i memories për të u larguar). -Meqenëse ky është një interval, vendosja e `config` në '`null` ose `delete` `config.alert` nuk do të mbledhet nga garbage-collector për intervalin, kështu që intervali do të vazhdojë të thirret. +Meqenëse ky është një interval, vendosja e `config` në '`null` ose `delete` `config.alert` nuk do të mbledhet nga garbage-collector për intervalin, kështu që intervali do të vazhdojë të thirret. Për ta hequr nga memoria duhet të e pastrojmë me `clearInterval(config.alert)`. Meqenëse nuk u fshi, funksioni `setInterval` callback do të vazhdojë të thirret çdo 1000ms (1s). @@ -3741,16 +3741,16 @@ Meqenëse nuk u fshi, funksioni `setInterval` callback do të vazhdojë të thir ```javascript const myMap = new Map(); -const myFunc = () => "greeting"; +const myFunc = () => 'greeting'; -myMap.set(myFunc, "Hello world!"); +myMap.set(myFunc, 'Hello world!'); //1 -myMap.get("greeting"); +myMap.get('greeting'); //2 myMap.get(myFunc); //3 -myMap.get(() => "greeting"); +myMap.get(() => 'greeting'); ``` - A: 1 @@ -3777,14 +3777,14 @@ Kur shtoni një çift çelës/vlerë duke përdorur metodën `set`, çelësi do ```javascript const person = { - name: "Lydia", + name: 'Lydia', age: 21, }; const changeAge = (x = { ...person }) => (x.age += 1); const changeAgeAndName = (x = { ...person }) => { x.age += 1; - x.name = "Sarah"; + x.name = 'Sarah'; }; changeAge(person); @@ -3843,7 +3843,7 @@ Me operatorin spread `...`, me mund të _përhapim_ iteruesit në elemente indiv ```javascript let num = 1; -const list = ["🥳", "🤠", "🥰", "🤪"]; +const list = ['🥳', '🤠', '🥰', '🤪']; console.log(list[(num += 1)]); ``` @@ -3869,11 +3869,11 @@ Me operandin `+=`, ne po rrisim vlerën e `sum` për `1`. `num` kishte vlerën i ```javascript const person = { - firstName: "Lydia", - lastName: "Hallie", + firstName: 'Lydia', + lastName: 'Hallie', pet: { - name: "Mara", - breed: "Dutch Tulip Hound", + name: 'Mara', + breed: 'Dutch Tulip Hound', }, getFullName() { return `${this.firstName} ${this.lastName}`; @@ -3911,10 +3911,10 @@ Me operatorin opsional të zinxhirit `?.`, nuk duhet të kontrollojmë më në m ###### 120. Cila është vlera e saj? ```javascript -const groceries = ["banana", "apple", "peanuts"]; +const groceries = ['banana', 'apple', 'peanuts']; -if (groceries.indexOf("banana")) { - console.log("We have to buy bananas!"); +if (groceries.indexOf('banana')) { + console.log('We have to buy bananas!'); } else { console.log(`We don't have to buy bananas!`); } @@ -3970,10 +3970,10 @@ Metoda `language` është metodë `setter` (vendosëse). Vendosësit nuk mbajë ###### 122. Cila është vlera e saj? ```javascript -const name = "Lydia Hallie"; +const name = 'Lydia Hallie'; -console.log(!typeof name === "object"); -console.log(!typeof name === "string"); +console.log(!typeof name === 'object'); +console.log(!typeof name === 'string'); ``` - A: `false` `true` @@ -3998,7 +3998,7 @@ console.log(!typeof name === "string"); ###### 123. Cila është vlera e saj? ```javascript -const add = (x) => (y) => (z) => { +const add = x => y => z => { console.log(x, y, z); return x + y + z; }; @@ -4016,7 +4016,7 @@ add(4)(5)(6); #### Përgjigja: A -Funksioni `add` kthen një funksion shigjete, i cili kthen një funksion shigjete, i cili kthen një funksion shigjete. Funksioni i parë merr një argument `x` me vlerën `4`. Ne e thërrasim funksionin e dytë, i cili merr një argument `y` me vlerën `5`. Pastaj thërrasim funksionin e tretë, i cili merr një argument `z` me vlerën `6`. Kur po provojmë të qasemi në vlerën `x`, `y` dhe `z` brenda funksionit të fundit të shigjetës, makina JS shkon lart në zinxhirin e shtrirjes për të gjetur vlerat për `x` dhe `y` përkatësisht. Kjo kthen `4` `5` `6`. +Funksioni `add` kthen një funksion shigjete, i cili kthen një funksion shigjete, i cili kthen një funksion shigjete. Funksioni i parë merr një argument `x` me vlerën `4`. Ne e thërrasim funksionin e dytë, i cili merr një argument `y` me vlerën `5`. Pastaj thërrasim funksionin e tretë, i cili merr një argument `z` me vlerën `6`. Kur po provojmë të qasemi në vlerën `x`, `y` dhe `z` brenda funksionit të fundit të shigjetës, makina JS shkon lart në zinxhirin e shtrirjes për të gjetur vlerat për `x` dhe `y` përkatësisht. Kjo kthen `4` `5` `6`.

@@ -4088,20 +4088,20 @@ myFunc(1, 2, 3); ```javascript function getFine(speed, amount) { - const formattedSpeed = new Intl.NumberFormat("en-US", { - style: "unit", - unit: "mile-per-hour", + const formattedSpeed = new Intl.NumberFormat('en-US', { + style: 'unit', + unit: 'mile-per-hour' }).format(speed); - const formattedAmount = new Intl.NumberFormat("en-US", { - style: "currency", - currency: "USD", + const formattedAmount = new Intl.NumberFormat('en-US', { + style: 'currency', + currency: 'USD' }).format(amount); return `The driver drove ${formattedSpeed} and has to pay ${formattedAmount}`; } -console.log(getFine(130, 300)); +console.log(getFine(130, 300)) ``` - A: The driver drove 130 and has to pay 300 @@ -4124,8 +4124,8 @@ Me metoden `Intl.NumberFormat`, ne mund të formatojmë vlerat numerike në çdo ###### 127. Cila është vlera e saj? ```javascript -const spookyItems = ["👻", "🎃", "🕸"]; -({ item: spookyItems[3] } = { item: "💀" }); +const spookyItems = ['👻', '🎃', '🕸']; +({ item: spookyItems[3] } = { item: '💀' }); console.log(spookyItems); ``` @@ -4150,7 +4150,7 @@ Duke destrukturuar objektet, ne mund të targetojmë vlerat nga objekti i djatht ###### 128. Cila është vlera e saj? ```javascript -const name = "Lydia Hallie"; +const name = 'Lydia Hallie'; const age = 21; console.log(Number.isNaN(name)); @@ -4186,7 +4186,7 @@ const randomValue = 21; function getInfo() { console.log(typeof randomValue); - const randomValue = "Lydia Hallie"; + const randomValue = 'Lydia Hallie'; } getInfo(); @@ -4212,7 +4212,7 @@ Variablat e deklaruara me fjalën kyçe `const` nuk janë të referueshme para i ###### 130. Cila është vlera e saj? ```javascript -const myPromise = Promise.resolve("Woah some cool data"); +const myPromise = Promise.resolve('Woah some cool data'); (async () => { try { @@ -4220,7 +4220,7 @@ const myPromise = Promise.resolve("Woah some cool data"); } catch { throw new Error(`Oops didn't work`); } finally { - console.log("Oh finally!"); + console.log('Oh finally!'); } })(); ``` @@ -4245,7 +4245,7 @@ Në bllokun `try`, ne jemi duke printuar vlerën e pritur të variablës `myProm ###### 131. Cila është vlera e saj? ```javascript -const emojis = ["🥑", ["✨", "✨", ["🍕", "🍕"]]]; +const emojis = ['🥑', ['✨', '✨', ['🍕', '🍕']]]; console.log(emojis.flat(1)); ``` @@ -4318,19 +4318,19 @@ Ne thërrasim `counterTwo.increment()`, i cili vendos `count` në `3`. Pastaj, p ###### 133. Cila është vlera e saj? ```javascript -const myPromise = Promise.resolve(Promise.resolve("Promise")); +const myPromise = Promise.resolve(Promise.resolve('Promise')); function funcOne() { - setTimeout(() => console.log("Timeout 1!"), 0); - myPromise.then((res) => res).then((res) => console.log(`${res} 1!`)); - console.log("Last line 1!"); + setTimeout(() => console.log('Timeout 1!'), 0); + myPromise.then(res => res).then(res => console.log(`${res} 1!`)); + console.log('Last line 1!'); } async function funcTwo() { const res = await myPromise; - console.log(`${res} 2!`); - setTimeout(() => console.log("Timeout 2!"), 0); - console.log("Last line 2!"); + console.log(`${res} 2!`) + setTimeout(() => console.log('Timeout 2!'), 0); + console.log('Last line 2!'); } funcOne(); @@ -4375,7 +4375,7 @@ export default function sum(x) { } // index.js -import * as sum from "./sum"; +import * as sum from './sum'; ``` - A: `sum(4)` @@ -4392,12 +4392,12 @@ Me yllin `*`, ne importojmë të gjitha vlerat e eksportuara nga ai fajll, si at ```javascript // info.js -export const name = "Lydia"; +export const name = 'Lydia'; export const age = 21; -export default "I love JavaScript"; +export default 'I love JavaScript'; // index.js -import * as info from "./info"; +import * as info from './info'; console.log(info); ``` @@ -4428,13 +4428,13 @@ Mund të e thërrasim këtë funksion, duke thirrur `sum.default` ```javascript const handler = { - set: () => console.log("Added a new property!"), - get: () => console.log("Accessed a property!"), + set: () => console.log('Added a new property!'), + get: () => console.log('Accessed a property!'), }; const person = new Proxy({}, handler); -person.name = "Lydia"; +person.name = 'Lydia'; person.name; ``` @@ -4464,7 +4464,7 @@ Pastaj, ne i qasemi një vlerë të vetisë në objektin proxy, vetia `get` në ###### 136. Cili nga opsionet e mëposhtme do të modifikojë objektin `person`? ```javascript -const person = { name: "Lydia Hallie" }; +const person = { name: 'Lydia Hallie' }; Object.seal(person); ``` @@ -4492,9 +4492,9 @@ Megjithatë, ju ende mund të modifikoni vlerën e vetive ekzistuese. ```javascript const person = { - name: "Lydia Hallie", + name: 'Lydia Hallie', address: { - street: "100 Main St", + street: '100 Main St', }, }; @@ -4523,7 +4523,7 @@ Megjithatë, ajo vetëm _ngrin sipërfaqësisht_ objektin, që do të thotë se ###### 138. Cila është vlera e saj? ```javascript -const add = (x) => x + x; +const add = x => x + x; function myFunc(num = 2, value = add(num)) { console.log(num, value); @@ -4556,21 +4556,21 @@ Më pas, ne thirrëm `myFunc(3)` dhe kaluam vlerën `3` si vlerë për argumenti ```javascript class Counter { - #number = 10; + #number = 10 increment() { - this.#number++; + this.#number++ } getNum() { - return this.#number; + return this.#number } } -const counter = new Counter(); -counter.increment(); +const counter = new Counter() +counter.increment() -console.log(counter.#number); +console.log(counter.#number) ``` - A: `10` @@ -4594,8 +4594,8 @@ Në ES2020, mund të shtojmë variabla private në klasa duke përdorur `#`. Nuk ```javascript const teams = [ - { name: "Team 1", members: ["Paul", "Lisa"] }, - { name: "Team 2", members: ["Laura", "Tim"] }, + { name: 'Team 1', members: ['Paul', 'Lisa'] }, + { name: 'Team 2', members: ['Laura', 'Tim'] }, ]; function* getMembers(members) { @@ -4638,8 +4638,8 @@ Nëse do të shkruanim `yield`, `return yield`, ose `return`, gjithë funksioni ```javascript const person = { - name: "Lydia Hallie", - hobbies: ["coding"], + name: 'Lydia Hallie', + hobbies: ['coding'], }; function addHobby(hobby, hobbies = person.hobbies) { @@ -4647,9 +4647,9 @@ function addHobby(hobby, hobbies = person.hobbies) { return hobbies; } -addHobby("running", []); -addHobby("dancing"); -addHobby("baking", person.hobbies); +addHobby('running', []); +addHobby('dancing'); +addHobby('baking', person.hobbies); console.log(person.hobbies); ``` @@ -4718,11 +4718,11 @@ Krijojmë variablën `pet` që është një instancë e klasës `Flamingo`. Kur ###### 143. Cila nga opsionet rezulton me gabim? ```javascript -const emojis = ["🎄", "🎅🏼", "🎁", "⭐"]; +const emojis = ['🎄', '🎅🏼', '🎁', '⭐']; -/* 1 */ emojis.push("🦌"); +/* 1 */ emojis.push('🦌'); /* 2 */ emojis.splice(0, 2); -/* 3 */ emojis = [...emojis, "🥂"]; +/* 3 */ emojis = [...emojis, '🥂']; /* 4 */ emojis.length = 0; ``` @@ -4777,11 +4777,11 @@ Objektet nuk janë të paraprakisht të iterueshme. Një objekt është i iterue let count = 0; const nums = [0, 1, 2, 3]; -nums.forEach((num) => { - if (num) count += 1; -}); +nums.forEach(num => { + if (num) count += 1 +}) -console.log(count); +console.log(count) ``` - A: 1 @@ -4805,12 +4805,12 @@ Kushti `if` brenda ciklit `forEach` kontrollon nëse vlera e `num` është e vë ```javascript function getFruit(fruits) { - console.log(fruits?.[1]?.[1]); + console.log(fruits?.[1]?.[1]) } -getFruit([["🍊", "🍌"], ["🍍"]]); -getFruit(); -getFruit([["🍍"], ["🍊", "🍌"]]); +getFruit([['🍊', '🍌'], ['🍍']]) +getFruit() +getFruit([['🍍'], ['🍊', '🍌']]) ``` - A: `null`, `undefined`, 🍌 @@ -4825,7 +4825,7 @@ getFruit([["🍍"], ["🍊", "🍌"]]); Simboli ? na lejon të i qasemi opsionalisht vetive më të thella brenda objekteve. Ne po provojmë të shfaqim elementin në indeksin 1 brenda në nën-array që është në indeksin 1 të array fruits. Nëse nën-array në indeksin 1 në array fruits nuk ekziston, thjesht do të kthejë undefined. Nëse nën-array në indeksin 1 në vargun fruits ekziston, por ky nën-array nuk ka një artikull në indeksin e tij 1, gjithashtu do të kthejë undefined. -Së pari, ne po përpiqemi të printojmë artikullin e dytë në nën-array `['🍍']` të `[['🍊', '🍌'], ['🍍']]`. Ky nën-array përmban vetëm një element, që do të thotë se nuk ka element në indeksin `1`, dhe kthen `undefined`. +Së pari, ne po përpiqemi të printojmë artikullin e dytë në nën-array `['🍍']` të `[['🍊', '🍌'], ['🍍']]`. Ky nën-array përmban vetëm një element, që do të thotë se nuk ka element në indeksin `1`, dhe kthen `undefined`. Më pas, ne po thërrasim funksionin `getFruits` pa kaluar një vlerë si argument, që do të thotë se `fruits` ka vlerë `undefined` të paracaktuar. Pasi që po lidhim në mënyrë kushtëzuese elementin në indeksin `1` të `fruits`, kthen `undefined` pasi ky element në indeksin `1` nuk ekziston. @@ -4840,19 +4840,19 @@ Së fundmi, po përpiqemi të shfaqim artikullin e dytë në nën-array `['🍊' ```javascript class Calc { - constructor() { - this.count = 0; - } + constructor() { + this.count = 0 + } - increase() { - this.count++; - } + increase() { + this.count ++ + } } -const calc = new Calc(); -new Calc().increase(); +const calc = new Calc() +new Calc().increase() -console.log(calc.count); +console.log(calc.count) ``` - A: `0` @@ -4876,25 +4876,25 @@ Ne i caktojmë variablës `calc` të jetë e barabartë me një instancë të re ```javascript const user = { - email: "e@mail.com", - password: "12345", -}; + email: "e@mail.com", + password: "12345" +} const updateUser = ({ email, password }) => { - if (email) { - Object.assign(user, { email }); - } + if (email) { + Object.assign(user, { email }) + } - if (password) { - user.password = password; - } + if (password) { + user.password = password + } - return user; -}; + return user +} -const updatedUser = updateUser({ email: "new@email.com" }); +const updatedUser = updateUser({ email: "new@email.com" }) -console.log(updatedUser === user); +console.log(updatedUser === user) ``` - A: `false` @@ -4917,13 +4917,13 @@ Funksioni `updateUser` përditëson vlerat e vetive `email` dhe `password` në u ###### 149. Cila është vlera e saj? ```javascript -const fruit = ["🍌", "🍊", "🍎"]; +const fruit = ['🍌', '🍊', '🍎'] -fruit.slice(0, 1); -fruit.splice(0, 1); -fruit.unshift("🍇"); +fruit.slice(0, 1) +fruit.splice(0, 1) +fruit.unshift('🍇') -console.log(fruit); +console.log(fruit) ``` - A: `['🍌', '🍊', '🍎']` @@ -4949,13 +4949,13 @@ Në fund, ne thirrim metodën `unshift` në array e frutave, e cila modifikon ar ```javascript const animals = {}; -let dog = { emoji: "🐶" }; -let cat = { emoji: "🐈" }; +let dog = { emoji: '🐶' } +let cat = { emoji: '🐈' } -animals[dog] = { ...dog, name: "Mara" }; -animals[cat] = { ...cat, name: "Sara" }; +animals[dog] = { ...dog, name: "Mara" } +animals[cat] = { ...cat, name: "Sara" } -console.log(animals[dog]); +console.log(animals[dog]) ``` - A: `{ emoji: "🐶", name: "Mara" }` @@ -4985,14 +4985,14 @@ Duke printuar `animals[dog]`, ose në fakt `animals["object Object"]` pasi që k ```javascript const user = { - email: "my@email.com", - updateEmail: (email) => { - this.email = email; - }, -}; + email: "my@email.com", + updateEmail: email => { + this.email = email + } +} -user.updateEmail("new@email.com"); -console.log(user.email); +user.updateEmail("new@email.com") +console.log(user.email) ``` - A: `my@email.com` @@ -5015,20 +5015,20 @@ Funksioni `updateEmail` është një funksion shigjetë dhe nuk është i lidhur ###### 152. Cila është vlera e saj? ```javascript -const promise1 = Promise.resolve("First"); -const promise2 = Promise.resolve("Second"); -const promise3 = Promise.reject("Third"); -const promise4 = Promise.resolve("Fourth"); +const promise1 = Promise.resolve('First') +const promise2 = Promise.resolve('Second') +const promise3 = Promise.reject('Third') +const promise4 = Promise.resolve('Fourth') const runPromises = async () => { - const res1 = await Promise.all([promise1, promise2]); - const res2 = await Promise.all([promise3, promise4]); - return [res1, res2]; -}; + const res1 = await Promise.all([promise1, promise2]) + const res2 = await Promise.all([promise3, promise4]) + return [res1, res2] +} runPromises() - .then((res) => console.log(res)) - .catch((err) => console.log(err)); + .then(res => console.log(res)) + .catch(err => console.log(err)) ``` - A: `[['First', 'Second'], ['Fourth']]` @@ -5051,16 +5051,13 @@ Metoda `Promise.all` ekzekuton premtimet e dhëna si argumente paralelisht. Nës ###### 153. Cila duhet të jetë vlera e `method` për të printuar `{ name: "Lydia", age: 22 }`? ```javascript -const keys = ["name", "age"]; -const values = ["Lydia", 22]; +const keys = ["name", "age"] +const values = ["Lydia", 22] -const method = - /* ?? */ - Object[method]( - keys.map((_, i) => { - return [keys[i], values[i]]; - }) - ); // { name: "Lydia", age: 22 } +const method = /* ?? */ +Object[method](keys.map((_, i) => { + return [keys[i], values[i]] +})) // { name: "Lydia", age: 22 } ``` - A: `entries` @@ -5073,7 +5070,7 @@ const method = #### Përgjigja: C -Metoda `fromEntries` transformon një array 2d në një objekt. Elementi i parë në çdo nën-array do të jetë çelësi, dhe elementi i dytë në çdo nën-array do të jetë vlera. Në këtë rast, ne jemi duke mapuar mbi array `keys`, i cili kthen një array ku elementi i parë është elementi në array të çelësave në indeksin aktual, dhe elementi i dytë është elementi i vlerave të array në indeksin aktual. +Metoda `fromEntries` transformon një array 2d në një objekt. Elementi i parë në çdo nën-array do të jetë çelësi, dhe elementi i dytë në çdo nën-array do të jetë vlera. Në këtë rast, ne jemi duke mapuar mbi array `keys`, i cili kthen një array ku elementi i parë është elementi në array të çelësave në indeksin aktual, dhe elementi i dytë është elementi i vlerave të array në indeksin aktual. Kjo krijon një array të nën-arrays që përmbajnë çelësat dhe vlerat e duhura, të cilat rezultojnë në `{ name: "Lydia", age: 22 }` @@ -5085,18 +5082,18 @@ Kjo krijon një array të nën-arrays që përmbajnë çelësat dhe vlerat e duh ###### 154. Cila është vlera e saj? ```javascript -const createMember = ({ email, address = {} }) => { - const validEmail = /.+\@.+\..+/.test(email); - if (!validEmail) throw new Error("Valid email pls"); +const createMember = ({ email, address = {}}) => { + const validEmail = /.+\@.+\..+/.test(email) + if (!validEmail) throw new Error("Valid email pls") - return { - email, - address: address ? address : null, - }; -}; + return { + email, + address: address ? address : null + } +} -const member = createMember({ email: "my@email.com" }); -console.log(member); +const member = createMember({ email: "my@email.com" }) +console.log(member) ``` - A: `{ email: "my@email.com", address: null }` @@ -5119,13 +5116,13 @@ Vlera e paracaktuar e `address` është një objekt i zbrazët `{}`. Kur vendos ###### 155. Cila është vlera e saj? ```javascript -let randomValue = { name: "Lydia" }; -randomValue = 23; +let randomValue = { name: "Lydia" } +randomValue = 23 if (!typeof randomValue === "string") { - console.log("It's not a string!"); + console.log("It's not a string!") } else { - console.log("Yay it's a string!"); + console.log("Yay it's a string!") } ``` diff --git a/th-TH/README.md b/th-TH/README.md index edcb70ce..22550eb2 100644 --- a/th-TH/README.md +++ b/th-TH/README.md @@ -16,8 +16,8 @@ -ลิสต์ภาษาอื่นๆ: +ลิสต์ภาษาอื่นๆ: - [🇸🇦 العربية](../ar-AR/README_AR.md) - [🇪🇬 اللغة العامية](../ar-EG/README_ar-EG.md) - [🇧🇦 Bosanski](../bs-BS/README-bs_BS.md) @@ -32,7 +32,6 @@ - [🇳🇱 Nederlands](../nl-NL/README.md) - [🇵🇱 Polski](../pl-PL/README.md) - [🇧🇷 Português Brasil](../pt-BR/README_pt_BR.md) -- [🇷o Română](../ro-RO/README.ro.md) - [🇷🇺 Русский](../ru-RU/README.md) - [🇽🇰 Shqip](../sq-KS/README_sq_KS.md) - [🇹🇷 Türkçe](../tr-TR/README-tr_TR.md) @@ -41,6 +40,7 @@ - [🇨🇳 简体中文](../zh-CN/README-zh_CN.md) - [🇹🇼 繁體中文](../zh-TW/README_zh-TW.md) + --- ###### 1. ผลลัพธ์ที่ได้คืออะไร? @@ -113,7 +113,7 @@ const shape = { diameter() { return this.radius * 2; }, - perimeter: () => 2 * Math.PI * this.radius, + perimeter: () => 2 * Math.PI * this.radius }; console.log(shape.diameter()); @@ -170,12 +170,12 @@ String `'Lydia'` เป็นค่าความจริง สิ่งท ```javascript const bird = { - size: "small", + size: "small" }; const mouse = { name: "Mickey", - small: true, + small: true }; ``` @@ -202,6 +202,7 @@ JavaScript interprets (or unboxes) statements. เมื่อเราใช้ --- + ###### 6. ผลลัพธ์ที่ได้คืออะไร? ```javascript @@ -369,7 +370,7 @@ function Person(firstName, lastName) { } const member = new Person("Lydia", "Hallie"); -Person.getFullName = function () { +Person.getFullName = function() { return `${this.firstName} ${this.lastName}`; }; @@ -389,7 +390,7 @@ console.log(member.getFullName()); You can't add properties to a constructor like you can with regular objects. If you want to add a feature to all objects at once, you have to use the prototype instead. So in this case, ```js -Person.prototype.getFullName = function () { +Person.prototype.getFullName = function() { return `${this.firstName} ${this.lastName}`; }; ``` @@ -845,7 +846,7 @@ String.prototype.giveLydiaPizza = () => { const name = "Lydia"; -console.log(name.giveLydiaPizza()); +console.log(name.giveLydiaPizza()) ``` - A: `"Just give Lydia pizza already!"` @@ -957,7 +958,9 @@ This is where an event loop starts to work. An **event loop** looks at the stack ```html
- +
``` @@ -983,7 +986,9 @@ The deepest nested element that caused the event is the target of the event. You ```html
-

Click here!

+

+ Click here! +

``` @@ -1059,7 +1064,6 @@ console.log(typeof sayHi()); The `sayHi` function returns the returned value of the immediately invoked function (IIFE). This function returned `0`, which is type `"number"`. FYI: there are only 7 built-in types: `null`, `undefined`, `boolean`, `number`, `string`, `object`, `symbol`, และ `bigint`. `"function"` is not a type, since functions are objects, it's of type `"object"`. -

@@ -1218,10 +1222,7 @@ What differentiates a primitive from an object is that primitives do not have an ###### 40. ผลลัพธ์ที่ได้คืออะไร? ```javascript -[ - [0, 1], - [2, 3], -].reduce( +[[0, 1], [2, 3]].reduce( (acc, cur) => { return acc.concat(cur); }, @@ -1369,7 +1370,7 @@ const secondPromise = new Promise((res, rej) => { setTimeout(res, 100, "two"); }); -Promise.race([firstPromise, secondPromise]).then((res) => console.log(res)); +Promise.race([firstPromise, secondPromise]).then(res => console.log(res)); ``` - A: `"one"` @@ -1433,7 +1434,7 @@ We are only modifying the value of the `person` variable, and not the first elem ```javascript const person = { name: "Lydia", - age: 21, + age: 21 }; for (const item in person) { @@ -1513,7 +1514,7 @@ Only the first numbers in the string is returned. Based on the _radix_ (the seco ###### 50. ผลลัพธ์ที่ได้คืออะไร? ```javascript -[1, 2, 3].map((num) => { +[1, 2, 3].map(num => { if (typeof num === "number") return; return num * 2; }); @@ -1690,7 +1691,7 @@ class Dog { } } -Dog.prototype.bark = function () { +Dog.prototype.bark = function() { console.log(`Woof I am ${this.name}`); }; @@ -1918,7 +1919,7 @@ Properties added using the `defineProperty` method are immutable by default. You const settings = { username: "lydiahallie", level: 19, - health: 90, + health: 90 }; const data = JSON.stringify(settings, ["level", "health"]); @@ -1952,7 +1953,7 @@ If the replacer is a _function_, this function gets called on every property in let num = 10; const increaseNumber = () => num++; -const increasePassedNumber = (number) => number++; +const increasePassedNumber = number => number++; const num1 = increaseNumber(); const num2 = increasePassedNumber(num1); @@ -2009,9 +2010,9 @@ In ES6, we can initialize parameters with a default value. The value of the para The default argument is evaluated at _call time_! Every time we call the function, a _new_ object is created. We invoke the `multiply` function the first two times without passing a value: `x` has the default value of `{ number: 10 }`. We then log the multiplied value of that number, which is `20`. -The third time we invoke multiply, we do pass an argument: the object called `value`. The `*=` operator is actually shorthand for `x.number = x.number * 2`: we modify the value of `x.number`, and log the multiplied value `20`. +The third time we invoke multiply, we do pass an argument: the object called `value`. The `*=` operator is actually shorthand for `x.number = x.number * 2`: we modify the value of `x.number`, and log the multiplied value `20`. -The fourth time, we pass the `value` object again. `x.number` was previously modified to `20`, so `x.number *= 2` logs `40`. +The fourth time, we pass the `value` object again. `x.number` was previously modified to `20`, so `x.number *= 2` logs `40`.

@@ -2034,18 +2035,17 @@ The fourth time, we pass the `value` object again. `x.number` was previously mod #### คำตอบ: D -The first argument that the `reduce` method receives is the _accumulator_, `x` in this case. The second argument is the _current value_, `y`. With the reduce method, we execute a callback function on every element in the array, which could ultimately result in one single value. +The first argument that the `reduce` method receives is the _accumulator_, `x` in this case. The second argument is the _current value_, `y`. With the reduce method, we execute a callback function on every element in the array, which could ultimately result in one single value. In this example, we are not returning any values, we are simply logging the values of the accumulator and the current value. The value of the accumulator is equal to the previously returned value of the callback function. If you don't pass the optional `initialValue` argument to the `reduce` method, the accumulator is equal to the first element on the first call. -On the first call, the accumulator (`x`) is `1`, and the current value (`y`) is `2`. We don't return from the callback function, we log the accumulator and current value: `1` และ `2` get logged. +On the first call, the accumulator (`x`) is `1`, and the current value (`y`) is `2`. We don't return from the callback function, we log the accumulator and current value: `1` และ `2` get logged. -If you don't return a value from a function, it returns `undefined`. On the next call, the accumulator is `undefined`, and the current value is `3`. `undefined` และ `3` get logged. +If you don't return a value from a function, it returns `undefined`. On the next call, the accumulator is `undefined`, and the current value is `3`. `undefined` และ `3` get logged. On the fourth call, we again don't return from the callback function. The accumulator is again `undefined`, and the current value is `4`. `undefined` และ `4` get logged. -

@@ -2061,7 +2061,7 @@ class Dog { }; class Labrador extends Dog { - // 1 + // 1 constructor(name, size) { this.size = size; } @@ -2075,7 +2075,7 @@ class Labrador extends Dog { super(name); this.size = size; } - // 4 + // 4 constructor(name, size) { this.name = name; this.size = size; @@ -2096,10 +2096,9 @@ class Labrador extends Dog { In a derived class, you cannot access the `this` keyword before calling `super`. If you try to do that, it will throw a ReferenceError: 1 and 4 would throw a reference error. -With the `super` keyword, we call that parent class's constructor with the given arguments. The parent's constructor receives the `name` argument, so we need to pass `name` to `super`. - -The `Labrador` class receives two arguments, `name` since it extends `Dog`, และ `size` as an extra property on the `Labrador` class. They both need to be passed to the constructor function on `Labrador`, which is done correctly using constructor 2. +With the `super` keyword, we call that parent class's constructor with the given arguments. The parent's constructor receives the `name` argument, so we need to pass `name` to `super`. +The `Labrador` class receives two arguments, `name` since it extends `Dog`, และ `size` as an extra property on the `Labrador` class. They both need to be passed to the constructor function on `Labrador`, which is done correctly using constructor 2.

@@ -2109,12 +2108,12 @@ The `Labrador` class receives two arguments, `name` since it extends `Dog`, แ ```javascript // index.js -console.log("running index.js"); -import { sum } from "./sum.js"; +console.log('running index.js'); +import { sum } from './sum.js'; console.log(sum(1, 2)); // sum.js -console.log("running sum.js"); +console.log('running sum.js'); export const sum = (a, b) => a + b; ``` @@ -2130,7 +2129,7 @@ export const sum = (a, b) => a + b; With the `import` keyword, all imported modules are _pre-parsed_. This means that the imported modules get run _first_, the code in the file which imports the module gets executed _after_. -This is a difference between `require()` in CommonJS and `import`! With `require()`, you can load dependencies on demand while the code is being run. If we would have used `require` instead of `import`, `running index.js`, `running sum.js`, `3` would have been logged to the console. +This is a difference between `require()` in CommonJS and `import`! With `require()`, you can load dependencies on demand while the code is being run. If we would have used `require` instead of `import`, `running index.js`, `running sum.js`, `3` would have been logged to the console.

@@ -2140,9 +2139,9 @@ This is a difference between `require()` in CommonJS and `import`! With `require ###### 68. ผลลัพธ์ที่ได้คืออะไร? ```javascript -console.log(Number(2) === Number(2)); -console.log(Boolean(false) === Boolean(false)); -console.log(Symbol("foo") === Symbol("foo")); +console.log(Number(2) === Number(2)) +console.log(Boolean(false) === Boolean(false)) +console.log(Symbol('foo') === Symbol('foo')) ``` - A: `true`, `true`, `false` @@ -2155,7 +2154,7 @@ console.log(Symbol("foo") === Symbol("foo")); #### คำตอบ: A -Every Symbol is entirely unique. The purpose of the argument passed to the Symbol is to give the Symbol a description. The value of the Symbol is not dependent on the passed argument. As we test equality, we are creating two entirely new symbols: the first `Symbol('foo')`, and the second `Symbol('foo')`. These two values are unique and not equal to each other, `Symbol('foo') === Symbol('foo')` returns `false`. +Every Symbol is entirely unique. The purpose of the argument passed to the Symbol is to give the Symbol a description. The value of the Symbol is not dependent on the passed argument. As we test equality, we are creating two entirely new symbols: the first `Symbol('foo')`, and the second `Symbol('foo')`. These two values are unique and not equal to each other, `Symbol('foo') === Symbol('foo')` returns `false`.

@@ -2165,15 +2164,15 @@ Every Symbol is entirely unique. The purpose of the argument passed to the Symbo ###### 69. ผลลัพธ์ที่ได้คืออะไร? ```javascript -const name = "Lydia Hallie"; -console.log(name.padStart(13)); -console.log(name.padStart(2)); +const name = "Lydia Hallie" +console.log(name.padStart(13)) +console.log(name.padStart(2)) ``` - A: `"Lydia Hallie"`, `"Lydia Hallie"` - B: `" Lydia Hallie"`, `" Lydia Hallie"` (`"[13x whitespace]Lydia Hallie"`, `"[2x whitespace]Lydia Hallie"`) - C: `" Lydia Hallie"`, `"Lydia Hallie"` (`"[1x whitespace]Lydia Hallie"`, `"Lydia Hallie"`) -- D: `"Lydia Hallie"`, `"Lyd"`, +- D: `"Lydia Hallie"`, `"Lyd"`,
คำตอบ

@@ -2441,7 +2440,7 @@ The `sum` function always returns the same result. If we pass `1` และ `2`, ```javascript const add = () => { const cache = {}; - return (num) => { + return num => { if (num in cache) { return `From cache! ${cache[num]}`; } else { @@ -2486,21 +2485,21 @@ The third time, we pass `5 * 2` to the function which gets evaluated to `10`. Th ###### 79. ผลลัพธ์ที่ได้คืออะไร? ```javascript -const myLifeSummedUp = ["☕", "💻", "🍷", "🍫"]; +const myLifeSummedUp = ["☕", "💻", "🍷", "🍫"] for (let item in myLifeSummedUp) { - console.log(item); + console.log(item) } for (let item of myLifeSummedUp) { - console.log(item); + console.log(item) } ``` - A: `0` `1` `2` `3` และ `"☕"` ` "💻"` `"🍷"` `"🍫"` - B: `"☕"` ` "💻"` `"🍷"` `"🍫"` และ `"☕"` ` "💻"` `"🍷"` `"🍫"` - C: `"☕"` ` "💻"` `"🍷"` `"🍫"` และ `0` `1` `2` `3` -- D: `0` `1` `2` `3` และ `{0: "☕", 1: "💻", 2: "🍷", 3: "🍫"}` +- D: `0` `1` `2` `3` และ `{0: "☕", 1: "💻", 2: "🍷", 3: "🍫"}`

คำตอบ

@@ -2523,14 +2522,14 @@ With a _for-of_ loop, we can iterate over **iterables**. An array is an iterable ###### 80. ผลลัพธ์ที่ได้คืออะไร? ```javascript -const list = [1 + 2, 1 * 2, 1 / 2]; -console.log(list); +const list = [1 + 2, 1 * 2, 1 / 2] +console.log(list) ``` - A: `["1 + 2", "1 * 2", "1 / 2"]` - B: `["12", 2, 0.5]` - C: `[3, 2, 0.5]` -- D: `[1, 1, 1]` +- D: `[1, 1, 1]`

คำตอบ

@@ -2539,7 +2538,7 @@ console.log(list); Array elements can hold any value. Numbers, strings, objects, other arrays, null, boolean values, undefined, and other expressions such as dates, functions, and calculations. -The element will be equal to the returned value. `1 + 2` returns `3`, `1 * 2` returns `2`, และ `1 / 2` returns `0.5`. +The element will be equal to the returned value. `1 + 2` returns `3`, `1 * 2` returns `2`, และ `1 / 2` returns `0.5`.

@@ -2550,16 +2549,16 @@ The element will be equal to the returned value. `1 + 2` returns `3`, `1 * 2` re ```javascript function sayHi(name) { - return `Hi there, ${name}`; + return `Hi there, ${name}` } -console.log(sayHi()); +console.log(sayHi()) ``` - A: `Hi there, ` - B: `Hi there, undefined` - C: `Hi there, null` -- D: `ReferenceError` +- D: `ReferenceError`
คำตอบ

@@ -2582,21 +2581,21 @@ In this case, if we didn't pass a value or if we passed `undefined`, `name` woul ###### 82. ผลลัพธ์ที่ได้คืออะไร? ```javascript -var status = "😎"; +var status = "😎" setTimeout(() => { - const status = "😍"; + const status = "😍" const data = { status: "🥑", getStatus() { - return this.status; - }, - }; + return this.status + } + } - console.log(data.getStatus()); - console.log(data.getStatus.call(this)); -}, 0); + console.log(data.getStatus()) + console.log(data.getStatus.call(this)) +}, 0) ``` - A: `"🥑"` และ `"😍"` @@ -2613,6 +2612,7 @@ The value of the `this` keyword is dependent on where you use it. In a **method* With the `call` method, we can change the object to which the `this` keyword refers. In **functions**, the `this` keyword refers to the _the object that the function belongs to_. We declared the `setTimeout` function on the _global object_, so within the `setTimeout` function, the `this` keyword refers to the _global object_. On the global object, there is a variable called _status_ with the value of `"😎"`. When logging `this.status`, `"😎"` gets logged. +

@@ -2623,13 +2623,13 @@ With the `call` method, we can change the object to which the `this` keyword ref ```javascript const person = { name: "Lydia", - age: 21, -}; + age: 21 +} -let city = person.city; -city = "Amsterdam"; +let city = person.city +city = "Amsterdam" -console.log(person); +console.log(person) ``` - A: `{ name: "Lydia", age: 21 }` @@ -2642,13 +2642,13 @@ console.log(person); #### คำตอบ: A -We set the variable `city` equal to the value of the property called `city` on the `person` object. There is no property on this object called `city`, so the variable `city` has the value of `undefined`. +We set the variable `city` equal to the value of the property called `city` on the `person` object. There is no property on this object called `city`, so the variable `city` has the value of `undefined`. Note that we are _not_ referencing the `person` object itself! We simply set the variable `city` equal to the current value of the `city` property on the `person` object. Then, we set `city` equal to the string `"Amsterdam"`. This doesn't change the person object: there is no reference to that object. -When logging the `person` object, the unmodified object gets returned. +When logging the `person` object, the unmodified object gets returned.

@@ -2660,15 +2660,15 @@ When logging the `person` object, the unmodified object gets returned. ```javascript function checkAge(age) { if (age < 18) { - const message = "Sorry, you're too young."; + const message = "Sorry, you're too young." } else { - const message = "Yay! You're old enough!"; + const message = "Yay! You're old enough!" } - return message; + return message } -console.log(checkAge(21)); +console.log(checkAge(21)) ``` - A: `"Sorry, you're too young."` @@ -2691,15 +2691,15 @@ Variables with the `const` และ `let` keyword are _block-scoped_. A block i ###### 85. ข้อมูลแบบไหนที่เราได้ใน log? ```javascript -fetch("https://www.website.com/api/user/1") - .then((res) => res.json()) - .then((res) => console.log(res)); +fetch('https://www.website.com/api/user/1') + .then(res => res.json()) + .then(res => console.log(res)) ``` - A: The result of the `fetch` method. - B: The result of the second invocation of the `fetch` method. - C: The result of the callback in the previous `.then()`. -- D: It would always be undefined. +- D: It would always be undefined.
คำตอบ

@@ -2747,7 +2747,7 @@ By setting `hasName` equal to `name`, you set `hasName` equal to whatever value ###### 87. ผลลัพธ์ที่ได้คืออะไร? ```javascript -console.log("I want pizza"[0]); +console.log("I want pizza"[0]) ``` - A: `"""` @@ -2773,10 +2773,10 @@ Note that this method is not supported in IE7 and below. In that case, use `.cha ```javascript function sum(num1, num2 = num1) { - console.log(num1 + num2); + console.log(num1 + num2) } -sum(10); +sum(10) ``` - A: `NaN` @@ -2789,9 +2789,9 @@ sum(10); #### คำตอบ: B -You can set a default parameter's value equal to another parameter of the function, as long as they've been defined _before_ the default parameter. We pass the value `10` to the `sum` function. If the `sum` function only receives 1 argument, it means that the value for `num2` is not passed, and the value of `num1` is equal to the passed value `10` in this case. The default value of `num2` is the value of `num1`, which is `10`. `num1 + num2` returns `20`. +You can set a default parameter's value equal to another parameter of the function, as long as they've been defined _before_ the default parameter. We pass the value `10` to the `sum` function. If the `sum` function only receives 1 argument, it means that the value for `num2` is not passed, and the value of `num1` is equal to the passed value `10` in this case. The default value of `num2` is the value of `num1`, which is `10`. `num1 + num2` returns `20`. -If you're trying to set a default parameter's value equal to a parameter which is defined _after_ (to the right), the parameter's value hasn't been initialized yet, which will throw an error. +If you're trying to set a default parameter's value equal to a parameter which is defined _after_ (to the right), the parameter's value hasn't been initialized yet, which will throw an error.

@@ -2801,14 +2801,14 @@ If you're trying to set a default parameter's value equal to a parameter which i ###### 89. ผลลัพธ์ที่ได้คืออะไร? ```javascript -// module.js -export default () => "Hello world"; -export const name = "Lydia"; +// module.js +export default () => "Hello world" +export const name = "Lydia" -// index.js -import * as data from "./module"; +// index.js +import * as data from "./module" -console.log(data); +console.log(data) ``` - A: `{ default: function default(), name: "Lydia" }` @@ -2821,9 +2821,9 @@ console.log(data); #### คำตอบ: A -With the `import * as name` syntax, we import _all exports_ from the `module.js` file into the `index.js` file as a new object called `data` is created. In the `module.js` file, there are two exports: the default export, and a named export. The default export is a function which returns the string `"Hello World"`, and the named export is a variable called `name` which has the value of the string `"Lydia"`. +With the `import * as name` syntax, we import _all exports_ from the `module.js` file into the `index.js` file as a new object called `data` is created. In the `module.js` file, there are two exports: the default export, and a named export. The default export is a function which returns the string `"Hello World"`, and the named export is a variable called `name` which has the value of the string `"Lydia"`. -The `data` object has a `default` property for the default export, other properties have the names of the named exports and their corresponding values. +The `data` object has a `default` property for the default export, other properties have the names of the named exports and their corresponding values.

@@ -2835,12 +2835,12 @@ The `data` object has a `default` property for the default export, other propert ```javascript class Person { constructor(name) { - this.name = name; + this.name = name } } -const member = new Person("John"); -console.log(typeof member); +const member = new Person("John") +console.log(typeof member) ``` - A: `"class"` @@ -2857,11 +2857,11 @@ Classes are syntactical sugar for function constructors. The equivalent of the ` ```javascript function Person() { - this.name = name; + this.name = name } ``` -Calling a function constructor with `new` results in the creation of an instance of `Person`, `typeof` keyword returns `"object"` for an instance. `typeof member` returns `"object"`. +Calling a function constructor with `new` results in the creation of an instance of `Person`, `typeof` keyword returns `"object"` for an instance. `typeof member` returns `"object"`.

@@ -2871,9 +2871,9 @@ Calling a function constructor with `new` results in the creation of an instance ###### 91. ผลลัพธ์ที่ได้คืออะไร? ```javascript -let newList = [1, 2, 3].push(4); +let newList = [1, 2, 3].push(4) -console.log(newList.push(5)); +console.log(newList.push(5)) ``` - A: `[1, 2, 3, 4, 5]` @@ -2886,7 +2886,7 @@ console.log(newList.push(5)); #### คำตอบ: D -The `.push` method returns the _new length_ of the array, not the array itself! By setting `newList` equal to `[1, 2, 3].push(4)`, we set `newList` equal to the new length of the array: `4`. +The `.push` method returns the _new length_ of the array, not the array itself! By setting `newList` equal to `[1, 2, 3].push(4)`, we set `newList` equal to the new length of the array: `4`. Then, we try to use the `.push` method on `newList`. Since `newList` is the numerical value `4`, we cannot use the `.push` method: a TypeError is thrown. @@ -2899,18 +2899,17 @@ Then, we try to use the `.push` method on `newList`. Since `newList` is the nume ```javascript function giveLydiaPizza() { - return "Here is pizza!"; + return "Here is pizza!" } -const giveLydiaChocolate = () => - "Here's chocolate... now go hit the gym already."; +const giveLydiaChocolate = () => "Here's chocolate... now go hit the gym already." -console.log(giveLydiaPizza.prototype); -console.log(giveLydiaChocolate.prototype); +console.log(giveLydiaPizza.prototype) +console.log(giveLydiaChocolate.prototype) ``` -- A: `{ constructor: ...}` `{ constructor: ...}` -- B: `{}` `{ constructor: ...}` +- A: `{ constructor: ...}` `{ constructor: ...}` +- B: `{}` `{ constructor: ...}` - C: `{ constructor: ...}` `{}` - D: `{ constructor: ...}` `undefined` @@ -2919,7 +2918,7 @@ console.log(giveLydiaChocolate.prototype); #### คำตอบ: D -Regular functions, such as the `giveLydiaPizza` function, have a `prototype` property, which is an object (prototype object) with a `constructor` property. Arrow functions however, such as the `giveLydiaChocolate` function, do not have this `prototype` property. `undefined` gets returned when trying to access the `prototype` property using `giveLydiaChocolate.prototype`. +Regular functions, such as the `giveLydiaPizza` function, have a `prototype` property, which is an object (prototype object) with a `constructor` property. Arrow functions however, such as the `giveLydiaChocolate` function, do not have this `prototype` property. `undefined` gets returned when trying to access the `prototype` property using `giveLydiaChocolate.prototype`.

@@ -2931,16 +2930,16 @@ Regular functions, such as the `giveLydiaPizza` function, have a `prototype` pro ```javascript const person = { name: "Lydia", - age: 21, -}; + age: 21 +} for (const [x, y] of Object.entries(person)) { - console.log(x, y); + console.log(x, y) } ``` - A: `name` `Lydia` และ `age` `21` -- B: `["name", "Lydia"]` และ `["age", 21]` +- B: `["name", "Lydia"]` และ `["age", 21]` - C: `["name", "age"]` และ `undefined` - D: `Error` @@ -2951,9 +2950,9 @@ for (const [x, y] of Object.entries(person)) { `Object.entries(person)` returns an array of nested arrays, containing the keys and objects: -`[ [ 'name', 'Lydia' ], [ 'age', 21 ] ]` +`[ [ 'name', 'Lydia' ], [ 'age', 21 ] ]` -Using the `for-of` loop, we can iterate over each element in the array, the subarrays in this case. We can destructure the subarrays instantly in the for-of loop, using `const [x, y]`. `x` is equal to the first element in the subarray, `y` is equal to the second element in the subarray. +Using the `for-of` loop, we can iterate over each element in the array, the subarrays in this case. We can destructure the subarrays instantly in the for-of loop, using `const [x, y]`. `x` is equal to the first element in the subarray, `y` is equal to the second element in the subarray. The first subarray is `[ "name", "Lydia" ]`, with `x` equal to `"name"`, และ `y` equal to `"Lydia"`, which get logged. The second subarray is `[ "age", 21 ]`, with `x` equal to `"age"`, และ `y` equal to `21`, which get logged. @@ -2974,7 +2973,7 @@ getItems(["banana", "apple"], "pear", "orange") ``` - A: `["banana", "apple", "pear", "orange"]` -- B: `[["banana", "apple"], "pear", "orange"]` +- B: `[["banana", "apple"], "pear", "orange"]` - C: `["banana", "apple", ["pear"], "orange"]` - D: `SyntaxError` @@ -2983,18 +2982,17 @@ getItems(["banana", "apple"], "pear", "orange") #### คำตอบ: D -`...args` is a rest parameter. The rest parameter's value is an array containing all remaining arguments, **and can only be the last parameter**! In this example, the rest parameter was the second parameter. This is not possible, and will throw a syntax error. +`...args` is a rest parameter. The rest parameter's value is an array containing all remaining arguments, **and can only be the last parameter**! In this example, the rest parameter was the second parameter. This is not possible, and will throw a syntax error. ```javascript function getItems(fruitList, favoriteFruit, ...args) { - return [...fruitList, ...args, favoriteFruit]; + return [...fruitList, ...args, favoriteFruit] } -getItems(["banana", "apple"], "pear", "orange"); +getItems(["banana", "apple"], "pear", "orange") ``` The above example works. This returns the array `[ 'banana', 'apple', 'orange', 'pear' ]` -

@@ -3004,14 +3002,17 @@ The above example works. This returns the array `[ 'banana', 'apple', 'orange', ```javascript function nums(a, b) { - if (a > b) console.log("a is bigger"); - else console.log("b is bigger"); - return; - a + b; + if + (a > b) + console.log('a is bigger') + else + console.log('b is bigger') + return + a + b } -console.log(nums(4, 2)); -console.log(nums(1, 2)); +console.log(nums(4, 2)) +console.log(nums(1, 2)) ``` - A: `a is bigger`, `6` และ `b is bigger`, `3` @@ -3024,13 +3025,13 @@ console.log(nums(1, 2)); #### คำตอบ: B -In JavaScript, we don't _have_ to write the semicolon (`;`) explicitly, however the JavaScript engine still adds them after statements. This is called **Automatic Semicolon Insertion**. A statement can for example be variables, or keywords like `throw`, `return`, `break`, etc. +In JavaScript, we don't _have_ to write the semicolon (`;`) explicitly, however the JavaScript engine still adds them after statements. This is called **Automatic Semicolon Insertion**. A statement can for example be variables, or keywords like `throw`, `return`, `break`, etc. Here, we wrote a `return` statement, and another value `a + b` on a _new line_. However, since it's a new line, the engine doesn't know that it's actually the value that we wanted to return. Instead, it automatically added a semicolon after `return`. You could see this as: ```javascript -return; -a + b; + return; + a + b ``` This means that `a + b` is never reached, since a function stops running after the `return` keyword. If no value gets returned, like here, the function returns `undefined`. Note that there is no automatic insertion after `if/else` statements! @@ -3045,18 +3046,18 @@ This means that `a + b` is never reached, since a function stops running after t ```javascript class Person { constructor() { - this.name = "Lydia"; + this.name = "Lydia" } } Person = class AnotherPerson { constructor() { - this.name = "Sarah"; + this.name = "Sarah" } -}; +} -const member = new Person(); -console.log(member.name); +const member = new Person() +console.log(member.name) ``` - A: `"Lydia"` @@ -3080,11 +3081,11 @@ We can set classes equal to other classes/function constructors. In this case, w ```javascript const info = { - [Symbol("a")]: "b", -}; + [Symbol('a')]: 'b' +} -console.log(info); -console.log(Object.keys(info)); +console.log(info) +console.log(Object.keys(info)) ``` - A: `{Symbol('a'): 'b'}` และ `["{Symbol('a')"]` @@ -3131,13 +3132,13 @@ console.log(getUser(user)) The `getList` function receives an array as its argument. Between the parentheses of the `getList` function, we destructure this array right away. You could see this as: -`[x, ...y] = [1, 2, 3, 4]` + `[x, ...y] = [1, 2, 3, 4]` -With the rest parameter `...y`, we put all "remaining" arguments in an array. The remaining arguments are `2`, `3` และ `4` in this case. The value of `y` is an array, containing all the rest parameters. The value of `x` is equal to `1` in this case, so when we log `[x, y]`, `[1, [2, 3, 4]]` gets logged. + With the rest parameter `...y`, we put all "remaining" arguments in an array. The remaining arguments are `2`, `3` และ `4` in this case. The value of `y` is an array, containing all the rest parameters. The value of `x` is equal to `1` in this case, so when we log `[x, y]`, `[1, [2, 3, 4]]` gets logged. -The `getUser` function receives an object. With arrow functions, we don't _have_ to write curly brackets if we just return one value. However, if you want to return an _object_ from an arrow function, you have to write it between parentheses, otherwise no value gets returned! The following function would have returned an object: + The `getUser` function receives an object. With arrow functions, we don't _have_ to write curly brackets if we just return one value. However, if you want to return an _object_ from an arrow function, you have to write it between parentheses, otherwise no value gets returned! The following function would have returned an object: -`const getUser = user => ({ name: user.name, age: user.age })` +```const getUser = user => ({ name: user.name, age: user.age })``` Since no value gets returned in this case, the function returns `undefined`. @@ -3149,9 +3150,9 @@ Since no value gets returned in this case, the function returns `undefined`. ###### 99. ผลลัพธ์ที่ได้คืออะไร? ```javascript -const name = "Lydia"; +const name = "Lydia" -console.log(name()); +console.log(name()) ``` - A: `SyntaxError` @@ -3164,11 +3165,11 @@ console.log(name()); #### คำตอบ: C -The variable `name` holds the value of a string, which is not a function, thus cannot invoke. +The variable `name` holds the value of a string, which is not a function, thus cannot invoke. TypeErrors get thrown when a value is not of the expected type. JavaScript expected `name` to be a function since we're trying to invoke it. It was a string however, so a TypeError gets thrown: name is not a function! -SyntaxErrors get thrown when you've written something that isn't valid JavaScript, for example when you've written the word `return` as `retrun`. +SyntaxErrors get thrown when you've written something that isn't valid JavaScript, for example when you've written the word `return` as `retrun`. ReferenceErrors get thrown when JavaScript isn't able to find a reference to a value that you're trying to access.

@@ -3181,8 +3182,8 @@ ReferenceErrors get thrown when JavaScript isn't able to find a reference to a v ```javascript // 🎉✨ This is my 100th question! ✨🎉 -const output = `${[] && "Im"}possible! -You should${"" && `n't`} see a therapist after so much JavaScript lol`; +const output = `${[] && 'Im'}possible! +You should${'' && `n't`} see a therapist after so much JavaScript lol` ``` - A: `possible! You should see a therapist after so much JavaScript lol` @@ -3207,11 +3208,11 @@ You should${"" && `n't`} see a therapist after so much JavaScript lol`; ###### 101. ผลลัพธ์ที่ได้คืออะไร? ```javascript -const one = false || {} || null; -const two = null || false || ""; -const three = [] || 0 || true; +const one = (false || {} || null) +const two = (null || false || "") +const three = ([] || 0 || true) -console.log(one, two, three); +console.log(one, two, three) ``` - A: `false` `null` `[]` @@ -3240,20 +3241,20 @@ With the `||` operator, we can return the first truthy operand. If all values ar ###### 102. ผลลัพธ์ที่ได้คืออะไร? ```javascript -const myPromise = () => Promise.resolve("I have resolved!"); +const myPromise = () => Promise.resolve('I have resolved!') function firstFunction() { - myPromise().then((res) => console.log(res)); - console.log("second"); + myPromise().then(res => console.log(res)) + console.log('second') } async function secondFunction() { - console.log(await myPromise()); - console.log("second"); + console.log(await myPromise()) + console.log('second') } -firstFunction(); -secondFunction(); +firstFunction() +secondFunction() ``` - A: `I have resolved!`, `second` และ `I have resolved!`, `second` @@ -3268,13 +3269,13 @@ secondFunction(); With a promise, we basically say _I want to execute this function, but I'll put it aside for now while it's running since this might take a while. Only when a certain value is resolved (or rejected), and when the call stack is empty, I want to use this value._ -We can get this value with both `.then` and the `await` keyword in an `async` function. Although we can get a promise's value with both `.then` และ `await`, they work a bit differently. +We can get this value with both `.then` and the `await` keyword in an `async` function. Although we can get a promise's value with both `.then` และ `await`, they work a bit differently. -In the `firstFunction`, we (sort of) put the myPromise function aside while it was running, but continued running the other code, which is `console.log('second')` in this case. Then, the function resolved with the string `I have resolved`, which then got logged after it saw that the callstack was empty. +In the `firstFunction`, we (sort of) put the myPromise function aside while it was running, but continued running the other code, which is `console.log('second')` in this case. Then, the function resolved with the string `I have resolved`, which then got logged after it saw that the callstack was empty. With the await keyword in `secondFunction`, we literally pause the execution of an async function until the value has been resolved before moving to the next line. -This means that it waited for the `myPromise` to resolve with the value `I have resolved`, and only once that happened, we moved to the next line: `second` got logged. +This means that it waited for the `myPromise` to resolve with the value `I have resolved`, and only once that happened, we moved to the next line: `second` got logged.

@@ -3284,14 +3285,14 @@ This means that it waited for the `myPromise` to resolve with the value `I have ###### 103. ผลลัพธ์ที่ได้คืออะไร? ```javascript -const set = new Set(); +const set = new Set() -set.add(1); -set.add("Lydia"); -set.add({ name: "Lydia" }); +set.add(1) +set.add("Lydia") +set.add({ name: "Lydia" }) for (let item of set) { - console.log(item + 2); + console.log(item + 2) } ``` @@ -3305,11 +3306,11 @@ for (let item of set) { #### คำตอบ: C -The `+` operator is not only used for adding numerica lvalues, but we can also use it to concatenate strings. Whenever the JavaScript engine sees that one or more values are not a number, it coerces the number into a string. +The `+` operator is not only used for adding numerica lvalues, but we can also use it to concatenate strings. Whenever the JavaScript engine sees that one or more values are not a number, it coerces the number into a string. The first one is `1`, which is a numerical value. `1 + 2` returns the number 3. -However, the second one is a string `"Lydia"`. `"Lydia"` is a string and `2` is a number: `2` gets coerced into a string. `"Lydia"` และ `"2"` get concatenated, whic hresults in the string `"Lydia2"`. +However, the second one is a string `"Lydia"`. `"Lydia"` is a string and `2` is a number: `2` gets coerced into a string. `"Lydia"` และ `"2"` get concatenated, whic hresults in the string `"Lydia2"`. `{ name: "Lydia" }` is an object. Neither a number nor an object is a string, so it stringifies both. Whenever we stringify a regular object, it becomes `"[object Object]"`. `"[object Object]"` concatenated with `"2"` becomes `"[object Object]2"`. @@ -3321,7 +3322,7 @@ However, the second one is a string `"Lydia"`. `"Lydia"` is a string and `2` is ###### 104. ผลลัพธ์ที่ได้คืออะไร? ```javascript -Promise.resolve(5); +Promise.resolve(5) ``` - A: `5` @@ -3336,7 +3337,7 @@ Promise.resolve(5); We can pass any type of value we want to `Promise.resolve`, either a promise or a non-promise. The method itself returns a promise with the resolved value (``). If you pass a regular function, it'll be a resolved promise with a regular value. If you pass a promise, it'll be a resolved promise with the resolved value of that passed promise. -In this case, we just passed the numerical value `5`. It returns a resolved promise with the value `5`. +In this case, we just passed the numerical value `5`. It returns a resolved promise with the value `5`.

@@ -3348,15 +3349,15 @@ In this case, we just passed the numerical value `5`. It returns a resolved prom ```javascript function compareMembers(person1, person2 = person) { if (person1 !== person2) { - console.log("Not the same!"); + console.log("Not the same!") } else { - console.log("They are the same!"); + console.log("They are the same!") } } -const person = { name: "Lydia" }; +const person = { name: "Lydia" } -compareMembers(person); +compareMembers(person) ``` - A: `Not the same!` @@ -3369,13 +3370,13 @@ compareMembers(person); #### คำตอบ: B -Objects are passed by reference. When we check objects for strict equality (`===`), we're comparing their references. +Objects are passed by reference. When we check objects for strict equality (`===`), we're comparing their references. We set the default value for `person2` equal to the `person` object, and passed the `person` object as the value for `person1`. This means that both values have a reference to the same spot in memory, thus they are equal. -The code block in the `else` statement gets run, and `They are the same!` gets logged. +The code block in the `else` statement gets run, and `They are the same!` gets logged.

@@ -3391,11 +3392,11 @@ const colorConfig = { green: true, black: true, yellow: false, -}; +} -const colors = ["pink", "red", "blue"]; +const colors = ["pink", "red", "blue"] -console.log(colorConfig.colors[1]); +console.log(colorConfig.colors[1]) ``` - A: `true` @@ -3408,11 +3409,11 @@ console.log(colorConfig.colors[1]); #### คำตอบ: D -In JavaScript, we have two ways to access properties on an object: bracket notation, or dot notation. In this example, we use dot notation (`colorConfig.colors`) instead of bracket notation (`colorConfig["colors"]`). +In JavaScript, we have two ways to access properties on an object: bracket notation, or dot notation. In this example, we use dot notation (`colorConfig.colors`) instead of bracket notation (`colorConfig["colors"]`). With dot notation, JavaScript tries to find the property on the object with that exact name. In this example, JavaScript tries to find a property called `colors` on the `colorConfig` object. There is no proprety called `colorConfig`, so this returns `undefined`. Then, we try to access the value of the first element by using `[1]`. We cannot do this on a value that's `undefined`, so it throws a `TypeError`: `Cannot read property '1' of undefined`. -JavaScript interprets (or unboxes) statements. When we use bracket notation, it sees the first opening bracket `[` and keeps going until it finds the closing bracket `]`. Only then, it will evaluate the statement. If we would've used `colorConfig[colors[1]]`, it would have returned the value of the `red` property on the `colorConfig` object. +JavaScript interprets (or unboxes) statements. When we use bracket notation, it sees the first opening bracket `[` and keeps going until it finds the closing bracket `]`. Only then, it will evaluate the statement. If we would've used `colorConfig[colors[1]]`, it would have returned the value of the `red` property on the `colorConfig` object.

@@ -3422,7 +3423,7 @@ JavaScript interprets (or unboxes) statements. When we use bracket notation, it ###### 107. ผลลัพธ์ที่ได้คืออะไร? ```javascript -console.log("❤️" === "❤️"); +console.log('❤️' === '❤️') ``` - A: `true` @@ -3433,7 +3434,7 @@ console.log("❤️" === "❤️"); #### คำตอบ: A -Under the hood, emojis are unicodes. The unicodes for the heart emoji is `"U+2764 U+FE0F"`. These are always the same for the same emojis, so we're comparing two equal strings to each other, which returns true. +Under the hood, emojis are unicodes. The unicodes for the heart emoji is `"U+2764 U+FE0F"`. These are always the same for the same emojis, so we're comparing two equal strings to each other, which returns true.

@@ -3443,19 +3444,19 @@ Under the hood, emojis are unicodes. The unicodes for the heart emoji is `"U+276 ###### 108. Which of these methods modifies the original array? ```javascript -const emojis = ["✨", "🥑", "😍"]; +const emojis = ['✨', '🥑', '😍'] -emojis.map((x) => x + "✨"); -emojis.filter((x) => x !== "🥑"); -emojis.find((x) => x !== "🥑"); -emojis.reduce((acc, cur) => acc + "✨"); -emojis.slice(1, 2, "✨"); -emojis.splice(1, 2, "✨"); +emojis.map(x => x + '✨') +emojis.filter(x => x !== '🥑') +emojis.find(x => x !== '🥑') +emojis.reduce((acc, cur) => acc + '✨') +emojis.slice(1, 2, '✨') +emojis.splice(1, 2, '✨') ``` - A: `All of them` - B: `map` `reduce` `slice` `splice` -- C: `map` `slice` `splice` +- C: `map` `slice` `splice` - D: `splice`
คำตอบ @@ -3463,7 +3464,7 @@ emojis.splice(1, 2, "✨"); #### คำตอบ: D -With `splice` method, we modify the original array by deleting, replacing or adding elements. In this case, we removed 2 items from index 1 (we removed `'🥑'` และ `'😍'`) and added the ✨ emoji instead. +With `splice` method, we modify the original array by deleting, replacing or adding elements. In this case, we removed 2 items from index 1 (we removed `'🥑'` และ `'😍'`) and added the ✨ emoji instead. `map`, `filter` และ `slice` return a new array, `find` returns an element, and `reduce` returns a reduced value. diff --git a/tr-TR/README-tr_TR.md b/tr-TR/README-tr_TR.md index f1abe649..e34ae66b 100644 --- a/tr-TR/README-tr_TR.md +++ b/tr-TR/README-tr_TR.md @@ -9,6 +9,7 @@ Cevaplar, soruların altında gizlenmiştir. Görmek için sadece tıklayın. İ Daha fazla soru eklendikçe eposta almak ister misiniz?
✨✉Eposta bildirimlerine abone olun✉✨ + Mevcut dillerin listesi: - [🇸🇦 العربية](../ar-AR/README_AR.md) @@ -25,7 +26,6 @@ Mevcut dillerin listesi: - [🇳🇱 Nederlands](../nl-NL/README.md) - [🇵🇱 Polski](../pl-PL/README.md) - [🇧🇷 Português Brasil](../pt-BR/README_pt_BR.md) -- [🇷o Română](../ro-RO/README.ro.md) - [🇷🇺 Русский](../ru-RU/README.md) - [🇽🇰 Shqip](../sq-KS/README_sq_KS.md) - [🇹🇭 ไทย](../th-TH/README-th_TH.md) @@ -60,9 +60,8 @@ sayHi(); #### Cevap: D Fonksiyonun içinde, önce `var` anahtar kelimesi ile `name` değişkenini tanımladık. Bu demektir ki, değişken varsayılan değeri olan `undefined` ile "hoisting" (hafızada alan oluşturma aşaması) olur, ta ki gerçekten değişkene değer ataması yaptığımız satıra varana dek. `name` değişkenini loglayama çalıştığımız satırda henüz değişkeni tanımlamadık, bu yüzden hala `undefined` değerini saklıyor. - + `let` (ve `const`) anahtar kelimelerine sahip değişkenler de "hoisted" olur, ama `var`'ın aksine ilk değer ataması yapılmaz. Değişkenleri tanımladığımız (ilk değer ataması yaptığımız) satırdan önce erişilebilir değillerdir. Bu, "geçici ölü alan / geçici değişmez çıktı alanı", "temporal dead zone", olarak adlandırılır. Değişkenlere, tanımlanmadan önce erişmeye çalıştığımız zaman, Javascript `ReferenceError` hatası fırlatır. -

@@ -92,7 +91,6 @@ for (let i = 0; i < 3; i++) { Javascript'deki olay kuyruğundan dolayı, `setTimeout` callback fonksiyonu, döngü uygulandıktan _sonra_ çağrılır. `i` değişkeni, ilk döngü sırasında `var` anahtar kelimesi ile tanımlandığından, bu değişken globaldir. Döngü boyunca, `++` unary operatörünü kullanarak, `i`'nin değerini her seferinde `1` arttırdık. İlk örnekte, `setTimeout` callback fonksiyonu çağrıldığı zaman, `i`'nin değeri `3`'e eşitti. İkinci döngüde, `i` değişkeni `let` anahtar kelimesi kullanılarak tanımlandı: `let` (ve `const`) ile tanımlanan değişkenler "block-scope"dur (block `{}` arasındaki herhangi bir şeydir). Her bir tekrarda, `i` yeni değere sahip olacak ve her değer döngü içinde "scoped" olacak. -

@@ -106,7 +104,7 @@ const shape = { diameter() { return this.radius * 2; }, - perimeter: () => 2 * Math.PI * this.radius, + perimeter: () => 2 * Math.PI * this.radius }; console.log(shape.diameter()); @@ -127,7 +125,7 @@ console.log(shape.perimeter()); Arrow fonksiyonlarda, `this` anahtar kelimesi, sıradan fonksiyonların aksine, kendi sardığı mevcut scope'u referans alır. Bu demektir ki, `perimeter`'i çağırdığımız zaman, `shape` objesini değil, kendi sardığı scope'u referans alıyor (örneğin window). -Bu objede, `radius` değeri olmadığından `undefined` döndürüyor. +Bu objede, `radius` değeri olmadığından `undefined` döndürüyor.

@@ -152,8 +150,7 @@ Bu objede, `radius` değeri olmadığından `undefined` döndürüyor. Artı (unary plus), işlemeye çalıştığı değişkeni sayıya çevirmeye çalışır. `true` `1` ve `false` `0` demektir. -`'Lydia'` harf dizisi doğrusal ("truthy") bir değerdir. Aslında sorduğumuz şey, "bu doğrusal değer yanlış-ımsı ("falsy") mı?". Bu da `false` döndürür. - +`'Lydia'` harf dizisi doğrusal ("truthy") bir değerdir. Aslında sorduğumuz şey, "bu doğrusal değer yanlış-ımsı ("falsy") mı?". Bu da `false` döndürür.

@@ -163,12 +160,12 @@ Artı (unary plus), işlemeye çalıştığı değişkeni sayıya çevirmeye ça ```javascript const bird = { - size: "small", + size: "small" }; const mouse = { name: "Mickey", - small: true, + small: true }; ``` @@ -189,12 +186,12 @@ Javascript, ifadeleri yorumlar (ya da açar ("unboxes")). Köşeli parentez nota `mouse[bird.size]`: Önce `bird.size` çalıştırılır, o da `"small"` demektir. `mouse["small"]`, `true` döndürür. Ancak, nokta notasyonunda bu gerçekleşmez. `mouse`, `bird` diye bir keye sahip değildir ki bu da `mouse.bird`, `undefined` demektir. Sonra, nokta notasyonunu kullanarak `size`'a ulaşmak istiyoruz: `mouse.bird.size`. `mouse.bird`, `undefined` olduğundan, aslında ulaşmaya çalıştığımız `undefined.size`. Bu geçerli değil ve `Cannot read property "size" of undefined`'a benzer bir hata fırlatacaktır. -

--- + ###### 6. Çıktısı Nedir? ```javascript @@ -256,7 +253,6 @@ console.log(b === c); `==` operatörünü kullandığımız zaman, sadece aynı _değer_'e sahip olup olmadığını kontrol eder. İkisi de `3` değerine sahip, yani `true` döndürür. Ancak, `===` kullandığımız zaman değer _ve_ tip aynı olmalıdır. Öyle değil: `new Number()`, sayı ("number") değildir, **nesne**dir. İkisi de `false` döndürür. -

@@ -291,7 +287,6 @@ console.log(freddie.colorChange("orange")); #### Cevap: D `colorChange` fonksiyonu statiktir. Statik methodlar, sadece oluşturuldukları kurucuda var olmak için tasarlanmıştır ve herhangi bir "children"a aktarılamaz. `freddie`, "child" olduğundan, fonksiyon aktarılmadı ve `freddie` üzerinden erişilebilir değil: `TypeError` hatası fırlatılır. -

@@ -317,7 +312,6 @@ console.log(greetign); Nesneyi loglar çünkü global nesne üzerinde boş bir nesne oluşturduk. `greeting`'i `greetign` olarak yanlış yazdığımız zaman, JS yorumlayıcısı bunu `global.greetign = {}` olarak gördü (ya da tarayıcı içinde `window.greetign = {}`). Bundan kaçınmak için, `"use strict"` kullanabiliriz. Bu, bir değişkene herhangi bir atama yapmadan önce tanımladığınızdan emin olmanızı sağlar. -

@@ -361,7 +355,7 @@ function Person(firstName, lastName) { } const member = new Person("Lydia", "Hallie"); -Person.getFullName = function () { +Person.getFullName = function() { return `${this.firstName} ${this.lastName}`; }; @@ -379,9 +373,8 @@ console.log(member.getFullName()); #### Cevap: A Sıradan fonksiyonlarla yaptığınız gibi bir yapıcıya ("constructor") özellik ekleyemezsiniz. Eğer, tek seferde tüm nesnelere özellik eklemek isterseniz, bunun yerine prototype kullanmalısınız. Yani bu durumda, - ```js -Person.prototype.getFullName = function () { +Person.prototype.getFullName = function() { return `${this.firstName} ${this.lastName}`; }; ``` @@ -421,7 +414,6 @@ console.log(sarah); `sarah` için `new` anahtar kelimesi kullanmadık. `new` kullandığınız zaman, oluşturduğumuz yeni boş nesneyi referans gösterir. Lakin, `new`'i eklemezseniz, **global nesne**'yi referans gösterir! `this.firstName`, `"Sarah"`'a eşittir ve `this.lastName`, `"Smith"`'e eşittir dedik. Aslında yaptığımız, `global.firstName = 'Sarah'` ve `global.lastName = 'Smith'` diye tanımlamaydı. `sarah`'ın kendisi `undefined` olarak kalır. -

@@ -439,7 +431,7 @@ console.log(sarah); #### Cevap: D -**capturing** aşaması süresince, olay ata ("ancestor) elemanlardan hedef elemana doğru gider. Daha sonra **target** elemana ulaşır ve **bubbling** başlar. +**capturing** aşaması süresince, olay ata ("ancestor) elemanlardan hedef elemana doğru gider. Daha sonra **target** elemana ulaşır ve **bubbling** başlar. @@ -459,7 +451,6 @@ console.log(sarah); #### Cevap: B Bütün nesneler prototiplere ("prototypes") sahiptir, **temel nesne**, **base object**, hariç. Temel nesne, kullanıcı tarafından oluşturulmuş nesnedir, ya da `new` anahtar kelimesi kullanarak oluşturulmuş bir nesnedir. Temel nesne bazı method ve özelliklere erişebilir, `.toString` gibi. Yerleşik gelen Javascript methodlarını kullanabilme sebebi budur! Buna benzer tüm methodlar prototip üzerinden erişebilir. Her ne kadar Javascript, methodu direkt olarak nesneniz üzerinden bulamasa da, prototip zinciri üzerinden aşağıya doğru gider ve orada bulur, böylece sizin için erişebilir yapar. -

@@ -515,6 +506,7 @@ console.log(number); **son ek**, **postfix**, `++` unary operatörü: + 1. Değer döndürür (`0` döndürür) 2. Değeri arttırır (sayı şimdi `1`) @@ -694,7 +686,7 @@ sessionStorage.setItem("cool_secret", 123); `sessionStorage` içinde saklanan veri _sekme_ kapatıldıktan sonra kaldırılır. -Eğer `localStorage` kullandıysanız, veri sonsuza kadar orada olacaktır, örnek olarak `localStorage.clear()` çalıştırılmadığı sürece. +Eğer `localStorage` kullandıysanız, veri sonsuza kadar orada olacaktır, örnek olarak `localStorage.clear()` çalıştırılmadığı sürece.

@@ -837,7 +829,7 @@ String.prototype.giveLydiaPizza = () => { const name = "Lydia"; -console.log(name.giveLydiaPizza()); +console.log(name.giveLydiaPizza()) ``` - A: `"Just give Lydia pizza already!"` @@ -949,7 +941,9 @@ Burası olay döngüsünün çalışmaya başlayacapı yerdir. **olay döngüsü ```html
- +
``` @@ -975,7 +969,9 @@ Olaya sebep olan en derindeki iç eleman, olayın hedefidir ("event.target"). `e ```html
-

Click here!

+

+ Click here! +

``` @@ -1189,7 +1185,7 @@ Sonra, bu block-scoped değişkeni `1`'e eşit olarak ayarladık ve `y` değişk - A: primitifdir ya da nesnedir - B: fonksiyondur or nesnedir - C: tuzak soru! sadece nesnedir -- D: sayıdır (number) ya da nesnedir +- D: sayıdır (number) ya da nesnedir
Cevap

@@ -1210,10 +1206,7 @@ Primitif ve nesneyi birbirinden ayıran, primitif tiplerin herhangi bir özelli ###### 40. Çıktısı Nedir? ```javascript -[ - [0, 1], - [2, 3], -].reduce( +[[0, 1], [2, 3]].reduce( (acc, cur) => { return acc.concat(cur); }, @@ -1339,7 +1332,7 @@ console.log(gen.next().value); #### Cevap: C -Sıradan fonksiyonlar yürütmenin başlamasının ardından yarı yolda durdurulamaz. Ancak, bir generator fonksiyon yarı yolda "durdurabilir" ve sonra nerede kaldıysa devam edebilir. Bir generator fonksiyon ne zaman `yield` anahtar kelimesiyle karşılaşsa, yield'de belirtilen değeri verir. Dikkat edin, generator fonksiyon değeri _döndürmez_ (_return_), değeri _verir_ (_yield_). +Sıradan fonksiyonlar yürütmenin başlamasının ardından yarı yolda durdurulamaz. Ancak, bir generator fonksiyon yarı yolda "durdurabilir" ve sonra nerede kaldıysa devam edebilir. Bir generator fonksiyon ne zaman `yield` anahtar kelimesiyle karşılaşsa, yield'de belirtilen değeri verir. Dikkat edin, generator fonksiyon değeri _döndürmez_ (_return_), değeri _verir_ (_yield_). Önce, generator fonksiyonu `i`'yi `10`'a eşitleyerek başlatıyoruz. `next()` metodunu kullanarak generator fonksiyonu çalıştırıyoruz. İlk kez generator fonksiyonu çalıştırdığımızda, `i` `10`'a eşit. Fonksiyon ilk `yield` anahtar kelimesi ile karşılaşıyor: `i`'nin değerini veriyor. Generatır şimdi "durdu", ve `10` loglandı. @@ -1361,7 +1354,7 @@ const secondPromise = new Promise((res, rej) => { setTimeout(res, 100, "two"); }); -Promise.race([firstPromise, secondPromise]).then((res) => console.log(res)); +Promise.race([firstPromise, secondPromise]).then(res => console.log(res)); ``` - A: `"one"` @@ -1413,7 +1406,7 @@ Sonra, `person` değişkenini `null`'a eşit olarak ayarlarız. -Sadece `person` değişkeninin değerini değiştiriyoruz, dizideki ilk elemanı değil, ilk eleman nesneyi gösteren farklı (kopyalanmış) bir referansa sahip. `members` içindeki ilk eleman hala orijinal nesneyi gösteren referansını saklıyor. `members` dizisini logladığımız zaman, ilk elemanın hala sakladığı nesnenin değeri loglanır. +Sadece `person` değişkeninin değerini değiştiriyoruz, dizideki ilk elemanı değil, ilk eleman nesneyi gösteren farklı (kopyalanmış) bir referansa sahip. `members` içindeki ilk eleman hala orijinal nesneyi gösteren referansını saklıyor. `members` dizisini logladığımız zaman, ilk elemanın hala sakladığı nesnenin değeri loglanır.

@@ -1425,7 +1418,7 @@ Sadece `person` değişkeninin değerini değiştiriyoruz, dizideki ilk elemanı ```javascript const person = { name: "Lydia", - age: 21, + age: 21 }; for (const item in person) { @@ -1505,7 +1498,7 @@ Sadece string içindeki ilk sayılar döndürülür. _Sayı tabanına_ (hangi ti ###### 50. Çıktısı Nedir`? ```javascript -[1, 2, 3].map((num) => { +[1, 2, 3].map(num => { if (typeof num === "number") return; return num * 2; }); @@ -1521,7 +1514,7 @@ Sadece string içindeki ilk sayılar döndürülür. _Sayı tabanına_ (hangi ti #### Cevap: C -Dizi üzerinde eşleme yaparken, `num`'ın değeri, o anda döngüye giren elemanın değerine eşittir. Bu durumda, elemanlar sayı, yani `typeof num === "number"` koşul ifadesi `true` durdurur. map fonksiyonu yeni bir dizi oluşturur ve fonksiyondan dönen değerleri yerleştirir. +Dizi üzerinde eşleme yaparken, `num`'ın değeri, o anda döngüye giren elemanın değerine eşittir. Bu durumda, elemanlar sayı, yani `typeof num === "number"` koşul ifadesi `true` durdurur. map fonksiyonu yeni bir dizi oluşturur ve fonksiyondan dönen değerleri yerleştirir. Ancak, biz değer döndürmüyoruz. Bir fonksiyondan değer döndürmediğimiz zaman, fonksiyon `undefined` döndürür. Dizideki her eleman için, fonksiyon bloğu çağrılır, yani her bir eleman için `undefined` döndürürüz. @@ -1682,7 +1675,7 @@ class Dog { } } -Dog.prototype.bark = function () { +Dog.prototype.bark = function() { console.log(`Woof I am ${this.name}`); }; @@ -1910,7 +1903,7 @@ console.log(Object.keys(person)); const settings = { username: "lydiahallie", level: 19, - health: 90, + health: 90 }; const data = JSON.stringify(settings, ["level", "health"]); @@ -1929,7 +1922,7 @@ console.log(data); `JSON.stringify`'ın ikinci argumanı _değiştiricidir_, _"replacer"_. Değiştirici bir fonksiyon ya da bir dizi olabilir, ve değerlerin hangilerinin ve nasıl string'e dönüşeceğini kontrol etmenize izin verir. -Eğer değiştirici _dizi_ ise, sadece dizi içinde ismi geçem özellikler JSON string'e dahil edilmiş olur. Bu durumda, sadece `"level"` ve `"health"` isimli özellikler dahil edildi, `"username"` dışarıda bırakıldı. `data`, `"{"level":19, "health":90}"` eşittir. +Eğer değiştirici _dizi_ ise, sadece dizi içinde ismi geçem özellikler JSON string'e dahil edilmiş olur. Bu durumda, sadece `"level"` ve `"health"` isimli özellikler dahil edildi, `"username"` dışarıda bırakıldı. `data`, `"{"level":19, "health":90}"` eşittir. Eğer değiştirici _fonksiyon_ ise, stringe dönüştürülen her özellik için bu fonksiyon çağrılır. Bu fonksiyondan dönen değer, JSON stringe eklenmiş olacak özelliğin değeri olacaktır. Eğer değer `undefined`'sa, bu özellik JSON stringe dahil edilmez. @@ -1944,7 +1937,7 @@ Eğer değiştirici _fonksiyon_ ise, stringe dönüştürülen her özellik içi let num = 10; const increaseNumber = () => num++; -const increasePassedNumber = (number) => number++; +const increasePassedNumber = number => number++; const num1 = increaseNumber(); const num2 = increasePassedNumber(num1); @@ -2032,7 +2025,7 @@ Bu örnekte, geriye bir değer döndürmüyoruz, sadece biriktiricinin değerini Biriktiricinin değeri, bir önceki callback fonksiyonunun dönen değerine eşittir. Eğer, opsiyonel olan `initialValue` agümanını `reduce` methoduna geçmezseniz, biriktiricinin değeri, ilk çağrılışta gelen elemana eşit olur. -İlk çağrılışta, biriktirici (`x`) `1`'dir, ve `y`'nin o anki değeri `2`'dir. callback fonksiyonundan bir şey döndürmüyoruz, biriktiriciyi ve o anki değeri logluyoruz: `1` ve `2` loglanır. +İlk çağrılışta, biriktirici (`x`) `1`'dir, ve `y`'nin o anki değeri `2`'dir. callback fonksiyonundan bir şey döndürmüyoruz, biriktiriciyi ve o anki değeri logluyoruz: `1` ve `2` loglanır. Eğer bir fonksiyondan değer döndürmezseniz, fonksiyon `undefined` döndürür. Sonraki çağrılışta, biriktirici `undefined`, ve o anki geçerli değer `3`'tür. `undefined` ve `3` loglanır. @@ -2053,7 +2046,7 @@ class Dog { }; class Labrador extends Dog { - // 1 + // 1 constructor(name, size) { this.size = size; } @@ -2067,7 +2060,7 @@ class Labrador extends Dog { super(name); this.size = size; } - // 4 + // 4 constructor(name, size) { this.name = name; this.size = size; @@ -2090,7 +2083,7 @@ Türetilmiş bir sınıfta, `super`'i çağırmadan önce `this` anahtar kelimes `super` anahtar kelimesiyle, parent sınıfın yapıcı methodunu verilen argümanlarla beraber çağırırız. Parent sınıfın yapıcısı `name` argümanını alıyor, bu yüzden `super`'e `name`'i vermemiz gerek. -`Dog` sınıfı iki argüman alıyor, `name` `Animal` sınıfından türediğinden, ve `size` `Dog` sınıfı üzerinde ekstra özellik olarak. İkisinin de `Dog` yapıcı methoduna geçilmesi gerek, bu da 2. yapıcı methodda doğru şekilde kullanılarak yapılmıştır. +`Dog` sınıfı iki argüman alıyor, `name` `Animal` sınıfından türediğinden, ve `size` `Dog` sınıfı üzerinde ekstra özellik olarak. İkisinin de `Dog` yapıcı methoduna geçilmesi gerek, bu da 2. yapıcı methodda doğru şekilde kullanılarak yapılmıştır.

@@ -2101,12 +2094,12 @@ Türetilmiş bir sınıfta, `super`'i çağırmadan önce `this` anahtar kelimes ```javascript // index.js -console.log("running index.js"); -import { sum } from "./sum.js"; +console.log('running index.js'); +import { sum } from './sum.js'; console.log(sum(1, 2)); // sum.js -console.log("running sum.js"); +console.log('running sum.js'); export const sum = (a, b) => a + b; ``` @@ -2132,9 +2125,9 @@ CommonJS'deki `require()` ve `import` arasındaki fark budur! `require()` ile, b ###### 68. Çıktısı Nedir? ```javascript -console.log(Number(2) === Number(2)); -console.log(Boolean(false) === Boolean(false)); -console.log(Symbol("foo") === Symbol("foo")); +console.log(Number(2) === Number(2)) +console.log(Boolean(false) === Boolean(false)) +console.log(Symbol('foo') === Symbol('foo')) ``` - A: `true`, `true`, `false` @@ -2157,15 +2150,15 @@ Her Symbol tamamen benzersizdir. Symbol'e geçilen argümanın amacı, Symbol'e ###### 69. Çıktısı Nedir? ```javascript -const name = "Lydia Hallie"; -console.log(name.padStart(13)); -console.log(name.padStart(2)); +const name = "Lydia Hallie" +console.log(name.padStart(13)) +console.log(name.padStart(2)) ``` - A: `"Lydia Hallie"`, `"Lydia Hallie"` - B: `" Lydia Hallie"`, `" Lydia Hallie"` (`"[13x whitespace]Lydia Hallie"`, `"[2x whitespace]Lydia Hallie"`) - C: `" Lydia Hallie"`, `"Lydia Hallie"` (`"[1x whitespace]Lydia Hallie"`, `"Lydia Hallie"`) -- D: `"Lydia Hallie"`, `"Lyd"`, +- D: `"Lydia Hallie"`, `"Lyd"`,
Cevap

@@ -2198,7 +2191,6 @@ console.log("🥑" + "💻"); #### Cevap: A `+` operatörü ile stringleri birleştirebilirsiniz. Bu örnekte, `"🥑"` ile `"💻"` birleştiriyoruz, `"🥑💻"` olarak sonuçlanıyor. -

@@ -2394,7 +2386,7 @@ Eşitliğin sağ tarafındaki nesneden `name` özelliğini çıkarttığımız z `{ name: myName }` ile, JavaScript'e diyoruz ki; eşitliğin sağ tarafındaki `name` özelliğinin değeriyle birlikte `myName` diye bir değişken tanımlamak istiyoruz. -`name`'i loglamayı denediğimizden dolayı, ki bu değişken tanımlanmamış, ReferenceError fırlatılır. +`name`'i loglamayı denediğimizden dolayı, ki bu değişken tanımlanmamış, ReferenceError fırlatılır.

@@ -2431,7 +2423,7 @@ Saf fonksiyon, aynı argümanlar geçildiği zaman, _her zaman_ aynı sonucu dö ```javascript const add = () => { const cache = {}; - return (num) => { + return num => { if (num in cache) { return `From cache! ${cache[num]}`; } else { @@ -2463,9 +2455,9 @@ console.log(addFunction(5 * 2)); Eğer `addFunction` fonksiyonunu aynı argüman ile tekrar çağırırsak, önce cache içinde o değerin hali hazırda olup olmadığını kontrol eder. Eğer varsa, cache değeri döndürülecektir ki böylece çalışma zamanından tasarruf sağlanır. Eğer yoksa, cache'lenmemişse, değeri hesaplayıp ardından saklayacaktır. `addFunction` fonksiyonunu üç kez aynı değer ile çağırıyoruz: ilk çağırmada, `num` `10`'a eşit olduğu zaman fonksiyonun değeri henüz cache'lenmemiş. `num in cache` if ifadesi `false` döndürür -ve else bloğu çalıştırılır: `Calculated! 20` loglanır, ve sonuç cache nesnesine eklenir. `cache` şimdi şuna benziyor; `{ 10: 20 }` + ve else bloğu çalıştırılır: `Calculated! 20` loglanır, ve sonuç cache nesnesine eklenir. `cache` şimdi şuna benziyor; `{ 10: 20 }` -İkincide, `cache` nesnesi `10` için döndürülen değeri içeriyor. `num in cache` if ifadesi `true` döndürür, ve `'From cache! 20'` loglanır. +İkincide, `cache` nesnesi `10` için döndürülen değeri içeriyor. `num in cache` if ifadesi `true` döndürür, ve `'From cache! 20'` loglanır. Üçüncü sefer de, fonksiyona `5 * 2` geçiyoruz ki bu da `10` olarak değerlendirilir. `cache` nesnesi `10` için döndürülen değeri içeriyor. `num in cache` if ifadesi `true` döndürür, ve `'From cache! 20'` loglanır. @@ -2477,21 +2469,21 @@ ve else bloğu çalıştırılır: `Calculated! 20` loglanır, ve sonuç cache n ###### 79. Çıktısı Nedir? ```javascript -const myLifeSummedUp = ["☕", "💻", "🍷", "🍫"]; +const myLifeSummedUp = ["☕", "💻", "🍷", "🍫"] for (let item in myLifeSummedUp) { - console.log(item); + console.log(item) } for (let item of myLifeSummedUp) { - console.log(item); + console.log(item) } ``` - A: `0` `1` `2` `3` ve `"☕"` ` "💻"` `"🍷"` `"🍫"` - B: `"☕"` ` "💻"` `"🍷"` `"🍫"` ve `"☕"` ` "💻"` `"🍷"` `"🍫"` - C: `"☕"` ` "💻"` `"🍷"` `"🍫"` ve `0` `1` `2` `3` -- D: `0` `1` `2` `3` ve `{0: "☕", 1: "💻", 2: "🍷", 3: "🍫"}` +- D: `0` `1` `2` `3` ve `{0: "☕", 1: "💻", 2: "🍷", 3: "🍫"}`
Cevap

@@ -2514,14 +2506,14 @@ _for-of_ döngüsü ile, **yinelenebilirler** (**iterables**) üzerinde iterasyo ###### 80. Çıktısı Nedir? ```javascript -const list = [1 + 2, 1 * 2, 1 / 2]; -console.log(list); +const list = [1 + 2, 1 * 2, 1 / 2] +console.log(list) ``` - A: `["1 + 2", "1 * 2", "1 / 2"]` - B: `["12", 2, 0.5]` - C: `[3, 2, 0.5]` -- D: `[1, 1, 1]` +- D: `[1, 1, 1]`

Cevap

@@ -2541,16 +2533,16 @@ Eleman dönen değere eşit olacaktır. `1 + 2` `3` döndürür, `1 * 2` `2` dö ```javascript function sayHi(name) { - return `Hi there, ${name}`; + return `Hi there, ${name}` } -console.log(sayHi()); +console.log(sayHi()) ``` - A: `Hi there, ` - B: `Hi there, undefined` - C: `Hi there, null` -- D: `ReferenceError` +- D: `ReferenceError`

Cevap

@@ -2573,21 +2565,21 @@ Bu örnekte, eğer bir değer geçmeseydik ya da `undefined` geçseydik, `name` ###### 82. Çıktısı Nedir? ```javascript -var status = "😎"; +var status = "😎" setTimeout(() => { - const status = "😍"; + const status = "😍" const data = { status: "🥑", getStatus() { - return this.status; - }, - }; + return this.status + } + } - console.log(data.getStatus()); - console.log(data.getStatus.call(this)); -}, 0); + console.log(data.getStatus()) + console.log(data.getStatus.call(this)) +}, 0) ``` - A: `"🥑"` ve `"😍"` @@ -2614,13 +2606,13 @@ setTimeout(() => { ```javascript const person = { name: "Lydia", - age: 21, -}; + age: 21 +} -let city = person.city; -city = "Amsterdam"; +let city = person.city +city = "Amsterdam" -console.log(person); +console.log(person) ``` - A: `{ name: "Lydia", age: 21 }` @@ -2632,13 +2624,13 @@ console.log(person);

#### Cevap: A - + `city` değişkenini, `person` nesnesindeki `city` özelliğinin değerine eşitledik. `person` nesnesinde `city` diye isimlendirilmiş bir özellik yok, bu yüzden `city` değişkeni `undefined` değerine sahip olur. `person` nesnesinin kendisini referans _göstermediğimize_ dikkat edin! Sadece `city` değişkenini, `person` nesnesindeki `city` özelliğinin o andaki değerine eşitledik. Sonra, `city`'i `"Amsterdam"` string'ine eşitledik. Bu `person` nesnesini değiştirmez: bu nesneye referans yok. - + `person` nesnesini logladığımız zaman, değişikliğe uğramamış nesne döndürülür.

@@ -2651,15 +2643,15 @@ Sonra, `city`'i `"Amsterdam"` string'ine eşitledik. Bu `person` nesnesini deği ```javascript function checkAge(age) { if (age < 18) { - const message = "Sorry, you're too young."; + const message = "Sorry, you're too young." } else { - const message = "Yay! You're old enough!"; + const message = "Yay! You're old enough!" } - return message; + return message } -console.log(checkAge(21)); +console.log(checkAge(21)) ``` - A: `"Sorry, you're too young."` @@ -2682,15 +2674,15 @@ console.log(checkAge(21)); ###### 85. Loglanacak değer ne tür olur? ```javascript -fetch("https://www.website.com/api/user/1") - .then((res) => res.json()) - .then((res) => console.log(res)); +fetch('https://www.website.com/api/user/1') + .then(res => res.json()) + .then(res => console.log(res)) ``` - A: `fetch` methodunun sonucu. - B: `fetch` methodunun ikinci kez çağrılmasından dönen sonuç. - C: Bir önceki `.then()`'in sonucu. -- D: Her zaman `undefined` olacaktır. +- D: Her zaman `undefined` olacaktır.
Cevap

@@ -2738,7 +2730,7 @@ function getName(name) { ###### 87. Çıktısı Nedir? ```javascript -console.log("I want pizza"[0]); +console.log("I want pizza"[0]) ``` - A: `"""` @@ -2764,10 +2756,10 @@ Bu yöntemin IE7 ve altında desteklenmediğine dikkat edin. Bu durumda, `.charA ```javascript function sum(num1, num2 = num1) { - console.log(num1 + num2); + console.log(num1 + num2) } -sum(10); +sum(10) ``` - A: `NaN` @@ -2781,7 +2773,7 @@ sum(10); #### Cevap: B Varsayılan parametrenin değerini fonksiyonun başka parametresine eşitleyebilirsiniz, varsayılan parametreden _önce_ tanımladıkları müddetçe. `sum` fonksiyonuna `10` değerini geçtik. Eğer `sum` fonksiyonu sadece 1 argüman alırsa, `num2` değeri geçilmedi demektir, ve `num1`'ın değeri geçtiğimiz `10` değerine eşittir bu durumda. `num2`'nun varsayılan değeri `num1`'dır ki o da `10`'dur. `num1 + num2` `20` döndürür. - + Eğer varsayılan parametrenin değerini, _sonrasında_ (sağında) tanımlanmış bir parametreye eşitlemeye çalışıyorsanız, parametrenin değeri henüz oluşturulmamıştır, hata fırlatacaktır.

@@ -2792,14 +2784,14 @@ Eğer varsayılan parametrenin değerini, _sonrasında_ (sağında) tanımlanmı ###### 89. Çıktısı Nedir? ```javascript -// module.js -export default () => "Hello world"; -export const name = "Lydia"; +// module.js +export default () => "Hello world" +export const name = "Lydia" -// index.js -import * as data from "./module"; +// index.js +import * as data from "./module" -console.log(data); +console.log(data) ``` - A: `{ default: function default(), name: "Lydia" }` @@ -2826,12 +2818,12 @@ console.log(data); ```javascript class Person { constructor(name) { - this.name = name; + this.name = name } } -const member = new Person("John"); -console.log(typeof member); +const member = new Person("John") +console.log(typeof member) ``` - A: `"class"` @@ -2848,7 +2840,7 @@ Sınıflar fonksiyon yapıcıları için "syntactical sugar"dır. `Person` sın ```javascript function Person() { - this.name = name; + this.name = name } ``` @@ -2862,9 +2854,9 @@ Bir fonksiyon yapıcısını `new` ile çağırmak `Person` "instance" oluşturu ###### 91. Çıktısı Nedir? ```javascript -let newList = [1, 2, 3].push(4); +let newList = [1, 2, 3].push(4) -console.log(newList.push(5)); +console.log(newList.push(5)) ``` - A: `[1, 2, 3, 4, 5]` @@ -2877,7 +2869,7 @@ console.log(newList.push(5)); #### Cevap: D -`.push` methodu dizinin _yeni uzunluğunu_ döndürür, dizinin kendisini değil! `newList`'i `[1, 2, 3].push(4)`'a eşitleyerek, `newList`'i dizinin yeni uzunluğuna eşitledik: `4`. +`.push` methodu dizinin _yeni uzunluğunu_ döndürür, dizinin kendisini değil! `newList`'i `[1, 2, 3].push(4)`'a eşitleyerek, `newList`'i dizinin yeni uzunluğuna eşitledik: `4`. Sonra, `.push` methodunu `newList` üzerinde kullanmayı denedik. `newList` sayısal değer `4` olduğundan, `.push` methodunu kullanamayız: TypeError fırlatılır. @@ -2890,18 +2882,17 @@ Sonra, `.push` methodunu `newList` üzerinde kullanmayı denedik. `newList` say ```javascript function giveLydiaPizza() { - return "Here is pizza!"; + return "Here is pizza!" } -const giveLydiaChocolate = () => - "Here's chocolate... now go hit the gym already."; +const giveLydiaChocolate = () => "Here's chocolate... now go hit the gym already." -console.log(giveLydiaPizza.prototype); -console.log(giveLydiaChocolate.prototype); +console.log(giveLydiaPizza.prototype) +console.log(giveLydiaChocolate.prototype) ``` -- A: `{ constructor: ...}` `{ constructor: ...}` -- B: `{}` `{ constructor: ...}` +- A: `{ constructor: ...}` `{ constructor: ...}` +- B: `{}` `{ constructor: ...}` - C: `{ constructor: ...}` `{}` - D: `{ constructor: ...}` `undefined` @@ -2910,7 +2901,7 @@ console.log(giveLydiaChocolate.prototype); #### Cevap: D -Sıradan fonksiyonlar, `giveLydiaPizza` gibi, `constructor` özelliği olan `prototype` nesnesi özelliğine sahiptir. Ancak ok fonksiyonlar (arrow functions), `giveLydiaChocolate` gibi, bu `prototype` özelliğine sahip değildir. `giveLydiaChocolate.prototype` ile `prototype` özelliğine erişmeye çalışıldığında `undefined` döndürülür. +Sıradan fonksiyonlar, `giveLydiaPizza` gibi, `constructor` özelliği olan `prototype` nesnesi özelliğine sahiptir. Ancak ok fonksiyonlar (arrow functions), `giveLydiaChocolate` gibi, bu `prototype` özelliğine sahip değildir. `giveLydiaChocolate.prototype` ile `prototype` özelliğine erişmeye çalışıldığında `undefined` döndürülür.

@@ -2922,16 +2913,16 @@ Sıradan fonksiyonlar, `giveLydiaPizza` gibi, `constructor` özelliği olan `pro ```javascript const person = { name: "Lydia", - age: 21, -}; + age: 21 +} for (const [x, y] of Object.entries(person)) { - console.log(x, y); + console.log(x, y) } ``` - A: `name` `Lydia` ve `age` `21` -- B: `["name", "Lydia"]` ve `["age", 21]` +- B: `["name", "Lydia"]` ve `["age", 21]` - C: `["name", "age"]` ve `undefined` - D: `Error` @@ -2942,7 +2933,7 @@ for (const [x, y] of Object.entries(person)) { `Object.entries(person)` key ve nesneleri içeren dizilerden oluşan dizi döndürür: -`[ [ 'name', 'Lydia' ], [ 'age', 21 ] ]` +`[ [ 'name', 'Lydia' ], [ 'age', 21 ] ]` `for-of` döngüsünü kullanarak, dizi içindeki her bir elemanı gezebiliriz, alt dizileri bu örnekte. for-of döngüsü içinde alt dizileri `const [x, y]` kullanarak parçalayabiliriz. `x` alt dizideki ilk elemana, `y` alt dizideki ikinci elemana eşittir. @@ -2965,7 +2956,7 @@ getItems(["banana", "apple"], "pear", "orange") ``` - A: `["banana", "apple", "pear", "orange"]` -- B: `[["banana", "apple"], "pear", "orange"]` +- B: `[["banana", "apple"], "pear", "orange"]` - C: `["banana", "apple", ["pear"], "orange"]` - D: `SyntaxError` @@ -2978,10 +2969,10 @@ getItems(["banana", "apple"], "pear", "orange") ```javascript function getItems(fruitList, favoriteFruit, ...args) { - return [...fruitList, ...args, favoriteFruit]; + return [...fruitList, ...args, favoriteFruit] } -getItems(["banana", "apple"], "pear", "orange"); +getItems(["banana", "apple"], "pear", "orange") ``` Yukarıdaki örnek çalışır. `[ 'banana', 'apple', 'orange', 'pear' ]` dizisini döndürür. @@ -2995,14 +2986,17 @@ Yukarıdaki örnek çalışır. `[ 'banana', 'apple', 'orange', 'pear' ]` dizisi ```javascript function nums(a, b) { - if (a > b) console.log("a is bigger"); - else console.log("b is bigger"); - return; - a + b; + if + (a > b) + console.log('a is bigger') + else + console.log('b is bigger') + return + a + b } -console.log(nums(4, 2)); -console.log(nums(1, 2)); +console.log(nums(4, 2)) +console.log(nums(1, 2)) ``` - A: `a is bigger`, `6` ve `b is bigger`, `3` @@ -3015,13 +3009,13 @@ console.log(nums(1, 2)); #### Cevap: B -JavaScript'te, noktalı virgülü (`;`) özellikle yazmak _zorunda değiliz_, ancak JavaScript motoru ifadelerden sonra noktalı virgül eklemektedir. bu **Automatic Semicolon Insertion**, **Otomatik Noktalı Virgül Ekleme**, olarak adlandırılır. İfade, örneğin, değişkenler ya da `throw`, `return`, `break`, vb. gibi anahtar kelimeler olabilir. - -Burada, bir `return` ifadesi yazdık, ve _yeni bir satırda_ başka bir değer olarak `a + b`. Ancak, `a + b` yeni satırda olduğundan, JavaScript motoru onun aslında bizim döndürmek istediğimiz değer olduğunu bilmiyor. Onun yerine, `return`'den sonra otomatik olarak noktalı virgül ekliyor. Şöyle düşünebilirsiniz: +JavaScript'te, noktalı virgülü (`;`) özellikle yazmak _zorunda değiliz_, ancak JavaScript motoru ifadelerden sonra noktalı virgül eklemektedir. bu **Automatic Semicolon Insertion**, **Otomatik Noktalı Virgül Ekleme**, olarak adlandırılır. İfade, örneğin, değişkenler ya da `throw`, `return`, `break`, vb. gibi anahtar kelimeler olabilir. +Burada, bir `return` ifadesi yazdık, ve _yeni bir satırda_ başka bir değer olarak `a + b`. Ancak, `a + b` yeni satırda olduğundan, JavaScript motoru onun aslında bizim döndürmek istediğimiz değer olduğunu bilmiyor. Onun yerine, `return`'den sonra otomatik olarak noktalı virgül ekliyor. Şöyle düşünebilirsiniz: + ```javascript -return; -a + b; + return; + a + b ``` Fonksiyon `return` anahtar kelimesinden sonra çalışmayı durduracağından, `a + b` asla ulaşılamaz demektir. Eğer hiçbir değer döndürülmezse, fonksiyon `undefined` döndürür. Dikkat etmeniz gereken, `if/else` ifadelerinden sonra otomatik ekleme yapılmadığıdır! @@ -3036,18 +3030,18 @@ Fonksiyon `return` anahtar kelimesinden sonra çalışmayı durduracağından, ` ```javascript class Person { constructor() { - this.name = "Lydia"; + this.name = "Lydia" } } Person = class AnotherPerson { constructor() { - this.name = "Sarah"; + this.name = "Sarah" } -}; +} -const member = new Person(); -console.log(member.name); +const member = new Person() +console.log(member.name) ``` - A: `"Lydia"` @@ -3071,11 +3065,11 @@ Sınıfları diğer sınıf/fonksiyon yapıcılara eşitleyebiliriz. Bu örnekte ```javascript const info = { - [Symbol("a")]: "b", -}; + [Symbol('a')]: 'b' +} -console.log(info); -console.log(Object.keys(info)); +console.log(info) +console.log(Object.keys(info)) ``` - A: `{Symbol('a'): 'b'}` ve `["{Symbol('a')"]` @@ -3090,7 +3084,7 @@ console.log(Object.keys(info)); Symbol _sayılabilir_, "_enumerable_" değildir. Object.keys methodu nesne üzerindeki tüm _sayılabilir_ özellikleri döndürür. Symbol gizli kalır ve boş bir dizi döndürülür. Tüm nesne loglandığı zaman, bütün özellikler görülebilir, sayılabilir olmayanlar bile. -Bu symbol'ün birçok özelliğinden birisidir: tamamen benzersiz bir değer temsil etmenin yanında (ki nesneler üzerindeki kazara isim çakışmasını önler, örneğin aynı nesneye özellikler eklemek isteyen 2 kütüphaneyle çalışırken), ayrıca bu yolla nesne üzerindeki özellikleri "saklayabilirsiniz" (gerçi tamamen değil. `Object.getOwnPropertySymbols()` methodunu kullanarak symbol'lere hala erişebilirsiniz). +Bu symbol'ün birçok özelliğinden birisidir: tamamen benzersiz bir değer temsil etmenin yanında (ki nesneler üzerindeki kazara isim çakışmasını önler, örneğin aynı nesneye özellikler eklemek isteyen 2 kütüphaneyle çalışırken), ayrıca bu yolla nesne üzerindeki özellikleri "saklayabilirsiniz" (gerçi tamamen değil. `Object.getOwnPropertySymbols()` methodunu kullanarak symbol'lere hala erişebilirsiniz).

@@ -3122,13 +3116,13 @@ console.log(getUser(user)) `getList` fonksiyonu argüman olarak bir dizi alır. `getList` fonksiyonunun parentezleri arasında, bu diziyi anında parçalıyoruz. Şu şekilde görebilirsiniz: -`[x, ...y] = [1, 2, 3, 4]` + `[x, ...y] = [1, 2, 3, 4]` -`...y` rest parametresi ile, dizi içinde "geriye kalan" tüm argümanları topluyoruz. Geriye kalan argümanlar `2`, `3`, ve `4` bu durumda. `y`'nin değeri tüm rest parametleri içeren bir dizi. `x`'in değeri `1`'a eşit, yani `[x, y]` logladığımız zaman, `[1, [2, 3, 4]]` loglanır. + `...y` rest parametresi ile, dizi içinde "geriye kalan" tüm argümanları topluyoruz. Geriye kalan argümanlar `2`, `3`, ve `4` bu durumda. `y`'nin değeri tüm rest parametleri içeren bir dizi. `x`'in değeri `1`'a eşit, yani `[x, y]` logladığımız zaman, `[1, [2, 3, 4]]` loglanır. -`getUser` fonksiyonu bir nesne alıyor. Ok fonksiyonlar ile, eğer sadece bir değer döndürmek istiyorsak süslü parentezleri yazmak _zorunda değiliz._ Ancak, bir ok fonksiyondan bir _nesne_ döndürmek istiyorsanız, parentezler arasında yazmak zorundasınız, aksi halde değer döndürülmez! Aşağıdaki fonksiyon bir nesne döndürecektir: + `getUser` fonksiyonu bir nesne alıyor. Ok fonksiyonlar ile, eğer sadece bir değer döndürmek istiyorsak süslü parentezleri yazmak _zorunda değiliz._ Ancak, bir ok fonksiyondan bir _nesne_ döndürmek istiyorsanız, parentezler arasında yazmak zorundasınız, aksi halde değer döndürülmez! Aşağıdaki fonksiyon bir nesne döndürecektir: -`const getUser = user => ({ name: user.name, age: user.age })` +```const getUser = user => ({ name: user.name, age: user.age })``` Bu örnekte değer döndürülmediği için, fonksiyon `undefined` döndürür. @@ -3140,9 +3134,9 @@ Bu örnekte değer döndürülmediği için, fonksiyon `undefined` döndürür. ###### 99. Çıktısı Nedir? ```javascript -const name = "Lydia"; +const name = "Lydia" -console.log(name()); +console.log(name()) ``` - A: `SyntaxError` @@ -3155,11 +3149,11 @@ console.log(name()); #### Cevap: C -`name` değişkeni string bir değer saklıyor, ki bu bir fonksiyon değil, bu yüzden çağrılamaz. + `name` değişkeni string bir değer saklıyor, ki bu bir fonksiyon değil, bu yüzden çağrılamaz. -TypeError'lar bir değer beklenilen tipte olmadığı zaman fırlatılır. `name`'i çağırmaya çalıştığımızdan, JavaScript `name`'in bir fonksiyon olmasını bekliyor. Ancak o bir string, bu yüzden TypeError fırlatılır: name is not a function! +TypeError'lar bir değer beklenilen tipte olmadığı zaman fırlatılır. `name`'i çağırmaya çalıştığımızdan, JavaScript `name`'in bir fonksiyon olmasını bekliyor. Ancak o bir string, bu yüzden TypeError fırlatılır: name is not a function! -SyntaxError'lar JavaScript'in geçerli olmadığı bir şeyler yazdığız zaman fırlatılır, örneğin `return`'ü `retrun` olarak yazdığınız zaman. +SyntaxError'lar JavaScript'in geçerli olmadığı bir şeyler yazdığız zaman fırlatılır, örneğin `return`'ü `retrun` olarak yazdığınız zaman. ReferenceError'lar erişmeye çalıştığınız değer için JavaScript referans bulamadığı zaman fırlatılır. @@ -3173,8 +3167,8 @@ ReferenceError'lar erişmeye çalıştığınız değer için JavaScript referan ```javascript // 🎉✨ 100. soru! ✨🎉 -const output = `${[] && "Im"}possible! -You should${"" && `n't`} see a therapist after so much JavaScript lol`; +const output = `${[] && 'Im'}possible! +You should${'' && `n't`} see a therapist after so much JavaScript lol` ``` - A: `possible! You should see a therapist after so much JavaScript lol` @@ -3189,7 +3183,7 @@ You should${"" && `n't`} see a therapist after so much JavaScript lol`; `[]` doğrusal bir değerdir. `&&` operatörü ile, eğer soldaki değer doğrusal bir değerse sağdaki değer döndürülür. Bu örnekte, soldaki değer `[]` doğrusal bir değerdir, böylece `"Im"` döndürülür. -`""` yanlış-ımsı bir değerdir. Eğer soldaki değer yanlış-ımsı ise, bir şey döndürülmez. `n't` döndürülmedi. +`""` yanlış-ımsı bir değerdir. Eğer soldaki değer yanlış-ımsı ise, bir şey döndürülmez. `n't` döndürülmedi.

@@ -3199,11 +3193,11 @@ You should${"" && `n't`} see a therapist after so much JavaScript lol`; ###### 101. Çıktısı Nedir? ```javascript -const one = false || {} || null; -const two = null || false || ""; -const three = [] || 0 || true; +const one = (false || {} || null) +const two = (null || false || "") +const three = ([] || 0 || true) -console.log(one, two, three); +console.log(one, two, three) ``` - A: `false` `null` `[]` diff --git a/uk-UA/README.md b/uk-UA/README.md index aeb4f3ee..3b38c921 100644 --- a/uk-UA/README.md +++ b/uk-UA/README.md @@ -20,7 +20,6 @@ - [🇳🇱 Nederlands](../nl-NL/README.md) - [🇵🇱 Polski](../pl-PL/README.md) - [🇧🇷 Português Brasil](../pt-BR/README_pt_BR.md) -- [🇷o Română](../ro-RO/README.ro.md) - [🇷🇺 Русский](../ru-RU/README.md) - [🇽🇰 Shqip](../sq-KS/README_sq_KS.md) - [🇹🇭 ไทย](../th-TH/README-th_TH.md) @@ -101,7 +100,7 @@ const shape = { diameter() { return this.radius * 2; }, - perimeter: () => 2 * Math.PI * this.radius, + perimeter: () => 2 * Math.PI * this.radius }; shape.diameter(); @@ -158,12 +157,12 @@ shape.perimeter(); ```javascript const bird = { - size: "small", + size: "small" }; const mouse = { name: "Mickey", - small: true, + small: true }; ``` @@ -357,7 +356,7 @@ function Person(firstName, lastName) { } const member = new Person("Lydia", "Hallie"); -Person.getFullName = function () { +Person.getFullName = function() { return `${this.firstName} ${this.lastName}`; }; @@ -377,7 +376,7 @@ console.log(member.getFullName()); Не можна додавати властивості конструктору, як звичайному об'єкту. Якщо потрібно додати фічу до всіх об'єктів, то необхідно використовувати прототипи. В даному випадку, ```js -Person.prototype.getFullName = function () { +Person.prototype.getFullName = function() { return `${this.firstName} ${this.lastName}`; }; ``` @@ -833,7 +832,7 @@ String.prototype.giveLydiaPizza = () => { const name = "Lydia"; -console.log(name.giveLydiaPizza()); +console.log(name.giveLydiaPizza()) ``` - A: `"Just give Lydia pizza already!"` @@ -945,7 +944,9 @@ baz(); ```html
- +
``` @@ -971,7 +972,9 @@ baz(); ```html
-

Click here!

+

+ Click here! +

``` @@ -1206,10 +1209,7 @@ console.log(numbers); ###### 40. Що буде в консолі? ```javascript -[ - [0, 1], - [2, 3], -].reduce( +[[0, 1], [2, 3]].reduce( (acc, cur) => { return acc.concat(cur); }, @@ -1344,20 +1344,21 @@ console.log(gen.next().value);

+ --- ###### 45. Що повернеться? ```javascript const firstPromise = new Promise((res, rej) => { - setTimeout(res, 500, "one"); + setTimeout(res, 500, 'one'); }); const secondPromise = new Promise((res, rej) => { - setTimeout(res, 100, "two"); + setTimeout(res, 100, 'two'); }); -Promise.race([firstPromise, secondPromise]).then((res) => console.log(res)); +Promise.race([firstPromise, secondPromise]).then(res => console.log(res)); ``` - A: `"one"` @@ -1380,7 +1381,7 @@ Promise.race([firstPromise, secondPromise]).then((res) => console.log(res)); ###### 46. Що буде на виході? ```javascript -let person = { name: "Lydia" }; +let person = { name: 'Lydia' }; const members = [person]; person = null; diff --git a/vi-VI/README-vi.md b/vi-VI/README-vi.md index 249532dd..8750b2d6 100644 --- a/vi-VI/README-vi.md +++ b/vi-VI/README-vi.md @@ -7,7 +7,6 @@ Các câu hỏi sẽ từ cơ bản đến nâng cao: kiểm tra trình độ Ja Các đáp án được đặt dưới mỗi câu hỏi, hãy click để tham khảo chúng. Chúc may mắn :heart: Danh sách các ngôn ngữ khác: - - [🇸🇦 العربية](../ar-AR/README_AR.md) - [🇪🇬 اللغة العامية](../ar-EG/README_ar-EG.md) - [🇧🇦 Bosanski](../bs-BS/README-bs_BS.md) @@ -22,7 +21,6 @@ Danh sách các ngôn ngữ khác: - [🇳🇱 Nederlands](../nl-NL/README.md) - [🇵🇱 Polski](../pl-PL/README.md) - [🇧🇷 Português Brasil](../pt-BR/README_pt_BR.md) -- [🇷o Română](../ro-RO/README.ro.md) - [🇷🇺 Русский](../ru-RU/README.md) - [🇽🇰 Shqip](../sq-KS/README_sq_KS.md) - [🇹🇭 ไทย](../th-TH/README-th_TH.md) @@ -103,7 +101,7 @@ const shape = { diameter() { return this.radius * 2; }, - perimeter: () => 2 * Math.PI * this.radius, + perimeter: () => 2 * Math.PI * this.radius }; shape.diameter(); @@ -149,7 +147,7 @@ Khi không có giá trị `radius` tại object đó, nó sẽ trả về `undef Phép toán cộng `+` sẽ convert một toán hạng sang dạng number. `true` là `1`, và `false` is `0`. -Chuỗi `'Lydia'` là một _truthy value_. Điều chúng ta thật sự đang hỏi chính là "có phải một giá trị truthy là falsy?". Rõ ràng câu trả lời là `false` rồi. +Chuỗi `'Lydia'` là một _truthy value_. Điều chúng ta thật sự đang hỏi chính là "có phải một giá trị truthy là falsy?". Rõ ràng câu trả lời là `false` rồi.

@@ -160,12 +158,12 @@ Chuỗi `'Lydia'` là một _truthy value_. Điều chúng ta thật sự đang ```javascript const bird = { - size: "small", + size: "small" }; const mouse = { name: "Mickey", - small: true, + small: true }; ``` @@ -185,13 +183,14 @@ JavaScript thông dịch (hay unboxes) từng câu lệnh. Khi chúng ta sử d `mouse[bird.size]`: Giá trị đầu tiên `bird.size` là `"small"`. `mouse["small"]` sẽ trả về `true` -Tuy nhiên, khi chúng ta sử dụng dấu chấm `.`, điều trên không còn đúng nữa. `mouse` không hề có key nào tên là `bird`, có nghĩa `mouse.bird` sẽ là `undefined`. Sau đó chúng ta gọi `size` sử dụng chấm `.`: `mouse.bird.size`. Vì `mouse.bird` là `undefined`, lời gọi sẽ trở thành `undefined.size`. Đây là một lời gọi không hợp lệ, nó sẽ throw ra một lỗi kiểu như `Cannot read property "size" of undefined`. +Tuy nhiên, khi chúng ta sử dụng dấu chấm `.`, điều trên không còn đúng nữa. `mouse` không hề có key nào tên là `bird`, có nghĩa `mouse.bird` sẽ là `undefined`. Sau đó chúng ta gọi `size` sử dụng chấm `.`: `mouse.bird.size`. Vì `mouse.bird` là `undefined`, lời gọi sẽ trở thành `undefined.size`. Đây là một lời gọi không hợp lệ, nó sẽ throw ra một lỗi kiểu như `Cannot read property "size" of undefined`.

--- + ###### 6. Output là gì? ```javascript @@ -214,7 +213,7 @@ console.log(d.greeting); #### Đáp án: A -Trong JavaScript, tất cả các object sẽ được _tham chiếu_ khi chúng được gán \_bằng_wwwww một giá trị khác. +Trong JavaScript, tất cả các object sẽ được _tham chiếu_ khi chúng được gán _bằng_wwwww một giá trị khác. Đầu tiên, giá trị `c` có giá trị là một object. Sau đó, chúng ta gán `d` tham chiếu tới object mà `c` trỏ tới. @@ -359,7 +358,7 @@ function Person(firstName, lastName) { } const member = new Person("Lydia", "Hallie"); -Person.getFullName = function () { +Person.getFullName = function() { return `${this.firstName} ${this.lastName}`; }; @@ -379,7 +378,7 @@ console.log(member.getFullName()); Chúng ta không thể add thêm một thuộc tính cho một constructor giống như một object thông thường. Nếu bạn muốn add thêm thuộc tính nào đó cho tất cả các object một lần, bạn phải dùng `prototype`. Trong trường hợp này cũng vậy. ```js -Person.prototype.getFullName = function () { +Person.prototype.getFullName = function() { return `${this.firstName} ${this.lastName}`; }; ``` @@ -836,7 +835,7 @@ String.prototype.giveLydiaPizza = () => { const name = "Lydia"; -console.log(name.giveLydiaPizza()); +console.log(name.giveLydiaPizza()) ``` - A: `"Just give Lydia pizza already!"` @@ -948,7 +947,9 @@ WebAPI không thể thêm thứ gì đó vào stack cho tới khi nó được s ```html
- +
``` @@ -974,7 +975,9 @@ Phần tử sâu nhất trong các phần tử lồng nhau sẽ là target của ```html
-

Click here!

+

+ Click here! +

``` @@ -1209,10 +1212,7 @@ Primitive types là `boolean`, `null`, `undefined`, `bigint`, `number`, `string` ###### 40. Output là gì? ```javascript -[ - [0, 1], - [2, 3], -].reduce( +[[0, 1], [2, 3]].reduce( (acc, cur) => { return acc.concat(cur); }, @@ -1360,7 +1360,7 @@ const secondPromise = new Promise((res, rej) => { setTimeout(res, 100, "two"); }); -Promise.race([firstPromise, secondPromise]).then((res) => console.log(res)); +Promise.race([firstPromise, secondPromise]).then(res => console.log(res)); ``` - A: `"one"` @@ -1424,7 +1424,7 @@ Chúng ta chỉ đơn thuần là thay đổi giá trị của biến `person` m ```javascript const person = { name: "Lydia", - age: 21, + age: 21 }; for (const item in person) { @@ -1504,7 +1504,7 @@ Chỉ có số đầu tiên trong chuỗi kí tự được trả về. Hệ cơ ###### 50. Output là gì? ```javascript -[1, 2, 3].map((num) => { +[1, 2, 3].map(num => { if (typeof num === "number") return; return num * 2; }); @@ -1681,7 +1681,7 @@ class Dog { } } -Dog.prototype.bark = function () { +Dog.prototype.bark = function() { console.log(`Woof I am ${this.name}`); }; @@ -1767,7 +1767,7 @@ console.log(myCounter); #### Đáp án: C -Một module khi được import sẽ là **read-only**: chúng ta sẽ không thể chỉnh sửa module đó, chỉ có bản thân module đó có thể chỉnh sửa giá trị của nó mà thôi. +Một module khi được import sẽ là __read-only__: chúng ta sẽ không thể chỉnh sửa module đó, chỉ có bản thân module đó có thể chỉnh sửa giá trị của nó mà thôi. Khi ta thay đổi giá trị cuả `myCounter`, nó sẽ throw ra một lỗi: `myCounter` là _read-only_ và không thể thay đổi. @@ -1909,7 +1909,7 @@ Thêm nữa, các thuộc tính được thêm bởi `defineProperty` là mặc const settings = { username: "lydiahallie", level: 19, - health: 90, + health: 90 }; const data = JSON.stringify(settings, ["level", "health"]); @@ -1943,7 +1943,7 @@ Nếu replacer là _function_, hàm này sẽ được gọi trên từng thuộ let num = 10; const increaseNumber = () => num++; -const increasePassedNumber = (number) => number++; +const increasePassedNumber = number => number++; const num1 = increaseNumber(); const num2 = increasePassedNumber(num1); @@ -2000,9 +2000,9 @@ Trong ES6 thì chúng ta có thể khởi tạo tham số với giá trị mặc Chú ý một điều là đối số sẽ được xét giá trị tại _call time_! Có nghĩa là mỗi khi chúng ta gọi hàm, một _object mới_ sẽ được tạo ra. Chúng ta gọi hàm `multiply` hai lần mà không truyền vào đối số nào cả: `x` sẽ nhận giá trị mặc định `{ number: 10 }`. Sau đó chúng ta sẽ ghi ra giá trị là `20`. -Lần gọi thứ ba chúng ta truyền vào một đối số: chính là `value`. Toán tử `*=` chính là cách viết gọn của `x.number = x.number * 2`: chúng ta thay đổi giá trị của `x.number`, và ghi ra giá trị `20`. +Lần gọi thứ ba chúng ta truyền vào một đối số: chính là `value`. Toán tử `*=` chính là cách viết gọn của `x.number = x.number * 2`: chúng ta thay đổi giá trị của `x.number`, và ghi ra giá trị `20`. -Tại lần gọi thứ tư, chúng ta truyền vào `value` một lần nữa. `x.number` trước đó đã bị thay đổi thành `20`, nên `x.number *= 2` sẽ ghi ra `40`. +Tại lần gọi thứ tư, chúng ta truyền vào `value` một lần nữa. `x.number` trước đó đã bị thay đổi thành `20`, nên `x.number *= 2` sẽ ghi ra `40`.

@@ -2025,18 +2025,17 @@ Tại lần gọi thứ tư, chúng ta truyền vào `value` một lần nữa. #### Đáp án: D -Đối số đầu tiên của hàm `reduce` chính là _accumulator_ (tổng tích lũy), trong trường hợp này là `x`. Đối số thứ 2 chính là _giá trị hiện tại_, tức `y`. Với hàm reduce, ta sẽ gọi callback trên mỗi phần tử của mảng, cứ vậy cho tới khi ra đến một giá trị cuối cùng. +Đối số đầu tiên của hàm `reduce` chính là _accumulator_ (tổng tích lũy), trong trường hợp này là `x`. Đối số thứ 2 chính là _giá trị hiện tại_, tức `y`. Với hàm reduce, ta sẽ gọi callback trên mỗi phần tử của mảng, cứ vậy cho tới khi ra đến một giá trị cuối cùng. Trong trường hợp này, chúng ta không trả về bất cứ giá trị nào cả, mà đơn thuần chỉ là ghi ra giá trị của _tổng tích lũy_ và _giá trị hiện tại_ mà thôi. Giá trị của tổng tích lũy chính là giá trị được hàm callback trả về tại vòng lặp trước đó. Nếu ta không đặt giá trị khởi tạo cho đối số trong hàm `reduce`, thì tổng tích lũy sẽ chính bằng giá trị đầu tiên tại lời gọi đầu tiên. -Trong lời gọi đầu tiên, tổng tích lũy (`x`) là `1`, và giá trị hiện tại (`y`) là `2`. Chúng ta không trả về giá trị cho hàm callback, mà đơn thuần chỉ ghi chúng ta, vậy nên `1` và `2` được ghi ra. +Trong lời gọi đầu tiên, tổng tích lũy (`x`) là `1`, và giá trị hiện tại (`y`) là `2`. Chúng ta không trả về giá trị cho hàm callback, mà đơn thuần chỉ ghi chúng ta, vậy nên `1` và `2` được ghi ra. -Nếu ta không trả về giá trị trong một function, thì nó sẽ mặc định trả về là `undefined`. Do đó trong lời gọi tiếp theo tổng tích lũy sẽ là `undefined`, và giá trị hiện tại là `3`. `undefined` và `3` sẽ được ghi ra. +Nếu ta không trả về giá trị trong một function, thì nó sẽ mặc định trả về là `undefined`. Do đó trong lời gọi tiếp theo tổng tích lũy sẽ là `undefined`, và giá trị hiện tại là `3`. `undefined` và `3` sẽ được ghi ra. Tiếp tục như vậy, trong lời gọi thứ tư thì tổng tích lũy sẽ vẫn là `undefined`, giá trị hiện tại là `4`. `undefined` và `4` sẽ được ghi ra. -

@@ -2052,7 +2051,7 @@ class Dog { }; class Labrador extends Dog { - // 1 + // 1 constructor(name, size) { this.size = size; } @@ -2066,7 +2065,7 @@ class Labrador extends Dog { super(name); this.size = size; } - // 4 + // 4 constructor(name, size) { this.name = name; this.size = size; @@ -2087,10 +2086,9 @@ class Labrador extends Dog { Trong class dẫn xuất, ta không thể truy cập từ khóa `this` trước khi gọi `super`. Nếu bạn chạy thử, nó sẽ throw ra một `ReferenceError`, do đó 1 và 4 sẽ throw ra reference error. -Với việc gọi `super`, chúng ta đã gọi hàm constructor của class cha với tham số truyền vào. Trong trường hợp này, class cha nhận `name` làm đối số trong constructor, do đó chúng cần đưa `name` vào hàm `super`. +Với việc gọi `super`, chúng ta đã gọi hàm constructor của class cha với tham số truyền vào. Trong trường hợp này, class cha nhận `name` làm đối số trong constructor, do đó chúng cần đưa `name` vào hàm `super`. `Labrador` class nhận vào hai đối số, `name` vì nó kế thừa `Dog`, và `size` - một thuộc tính của `Labrador` class. Cả hai đều cần thiết để đưa vào trong constructor của class `Labrador`, do đó cách khởi tạo đúng là 2. -

@@ -2100,12 +2098,12 @@ Với việc gọi `super`, chúng ta đã gọi hàm constructor của class ch ```javascript // index.js -console.log("running index.js"); -import { sum } from "./sum.js"; +console.log('running index.js'); +import { sum } from './sum.js'; console.log(sum(1, 2)); // sum.js -console.log("running sum.js"); +console.log('running sum.js'); export const sum = (a, b) => a + b; ``` @@ -2121,7 +2119,7 @@ export const sum = (a, b) => a + b; Với `import`, tất cả các module import vào đều sẽ được _pre-parsed_ (đánh giá trước). Có nghĩa là những module được import vào sẽ được _chạy trước_, còn code trong file sẽ _chạy sau_. -Đó chính là điều khác biệt giữa `require()` trong CommonJS và `import`! Với `require()`, ta có thể load các dependencies tại bất cứ khi nào ta cần. Nếu ta sử dụng `require` thay thế cho `import` thì `running index.js`, `running sum.js`, `3` sẽ được ghi ra. +Đó chính là điều khác biệt giữa `require()` trong CommonJS và `import`! Với `require()`, ta có thể load các dependencies tại bất cứ khi nào ta cần. Nếu ta sử dụng `require` thay thế cho `import` thì `running index.js`, `running sum.js`, `3` sẽ được ghi ra.

@@ -2146,7 +2144,7 @@ console.log(Symbol('foo') === Symbol('foo'))**** #### Đáp án: A -Mỗi Symbol là một thứ hoàn toàn khác biệt. Giá trị truyền vào làm đối số trong Symbol chỉ đơn thuần là phần giải thích cho Symbol đó mà thôi, và nó không liên quan gì tới giá trị của Symbol đó cả. Chúng ta kiểm tra tính bằng nhau của hai Symbol hoàn toàn khác biệt: `Symbol('foo')` thứ nhất, và `Symbol('foo')` thứ hai. Mỗi giá trị đều là riêng biệt và duy nhất, nên `Symbol('foo') === Symbol('foo')` sẽ trả về `false`. +Mỗi Symbol là một thứ hoàn toàn khác biệt. Giá trị truyền vào làm đối số trong Symbol chỉ đơn thuần là phần giải thích cho Symbol đó mà thôi, và nó không liên quan gì tới giá trị của Symbol đó cả. Chúng ta kiểm tra tính bằng nhau của hai Symbol hoàn toàn khác biệt: `Symbol('foo')` thứ nhất, và `Symbol('foo')` thứ hai. Mỗi giá trị đều là riêng biệt và duy nhất, nên `Symbol('foo') === Symbol('foo')` sẽ trả về `false`.

@@ -2156,15 +2154,15 @@ Mỗi Symbol là một thứ hoàn toàn khác biệt. Giá trị truyền vào ###### 69. Output là gì? ```javascript -const name = "Lydia Hallie"; -console.log(name.padStart(13)); -console.log(name.padStart(2)); +const name = "Lydia Hallie" +console.log(name.padStart(13)) +console.log(name.padStart(2)) ``` - A: `"Lydia Hallie"`, `"Lydia Hallie"` - B: `" Lydia Hallie"`, `" Lydia Hallie"` (`"[13x whitespace]Lydia Hallie"`, `"[2x whitespace]Lydia Hallie"`) - C: `" Lydia Hallie"`, `"Lydia Hallie"` (`"[1x whitespace]Lydia Hallie"`, `"Lydia Hallie"`) -- D: `"Lydia Hallie"`, `"Lyd"`, +- D: `"Lydia Hallie"`, `"Lyd"`,
Đáp án

@@ -2239,9 +2237,7 @@ Khi ta gọi `game.next("Yes").value`, `yield` trước đó sẽ được thay

--- - ---- - +**** ###### 72. Output là gì? ```javascript @@ -2434,7 +2430,7 @@ Hàm `sum` luôn trả về giá trị giống nhau. Nếu ta đưa vào `1` và ```javascript const add = () => { const cache = {}; - return (num) => { + return num => { if (num in cache) { return `From cache! ${cache[num]}`; } else { @@ -2479,21 +2475,21 @@ Tại lần gọi thứ ba, ta đưa vào `5 * 2`, tức `10` vào hàm. Tiếp ###### 79. Output là gì? ```javascript -const myLifeSummedUp = ["☕", "💻", "🍷", "🍫"]; +const myLifeSummedUp = ["☕", "💻", "🍷", "🍫"] for (let item in myLifeSummedUp) { - console.log(item); + console.log(item) } for (let item of myLifeSummedUp) { - console.log(item); + console.log(item) } ``` - A: `0` `1` `2` `3` and `"☕"` ` "💻"` `"🍷"` `"🍫"` - B: `"☕"` ` "💻"` `"🍷"` `"🍫"` and `"☕"` ` "💻"` `"🍷"` `"🍫"` - C: `"☕"` ` "💻"` `"🍷"` `"🍫"` and `0` `1` `2` `3` -- D: `0` `1` `2` `3` and `{0: "☕", 1: "💻", 2: "🍷", 3: "🍫"}` +- D: `0` `1` `2` `3` and `{0: "☕", 1: "💻", 2: "🍷", 3: "🍫"}`
Đáp án

@@ -2516,14 +2512,14 @@ Với vòng lặp _for-of_, chúng ta sẽ duyệt qua các phần tử của m ###### 80. Output là gì? ```javascript -const list = [1 + 2, 1 * 2, 1 / 2]; -console.log(list); +const list = [1 + 2, 1 * 2, 1 / 2] +console.log(list) ``` - A: `["1 + 2", "1 * 2", "1 / 2"]` - B: `["12", 2, 0.5]` - C: `[3, 2, 0.5]` -- D: `[1, 1, 1]` +- D: `[1, 1, 1]`

Đáp án

@@ -2532,7 +2528,7 @@ console.log(list); Mảng có thể nhận bất cứ giá trị nào. Số, chuỗi, objects, mảng khác, null, boolean, undefined, và nhiều dạng biểu thức nữa như ngày tháng, hàm, và các tính toán. -Giá trị của phần tử chính là giá trị trả về. `1 + 2` trả về `3`, `1 * 2` trả về `2`, và `1 / 2` trả về `0.5`. +Giá trị của phần tử chính là giá trị trả về. `1 + 2` trả về `3`, `1 * 2` trả về `2`, và `1 / 2` trả về `0.5`.

@@ -2543,16 +2539,16 @@ Giá trị của phần tử chính là giá trị trả về. `1 + 2` trả v ```javascript function sayHi(name) { - return `Hi there, ${name}`; + return `Hi there, ${name}` } -console.log(sayHi()); +console.log(sayHi()) ``` - A: `Hi there, ` - B: `Hi there, undefined` - C: `Hi there, null` -- D: `ReferenceError` +- D: `ReferenceError`
Đáp án

@@ -2575,21 +2571,21 @@ Trong trường hợp này, nếu ta không đưa giá trị nào vào hoặc đ ###### 82. Output là gì? ```javascript -var status = "😎"; +var status = "😎" setTimeout(() => { - const status = "😍"; + const status = "😍" const data = { status: "🥑", getStatus() { - return this.status; - }, - }; + return this.status + } + } - console.log(data.getStatus()); - console.log(data.getStatus.call(this)); -}, 0); + console.log(data.getStatus()) + console.log(data.getStatus.call(this)) +}, 0) ``` - A: `"🥑"` and `"😍"` @@ -2616,13 +2612,13 @@ Với phương thức `call`, chúng ta thay đổi tham chiếu mà `this` tr ```javascript const person = { name: "Lydia", - age: 21, -}; + age: 21 +} -let city = person.city; -city = "Amsterdam"; +let city = person.city +city = "Amsterdam" -console.log(person); +console.log(person) ``` - A: `{ name: "Lydia", age: 21 }` @@ -2635,13 +2631,13 @@ console.log(person); #### Đáp án: A -Chúng ta set biến `city` bằng với giá trị của thuộc tính `city` của object `person`. Nhưng object này không có thuộc tính nào là `city` cả, nên giá trị của biến `city` sẽ là `undefined`. +Chúng ta set biến `city` bằng với giá trị của thuộc tính `city` của object `person`. Nhưng object này không có thuộc tính nào là `city` cả, nên giá trị của biến `city` sẽ là `undefined`. Chú ý là chúng ta _không tham chiếu_ tới bản thân object `person`! Chúng ta chỉ đơn giản là set giá trị của biến `city` bằng với giá trị của thuộc tính `city` trong object `person` mà thôi. Sau đó chúng ta set biến `city` bằng với chuỗi `"Amsterdam"`. Điều này không hề ảnh hưởng gì tới object person vì không có tham chiếu nào ở đây cả. -Do đó khi ghi object `person` ra, Tất cả các thuộc tính vẫn như cũ không hề thay đổi gì cả. +Do đó khi ghi object `person` ra, Tất cả các thuộc tính vẫn như cũ không hề thay đổi gì cả.

@@ -2653,15 +2649,15 @@ Do đó khi ghi object `person` ra, Tất cả các thuộc tính vẫn như cũ ```javascript function checkAge(age) { if (age < 18) { - const message = "Sorry, you're too young."; + const message = "Sorry, you're too young." } else { - const message = "Yay! You're old enough!"; + const message = "Yay! You're old enough!" } - return message; + return message } -console.log(checkAge(21)); +console.log(checkAge(21)) ``` - A: `"Sorry, you're too young."` @@ -2684,15 +2680,15 @@ Biến số được khai báo với các từ khóa như `const` hay `let` đ ###### 85. Những thông tin nào sẽ được ghi ra? ```javascript -fetch("https://www.website.com/api/user/1") - .then((res) => res.json()) - .then((res) => console.log(res)); +fetch('https://www.website.com/api/user/1') + .then(res => res.json()) + .then(res => console.log(res)) ``` - A: The result of the `fetch` method. - B: The result of the second invocation of the `fetch` method. - C: The result of the callback in the previous `.then()`. -- D: It would always be undefined. +- D: It would always be undefined.
Đáp án

@@ -2740,7 +2736,7 @@ Bằng cách set `hasName` bằng với `name`, chúng ta set `hasName` bằng v ###### 87. Output là gì? ```javascript -console.log("I want pizza"[0]); +console.log("I want pizza"[0]) ``` - A: `"""` @@ -2766,10 +2762,10 @@ Chú ý là phương thức này không hoạt động với IE7 trở xuống. ```javascript function sum(num1, num2 = num1) { - console.log(num1 + num2); + console.log(num1 + num2) } -sum(10); +sum(10) ``` - A: `NaN` @@ -2784,7 +2780,7 @@ sum(10); Ta có thể set giá trị mặc định của một tham số là tham số khác trong hàm, miễn là tham số đó được khai báo _trước_ tham số mặc định. Chúng ta đưa `10` vào hàm `sum`. Nếu hàm `sum` chỉ nhận 1 đối số, nó có nghĩa là giá trị của `num2` không được đưa vào, nên nó sẽ lấy giá trị mặc định là giá trị của `num1` đã được đưa vào, hay chính là `10` trong trường hợp này. Khi này `num1 + num2` trả về `20`. -Nếu chúng ta thử set một giá trị mặc định của tham số bằng với giá trị của tham số khai báo _sau_ (về bên phải), giá trị của tham số đó sẽ không được khởi tạo và dẫn đến throw ra lỗi. +Nếu chúng ta thử set một giá trị mặc định của tham số bằng với giá trị của tham số khai báo _sau_ (về bên phải), giá trị của tham số đó sẽ không được khởi tạo và dẫn đến throw ra lỗi.

@@ -2794,14 +2790,14 @@ Nếu chúng ta thử set một giá trị mặc định của tham số bằng ###### 89. Output là gì? ```javascript -// module.js -export default () => "Hello world"; -export const name = "Lydia"; +// module.js +export default () => "Hello world" +export const name = "Lydia" -// index.js -import * as data from "./module"; +// index.js +import * as data from "./module" -console.log(data); +console.log(data) ``` - A: `{ default: function default(), name: "Lydia" }` @@ -2814,9 +2810,9 @@ console.log(data); #### Đáp án: A -Cú pháp `import * as data` sẽ import _tất cả những gì được export_ từ `module.js` vào trong `index.js` và lưu trữ dưới một object có tên là `data`. Trong file `module.js`, có hai thứ được export ra: default export và một named export. Default export là một hàm trả về chuỗi `"Hello World"`, và named export là một biến `name` nhận giá trị là chuỗi `"Lydia"`. +Cú pháp `import * as data` sẽ import _tất cả những gì được export_ từ `module.js` vào trong `index.js` và lưu trữ dưới một object có tên là `data`. Trong file `module.js`, có hai thứ được export ra: default export và một named export. Default export là một hàm trả về chuỗi `"Hello World"`, và named export là một biến `name` nhận giá trị là chuỗi `"Lydia"`. -Do đó `data` object có thuộc tính `default` cho default export, các thuộc tính khác sẽ có tên chính là tên của named exports và giá trị đi kèm. +Do đó `data` object có thuộc tính `default` cho default export, các thuộc tính khác sẽ có tên chính là tên của named exports và giá trị đi kèm.

@@ -2828,12 +2824,12 @@ Do đó `data` object có thuộc tính `default` cho default export, các thu ```javascript class Person { constructor(name) { - this.name = name; + this.name = name } } -const member = new Person("John"); -console.log(typeof member); +const member = new Person("John") +console.log(typeof member) ``` - A: `"class"` @@ -2850,11 +2846,11 @@ Classes chỉ đơn thuần là `syntactical sugar` (cú pháp đặc biệt) c ```javascript function Person() { - this.name = name; + this.name = name } ``` -Gọi một constructor với từ khóa `new` sẽ tạo ra một instance của class `Person`, `typeof` sẽ trả về là `"object"` cho các instance. Do đó `typeof member` trả về `"object"`. +Gọi một constructor với từ khóa `new` sẽ tạo ra một instance của class `Person`, `typeof` sẽ trả về là `"object"` cho các instance. Do đó `typeof member` trả về `"object"`.

@@ -2864,9 +2860,9 @@ Gọi một constructor với từ khóa `new` sẽ tạo ra một instance củ ###### 91. Output là gì? ```javascript -let newList = [1, 2, 3].push(4); +let newList = [1, 2, 3].push(4) -console.log(newList.push(5)); +console.log(newList.push(5)) ``` - A: `[1, 2, 3, 4, 5]` @@ -2879,7 +2875,7 @@ console.log(newList.push(5)); #### Đáp án: D -Hàm `.push` trả về _độ dài mới_ của mảng, chứ không phải bản thân mảng đó! Bằng cách set `newList` bằng với `[1, 2, 3].push(4)`, ta đã set cho `newList` giá trị là `4` - tức độ dài của mảng lúc này. +Hàm `.push` trả về _độ dài mới_ của mảng, chứ không phải bản thân mảng đó! Bằng cách set `newList` bằng với `[1, 2, 3].push(4)`, ta đã set cho `newList` giá trị là `4` - tức độ dài của mảng lúc này. Sau đó chúng ta tiến hành `.push` trên `newList`. Vì `newList` là một số thông thường, ta không thể dùng `.push` được, nên sẽ throw ra một TypeError. @@ -2892,18 +2888,17 @@ Sau đó chúng ta tiến hành `.push` trên `newList`. Vì `newList` là một ```javascript function giveLydiaPizza() { - return "Here is pizza!"; + return "Here is pizza!" } -const giveLydiaChocolate = () => - "Here's chocolate... now go hit the gym already."; +const giveLydiaChocolate = () => "Here's chocolate... now go hit the gym already." -console.log(giveLydiaPizza.prototype); -console.log(giveLydiaChocolate.prototype); +console.log(giveLydiaPizza.prototype) +console.log(giveLydiaChocolate.prototype) ``` -- A: `{ constructor: ...}` `{ constructor: ...}` -- B: `{}` `{ constructor: ...}` +- A: `{ constructor: ...}` `{ constructor: ...}` +- B: `{}` `{ constructor: ...}` - C: `{ constructor: ...}` `{}` - D: `{ constructor: ...}` `undefined` @@ -2912,7 +2907,7 @@ console.log(giveLydiaChocolate.prototype); #### Đáp án: D -Hàm thông thường giống như `giveLydiaPizza`, sẽ có thuộc tính `prototype` là một object (prototype object) với một thuộc tính là `constructor`. Còn `arrow functions` giống như `giveLydiaChocolate`thì không có thuộc tính `prototype` này. `undefined` trả về khi ta truy cập thuộc tính `prototype` bằng cách gọi `giveLydiaChocolate.prototype`. +Hàm thông thường giống như `giveLydiaPizza`, sẽ có thuộc tính `prototype` là một object (prototype object) với một thuộc tính là `constructor`. Còn `arrow functions` giống như `giveLydiaChocolate`thì không có thuộc tính `prototype` này. `undefined` trả về khi ta truy cập thuộc tính `prototype` bằng cách gọi `giveLydiaChocolate.prototype`.

@@ -2924,16 +2919,16 @@ Hàm thông thường giống như `giveLydiaPizza`, sẽ có thuộc tính `pro ```javascript const person = { name: "Lydia", - age: 21, -}; + age: 21 +} for (const [x, y] of Object.entries(person)) { - console.log(x, y); + console.log(x, y) } ``` - A: `name` `Lydia` và `age` `21` -- B: `["name", "Lydia"]` và `["age", 21]` +- B: `["name", "Lydia"]` và `["age", 21]` - C: `["name", "age"]` và `undefined` - D: `Error` @@ -2944,9 +2939,9 @@ for (const [x, y] of Object.entries(person)) { `Object.entries(person)` sẽ trả về một mảng của mảng, bao gồm các key và các object: -`[ [ 'name', 'Lydia' ], [ 'age', 21 ] ]` +`[ [ 'name', 'Lydia' ], [ 'age', 21 ] ]` -Khí sử dụng `for-of`, chúng ta sẽ duyệt qua từng thành phần của mảng, trong trường hợp này chính là những mảng con. Đồng thời tiến hành gán giá trị luôn trong vongf lặp for-of, bằng cách sử dụng `const [x, y]`. Khi này `x` sẽ là phần tử đầu tiên trong mảng con, `y` chính là phần tử thứ hai trong mảng con. +Khí sử dụng `for-of`, chúng ta sẽ duyệt qua từng thành phần của mảng, trong trường hợp này chính là những mảng con. Đồng thời tiến hành gán giá trị luôn trong vongf lặp for-of, bằng cách sử dụng `const [x, y]`. Khi này `x` sẽ là phần tử đầu tiên trong mảng con, `y` chính là phần tử thứ hai trong mảng con. Mảng con đầu tiên là `[ "name", "Lydia" ]`, nên `x` sẽ là `"name"`, và `y` sẽ là `"Lydia"`, và được ghi ra. Mảng con thứ hai là `[ "age", 21 ]`, nên `x` sẽ là `"age"`, và `y` sẽ là `21`, và được ghi ra. @@ -2967,7 +2962,7 @@ getItems(["banana", "apple"], "pear", "orange") ``` - A: `["banana", "apple", "pear", "orange"]` -- B: `[["banana", "apple"], "pear", "orange"]` +- B: `[["banana", "apple"], "pear", "orange"]` - C: `["banana", "apple", ["pear"], "orange"]` - D: `SyntaxError` @@ -2976,18 +2971,17 @@ getItems(["banana", "apple"], "pear", "orange") #### Đáp án: D -`...args` là cú pháp tham số cuối cùng. Giá trị của tham số cuối cùng chính là toàn bộ các đối số còn lại, **và nó là tham số cuối cùng duy nhất**! Trong trường hợp này, tham số cuối cùng lại là tham số thứ hai. Điều đó là không thể được, và sẽ throw ra một lỗi cú pháp. +`...args` là cú pháp tham số cuối cùng. Giá trị của tham số cuối cùng chính là toàn bộ các đối số còn lại, **và nó là tham số cuối cùng duy nhất**! Trong trường hợp này, tham số cuối cùng lại là tham số thứ hai. Điều đó là không thể được, và sẽ throw ra một lỗi cú pháp. ```javascript function getItems(fruitList, favoriteFruit, ...args) { - return [...fruitList, ...args, favoriteFruit]; + return [...fruitList, ...args, favoriteFruit] } -getItems(["banana", "apple"], "pear", "orange"); +getItems(["banana", "apple"], "pear", "orange") ``` Nếu ta code như thế này thì lại đúng. Giá trị trả về sẽ là `[ 'banana', 'apple', 'orange', 'pear' ]` -

@@ -2997,14 +2991,17 @@ Nếu ta code như thế này thì lại đúng. Giá trị trả về sẽ là ```javascript function nums(a, b) { - if (a > b) console.log("a is bigger"); - else console.log("b is bigger"); - return; - a + b; + if + (a > b) + console.log('a is bigger') + else + console.log('b is bigger') + return + a + b } -console.log(nums(4, 2)); -console.log(nums(1, 2)); +console.log(nums(4, 2)) +console.log(nums(1, 2)) ``` - A: `a is bigger`, `6` và `b is bigger`, `3` @@ -3017,13 +3014,13 @@ console.log(nums(1, 2)); #### Đáp án: B -Với JavaScript, ta _không bắt buộc_ phải viết dấu chấm phẩy (`;`), JavaScript engine sẽ tự động thêm vào sau mỗi câu lệnh. Nó gọi là **Automatic Semicolon Insertion**. Một câu lệnh có thể là khai báo biến, hoặc từ khóa như `throw`, `return`, `break`, vv. +Với JavaScript, ta _không bắt buộc_ phải viết dấu chấm phẩy (`;`), JavaScript engine sẽ tự động thêm vào sau mỗi câu lệnh. Nó gọi là **Automatic Semicolon Insertion**. Một câu lệnh có thể là khai báo biến, hoặc từ khóa như `throw`, `return`, `break`, vv. Ở đây ta sử dụng câu lệnh `return` ở một dòng và giá trị `a + b` ở một _dòng khác_. Tuy nhiên do khác dòng nên JS engine không thể biết đâu là giá trị ta thực sự muốn trả về. Thay vì thế, nó sẽ tự động thêm vào dấu chấm phẩy ngay sau `return` giống như này: ```javascript -return; -a + b; + return; + a + b ``` Có nghĩa là `a + b` sẽ không bao giờ được thực hiện, vì hàm đã được `return` rồi. Do không giá trị nào được trả về, nên giá trị trả về của hàm sẽ là `undefined`. Lưu ý là sẽ không tự động thêm dấu chấm phẩy ngay sau `if/else` đâu nhé! @@ -3038,18 +3035,18 @@ Có nghĩa là `a + b` sẽ không bao giờ được thực hiện, vì hàm đ ```javascript class Person { constructor() { - this.name = "Lydia"; + this.name = "Lydia" } } Person = class AnotherPerson { constructor() { - this.name = "Sarah"; + this.name = "Sarah" } -}; +} -const member = new Person(); -console.log(member.name); +const member = new Person() +console.log(member.name) ``` - A: `"Lydia"` @@ -3073,11 +3070,11 @@ Chúng ta có thể set một class với giá trị là một classes/function ```javascript const info = { - [Symbol("a")]: "b", -}; + [Symbol('a')]: 'b' +} -console.log(info); -console.log(Object.keys(info)); +console.log(info) +console.log(Object.keys(info)) ``` - A: `{Symbol('a'): 'b'}` và `["{Symbol('a')"]` @@ -3124,13 +3121,13 @@ console.log(getUser(user)) Hàm `getList` nhận vào một mảng các đối số, và tiến hành xử lý mảng đó luôn khi đưa vào hàm: -`[x, ...y] = [1, 2, 3, 4]` + `[x, ...y] = [1, 2, 3, 4]` -Với việc sử dụng cú pháp tham số cuối cùng `...y`, chúng ta đưa toàn bộ "những đối số còn lại" vào một mảng y. Trong trường hợp này đó là mảng gồm các phần tử `2`, `3` và `4`. Do đó giá trị của `y` lúc này chính là mảng `[2, 3, 4]`. Giá trị của `x` là `1`, nên khi ghi `[x, y]` ra, kết quả sẽ là `[1, [2, 3, 4]]`. + Với việc sử dụng cú pháp tham số cuối cùng `...y`, chúng ta đưa toàn bộ "những đối số còn lại" vào một mảng y. Trong trường hợp này đó là mảng gồm các phần tử `2`, `3` và `4`. Do đó giá trị của `y` lúc này chính là mảng `[2, 3, 4]`. Giá trị của `x` là `1`, nên khi ghi `[x, y]` ra, kết quả sẽ là `[1, [2, 3, 4]]`. Hàm `getUser` nhận vào một object. Với cú pháp arrow function, chúng ta sẽ không phải viết trong ngoặc nhọn `{}` nữa nếu ta chỉ muốn đơn thuần trả về giá trị. Tuy nhiên, nếu ta muốn trả về một _object_ t arrow function, ta sẽ phải viết chúng trong dấu ngoặc tròn `()`, nếu không thì sẽ không có giá trị nào được trả về! Ví dụ như sau: -`const getUser = user => ({ name: user.name, age: user.age })` +```const getUser = user => ({ name: user.name, age: user.age })``` Do không giá trị nào được trả về, kết quả sẽ là `undefined`. @@ -3142,9 +3139,9 @@ Do không giá trị nào được trả về, kết quả sẽ là `undefined`. ###### 99. Output là gì? ```javascript -const name = "Lydia"; +const name = "Lydia" -console.log(name()); +console.log(name()) ``` - A: `SyntaxError` @@ -3157,11 +3154,11 @@ console.log(name()); #### Đáp án: C -Biến `name` có giá trị là một chuỗi, không phải hàm, vì thế không thể gọi được. +Biến `name` có giá trị là một chuỗi, không phải hàm, vì thế không thể gọi được. TypeErrors sẽ được throw ra nếu một giá trị không được sử dụng đúng kiểu. JavaScript muốn `name` là một hàm khi ta tiến hành gọi nó. Nhưng nó là chuỗi, nên sẽ throw ra một TypeError. -SyntaxErrors sẽ được throw khi ta viết code không đúng cú pháp của JavaScript, ví dụ thay vì `return` ta viết `retrun`. +SyntaxErrors sẽ được throw khi ta viết code không đúng cú pháp của JavaScript, ví dụ thay vì `return` ta viết `retrun`. ReferenceErrors sẽ được throw ra khi Javascript không thể tìm được tham chiếu nào đến giá trị mà ta đang cố truy cập. @@ -3175,8 +3172,8 @@ ReferenceErrors sẽ được throw ra khi Javascript không thể tìm được ```javascript // 🎉✨ Đây là câu hỏi thứ 100 của tôi! ✨🎉 -const output = `${[] && "Im"}possible! -You should${"" && `n't`} see a therapist after so much JavaScript lol`; +const output = `${[] && 'Im'}possible! +You should${'' && `n't`} see a therapist after so much JavaScript lol` ``` - A: `possible! You should see a therapist after so much JavaScript lol` @@ -3201,11 +3198,11 @@ You should${"" && `n't`} see a therapist after so much JavaScript lol`; ###### 101. Output là gì? ```javascript -const one = false || {} || null; -const two = null || false || ""; -const three = [] || 0 || true; +const one = (false || {} || null) +const two = (null || false || "") +const three = ([] || 0 || true) -console.log(one, two, three); +console.log(one, two, three) ``` - A: `false` `null` `[]` @@ -3234,20 +3231,20 @@ Với phép toán `||`, ta sẽ trả về giá trị truethy đầu tiên. Nế ###### 102. Output là gì? ```javascript -const myPromise = () => Promise.resolve("I have resolved!"); +const myPromise = () => Promise.resolve('I have resolved!') function firstFunction() { - myPromise().then((res) => console.log(res)); - console.log("second"); + myPromise().then(res => console.log(res)) + console.log('second') } async function secondFunction() { - console.log(await myPromise()); - console.log("second"); + console.log(await myPromise()) + console.log('second') } -firstFunction(); -secondFunction(); +firstFunction() +secondFunction() ``` - A: `I have resolved!`, `second` và `I have resolved!`, `second` @@ -3264,11 +3261,11 @@ Có thể tưởng tượng đơn giản cách promise thực thi như sau: _bâ Dù chúng ta có thể sử dụng giá trị thu được bằng cú pháp `.then`, hoặc sử dụng cặp cú pháp `await/async`, nhưng, cách chúng hoạt động là khác nhau. -Trong `firstFunction`, chúng ta đưa promise qua một bên chờ cho nó tính toán xong, và vẫn tiếp tục chạy những code tiếp sau đó, theo đó `console.log('second')` sẽ được chạy. Sau đó promise được hoàn thành trả về giá trị `I have resolved`, giá trị này sẽ được log ra khi call stack trở nên rỗng. +Trong `firstFunction`, chúng ta đưa promise qua một bên chờ cho nó tính toán xong, và vẫn tiếp tục chạy những code tiếp sau đó, theo đó `console.log('second')` sẽ được chạy. Sau đó promise được hoàn thành trả về giá trị `I have resolved`, giá trị này sẽ được log ra khi call stack trở nên rỗng. Với từ khóa `await` trong `secondFunction`, ta đã tạm dừng một hàm bất đồng bộ cho tới khi chúng trả về giá trị, sau đó ta mới đi tiếp đến các câu lệnh tiếp theo. -Do đó nó sẽ chờ cho tới khi `myPromise` được hoàn thành và trả về giá trị `I have resolved`, sau đó chúng ta sẽ chạy tiếp câu lệnh tiếp theo in ra `second`. +Do đó nó sẽ chờ cho tới khi `myPromise` được hoàn thành và trả về giá trị `I have resolved`, sau đó chúng ta sẽ chạy tiếp câu lệnh tiếp theo in ra `second`.

@@ -3278,14 +3275,14 @@ Do đó nó sẽ chờ cho tới khi `myPromise` được hoàn thành và trả ###### 103. Output là gì? ```javascript -const set = new Set(); +const set = new Set() -set.add(1); -set.add("Lydia"); -set.add({ name: "Lydia" }); +set.add(1) +set.add("Lydia") +set.add({ name: "Lydia" }) for (let item of set) { - console.log(item + 2); + console.log(item + 2) } ``` @@ -3299,11 +3296,11 @@ for (let item of set) { #### Đáp án: C -Phép toán `+` không chỉ dùng để cộng các số, mà nó còn dùng để nối chuỗi nữa. Mỗi khi Javascript engine gặp một giá trị trong phép toán không phải dạng số, nó sẽ chuyển các số trong phép toán đó sang dạng chuỗi. +Phép toán `+` không chỉ dùng để cộng các số, mà nó còn dùng để nối chuỗi nữa. Mỗi khi Javascript engine gặp một giá trị trong phép toán không phải dạng số, nó sẽ chuyển các số trong phép toán đó sang dạng chuỗi. Phép toán đầu tiên item là một số `1`, nên `1 + 2` trả về 3. -Ở phép toán thứ hai, item là một chuỗi `"Lydia"`. trong khi đó `2` là một số, nên `2` sẽ bị chuyển sang dạng chuỗi, sau khi nối vào ta có chuỗi `"Lydia2"`. +Ở phép toán thứ hai, item là một chuỗi `"Lydia"`. trong khi đó `2` là một số, nên `2` sẽ bị chuyển sang dạng chuỗi, sau khi nối vào ta có chuỗi `"Lydia2"`. Ở phép toán thứ ba, `{ name: "Lydia" }` là một object. Tuy nhiên dù có là object hay gì đi nữa thì nó cũng sẽ bị chuyển sang dạng chuỗi. Đối với object thì khi chuyển sang dạng chuỗi nó sẽ trở thành `"[object Object]"`. `"[object Object]"` nối với `"2"` trở thành `"[object Object]2"`. @@ -3315,7 +3312,7 @@ Phép toán đầu tiên item là một số `1`, nên `1 + 2` trả về 3. ###### 104. Output là gì? ```javascript -Promise.resolve(5); +Promise.resolve(5) ``` - A: `5` @@ -3330,7 +3327,7 @@ Promise.resolve(5); Ta có thể truyền vào giá trị bất kì cho `Promise.resolve`, dù có là promise hay không promise. Bản thân nó sẽ là một hàm trả về một promise với giá trị đã được resolved. -Trong trường hợp này ta đưa vào giá trị `5`. Nó sẽ trả về một resolved promise với giá trị `5`. +Trong trường hợp này ta đưa vào giá trị `5`. Nó sẽ trả về một resolved promise với giá trị `5`.

@@ -3342,15 +3339,15 @@ Trong trường hợp này ta đưa vào giá trị `5`. Nó sẽ trả về m ```javascript function compareMembers(person1, person2 = person) { if (person1 !== person2) { - console.log("Not the same!"); + console.log("Not the same!") } else { - console.log("They are the same!"); + console.log("They are the same!") } } -const person = { name: "Lydia" }; +const person = { name: "Lydia" } -compareMembers(person); +compareMembers(person) ``` - A: `Not the same!` @@ -3363,7 +3360,7 @@ compareMembers(person); #### Đáp án: B -Object sẽ được truyền vào hàm theo reference. Khi chúng ta nói so sánh strict equal (`===`), nghĩa là ta đang so sánh các reference của chúng. +Object sẽ được truyền vào hàm theo reference. Khi chúng ta nói so sánh strict equal (`===`), nghĩa là ta đang so sánh các reference của chúng. Ta set giá trị mặc định của `person2` là object `person`, và đưa object `person` vào làm giá trị cho đối số `person1`. @@ -3383,11 +3380,11 @@ const colorConfig = { green: true, black: true, yellow: false, -}; +} -const colors = ["pink", "red", "blue"]; +const colors = ["pink", "red", "blue"] -console.log(colorConfig.colors[1]); +console.log(colorConfig.colors[1]) ``` - A: `true` @@ -3400,11 +3397,11 @@ console.log(colorConfig.colors[1]); #### Đáp án: D -Trong Javascript ta có hai cách để truy cập thuộc tính của một object: sử dụng ngoặc vuông `[]`, hoặc sử dụng chấm `.`. Trong trương hợp này chúng ta sử dụng chấm (`colorConfig.colors`) thay cho ngoặc vuông (`colorConfig["colors"]`). +Trong Javascript ta có hai cách để truy cập thuộc tính của một object: sử dụng ngoặc vuông `[]`, hoặc sử dụng chấm `.`. Trong trương hợp này chúng ta sử dụng chấm (`colorConfig.colors`) thay cho ngoặc vuông (`colorConfig["colors"]`). -Với cách sử dụng chấm, Javascript sẽ tìm kiếm một thuộc tính có tên chính xác như tên ta đưa vào. Trong trường hợp này nó là thuộc tính `colors` trong object `colorConfig` Tuy nhiên trong object này không có thuộc tính nào tên là `colors`, nên nó sẽ trả về `undefined`. Sau đó chúng ta cố truy cậ vào thuộc tính 1 của nó bằng cách gọi `[1]`. Chúng ta không thể làm như vậy trên giá trị `undefined`, nên nó sẽ trả về `TypeError`: `Cannot read property '1' of undefined`. +Với cách sử dụng chấm, Javascript sẽ tìm kiếm một thuộc tính có tên chính xác như tên ta đưa vào. Trong trường hợp này nó là thuộc tính `colors` trong object `colorConfig` Tuy nhiên trong object này không có thuộc tính nào tên là `colors`, nên nó sẽ trả về `undefined`. Sau đó chúng ta cố truy cậ vào thuộc tính 1 của nó bằng cách gọi `[1]`. Chúng ta không thể làm như vậy trên giá trị `undefined`, nên nó sẽ trả về `TypeError`: `Cannot read property '1' of undefined`. -Javascript thông dịch theo câu lệnh. Khi ta sử dụng ngoặc vuông, Nnó sẽ tìm mở ngoặc đầu tiên `[` và tiếp tục cho tới khi gặp đóng ngoặc tương ứng `]`. Chỉ khi đó nó mới đánh giá câu lệnh. Nếu chúng ta sử dụng cú pháp `colorConfig[colors[1]]`, nó sẽ trả về giá trị của thuộc tính `red` trong object `colorConfig`. +Javascript thông dịch theo câu lệnh. Khi ta sử dụng ngoặc vuông, Nnó sẽ tìm mở ngoặc đầu tiên `[` và tiếp tục cho tới khi gặp đóng ngoặc tương ứng `]`. Chỉ khi đó nó mới đánh giá câu lệnh. Nếu chúng ta sử dụng cú pháp `colorConfig[colors[1]]`, nó sẽ trả về giá trị của thuộc tính `red` trong object `colorConfig`.

@@ -3414,7 +3411,7 @@ Javascript thông dịch theo câu lệnh. Khi ta sử dụng ngoặc vuông, Nn ###### 107. Ouput là gì? ```javascript -console.log("❤️" === "❤️"); +console.log('❤️' === '❤️') ``` - A: `true` @@ -3425,7 +3422,7 @@ console.log("❤️" === "❤️"); #### Đáp án: A -Về cơ bản, emoji vẫn là các ký tự unicode mà thôi. Mã unicode cho hình trái tim là `"U+2764 U+FE0F"`. Chúng luôn luôn là một, nên phép toán đơn giản trả về `true`. +Về cơ bản, emoji vẫn là các ký tự unicode mà thôi. Mã unicode cho hình trái tim là `"U+2764 U+FE0F"`. Chúng luôn luôn là một, nên phép toán đơn giản trả về `true`.

@@ -3435,19 +3432,19 @@ Về cơ bản, emoji vẫn là các ký tự unicode mà thôi. Mã unicode cho ###### 108. Phép toán nào sau đây làm thay đổi mảng gốc? ```javascript -const emojis = ["✨", "🥑", "😍"]; +const emojis = ['✨', '🥑', '😍'] -emojis.map((x) => x + "✨"); -emojis.filter((x) => x !== "🥑"); -emojis.find((x) => x !== "🥑"); -emojis.reduce((acc, cur) => acc + "✨"); -emojis.slice(1, 2, "✨"); -emojis.splice(1, 2, "✨"); +emojis.map(x => x + '✨') +emojis.filter(x => x !== '🥑') +emojis.find(x => x !== '🥑') +emojis.reduce((acc, cur) => acc + '✨') +emojis.slice(1, 2, '✨') +emojis.splice(1, 2, '✨') ``` - A: `All of them` - B: `map` `reduce` `slice` `splice` -- C: `map` `slice` `splice` +- C: `map` `slice` `splice` - D: `splice`
Đáp án @@ -3455,7 +3452,7 @@ emojis.splice(1, 2, "✨"); #### Đáp án: D -Với `splice`, ta thay đổi mảng gốc bằng cách thêm sửa xóa các phần tử. Trong trường hợp này ta xóa 2 phần tử kể từ index 1 (ta xóa `'🥑'` và `'😍'`) và thêm vào ✨ emoji. +Với `splice`, ta thay đổi mảng gốc bằng cách thêm sửa xóa các phần tử. Trong trường hợp này ta xóa 2 phần tử kể từ index 1 (ta xóa `'🥑'` và `'😍'`) và thêm vào ✨ emoji. `map`, `filter` và `slice` trả về một mảng mới, `find` trả về một phần tử, và `reduce` trả về giá trị tích lũy. @@ -3467,17 +3464,17 @@ Với `splice`, ta thay đổi mảng gốc bằng cách thêm sửa xóa các p ###### 109. Output là gì? ```javascript -const food = ["🍕", "🍫", "🥑", "🍔"]; -const info = { favoriteFood: food[0] }; +const food = ['🍕', '🍫', '🥑', '🍔'] +const info = { favoriteFood: food[0] } -info.favoriteFood = "🍝"; +info.favoriteFood = '🍝' -console.log(food); +console.log(food) ``` - A: `['🍕', '🍫', '🥑', '🍔']` - B: `['🍝', '🍫', '🥑', '🍔']` -- C: `['🍝', '🍕', '🍫', '🥑', '🍔']` +- C: `['🍝', '🍕', '🍫', '🥑', '🍔']` - D: `ReferenceError`
Đáp án @@ -3497,7 +3494,7 @@ Bản thân mảng `food` không hề thay đổi, do giá trị của `favorite ###### 110. Phép toán này dùng để làm gì? ```javascript -JSON.parse(); +JSON.parse() ``` - A: Parse JSON thành một giá trị JavaScript @@ -3510,22 +3507,22 @@ JSON.parse(); #### Đáp án: A -Với phương thức `JSON.parse()`, ta sẽ parse một chuỗi JSON thành một giá trị JavaScript. +Với phương thức `JSON.parse()`, ta sẽ parse một chuỗi JSON thành một giá trị JavaScript. Ví dụ: ```javascript // Chuyển một số thành một chuỗi JSON, sau đó parse chuỗi JSON đó để trả về một giá trị JavaScript: -const jsonNumber = JSON.stringify(4); // '4' -JSON.parse(jsonNumber); // 4 +const jsonNumber = JSON.stringify(4) // '4' +JSON.parse(jsonNumber) // 4 // Chuyển một mảng thành một chuỗi JSON, sau đó parse chuỗi JSON để trả về một giá trị JavaScript: -const jsonArray = JSON.stringify([1, 2, 3]); // '[1, 2, 3]' -JSON.parse(jsonArray); // [1, 2, 3] +const jsonArray = JSON.stringify([1, 2, 3]) // '[1, 2, 3]' +JSON.parse(jsonArray) // [1, 2, 3] // Chuyển một object thành một chuỗi JSON, sau đó parse chuỗi JSON để trả về một giá trị JavaScript: -const jsonArray = JSON.stringify({ name: "Lydia" }); // '{"name":"Lydia"}' -JSON.parse(jsonArray); // { name: 'Lydia' } +const jsonArray = JSON.stringify({ name: "Lydia" }) // '{"name":"Lydia"}' +JSON.parse(jsonArray) // { name: 'Lydia' } ```

@@ -3533,17 +3530,17 @@ JSON.parse(jsonArray); // { name: 'Lydia' } --- -###### 111. Ouput là gì? +###### 111. Ouput là gì? ```javascript -let name = "Lydia"; +let name = 'Lydia' function getName() { - console.log(name); - let name = "Sarah"; + console.log(name) + let name = 'Sarah' } -getName(); +getName() ``` - A: Lydia @@ -3556,20 +3553,20 @@ getName(); #### Đáp án: D -Mỗi hàm sẽ có một _context thực thi_ (hay _scope_) của riêng nó. Hàm `getName` đầu tiên sẽ tìm trong context của nó (scope) để tìm xem có biến nào tên là `name` hay không. Trong trường hợp này, hàm `getName` có biến `name` được khai báo với từ khóa `let`, giá trị là `'Sarah'`. +Mỗi hàm sẽ có một _context thực thi_ (hay _scope_) của riêng nó. Hàm `getName` đầu tiên sẽ tìm trong context của nó (scope) để tìm xem có biến nào tên là `name` hay không. Trong trường hợp này, hàm `getName` có biến `name` được khai báo với từ khóa `let`, giá trị là `'Sarah'`. -Một biến được khai báo với từ khóa `let` (hoặc `const`) sẽ được `hoisted`, nhưng không giống như `var`, nó sẽ không được _khởi tạo_. Nó sẽ không thể truy cập được trước dòng ta khai báo (initialize). Nó được gọi là "temporal dead zone". Khi ta cố truy cập một biến trước khi nó được khai báo, JavaScript sẽ throw ra `ReferenceError`. +Một biến được khai báo với từ khóa `let` (hoặc `const`) sẽ được `hoisted`, nhưng không giống như `var`, nó sẽ không được _khởi tạo_. Nó sẽ không thể truy cập được trước dòng ta khai báo (initialize). Nó được gọi là "temporal dead zone". Khi ta cố truy cập một biến trước khi nó được khai báo, JavaScript sẽ throw ra `ReferenceError`. -Nếu ta không khai báo biến `name` bên trong hàm `getName`, thì Javascript engine sẽ tiếp tục tìm kiếm trong _scope chain_. Nó sẽ tìm thấy ở scope phía ngoài một biến `name` với giá trị là `Lydia`. Trong trường hợp này nó sẽ log ra `Lydia`. +Nếu ta không khai báo biến `name` bên trong hàm `getName`, thì Javascript engine sẽ tiếp tục tìm kiếm trong _scope chain_. Nó sẽ tìm thấy ở scope phía ngoài một biến `name` với giá trị là `Lydia`. Trong trường hợp này nó sẽ log ra `Lydia`. ```javascript -let name = "Lydia"; +let name = 'Lydia' function getName() { - console.log(name); + console.log(name) } -getName(); // Lydia +getName() // Lydia ```

@@ -3581,18 +3578,18 @@ getName(); // Lydia ```javascript function* generatorOne() { - yield ["a", "b", "c"]; + yield ['a', 'b', 'c']; } function* generatorTwo() { - yield* ["a", "b", "c"]; + yield* ['a', 'b', 'c']; } -const one = generatorOne(); -const two = generatorTwo(); +const one = generatorOne() +const two = generatorTwo() -console.log(one.next().value); -console.log(two.next().value); +console.log(one.next().value) +console.log(two.next().value) ``` - A: `a` and `a` @@ -3610,17 +3607,17 @@ Với từ khóa `yield`, ta sẽ trả về các giá trị trong một `genera Trong `generatorOne`, ta trả về toàn bộ mảng `['a', 'b', 'c']` sử dụng từ khóa `yield`. Giá trị của thuộc tính `value` trong object thu được bởi phương thức `next` trong `one` (`one.next().value`) là toàn bộ mảng `['a', 'b', 'c']`. ```javascript -console.log(one.next().value); // ['a', 'b', 'c'] -console.log(one.next().value); // undefined +console.log(one.next().value) // ['a', 'b', 'c'] +console.log(one.next().value) // undefined ``` -Trong `generatorTwo`, ta sử dụng từ khóa `yield*`. Có nghĩa là giá trị đầu tiên mà `two` trả về là giá trị đầu tiên trong `iterator`. Trong trường hợp này `iterator` của chúng ta là mảng `['a', 'b', 'c']`. Giá trị đầu tiên của mảng là `a`, nên lần đầu tiên khi ta gọi `two.next().value`, `a` sẽ được trả về. +Trong `generatorTwo`, ta sử dụng từ khóa `yield*`. Có nghĩa là giá trị đầu tiên mà `two` trả về là giá trị đầu tiên trong `iterator`. Trong trường hợp này `iterator` của chúng ta là mảng `['a', 'b', 'c']`. Giá trị đầu tiên của mảng là `a`, nên lần đầu tiên khi ta gọi `two.next().value`, `a` sẽ được trả về. ```javascript -console.log(two.next().value); // 'a' -console.log(two.next().value); // 'b' -console.log(two.next().value); // 'c' -console.log(two.next().value); // undefined +console.log(two.next().value) // 'a' +console.log(two.next().value) // 'b' +console.log(two.next().value) // 'c' +console.log(two.next().value) // undefined ```

@@ -3631,7 +3628,7 @@ console.log(two.next().value); // undefined ###### 113. Output là gì? ```javascript -console.log(`${((x) => x)("I love")} to program`); +console.log(`${(x => x)('I love')} to program`) ``` - A: `I love to program` @@ -3644,7 +3641,7 @@ console.log(`${((x) => x)("I love")} to program`); #### Đáp án: A -Biểu thức bên trong chuỗi template (tức chuỗi nằm trong hai dấu ``, gọi là `template literals`) sẽ được đánh giá trước. Sau đó kết quả của biểu thức sẽ được đưa vào chuỗi, trong trường hợp này biểu thức là `(x => x)('I love')`. Chúng ta truyền giá trị đối số `'I love'`cho một arrow function`x => x`. `x`lúc này là`'I love'`, và trả về chính nó. Cuối cùng kết quả của chuỗi là `I love to program`. +Biểu thức bên trong chuỗi template (tức chuỗi nằm trong hai dấu ``, gọi là `template literals`) sẽ được đánh giá trước. Sau đó kết quả của biểu thức sẽ được đưa vào chuỗi, trong trường hợp này biểu thức là `(x => x)('I love')`. Chúng ta truyền giá trị đối số `'I love'` cho một arrow function `x => x`. `x` lúc này là `'I love'`, và trả về chính nó. Cuối cùng kết quả của chuỗi là `I love to program`.

@@ -3656,11 +3653,11 @@ Biểu thức bên trong chuỗi template (tức chuỗi nằm trong hai dấu ` ```javascript let config = { alert: setInterval(() => { - console.log("Alert!"); - }, 1000), -}; + console.log('Alert!') + }, 1000) +} -config = null; +config = null ``` - A: Callback `setInterval` sẽ không được gọi @@ -3683,17 +3680,17 @@ Thông thường khi ta set một object bằng `null`, thì object này sẽ đ ###### 115. Những hàm nào sẽ trả về `'Hello world!'`? ```javascript -const myMap = new Map(); -const myFunc = () => "greeting"; +const myMap = new Map() +const myFunc = () => 'greeting' -myMap.set(myFunc, "Hello world!"); +myMap.set(myFunc, 'Hello world!') //1 -myMap.get("greeting"); +myMap.get('greeting') //2 -myMap.get(myFunc); +myMap.get(myFunc) //3 -myMap.get(() => "greeting"); +myMap.get(() => 'greeting') ``` - A: 1 @@ -3706,7 +3703,7 @@ myMap.get(() => "greeting"); #### Đáp án: B -Khi ta thêm vào một cặp key/value với từ khóa `set`, key sẽ là đối số đầu tiên đưa vào trong hàm `set` function, và value sẽ là đối số thứ hai.Trong trường hơp này key chính là _hàm_ `() => 'greeting'`, value là `'Hello world'`. `myMap` trở thành `{ () => 'greeting' => 'Hello world!' }`. +Khi ta thêm vào một cặp key/value với từ khóa `set`, key sẽ là đối số đầu tiên đưa vào trong hàm `set` function, và value sẽ là đối số thứ hai.Trong trường hơp này key chính là _hàm_ `() => 'greeting'`, value là `'Hello world'`. `myMap` trở thành `{ () => 'greeting' => 'Hello world!' }`. 1 sai, vì key là `() => 'greeting'` chứ không phải là `'greeting'`. 3 sai, vì khi chúng ta đưa một hàm vào làm đối số trong phương thức `get`, nó sẽ được đưa vào dưới dạng _reference_. Function vốn là object, do đó 2 hàm sẽ không bao giờ là `strictly equal`, mặc dù chúng có trông giống nhau đi chăng nữa thì chúng vẫn trỏ đến các vùng nhớ khác nhau. @@ -3721,19 +3718,19 @@ Khi ta thêm vào một cặp key/value với từ khóa `set`, key sẽ là đ ```javascript const person = { name: "Lydia", - age: 21, -}; + age: 21 +} -const changeAge = (x = { ...person }) => (x.age += 1); +const changeAge = (x = { ...person }) => x.age += 1 const changeAgeAndName = (x = { ...person }) => { - x.age += 1; - x.name = "Sarah"; -}; + x.age += 1 + x.name = "Sarah" +} -changeAge(person); -changeAgeAndName(); +changeAge(person) +changeAgeAndName() -console.log(person); +console.log(person) ``` - A: `{name: "Sarah", age: 22}` @@ -3746,7 +3743,7 @@ console.log(person); #### Đáp án: C -Cả hai hàm `changeAge` và `changeAgeAndName` đều có tham số mặc định - nó là một _bản copy_ mới của object `{ ...person }`. Object này sẽ copy tất cả những cặp key/values bên trong object `person`. +Cả hai hàm `changeAge` và `changeAgeAndName` đều có tham số mặc định - nó là một _bản copy_ mới của object `{ ...person }`. Object này sẽ copy tất cả những cặp key/values bên trong object `person`. Đầu tiên, chúng ta gọi hàm `changeAge` và đưa chính object `person` vào làm đối số. Hàm này sẽ tăng giá trị của thuộc tính `age` lên 1. `person` lúc này là `{ name: "Lydia", age: 22 }`. @@ -3761,7 +3758,7 @@ Sau đó, chúng ta gọi hàm `changeAgeAndName` tuy nhiên không đưa vào ```javascript function sumValues(x, y, z) { - return x + y + z; + return x + y + z; } ``` @@ -3812,15 +3809,15 @@ Với phép toán `+=`, Ta tăng giá trị của `num` lên `1`. `num` có giá ```javascript const person = { - firstName: "Lydia", - lastName: "Hallie", - pet: { - name: "Mara", - breed: "Dutch Tulip Hound", - }, - getFullName() { - return `${this.firstName} ${this.lastName}`; - }, + firstName: "Lydia", + lastName: "Hallie", + pet: { + name: "Mara", + breed: "Dutch Tulip Hound" + }, + getFullName() { + return `${this.firstName} ${this.lastName}`; + } }; console.log(person.pet?.name); @@ -3860,9 +3857,9 @@ Với phép toán optional chaining `?.`, chúng ta sẽ không cần phải che const groceries = ["banana", "apple", "peanuts"]; if (groceries.indexOf("banana")) { - console.log("We have to buy bananas!"); + console.log("We have to buy bananas!"); } else { - console.log(`We don't have to buy bananas!`); + console.log(`We don't have to buy bananas!`); } ``` @@ -3887,10 +3884,10 @@ Ta đưa một điều kiện `groceries.indexOf("banana")` vào câu lệnh `if ```javascript const config = { - languages: [], - set language(lang) { - return this.languages.push(lang); - }, + languages: [], + set language(lang) { + return this.languages.push(lang); + } }; console.log(config.language); @@ -3944,9 +3941,9 @@ console.log(!typeof name === "string"); ###### 123. Output là gì? ```javascript -const add = (x) => (y) => (z) => { - console.log(x, y, z); - return x + y + z; +const add = x => y => z => { + console.log(x, y, z); + return x + y + z; }; add(4)(5)(6); @@ -3973,16 +3970,16 @@ Hàm `add` trả về một arrow function, arrow function này lại trả về ```javascript async function* range(start, end) { - for (let i = start; i <= end; i++) { - yield Promise.resolve(i); - } + for (let i = start; i <= end; i++) { + yield Promise.resolve(i); + } } (async () => { - const gen = range(1, 3); - for await (const item of gen) { - console.log(item); - } + const gen = range(1, 3); + for await (const item of gen) { + console.log(item); + } })(); ``` @@ -4007,7 +4004,7 @@ Generator `range` trả về một async object với các promise tương ứng ```javascript const myFunc = ({ x, y, z }) => { - console.log(x, y, z); + console.log(x, y, z); }; myFunc(1, 2, 3); @@ -4130,8 +4127,8 @@ Với phương thức `isNaN`, ta đơn thuần chỉ check xem giá trị đưa const randomValue = 21; function getInfo() { - console.log(typeof randomValue); - const randomValue = "Lydia Hallie"; + console.log(typeof randomValue); + const randomValue = "Lydia Hallie"; } getInfo(); @@ -4160,13 +4157,13 @@ Một biến được khai báo với từ khóa `const` sẽ không thể truy const myPromise = Promise.resolve("Woah some cool data"); (async () => { - try { - console.log(await myPromise); - } catch { - throw new Error(`Oops didn't work`); - } finally { - console.log("Oh finally!"); - } + try { + console.log(await myPromise); + } catch { + throw new Error(`Oops didn't work`); + } finally { + console.log("Oh finally!"); + } })(); ``` @@ -4216,13 +4213,13 @@ Với phương thức `flat`, ta có thể tạo một mảng mới với các p ```javascript class Counter { - constructor() { - this.count = 0; - } + constructor() { + this.count = 0; + } - increment() { - this.count++; - } + increment() { + this.count++; + } } const counterOne = new Counter(); @@ -4266,16 +4263,16 @@ Ta gọi hàm `counterTwo.increment()` để tăng `count` lên `3`. Sau đó ch const myPromise = Promise.resolve(Promise.resolve("Promise!")); function funcOne() { - myPromise.then((res) => res).then((res) => console.log(res)); - setTimeout(() => console.log("Timeout!", 0)); - console.log("Last line!"); + myPromise.then(res => res).then(res => console.log(res)); + setTimeout(() => console.log("Timeout!", 0)); + console.log("Last line!"); } async function funcTwo() { - const res = await myPromise; - console.log(await res); - setTimeout(() => console.log("Timeout!", 0)); - console.log("Last line!"); + const res = await myPromise; + console.log(await res); + setTimeout(() => console.log("Timeout!", 0)); + console.log("Last line!"); } funcOne(); @@ -4312,7 +4309,7 @@ Ta tiếp tục thực thi dòng cuối cùng của `funcTwo`, trả về `Last ```javascript // sum.js export default function sum(x) { - return x + x; + return x + x; } // index.js @@ -4369,8 +4366,8 @@ Ta có thể gọi hàm này bằng cách sử dụng `sum.default` ```javascript const handler = { - set: () => console.log("Added a new property!"), - get: () => console.log("Accessed a property!"), + set: () => console.log("Added a new property!"), + get: () => console.log("Accessed a property!") }; const person = new Proxy({}, handler); @@ -4433,10 +4430,10 @@ Tuy nhiên ta vẫn có thể _thay đổi_ các thuộc tính cũ. ```javascript const person = { - name: "Lydia Hallie", - address: { - street: "100 Main St", - }, + name: "Lydia Hallie", + address: { + street: "100 Main St" + } }; Object.freeze(person); @@ -4464,10 +4461,10 @@ Tuy nhiên trên thực tế đây chỉ là đóng băng _nông_ (_shallowly_) ###### 138. Output là gì? ```javascript -const add = (x) => x + x; +const add = x => x + x; function myFunc(num = 2, value = add(num)) { - console.log(num, value); + console.log(num, value); } myFunc(); @@ -4497,21 +4494,21 @@ Sau đó ta gọi hàm `myFunc(3)`, khi này `3` sẽ là giá trị của `num` ```javascript class Counter { - #number = 10; + #number = 10 increment() { - this.#number++; + this.#number++ } getNum() { - return this.#number; + return this.#number } } -const counter = new Counter(); -counter.increment(); +const counter = new Counter() +counter.increment() -console.log(counter.#number); +console.log(counter.#number) ``` - A: `10` @@ -4535,20 +4532,20 @@ Với cú pháp ES2020, ta có thể thêm các thuộc tính private vào class ```javascript const teams = [ - { name: "Team 1", members: ["Paul", "Lisa"] }, - { name: "Team 2", members: ["Laura", "Tim"] }, + { name: "Team 1", members: ["Paul", "Lisa"] }, + { name: "Team 2", members: ["Laura", "Tim"] } ]; function* getMembers(members) { - for (let i = 0; i < members.length; i++) { - yield members[i]; - } + for (let i = 0; i < members.length; i++) { + yield members[i]; + } } function* getTeams(teams) { - for (let i = 0; i < teams.length; i++) { - // ✨ SOMETHING IS MISSING HERE ✨ - } + for (let i = 0; i < teams.length; i++) { + // ✨ SOMETHING IS MISSING HERE ✨ + } } const obj = getTeams(teams); @@ -4573,19 +4570,20 @@ Nếu ta dùng `yield`, `return yield`, hay `return`, toàn bộ generator sẽ

+ --- ###### 141. Output là gì? ```javascript const person = { - name: "Lydia Hallie", - hobbies: ["coding"], + name: "Lydia Hallie", + hobbies: ["coding"] }; function addHobby(hobby, hobbies = person.hobbies) { - hobbies.push(hobby); - return hobbies; + hobbies.push(hobby); + return hobbies; } addHobby("running", []); @@ -4624,16 +4622,16 @@ Sau khi thêm `dancing` và `baking`, giá trị của `person.hobbies` là `["c ```javascript class Bird { - constructor() { - console.log("I'm a bird. 🦢"); - } + constructor() { + console.log("I'm a bird. 🦢"); + } } class Flamingo extends Bird { - constructor() { - console.log("I'm pink. 🌸"); - super(); - } + constructor() { + console.log("I'm pink. 🌸"); + super(); + } } const pet = new Flamingo(); @@ -4718,11 +4716,11 @@ Mặc định ta không thể duyệt qua được object. Trừ phi nó đượ let count = 0; const nums = [0, 1, 2, 3]; -nums.forEach((num) => { - if (num) count += 1; -}); +nums.forEach(num => { + if (num) count += 1 +}) -console.log(count); +console.log(count) ``` - A: 1 @@ -4746,12 +4744,12 @@ Câu lệnh `if` trong vòng lập `forEach` kiểm tra giá trị của `num` l ```javascript function getFruit(fruits) { - console.log(fruits?.[1]?.[1]); + console.log(fruits?.[1]?.[1]) } -getFruit([["🍊", "🍌"], ["🍍"]]); -getFruit(); -getFruit([["🍍"], ["🍊", "🍌"]]); +getFruit([['🍊', '🍌'], ['🍍']]) +getFruit() +getFruit([['🍍'], ['🍊', '🍌']]) ``` - A: `null`, `undefined`, 🍌 @@ -4768,7 +4766,7 @@ Phép toán `?` cho phép ta truy cập giá trị bên trong của object. Chú Trước tiên, chúng ta thử in ra phần tử thứ hai trong mảng con `['🍍']` của `[['🍊', '🍌'], ['🍍']]`. Mảng con này chỉ chứa một phần tử, nghĩa là không có phần tử nào với thứ tự là `1`, và trả về `undefined`. -Sau đó, ta gọi hàm `getFruits` khi không truyền vào một đối số nào, nghĩa là `fruits` có giá trị mặc định là `undefined`. Vì ta truyền phần tử mang thứ tự `1` của `fruits`, nó trả về `undefined` do phần tử này không tồn tại. +Sau đó, ta gọi hàm `getFruits` khi không truyền vào một đối số nào, nghĩa là `fruits` có giá trị mặc định là `undefined`. Vì ta truyền phần tử mang thứ tự `1` của `fruits`, nó trả về `undefined` do phần tử này không tồn tại. Cuối cùng, ta thử in ra phần tử thứ hai trong mảng con `['🍊', '🍌']` của mảng `['🍍'], ['🍊', '🍌']`. Phần tử mang thứ tự `1` bên trong mảng con này là `🍌` sẽ được in ra. @@ -4781,19 +4779,19 @@ Cuối cùng, ta thử in ra phần tử thứ hai trong mảng con `['🍊', ' ```javascript class Calc { - constructor() { - this.count = 0; - } + constructor() { + this.count = 0 + } - increase() { - this.count++; - } + increase() { + this.count ++ + } } -const calc = new Calc(); -new Calc().increase(); +const calc = new Calc() +new Calc().increase() -console.log(calc.count); +console.log(calc.count) ``` - A: `0` @@ -4817,25 +4815,25 @@ Ta set biến `calc` bằng một instance mới của `Calc` class. Sau đó ta ```javascript const user = { - email: "e@mail.com", - password: "12345", -}; + email: "e@mail.com", + password: "12345" +} const updateUser = ({ email, password }) => { - if (email) { - Object.assign(user, { email }); - } + if (email) { + Object.assign(user, { email }) + } - if (password) { - user.password = password; - } + if (password) { + user.password = password + } - return user; -}; + return user +} -const updatedUser = updateUser({ email: "new@email.com" }); +const updatedUser = updateUser({ email: "new@email.com" }) -console.log(updatedUser === user); +console.log(updatedUser === user) ``` - A: `false` @@ -4858,13 +4856,13 @@ Hàm `updateUser` thay đổi các giá trị của thuộc tính `email` và `p ###### 149. Output là gi? ```javascript -const fruit = ["🍌", "🍊", "🍎"]; +const fruit = ['🍌', '🍊', '🍎'] -fruit.slice(0, 1); -fruit.splice(0, 1); -fruit.unshift("🍇"); +fruit.slice(0, 1) +fruit.splice(0, 1) +fruit.unshift('🍇') -console.log(fruit); +console.log(fruit) ``` - A: `['🍌', '🍊', '🍎']` @@ -4888,13 +4886,13 @@ Trước tiên, ta gọi hàm `slice` trên mảng fruit. Hàm slice không thay ```javascript const animals = {}; -let dog = { emoji: "🐶" }; -let cat = { emoji: "🐈" }; +let dog = { emoji: '🐶' } +let cat = { emoji: '🐈' } -animals[dog] = { ...dog, name: "Mara" }; -animals[cat] = { ...cat, name: "Sara" }; +animals[dog] = { ...dog, name: "Mara" } +animals[cat] = { ...cat, name: "Sara" } -console.log(animals[dog]); +console.log(animals[dog]) ``` - A: `{ emoji: "🐶", name: "Mara" }` @@ -4911,7 +4909,7 @@ Các keys của object được chuyển thành các chuỗi. Do giá trị của `dog` là một object, `animals[dog]` thực sự nghĩa là ta tạo ra một thuộc tính mới gọi là `"object Object"` bằng với object mới. `animals["object Object"]` lúc này bằng với `{ emoji: "🐶", name: "Mara"}`. -`cat` cũng là một object, nên `animals[cat]` thực sự nghĩa là ta thay đổi giá trị của ` animals[``"``object Object``"``] ` bằng thuộc tính cat mới. +`cat` cũng là một object, nên `animals[cat]` thực sự nghĩa là ta thay đổi giá trị của `animals[``"``object Object``"``]` bằng thuộc tính cat mới. Khi in ra `animals[dog]`, hoặc thực chất là `animals["object Object"]` vì thay `dog` object bằng một chuỗi thì nó trả về `"object Object"`, ta nhận được `{ emoji: "🐈", name: "Sara" }`. @@ -4924,14 +4922,14 @@ Khi in ra `animals[dog]`, hoặc thực chất là `animals["object Object"]` v ```javascript const user = { - email: "my@email.com", - updateEmail: (email) => { - this.email = email; - }, -}; + email: "my@email.com", + updateEmail: email => { + this.email = email + } +} -user.updateEmail("new@email.com"); -console.log(user.email); +user.updateEmail("new@email.com") +console.log(user.email) ``` - A: `my@email.com` @@ -4954,20 +4952,20 @@ Hàm `updateEmail` là một cú pháp arrow function và nó không gắn với ###### 152. Output là gì? ```javascript -const promise1 = Promise.resolve("First"); -const promise2 = Promise.resolve("Second"); -const promise3 = Promise.reject("Third"); -const promise4 = Promise.resolve("Fourth"); +const promise1 = Promise.resolve('First') +const promise2 = Promise.resolve('Second') +const promise3 = Promise.reject('Third') +const promise4 = Promise.resolve('Fourth') const runPromises = async () => { - const res1 = await Promise.all([promise1, promise2]); - const res2 = await Promise.all([promise3, promise4]); - return [res1, res2]; -}; + const res1 = await Promise.all([promise1, promise2]) + const res2 = await Promise.all([promise3, promise4]) + return [res1, res2] +} runPromises() - .then((res) => console.log(res)) - .catch((err) => console.log(err)); + .then(res => console.log(res)) + .catch(err => console.log(err)) ``` - A: `[['First', 'Second'], ['Fourth']]` @@ -4987,19 +4985,16 @@ Hàm `Promise.all` trả về những promise truyền vào song song nhau. Nế --- -###### 153. Giá trị nào của `method` sẽ được trả về với log `{ name: "Lydia", age: 22 }`? +###### 153. Giá trị nào của `method` sẽ được trả về với log `{ name: "Lydia", age: 22 }`? ```javascript -const keys = ["name", "age"]; -const values = ["Lydia", 22]; +const keys = ["name", "age"] +const values = ["Lydia", 22] -const method = - /* ?? */ - Object[method]( - keys.map((_, i) => { - return [keys[i], values[i]]; - }) - ); // { name: "Lydia", age: 22 } +const method = /* ?? */ +Object[method](keys.map((_, i) => { + return [keys[i], values[i]] +})) // { name: "Lydia", age: 22 } ``` - A: `entries` @@ -5024,18 +5019,18 @@ Theo như trên thì ta tạo ra một mảng gồm những mảng con chứa đ ###### 154. Output là gì? ```javascript -const createMember = ({ email, address = {} }) => { - const validEmail = /.+\@.+\..+/.test(email); - if (!validEmail) throw new Error("Valid email pls"); +const createMember = ({ email, address = {}}) => { + const validEmail = /.+\@.+\..+/.test(email) + if (!validEmail) throw new Error("Valid email pls") - return { - email, - address: address ? address : null, - }; -}; + return { + email, + address: address ? address : null + } +} -const member = createMember({ email: "my@email.com" }); -console.log(member); +const member = createMember({ email: "my@email.com" }) +console.log(member) ``` - A: `{ email: "my@email.com", address: null }` @@ -5058,13 +5053,13 @@ Giá trị mặc định của `address` là một object rỗng `{}`. Khi ta ch ###### 155. Output là gì? ```javascript -let randomValue = { name: "Lydia" }; -randomValue = 23; +let randomValue = { name: "Lydia" } +randomValue = 23 if (!typeof randomValue === "string") { - console.log("It's not a string!"); + console.log("It's not a string!") } else { - console.log("Yay it's a string!"); + console.log("Yay it's a string!") } ``` From 7b747e930b03606504cd0a179d1c45baee7dc46f Mon Sep 17 00:00:00 2001 From: alexb017 Date: Tue, 22 Aug 2023 02:46:20 +0300 Subject: [PATCH 169/193] Added the Romanian language --- README.md | 1 + ar-AR/README_AR.md | 1 + bs-BS/README-bs_BS.md | 1 + de-DE/README.md | 1 + es-ES/README-ES.md | 1 + fr-FR/README_fr-FR.md | 1 + id-ID/README.md | 1 + it-IT/README.md | 1 + ja-JA/README-ja_JA.md | 1 + ko-KR/README-ko_KR.md | 1 + nl-NL/README.md | 1 + pl-PL/README.md | 1 + pt-BR/README_pt_BR.md | 1 + ro-RO/README.ro.md | 49 +++++++++++++++++++++++++++++++++++++++++++ ru-RU/README.md | 1 + sq-KS/README_sq_KS.md | 1 + th-TH/README.md | 1 + tr-TR/README-tr_TR.md | 1 + uk-UA/README.md | 1 + vi-VI/README-vi.md | 1 + 20 files changed, 68 insertions(+) create mode 100644 ro-RO/README.ro.md diff --git a/README.md b/README.md index 97cde89e..7ccfaa63 100644 --- a/README.md +++ b/README.md @@ -33,6 +33,7 @@ Feel free to reach out to me! 😊
- [🇳🇱 Nederlands](./nl-NL/README.md) - [🇵🇱 Polski](./pl-PL/README.md) - [🇧🇷 Português Brasil](./pt-BR/README_pt_BR.md) +- [🇷o Română](../ro-RO/README.ro.md) - [🇷🇺 Русский](./ru-RU/README.md) - [🇽🇰 Shqip](./sq-KS/README_sq_KS.md) - [🇹🇭 ไทย](./th-TH/README-th_TH.md) diff --git a/ar-AR/README_AR.md b/ar-AR/README_AR.md index 6d5638e7..ace6ed98 100644 --- a/ar-AR/README_AR.md +++ b/ar-AR/README_AR.md @@ -27,6 +27,7 @@ - [🇳🇱 Nederlands](../nl-NL/README.md) - [🇵🇱 Polski](../pl-PL/README.md) - [🇧🇷 Português Brasil](../pt-BR/README_pt_BR.md) +- [🇷o Română](../ro-RO/README.ro.md) - [🇷🇺 Русский](../ru-RU/README.md) - [🇽🇰 Shqip](../sq-KS/README_sq_KS.md) - [🇹🇭 ไทย](../th-TH/README-th_TH.md) diff --git a/bs-BS/README-bs_BS.md b/bs-BS/README-bs_BS.md index 65ee11f7..eeeb7ea3 100644 --- a/bs-BS/README-bs_BS.md +++ b/bs-BS/README-bs_BS.md @@ -25,6 +25,7 @@ kliknite na njih da biste ih proširili. Sretno :heart: - [🇳🇱 Nederlands](../nl-NL/README.md) - [🇵🇱 Polski](../pl-PL/README.md) - [🇧🇷 Português Brasil](../pt-BR/README_pt_BR.md) +- [🇷o Română](../ro-RO/README.ro.md) - [🇷🇺 Русский](../ru-RU/README.md) - [🇽🇰 Shqip](../sq-KS/README_sq_KS.md) - [🇹🇭 ไทย](../th-TH/README-th_TH.md) diff --git a/de-DE/README.md b/de-DE/README.md index 10145050..0ac8c271 100644 --- a/de-DE/README.md +++ b/de-DE/README.md @@ -35,6 +35,7 @@ Kontaktiert mich, wenn ihr möchtet! 😊
- [🇳🇱 Nederlands](../nl-NL/README.md) - [🇵🇱 Polski](../pl-PL/README.md) - [🇧🇷 Português Brasil](../pt-BR/README_pt_BR.md) +- [🇷o Română](../ro-RO/README.ro.md) - [🇷🇺 Русский](../ru-RU/README.md) - [🇽🇰 Shqip](../sq-KS/README_sq_KS.md) - [🇹🇭 ไทย](../th-TH/README-th_TH.md) diff --git a/es-ES/README-ES.md b/es-ES/README-ES.md index 5c3ddc40..e839d901 100644 --- a/es-ES/README-ES.md +++ b/es-ES/README-ES.md @@ -25,6 +25,7 @@ Lista de lenguajes disponibles: - [🇳🇱 Nederlands](../nl-NL/README.md) - [🇵🇱 Polski](../pl-PL/README.md) - [🇧🇷 Português Brasil](../pt-BR/README_pt_BR.md) +- [🇷o Română](../ro-RO/README.ro.md) - [🇷🇺 Русский](../ru-RU/README.md) - [🇽🇰 Shqip](../sq-KS/README_sq_KS.md) - [🇹🇭 ไทย](../th-TH/README-th_TH.md) diff --git a/fr-FR/README_fr-FR.md b/fr-FR/README_fr-FR.md index cce10323..16d0d14e 100644 --- a/fr-FR/README_fr-FR.md +++ b/fr-FR/README_fr-FR.md @@ -19,6 +19,7 @@ Les réponses se trouvent dans les sections repliées en dessous des questions, - [🇳🇱 Nederlands](../nl-NL/README.md) - [🇵🇱 Polski](../pl-PL/README.md) - [🇧🇷 Português Brasil](../pt-BR/README_pt_BR.md) +- [🇷o Română](../ro-RO/README.ro.md) - [🇷🇺 Русский](../ru-RU/README.md) - [🇽🇰 Shqip](../sq-KS/README_sq_KS.md) - [🇹🇭 ไทย](../th-TH/README-th_TH.md) diff --git a/id-ID/README.md b/id-ID/README.md index 26a566cc..482955fb 100644 --- a/id-ID/README.md +++ b/id-ID/README.md @@ -29,6 +29,7 @@ Jangan sungkan untuk terhubung dengan saya! 😊
- [🇳🇱 Nederlands](../nl-NL/README.md) - [🇵🇱 Polski](../pl-PL/README.md) - [🇧🇷 Português Brasil](../pt-BR/README_pt_BR.md) +- [🇷o Română](../ro-RO/README.ro.md) - [🇷🇺 Русский](../ru-RU/README.md) - [🇽🇰 Shqip](../sq-KS/README_sq_KS.md) - [🇹🇭 ไทย](../th-TH/README-th_TH.md) diff --git a/it-IT/README.md b/it-IT/README.md index 71b71ca5..23d43ea2 100644 --- a/it-IT/README.md +++ b/it-IT/README.md @@ -37,6 +37,7 @@ Traduzione a cura di: Lucia Cenetie - [🇳🇱 Nederlands](../nl-NL/README.md) - [🇵🇱 Polski](../pl-PL/README.md) - [🇧🇷 Português Brasil](../pt-BR/README_pt_BR.md) +- [🇷o Română](../ro-RO/README.ro.md) - [🇷🇺 Русский](../ru-RU/README.md) - [🇽🇰 Shqip](../sq-KS/README_sq_KS.md) - [🇹🇭 ไทย](../th-TH/README-th_TH.md) diff --git a/ja-JA/README-ja_JA.md b/ja-JA/README-ja_JA.md index 1cc85d76..577982ce 100644 --- a/ja-JA/README-ja_JA.md +++ b/ja-JA/README-ja_JA.md @@ -21,6 +21,7 @@ - [🇳🇱 Nederlands](../nl-NL/README.md) - [🇵🇱 Polski](../pl-PL/README.md) - [🇧🇷 Português Brasil](../pt-BR/README_pt_BR.md) +- [🇷o Română](../ro-RO/README.ro.md) - [🇷🇺 Русский](../ru-RU/README.md) - [🇽🇰 Shqip](../sq-KS/README_sq_KS.md) - [🇹🇭 ไทย](../th-TH/README-th_TH.md) diff --git a/ko-KR/README-ko_KR.md b/ko-KR/README-ko_KR.md index 13651a7c..96d75bf7 100644 --- a/ko-KR/README-ko_KR.md +++ b/ko-KR/README-ko_KR.md @@ -34,6 +34,7 @@ - [🇳🇱 Nederlands](../nl-NL/README.md) - [🇵🇱 Polski](../pl-PL/README.md) - [🇧🇷 Português Brasil](../pt-BR/README_pt_BR.md) +- [🇷o Română](../ro-RO/README.ro.md) - [🇷🇺 Русский](../ru-RU/README.md) - [🇽🇰 Shqip](../sq-KS/README_sq_KS.md) - [🇹🇭 ไทย](../th-TH/README-th_TH.md) diff --git a/nl-NL/README.md b/nl-NL/README.md index 0400e8ed..ffc14a97 100644 --- a/nl-NL/README.md +++ b/nl-NL/README.md @@ -30,6 +30,7 @@ - [🇰🇷 한국어](../ko-KR/README-ko_KR.md) - [🇵🇱 Polski](../pl-PL/README.md) - [🇧🇷 Português Brasil](../pt-BR/README_pt_BR.md) +- [🇷o Română](../ro-RO/README.ro.md) - [🇷🇺 Русский](../ru-RU/README.md) - [🇽🇰 Shqip](../sq-KS/README_sq_KS.md) - [🇹🇭 ไทย](../th-TH/README-th_TH.md) diff --git a/pl-PL/README.md b/pl-PL/README.md index 866f4458..31d8e974 100644 --- a/pl-PL/README.md +++ b/pl-PL/README.md @@ -32,6 +32,7 @@ Nie krępuj się ze mną kontaktować! 😊
- [🇰🇷 한국어](./ko-KR/README-ko_KR.md) - [🇳🇱 Nederlands](./nl-NL/README.md) - [🇧🇷 Português Brasil](./pt-BR/README_pt_BR.md) +- [🇷o Română](../ro-RO/README.ro.md) - [🇷🇺 Русский](./ru-RU/README.md) - [🇽🇰 Shqip](../sq-KS/README_sq_KS.md) - [🇹🇭 ไทย](./th-TH/README-th_TH.md) diff --git a/pt-BR/README_pt_BR.md b/pt-BR/README_pt_BR.md index e59c6a6f..54c8daf1 100644 --- a/pt-BR/README_pt_BR.md +++ b/pt-BR/README_pt_BR.md @@ -19,6 +19,7 @@ As respostas estão em seções recolhidas abaixo das questões, basta clicar ne - [🇰🇷 한국어](../ko-KR/README-ko_KR.md) - [🇳🇱 Nederlands](../nl-NL/README.md) - [🇵🇱 Polski](../pl-PL/README.md) +- [🇷o Română](../ro-RO/README.ro.md) - [🇷🇺 Русский](../ru-RU/README.md) - [🇽🇰 Shqip](../sq-KS/README_sq_KS.md) - [🇹🇭 ไทย](../th-TH/README-th_TH.md) diff --git a/ro-RO/README.ro.md b/ro-RO/README.ro.md new file mode 100644 index 00000000..86de596e --- /dev/null +++ b/ro-RO/README.ro.md @@ -0,0 +1,49 @@ +
+ +

Întrebări JavaScript

+ +--- + +Postez întrebări JavaScript cu opțiuni multiple pe [Instagram](https://www.instagram.com/theavocoder) **stories**, pe care le voi posta și aici! Ultima actualizare:
12 Iunie + +De la nivel de bază la avansat: testează cât de bine cunoști JavaScript, reîmprospătează-ți puțin cunoștințele sau pregătește-te pentru interviul tău de codare! :muscle: :rocket: Actualizez acest depozit în mod regulat cu întrebări noi. Am adăugat răspunsurile în **secțiunile restrânse** de sub întrebări, pur și simplu dă clic pe ele pentru a le extinde. Este doar pentru distracție, mult noroc! :heart: + +Nu ezita să mă contactezi! 😊
+Instagram || Twitter || LinkedIn || Blog + +
+ +| Simte-te liber să le folosești într-un proiect! 😃 Aș aprecia _cu adevărat_ o referință la acest depozit, eu creez întrebările și explicațiile (da, sunt tristă lol) și comunitatea mă ajută foarte mult să îl mențin și să îl îmbunătățesc! 💪🏼 Mulțumesc și distracție plăcută! | +|---| + +--- + +
Vezi 20 de traduceri disponibile 🇸🇦🇪🇬🇧🇦🇩🇪🇪🇸🇫🇷🇮🇩🇯🇵🇰🇷🇳🇱🇧🇷🇷🇺🇹🇭🇹🇷🇺🇦🇻🇳🇨🇳🇹🇼🇽🇰 +

+ +- [🇸🇦 العربية](./ar-AR/README_AR.md) +- [🇪🇬 اللغة العامية](./ar-EG/README_ar-EG.md) +- [🇧🇦 Bosanski](./bs-BS/README-bs_BS.md) +- [🇩🇪 Deutsch](./de-DE/README.md) +- [🇪🇸 Español](./es-ES/README-ES.md) +- [🇫🇷 Français](./fr-FR/README_fr-FR.md) +- [🇮🇩 Indonesia](./id-ID/README.md) +- [🇮🇹 Italiano](./it-IT/README.md) +- [🇯🇵 日本語](./ja-JA/README-ja_JA.md) +- [🇰🇷 한국어](./ko-KR/README-ko_KR.md) +- [🇳🇱 Nederlands](./nl-NL/README.md) +- [🇵🇱 Polski](./pl-PL/README.md) +- [🇧🇷 Português Brasil](./pt-BR/README_pt_BR.md) +- [🇷🇺 Русский](./ru-RU/README.md) +- [🇽🇰 Shqip](./sq-KS/README_sq_KS.md) +- [🇹🇭 ไทย](./th-TH/README-th_TH.md) +- [🇹🇷 Türkçe](./tr-TR/README-tr_TR.md) +- [🇺🇦 Українська мова](./uk-UA/README.md) +- [🇻🇳 Tiếng Việt](./vi-VI/README-vi.md) +- [🇨🇳 简体中文](./zh-CN/README-zh_CN.md) +- [🇹🇼 繁體中文](./zh-TW/README_zh-TW.md) + +

+
+ +--- \ No newline at end of file diff --git a/ru-RU/README.md b/ru-RU/README.md index 17a083ab..2df08edb 100644 --- a/ru-RU/README.md +++ b/ru-RU/README.md @@ -33,6 +33,7 @@ - [🇳🇱 Nederlands](../nl-NL/README.md) - [🇵🇱 Polski](../pl-PL/README.md) - [🇧🇷 Português Brasil](../pt-BR/README_pt_BR.md) +- [🇷o Română](../ro-RO/README.ro.md) - [🇬🇧 English](../README.md) - [🇽🇰 Shqip](../sq-KS/README_sq_KS.md) - [🇹🇭 ไทย](../th-TH/README-th_TH.md) diff --git a/sq-KS/README_sq_KS.md b/sq-KS/README_sq_KS.md index aa1eb9dc..19508cf7 100644 --- a/sq-KS/README_sq_KS.md +++ b/sq-KS/README_sq_KS.md @@ -32,6 +32,7 @@ Mos hezitoni të më kontaktoni! 😊 - [🇳🇱 Nederlands](../nl-NL/README.md) - [🇵🇱 Polski](../pl-PL/README.md) - [🇧🇷 Português Brasil](../pt-BR/README_pt_BR.md) +- [🇷o Română](../ro-RO/README.ro.md) - [🇷🇺 Русский](../ru-RU/README.md) - [🇽🇰 Shqip](./sq-KS/README_sq_KS.md) - [🇹🇭 ไทย](../th-TH/README-th_TH.md) diff --git a/th-TH/README.md b/th-TH/README.md index 22550eb2..a5948da5 100644 --- a/th-TH/README.md +++ b/th-TH/README.md @@ -32,6 +32,7 @@ - [🇳🇱 Nederlands](../nl-NL/README.md) - [🇵🇱 Polski](../pl-PL/README.md) - [🇧🇷 Português Brasil](../pt-BR/README_pt_BR.md) +- [🇷o Română](../ro-RO/README.ro.md) - [🇷🇺 Русский](../ru-RU/README.md) - [🇽🇰 Shqip](../sq-KS/README_sq_KS.md) - [🇹🇷 Türkçe](../tr-TR/README-tr_TR.md) diff --git a/tr-TR/README-tr_TR.md b/tr-TR/README-tr_TR.md index e34ae66b..f1b36c1f 100644 --- a/tr-TR/README-tr_TR.md +++ b/tr-TR/README-tr_TR.md @@ -26,6 +26,7 @@ Mevcut dillerin listesi: - [🇳🇱 Nederlands](../nl-NL/README.md) - [🇵🇱 Polski](../pl-PL/README.md) - [🇧🇷 Português Brasil](../pt-BR/README_pt_BR.md) +- [🇷o Română](../ro-RO/README.ro.md) - [🇷🇺 Русский](../ru-RU/README.md) - [🇽🇰 Shqip](../sq-KS/README_sq_KS.md) - [🇹🇭 ไทย](../th-TH/README-th_TH.md) diff --git a/uk-UA/README.md b/uk-UA/README.md index 3b38c921..6498cc94 100644 --- a/uk-UA/README.md +++ b/uk-UA/README.md @@ -20,6 +20,7 @@ - [🇳🇱 Nederlands](../nl-NL/README.md) - [🇵🇱 Polski](../pl-PL/README.md) - [🇧🇷 Português Brasil](../pt-BR/README_pt_BR.md) +- [🇷o Română](../ro-RO/README.ro.md) - [🇷🇺 Русский](../ru-RU/README.md) - [🇽🇰 Shqip](../sq-KS/README_sq_KS.md) - [🇹🇭 ไทย](../th-TH/README-th_TH.md) diff --git a/vi-VI/README-vi.md b/vi-VI/README-vi.md index 8750b2d6..fa974a44 100644 --- a/vi-VI/README-vi.md +++ b/vi-VI/README-vi.md @@ -21,6 +21,7 @@ Danh sách các ngôn ngữ khác: - [🇳🇱 Nederlands](../nl-NL/README.md) - [🇵🇱 Polski](../pl-PL/README.md) - [🇧🇷 Português Brasil](../pt-BR/README_pt_BR.md) +- [🇷o Română](../ro-RO/README.ro.md) - [🇷🇺 Русский](../ru-RU/README.md) - [🇽🇰 Shqip](../sq-KS/README_sq_KS.md) - [🇹🇭 ไทย](../th-TH/README-th_TH.md) From fb56bd08dbc3e406e05f4a535c1b8521bebd6df0 Mon Sep 17 00:00:00 2001 From: alexb017 Date: Tue, 22 Aug 2023 02:51:47 +0300 Subject: [PATCH 170/193] Added the first 30 questions --- ro-RO/README.ro.md | 914 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 914 insertions(+) diff --git a/ro-RO/README.ro.md b/ro-RO/README.ro.md index 86de596e..1f15fd70 100644 --- a/ro-RO/README.ro.md +++ b/ro-RO/README.ro.md @@ -46,4 +46,918 @@ Nu ezita să mă contactezi! 😊

+--- + +###### 1. Care este rezultatul? + +```javascript +function sayHi() { + console.log(name); + console.log(age); + var name = 'Lydia'; + let age = 21; +} + +sayHi(); +``` + +- A: `Lydia` și `undefined` +- B: `Lydia` și `ReferenceError` +- C: `ReferenceError` și `21` +- D: `undefined` și `ReferenceError` + +
Răspuns +

+ +#### Răspuns: D + +În interiorul funcției, mai întâi declarăm variabila `name` cu cuvântul cheie `var`. Acest lucru înseamnă că variabila este hoisted (spațiul de memorie este configurat în faza de creare) cu valoarea implicită `undefined`, până când ajungem efectiv la linia în care definim variabila. Nu am definit încă variabila pe linia în care încercăm să înregistrăm variabila `name`, așa că aceasta păstrează încă valoarea `undefined`. + +Variabilele create cu cuvântul cheie `let` (și `const`) sunt hoisted, dar, spre deosebire de `var`, nu sunt inițializate. Acestea nu sunt accesibile înainte de linia în care le declarăm (initializăm). Aceasta se numește zona moartă temporală (temporal dead zone). Atunci când încercăm să accesăm variabilele înainte de a fi declarate, JavaScript aruncă o excepție de tip `ReferenceError`. + +

+
+ +--- + +###### 2. Care este rezultatul? + +```javascript +for (var i = 0; i < 3; i++) { + setTimeout(() => console.log(i), 1); +} + +for (let i = 0; i < 3; i++) { + setTimeout(() => console.log(i), 1); +} +``` + +- A: `0 1 2` și `0 1 2` +- B: `0 1 2` și `3 3 3` +- C: `3 3 3` și `0 1 2` + +
Răspuns +

+ +#### Răspuns: C + +Datorită cozii de evenimente din JavaScript, funcția de callback `setTimeout` este apelată _după_ ce bucla a fost executată. Deoarece variabila `i` din prima buclă a fost declarată folosind cuvântul cheie `var`, această valoare a fost globală. În timpul buclei, am incrementat valoarea lui `i` cu `1` de fiecare dată, folosind operatorul unary `++`. Până când funcția de callback `setTimeout` a fost invocată, `i` era egal cu `3` în primul exemplu. + +În cea de-a doua buclă, variabila `i` a fost declarată folosind cuvântul cheie `let`: variabilele declarate cu cuvântul cheie `let` (și `const`) sunt cu scop la nivel de bloc (un bloc este orice între `{ }`). În fiecare iterație, `i` va avea o valoare nouă, iar fiecare valoare este în cadrul buclei. + +

+
+ +--- + +###### 3. Care este rezultatul? + +```javascript +const shape = { + radius: 10, + diameter() { + return this.radius * 2; + }, + perimeter: () => 2 * Math.PI * this.radius, +}; + +console.log(shape.diameter()); +console.log(shape.perimeter()); +``` + +- A: `20` și `62.83185307179586` +- B: `20` și `NaN` +- C: `20` și `63` +- D: `NaN` și `63` + +
Răspuns +

+ +#### Răspuns: B + +Rețineți că valoarea lui `diameter` este o funcție obișnuită, în timp ce valoarea lui `perimeter` este o funcție arrow. + +Cu funcțiile arrow, cuvântul cheie `this` se referă la contextul său curent de încadrare, spre deosebire de funcțiile obișnuite! Acest lucru înseamnă că atunci când apelăm `perimeter`, acesta nu se referă la obiectul formei, ci la încadrarea sa curentă (de exemplu, fereastra). + +Nu există nicio valoare `radius` pe acel obiect, ceea ce returnează `NaN`. + +

+
+ +--- + +###### 4. Care este rezultatul? + +```javascript ++true; +!'Lydia'; +``` + +- A: `1` și `false` +- B: `false` și `NaN` +- C: `false` și `false` + +
Răspuns +

+ +#### Răspuns: A + +Operatorul unary plus încearcă să convertească un operand într-un număr. `true` este `1`, și `false` este `0`. + +Șirul de caractere `'Lydia'` este o valoare adevărată. Ceea ce întrebăm de fapt, este "este această valoare adevărată falsă?". Acest lucru returnează `false`. + +

+
+ +--- + +###### 5. Care este rezultatul? + +```javascript +const bird = { + size: 'small', +}; + +const mouse = { + name: 'Mickey', + small: true, +}; +``` + +- A: `mouse.bird.size` nu este valid +- B: `mouse[bird.size]` nu este valid +- C: `mouse[bird["size"]]` nu este valid +- D: Toate sunt valide + +
Răspuns +

+ +#### Răspuns: A + +În JavaScript, toate cheile obiectelor sunt șiruri de caractere (cu excepția simbolurilor). Chiar dacă nu le _tipizăm_ ca șiruri de caractere, ele sunt întotdeauna convertite în șiruri de caractere în fundal. + +avaScript interpretează (sau dezambalează) instrucțiunile. Atunci când folosim notația cu paranteze pătrate, vede prima paranteză pătrată de deschidere `[` și continuă până când găsește paranteza pătrată de închidere `]`. Doar atunci va evalua instrucțiunea. + +`mouse[bird.size]`: Întâi evaluează `bird.size`, care este `"small"`. `mouse["small"]` returnează `true` + +Cu toate acestea, cu notația cu punct, acest lucru nu se întâmplă. `mouse` nu are o cheie numită `bird`, ceea ce înseamnă că `mouse.bird` este `undefined`. Apoi, cerem `size` folosind notația cu punct: `mouse.bird.size`. Deoarece `mouse.bird` este `undefined`, de fapt cerem `undefined.size`. Acest lucru nu este valid și va arunca o eroare similară cu `Cannot read property "size" of undefined` (Nu se poate citi proprietatea "size" a unei valori nedefinite). + +

+
+ +--- + +###### 6. Care este rezultatul? + +```javascript +let c = { greeting: 'Hey!' }; +let d; + +d = c; +c.greeting = 'Hello'; +console.log(d.greeting); +``` + +- A: `Hello` +- B: `Hey!` +- C: `undefined` +- D: `ReferenceError` +- E: `TypeError` + +
Răspuns +

+ +#### Răspuns: A + +În JavaScript, toate obiectele interacționează prin _referință_ atunci când sunt setate ca egale între ele. + +Mai întâi, variabila `c` deține o valoare care face referire la un obiect. Ulterior, atribuim variabilei `d` aceeași referință pe care o are `c` la obiect. + + + +Când modifici un obiect, le modifici pe toate. + +

+
+ +--- + +###### 7. Care este rezultatul? + +```javascript +let a = 3; +let b = new Number(3); +let c = 3; + +console.log(a == b); +console.log(a === b); +console.log(b === c); +``` + +- A: `true` `false` `true` +- B: `false` `false` `true` +- C: `true` `false` `false` +- D: `false` `true` `true` + +
Răspuns +

+ +#### Răspuns: C + +`new Number()` este un constructor de funcții încorporat. Deși arată ca un număr, nu este într-adevăr un număr: are o mulțime de funcționalități suplimentare și este un obiect. + +Atunci când folosim operatorul `==` (operatorul de egalitate), acesta verifică doar dacă au aceeași _valuare_. Ambele au valoarea `3`, șa că returnează `true`. + +Cu toate acestea, atunci când folosim operatorul `===` (operatorul de egalitate strictă), atât valoarea, cât _și_ tipul trebuie să fie la fel. Nu sunt: `new Number()` nu este un număr, este un **object**. Ambele returnează `false.` + +

+
+ +--- + +###### 8. Care este rezultatul? + +```javascript +class Chameleon { + static colorChange(newColor) { + this.newColor = newColor; + return this.newColor; + } + + constructor({ newColor = 'green' } = {}) { + this.newColor = newColor; + } +} + +const freddie = new Chameleon({ newColor: 'purple' }); +console.log(freddie.colorChange('orange')); +``` + +- A: `orange` +- B: `purple` +- C: `green` +- D: `TypeError` + +
Răspuns +

+ +#### Răspuns: D + +Funcția `colorChange` este statică. Metodele statice sunt concepute să existe doar pe constructorul în care sunt create și nu pot fi transmise către niciun copil sau apelate pe instanțele clasei. Deoarece `freddie` este o instanță a clasei Chameleon, funcția nu poate fi apelată pe aceasta. Se aruncă o eroare de tip `TypeError`. + +

+
+ +--- + +###### 9. Care este rezultatul? + +```javascript +let greeting; +greetign = {}; // Typo! +console.log(greetign); +``` + +- A: `{}` +- B: `ReferenceError: greetign is not defined` +- C: `undefined` + +
Răspuns +

+ +#### Răspuns: A + +Se afișează obiectul, deoarece tocmai am creat un obiect gol pe obiectul global! Atunci când am greșit și am scris `greeting` în loc de `greetign`, interpretorul JavaScript a văzut efectiv acest lucru ca: + +1. `global.greetign = {}` în Node.js +2. `window.greetign = {}`, `frames.greetign = {}` și `self.greetign` în browser-e. +3. `self.greetign` în web workers. +4. `globalThis.greetign` în toate mediile. + +Pentru a evita acest lucru, putem folosi `"use strict"`. Acest lucru se asigură că ai declarat o variabilă înainte de a-i atribui o valoare. + +

+
+ +--- + +###### 10. Ce se întâmplă când facem asta? + +```javascript +function bark() { + console.log('Woof!'); +} + +bark.animal = 'dog'; +``` + +- A: Nimic, este absolut în regulă! +- B: `SyntaxError`. Nu poți adăuga proprietăți la o funcție în acest fel. +- C: `"Woof"` este înregistrat. +- D: `ReferenceError` + +
Răspuns +

+ +#### Răspuns: A + +Acest lucru este posibil în JavaScript, deoarece funcțiile sunt obiecte! (Totul, în afară de tipurile primitive, sunt obiecte) + +O funcție este un tip special de obiect. Codul pe care îl scrii tu însuți nu este funcția efectivă. Funcția este un obiect cu proprietăți. Această proprietate este invocabilă. + +

+
+ +--- + +###### 11. Care este rezultatul? + +```javascript +function Person(firstName, lastName) { + this.firstName = firstName; + this.lastName = lastName; +} + +const member = new Person('Lydia', 'Hallie'); +Person.getFullName = function () { + return `${this.firstName} ${this.lastName}`; +}; + +console.log(member.getFullName()); +``` + +- A: `TypeError` +- B: `SyntaxError` +- C: `Lydia Hallie` +- D: `undefined` `undefined` + +
Răspuns +

+ +#### Răspuns: A + +În JavaScript, funcțiile sunt obiecte și, prin urmare, metoda `getFullName` este adăugată obiectului constructor al funcției în sine. Din acest motiv, putem apela `Person.getFullName()`, dar `member.getFullName` aruncă o eroare de tip `TypeError`. + +Dacă doriți ca o metodă să fie disponibilă pentru toate instanțele obiectului, trebuie să o adăugați la proprietatea prototype: + +```js +Person.prototype.getFullName = function () { + return `${this.firstName} ${this.lastName}`; +}; +``` + +

+
+ +--- + +###### 12. Care este rezultatul? + +```javascript +function Person(firstName, lastName) { + this.firstName = firstName; + this.lastName = lastName; +} + +const lydia = new Person('Lydia', 'Hallie'); +const sarah = Person('Sarah', 'Smith'); + +console.log(lydia); +console.log(sarah); +``` + +- A: `Person {firstName: "Lydia", lastName: "Hallie"}` și `undefined` +- B: `Person {firstName: "Lydia", lastName: "Hallie"}` și `Person {firstName: "Sarah", lastName: "Smith"}` +- C: `Person {firstName: "Lydia", lastName: "Hallie"}` și `{}` +- D: `Person {firstName: "Lydia", lastName: "Hallie"}` și `ReferenceError` + +
Răspuns +

+ +#### Răspuns: A + +Pentru `sarah`, nu am folosit cuvântul cheie `new`. Când folosim `new`, `this` se referă la noul obiect gol pe care îl creăm. Cu toate acestea, dacă nu adăugăm `new`, `this` se referă la **obiectul global**! + +Am spus că `this.firstName` este egal cu `"Sarah"` și `this.lastName` este egal cu `"Smith"`. Ceea ce am făcut de fapt este să definim `global.firstName = 'Sarah'` și `global.lastName = 'Smith'`. `sarah` în sine rămâne `undefined`, deoarece nu returnăm o valoare din funcția `Person`. + +

+
+ +--- + +###### 13. Care sunt cele trei faze ale propagării evenimentelor? + +- A: Target > Capturing > Bubbling +- B: Bubbling > Target > Capturing +- C: Target > Bubbling > Capturing +- D: Capturing > Target > Bubbling + +
Răspuns +

+ +#### Răspuns: D + +În timpul fazei de **capturing**, evenimentul trece prin elementele părinte până la elementul țintă. Apoi ajunge la elementul **target**, și începe **bubbling**. + + + +

+
+ +--- + +###### 14. Toate obiectele au prototipuri. + +- A: true +- B: false + +
Răspuns +

+ +#### Răspuns: B + +Toate obiectele au prototipuri, cu excepția **obiectului de bază**. Obiectul de bază este obiectul creat de utilizator sau un obiect creat folosind cuvântul cheie `new`. Obiectul de bază are acces la unele metode și proprietăți, cum ar fi `.toString`. Acesta este motivul pentru care puteți utiliza metode JavaScript încorporate! Toate aceste metode sunt disponibile în prototip. Deși JavaScript nu le poate găsi direct în obiectul dvs., merge în jos pe lanțul prototip și le găsește acolo, ceea ce le face accesibile pentru dvs. + +

+
+ +--- + +###### 15. Care este rezultatul? + +```javascript +function sum(a, b) { + return a + b; +} + +sum(1, '2'); +``` + +- A: `NaN` +- B: `TypeError` +- C: `"12"` +- D: `3` + +
Răspuns +

+ +#### Răspuns: C + +JavaScript este un limbaj **dinamic tipizat**: nu specificăm tipurile variabilelor. Valorile pot fi convertite automat în alt tip fără să știți, ceea ce se numește _coerție de tip implicită_. **Coerția** este conversia dintr-un tip în altul. + +În acest exemplu, JavaScript convertește numărul `1` într-un șir de caractere, pentru ca funcția să aibă sens și să returneze o valoare. În timpul adunării unui tip numeric (`1`) și unui tip șir de caractere (`'2'`), numărul este tratat ca un șir de caractere. Putem concatena șiruri de caractere, așa cum facem cu `"Hello" + "World"`, deci ceea ce se întâmplă aici este `"1" + "2"` care returnează `"12"`. + +

+
+ +--- + +###### 16. Care este rezultatul? + +```javascript +let number = 0; +console.log(number++); +console.log(++number); +console.log(number); +``` + +- A: `1` `1` `2` +- B: `1` `2` `2` +- C: `0` `2` `2` +- D: `0` `1` `2` + +
Răspuns +

+ +#### Răspuns: C + +Operatorul unary **postfix** `++`: + +1. Returnează valoarea (aceasta returnează `0`) +2. Incrementează valoarea (numărul este acum `1`) + +Operatorul unary **prefix** `++`: + +1. Incrementează valoarea (numărul este acum `2`) +2. Returnează valoarea (aceasta returnează `2`) + +Aceasta returnează `0 2 2`. + +

+
+ +--- + +###### 17. Care este rezultatul? + +```javascript +function getPersonInfo(one, two, three) { + console.log(one); + console.log(two); + console.log(three); +} + +const person = 'Lydia'; +const age = 21; + +getPersonInfo`${person} is ${age} years old`; +``` + +- A: `"Lydia"` `21` `["", " is ", " years old"]` +- B: `["", " is ", " years old"]` `"Lydia"` `21` +- C: `"Lydia"` `["", " is ", " years old"]` `21` + +
Răspuns +

+ +#### Răspuns: B + +Dacă utilizați șiruri template etichetate, valoarea primului argument este întotdeauna un șir de valori. Argumentele rămase primesc valorile expresiilor transmise! + +

+
+ +--- + +###### 18. Care este rezultatul? + +```javascript +function checkAge(data) { + if (data === { age: 18 }) { + console.log('You are an adult!'); + } else if (data == { age: 18 }) { + console.log('You are still an adult.'); + } else { + console.log(`Hmm.. You don't have an age I guess`); + } +} + +checkAge({ age: 18 }); +``` + +- A: `You are an adult!` +- B: `You are still an adult.` +- C: `Hmm.. You don't have an age I guess` + +
Răspuns +

+ +#### Răspuns: C + +Când se testează egalitatea, primitivele sunt comparate în funcție de valoarea lor, în timp ce obiectele sunt comparate în funcție de _referința_ lor. JavaScript verifică dacă obiectele au o referință către aceeași locație în memorie. + +Cele două obiecte pe care le comparăm nu au aceeași referință: obiectul pe care l-am trecut ca parametru se referă la o altă locație în memorie decât obiectul pe care l-am folosit pentru a verifica egalitatea. + +Acesta este motivul pentru care ambele `{ age: 18 } === { age: 18 }` și `{ age: 18 } == { age: 18 }` returnează `false`. + +

+
+ +--- + +###### 19. Care este rezultatul? + +```javascript +function getAge(...args) { + console.log(typeof args); +} + +getAge(21); +``` + +- A: `"number"` +- B: `"array"` +- C: `"object"` +- D: `"NaN"` + +
Răspuns +

+ +#### Răspuns: C + +Parametrul rest (`...args`) ne permite să "colectăm" toate argumentele rămase într-un array. Un array este un obiect, așa că `typeof args` returnează `"object"` + +

+
+ +--- + +###### 20. Care este rezultatul? + +```javascript +function getAge() { + 'use strict'; + age = 21; + console.log(age); +} + +getAge(); +``` + +- A: `21` +- B: `undefined` +- C: `ReferenceError` +- D: `TypeError` + +
Răspuns +

+ +#### Răspuns: C + +Cu `"use strict"`, puteți asigura că nu declarați accidental variabile globale. Niciodată nu am declarat variabila `age`, și deoarece folosim `"use strict"`, va arunca o eroare de referință. Dacă nu am fi folosit `"use strict"`, ar fi funcționat, deoarece proprietatea `age` ar fi fost adăugată la obiectul global. + +

+
+ +--- + +###### 21. Care este valoarea lui `sum`? + +```javascript +const sum = eval('10*10+5'); +``` + +- A: `105` +- B: `"105"` +- C: `TypeError` +- D: `"10*10+5"` + +
Răspuns +

+ +#### Răspuns: A + +`eval` evaluează codul care este trecut ca un șir de caractere. Dacă este o expresie, așa cum este în acest caz, evaluează expresia. Expresia este `10 * 10 + 5`. Aceasta returnează numărul `105`. + +

+
+ +--- + +###### 22. Cât timp este accesibil cool_secret? + +```javascript +sessionStorage.setItem('cool_secret', 123); +``` + +- A: Pentru totdeauna, datele nu se pierd. +- B: Când utilizatorul închide fila. +- C: Când utilizatorul închide întregul browser, nu doar fila. +- D: Când utilizatorul oprește computerul. + +
Răspuns +

+ +#### Răspuns: B + +Datele stocate în `sessionStorage` sunt eliminate după închiderea _filei_. + +Dacă ați fi folosit `localStorage`, datele ar fi rămas acolo pentru totdeauna, cu excepția cazului în care, de exemplu, este invocată comanda `localStorage.clear()`. + +

+
+ +--- + +###### 23. Care este rezultatul? + +```javascript +var num = 8; +var num = 10; + +console.log(num); +``` + +- A: `8` +- B: `10` +- C: `SyntaxError` +- D: `ReferenceError` + +
Răspuns +

+ +#### Răspuns: B + +Cu cuvântul cheie `var`, puteți declara mai multe variabile cu același nume. Variabila va reține apoi cea mai recentă valoare. + +Nu puteți face acest lucru cu `let` sau `const` deoarece acestea sunt cu scop de bloc. + +

+
+ +--- + +###### 24. Care este rezultatul? + +```javascript +const obj = { 1: 'a', 2: 'b', 3: 'c' }; +const set = new Set([1, 2, 3, 4, 5]); + +obj.hasOwnProperty('1'); +obj.hasOwnProperty(1); +set.has('1'); +set.has(1); +``` + +- A: `false` `true` `false` `true` +- B: `false` `true` `true` `true` +- C: `true` `true` `false` `true` +- D: `true` `true` `true` `true` + +
Răspuns +

+ +#### Răspuns: C + +Toate cheile obiectelor (cu excepția simbolurilor) sunt șiruri de caractere în culise, chiar dacă nu le tastați ca șiruri de caractere. De aceea `obj.hasOwnProperty('1')` returnează de asemenea `true`. + +Acest lucru nu funcționează în același fel pentru un set. Nu există `'1'` în setul nostru: `set.has('1')` returnează `false`. Acesta are tipul numeric `1`, `set.has(1)` returnează `true`. + +

+
+ +--- + +###### 25. Care este rezultatul? + +```javascript +const obj = { a: 'one', b: 'two', a: 'three' }; +console.log(obj); +``` + +- A: `{ a: "one", b: "two" }` +- B: `{ b: "two", a: "three" }` +- C: `{ a: "three", b: "two" }` +- D: `SyntaxError` + +
Răspuns +

+ +#### Răspuns: C + +Dacă aveți două chei cu același nume, cheia va fi înlocuită. Va rămâne totuși în prima sa poziție, dar cu ultima valoare specificată. + +

+
+ +--- + +###### 26. Contextul global de execuție JavaScript creează două lucruri pentru dvs.: obiectul global și cuvântul cheie "this". + +- A: true +- B: false +- C: it depends + +
Răspuns +

+ +#### Răspuns: A + +Contextul de execuție de bază este contextul global de execuție: este ceea ce este accesibil peste tot în codul dvs. + +

+
+ +--- + +###### 27. Care este rezultatul? + +```javascript +for (let i = 1; i < 5; i++) { + if (i === 3) continue; + console.log(i); +} +``` + +- A: `1` `2` +- B: `1` `2` `3` +- C: `1` `2` `4` +- D: `1` `3` `4` + +
Răspuns +

+ +#### Răspuns: C + +Instrucțiunea `continue` sare peste o iterație dacă o anumită condiție returnează `true`. + +

+
+ +--- + +###### 28. Care este rezultatul? + +```javascript +String.prototype.giveLydiaPizza = () => { + return 'Just give Lydia pizza already!'; +}; + +const name = 'Lydia'; + +console.log(name.giveLydiaPizza()); +``` + +- A: `"Just give Lydia pizza already!"` +- B: `TypeError: not a function` +- C: `SyntaxError` +- D: `undefined` + +
Răspuns +

+ +#### Răspuns: A + +`String` este un constructor încorporat, la care putem adăuga proprietăți. Am adăugat doar o metodă la prototipul său. Șirurile primitive sunt convertite automat într-un obiect șir, generat de funcția prototip a șirului. Prin urmare, toate șirurile (obiecte de șir) au acces la acea metodă! + +

+
+ +--- + +###### 29. Care este rezultatul? + +```javascript +const a = {}; +const b = { key: 'b' }; +const c = { key: 'c' }; + +a[b] = 123; +a[c] = 456; + +console.log(a[b]); +``` + +- A: `123` +- B: `456` +- C: `undefined` +- D: `ReferenceError` + +
Răspuns +

+ +#### Răspuns: B + +Cheile obiectului sunt convertite automat în șiruri de caractere. Încercăm să setăm un obiect ca cheie pentru obiectul `a`, cu valoarea `123`. + +Cu toate acestea, când transformăm în șir un obiect, acesta devine `"[object Object]"`. Deci ceea ce spunem aici este că `a["[object Object]"] = 123`. Apoi, putem încerca să facem același lucru din nou. `c` este un alt obiect pe care îl transformăm implicit în șir. Așadar, `a["[object Object]"] = 456`. + +Apoi, afișăm înregistrarea `a[b]`, care de fapt este `a["[object Object]"]`. Am setat doar asta la `456`, deci returnează `456`. + +

+
+ +--- + +###### 30. Care este rezultatul? + +```javascript +const foo = () => console.log('First'); +const bar = () => setTimeout(() => console.log('Second')); +const baz = () => console.log('Third'); + +bar(); +foo(); +baz(); +``` + +- A: `First` `Second` `Third` +- B: `First` `Third` `Second` +- C: `Second` `First` `Third` +- D: `Second` `Third` `First` + +
Răspuns +

+ +#### Răspuns: B + +Avem o funcție `setTimeout` și am invocat-o mai întâi. Cu toate acestea, a fost înregistrată în ultimul rând. + +Acest lucru se datorează faptului că în browsere, nu avem doar motorul de execuție, avem și ceva numit `WebAPI`.`WebAPI` ne oferă funcția `setTimeout` de exemplu, și DOM-ul. + +După ce _callback_-ul este trimis către WebAPI, funcția `setTimeout` în sine (dar nu și callback-ul!) este scos din stivă. + + + +Acum, `foo` este invocată, iar`"First"` este înregistrat. + + + +`foo` este scoasă din stivă, iar `baz` este invocată. Se înregistrează `"Third"`. + + + +WebAPI-ul nu poate adăuga pur și simplu lucruri în stivă atunci când este gata. În schimb, împinge funcția de callback într-o structură numită _coadă_. + + + +Aici începe să lucreze un event loop. Un **event loop** se uită la stivă și la coada de sarcini. Dacă stiva este goală, ia primul lucru din coadă și-l adaugă în stivă. + + + +`bar` este invocată, `"Second"` este înregistrat și este scos din stivă. + +

+
+ --- \ No newline at end of file From f71c4165a7e8cbdb97df743ddaa7a837aeb43fad Mon Sep 17 00:00:00 2001 From: alexb017 Date: Tue, 22 Aug 2023 23:23:51 +0300 Subject: [PATCH 171/193] Added the questions from 31-40 --- ro-RO/README.ro.md | 299 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 299 insertions(+) diff --git a/ro-RO/README.ro.md b/ro-RO/README.ro.md index 1f15fd70..1a86110b 100644 --- a/ro-RO/README.ro.md +++ b/ro-RO/README.ro.md @@ -960,4 +960,303 @@ Aici începe să lucreze un event loop. Un **event loop** se uită la stivă și

+--- + +###### 31. Ce reprezintă "event.target" atunci când se face clic pe buton? + +```html +
+
+ +
+
+``` + +- A: În afara `div` +- B: În interior `div` +- C: `button` +- D: Un șir de toate elementele înglobate. + +
Răspuns +

+ +#### Răspuns: C + +Cel mai profund element înglobat care a cauzat evenimentul este ținta evenimentului. Puteți opri propagarea acestuia prin `event.stopPropagation` + +

+
+ +--- + +###### 32. Când faceți clic pe paragraf, care este ieșirea înregistrată? + +```html +
+

+ Click here! +

+
+``` + +- A: `p` `div` +- B: `div` `p` +- C: `p` +- D: `div` + +
Răspuns +

+ +#### Răspuns: A + +Dacă facem clic pe `p`, vom vedea două înregistrări: `p` și `div`. În timpul propagării evenimentului, există 3 faze: capturare, țintă și propagare. În mod implicit, gestionarii de evenimente sunt executați în faza de propagare (cu excepția cazului în care setați `useCapture` la `true`). Aceștia se execută de la cel mai profund element înglobat către exterior. + +

+
+ +--- + +###### 33. Care este rezultatul? + +```javascript +const person = { name: 'Lydia' }; + +function sayHi(age) { + return `${this.name} is ${age}`; +} + +console.log(sayHi.call(person, 21)); +console.log(sayHi.bind(person, 21)); +``` + +- A: `undefined is 21` `Lydia is 21` +- B: `function` `function` +- C: `Lydia is 21` `Lydia is 21` +- D: `Lydia is 21` `function` + +
Răspuns +

+ +#### Răspuns: D + +Cu ambele metode, putem transmite obiectul la care dorim să se refere cuvântul cheie `this`. Cu toate acestea, `.call` este de asemenea _executat imediat_! + +`.bind.` returnează o _copie_ a funcției, dar cu un context legat! Nu este executat imediat. + +

+
+ +--- + +###### 34. Care este rezultatul? + +```javascript +function sayHi() { + return (() => 0)(); +} + +console.log(typeof sayHi()); +``` + +- A: `"object"` +- B: `"number"` +- C: `"function"` +- D: `"undefined"` + +
Răspuns +

+ +#### Răspuns: B + +Funcția `sayHi` returnează valoarea returnată de expresia funcției invocate imediat (IIFE). This function returned `0`, care este de tip `"number"`. + +Informație utilă: `typeof` poate returna următoarele valori: `undefined`, `boolean`, `number`, `bigint`, `string`, `symbol`, `function` și `object`. Notați că `typeof null` returnează `"object"`. + +

+
+ +--- + +###### 35. Care dintre aceste valori sunt considerate falsy? + +```javascript +0; +new Number(0); +(''); +(' '); +new Boolean(false); +undefined; +``` + +- A: `0`, `''`, `undefined` +- B: `0`, `new Number(0)`, `''`, `new Boolean(false)`, `undefined` +- C: `0`, `''`, `new Boolean(false)`, `undefined` +- D: Toate dintre ele sunt considerate falsy + +
Răspuns +

+ +#### Răspuns: A + +Există 8 valori considerate falsy: + +- `undefined` +- `null` +- `NaN` +- `false` +- `''` (șir de caractere gol) +- `0` +- `-0` +- `0n` (BigInt(0)) + +Constructorii de funcții, cum ar fi `new Number` și `new Boolean` sunt considerați truthy. + +

+
+ +--- + +###### 36. Care este rezultatul? + +```javascript +console.log(typeof typeof 1); +``` + +- A: `"number"` +- B: `"string"` +- C: `"object"` +- D: `"undefined"` + +
Răspuns +

+ +#### Răspuns: B + +`typeof 1` returnează `"number"`. +`typeof "number"` returnează `"string"` + +

+
+ +--- + +###### 37. Care este rezultatul? + +```javascript +const numbers = [1, 2, 3]; +numbers[10] = 11; +console.log(numbers); +``` + +- A: `[1, 2, 3, null x 7, 11]` +- B: `[1, 2, 3, 11]` +- C: `[1, 2, 3, empty x 7, 11]` +- D: `SyntaxError` + +
Răspuns +

+ +#### Răspuns: C + +Când setați o valoare pentru un element într-un array care depășește lungimea array-ului, JavaScript creează ceea ce se numește "slot-uri goale" (empty slots). Acestea au de fapt valoarea `undefined`, dar veți vedea ceva de genul: + +`[1, 2, 3, empty x 7, 11]` + +în funcție de locul în care îl rulați (este diferit pentru fiecare browser, Node.js, etc.) + +

+
+ +--- + +###### 38. Care este rezultatul? + +```javascript +(() => { + let x, y; + try { + throw new Error(); + } catch (x) { + (x = 1), (y = 2); + console.log(x); + } + console.log(x); + console.log(y); +})(); +``` + +- A: `1` `undefined` `2` +- B: `undefined` `undefined` `undefined` +- C: `1` `1` `2` +- D: `1` `undefined` `undefined` + +
Răspuns +

+ +#### Răspuns: A + +Blocul `catch` primește argumentul `x`. Acesta nu este același `x` ca variabila când transmitem argumente. Această variabilă `x` este având domeniu de bloc (block-scoped). + +Mai târziu, setăm această variabilă cu domeniu de bloc la valoarea `1`, și stabilim valoarea variabilei `y`. Acum, înregistrăm în consolă variabila cu domeniu de bloc `x`, care este egală cu `1`. + +În afara blocului `catch`, `x` rămâne `undefined`, și `y` este `2`. Atunci când dorim să afișăm în consolă `console.log(x)` în afara blocului `catch`, acesta returnează `undefined`, și `y` returnează `2`. + +

+
+ +--- + +###### 39. Totul în JavaScript este fie un... + +- A: primitiv sau obiect +- B: funcție sau obiect +- C: întrebare trucată! doar obiecte +- D: număr sau obiect + +
Răspuns +

+ +#### Răspuns: A + +JavaScript are doar tipuri primitive și obiecte. + +Tipurile primitive sunt `boolean`, `null`, `undefined`, `bigint`, `number`, `string`, și `symbol`. + +Ceea ce diferențiază un tip primitiv de un obiect este faptul că tipurile primitive nu au proprietăți sau metode. Cu toate acestea, veți observa că `'foo'.toUpperCase()` se evaluează la `'FOO'` și nu duce la o eroare `TypeError`. Acest lucru se întâmplă pentru că atunci când încercați să accesați o proprietate sau o metodă pe un tip primitiv, cum ar fi un șir de caractere (string), JavaScript va înconjura implicit tipul primitiv folosind una dintre clasele de înveliș, adică `String`, și apoi va renunța imediat la înveliș după ce expresia se evaluează. Toate tipurile primitive, cu excepția `null` și `undefined` prezintă acest comportament. + +

+
+ +--- + +###### 40. Care este rezultatul? + +```javascript +[[0, 1], [2, 3]].reduce( + (acc, cur) => { + return acc.concat(cur); + }, + [1, 2], +); +``` + +- A: `[0, 1, 2, 3, 1, 2]` +- B: `[6, 1, 2]` +- C: `[1, 2, 0, 1, 2, 3]` +- D: `[1, 2, 6]` + +
Răspuns +

+ +#### Răspuns: C + +`[1, 2]` este valoarea noastră inițială. Aceasta este valoarea cu care începem și valoarea primului `acc`. În prima rundă, `acc` este `[1,2]`, și `cur` este `[0, 1]`. Le concatenăm, ceea ce duce la rezultatul `[1, 2, 0, 1]`. + +Atunci, `[1, 2, 0, 1]` este `acc` și `[2, 3]` este `cur`. Le concatenăm și obținem `[1, 2, 0, 1, 2, 3]` + +

+
+ --- \ No newline at end of file From 61c9c0b0592259332dd1c476f7d4efc7dce7801a Mon Sep 17 00:00:00 2001 From: alexb017 Date: Tue, 22 Aug 2023 23:26:24 +0300 Subject: [PATCH 172/193] fix: ro-language link --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 7ccfaa63..30168af0 100644 --- a/README.md +++ b/README.md @@ -33,7 +33,7 @@ Feel free to reach out to me! 😊
- [🇳🇱 Nederlands](./nl-NL/README.md) - [🇵🇱 Polski](./pl-PL/README.md) - [🇧🇷 Português Brasil](./pt-BR/README_pt_BR.md) -- [🇷o Română](../ro-RO/README.ro.md) +- [🇷o Română](./ro-RO/README.ro.md) - [🇷🇺 Русский](./ru-RU/README.md) - [🇽🇰 Shqip](./sq-KS/README_sq_KS.md) - [🇹🇭 ไทย](./th-TH/README-th_TH.md) From 2b20d4a8df8d319100e59b5be52a9b50c91df721 Mon Sep 17 00:00:00 2001 From: alexb017 Date: Wed, 23 Aug 2023 23:21:40 +0300 Subject: [PATCH 173/193] Added the questions from 41-50 --- ro-RO/README.ro.md | 290 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 290 insertions(+) diff --git a/ro-RO/README.ro.md b/ro-RO/README.ro.md index 1a86110b..9ad92324 100644 --- a/ro-RO/README.ro.md +++ b/ro-RO/README.ro.md @@ -1259,4 +1259,294 @@ Atunci, `[1, 2, 0, 1]` este `acc` și `[2, 3]` este `cur`. Le concatenăm și ob

+--- + +###### 41. Care este rezultatul? + +```javascript +!!null; +!!''; +!!1; +``` + +- A: `false` `true` `false` +- B: `false` `false` `true` +- C: `false` `true` `true` +- D: `true` `true` `false` + +
Răspuns +

+ +#### Răspuns: B + +`null` este falsy. `!null` returnează `true`. `!true` returnează `false`. + +`""` este falsy. `!""` returnează `true`. `!true` returnează `false`. + +`1` este truthy. `!1` returnează `false`. `!false` returnează `true`. + +

+
+ +--- + +###### 42. Ce returnează metoda `setInterval` în browser? + +```javascript +setInterval(() => console.log('Hi'), 1000); +``` + +- A: un id unic +- B: cantitatea de milisecunde specificată +- C: funcția furnizată +- D: `undefined` + +
Răspuns +

+ +#### Răspuns: A + +Aceasta returnează un identificator unic. Acest id poate fi utilizat pentru a opri intervalul respectiv cu ajutorul funcției `clearInterval()`. + +

+
+ +--- + +###### 43. Ce returnează acest lucru? + +```javascript +[...'Lydia']; +``` + +- A: `["L", "y", "d", "i", "a"]` +- B: `["Lydia"]` +- C: `[[], "Lydia"]` +- D: `[["L", "y", "d", "i", "a"]]` + +
Răspuns +

+ +#### Răspuns: A + +Un șir de caractere este un obiect iterabil. Operatorul de răspândire (spread operator) mapează fiecare caracter dintr-un obiect iterabil la un element separat. + +

+
+ +--- + +###### 44. Care este rezultatul? + +```javascript +function* generator(i) { + yield i; + yield i * 2; +} + +const gen = generator(10); + +console.log(gen.next().value); +console.log(gen.next().value); +``` + +- A: `[0, 10], [10, 20]` +- B: `20, 20` +- C: `10, 20` +- D: `0, 10 and 10, 20` + +
Răspuns +

+ +#### Răspuns: C + +Funcțiile regulate nu pot fi oprite în mijlocul execuției după invocare. Cu toate acestea, o funcție generator poate fi "oprită" în mijloc și ulterior poate continua de la locul unde s-a oprit. De fiecare dată când o funcție generator întâlnește un cuvânt cheie `yield`, funcția furnizează valoarea specificată după el. Notați că funcția generator în acest caz nu _returnează_ the valoarea, ci _furnizează_ valoarea. + +Mai întâi, inițializăm funcția generator cu `i` egal cu `10`. Invocăm funcția generator folosind metoda `next()`. Prima dată când invocăm funcția generator, `i` este egal cu `10`. Aceasta întâlnește primul cuvânt cheie `yield`: furnizează valoarea lui `i`. Generatorul este acum "pauzat", și se înregistrează valoarea `10`. + +Apoi, invocăm din nou funcția cu metoda `next()`. Ea începe să continue de unde s-a oprit anterior, încă cu `i` egal cu `10`. Acum, întâlnește următorul cuvânt cheie `yield`, și furnizează `i * 2`. `i` este egal cu `10`, așa că returnează `10 * 2`, adică `20`. Acest lucru duce la rezultatul `10, 20`. + +

+
+ +--- + +###### 45. Ce returnează asta? + +```javascript +const firstPromise = new Promise((res, rej) => { + setTimeout(res, 500, 'one'); +}); + +const secondPromise = new Promise((res, rej) => { + setTimeout(res, 100, 'two'); +}); + +Promise.race([firstPromise, secondPromise]).then(res => console.log(res)); +``` + +- A: `"one"` +- B: `"two"` +- C: `"two" "one"` +- D: `"one" "two"` + +
Răspuns +

+ +#### Răspuns: B + +Atunci când transmitem mai multe promisiuni metodei `Promise.race`, ea rezolvă/rejectează _prima_ promisiune care se rezolvă/rejectează. Pentru metoda `setTimeout`, transmitem un cronometru: 500ms pentru prima promisiune (`firstPromise`), și 100ms pentru a doua promisiune (`secondPromise`). Acest lucru înseamnă că `secondPromise` se rezolvă primul cu valoarea `'two'`. `res` conține acum valoarea `'two'`, care se înregistrează în consolă. + +

+
+ +--- + +###### 46. Care este resultatul? + +```javascript +let person = { name: 'Lydia' }; +const members = [person]; +person = null; + +console.log(members); +``` + +- A: `null` +- B: `[null]` +- C: `[{}]` +- D: `[{ name: "Lydia" }]` + +
Răspuns +

+ +#### Răspuns: D + +În primul rând, declarăm o variabilă `person` cu valoarea unui obiect care are o proprietate `name`. + + + +Apoi, declarăm o variabilă numită `members`. Setăm primul element al acestui array egal cu valoarea variabilei `person`. Obiectele interacționează prin _referință_ atunci când le setăm egale între ele. Atunci când atribuiți o referință de la o variabilă la alta, faceți o _copie_ a acelei referințe. (notați că acestea nu au _aceași_ referință!) + + + +Apoi, setăm variabila `person` egală cu `null`. + + + +Noi modificăm doar valoarea variabilei `person` nu și primul element din array, deoarece acel element are o referință diferită (copiată) la obiect. Primul element din `members` încă păstrează referința sa la obiectul original. Când înregistrăm în consolă array-ul `members` primul element păstrează valoarea obiectului, care este afișată în consolă. + +

+
+ +--- + +###### 47. Care este rezultatul? + +```javascript +const person = { + name: 'Lydia', + age: 21, +}; + +for (const item in person) { + console.log(item); +} +``` + +- A: `{ name: "Lydia" }, { age: 21 }` +- B: `"name", "age"` +- C: `"Lydia", 21` +- D: `["name", "Lydia"], ["age", 21]` + +
Răspuns +

+ +#### Răspuns: B + +Cu un ciclu `for-in` putem itera prin cheile obiectului, în acest caz `name` și `age`. În interior, cheile obiectului sunt șiruri de caractere (dacă nu sunt de tip Symbol). În fiecare iterație, setăm valoarea lui `item` egală cu cheia curentă pe care o parcurge. Mai întâi, `item` este egal cu `name`, și este înregistrat în consolă. Apoi, `item` este egal cu `age`, care este, de asemenea, înregistrat în consolă. + +

+
+ +--- + +###### 48. Care este rezultatul? + +```javascript +console.log(3 + 4 + '5'); +``` + +- A: `"345"` +- B: `"75"` +- C: `12` +- D: `"12"` + +
Răspuns +

+ +#### Răspuns: B + +Asociativitatea operatorilor este ordinea în care compilatorul evaluează expresiile, fie de la stânga la dreapta, fie de la dreapta la stânga. Acest lucru se întâmplă doar dacă toți operatorii au aceeași precedență. În cazul nostru, avem doar un tip de operator: `+`. Pentru adunare, asociativitatea este de la stânga la dreapta. + +`3 + 4` este evaluat mai întâi. Acest lucru duce la numărul `7`. + +`7 + '5'` duce la rezultatul `"75"` datorită coerției. JavaScript convertește numărul `7` într-un șir de caractere, așa cum am discutat în întrebarea 15. Putem concatena două șiruri de caractere folosind operatorul `+`. `"7" + "5"` rezultă în `"75"`. + +

+
+ +--- + +###### 49. Care este valoarea lui`num`? + +```javascript +const num = parseInt('7*6', 10); +``` + +- A: `42` +- B: `"42"` +- C: `7` +- D: `NaN` + +
Răspuns +

+ +#### Răspuns: C + +Este returnat doar primul număr din șir. Bazat pe _radix_ (al doilea argument pentru a specifica în ce tip de număr dorim să-l parsăm: bază 10, hexazecimal, octal, binar, etc.), `parseInt` verifică dacă caracterele din șir sunt valide. Odată ce întâlnește un caracter care nu este un număr valid în baza specificată, oprește parsarea și ignoră caracterele ulterioare. + +`*` nu este un număr valid. Parsează doar `"7"` în numărul zecimal `7`. Acum, `num` conține valoarea `7`. + +

+
+ +--- + +###### 50. Care este rezultatul? + +```javascript +[1, 2, 3].map(num => { + if (typeof num === 'number') return; + return num * 2; +}); +``` + +- A: `[]` +- B: `[null, null, null]` +- C: `[undefined, undefined, undefined]` +- D: `[ 3 x empty ]` + +
Răspuns +

+ +#### Răspuns: C + +Când se parcurge array-ul, valoarea lui `num` este egală cu elementul prin care parcurge în acel moment. În acest caz, elementele sunt numere, astfel că condiția din instrucțiunea `typeof num === "number"` returnează `true`. Funcția map creează un nou array și introduce valorile returnate de funcție. + +Cu toate acestea, nu returnăm o valoare. Atunci când nu returnăm o valoare din funcție, funcția returnează `undefined`. Pentru fiecare element din array, blocul funcției este apelat, deci pentru fiecare element returnăm `undefined`. + +

+
+ --- \ No newline at end of file From 34523eb086f9bbbbfd93ec3aec5cd2ae1d0e1b55 Mon Sep 17 00:00:00 2001 From: alexb017 Date: Thu, 24 Aug 2023 23:32:29 +0300 Subject: [PATCH 174/193] Added the questions from 51-60 --- ro-RO/README.ro.md | 346 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 346 insertions(+) diff --git a/ro-RO/README.ro.md b/ro-RO/README.ro.md index 9ad92324..921da0d2 100644 --- a/ro-RO/README.ro.md +++ b/ro-RO/README.ro.md @@ -1549,4 +1549,350 @@ Cu toate acestea, nu returnăm o valoare. Atunci când nu returnăm o valoare di

+--- + +###### 51. Care este rezultatul? + +```javascript +function getInfo(member, year) { + member.name = 'Lydia'; + year = '1998'; +} + +const person = { name: 'Sarah' }; +const birthYear = '1997'; + +getInfo(person, birthYear); + +console.log(person, birthYear); +``` + +- A: `{ name: "Lydia" }, "1997"` +- B: `{ name: "Sarah" }, "1998"` +- C: `{ name: "Lydia" }, "1998"` +- D: `{ name: "Sarah" }, "1997"` + +
Răspuns +

+ +#### Răspuns: A + +Argumentele sunt transmise prin _valoare_, cu excepția cazului în care valoarea lor este un obiect, caz în care sunt transmise prin _referință_. `birthYear` este transmis prin valoare, deoarece este un șir de caractere (string), nu un obiect. Atunci când transmitem argumente prin valoare, se creează o _copie_ a acelei valori (consultați întrebarea 46). + +Variabila `birthYear` are o referință la valoarea `"1997"`. Argumentul `year` are, de asemenea, o referință la valoarea `"1997"`, dar nu este aceeași valoare la care se referă `birthYear`. Atunci când actualizăm valoarea lui `year` prin setarea lui `year` egal cu `"1998"`, actualizăm doar valoarea lui `year`. `birthYear` rămâne în continuare egal cu `"1997"`. + +Valoarea lui `person` este un obiect. Argumentul `member` are o referință (copiată) către _același_ obiect. Atunci când modificăm o proprietate a obiectului la care se referă `member` valoarea lui `person` va fi de asemenea modificată, deoarece ambele au o referință la același obiect. Proprietatea `name` a lui `person` este acum egală cu valoarea `"Lydia"`. + +

+
+ +--- + +###### 52. Care este rezultatul? + +```javascript +function greeting() { + throw 'Hello world!'; +} + +function sayHi() { + try { + const data = greeting(); + console.log('It worked!', data); + } catch (e) { + console.log('Oh no an error:', e); + } +} + +sayHi(); +``` + +- A: `It worked! Hello world!` +- B: `Oh no an error: undefined` +- C: `SyntaxError: can only throw Error objects` +- D: `Oh no an error: Hello world!` + +
Răspuns +

+ +#### Răspuns: D + +Cu instrucțiunea `throw` putem crea erori personalizate. Cu această instrucțiune, puteți arunca excepții. O excepție poate fi un șir de caractere, un număr, un boolean sau un obiect. În acest caz, excepția noastră este șirul `'Hello world!'`. + +Cu instrucțiunea `catch` putem specifica ce să facem dacă o excepție este aruncată în blocul `try`. O excepție este aruncată: șirul `'Hello world!'`. `e` este acum egal cu acel șir, pe care îl înregistrăm. Acest lucru duce la rezultatul `'Oh an error: Hello world!'`. + +

+
+ +--- + +###### 53. Care este rezultatul? + +```javascript +function Car() { + this.make = 'Lamborghini'; + return { make: 'Maserati' }; +} + +const myCar = new Car(); +console.log(myCar.make); +``` + +- A: `"Lamborghini"` +- B: `"Maserati"` +- C: `ReferenceError` +- D: `TypeError` + +
Răspuns +

+ +#### Răspuns: B + +Atunci când o funcție constructor este apelată cu cuvântul cheie `new`, aceasta creează un obiect și stabilește cuvântul cheie `this` să se refere la acel obiect. În mod implicit, dacă funcția constructor nu returnează explicit nimic, va returna obiectul creat recent. + +În acest caz, funcția constructor `Car` returnează în mod explicit un obiect nou cu proprietatea `make` setată la `"Maserati"`, ceea ce suprascrie comportamentul implicit. Prin urmare, atunci când este apelat `new Car()` obiectul _returnat_ este atribuit lui `myCar`, ceea ce duce la rezultatul `"Maserati"` atunci când se accesează `myCar.make`. + +

+
+ +--- + +###### 54. Care este rezultatul? + +```javascript +(() => { + let x = (y = 10); +})(); + +console.log(typeof x); +console.log(typeof y); +``` + +- A: `"undefined", "number"` +- B: `"number", "number"` +- C: `"object", "number"` +- D: `"number", "undefined"` + +
Răspuns +

+ +#### Răspuns: A + +`let x = (y = 10);` este de fapt o prescurtare pentru + +```javascript +y = 10; +let x = y; +``` + +Când setăm `y` egal cu `10`, adăugăm de fapt o proprietate `y` la obiectul global (`window` într-un browser, `global` în Node). Într-un browser, `window.y` este acum egal cu `10`. + +Apoi, declarăm o variabilă `x` cu valoarea `y`, care este `10`. Variabilele declarate cu cuvântul cheie `let` au domeniu de bloc _block scoped_, ele sunt definite doar în blocul în care sunt declarate; în cazul de față, în funcția expresie invocată imediat (IIFE). Atunci când folosim operatorul `typeof` operandul `x` nu este definit: încercăm să accesăm `x` în afara blocului în care este declarat. Acest lucru înseamnă că `x` nu este definit. Valorile care nu au primit o valoare sau nu au fost declarate sunt de tip `"undefined"`. `console.log(typeof x)` returnează `"undefined"`. + +Cu toate acestea, am creat o variabilă globală `y` atunci când am setat `y` egal cu `10`. Această valoare este accesibilă oriunde în codul nostru. `y` este definită și deține o valoare de tip `"number"`. `console.log(typeof y)` returnează `"number"`. + +

+
+ +--- + +###### 55. Care este rezultatul? + +```javascript +class Dog { + constructor(name) { + this.name = name; + } +} + +Dog.prototype.bark = function() { + console.log(`Woof I am ${this.name}`); +}; + +const pet = new Dog('Mara'); + +pet.bark(); + +delete Dog.prototype.bark; + +pet.bark(); +``` + +- A: `"Woof I am Mara"`, `TypeError` +- B: `"Woof I am Mara"`, `"Woof I am Mara"` +- C: `"Woof I am Mara"`, `undefined` +- D: `TypeError`, `TypeError` + +
Răspuns +

+ +#### Răspuns: A + +Putem șterge proprietăți din obiecte folosind cuvântul cheie `delete` inclusiv de pe prototip. Prin ștergerea unei proprietăți de pe prototip, aceasta nu mai este disponibilă în lanțul prototipului. În acest caz, funcția `bark` nu mai este disponibilă pe prototip după `delete Dog.prototype.bark`, dar încercăm totuși să o accesăm. + +Când încercăm să apelăm ceva care nu este o funcție, este aruncată o excepție `TypeError`. În acest caz, se generează eroarea `TypeError: pet.bark is not a function`, deoarece `pet.bark` este `undefined`. + +

+
+ +--- + +###### 56. Care este rezultatul? + +```javascript +const set = new Set([1, 1, 2, 3, 4]); + +console.log(set); +``` + +- A: `[1, 1, 2, 3, 4]` +- B: `[1, 2, 3, 4]` +- C: `{1, 1, 2, 3, 4}` +- D: `{1, 2, 3, 4}` + +
Răspuns +

+ +#### Răspuns: D + +Obiectul `Set` este o colecție de valori unice: o valoare poate apărea doar o singură dată într-un set. + +m transmis iterable-ul `[1, 1, 2, 3, 4]` cu o valoare duplicată `1`. Deoarece nu putem avea două valori identice într-un set, una dintre ele este eliminată. Acest lucru duce la rezultatul `{1, 2, 3, 4}`. + +

+
+ +--- + +###### 57. Care este rezultatul? + +```javascript +// counter.js +let counter = 10; +export default counter; +``` + +```javascript +// index.js +import myCounter from './counter'; + +myCounter += 1; + +console.log(myCounter); +``` + +- A: `10` +- B: `11` +- C: `Error` +- D: `NaN` + +
Răspuns +

+ +#### Răspuns: C + +Un modul importat este _doar pentru citire_: nu puteți modifica modulul importat. Doar modulul care le exportă poate schimba valorile acestora. + +Când încercăm să incrementăm valoarea lui `myCounter`, apare o eroare: `myCounter` este doar pentru citire și nu poate fi modificat. + +

+
+ +--- + +###### 58. Care este rezultatul? + +```javascript +const name = 'Lydia'; +age = 21; + +console.log(delete name); +console.log(delete age); +``` + +- A: `false`, `true` +- B: `"Lydia"`, `21` +- C: `true`, `true` +- D: `undefined`, `undefined` + +
Răspuns +

+ +#### Răspuns: A + +Operatorul `delete` returnează o valoare booleană: `true` în cazul ștergerii reușite, în caz contrar va returna `false`. Cu toate acestea, variabilele declarate cu cuvintele cheie `var`, `const` sau `let` nu pot fi șterse folosind operatorul `delete`. + +Variabila `name` a fost declarată cu cuvântul cheie `const` așa că ștergerea sa nu reușește: se returnează `false`. Atunci când setăm `age` egal cu `21`, de fapt am adăugat o proprietate numită `age` la obiectul global. În acest fel, puteți șterge cu succes proprietăți din obiecte, inclusiv din obiectul global, așa că `delete age` returnează `true`. + +

+
+ +--- + +###### 59. Care este rezultatul? + +```javascript +const numbers = [1, 2, 3, 4, 5]; +const [y] = numbers; + +console.log(y); +``` + +- A: `[[1, 2, 3, 4, 5]]` +- B: `[1, 2, 3, 4, 5]` +- C: `1` +- D: `[1]` + +
Răspuns +

+ +#### Răspuns: C + +Putem dezasambla (unpack) valori din array-uri sau proprietăți din obiecte prin destructurare. De exemplu: + +```javascript +[a, b] = [1, 2]; +``` + + + +Valoarea lui `a` este acum `1`, iar valoarea lui `b` este acum `2`. Ceea ce am făcut în întrebare este: + +```javascript +[y] = [1, 2, 3, 4, 5]; +``` + + + +Acest lucru înseamnă că valoarea lui `y` este egală cu prima valoare din array, care este numărul `1`. Când înregistrăm în consolă `y`, se returnează `1`. + +

+
+ +--- + +###### 60. Care este rezultatul? + +```javascript +const user = { name: 'Lydia', age: 21 }; +const admin = { admin: true, ...user }; + +console.log(admin); +``` + +- A: `{ admin: true, user: { name: "Lydia", age: 21 } }` +- B: `{ admin: true, name: "Lydia", age: 21 }` +- C: `{ admin: true, user: ["Lydia", 21] }` +- D: `{ admin: true }` + +
Răspuns +

+ +#### Răspuns: B + +Este posibil să combinăm obiecte folosind operatorul de răspândire`...`. Acesta vă permite să creați copii ale perechilor cheie/valoare dintr-un obiect și să le adăugați la alt obiect. În acest caz, creăm copii ale obiectului `user` și le adăugăm la obiectul `admin`. Obiectul `admin` conține acum perechile cheie/valoare copiate, ceea ce duce la rezultatul `{ admin: true, name: "Lydia", age: 21 }`. + +

+
+ --- \ No newline at end of file From b99e7b2f2c0cec77aaccb975bd675873813424f4 Mon Sep 17 00:00:00 2001 From: alexb017 Date: Fri, 25 Aug 2023 15:08:24 +0300 Subject: [PATCH 175/193] fix: fixed typo from question 63 --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 30168af0..40c520c0 100644 --- a/README.md +++ b/README.md @@ -1988,7 +1988,7 @@ console.log(num2); The unary operator `++` _first returns_ the value of the operand, _then increments_ the value of the operand. The value of `num1` is `10`, since the `increaseNumber` function first returns the value of `num`, which is `10`, and only increments the value of `num` afterwards. -`num2` is `10`, since we passed `num1` to the `increasePassedNumber`. `number` is equal to `10`(the value of `num1`. Again, the unary operator `++` _first returns_ the value of the operand, _then increments_ the value of the operand. The value of `number` is `10`, so `num2` is equal to `10`. +`num2` is `10`, since we passed `num1` to the `increasePassedNumber`. `number` is equal to `10`(the value of `num1`). Again, the unary operator `++` _first returns_ the value of the operand, _then increments_ the value of the operand. The value of `number` is `10`, so `num2` is equal to `10`.

From 270616517ec283f8376ea7e79524f13223f5a04f Mon Sep 17 00:00:00 2001 From: Rahil Ghanchi <94079100+rahiljakir@users.noreply.github.com> Date: Mon, 28 Aug 2023 04:06:15 +0530 Subject: [PATCH 176/193] Update README.md made little correction in answer of 150. where property would be "[object Object]" not "object Object" --- README.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 97cde89e..7988c04a 100644 --- a/README.md +++ b/README.md @@ -4973,11 +4973,11 @@ console.log(animals[dog]) Object keys are converted to strings. -Since the value of `dog` is an object, `animals[dog]` actually means that we’re creating a new property called `"object Object"` equal to the new object. `animals["object Object"]` is now equal to `{ emoji: "🐶", name: "Mara"}`. +Since the value of `dog` is an object, `animals[dog]` actually means that we’re creating a new property called `"[object Object]"` equal to the new object. `animals["[object Object]"]` is now equal to `{ emoji: "🐶", name: "Mara"}`. -`cat` is also an object, which means that `animals[cat]` actually means that we’re overwriting the value of `animals["object Object"]` with the new cat properties. +`cat` is also an object, which means that `animals[cat]` actually means that we’re overwriting the value of `animals["[object Object]"]` with the new cat properties. -Logging `animals[dog]`, or actually `animals["object Object"]` since converting the `dog` object to a string results `"object Object"`, returns the `{ emoji: "🐈", name: "Sara" }`. +Logging `animals[dog]`, or actually `animals["[object Object]"]` since converting the `dog` object to a string results `"[object Object]"`, returns the `{ emoji: "🐈", name: "Sara" }`.

From 4ba6b35ab4c3fb3b4ddde4f76b5785dc5f85616e Mon Sep 17 00:00:00 2001 From: alexb017 Date: Tue, 29 Aug 2023 18:30:58 +0300 Subject: [PATCH 177/193] Added the questions from 61-155 --- ro-RO/README.ro.md | 3252 +++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 3251 insertions(+), 1 deletion(-) diff --git a/ro-RO/README.ro.md b/ro-RO/README.ro.md index 921da0d2..0907fa94 100644 --- a/ro-RO/README.ro.md +++ b/ro-RO/README.ro.md @@ -1895,4 +1895,3254 @@ Este posibil să combinăm obiecte folosind operatorul de răspândire`...`. Ace

---- \ No newline at end of file +--- + +###### 61. Care este rezultatul? + +```javascript +const person = { name: 'Lydia' }; + +Object.defineProperty(person, 'age', { value: 21 }); + +console.log(person); +console.log(Object.keys(person)); +``` + +- A: `{ name: "Lydia", age: 21 }`, `["name", "age"]` +- B: `{ name: "Lydia", age: 21 }`, `["name"]` +- C: `{ name: "Lydia"}`, `["name", "age"]` +- D: `{ name: "Lydia"}`, `["age"]` + +
Răspuns +

+ +#### Răspuns: B + +Cu metoda `defineProperty` putem adăuga noi proprietăți la un obiect sau să modificăm cele existente. Atunci când adăugăm o proprietate la un obiect folosind metoda `defineProperty` aceasta nu este, în mod implicit, _nu enumerabilă_. Metoda `Object.keys` returnează toate numele de proprietăți _enumerabile_ dintr-un obiect, în acest caz doar `"name"`. + +Proprietățile adăugate folosind metoda `defineProperty` sunt, în mod implicit, imutabile (nu pot fi schimbate). Puteți anula acest comportament folosind proprietățile `writable`, `configurable` și `enumerable` În acest fel, metoda `defineProperty` vă oferă un control mai mare asupra proprietăților pe care le adăugați la un obiect. + +

+
+ +--- + +###### 62. Care este rezultatul? + +```javascript +const settings = { + username: 'lydiahallie', + level: 19, + health: 90, +}; + +const data = JSON.stringify(settings, ['level', 'health']); +console.log(data); +``` + +- A: `"{"level":19, "health":90}"` +- B: `"{"username": "lydiahallie"}"` +- C: `"["level", "health"]"` +- D: `"{"username": "lydiahallie", "level":19, "health":90}"` + +
Răspuns +

+ +#### Răspuns: A + +Al doilea argument al funcției `JSON.stringify` este _replacer-ul_. Replacer-ul poate fi fie o funcție, fie un array, și vă permite să controlați ce și cum ar trebui să fie serializate (convertite în șir de caractere) valorile. + +Dacă replacer-ul este un _array_, în șirul JSON vor fi incluse doar numele de proprietăți care sunt prezente în array. În acest caz, doar proprietățile cu numele `"level"` și `"health"` sunt incluse, în timp ce `"username"` este exclus. Astfel, `data` devine egal cu `"{"level":19, "health":90}"`. + +Dacă replacer-ul este o _funcție_, această funcție este apelată pentru fiecare proprietate din obiectul pe care îl serializați. Valoarea returnată de această funcție va fi valoarea proprietății atunci când este adăugată în șirul JSON. Dacă valoarea este `undefined`, această proprietate este exclusă din șirul JSON. + +

+
+ +--- + +###### 63. Care este rezultatul? + +```javascript +let num = 10; + +const increaseNumber = () => num++; +const increasePassedNumber = number => number++; + +const num1 = increaseNumber(); +const num2 = increasePassedNumber(num1); + +console.log(num1); +console.log(num2); +``` + +- A: `10`, `10` +- B: `10`, `11` +- C: `11`, `11` +- D: `11`, `12` + +
Răspuns +

+ +#### Răspuns: A + +Operatorul unary `++` _returnează mai întâi_ valoarea operandului și _apoi incrementează_ valoarea operandului. Valoarea lui `num1` este `10`, deoarece funcția `increaseNumber` returnează mai întâi valoarea lui `num`, care este `10`, și numai apoi incrementează valoarea lui `num`. + +`num2` este `10`, deoarece am transmis `num1` către funcția `increasePassedNumber`. `number` ieste egal cu `10`(valoarea lui `num1`). Iarăși, operatorul unary `++` _returnează mai întâi_ valoarea operandului și _apoi incrementeazăs_ valoarea operandului. Valoarea lui `number` este `10`, așa că `num2` este egal cu `10`. + +

+
+ +--- + +###### 64. Care este rezultatul? + +```javascript +const value = { number: 10 }; + +const multiply = (x = { ...value }) => { + console.log((x.number *= 2)); +}; + +multiply(); +multiply(); +multiply(value); +multiply(value); +``` + +- A: `20`, `40`, `80`, `160` +- B: `20`, `40`, `20`, `40` +- C: `20`, `20`, `20`, `40` +- D: `NaN`, `NaN`, `20`, `40` + +
Răspuns +

+ +#### Răspuns: C + +În ES6, putem inițializa parametri cu o valoare implicită. Valoarea parametrului va fi valoarea implicită, dacă nu a fost furnizată nicio altă valoare funcției sau dacă valoarea parametrului este `"undefined"`. În acest caz, răspândim proprietățile obiectului `value` într-un obiect nou, astfel încât `x` are valoarea implicită `{ number: 10 }`. + +Argumentul implicit este evaluat la _momentul apelului_! De fiecare dată când apelăm funcția, se creează un obiect _nou_. Invocăm funcția `multiply` primele două ori fără a furniza o valoare: `x` are valoarea implicită `{ number: 10 }`. Apoi înregistrăm în consolă valoarea înmulțită a acelui număr, care este `20`. + +A treia oară când apelăm `multiply`, furnizăm un argument: obiectul numit `value`. Operatorul `*=` este, de fapt, o prescurtare pentru `x.number = x.number * 2`: modificăm valoarea lui`x.number`, și înregistrăm în consolă valoarea înmulțită, care este `20`. + +A patra oară, trecem din nou obiectul `value`. `x.number` a fost modificat anterior la `20`, deci `x.number *= 2` înregistrează `40`. + +

+
+ +--- + +###### 65. Care este rezultatul? + +```javascript +[1, 2, 3, 4].reduce((x, y) => console.log(x, y)); +``` + +- A: `1` `2` și `3` `3` și `6` `4` +- B: `1` `2` și `2` `3` și `3` `4` +- C: `1` `undefined` și `2` `undefined` și `3` `undefined` și `4` `undefined` +- D: `1` `2` și `undefined` `3` și `undefined` `4` + +
Răspuns +

+ +#### Răspuns: D + +Primul argument pe care îl primește metoda `reduce` este _acumulator-ul_, `x` în acest caz. Al doilea argument este _valoarea curentă_, `y`. Cu metoda `reduce`, executăm o funcție de apel pe fiecare element din array, ceea ce poate duce în cele din urmă la o singură valoare. + +În acest exemplu, nu returnăm nicio valoare, ci doar înregistrăm valorile accumulatorului și valorii curente. + +Valoarea accumulatorului este egală cu valoarea returnată anterior de funcția de apel. Dacă nu furnizați argumentul opțional `initialValue` metodei `reduce`, accumulatorul este egal cu primul element la prima apelare. + +La prima apelare, accumulatorul (`x`) este `1`, iar valoarea curentă (`y`) este `2`. Nu returnăm din funcția de apel, ci înregistrăm valorile accumulatorului și valoarea curentă: se înregistrează `1` și `2`. + +Dacă nu returnați o valoare dintr-o funcție, aceasta va returna `undefined`. OLa următoarea apelare, accumulatorul este `undefined`, iar valoarea curentă este `3`. Se înregistrează `undefined` și `3`. + +La a patra apelare, din nou nu returnăm din funcția de apel. Accumulatorul este din nou `undefined`, iar valoarea curentă este `4`. Se înregistrează `undefined` și `4`. + +

+
+ +--- + +###### 66. Cu ce constructor putem extinde cu succes clasa `Dog`? + +```javascript +class Dog { + constructor(name) { + this.name = name; + } +}; + +class Labrador extends Dog { + // 1 + constructor(name, size) { + this.size = size; + } + // 2 + constructor(name, size) { + super(name); + this.size = size; + } + // 3 + constructor(size) { + super(name); + this.size = size; + } + // 4 + constructor(name, size) { + this.name = name; + this.size = size; + } + +}; +``` + +- A: 1 +- B: 2 +- C: 3 +- D: 4 + +
Răspuns +

+ +#### Răspuns: B + +Într-o clasă derivată, nu puteți accesa cuvântul cheie `this` înainte de a apela `super`. Dacă încercați să faceți acest lucru, va arunca o ReferenceError: 1 și 4 ar arunca o eroare de referință. + +Cu cuvântul cheie `super`, apelăm constructorul clasei părinte cu argumentele date. Constructorul părintelui primește argumentul `name`, deci trebuie să transmitem `name` la `super`. + +Clasa `Labrador` primește doi argumente, `name` deoarece extinde clasa `Dog`, și `size` ca o proprietate suplimentară în clasa `Labrador`. Ambele trebuie să fie transmise funcției constructor din clasa `Labrador`, ceea ce se face corect utilizând constructorul 2. + +

+
+ +--- + +###### 67. Care este rezultatul? + +```javascript +// index.js +console.log('running index.js'); +import { sum } from './sum.js'; +console.log(sum(1, 2)); + +// sum.js +console.log('running sum.js'); +export const sum = (a, b) => a + b; +``` + +- A: `running index.js`, `running sum.js`, `3` +- B: `running sum.js`, `running index.js`, `3` +- C: `running sum.js`, `3`, `running index.js` +- D: `running index.js`, `undefined`, `running sum.js` + +
Răspuns +

+ +#### Răspuns: B + +Cu cuvântul cheie `import`, toate modulele importate sunt _preparate în prealabil_. Acest lucru înseamnă că modulele importate sunt executate _mai întâi_, codul din fișierul care importă modulul este executat _după accea_. + +Acesta este un diferență între `require()` în CommonJS și `import`! Cu `require()`, puteți încărca dependențele la cerere în timp ce codul este în curs de desfășurare. Dacă am fi folosit `require` în loc de `import`, ar fi fost înregistrate în consolă mesajele `running index.js`, `running sum.js`, `3`. + +

+
+ +--- + +###### 68. Care este rezultatul? + +```javascript +console.log(Number(2) === Number(2)); +console.log(Boolean(false) === Boolean(false)); +console.log(Symbol('foo') === Symbol('foo')); +``` + +- A: `true`, `true`, `false` +- B: `false`, `true`, `false` +- C: `true`, `false`, `true` +- D: `true`, `true`, `true` + +
Răspuns +

+ +#### Răspuns: A + +Fiecare Symbol este complet unic. Scopul argumentului furnizat către Symbol este de a oferi Symbolului o descriere. Valoarea Symbolului nu depinde de argumentul furnizat. În timp ce testăm egalitatea, creăm două simboluri complet noi: primul `Symbol('foo')`, și al doilea `Symbol('foo')`. Aceste două valori sunt unice și nu sunt egale între ele, `Symbol('foo') === Symbol('foo')` returnează `false`. + +

+
+ +--- + +###### 69. Care este rezultatul? + +```javascript +const name = 'Lydia Hallie'; +console.log(name.padStart(13)); +console.log(name.padStart(2)); +``` + +- A: `"Lydia Hallie"`, `"Lydia Hallie"` +- B: `" Lydia Hallie"`, `" Lydia Hallie"` (`"[13x whitespace]Lydia Hallie"`, `"[2x whitespace]Lydia Hallie"`) +- C: `" Lydia Hallie"`, `"Lydia Hallie"` (`"[1x whitespace]Lydia Hallie"`, `"Lydia Hallie"`) +- D: `"Lydia Hallie"`, `"Lyd"`, + +
Răspuns +

+ +#### Răspuns: C + +Cu metoda `padStart` putem adăuga umplutură la începutul unui șir. Valoarea transmisă acestei metode este lungimea _totală_ a șirului împreună cu umplutura. Șirul `"Lydia Hallie"` are o lungime de `12`. `name.padStart(13)` introduce 1 spațiu la începutul șirului, deoarece 12 + 1 este 13. + +Dacă argumentul transmis metodei `padStart` este mai mic decât lungimea șirului, nu va fi adăugată nicio umplutură. + +

+
+ +--- + +###### 70. Care este rezultatul? + +```javascript +console.log('🥑' + '💻'); +``` + +- A: `"🥑💻"` +- B: `257548` +- C: Un șir care conține punctele de cod ale caracterelor +- D: Eroare + +
Răspuns +

+ +#### Răspuns: A + +Cu operatorul `+`, puteți concatena șiruri. În acest caz, concatenăm șirul `"🥑"` cu șirul `"💻"`, rezultând `"🥑💻"`. + +

+
+ +--- + +###### 71. Cum putem înregistra valorile aflate în comentarii după instrucțiunea console.log? + +```javascript +function* startGame() { + const answer = yield 'Do you love JavaScript?'; + if (answer !== 'Yes') { + return "Oh wow... Guess we're done here"; + } + return 'JavaScript loves you back ❤️'; +} + +const game = startGame(); +console.log(/* 1 */); // Do you love JavaScript? +console.log(/* 2 */); // JavaScript loves you back ❤️ +``` + +- A: `game.next("Yes").value` și `game.next().value` +- B: `game.next.value("Yes")` și `game.next.value()` +- C: `game.next().value` și `game.next("Yes").value` +- D: `game.next.value()` și `game.next.value("Yes")` + +
Răspuns +

+ +#### Răspuns: C + +O funcție generator "pauzează" execuția când întâlnește cuvântul cheie `yield`. Mai întâi, trebuie să permitem funcției să emită șirul "Do you love JavaScript?", ceea ce poate fi făcut apelând `game.next().value`. + +Fiecare linie este executată până când găsește primul cuvânt cheie `yield`. Există un cuvânt cheie `yield` pe prima linie din funcție: execuția se oprește cu primul `yield`. _Acest lucru înseamnă că variabila `answer` nu este definită încă!_ + +Când apelăm `game.next("Yes").value`, cuvântul cheie `yield` anterior este înlocuit cu valoarea parametrilor transmiși funcției `next()`, `"Yes"` în acest caz. Valoarea variabilei `answer` este acum egală cu `"Yes"`. Condiția declarației if returnează `false`, și `JavaScript loves you back ❤️` este înregistrat în consolă. + +

+
+ +--- + +###### 72. Care este rezultatul? + +```javascript +console.log(String.raw`Hello\nworld`); +``` + +- A: `Hello world!` +- B: `Hello`
     `world` +- C: `Hello\nworld` +- D: `Hello\n`
     `world` + +
Răspuns +

+ +#### Răspuns: C + +`String.raw` returnează un șir în care escape-urile (`\n`, `\v`, `\t` etc.) sunt ignorate! Backslash-urile pot fi o problemă, deoarece puteți ajunge cu ceva similar cu: + +`` const path = `C:\Documents\Projects\table.html` `` + +Acest lucru ar rezulta în: + +`"C:DocumentsProjects able.html"` + +Cu `String.raw`, acesta ar ignora pur și simplu escape-ul și ar afișa: + +`C:\Documents\Projects\table.html` + +În acest caz, șirul este `Hello\nworld`, care este înregistrat în consolă. + +

+
+ +--- + +###### 73. Care este rezultatul? + +```javascript +async function getData() { + return await Promise.resolve('I made it!'); +} + +const data = getData(); +console.log(data); +``` + +- A: `"I made it!"` +- B: `Promise {: "I made it!"}` +- C: `Promise {}` +- D: `undefined` + +
Răspuns +

+ +#### Răspuns: C + +O funcție `async` întotdeauna returnează o promisiune. Instrucțiunea `await` încă trebuie să aștepte ca promisiunea să se rezolve: o promisiune în așteptare este returnată atunci când apelăm `getData()` pentru a o atribui variabilei `data`. + +Dacă dorim să avem acces la valoarea rezolvată `"I made it"`, am putea folosi metoda `.then()` pe `data`: + +`data.then(res => console.log(res))` + +Acest lucru ar fi înregistrat `"I made it!"` + +

+
+ +--- + +###### 74. Care este rezultatul? + +```javascript +function addToList(item, list) { + return list.push(item); +} + +const result = addToList('apple', ['banana']); +console.log(result); +``` + +- A: `['apple', 'banana']` +- B: `2` +- C: `true` +- D: `undefined` + +
Răspuns +

+ +#### Răspuns: B + +Metoda`.push()` returnează _lungimea_ noului șir! Înainte, șirul conținea un element (șirul `"banana"`) și avea o lungime de `1`. După adăugarea șirului `"apple"` în șir, șirul conține două elemente și are o lungime de `2`. Aceasta este valoarea returnată de funcția `addToList`. + +Metoda `push` modifică șirul original. Dacă doreați să returnați _șirul_ din funcție în loc de _lungimea șirului_, ar fi trebuit să returnați `list` după ce ați adăugat `item` la el. + +

+
+ +--- + +###### 75. Care este rezultatul? + +```javascript +const box = { x: 10, y: 20 }; + +Object.freeze(box); + +const shape = box; +shape.x = 100; + +console.log(shape); +``` + +- A: `{ x: 100, y: 20 }` +- B: `{ x: 10, y: 20 }` +- C: `{ x: 100 }` +- D: `ReferenceError` + +
Răspuns +

+ +#### Răspuns: B + +`Object.freeze` face imposibilă adăugarea, eliminarea sau modificarea proprietăților unui obiect (cu excepția cazului în care valoarea proprietății este un alt obiect). + +Când creăm variabila `shape` și o setăm egală cu obiectul înghețat `box`, `shape` de asemenea se referă la un obiect înghețat. Puteți verifica dacă un obiect este înghețat folosind `Object.isFrozen`. În acest caz, `Object.isFrozen(shape)` ar returna true, deoarece variabila `shape` are o referință către un obiect înghețat. + +Deoarece `shape` este înghețat și deoarece valoarea lui`x` nu este un obiect, nu putem modifica proprietatea `x`. `x` rămâne egal cu `10`, și `{ x: 10, y: 20 }` este afișat în consolă. + +

+
+ +--- + +###### 76. Care este rezultatul? + +```javascript +const { firstName: myName } = { firstName: 'Lydia' }; + +console.log(firstName); +``` + +- A: `"Lydia"` +- B: `"myName"` +- C: `undefined` +- D: `ReferenceError` + +
Răspuns +

+ +#### Răspuns: D + +Folosind [destructuring assignment](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment) cu sintaxa de mai jos putem extrage valori din array-uri sau proprietăți din obiecte în variabile distincte: + +```javascript +const { firstName } = { firstName: 'Lydia' }; +// ES5 version: +// var firstName = { firstName: 'Lydia' }.firstName; + +console.log(firstName); // "Lydia" +``` + +De asemenea, o proprietate poate fi extras dintr-un obiect și atribuită unei variabile cu un nume diferit decât proprietatea obiectului: + +```javascript +const { firstName: myName } = { firstName: 'Lydia' }; +// ES5 version: +// var myName = { firstName: 'Lydia' }.firstName; + +console.log(myName); // "Lydia" +console.log(firstName); // Uncaught ReferenceError: firstName is not defined +``` + +Prin urmare, `firstName` nu există ca variabilă, astfel încât încercarea de a accesa valoarea sa va genera o eroare `ReferenceError`. + +**Notă:** Fiți conștienți de proprietățile în `global scope` (spațiul global): + +```javascript +const { name: myName } = { name: 'Lydia' }; + +console.log(myName); // "lydia" +console.log(name); // "" ----- Browser e.g. Chrome +console.log(name); // ReferenceError: name is not defined ----- NodeJS + +``` + +În cazul în care JavaScript nu poate găsi o variabilă în _cadrul curent_, acesta urcă pe [Scope chain](https://github.com/getify/You-Dont-Know-JS/blob/2nd-ed/scope-closures/ch3.md) și o caută. Dacă ajunge la nivelul superior al cadrului, adică la **spațiul global**, și tot nu o găsește, va arunca o excepție `ReferenceError`. + +- În **Browser-e** cum ar fi _Chrome_, `name` este o _proprietate de spațiu global depășită_. În acest exemplu, codul rulează în _spațiul global_ și nu există o variabilă locală definită de utilizator pentru `name`, așa că caută _variabilele/proprietățile_ predefinite în spațiul global, care în cazul browser-elor înseamnă că caută în obiectul `window` de unde extrage valoarea [window.name](https://developer.mozilla.org/en-US/docs/Web/API/Window/name) care este egală cu un **șir gol**. + +- În **NodeJS**, nu există o astfel de proprietate pe obiectul `global` așadar încercarea de a accesa o variabilă inexistentă va genera o [ReferenceError](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/Not_defined). + +

+
+ +--- + +###### 77. Este aceasta o funcție pură? + +```javascript +function sum(a, b) { + return a + b; +} +``` + +- A: Da +- B: Nu + +
Răspuns +

+ +#### Răspuns: A + +O funcție pură este o funcție care _întotdeauna_ returnează același rezultat, dacă aceleași argumente sunt furnizate. + +Funcția `sum` întotdeauna returnează același rezultat. Dacă îi furnizăm `1` și `2`, va returna _întotdeauna_ `3` fără efecte secundare. Dacă îi furnizăm `5` și `10`, va returna _întotdeauna_ `15`, și tot așa. Aceasta este definiția unei funcții pure. + +

+
+ +--- + +###### 78. Care este rezultatul? + +```javascript +const add = () => { + const cache = {}; + return num => { + if (num in cache) { + return `From cache! ${cache[num]}`; + } else { + const result = num + 10; + cache[num] = result; + return `Calculated! ${result}`; + } + }; +}; + +const addFunction = add(); +console.log(addFunction(10)); +console.log(addFunction(10)); +console.log(addFunction(5 * 2)); +``` + +- A: `Calculated! 20` `Calculated! 20` `Calculated! 20` +- B: `Calculated! 20` `From cache! 20` `Calculated! 20` +- C: `Calculated! 20` `From cache! 20` `From cache! 20` +- D: `Calculated! 20` `From cache! 20` `Error` + +
Răspuns +

+ +#### Răspuns: C + +Funcția `add` este o funcție _memoizată_. Cu ajutorul memoizării, putem să memorăm rezultatele unei funcții pentru a accelera execuția ulterioară. În acest caz, creăm un obiect `cache` care stochează valorile returnate anterior. + +Dacă apelăm din nou funcția `addFunction` cu același argument, funcția verifică mai întâi dacă a primit deja acea valoare în memoria sa cache. Dacă acest lucru este adevărat, se va returna valoarea din cache, economisind timp de execuție. Dacă nu este în cache, funcția va calcula valoarea și o va memora ulterior. + +Apelăm funcția `addFunction` de trei ori cu aceeași valoare: în prima invocare, valoarea funcției când `num` este egal cu `10` nu este încă în cache. Condiția instrucțiunii `num in cache` returnează `false`, iar blocul `else` este executat: se afișează `Calculated! 20` iar valoarea rezultatului este adăugată în obiectul de cache. Acum, `cache` arată astfel `{ 10: 20 }`. + +A doua oară, obiectul `cache` conține valoarea care este returnată pentru `10`. Condiția instrucțiunii `num in cache` returnează `true`, și se afișează `'From cache! 20'`. + +A treia oară, trecem `5 * 2` funcției, care este evaluat la `10`. Obiectul `cache` conține valoarea care este returnată pentru `10`. Condiția instrucțiunii `num in cache` returnează `true`, și se afișează `'From cache! 20'`. + +

+
+ +--- + +###### 79. Care este rezultatul? + +```javascript +const myLifeSummedUp = ['☕', '💻', '🍷', '🍫']; + +for (let item in myLifeSummedUp) { + console.log(item); +} + +for (let item of myLifeSummedUp) { + console.log(item); +} +``` + +- A: `0` `1` `2` `3` și `"☕"` `"💻"` `"🍷"` `"🍫"` +- B: `"☕"` `"💻"` `"🍷"` `"🍫"` și `"☕"` `"💻"` `"🍷"` `"🍫"` +- C: `"☕"` `"💻"` `"🍷"` `"🍫"` și `0` `1` `2` `3` +- D: `0` `1` `2` `3` și `{0: "☕", 1: "💻", 2: "🍷", 3: "🍫"}` + +
Răspuns +

+ +#### Răspuns: A + +Cu o buclă _for-in_, putem itera peste proprietățile **enumerabile**. Într-un șir, proprietățile enumerate sunt "cheile" elementelor din șir, care sunt de fapt indexurile lor. Puteți vedea un șir ca: + +`{0: "☕", 1: "💻", 2: "🍷", 3: "🍫"}` + +Unde cheile sunt proprietățile enumerate. `0` `1` `2` `3` sunt afișate. + +Cu o buclă _for-of_, putem itera peste obiecte **iterabile**. Un șir este un obiect iterabil. Când iterăm peste șir, variabila "item" este egală cu elementul pe care îl parcurge în acel moment, sunt afișate `"☕"` `"💻"` `"🍷"` `"🍫"`. + +

+
+ +--- + +###### 80. Care este rezultatul? + +```javascript +const list = [1 + 2, 1 * 2, 1 / 2]; +console.log(list); +``` + +- A: `["1 + 2", "1 * 2", "1 / 2"]` +- B: `["12", 2, 0.5]` +- C: `[3, 2, 0.5]` +- D: `[1, 1, 1]` + +
Răspuns +

+ +#### Răspuns: C + +Elementele dintr-un șir pot stoca orice valoare. Numere, șiruri, obiecte, alte șiruri, null, valori booleane, undefined și alte expresii precum date, funcții și calculații. + +Elementul va fi egal cu valoarea returnată. `1 + 2` returnează `3`, `1 * 2` returnează `2`, și `1 / 2` returnează `0.5`. + +

+
+ +--- + +###### 81. Care este rezultatul? + +```javascript +function sayHi(name) { + return `Hi there, ${name}`; +} + +console.log(sayHi()); +``` + +- A: `Hi there,` +- B: `Hi there, undefined` +- C: `Hi there, null` +- D: `ReferenceError` + +
Răspuns +

+ +#### Răspuns: B + +În mod implicit, argumentele au valoarea `undefined`, cu excepția cazului în care s-a transmis o valoare funcției. În acest caz, nu am transmis o valoare pentru argumentul `name`. `name` este egal cu `undefined` iar acesta este afișat. + +În ES6, putem suprascrie această valoare implicită `undefined` cu parametri impliciti. De exemplu: + +`function sayHi(name = "Lydia") { ... }` + +În acest caz, dacă nu am fi furnizat o valoare sau am fi furnizat `undefined`, `name` ar fi fost întotdeauna egal cu șirul `Lydia`. + +

+
+ +--- + +###### 82. Care este rezultatul? + +```javascript +var status = '😎'; + +setTimeout(() => { + const status = '😍'; + + const data = { + status: '🥑', + getStatus() { + return this.status; + }, + }; + + console.log(data.getStatus()); + console.log(data.getStatus.call(this)); +}, 0); +``` + +- A: `"🥑"` și `"😍"` +- B: `"🥑"` și `"😎"` +- C: `"😍"` și `"😎"` +- D: `"😎"` și `"😎"` + +
Răspuns +

+ +#### Răspuns: B + +Valoarea cuvântului cheie `this` depinde de locul în care este utilizat. Într-o **metodă**, cum ar fi metoda `getStatus`, cuvântul cheie `this` se referă la _obiectul la care aparține metoda_. Metoda aparține obiectului `data`, deci `this` se referă la obiectul `data`. Când înregistrăm `this.status`, se înregistrează proprietatea `status` de pe obiectul `data` care este `"🥑"`. + +Cu metoda `call` putem schimba obiectul la care se referă cuvântul cheie `this`. În **funcții**, cuvântul cheie `this` se referă la _obiectul la care aparține funcția_. Am declarat funcția `setTimeout` pe _obiectul global_, deci în interiorul funcției `setTimeout`, cuvântul cheie `this` se referă la _obiectul global_. Pe obiectul global există o variabilă numită status cu valoarea `"😎"`. Când înregistrați `this.status`, se înregistrează `"😎"`. + +

+
+ +--- + +###### 83. Care este rezultatul? + +```javascript +const person = { + name: 'Lydia', + age: 21, +}; + +let city = person.city; +city = 'Amsterdam'; + +console.log(person); +``` + +- A: `{ name: "Lydia", age: 21 }` +- B: `{ name: "Lydia", age: 21, city: "Amsterdam" }` +- C: `{ name: "Lydia", age: 21, city: undefined }` +- D: `"Amsterdam"` + +
Răspuns +

+ +#### Răspuns: A + +Am setat variabila `city` egală cu valoarea proprietății numită `city` pe obiectul `person`. Nu există o proprietate pe acest obiect numită `city`, astfel că variabila `city` are valoarea `undefined`. + +Rețineți că nu facem referire la obiectul `person` în sine! Pur și simplu am setat variabila `city` egală cu valoarea curentă a proprietății `city` de pe obiectul `person`. + +Apoi, am setat `city` egal cu șirul de caractere `"Amsterdam"`. Acest lucru nu schimbă obiectul `person` nu există o referință la acel obiect. + +Atunci când se afișează obiectul `person` se va afișa obiectul original, nealterat. + +

+
+ +--- + +###### 84. Care este rezultatul? + +```javascript +function checkAge(age) { + if (age < 18) { + const message = "Sorry, you're too young."; + } else { + const message = "Yay! You're old enough!"; + } + + return message; +} + +console.log(checkAge(21)); +``` + +- A: `"Sorry, you're too young."` +- B: `"Yay! You're old enough!"` +- C: `ReferenceError` +- D: `undefined` + +
Răspuns +

+ +#### Răspuns: C + +Variabilele declarate cu cuvintele cheie `const` și `let` au _domeniu de vizibilitate la nivel de bloc_. Un bloc poate fi definit între parantezele acolade (`{ }`). În acest caz, parantezele acolade ale instrucțiunilor if/else. Nu puteți face referire la o variabilă în afara blocului în care a fost declarată, va fi generată o eroare de tip ReferenceError. + +

+
+ +--- + +###### 85. Ce tip de informații ar fi înregistrate? + +```javascript +fetch('https://www.website.com/api/user/1') + .then(res => res.json()) + .then(res => console.log(res)); +``` + +- A: Rezultatul metodei `fetch`. +- B: Rezultatul celei de-a doua apelări a metodei `fetch`. +- C: Rezultatul funcției de retur (callback) din `.then()`-ul anterior. +- D: Ar fi întotdeauna `undefined`. + +
Răspuns +

+ +#### Răspuns: C + +Valoarea lui `res` în al doilea `.then` este egală cu valoarea returnată de `.then` anterior. Puteți continua să înșirați `.then`-uri în acest fel, unde valoarea este pasată către următorul manipulator. + +

+
+ +--- + +###### 86. Care opțiune este o modalitate de a seta `hasName` egala cu `true`, cu condiția să nu puteți furniza `true` ca argument? + +```javascript +function getName(name) { + const hasName = // +} +``` + +- A: `!!name` +- B: `name` +- C: `new Boolean(name)` +- D: `name.length` + +
Răspuns +

+ +#### Răspuns: A + +Cu `!!name`, determinăm dacă valoarea lu `name` este adevărată sau falsă. Dacă `name` este adevărat, ceea ce dorim să testăm, `!name` returnează `false`. `!false` (practic, ceea ce este `!!name`) returnează `true`. + +Prin setarea lui `hasName` egal cu `name`, se face ca `hasName` să fie egal cu valoarea pe care ați furnizat-o funcției `getName`, nu cu valoarea booleană `true`. + +`new Boolean(true)` returnează un obiect încapsulator, nu valoarea booleană în sine. + +`name.length` returnează lungimea argumentului furnizat, nu dacă acesta este `true`. + +

+
+ +--- + +###### 87. Care este rezultatul? + +```javascript +console.log('I want pizza'[0]); +``` + +- A: `"""` +- B: `"I"` +- C: `SyntaxError` +- D: `undefined` + +
Răspuns +

+ +#### Răspuns: B + +Pentru a obține un caracter la un anumit index dintr-un șir de caractere, puteți utiliza notația cu paranteze pătrate. Primul caracter din șir are indexul 0, și așa mai departe. În acest caz, dorim să obținem elementul cu indexul 0, adică caracterul `"I'`, care va fi afișat în jurnal. + +Rețineți că această metodă nu este suportată în IE7 și versiunile anterioare. În acest caz, utilizați `.charAt()`. + +

+
+ +--- + +###### 88. Care este rezultatul? + +```javascript +function sum(num1, num2 = num1) { + console.log(num1 + num2); +} + +sum(10); +``` + +- A: `NaN` +- B: `20` +- C: `ReferenceError` +- D: `undefined` + +
Răspuns +

+ +#### Răspuns: B + +Puteți seta valoarea implicită a unui parametru la valoarea altui parametru al funcției, atâta timp cât acestea sunt definite _înainte_ de parametrul cu valoarea implicită. Am transmis valoarea `10` funcției `sum`. Dacă funcția `sum` primește doar un argument, înseamnă că valoarea pentru `num2` nu este transmisă, iar valoarea lui `num1` este egală cu valoarea transmisă `10` în acest caz. Valoarea implicită a lui `num2` este valoarea lui `num1`, care este `10`. `num1 + num2` returnează `20`. + +Dacă încercați să setați valoarea implicită a unui parametru egală cu un parametru care este definit _după_ (în dreapta), valoarea parametrului nu a fost încă inițializată, ceea ce va genera o eroare. + +

+
+ +--- + +###### 89. Care este rezultatul? + +```javascript +// module.js +export default () => 'Hello world'; +export const name = 'Lydia'; + +// index.js +import * as data from './module'; + +console.log(data); +``` + +- A: `{ default: function default(), name: "Lydia" }` +- B: `{ default: function default() }` +- C: `{ default: "Hello world", name: "Lydia" }` +- D: Obiectul global al `module.js` + +
Răspuns +

+ +#### Răspuns: A + +Cu sintaxa `import * as name`, importăm _toate exporturile_ din fișierul `module.js` în fișierul `index.js` sub forma unui nou obiect numit `data`. În fișierul `module.js` există două exporturi: exportul implicit și un export cu nume. Exportul implicit este o funcție care returnează șirul de caractere `"Hello World"`, iar exportul cu nume este o variabilă numită `name` care are valoarea șirului de caractere `"Lydia"`. + +Obiectul `data` are o proprietate `default` pentru exportul implicit, iar celelalte proprietăți au numele exporturilor cu nume și valorile lor corespunzătoare. + +

+
+ +--- + +###### 90. Care este rezultatul? + +```javascript +class Person { + constructor(name) { + this.name = name; + } +} + +const member = new Person('John'); +console.log(typeof member); +``` + +- A: `"class"` +- B: `"function"` +- C: `"object"` +- D: `"string"` + +
Răspuns +

+ +#### Răspuns: C + +Clasele sunt o sintaxă mai simplă pentru constructorii de funcții. Echivalentul clasei `Person` sub forma unui constructor de funcții ar fi: + +```javascript +function Person(name) { + this.name = name; +} +``` + +Apelarea unui constructor de funcții cu `new` duce la crearea unei instanțe a obiectului `Person`, iar cuvântul cheie `typeof` returnează `"object"` pentru o astfel de instanță. `typeof member` returnează `"object"`. + +

+
+ +--- + +###### 91. Care este rezultatul? + +```javascript +let newList = [1, 2, 3].push(4); + +console.log(newList.push(5)); +``` + +- A: `[1, 2, 3, 4, 5]` +- B: `[1, 2, 3, 5]` +- C: `[1, 2, 3, 4]` +- D: `Error` + +
Răspuns +

+ +#### Răspuns: D + +Metoda `.push` returnează _lungimea nouă_ a array-ului, nu array-ul însuși! Prin setarea `newList` egal cu `[1, 2, 3].push(4)`, am setat `newList` egal cu noua lungime a array-ului: `4`. + +Apoi, încercăm să folosim metoda `.push` pe `newList`. Deoarece `newList` este o valoare numerică `4`, nu putem folosi metoda `.push` se va genera o eroare de tip TypeError. + +

+
+ +--- + +###### 92. Care este rezultatul? + +```javascript +function giveLydiaPizza() { + return 'Here is pizza!'; +} + +const giveLydiaChocolate = () => + "Here's chocolate... now go hit the gym already."; + +console.log(giveLydiaPizza.prototype); +console.log(giveLydiaChocolate.prototype); +``` + +- A: `{ constructor: ...}` `{ constructor: ...}` +- B: `{}` `{ constructor: ...}` +- C: `{ constructor: ...}` `{}` +- D: `{ constructor: ...}` `undefined` + +
Răspuns +

+ +#### Răspuns: D + +Funcțiile obișnuite, cum ar fi funcția `giveLydiaPizza` au o proprietate `prototype` care este un obiect (obiectul prototip) cu o proprietate `constructor`. Cu toate acestea, funcțiile arrow, cum ar fi funcția `giveLydiaChocolate`, nu au această proprietate `prototype`. `undefined` este returnat atunci când încearca să acceseze proprietatea `prototype` folosind `giveLydiaChocolate.prototype`. + +

+
+ +--- + +###### 93. Care este rezultatul? + +```javascript +const person = { + name: 'Lydia', + age: 21, +}; + +for (const [x, y] of Object.entries(person)) { + console.log(x, y); +} +``` + +- A: `name` `Lydia` și `age` `21` +- B: `["name", "Lydia"]` și `["age", 21]` +- C: `["name", "age"]` și `undefined` +- D: `Error` + +
Răspuns +

+ +#### Răspuns: A + +`Object.entries(person)` returnează un array de array-uri imbricate, care conțin cheile și obiectele: + +`[ [ 'name', 'Lydia' ], [ 'age', 21 ] ]` + +Folosind bucla `for-of` putem itera prin fiecare element din array, în acest caz, subarray-urile. Putem dezasambla subarray-urile instantaneu în bucla `for-of`, folosind `const [x, y]`. Astfel, `x` este egal cu primul element din subarray, iar `y` este egal cu al doilea element din subarray. + +Primul subarray este `[ "name", "Lydia" ]`, cu `x` egal cu `"name"`, și `y` egal cu `"Lydia"`, care sunt afișate în jurnal. +Al doilea subarray este `[ "age", 21 ]`, cu `x` egal cu `"age"`, și `y` egal cu `21`, care sunt afișate în jurnal. + +

+
+ +--- + +###### 94. Care este rezultatul? + +```javascript +function getItems(fruitList, ...args, favoriteFruit) { + return [...fruitList, ...args, favoriteFruit] +} + +getItems(["banana", "apple"], "pear", "orange") +``` + +- A: `["banana", "apple", "pear", "orange"]` +- B: `[["banana", "apple"], "pear", "orange"]` +- C: `["banana", "apple", ["pear"], "orange"]` +- D: `SyntaxError` + +
Răspuns +

+ +#### Răspuns: D + +`...args` este un parametru rest. Valoarea parametrului rest este un array care conține toate argumentele rămase și **poate fi doar ultimul parametru**! În acest exemplu, parametrul rest era al doilea parametru. Acest lucru nu este posibil și va genera o eroare de sintaxă. + +```javascript +function getItems(fruitList, favoriteFruit, ...args) { + return [...fruitList, ...args, favoriteFruit]; +} + +getItems(['banana', 'apple'], 'pear', 'orange'); +``` + +Exemplul de mai sus funcționează. Acesta returnează array-ul `[ 'banana', 'apple', 'orange', 'pear' ]` + +

+
+ +--- + +###### 95. Care este rezultatul? + +```javascript +function nums(a, b) { + if (a > b) console.log('a is bigger'); + else console.log('b is bigger'); + return + a + b; +} + +console.log(nums(4, 2)); +console.log(nums(1, 2)); +``` + +- A: `a is bigger`, `6` și `b is bigger`, `3` +- B: `a is bigger`, `undefined` și `b is bigger`, `undefined` +- C: `undefined` și `undefined` +- D: `SyntaxError` + +
Răspuns +

+ +#### Răspuns: B + +În JavaScript, nu _trebuie_ să scriem explicit semnul punct și virgulă (`;`) totuși motorul JavaScript le adaugă automat după instrucțiuni. Acest lucru se numește **Inserția Automată a Semnelor de Punct și Virgulă**. O instrucțiune poate fi, de exemplu, variabile sau cuvinte cheie precum `throw`, `return`, `break`, etc. + +Aici, am scris o instrucțiune `return` și o altă valoare `a + b` pe o _linie nouă_. Cu toate acestea, deoarece este o linie nouă, motorul JavaScript nu știe că este de fapt valoarea pe care am dorit să o returnăm. În schimb, a adăugat automat un punct și virgulă după `return`. Puteți vedea acest lucru ca: + +```javascript +return; +a + b; +``` + +Acest lucru înseamnă că `a + b` nu este niciodată atins, deoarece o funcție se oprește din executare după cuvântul cheie `return`. Dacă nu se returnează nicio valoare, așa cum se întâmplă aici, funcția returnează `undefined`. Rețineți că nu există inserție automată a semnelor de punct și virgulă după instrucțiunile `if/else`! + +

+
+ +--- + +###### 96. Care este rezultatul? + +```javascript +class Person { + constructor() { + this.name = 'Lydia'; + } +} + +Person = class AnotherPerson { + constructor() { + this.name = 'Sarah'; + } +}; + +const member = new Person(); +console.log(member.name); +``` + +- A: `"Lydia"` +- B: `"Sarah"` +- C: `Error: cannot redeclare Person` +- D: `SyntaxError` + +
Răspuns +

+ +#### Răspuns: B + +Putem seta clasele egale cu alte clase sau constructori de funcții. În acest caz, am setat `Person` egal cu `AnotherPerson`. Numele în acest constructor este `Sarah`, astfel încât proprietatea `Person` de pe noua instanță `member` este `"Sarah"`. + +

+
+ +--- + +###### 97. Care este rezultatul? + +```javascript +const info = { + [Symbol('a')]: 'b', +}; + +console.log(info); +console.log(Object.keys(info)); +``` + +- A: `{Symbol('a'): 'b'}` și `["{Symbol('a')"]` +- B: `{}` și `[]` +- C: `{ a: "b" }` și `["a"]` +- D: `{Symbol('a'): 'b'}` și `[]` + +
Răspuns +

+ +#### Răspuns: D + +Un simbol nu este _enumerabil_. Metoda `Object.keys` returnează toate proprietățile cheie _enumerabil_ ale unui obiect. Simbolul nu va fi vizibil, și va fi returnat un array gol. Atunci când se afișează întregul obiect, vor fi vizibile toate proprietățile, inclusiv cele care nu sunt enumerate. + +Asta este una dintre multele calități ale unui simbol: pe lângă faptul că reprezintă o valoare complet unică (ceea ce previne coliziunile accidentale de nume pe obiecte, de exemplu, atunci când lucrați cu două biblioteci care doresc să adauge proprietăți la același obiect), puteți "ascunde" proprietăți pe obiecte în acest fel (deși nu în întregime. Încă puteți accesa simbolurile folosind metoda `Object.getOwnPropertySymbols()`). + +

+
+ +--- + +###### 98. Care este rezultatul? + +```javascript +const getList = ([x, ...y]) => [x, y] +const getUser = user => { name: user.name, age: user.age } + +const list = [1, 2, 3, 4] +const user = { name: "Lydia", age: 21 } + +console.log(getList(list)) +console.log(getUser(user)) +``` + +- A: `[1, [2, 3, 4]]` și `SyntaxError` +- B: `[1, [2, 3, 4]]` și `{ name: "Lydia", age: 21 }` +- C: `[1, 2, 3, 4]` și `{ name: "Lydia", age: 21 }` +- D: `Error` și `{ name: "Lydia", age: 21 }` + +
Răspuns +

+ +#### Răspuns: A + +Funcția `getList` primește un array ca argument. Între parantezele funcției `getList` dezasamblăm acest array imediat. Puteți vedea acest lucru ca: + +`[x, ...y] = [1, 2, 3, 4]` + +Cu ajutorul parametrului rest `...y`, punem toți "parametrii rămași" într-un array. Parametrii rămași în acest caz sunt `2`, `3` și `4`. Valoarea lui `y` este un array care conține toți parametrii rămași. Valoarea lui `x` este egal cu `1` în acest caz, deci când afișăm `[x, y]`, va fi afișat `[1, [2, 3, 4]]`. + +Funcția `getUser` primește un obiect ca argument. Cu funcțiile arrow, nu _trebuie_ să scriem acolade dacă dorim să returnăm doar o valoare. Cu toate acestea, dacă doriți să returnați instantaneu un _obiect_ dintr-o funcție arrow, trebuie să-l scrieți între paranteze. Altfel, tot ce este între acolade va fi interpretat ca o instrucțiune bloc. În acest caz, codul dintre acolade nu este un cod JavaScript valid, așa că se va genera o eroare de sintaxă `SyntaxError`. + +Funcția următoare ar fi returnat un obiect: + +`const getUser = user => ({ name: user.name, age: user.age })` + +

+
+ +--- + +###### 99. Care este rezultatul? + +```javascript +const name = 'Lydia'; + +console.log(name()); +``` + +- A: `SyntaxError` +- B: `ReferenceError` +- C: `TypeError` +- D: `undefined` + +
Răspuns +

+ +#### Răspuns: C + +Variabila `name` conține o valoare de tip șir de caractere (string), care nu este o funcție și, prin urmare, nu poate fi invocată. + +TypeError-urile sunt generate atunci când o valoare nu este de tipul așteptat. JavaScript e aștepta ca `name` să fie o funcție, deoarece încercăm să o apelăm. Cu toate acestea, era de tip șir de caractere (string), așa că a generat o eroare de tip TypeError: name nu este o funcție! + +SyntaxError-urile sunt generate atunci când ați scris ceva care nu este JavaScript valid, de exemplu, atunci când ați scris cuvântul `return` ca `retrun`. +ReferenceError-urile sunt generate atunci când JavaScript nu poate găsi o referință la o valoare la care încercați să accesați. + +

+
+ +--- + +###### 100. Care este valoarea lui output? + +```javascript +// 🎉✨ Aceasta este a 100-a mea întrebare! ✨🎉 + +const output = `${[] && 'Im'}possible! +You should${'' && `n't`} see a therapist after so much JavaScript lol`; +``` + +- A: `possible! You should see a therapist after so much JavaScript lol` +- B: `Impossible! You should see a therapist after so much JavaScript lol` +- C: `possible! You shouldn't see a therapist after so much JavaScript lol` +- D: `Impossible! You shouldn't see a therapist after so much JavaScript lol` + +
Răspuns +

+ +#### Răspuns: B + +`[]` este o valoare adevărată (truthy). Cu operatorul `&&` valoarea din partea dreaptă va fi returnată dacă valoarea din partea stângă este adevărată. În acest caz, valoarea din partea stângă, `[]` este adevărată, astfel că se va returna `"Im'`. + +`""` este o valoare falsă (falsy). Dacă valoarea din partea stângă este falsă, nu se returnează nimic. `n't` nu va fi returnat. + +

+
+ +--- + +###### 101. Care este valoarea ieșirii? + +```javascript +const one = false || {} || null; +const two = null || false || ''; +const three = [] || 0 || true; + +console.log(one, two, three); +``` + +- A: `false` `null` `[]` +- B: `null` `""` `true` +- C: `{}` `""` `[]` +- D: `null` `null` `true` + +
Răspuns +

+ +#### Răspuns: C + +Cu operatorul `||` utem returna primul operand adevărat (truthy). Dacă toate valorile sunt false, se va returna ultimul operand. + +`(false || {} || null)`: obiectul go `{}` este o valoare adevărată (truthy). Aceasta este prima (și singura) valoare adevărată, care este returnată. `one` este egal cu `{}`. + +`(null || false || "")`: toate operanzii sunt valori false. Acest lucru înseamnă că ultimul operand `""` este returnat. `two` este egal cu `""`. + +`([] || 0 || "")`: array-ul gol `[]` este o valoare adevărată (truthy). Aceasta este prima valoare adevărată, care este returnată. `three` este egal cu `[]`. + +

+
+ +--- + +###### 102. Care este valoarea ieșirii? + +```javascript +const myPromise = () => Promise.resolve('I have resolved!'); + +function firstFunction() { + myPromise().then(res => console.log(res)); + console.log('second'); +} + +async function secondFunction() { + console.log(await myPromise()); + console.log('second'); +} + +firstFunction(); +secondFunction(); +``` + +- A: `I have resolved!`, `second` și `I have resolved!`, `second` +- B: `second`, `I have resolved!` și `second`, `I have resolved!` +- C: `I have resolved!`, `second` și `second`, `I have resolved!` +- D: `second`, `I have resolved!` și `I have resolved!`, `second` + +
Răspuns +

+ +#### Răspuns: D + +Cu o promisiune, spunem în principiu _Vreau să execut această funcție, dar o pun deoparte pentru moment în timp ce rulează, deoarece acest lucru poate dura ceva timp. Doar atunci când o anumită valoare este rezolvată (sau respinsă), și atunci când stiva de apeluri este goală, doresc să folosesc această valoare._ + +Putem obține această valoare atât cu `.then` cât și cu cuvântul cheie `await` într-o funcție `async`. Cu toate că putem obține valoarea unei promisiuni cu ambele metode `.then` și `await`, ele funcționează puțin diferit. + +În `firstFunction`, am pus (într-un fel) funcția `myPromise` deoparte în timp ce aceasta se executa, dar am continuat să executăm restul codului, care este `console.log('second')` în acest caz. Apoi, funcția a fost rezolvată cu șirul `I have resolved`, care a fost apoi înregistrat în jurnal după ce s-a constatat că stiva de apeluri era goală. + +Cu cuvântul cheie `await` în `secondFunction`, efectiv pauzăm execuția unei funcții asincrone până când valoarea a fost rezolvată înainte de a trece la următoarea linie. + +Acest lucru înseamnă că a așteptat ca `myPromise` să fie rezolvat cu valoarea `I have resolved`, și doar după ce s-a întâmplat acest lucru, s-a trecut la următoarea linie: a fost înregistrat `second`. + +

+
+ +--- + +###### 103. Care este valoarea ieșirii? + +```javascript +const set = new Set(); + +set.add(1); +set.add('Lydia'); +set.add({ name: 'Lydia' }); + +for (let item of set) { + console.log(item + 2); +} +``` + +- A: `3`, `NaN`, `NaN` +- B: `3`, `7`, `NaN` +- C: `3`, `Lydia2`, `[object Object]2` +- D: `"12"`, `Lydia2`, `[object Object]2` + +
Răspuns +

+ +#### Răspuns: C + +Operatorul `+` nu este folosit doar pentru adunarea valorilor numerice, ci îl putem utiliza și pentru concatenarea șirurilor de caractere. Ori de câte ori motorul JavaScript observă că una sau mai multe valori nu sunt de tip număr, va converti numărul într-un șir de caractere. + +Primul operand este `1`, care este o valoare numerică. `1 + 2` returnează numărul 3. + +Cu toate acestea, al doilea operand este un șir de caractere `"Lydia"`. `"Lydia"` este un șir de caractere și `2` este un număr: `2` este convertit într-un șir de caractere. `"Lydia"` și `"2"` sunt concatenate, rezultând șirul de caractere `"Lydia2"`. + +`{ name: "Lydia" }` este un obiect. Niciun număr, niciun obiect nu este un șir de caractere, astfel că sunt convertite în șiruri. Ori de câte ori convertim un obiect regulat în șir de caractere, devine `"[object Object]"`. `"[object Object]"` concatenat cu `"2"` devine `"[object Object]2"`. + +

+
+ +--- + +###### 104. Care este rezultatul? + +```javascript +Promise.resolve(5); +``` + +- A: `5` +- B: `Promise {: 5}` +- C: `Promise {: 5}` +- D: `Error` + +
Răspuns +

+ +#### Răspuns: C + +Putem pasa orice tip de valoare dorim către `Promise.resolve`, fie o promisiune, fie o valoare non-promisiune. Metoda în sine returnează o promisiune cu valoarea rezolvată (``). Dacă pasați o funcție regulată, va fi o promisiune rezolvată cu o valoare regulată. Dacă pasați o promisiune, va fi o promisiune rezolvată cu valoarea rezolvată a promisiunii respective pasate. + +În acest caz, am pasat doar valoarea numerică `5`. Aceasta returnează o promisiune rezolvată cu valoarea `5`. + +

+
+ +--- + +###### 105. Care este rezultatul? + +```javascript +function compareMembers(person1, person2 = person) { + if (person1 !== person2) { + console.log('Not the same!'); + } else { + console.log('They are the same!'); + } +} + +const person = { name: 'Lydia' }; + +compareMembers(person); +``` + +- A: `Not the same!` +- B: `They are the same!` +- C: `ReferenceError` +- D: `SyntaxError` + +
Răspuns +

+ +#### Răspuns: B + +Obiectele sunt pasate prin referință. Atunci când verificăm obiecte pentru egalitate strictă (`===`), comparăm referințele lor. + +Am setat valoarea implicită pentru `person2` egală cu obiectul `person` și am pasat obiectul `person` ca valoare pentru `person1`. + +Acest lucru înseamnă că ambele valori au o referință către aceeași locație în memorie, astfel că sunt egale. + +Blocul de cod din instrucțiunea `else` se execută, și este înregistrat mesajul`They are the same!`. + +

+
+ +--- + +###### 106. Care este rezultatul? + +```javascript +const colorConfig = { + red: true, + blue: false, + green: true, + black: true, + yellow: false, +}; + +const colors = ['pink', 'red', 'blue']; + +console.log(colorConfig.colors[1]); +``` + +- A: `true` +- B: `false` +- C: `undefined` +- D: `TypeError` + +
Răspuns +

+ +#### Răspuns: D + +În JavaScript, avem două moduri de a accesa proprietăți pe un obiect: notare cu paranteze pătrate sau notare cu punct. În acest exemplu, folosim notarea cu punct (`colorConfig.colors`) în loc de notarea cu paranteze pătrate (`colorConfig["colors"]`). + +Cu notarea cu punct, JavaScript încearcă să găsească proprietatea pe obiect cu exact același nume. În acest exemplu, JavaScript încearcă să găsească o proprietate numită `colors` pe obiectul `colorConfig`. Nu există o proprietate numită `colors`, așa că acest lucru returnează `undefined`. Apoi, încercăm să accesăm valoarea primului element folosind `[1]`. Nu putem face acest lucru pe o valoare care este `undefined`, astfel că se generează o eroare de tip `TypeError`: `Cannot read property '1' of undefined`. + +JavaScript interpretează (sau deschide) declarațiile. Atunci când folosim notația cu paranteze pătrate, vede prima paranteză deschisă `[` și continuă până găsește paranteza de închidere `]`. Abia atunci va evalua declarația. Dacă am fi folosit `colorConfig[colors[1]]`, ar fi returnat valoarea proprietății `red` pe obiectul `colorConfig`. + +

+
+ +--- + +###### 107. Care este rezultatul? + +```javascript +console.log('❤️' === '❤️'); +``` + +- A: `true` +- B: `false` + +
Răspuns +

+ +#### Răspuns: A + +În culise, emoji-urile sunt reprezentate ca coduri Unicode. Codurile Unicode pentru emoji-ul inimii sunt `"U+2764 U+FE0F"`. Acestea sunt întotdeauna aceleași pentru aceleași emoji-uri, așa că comparăm două șiruri identice între ele, ceea ce returnează + +

+
+ +--- + +###### 108. Care dintre aceste metode modifică array-ul original? + +```javascript +const emojis = ['✨', '🥑', '😍']; + +emojis.map(x => x + '✨'); +emojis.filter(x => x !== '🥑'); +emojis.find(x => x !== '🥑'); +emojis.reduce((acc, cur) => acc + '✨'); +emojis.slice(1, 2, '✨'); +emojis.splice(1, 2, '✨'); +``` + +- A: `Toate` +- B: `map` `reduce` `slice` `splice` +- C: `map` `slice` `splice` +- D: `splice` + +
Răspuns +

+ +#### Răspuns: D + +Cu metoda `splice` mmodificăm array-ul original prin ștergerea, înlocuirea sau adăugarea de elemente. În acest caz, am eliminat 2 elemente de la indexul 1 (am eliminat `'🥑'` și `'😍'`) și am adăugat emoji-ul ✨ în locul lor. + +`map`, `filter` și `slice` returnează un nou array, `find` returnează un element, ia `reduce` returnează o valoare redusă. + +

+
+ +--- + +###### 109. Care este rezultatul? + +```javascript +const food = ['🍕', '🍫', '🥑', '🍔']; +const info = { favoriteFood: food[0] }; + +info.favoriteFood = '🍝'; + +console.log(food); +``` + +- A: `['🍕', '🍫', '🥑', '🍔']` +- B: `['🍝', '🍫', '🥑', '🍔']` +- C: `['🍝', '🍕', '🍫', '🥑', '🍔']` +- D: `ReferenceError` + +
Răspuns +

+ +#### Răspuns: A + +Am setat valoarea proprietății `favoriteFood` pe obiectul `info` egal cu șirul de caractere cu emoji-ul de pizza, `'🍕'`. Un șir de caractere este un tip de date primitiv. În JavaScript, tipurile de date primitive nu interacționează prin referință. + +În JavaScript, tipurile de date primitive (tot ceea ce nu este obiect) interacționează prin _valoare_. În acest caz, am setat valoarea proprietății `favoriteFood` pe obiectul `info` egală cu valoarea primului element din array-ul `food` care este un șir de caractere cu emoji-ul de pizza în acest caz (`'🍕'`). Un șir de caractere este un tip de date primitiv și interacționează prin valoare (vedeți [blogpost](https://www.theavocoder.com/complete-javascript/2018/12/21/by-value-vs-by-reference) meu dacă doriți să aflați mai multe). + +Apoi, schimbăm valoarea proprietății `favoriteFood` pe obiectul `info`. Array-ul `food` nu s-a schimbat, deoarece valoarea `favoriteFood` era doar o _copie_ a valorii primului element din array și nu are o referință la aceeași locație în memorie ca elementul din `food[0]`. Când înregistrăm array-ul `food`, acesta rămâne neschimbat, `['🍕', '🍫', '🥑', '🍔']`. + +

+
+ +--- + +###### 110. Ce face această metodă? + +```javascript +JSON.parse(); +``` + +- A: Parcurge JSON-ul pentru a obține o valoare JavaScript +- B: Parcurge un obiect JavaScript pentru a obține un JSON +- C: Parcurge orice valoare JavaScript într-un JSON +- D: Parcurge doar JSON-ul într-un obiect JavaScript + +
Răspuns +

+ +#### Răspuns: A + +Cu metoda `JSON.parse()` putem parsa un șir JSON într-o valoare JavaScript. + +```javascript +// Transformarea unui număr într-un JSON valid, apoi parsarea șirului JSON într-o valoare JavaScript: +const jsonNumber = JSON.stringify(4); // '4' +JSON.parse(jsonNumber); // 4 + +// Transformarea unei valori de tip array într-un JSON valid, apoi parsarea șirului JSON într-o valoare JavaScript: +const jsonArray = JSON.stringify([1, 2, 3]); // '[1, 2, 3]' +JSON.parse(jsonArray); // [1, 2, 3] + +// Transformarea unui obiect într-un JSON valid, apoi parsarea șirului JSON într-o valoare JavaScript: +const jsonArray = JSON.stringify({ name: 'Lydia' }); // '{"name":"Lydia"}' +JSON.parse(jsonArray); // { name: 'Lydia' } +``` + +

+
+ +--- + +###### 111. Care este rezultatul? + +```javascript +let name = 'Lydia'; + +function getName() { + console.log(name); + let name = 'Sarah'; +} + +getName(); +``` + +- A: Lydia +- B: Sarah +- C: `undefined` +- D: `ReferenceError` + +
Răspuns +

+ +#### Răspuns: D + +Fiecare funcție are propriul său _context de execuție_ (sau _domeniu_). Funcția `getName` caută mai întâi în propriul său context (domeniu) pentru a vedea dacă conține variabila `name` pe care încercăm să o accesăm. În acest caz, funcția `getName` conține propria sa variabilă `name` declarăm variabila `name` cu cuvântul cheie `let`, și cu valoarea `'Sarah'`. + +Variabilele declarate cu cuvântul cheie `let` (și `const`) sunt hoisted, dar, spre deosebire de `var`, nu sunt inițializate. Ele nu sunt accesibile înainte de linia în care le declarăm (inițializăm). Acest lucru se numește "zona temporală moartă" (temporal dead zone). Atunci când încercăm să accesăm variabilele înainte de a fi declarate, JavaScript aruncă o eroare de tip `ReferenceError`. + +Dacă nu am fi declarat variabila `name` în interiorul funcției `getName` motorul JavaScript ar fi căutat în josul lanțului de _domenii_. Domeniul exterior are o variabilă numită `name` cu valoarea `Lydia`. În acest caz, ar fi afișat `Lydia`. + +```javascript +let name = 'Lydia'; + +function getName() { + console.log(name); +} + +getName(); // Lydia +``` + +

+
+ +--- + +###### 112. Care este rezultatul? + +```javascript +function* generatorOne() { + yield ['a', 'b', 'c']; +} + +function* generatorTwo() { + yield* ['a', 'b', 'c']; +} + +const one = generatorOne(); +const two = generatorTwo(); + +console.log(one.next().value); +console.log(two.next().value); +``` + +- A: `a` și `a` +- B: `a` și `undefined` +- C: `['a', 'b', 'c']` și `a` +- D: `a` și `['a', 'b', 'c']` + +
Răspuns +

+ +#### Răspuns: C + +Cu cuvântul cheie `yield`, cedăm valorile într-o funcție generator. Cu cuvântul cheie `yield*`, putem ceda valori dintr-o altă funcție generator sau dintr-un obiect iterabil (de exemplu, un array). + +În `generatorOne`, folosim cuvântul cheie `yield` pentru a ceda intrega mulțime `['a', 'b', 'c']`. Valoarea proprietății `value` a obiectului returnat de metoda `next` pe obiectul `one` (`one.next().value`) este egală cu întregul array `['a', 'b', 'c']`. + +```javascript +console.log(one.next().value); // ['a', 'b', 'c'] +console.log(one.next().value); // undefined +``` + +În `generatorTwo`, folosim cuvântul cheie `yield*`. Acest lucru înseamnă că prima valoare cedată din `two`, este egală cu prima valoare cedată din iterator. Iteratorul este mulțimea `['a', 'b', 'c']`. Prima valoare cedată este `a`, așa că prima dată când apelăm `two.next().value`, este returnată valoarea `a`. + +```javascript +console.log(two.next().value); // 'a' +console.log(two.next().value); // 'b' +console.log(two.next().value); // 'c' +console.log(two.next().value); // undefined +``` + +

+
+ +--- + +###### 113. Care este rezultatul? + +```javascript +console.log(`${(x => x)('I love')} to program`); +``` + +- A: `I love to program` +- B: `undefined to program` +- C: `${(x => x)('I love') to program` +- D: `TypeError` + +
Răspuns +

+ +#### Răspuns: A + +Expresiile din șirurile șablon (template literals) sunt evaluate mai întâi. Acest lucru înseamnă că șirul va conține valoarea returnată de expresie, funcția imediat invocată `(x => x)('I love')` în acest caz. Trecem valoarea `'I love'` ca argument către funcția arrow `x => x`. `x` este egal cu `'I love'`, care este returnată. Aceasta duce la rezultatul `I love to program`. + +

+
+ +--- + +###### 114. Ce se va întâmpla? + +```javascript +let config = { + alert: setInterval(() => { + console.log('Alert!'); + }, 1000), +}; + +config = null; +``` + +- A: Funcția de callback a `setInterval` nu va fi invocată +- B: Funcția de callback a `setInterval` este invocată o singură dată +- C: Funcția de callback a `setInterval` va fi totuși apelată în fiecare secundă +- D: Nu am apelat niciodată `config.alert()`, config este `null` + +
Răspuns +

+ +#### Răspuns: C + +În mod normal, atunci când setăm obiecte egal cu `null`, acele obiecte sunt _colectate de gunoi_ (garbage collected), deoarece nu mai există nicio referință către acel obiect. Cu toate acestea, deoarece funcția de callback din `setInterval` este o funcție arrow (și, prin urmare, legată de obiectul `config`), funcția de callback încă menține o referință la obiectul `config`. +Atâta timp cât există o referință, obiectul nu va fi colectat de gunoi (garbage collected). +Deoarece aceasta este o intervală de timp, setarea lui `config` la `null` sau `delete` lui `config.alert` nu va colecta intervalul de gunoi și intervalul va continua să fie apelat. +Pentru a-l opri și a-l elimina din memorie, trebuie să folosiți `clearInterval(config.alert)`. +Deoarece acest lucru nu a fost făcut, funcția de callback a `setInterval` va fi în continuare invocată la fiecare 1000 ms (1 secundă). + +

+
+ +--- + +###### 115. Ce metodă(e) va returna valoarea `'Hello world!'`? + +```javascript +const myMap = new Map(); +const myFunc = () => 'greeting'; + +myMap.set(myFunc, 'Hello world!'); + +//1 +myMap.get('greeting'); +//2 +myMap.get(myFunc); +//3 +myMap.get(() => 'greeting'); +``` + +- A: 1 +- B: 2 +- C: 2 și 3 +- D: Toate + +
Răspuns +

+ +#### Răspuns: B + +Când adăugăm o pereche cheie/valoare folosind metoda `set`, cheia va fi valoarea primului argument transmis funcției `set`, iar valoarea va fi cea de-a doua valoare transmisă funcție `set`. Cheia în acest caz este _funcția_ `() => 'greeting'`, iar valoarea `'Hello world'`. `myMap` este acum `{ () => 'greeting' => 'Hello world!' }`. + +1 este incorect pentru că cheia nu este `'greeting'` ci `() => 'greeting'`. +3 este incorect pentru că creăm o nouă funcție prin transmiterea ei ca parametru către metoda `get`. Obiectele interacționează prin _referință_. Funcțiile sunt obiecte, motiv pentru care două funcții nu sunt niciodată strict egale, chiar dacă sunt identice: ele au o referință către un loc diferit în memorie. + +

+
+ +--- + +###### 116. Care este rezultatul? + +```javascript +const person = { + name: 'Lydia', + age: 21, +}; + +const changeAge = (x = { ...person }) => (x.age += 1); +const changeAgeAndName = (x = { ...person }) => { + x.age += 1; + x.name = 'Sarah'; +}; + +changeAge(person); +changeAgeAndName(); + +console.log(person); +``` + +- A: `{name: "Sarah", age: 22}` +- B: `{name: "Sarah", age: 23}` +- C: `{name: "Lydia", age: 22}` +- D: `{name: "Lydia", age: 23}` + +
Răspuns +

+ +#### Răspuns: C + +Ambele funcții `changeAge` și `changeAgeAndName` au un parametru implicit, și anume un obiect _nou_ creat `{ ...person }`. Acest obiect conține copii ale tuturor cheilor/valorilor din obiectul `person`. + +În primul rând, apelăm funcția `changeAge` și transmitem obiectul `person` ca argument. Această funcție crește valoarea proprietății `age` cu 1. `person` devine `{ name: "Lydia", age: 22 }`. + +Apoi, apelăm funcția `changeAgeAndName`, însă nu transmitem un parametru. În schimb, valoarea lui `x` este egală cu un obiect _nou_: `{ ...person }`. Deoarece este un obiect nou, acesta nu afectează valorile proprietăților din obiectul `person`. `person` rămâne egal cu `{ name: "Lydia", age: 22 }`. + +

+
+ +--- + +###### 117. Care dintre opțiunile următoare va returna `6`? + +```javascript +function sumValues(x, y, z) { + return x + y + z; +} +``` + +- A: `sumValues([...1, 2, 3])` +- B: `sumValues([...[1, 2, 3]])` +- C: `sumValues(...[1, 2, 3])` +- D: `sumValues([1, 2, 3])` + +
Răspuns +

+ +#### Răspuns: C + +Cu operatorul spread `...`, putem _răspândi_ obiecte iterabile în elemente individuale. Funcția `sumValues` primește trei argumente: `x`, `y` și `z`. `...[1, 2, 3]` va rezulta în `1, 2, 3`, pe care le transmitem funcției `sumValues`. + +

+
+ +--- + +###### 118. Care este rezultatul? + +```javascript +let num = 1; +const list = ['🥳', '🤠', '🥰', '🤪']; + +console.log(list[(num += 1)]); +``` + +- A: `🤠` +- B: `🥰` +- C: `SyntaxError` +- D: `ReferenceError` + +
Răspuns +

+ +#### Răspuns: B + +Cu operandul `+=` incrementăm valoarea lui `num` cu `1`. Inițial, `num` avea valoarea `1`, deci `1 + 1` este `2`. Elementul de pe al doilea index în mulțimea `list` este 🥰, `console.log(list[2])` va afișa 🥰. + +

+
+ +--- + +###### 119. Care este rezultatul? + +```javascript +const person = { + firstName: 'Lydia', + lastName: 'Hallie', + pet: { + name: 'Mara', + breed: 'Dutch Tulip Hound', + }, + getFullName() { + return `${this.firstName} ${this.lastName}`; + }, +}; + +console.log(person.pet?.name); +console.log(person.pet?.family?.name); +console.log(person.getFullName?.()); +console.log(member.getLastName?.()); +``` + +- A: `undefined` `undefined` `undefined` `undefined` +- B: `Mara` `undefined` `Lydia Hallie` `ReferenceError` +- C: `Mara` `null` `Lydia Hallie` `null` +- D: `null` `ReferenceError` `null` `ReferenceError` + +
Răspuns +

+ +#### Răspuns: B + +Cu operatorul de verificare opțională `?.`, nu mai este necesar să verificăm explicit dacă valorile mai profunde încorporate sunt valide sau nu. Dacă încercăm să accesăm o proprietate pe o valoare `undefined` sau `null` valoarea (_nullish_), expresia face un scurtcircuit și returnează `undefined`. + +`person.pet?.name`: `person` are o proprietate numită `pet`: `person.pet` nu este `nullish`. Are o proprietate numită `name`, și returnează `Mara`. +`person.pet?.family?.name`: `person` are o proprietate numită `pet`: `person.pet` nu este `nullish`. `pet` _nu_ are o proprietate numită `family`, `person.pet.family` este `nullish`. Expresia returnează `undefined`. +`person.getFullName?.()`: `person` are o proprietate `getFullName`: `person.getFullName()` nu este `nullish` și poate fi invocată, care returnează `Lydia Hallie`. +`member.getLastName?.()`: variabila `member` nu există, prin urmare se va genera o excepție de tip `ReferenceError` gets thrown! + +

+
+ +--- + +###### 120. Care este rezultatul? + +```javascript +const groceries = ['banana', 'apple', 'peanuts']; + +if (groceries.indexOf('banana')) { + console.log('We have to buy bananas!'); +} else { + console.log(`We don't have to buy bananas!`); +} +``` + +- A: We have to buy bananas! +- B: We don't have to buy bananas +- C: `undefined` +- D: `1` + +
Răspuns +

+ +#### Răspuns: B + +Am trecut condiția `groceries.indexOf("banana")` în instrucțiunea `if`. `groceries.indexOf("banana")` returnează `0`, care este o valoare falsă. Deoarece condiția din instrucțiunea `if` este falsă, se execută codul din blocul `else`, și `We don't have to buy bananas!` se afișează. + +

+
+ +--- + +###### 121. Care este rezultatul? + +```javascript +const config = { + languages: [], + set language(lang) { + return this.languages.push(lang); + }, +}; + +console.log(config.language); +``` + +- A: `function language(lang) { this.languages.push(lang }` +- B: `0` +- C: `[]` +- D: `undefined` + +
Răspuns +

+ +#### Răspuns: D + +Metoda `language` este un `setter`. Setter-urile nu rețin o valoare reală; scopul lor este să _modifice_ proprietăți. Atunci când apelați o metodă `setter`, aceasta va returna `undefined`. + +

+
+ +--- + +###### 122. Care este rezultatul? + +```javascript +const name = 'Lydia Hallie'; + +console.log(!typeof name === 'object'); +console.log(!typeof name === 'string'); +``` + +- A: `false` `true` +- B: `true` `false` +- C: `false` `false` +- D: `true` `true` + +
Răspuns +

+ +#### Răspuns: C + +`typeof name` returnează `"string"`. Șirul de caractere `"string"` este o valoare adevărată (truthy), așa că `!typeof name` returnează valoarea booleană `false`. `false === "object"` și `false === "string"` ambele returnează `false`. + +(Dacă dorim să verificăm dacă tipul este (ne)egal cu un anumit tip, ar trebui să folosim `!==` în loc de `!typeof`) + +

+
+ +--- + +###### 123. Care este rezultatul? + +```javascript +const add = x => y => z => { + console.log(x, y, z); + return x + y + z; +}; + +add(4)(5)(6); +``` + +- A: `4` `5` `6` +- B: `6` `5` `4` +- C: `4` `function` `function` +- D: `undefined` `undefined` `6` + +
Răspuns +

+ +#### Răspuns: A + +Funcția `add` returnează o funcție arrow, care returnează o altă funcție arrow, care la rândul ei returnează o altă funcție arrow (încă sunteți cu mine?). Prima funcție primește un argument `x` cu valoarea `4`. Apelăm a doua funcție, care primește un argument `y` cu valoarea `5`. Apoi apelăm a treia funcție, care primește un argument `z` cu valoarea `6`. Când încercăm să accesăm valorile `x`, `y` și `z` în ultima funcție arrow, motorul JavaScript urcă lanțul de domenii pentru a găsi valorile pentru `x` și `y` în consecință. Aceasta returnează `4` `5` `6`. + +

+
+ +--- + +###### 124. Care este rezultatul? + +```javascript +async function* range(start, end) { + for (let i = start; i <= end; i++) { + yield Promise.resolve(i); + } +} + +(async () => { + const gen = range(1, 3); + for await (const item of gen) { + console.log(item); + } +})(); +``` + +- A: `Promise {1}` `Promise {2}` `Promise {3}` +- B: `Promise {}` `Promise {}` `Promise {}` +- C: `1` `2` `3` +- D: `undefined` `undefined` `undefined` + +
Răspuns +

+ +#### Răspuns: C + +Funcția generator `range` returnează un obiect asincron cu promisiuni pentru fiecare element din intervalul pe care îl transmitem: `Promise{1}`, `Promise{2}`, `Promise{3}`. Setăm variabila `gen` egală cu obiectul asincron, după care facem o buclă peste el folosind o buclă `for await ... of`. Setăm variabila `item` eegală cu valorile promisiunilor returnate: mai întâi `Promise{1}`, apoi `Promise{2}`, apoi `Promise{3}`. Deoarece _așteptăm_ valoarea lui `item`, adică promisiunea rezolvată, _valorile_ rezolvate ale promisiunilor sunt returnate: `1`, `2`, apoi `3`. + +

+
+ +--- + +###### 125. Care este rezultatul? + +```javascript +const myFunc = ({ x, y, z }) => { + console.log(x, y, z); +}; + +myFunc(1, 2, 3); +``` + +- A: `1` `2` `3` +- B: `{1: 1}` `{2: 2}` `{3: 3}` +- C: `{ 1: undefined }` `undefined` `undefined` +- D: `undefined` `undefined` `undefined` + +
Răspuns +

+ +#### Răspuns: D + +`myFunc` așteaptă ca argument un obiect cu proprietățile `x`, `y` și `z`. Deoarece transmitem doar trei valori numerice separate (1, 2, 3) în loc de un obiect cu proprietățile `x`, `y` și `z` ({x: 1, y: 2, z: 3}), `x`, `y` și `z` primesc valoarea lor implicită, care este `undefined`. + +

+
+ +--- + +###### 126. Care este rezultatul? + +```javascript +function getFine(speed, amount) { + const formattedSpeed = new Intl.NumberFormat('en-US', { + style: 'unit', + unit: 'mile-per-hour' + }).format(speed); + + const formattedAmount = new Intl.NumberFormat('en-US', { + style: 'currency', + currency: 'USD' + }).format(amount); + + return `Șoferul a condus ${formattedSpeed} și trebuie să plătească ${formattedAmount}`; +} + +console.log(getFine(130, 300)) +``` + +- A: Șoferul a condus 130 și trebuie să plătească 300 +- B: Șoferul a condus 130 mph și trebuie să plătească \$300.00 +- C: Șoferul a condus undefined și trebuie să plătească undefined +- D: Șoferul a condus 130.00 și trebuie să plătească 300.00 + +
Răspuns +

+ +#### Răspuns: B + +Cu metoda `Intl.NumberFormat` putem formata valorile numerice în orice locație. Formatez valoarea numerică `130` pentru locația `en-US` ca o `unitate` în `mile-per-hour`, ceea ce rezultă în `130 mph`. Valoarea numerică `300` pentru locația `en-US` ca `monedă` în `USD` rezultă în `$300.00`. + +

+
+ +--- + +###### 127. Care este rezultatul? + +```javascript +const spookyItems = ['👻', '🎃', '🕸']; +({ item: spookyItems[3] } = { item: '💀' }); + +console.log(spookyItems); +``` + +- A: `["👻", "🎃", "🕸"]` +- B: `["👻", "🎃", "🕸", "💀"]` +- C: `["👻", "🎃", "🕸", { item: "💀" }]` +- D: `["👻", "🎃", "🕸", "[object Object]"]` + +
Răspuns +

+ +#### Răspuns: B + +Prin destrucțurarea obiectelor, putem extrage valorile din obiectul din partea dreaptă și le atribui valorii cu același nume de proprietate din obiectul din partea stângă. În acest caz, atribuim valoarea "💀" lui `spookyItems[3]`. Acest lucru înseamnă că modificăm array-ul `spookyItems`, adăugăm "💀" la el. La afișarea în consolă a lui `spookyItems`, se va afișa `["👻", "🎃", "🕸", "💀"]`. + +

+
+ +--- + +###### 128. Care este rezultatul? + +```javascript +const name = 'Lydia Hallie'; +const age = 21; + +console.log(Number.isNaN(name)); +console.log(Number.isNaN(age)); + +console.log(isNaN(name)); +console.log(isNaN(age)); +``` + +- A: `true` `false` `true` `false` +- B: `true` `false` `false` `false` +- C: `false` `false` `true` `false` +- D: `false` `true` `false` `true` + +
Răspuns +

+ +#### Răspuns: C + +Cu metoda `Number.isNaN` puteți verifica dacă valoarea pe care o transmiteți este o _valoare numerică_ și este egală cu `NaN`. `name` nu este o valoare numerică, așa că `Number.isNaN(name)` returnează `false`. `age` este o valoare numerică, dar nu este egală cu `NaN`, astfel că `Number.isNaN(age)` returnează `false`. + +Cu metoda `isNaN` puteți verifica dacă valoarea pe care o transmiteți nu este un număr. `name` nu este un număr, așa că `isNaN(name)` returnează `true`. `age` este un număr, astfel că `isNaN(age)` returnează `false`. + +

+
+ +--- + +###### 129. Care este rezultatul? + +```javascript +const randomValue = 21; + +function getInfo() { + console.log(typeof randomValue); + const randomValue = 'Lydia Hallie'; +} + +getInfo(); +``` + +- A: `"number"` +- B: `"string"` +- C: `undefined` +- D: `ReferenceError` + +
Răspuns +

+ +#### Răspuns: D + +Variabilele declarate cu cuvântul cheie `const` nu pot fi referite înainte de inițializare: acest lucru se numește _zona temporală moartă_ (temporal dead zone). În funcția `getInfo`, variabila`randomValue` este de domeniu în domeniul funcțional al funcției `getInfo`. Pe linia în care dorim să afișăm valoarea `typeof randomValue`, variabila `randomValue` nu este încă inițializată: se va genera o eroare de tip `ReferenceError`! Motorul nu a căutat în josul lanțului de domenii deoarece am declarat variabila `randomValue` în funcția `getInfo`. + +

+
+ +--- + +###### 130. Care este rezultatul? + +```javascript +const myPromise = Promise.resolve('Woah some cool data'); + +(async () => { + try { + console.log(await myPromise); + } catch { + throw new Error(`Oops didn't work`); + } finally { + console.log('Oh finally!'); + } +})(); +``` + +- A: `Woah some cool data` +- B: `Oh finally!` +- C: `Woah some cool data` `Oh finally!` +- D: `Oops didn't work` `Oh finally!` + +
Răspuns +

+ +#### Răspuns: C + +În blocul `try` înregistrăm valoarea așteptată a variabilei `myPromise`: `"Woah some cool data"`. Deoarece nu s-au generat erori în blocul `try` codul din blocul `catch` nu se execută. Codul din blocul `finally` se execută _întotdeauna_, și se va afișa `"Oh finally!"`. + +

+
+ +--- + +###### 131. Care este rezultatul? + +```javascript +const emojis = ['🥑', ['✨', '✨', ['🍕', '🍕']]]; + +console.log(emojis.flat(1)); +``` + +- A: `['🥑', ['✨', '✨', ['🍕', '🍕']]]` +- B: `['🥑', '✨', '✨', ['🍕', '🍕']]` +- C: `['🥑', ['✨', '✨', '🍕', '🍕']]` +- D: `['🥑', '✨', '✨', '🍕', '🍕']` + +
Răspuns +

+ +#### Răspuns: B + +Cu metoda `flat` putem crea un nou array aplatizat. Adâncimea array-ului aplatizat depinde de valoarea pe care o transmitem. În acest caz, am transmis valoarea `1` (care nu era necesară, deoarece aceasta este valoarea implicită), ceea ce înseamnă că vor fi concatenate doar array-urile de pe primul nivel de adâncime. `['🥑']` și `['✨', '✨', ['🍕', '🍕']]`. Concatenarea acestor două array-uri rezultă în `['🥑', '✨', '✨', ['🍕', '🍕']]`. + +

+
+ +--- + +###### 132. Care este rezultatul? + +```javascript +class Counter { + constructor() { + this.count = 0; + } + + increment() { + this.count++; + } +} + +const counterOne = new Counter(); +counterOne.increment(); +counterOne.increment(); + +const counterTwo = counterOne; +counterTwo.increment(); + +console.log(counterOne.count); +``` + +- A: `0` +- B: `1` +- C: `2` +- D: `3` + +
Răspuns +

+ +#### Răspuns: D + +`counterOne` este o instanță a clasei `Counter`. Clasa `Counter` conține o proprietate `count` în constructorul său și o metodă `increment`. Mai întâi, am invocat metoda `increment` de două ori, apelând `counterOne.increment()`. În prezent, `counterOne.count` este `2`. + + + +Apoi, creăm o nouă variabilă `counterTwo`, și o setăm egală cu `counterOne`. Deoarece obiectele interacționează prin referință, creăm doar o nouă referință către același loc în memorie la care indică `counterOne`. Deoarece au același loc în memorie, orice modificări făcute asupra obiectului la care `counterTwo` are o referință se aplică și la `counterOne`. În prezen, `counterTwo.count` este `2`. + +Apelăm `counterTwo.increment()`, ceea ce setează `count` la `3`. Apoi, afișăm valoarea lui `counterOne`, ceea ce va afișa `3`. + + + +

+
+ +--- + +###### 133. Care este rezultatul? + +```javascript +const myPromise = Promise.resolve(Promise.resolve('Promise')); + +function funcOne() { + setTimeout(() => console.log('Timeout 1!'), 0); + myPromise.then(res => res).then(res => console.log(`${res} 1!`)); + console.log('Last line 1!'); +} + +async function funcTwo() { + const res = await myPromise; + console.log(`${res} 2!`) + setTimeout(() => console.log('Timeout 2!'), 0); + console.log('Last line 2!'); +} + +funcOne(); +funcTwo(); +``` + +- A: `Promise 1! Last line 1! Promise 2! Last line 2! Timeout 1! Timeout 2!` +- B: `Last line 1! Timeout 1! Promise 1! Last line 2! Promise2! Timeout 2! ` +- C: `Last line 1! Promise 2! Last line 2! Promise 1! Timeout 1! Timeout 2!` +- D: `Timeout 1! Promise 1! Last line 1! Promise 2! Timeout 2! Last line 2!` + +
Răspuns +

+ +#### Răspuns: C + +În primul rând, apelăm `funcOne`. Pe prima linie a lui `funcOne`, apelăm funcția _asincronă_ `setTimeout`, din care funcția de apel se trimite către API-ul Web. (vezi articolul meu despre bucla evenimentelor aici.) + +Apoi apelăm promisiunea `myPromise` care este o operațiune _asincronă_. + +Ambele promisiuni și întârzierile (timeout) sunt operațiuni asincrone, iar funcția continuă să ruleze în timp ce finalizează promisiunea și gestionează apelul de întârziere `setTimeout`. Acest lucru înseamnă că se va afișa mai întâi `Last line 1!`, deoarece aceasta nu este o operațiune asincronă. + +Deoarece stiva de apel nu este încă goală, funcția `setTimeout` și promisiunea din `funcOne` nu pot fi adăugate încă la stiva de apel. + +În `funcTwo`, variabila `res` primește o `Promise` pentru că `Promise.resolve(Promise.resolve('Promise'))` este echivalent cu `Promise.resolve('Promise')` deoarece rezolvarea unei promisiuni rezolvă doar valoarea acesteia. Cuvântul cheie `await` din această linie oprește execuția funcției până când primește rezoluția promisiunii și apoi continuă să ruleze sincron până la finalizare, așa că sunt afișate `Promise 2!` apoi `Last line 2!` iar apelul `setTimeout` este trimis către API-ul Web. + +Apoi stiva de apel este goală. Promisiunile sunt _microtask-uri_ astfel că sunt rezolvate în primul rând atunci când stiva de apel este goală, așa că se afișează `Promise 1!`. + +Acum, deoarece `funcTwo` pa fost scoasă din stiva de apel, stiva de apel este goală. Callback-urile așteptând în coadă (`() => console.log("Timeout 1!")` din `funcOne`, și `() => console.log("Timeout 2!")` din `funcTwo`) sunt adăugate pe stivă unul câte unul. Primul callback afișează `Timeout 1!`, și este eliminat din stivă. Apoi, al doilea callback afișează `Timeout 2!`, și este eliminat din stivă. + +

+
+ +--- + +###### 134. Cum putem apela funcția `sum` în `sum.js` din `index.js`? + +```javascript +// sum.js +export default function sum(x) { + return x + x; +} + +// index.js +import * as sum from './sum'; +``` + +- A: `sum(4)` +- B: `sum.sum(4)` +- C: `sum.default(4)` +- D: Exporturile implicite nu sunt importate cu `*`, doar exporturile numite + +
Răspuns +

+ +#### Răspuns: C + +Cu asteriscul `*`, importăm toate valorile exportate din acel fișier, atât exporturile implicite, cât și cele numite. Dacă avem următorul fișierȘ + +```javascript +// info.js +export const name = 'Lydia'; +export const age = 21; +export default 'I love JavaScript'; + +// index.js +import * as info from './info'; +console.log(info); +``` + +Acesta ar fi rezultatul înregistrărilor: + +```javascript +{ + default: "I love JavaScript", + name: "Lydia", + age: 21 +} +``` + +Pentru exemplul cu funcția `sum`, înseamnă că valoarea importată `sum` arată în felul următor: + +```javascript +{ default: function sum(x) { return x + x } } +``` + +Putem invoca această funcție, apelând `sum.default` + +

+
+ +--- + +###### 135. Care este rezultatul? + +```javascript +const handler = { + set: () => console.log('Added a new property!'), + get: () => console.log('Accessed a property!'), +}; + +const person = new Proxy({}, handler); + +person.name = 'Lydia'; +person.name; +``` + +- A: `Added a new property!` +- B: `Accessed a property!` +- C: `Added a new property!` `Accessed a property!` +- D: Nu se înregistrează nimic + +
Răspuns +

+ +#### Răspuns: C + +Cu un obiect Proxy, putem adăuga comportament personalizat unui obiect pe care îl transmitem ca al doilea argument. În acest caz, transmitem obiectul `handler` care conține două proprietăți: `set` și `get`. `set` este invocată ori de câte ori _set_ (setăm) valori de proprietate, `get` este invocată ori de câte ori _get_ (accesăm) valori de proprietate. + +Primul argument este un obiect gol `{}`, care este valoarea lui `person`. La acest obiect, se adaugă comportamentul personalizat specificat în obiectul `handler`. Dacă adăugăm o proprietate la obiectul `person`, `set` va fi invocată. Dacă accesăm o proprietate a obiectului `person`, `get` va fi invocată. + +În primul rând, am adăugat o nouă proprietate `name` la obiectul proxy (`person.name = "Lydia"`). `set` este invocată și înregistrează mesajul `"Added a new property!"`. + +Then, we access a property value on the proxy object, the `get` property on the handler object got invoked. `"Accessed a property!"` gets logged. + +

+
+ +--- + +###### 136. Care dintre următoarele va modifica obiectul `person`? + +```javascript +const person = { name: 'Lydia Hallie' }; + +Object.seal(person); +``` + +- A: `person.name = "Evan Bacon"` +- B: `person.age = 21` +- C: `delete person.name` +- D: `Object.assign(person, { age: 21 })` + +
Răspuns +

+ +#### Răspuns: A + +Cu `Object.seal` putem preveni _adăugarea_ de noi proprietăți sau _eliminarea_ proprietăților existente. + +Cu toate acestea, puteți încă să modificați valoarea proprietăților existente. + +

+
+ +--- + +###### 137. Care dintre următoarele va modifica obiectul `person`? + +```javascript +const person = { + name: 'Lydia Hallie', + address: { + street: '100 Main St', + }, +}; + +Object.freeze(person); +``` + +- A: `person.name = "Evan Bacon"` +- B: `delete person.address` +- C: `person.address.street = "101 Main St"` +- D: `person.pet = { name: "Mara" }` + +
Răspuns +

+ +#### Răspuns: C + +Metoda `Object.freeze` _îngheață_ un obiect. Nu se pot adăuga, modifica sau elimina proprietăți. + +Cu toate acestea, aceasta îngheață obiectul doar în mod _superficial_, ceea ce înseamnă că numai proprietățile _directe_ ale obiectului sunt înghețate. Dacă proprietatea este un alt obiect, cum ar fi `address` în acest caz, proprietățile de pe acel obiect nu sunt înghețate și pot fi modificate. + +

+
+ +--- + +###### 138. Care este rezultatul? + +```javascript +const add = x => x + x; + +function myFunc(num = 2, value = add(num)) { + console.log(num, value); +} + +myFunc(); +myFunc(3); +``` + +- A: `2` `4` și `3` `6` +- B: `2` `NaN` și `3` `NaN` +- C: `2` `Error` și `3` `6` +- D: `2` `4` și `3` `Error` + +
Răspuns +

+ +#### Răspuns: A + +În primul rând, am apelat `myFunc()` fără a transmite niciun argument. Deoarece nu am transmis argumente, `num` și `value` au primit valorile lor implicite: `num` este `2`, și `value` este valoarea returnată de funcția `add`. Funcției `add` îi transmitem `num` ca argument, care avea valoarea `2`. `add` returnează `4`, care este valoarea lui `value`. + +Apoi, am apelat `myFunc(3)` și am transmis valoarea `3` ca valoare pentru argumentul `num`. Nu am transmis un argument pentru `value`. Deoarece nu am transmis o valoare pentru argumentul `value` acesta a primit valoarea implicită: valoarea returnată de funcția `add`. Funcției `add`, îi transmitem `num`, care are valoarea `3`. `add` returnează `6`, care este valoarea lui `value`. + +

+
+ +--- + +###### 139. Care este rezultatul? + +```javascript +class Counter { + #number = 10 + + increment() { + this.#number++ + } + + getNum() { + return this.#number + } +} + +const counter = new Counter() +counter.increment() + +console.log(counter.#number) +``` + +- A: `10` +- B: `11` +- C: `undefined` +- D: `SyntaxError` + +
Răspuns +

+ +#### Răspuns: D + +În ES2020, putem adăuga variabile private în clase folosind simbolul `#`. Nu putem accesa aceste variabile în afara clasei. Atunci când încercăm să înregistrăm `counter.#number`, se aruncă o eroare de sintaxă (SyntaxError): nu putem accesa această variabilă în afara clasei `Counter`! + +

+
+ +--- + +###### 140. Ce lipsește? + +```javascript +const teams = [ + { name: 'Team 1', members: ['Paul', 'Lisa'] }, + { name: 'Team 2', members: ['Laura', 'Tim'] }, +]; + +function* getMembers(members) { + for (let i = 0; i < members.length; i++) { + yield members[i]; + } +} + +function* getTeams(teams) { + for (let i = 0; i < teams.length; i++) { + // ✨ SOMETHING IS MISSING HERE ✨ + } +} + +const obj = getTeams(teams); +obj.next(); // { value: "Paul", done: false } +obj.next(); // { value: "Lisa", done: false } +``` + +- A: `yield getMembers(teams[i].members)` +- B: `yield* getMembers(teams[i].members)` +- C: `return getMembers(teams[i].members)` +- D: `return yield getMembers(teams[i].members)` + +
Răspuns +

+ +#### Răspuns: B + +Pentru a itera prin `membrii` din fiecare element din array-ul `members` trebuie să transmitem `teams[i].members` către funcția generator `getMembers`. Funcția generator returnează un obiect generator. Pentru a itera prin fiecare element din acest obiect generator, trebuie să folosim `yield*`. + +Dacă am fi scris `yield`, `return yield`, sau `return`, întreaga funcție generator ar fi fost returnată prima dată când am apelat metoda `next`. + +

+
+ +--- + +###### 141. Care este rezultatul? + +```javascript +const person = { + name: 'Lydia Hallie', + hobbies: ['coding'], +}; + +function addHobby(hobby, hobbies = person.hobbies) { + hobbies.push(hobby); + return hobbies; +} + +addHobby('running', []); +addHobby('dancing'); +addHobby('baking', person.hobbies); + +console.log(person.hobbies); +``` + +- A: `["coding"]` +- B: `["coding", "dancing"]` +- C: `["coding", "dancing", "baking"]` +- D: `["coding", "running", "dancing", "baking"]` + +
Răspuns +

+ +#### Răspuns: C + +Funcția `addHobby` primește două argumente, `hobby` și `hobbies` cu valoarea implicită a array-ului `hobbies` din obiectul `person`. + +În primul rând, apelăm funcția `addHobby`, și transmitem `"running"` ca valoare pentru `hobby` și un array gol ca valoare pentru `hobbies`. Deoarece transmitem un array gol ca valoare pentru `hobbies`, `"running"` este adăugat la acest array gol. + +Apoi, apelăm funcția `addHobby` și transmitem `"dancing"` ca valoare pentru `hobby`. Nu am transmis o valoare pentru `hobbies`, astfel că aceasta primește valoarea implicită, adică proprietatea `hobbies` din obiectul `person`. Adăugăm hobby-ul `dancing` în array-ul `person.hobbies`. + +În final, apelăm funcția `addHobby`, și transmitem `"baking"` ca valoare pentru `hobby`, și array-ul `person.hobbies` ca valoare pentru `hobbies`. Adăugăm hobby-ul `baking` în array-ul `person.hobbies`. + +După adăugarea lui `dancing` și `baking`, valoarea lui `person.hobbies` este `["coding", "dancing", "baking"]` + +

+
+ +--- + +###### 142. Care este rezultatul? + +```javascript +class Bird { + constructor() { + console.log("I'm a bird. 🦢"); + } +} + +class Flamingo extends Bird { + constructor() { + console.log("I'm pink. 🌸"); + super(); + } +} + +const pet = new Flamingo(); +``` + +- A: `I'm pink. 🌸` +- B: `I'm pink. 🌸` `I'm a bird. 🦢` +- C: `I'm a bird. 🦢` `I'm pink. 🌸` +- D: Nimic, nu am apelat la nicio metodă + +
Răspuns +

+ +#### Răspuns: B + +Creăm variabila `pet` care este o instanță a clasei `Flamingo`. Când instantiem această instanță, `constructor` din clasa `Flamingo` este apelat. Mai întâi, se înregistrează `"I'm pink. 🌸"` după care apelăm `super()`. `super()` apelează constructorul clasei părinte, `Bird`. Constructorul din clasa `Bird` este apelat și înregistrează `"I'm a bird. 🦢"`. + +

+
+ +--- + +###### 143. Care dintre opțiuni rezultă într-o eroare? + +```javascript +const emojis = ['🎄', '🎅🏼', '🎁', '⭐']; + +/* 1 */ emojis.push('🦌'); +/* 2 */ emojis.splice(0, 2); +/* 3 */ emojis = [...emojis, '🥂']; +/* 4 */ emojis.length = 0; +``` + +- A: 1 +- B: 1 și 2 +- C: 3 și 4 +- D: 3 + +
Răspuns +

+ +#### Răspuns: D + +Cuvântul cheie `const` înseamnă pur și simplu că nu putem _redeclara_ valoarea acelei variabile, aceasta este _numai pentru citire_ (read-only). Cu toate acestea, valoarea în sine nu este imutabilă. Proprietățile din array-ul `emojis` pot fi modificate, de exemplu, prin adăugarea de valori noi, prin decuparea lor sau prin setarea lungimii array-ului la 0. + +

+
+ +--- + +###### 144. Ce trebuie să adăugăm la obiectul `person` pentru a obține `["Lydia Hallie", 21]` ca rezultat al `[...person]`? + +```javascript +const person = { + name: "Lydia Hallie", + age: 21 +} + +[...person] // ["Lydia Hallie", 21] +``` + +- A: Nimic, obiectele sunt iterabile în mod implicit +- B: `*[Symbol.iterator]() { for (let x in this) yield* this[x] }` +- C: `*[Symbol.iterator]() { yield* Object.values(this) }` +- D: `*[Symbol.iterator]() { for (let x in this) yield this }` + +
Răspuns +

+ +#### Răspuns: C + +Obiectele nu sunt iterabile în mod implicit. Un obiect devine iterabil atunci când protocolul iterator este prezent. Putem adăuga acest protocol manual prin adăugarea simbolului iterator `[Symbol.iterator]`, care trebuie să returneze un obiect generator, de exemplu, prin definirea unei funcții generator `*[Symbol.iterator]() {}`. Această funcție generator trebuie să furnizeze `Object.values` ale obiectulu `person` pentru a obține array-ul `["Lydia Hallie", 21]`: `yield* Object.values(this)`. + +

+
+ +--- + +###### 145. Care este rezultatul? + +```javascript +let count = 0; +const nums = [0, 1, 2, 3]; + +nums.forEach(num => { + if (num) count += 1 +}) + +console.log(count) +``` + +- A: 1 +- B: 2 +- C: 3 +- D: 4 + +
Răspuns +

+ +#### Răspuns: C + +Condiția `if` din interiorul buclei `forEach` verifică dacă valoarea lui `num` este adevărată (truthy) sau falsă (falsy). Deoarece primul număr din array-ul `nums` este `0`, o valoare falsă, blocul de cod al instrucțiunii `if` nu va fi executat. `count` se incrementează doar pentru celelalte 3 numere din array-ul `nums`, adică `1`, `2` și `3`. Deoarece `count` se incrementează cu `1` de 3 ori, valoarea lui `count` este `3`. + +

+
+ +--- + +###### 146. Care este rezultatul? + +```javascript +function getFruit(fruits) { + console.log(fruits?.[1]?.[1]) +} + +getFruit([['🍊', '🍌'], ['🍍']]) +getFruit() +getFruit([['🍍'], ['🍊', '🍌']]) +``` + +- A: `null`, `undefined`, 🍌 +- B: `[]`, `null`, 🍌 +- C: `[]`, `[]`, 🍌 +- D: `undefined`, `undefined`, 🍌 + +
Răspuns +

+ +#### Răspuns: D + +Simbolul `?` ne permite să accesăm opțional proprietăți mai adânc în obiecte. Încercăm să înregistrăm elementul de pe indexul `1` din sub-array-ul de pe indexul `1` al array-ului `fruits`. Dacă sub-array-ul de pe indexul `1` din array-ul `fruits` nu există, va returna pur și simplu `undefined`. Dacă sub-array-ul de pe indexul `1` din array-ul `fruits` există, dar acest sub-array nu are un element pe indexul `1` va returna, de asemenea, `undefined`. + +În primul rând, încercăm să înregistrăm al doilea element din sub-array-ul`['🍍']` din `[['🍊', '🍌'], ['🍍']]`. Acest sub-array conține doar un singur element, ceea ce înseamnă că nu există niciun element pe indexul `1`, și va returna `undefined`. + +Apoi, apelăm funcția `getFruits` fără a transmite o valoare ca argument, ceea ce înseamnă că `fruits` are implicit o valoare de `undefined`. Deoarece facem o verificare condițională pentru accesarea elementului de pe indexul `1` al `fruits`, aceasta va returna `undefined` deoarece acest element de pe indexu `1` nu există. + +În cele din urmă, încercăm să înregistrăm al doilea element din sub-array-ul `['🍊', '🍌']` din `['🍍'], ['🍊', '🍌']`. Elementul de pe indexul `1` în acest sub-array este `🍌`, are este înregistrat. + +

+
+ +--- + +###### 147. Care este rezultatul? + +```javascript +class Calc { + constructor() { + this.count = 0 + } + + increase() { + this.count ++ + } +} + +const calc = new Calc() +new Calc().increase() + +console.log(calc.count) +``` + +- A: `0` +- B: `1` +- C: `undefined` +- D: `ReferenceError` + +
Răspuns +

+ +#### Răspuns: A + +Am setat variabila `calc` gal cu o nouă instanță a clasei `Calc`. Apoi, am creat o altă instanță nouă a clasei `Calc`, și am apelat metoda `increase` pe această instanță. Deoarece proprietatea `count` se află în constructorul clasei `Calc`, proprietatea `count` nu este partajată în prototipul clasei `Calc`. Acest lucru înseamnă că valoarea lui `count` nu a fost actualizată pentru instanța către care arată `calc` astfel încât `count` rămâne `0`. + +

+
+ +--- + +###### 148. Care este rezultatul? + +```javascript +const user = { + email: "e@mail.com", + password: "12345" +} + +const updateUser = ({ email, password }) => { + if (email) { + Object.assign(user, { email }) + } + + if (password) { + user.password = password + } + + return user +} + +const updatedUser = updateUser({ email: "new@email.com" }) + +console.log(updatedUser === user) +``` + +- A: `false` +- B: `true` +- C: `TypeError` +- D: `ReferenceError` + +
Răspuns +

+ +#### Răspuns: B + +Funcția `updateUser` actualizează valorile proprietăților `email` și `password` ale obiectului `user`, dacă aceste valori sunt transmise funcției, după care funcția returnează obiectul `user`. Valoarea returnată a funcției `updateUser` este obiectul `user`, ceea ce înseamnă că valoarea lui `updatedUser` este o referință către același obiect `user` la care face referință și `user`. `updatedUser === user` este egal cu `true`. + +

+
+ +--- + +###### 149. Care este rezultatul? + +```javascript +const fruit = ['🍌', '🍊', '🍎'] + +fruit.slice(0, 1) +fruit.splice(0, 1) +fruit.unshift('🍇') + +console.log(fruit) +``` + +- A: `['🍌', '🍊', '🍎']` +- B: `['🍊', '🍎']` +- C: `['🍇', '🍊', '🍎']` +- D: `['🍇', '🍌', '🍊', '🍎']` + +
Răspuns +

+ +#### Răspuns: C + +În primul rând, apelăm metoda `slice` pe array-ul `fruit`. Metoda `slice` nu modifică array-ul original, ci returnează valoarea pe care a tăiat-o din array: emoji-ul de banană. +Apoi, apelăm metoda `splice` pe array-ul `fruit`. Metoda `splice` modifică array-ul original, ceea ce înseamnă că array-ul `fruit` acum conține `['🍊', '🍎']`. +În cele din urmă, apelăm metoda `unshift` pe array-u `fruit`, care modifică array-ul original prin adăugarea valorii furnizate, în acest caz, ‘🍇’ ca prim element în array. Array-ul `fruit` acum conține `['🍇', '🍊', '🍎']`. + +

+
+ +--- + +###### 150. Care este rezultatul? + +```javascript +const animals = {}; +let dog = { emoji: '🐶' } +let cat = { emoji: '🐈' } + +animals[dog] = { ...dog, name: "Mara" } +animals[cat] = { ...cat, name: "Sara" } + +console.log(animals[dog]) +``` + +- A: `{ emoji: "🐶", name: "Mara" }` +- B: `{ emoji: "🐈", name: "Sara" }` +- C: `undefined` +- D: `ReferenceError` + +
Răspuns +

+ +#### Răspuns: B + +Cheile obiectelor sunt convertite în șiruri de caractere. + +Deoarece valoarea lui `dog` este un obiect, `animals[dog]` înseamnă de fapt că creăm o nouă proprietate numită `"object Object"` egală cu noul obiect. `animals["object Object"]` este acum egal cu `{ emoji: "🐶", name: "Mara"}`. + +`cat` este, de asemenea, un obiect, ceea ce înseamnă că `animals[cat]` înseamnă de fapt că suprascriem valoarea lui `animals["object Object"]` cu noile proprietăți ale pisicii. + +Înregistrarea `animals[dog]`, sau mai exact `animals["object Object"]` deoarece convertirea obiectului `dog` într-un șir rezultă în `"object Object"`, returnează `{ emoji: "🐈", name: "Sara" }`. + +

+
+ +--- + +###### 151. Care este rezultatul? + +```javascript +const user = { + email: "my@email.com", + updateEmail: email => { + this.email = email + } +} + +user.updateEmail("new@email.com") +console.log(user.email) +``` + +- A: `my@email.com` +- B: `new@email.com` +- C: `undefined` +- D: `ReferenceError` + +
Răspuns +

+ +#### Răspuns: A + +Funcția `updateEmail` este o funcție săgeată și nu este legată de obiectul `user`. Acest lucru înseamnă că cuvântul cheie `this` nu se referă la obiectul `user`, ci se referă la domeniul global în acest caz. Valoarea `email` din obiectul `user` nu se actualizează. Când se înregistrează valoarea `user.email`, se returnează valoarea originală `my@email.com`. + +

+
+ +--- + +###### 152. Care este rezultatul? + +```javascript +const promise1 = Promise.resolve('First') +const promise2 = Promise.resolve('Second') +const promise3 = Promise.reject('Third') +const promise4 = Promise.resolve('Fourth') + +const runPromises = async () => { + const res1 = await Promise.all([promise1, promise2]) + const res2 = await Promise.all([promise3, promise4]) + return [res1, res2] +} + +runPromises() + .then(res => console.log(res)) + .catch(err => console.log(err)) +``` + +- A: `[['First', 'Second'], ['Fourth']]` +- B: `[['First', 'Second'], ['Third', 'Fourth']]` +- C: `[['First', 'Second']]` +- D: `'Third'` + +
Răspuns +

+ +#### Răspuns: D + +Metoda `Promise.all` rulează promisiunile transmise în paralel. Dacă o promisiune eșuează, metoda `Promise.all` se _respinge_ cu valoarea promisiunii respinse. În acest caz, `promise3` a fost respinsă cu valoarea `"Third"`. Prindem valoarea respinsă în metoda `catch` lantată în invocarea `runPromises` pentru a prinde orice erori din interiorul funcției `runPromises`. Se înregistrează doar `"Third"` deoarece `promise3` a fost respinsă cu această valoare. + +

+
+ +--- + +###### 153. Ce valoare ar trebui să aibă `method` pentru a înregistra `{ name: "Lydia", age: 22 }`? + +```javascript +const keys = ["name", "age"] +const values = ["Lydia", 22] + +const method = /* ?? */ +Object[method](keys.map((_, i) => { + return [keys[i], values[i]] +})) // { name: "Lydia", age: 22 } +``` + +- A: `entries` +- B: `values` +- C: `fromEntries` +- D: `forEach` + +
Răspuns +

+ +#### Răspuns: C + +Metoda `fromEntries` transformă o matrice 2D într-un obiect. Primul element din fiecare submatrice va fi cheia, iar al doilea element din fiecare submatrice va fi valoarea. În acest caz, facem mapare peste matricea `keys` care returnează o matrice în care primul element este elementul din matricea cheilor la indexul curent, iar al doilea element este elementul din matricea valorilor la indexul curent. + +Acest lucru creează o matrice de submatrici care conțin cheile și valorile corecte, rezultând în `{ name: "Lydia", age: 22 }` + +

+
+ +--- + +###### 154. Care este rezultatul? + +```javascript +const createMember = ({ email, address = {}}) => { + const validEmail = /.+\@.+\..+/.test(email) + if (!validEmail) throw new Error("Valid email pls") + + return { + email, + address: address ? address : null + } +} + +const member = createMember({ email: "my@email.com" }) +console.log(member) +``` + +- A: `{ email: "my@email.com", address: null }` +- B: `{ email: "my@email.com" }` +- C: `{ email: "my@email.com", address: {} }` +- D: `{ email: "my@email.com", address: undefined }` + +
Răspuns +

+ +#### Răspuns: C + +Valoarea implicită a lui `address` este un obiect gol `{}`. Când setăm variabila `member` egală cu obiectul returnat de funcția `createMember`, nu am transmis o valoare pentru `address`, ceea ce înseamnă că valoarea lui `address` este obiectul gol implicit `{}`. Un obiect gol este o valoare adevărată (truthy), ceea ce înseamnă că condiția din expresia ternară `address ? address : null` returnează `true`. Prin urmare, valoarea lui `address` este obiectul gol `{}`. + +

+
+ +--- + +###### 155. Care este rezultatul? + +```javascript +let randomValue = { name: "Lydia" } +randomValue = 23 + +if (!typeof randomValue === "string") { + console.log("It's not a string!") +} else { + console.log("Yay it's a string!") +} +``` + +- A: `It's not a string!` +- B: `Yay it's a string!` +- C: `TypeError` +- D: `undefined` + +
Răspuns +

+ +#### Răspuns: B + +Condiția din instrucțiunea `if` verifică dacă valoarea lui `!typeof randomValue` este egală cu `"string"`. Operatorul `!` convertește valoarea la o valoare booleană. Dacă valoarea este adevărată (truthy), valoarea returnată va fi `false`, iar dacă valoarea este falsă (falsy), valoarea returnată va fi `true`. În acest caz, valoarea returnată de `typeof randomValue` este valoarea adevărată (truthy) `"number"`, ceea ce înseamnă că valoarea lui `!typeof randomValue` este valoarea booleană `false`. + +`!typeof randomValue === "string"` întotdeauna returnează `false`, deoarece de fapt verificăm `false === "string"`. Deoarece condiția returnează `false`, blocul de cod al instrucțiunii `else` se execută, iar `Yay it's a string!` este înregistrat. + +

+
\ No newline at end of file From 5d33c9163bb51fee479e536ee8eb1b3731299184 Mon Sep 17 00:00:00 2001 From: Jacob Herper Date: Sun, 10 Sep 2023 15:37:41 +0100 Subject: [PATCH 178/193] updated the repo introduction --- README.md | 641 +++++++++++++++++++++++++++--------------------------- 1 file changed, 322 insertions(+), 319 deletions(-) diff --git a/README.md b/README.md index 1b7a6f7a..76e834d5 100644 --- a/README.md +++ b/README.md @@ -1,23 +1,26 @@

JavaScript Questions

+
+ +> [!NOTE] +> This repo was created in 2019 and the questions provided here are therefore based on the JavaScript syntax and behaviour at that time. Since JavaScript is a constantly evolving language, there are newer language features that are not covered by the questions here. --- -I post multiple choice JavaScript questions on my [Instagram](https://www.instagram.com/theavocoder) **stories**, which I'll also post here! Last updated: June 12th +

+From basic to advanced: test how well you know JavaScript, refresh your knowledge a bit, or prepare for your coding interview! :muscle: :rocket: I update this repo regularly with new questions. I added the answers in the **collapsed sections** below the questions, simply click on them to expand it. It's just for fun, good luck! :heart:

-From basic to advanced: test how well you know JavaScript, refresh your knowledge a bit, or prepare for your coding interview! :muscle: :rocket: I update this repo regularly with new questions. I added the answers in the **collapsed sections** below the questions, simply click on them to expand it. It's just for fun, good luck! :heart:
+

Feel free to reach out to me! 😊

-Feel free to reach out to me! 😊
-Instagram || Twitter || LinkedIn || Blog - +

+ Instagram || Twitter || LinkedIn || Blog +

-| Feel free to use them in a project! 😃 I would _really_ appreciate a reference to this repo, I create the questions and explanations (yes I'm sad lol) and the community helps me so much to maintain and improve it! 💪🏼 Thank you and have fun! | -|---| +| Feel free to use them in a project! 😃 I would _really_ appreciate a reference to this repo, I create the questions and explanations (yes I'm sad lol) and the community helps me so much to maintain and improve it! 💪🏼 Thank you and have fun! | +| ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ---- - -
See 20 Available Translations 🇸🇦🇪🇬🇧🇦🇩🇪🇪🇸🇫🇷🇮🇩🇯🇵🇰🇷🇳🇱🇧🇷🇷🇺🇹🇭🇹🇷🇺🇦🇻🇳🇨🇳🇹🇼🇽🇰 +
See 20 Available Translations 🇸🇦🇪🇬🇧🇦🇩🇪🇪🇸🇫🇷🇮🇩🇯🇵🇰🇷🇳🇱🇧🇷🇷🇺🇹🇭🇹🇷🇺🇦🇻🇳🇨🇳🇹🇼🇽🇰

- [🇸🇦 العربية](./ar-AR/README_AR.md) @@ -54,7 +57,7 @@ Feel free to reach out to me! 😊
function sayHi() { console.log(name); console.log(age); - var name = 'Lydia'; + var name = "Lydia"; let age = 21; } @@ -150,7 +153,7 @@ There is no value `radius` on that object, which returns `NaN`. ```javascript +true; -!'Lydia'; +!"Lydia"; ``` - A: `1` and `false` @@ -175,11 +178,11 @@ The string `'Lydia'` is a truthy value. What we're actually asking, is "is this ```javascript const bird = { - size: 'small', + size: "small", }; const mouse = { - name: 'Mickey', + name: "Mickey", small: true, }; ``` @@ -210,11 +213,11 @@ However, with dot notation, this doesn't happen. `mouse` does not have a key cal ###### 6. What's the output? ```javascript -let c = { greeting: 'Hey!' }; +let c = { greeting: "Hey!" }; let d; d = c; -c.greeting = 'Hello'; +c.greeting = "Hello"; console.log(d.greeting); ``` @@ -284,13 +287,13 @@ class Chameleon { return this.newColor; } - constructor({ newColor = 'green' } = {}) { + constructor({ newColor = "green" } = {}) { this.newColor = newColor; } } -const freddie = new Chameleon({ newColor: 'purple' }); -console.log(freddie.colorChange('orange')); +const freddie = new Chameleon({ newColor: "purple" }); +console.log(freddie.colorChange("orange")); ``` - A: `orange` @@ -345,10 +348,10 @@ In order to avoid this, we can use `"use strict"`. This makes sure that you have ```javascript function bark() { - console.log('Woof!'); + console.log("Woof!"); } -bark.animal = 'dog'; +bark.animal = "dog"; ``` - A: Nothing, this is totally fine! @@ -378,8 +381,8 @@ function Person(firstName, lastName) { this.lastName = lastName; } -const member = new Person('Lydia', 'Hallie'); -Person.getFullName = function() { +const member = new Person("Lydia", "Hallie"); +Person.getFullName = function () { return `${this.firstName} ${this.lastName}`; }; @@ -396,12 +399,12 @@ console.log(member.getFullName()); #### Answer: A -In JavaScript, functions are objects, and therefore, the method `getFullName` gets added to the constructor function object itself. For that reason, we can call `Person.getFullName()`, but `member.getFullName` throws a `TypeError`. +In JavaScript, functions are objects, and therefore, the method `getFullName` gets added to the constructor function object itself. For that reason, we can call `Person.getFullName()`, but `member.getFullName` throws a `TypeError`. If you want a method to be available to all object instances, you have to add it to the prototype property: ```js -Person.prototype.getFullName = function() { +Person.prototype.getFullName = function () { return `${this.firstName} ${this.lastName}`; }; ``` @@ -419,8 +422,8 @@ function Person(firstName, lastName) { this.lastName = lastName; } -const lydia = new Person('Lydia', 'Hallie'); -const sarah = Person('Sarah', 'Smith'); +const lydia = new Person("Lydia", "Hallie"); +const sarah = Person("Sarah", "Smith"); console.log(lydia); console.log(sarah); @@ -490,7 +493,7 @@ function sum(a, b) { return a + b; } -sum(1, '2'); +sum(1, "2"); ``` - A: `NaN` @@ -557,7 +560,7 @@ function getPersonInfo(one, two, three) { console.log(three); } -const person = 'Lydia'; +const person = "Lydia"; const age = 21; getPersonInfo`${person} is ${age} years old`; @@ -584,9 +587,9 @@ If you use tagged template literals, the value of the first argument is always a ```javascript function checkAge(data) { if (data === { age: 18 }) { - console.log('You are an adult!'); + console.log("You are an adult!"); } else if (data == { age: 18 }) { - console.log('You are still an adult.'); + console.log("You are still an adult."); } else { console.log(`Hmm.. You don't have an age I guess`); } @@ -646,7 +649,7 @@ The rest parameter (`...args`) lets us "collect" all remaining arguments into an ```javascript function getAge() { - 'use strict'; + "use strict"; age = 21; console.log(age); } @@ -674,7 +677,7 @@ With `"use strict"`, you can make sure that you don't accidentally declare globa ###### 21. What's the value of `sum`? ```javascript -const sum = eval('10*10+5'); +const sum = eval("10*10+5"); ``` - A: `105` @@ -697,7 +700,7 @@ const sum = eval('10*10+5'); ###### 22. How long is cool_secret accessible? ```javascript -sessionStorage.setItem('cool_secret', 123); +sessionStorage.setItem("cool_secret", 123); ``` - A: Forever, the data doesn't get lost. @@ -750,12 +753,12 @@ You cannot do this with `let` or `const` since they're block-scoped. ###### 24. What's the output? ```javascript -const obj = { 1: 'a', 2: 'b', 3: 'c' }; +const obj = { 1: "a", 2: "b", 3: "c" }; const set = new Set([1, 2, 3, 4, 5]); -obj.hasOwnProperty('1'); +obj.hasOwnProperty("1"); obj.hasOwnProperty(1); -set.has('1'); +set.has("1"); set.has(1); ``` @@ -781,7 +784,7 @@ It doesn't work that way for a set. There is no `'1'` in our set: `set.has('1')` ###### 25. What's the output? ```javascript -const obj = { a: 'one', b: 'two', a: 'three' }; +const obj = { a: "one", b: "two", a: "three" }; console.log(obj); ``` @@ -850,12 +853,12 @@ The `continue` statement skips an iteration if a certain condition returns `true ```javascript String.prototype.giveLydiaPizza = () => { - return 'Just give Lydia pizza already!'; + return "Just give Lydia pizza already!"; }; -const name = 'Lydia'; +const name = "Lydia"; -console.log(name.giveLydiaPizza()) +console.log(name.giveLydiaPizza()); ``` - A: `"Just give Lydia pizza already!"` @@ -879,8 +882,8 @@ console.log(name.giveLydiaPizza()) ```javascript const a = {}; -const b = { key: 'b' }; -const c = { key: 'c' }; +const b = { key: "b" }; +const c = { key: "c" }; a[b] = 123; a[c] = 456; @@ -912,9 +915,9 @@ Then, we log `a[b]`, which is actually `a["[object Object]"]`. We just set that ###### 30. What's the output? ```javascript -const foo = () => console.log('First'); -const bar = () => setTimeout(() => console.log('Second')); -const baz = () => console.log('Third'); +const foo = () => console.log("First"); +const bar = () => setTimeout(() => console.log("Second")); +const baz = () => console.log("Third"); bar(); foo(); @@ -967,9 +970,7 @@ This is where an event loop starts to work. An **event loop** looks at the stack ```html

- +
``` @@ -995,9 +996,7 @@ The deepest nested element that caused the event is the target of the event. You ```html
-

- Click here! -

+

Click here!

``` @@ -1021,7 +1020,7 @@ If we click `p`, we see two logs: `p` and `div`. During event propagation, there ###### 33. What's the output? ```javascript -const person = { name: 'Lydia' }; +const person = { name: "Lydia" }; function sayHi(age) { return `${this.name} is ${age}`; @@ -1071,7 +1070,6 @@ console.log(typeof sayHi()); #### Answer: B The `sayHi` function returns the returned value of the immediately invoked function expression (IIFE). This function returned `0`, which is type `"number"`. - FYI: `typeof` can return the following list of values: `undefined`, `boolean`, `number`, `bigint`, `string`, `symbol`, `function` and `object`. Note that `typeof null` returns `"object"`.

@@ -1084,8 +1082,8 @@ FYI: `typeof` can return the following list of values: `undefined`, `boolean`, ` ```javascript 0; new Number(0); -(''); -(' '); +(""); +(" "); new Boolean(false); undefined; ``` @@ -1234,11 +1232,14 @@ What differentiates a primitive from an object is that primitives do not have an ###### 40. What's the output? ```javascript -[[0, 1], [2, 3]].reduce( +[ + [0, 1], + [2, 3], +].reduce( (acc, cur) => { return acc.concat(cur); }, - [1, 2], + [1, 2] ); ``` @@ -1265,7 +1266,7 @@ Then, `[1, 2, 0, 1]` is `acc` and `[2, 3]` is `cur`. We concatenate them, and ge ```javascript !!null; -!!''; +!!""; !!1; ``` @@ -1293,7 +1294,7 @@ Then, `[1, 2, 0, 1]` is `acc` and `[2, 3]` is `cur`. We concatenate them, and ge ###### 42. What does the `setInterval` method return in the browser? ```javascript -setInterval(() => console.log('Hi'), 1000); +setInterval(() => console.log("Hi"), 1000); ``` - A: a unique id @@ -1316,7 +1317,7 @@ It returns a unique id. This id can be used to clear that interval with the `cle ###### 43. What does this return? ```javascript -[...'Lydia']; +[..."Lydia"]; ``` - A: `["L", "y", "d", "i", "a"]` @@ -1375,14 +1376,14 @@ Then, we invoke the function again with the `next()` method. It starts to contin ```javascript const firstPromise = new Promise((res, rej) => { - setTimeout(res, 500, 'one'); + setTimeout(res, 500, "one"); }); const secondPromise = new Promise((res, rej) => { - setTimeout(res, 100, 'two'); + setTimeout(res, 100, "two"); }); -Promise.race([firstPromise, secondPromise]).then(res => console.log(res)); +Promise.race([firstPromise, secondPromise]).then((res) => console.log(res)); ``` - A: `"one"` @@ -1405,7 +1406,7 @@ When we pass multiple promises to the `Promise.race` method, it resolves/rejects ###### 46. What's the output? ```javascript -let person = { name: 'Lydia' }; +let person = { name: "Lydia" }; const members = [person]; person = null; @@ -1445,7 +1446,7 @@ We are only modifying the value of the `person` variable, and not the first elem ```javascript const person = { - name: 'Lydia', + name: "Lydia", age: 21, }; @@ -1474,7 +1475,7 @@ With a `for-in` loop, we can iterate through object keys, in this case `name` an ###### 48. What's the output? ```javascript -console.log(3 + 4 + '5'); +console.log(3 + 4 + "5"); ``` - A: `"345"` @@ -1501,7 +1502,7 @@ Operator associativity is the order in which the compiler evaluates the expressi ###### 49. What's the value of `num`? ```javascript -const num = parseInt('7*6', 10); +const num = parseInt("7*6", 10); ``` - A: `42` @@ -1526,8 +1527,8 @@ Only the first numbers in the string is returned. Based on the _radix_ (the seco ###### 50. What's the output? ```javascript -[1, 2, 3].map(num => { - if (typeof num === 'number') return; +[1, 2, 3].map((num) => { + if (typeof num === "number") return; return num * 2; }); ``` @@ -1555,12 +1556,12 @@ However, we don’t return a value. When we don’t return a value from the func ```javascript function getInfo(member, year) { - member.name = 'Lydia'; - year = '1998'; + member.name = "Lydia"; + year = "1998"; } -const person = { name: 'Sarah' }; -const birthYear = '1997'; +const person = { name: "Sarah" }; +const birthYear = "1997"; getInfo(person, birthYear); @@ -1592,15 +1593,15 @@ The value of `person` is an object. The argument `member` has a (copied) referen ```javascript function greeting() { - throw 'Hello world!'; + throw "Hello world!"; } function sayHi() { try { const data = greeting(); - console.log('It worked!', data); + console.log("It worked!", data); } catch (e) { - console.log('Oh no an error:', e); + console.log("Oh no an error:", e); } } @@ -1630,8 +1631,8 @@ With the `catch` statement, we can specify what to do if an exception is thrown ```javascript function Car() { - this.make = 'Lamborghini'; - return { make: 'Maserati' }; + this.make = "Lamborghini"; + return { make: "Maserati" }; } const myCar = new Car(); @@ -1705,11 +1706,11 @@ class Dog { } } -Dog.prototype.bark = function() { +Dog.prototype.bark = function () { console.log(`Woof I am ${this.name}`); }; -const pet = new Dog('Mara'); +const pet = new Dog("Mara"); pet.bark(); @@ -1774,7 +1775,7 @@ export default counter; ```javascript // index.js -import myCounter from './counter'; +import myCounter from "./counter"; myCounter += 1; @@ -1803,7 +1804,7 @@ When we try to increment the value of `myCounter`, it throws an error: `myCounte ###### 58. What's the output? ```javascript -const name = 'Lydia'; +const name = "Lydia"; age = 21; console.log(delete name); @@ -1874,7 +1875,7 @@ This means that the value of `y` is equal to the first value in the array, which ###### 60. What's the output? ```javascript -const user = { name: 'Lydia', age: 21 }; +const user = { name: "Lydia", age: 21 }; const admin = { admin: true, ...user }; console.log(admin); @@ -1900,9 +1901,9 @@ It's possible to combine objects using the spread operator `...`. It lets you cr ###### 61. What's the output? ```javascript -const person = { name: 'Lydia' }; +const person = { name: "Lydia" }; -Object.defineProperty(person, 'age', { value: 21 }); +Object.defineProperty(person, "age", { value: 21 }); console.log(person); console.log(Object.keys(person)); @@ -1931,12 +1932,12 @@ Properties added using the `defineProperty` method are immutable by default. You ```javascript const settings = { - username: 'lydiahallie', + username: "lydiahallie", level: 19, health: 90, }; -const data = JSON.stringify(settings, ['level', 'health']); +const data = JSON.stringify(settings, ["level", "health"]); console.log(data); ``` @@ -1967,7 +1968,7 @@ If the replacer is a _function_, this function gets called on every property in let num = 10; const increaseNumber = () => num++; -const increasePassedNumber = number => number++; +const increasePassedNumber = (number) => number++; const num1 = increaseNumber(); const num2 = increasePassedNumber(num1); @@ -2124,12 +2125,12 @@ The `Labrador` class receives two arguments, `name` since it extends `Dog`, and ```javascript // index.js -console.log('running index.js'); -import { sum } from './sum.js'; +console.log("running index.js"); +import { sum } from "./sum.js"; console.log(sum(1, 2)); // sum.js -console.log('running sum.js'); +console.log("running sum.js"); export const sum = (a, b) => a + b; ``` @@ -2157,7 +2158,7 @@ This is a difference between `require()` in CommonJS and `import`! With `require ```javascript console.log(Number(2) === Number(2)); console.log(Boolean(false) === Boolean(false)); -console.log(Symbol('foo') === Symbol('foo')); +console.log(Symbol("foo") === Symbol("foo")); ``` - A: `true`, `true`, `false` @@ -2180,7 +2181,7 @@ Every Symbol is entirely unique. The purpose of the argument passed to the Symbo ###### 69. What's the output? ```javascript -const name = 'Lydia Hallie'; +const name = "Lydia Hallie"; console.log(name.padStart(13)); console.log(name.padStart(2)); ``` @@ -2207,7 +2208,7 @@ If the argument passed to the `padStart` method is smaller than the length of th ###### 70. What's the output? ```javascript -console.log('🥑' + '💻'); +console.log("🥑" + "💻"); ``` - A: `"🥑💻"` @@ -2231,11 +2232,11 @@ With the `+` operator, you can concatenate strings. In this case, we are concate ```javascript function* startGame() { - const answer = yield 'Do you love JavaScript?'; - if (answer !== 'Yes') { + const answer = yield "Do you love JavaScript?"; + if (answer !== "Yes") { return "Oh wow... Guess we're done here"; } - return 'JavaScript loves you back ❤️'; + return "JavaScript loves you back ❤️"; } const game = startGame(); @@ -2303,7 +2304,7 @@ In this case, the string is `Hello\nworld`, which gets logged. ```javascript async function getData() { - return await Promise.resolve('I made it!'); + return await Promise.resolve("I made it!"); } const data = getData(); @@ -2340,7 +2341,7 @@ function addToList(item, list) { return list.push(item); } -const result = addToList('apple', ['banana']); +const result = addToList("apple", ["banana"]); console.log(result); ``` @@ -2400,7 +2401,7 @@ Since `shape` is frozen, and since the value of `x` is not an object, we cannot ###### 76. What's the output? ```javascript -const { firstName: myName } = { firstName: 'Lydia' }; +const { firstName: myName } = { firstName: "Lydia" }; console.log(firstName); ``` @@ -2418,7 +2419,7 @@ console.log(firstName); By using [destructuring assignment](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment) syntax we can unpack values from arrays, or properties from objects, into distinct variables: ```javascript -const { firstName } = { firstName: 'Lydia' }; +const { firstName } = { firstName: "Lydia" }; // ES5 version: // var firstName = { firstName: 'Lydia' }.firstName; @@ -2428,7 +2429,7 @@ console.log(firstName); // "Lydia" Also, a property can be unpacked from an object and assigned to a variable with a different name than the object property: ```javascript -const { firstName: myName } = { firstName: 'Lydia' }; +const { firstName: myName } = { firstName: "Lydia" }; // ES5 version: // var myName = { firstName: 'Lydia' }.firstName; @@ -2441,12 +2442,11 @@ Therefore, `firstName` does not exist as a variable, thus attempting to access i **Note:** Be aware of the `global scope` properties: ```javascript -const { name: myName } = { name: 'Lydia' }; +const { name: myName } = { name: "Lydia" }; console.log(myName); // "lydia" console.log(name); // "" ----- Browser e.g. Chrome console.log(name); // ReferenceError: name is not defined ----- NodeJS - ``` Whenever Javascript is unable to find a variable within the _current scope_, it climbs up the [Scope chain](https://github.com/getify/You-Dont-Know-JS/blob/2nd-ed/scope-closures/ch3.md) and searches for it and if it reaches the top-level scope, aka **Global scope**, and still doesn't find it, it will throw a `ReferenceError`. @@ -2490,7 +2490,7 @@ The `sum` function always returns the same result. If we pass `1` and `2`, it wi ```javascript const add = () => { const cache = {}; - return num => { + return (num) => { if (num in cache) { return `From cache! ${cache[num]}`; } else { @@ -2535,7 +2535,7 @@ The third time, we pass `5 * 2` to the function which gets evaluated to `10`. Th ###### 79. What is the output? ```javascript -const myLifeSummedUp = ['☕', '💻', '🍷', '🍫']; +const myLifeSummedUp = ["☕", "💻", "🍷", "🍫"]; for (let item in myLifeSummedUp) { console.log(item); @@ -2631,13 +2631,13 @@ In this case, if we didn't pass a value or if we passed `undefined`, `name` woul ###### 82. What is the output? ```javascript -var status = '😎'; +var status = "😎"; setTimeout(() => { - const status = '😍'; + const status = "😍"; const data = { - status: '🥑', + status: "🥑", getStatus() { return this.status; }, @@ -2671,12 +2671,12 @@ With the `call` method, we can change the object to which the `this` keyword ref ```javascript const person = { - name: 'Lydia', + name: "Lydia", age: 21, }; let city = person.city; -city = 'Amsterdam'; +city = "Amsterdam"; console.log(person); ``` @@ -2740,9 +2740,9 @@ Variables with the `const` and `let` keyword are _block-scoped_. A block is anyt ###### 85. What kind of information would get logged? ```javascript -fetch('https://www.website.com/api/user/1') - .then(res => res.json()) - .then(res => console.log(res)); +fetch("https://www.website.com/api/user/1") + .then((res) => res.json()) + .then((res) => console.log(res)); ``` - A: The result of the `fetch` method. @@ -2796,7 +2796,7 @@ By setting `hasName` equal to `name`, you set `hasName` equal to whatever value ###### 87. What's the output? ```javascript -console.log('I want pizza'[0]); +console.log("I want pizza"[0]); ``` - A: `"""` @@ -2851,11 +2851,11 @@ If you're trying to set a default parameter's value equal to a parameter which i ```javascript // module.js -export default () => 'Hello world'; -export const name = 'Lydia'; +export default () => "Hello world"; +export const name = "Lydia"; // index.js -import * as data from './module'; +import * as data from "./module"; console.log(data); ``` @@ -2888,7 +2888,7 @@ class Person { } } -const member = new Person('John'); +const member = new Person("John"); console.log(typeof member); ``` @@ -2948,7 +2948,7 @@ Then, we try to use the `.push` method on `newList`. Since `newList` is the nume ```javascript function giveLydiaPizza() { - return 'Here is pizza!'; + return "Here is pizza!"; } const giveLydiaChocolate = () => @@ -2979,7 +2979,7 @@ Regular functions, such as the `giveLydiaPizza` function, have a `prototype` pro ```javascript const person = { - name: 'Lydia', + name: "Lydia", age: 21, }; @@ -3039,7 +3039,7 @@ function getItems(fruitList, favoriteFruit, ...args) { return [...fruitList, ...args, favoriteFruit]; } -getItems(['banana', 'apple'], 'pear', 'orange'); +getItems(["banana", "apple"], "pear", "orange"); ``` The above example works. This returns the array `[ 'banana', 'apple', 'orange', 'pear' ]` @@ -3053,9 +3053,9 @@ The above example works. This returns the array `[ 'banana', 'apple', 'orange', ```javascript function nums(a, b) { - if (a > b) console.log('a is bigger'); - else console.log('b is bigger'); - return + if (a > b) console.log("a is bigger"); + else console.log("b is bigger"); + return; a + b; } @@ -3094,13 +3094,13 @@ This means that `a + b` is never reached, since a function stops running after t ```javascript class Person { constructor() { - this.name = 'Lydia'; + this.name = "Lydia"; } } Person = class AnotherPerson { constructor() { - this.name = 'Sarah'; + this.name = "Sarah"; } }; @@ -3129,7 +3129,7 @@ We can set classes equal to other classes/function constructors. In this case, w ```javascript const info = { - [Symbol('a')]: 'b', + [Symbol("a")]: "b", }; console.log(info); @@ -3184,7 +3184,7 @@ The `getList` function receives an array as its argument. Between the parenthese With the rest parameter `...y`, we put all "remaining" arguments in an array. The remaining arguments are `2`, `3` and `4` in this case. The value of `y` is an array, containing all the rest parameters. The value of `x` is equal to `1` in this case, so when we log `[x, y]`, `[1, [2, 3, 4]]` gets logged. -The `getUser` function receives an object. With arrow functions, we don't _have_ to write curly brackets if we just return one value. However, if you want to instantly return an _object_ from an arrow function, you have to write it between parentheses, otherwise everything between the two braces will be interpreted as a block statement. In this case the code between the braces is not a valid JavaScript code, so a `SyntaxError` gets thrown. +The `getUser` function receives an object. With arrow functions, we don't _have_ to write curly brackets if we just return one value. However, if you want to instantly return an _object_ from an arrow function, you have to write it between parentheses, otherwise everything between the two braces will be interpreted as a block statement. In this case the code between the braces is not a valid JavaScript code, so a `SyntaxError` gets thrown. The following function would have returned an object: @@ -3198,7 +3198,7 @@ The following function would have returned an object: ###### 99. What's the output? ```javascript -const name = 'Lydia'; +const name = "Lydia"; console.log(name()); ``` @@ -3230,8 +3230,8 @@ ReferenceErrors get thrown when JavaScript isn't able to find a reference to a v ```javascript // 🎉✨ This is my 100th question! ✨🎉 -const output = `${[] && 'Im'}possible! -You should${'' && `n't`} see a therapist after so much JavaScript lol`; +const output = `${[] && "Im"}possible! +You should${"" && `n't`} see a therapist after so much JavaScript lol`; ``` - A: `possible! You should see a therapist after so much JavaScript lol` @@ -3257,7 +3257,7 @@ You should${'' && `n't`} see a therapist after so much JavaScript lol`; ```javascript const one = false || {} || null; -const two = null || false || ''; +const two = null || false || ""; const three = [] || 0 || true; console.log(one, two, three); @@ -3289,16 +3289,16 @@ With the `||` operator, we can return the first truthy operand. If all values ar ###### 102. What's the value of output? ```javascript -const myPromise = () => Promise.resolve('I have resolved!'); +const myPromise = () => Promise.resolve("I have resolved!"); function firstFunction() { - myPromise().then(res => console.log(res)); - console.log('second'); + myPromise().then((res) => console.log(res)); + console.log("second"); } async function secondFunction() { console.log(await myPromise()); - console.log('second'); + console.log("second"); } firstFunction(); @@ -3336,8 +3336,8 @@ This means that it waited for the `myPromise` to resolve with the value `I have const set = new Set(); set.add(1); -set.add('Lydia'); -set.add({ name: 'Lydia' }); +set.add("Lydia"); +set.add({ name: "Lydia" }); for (let item of set) { console.log(item + 2); @@ -3397,13 +3397,13 @@ In this case, we just passed the numerical value `5`. It returns a resolved prom ```javascript function compareMembers(person1, person2 = person) { if (person1 !== person2) { - console.log('Not the same!'); + console.log("Not the same!"); } else { - console.log('They are the same!'); + console.log("They are the same!"); } } -const person = { name: 'Lydia' }; +const person = { name: "Lydia" }; compareMembers(person); ``` @@ -3442,7 +3442,7 @@ const colorConfig = { yellow: false, }; -const colors = ['pink', 'red', 'blue']; +const colors = ["pink", "red", "blue"]; console.log(colorConfig.colors[1]); ``` @@ -3471,7 +3471,7 @@ JavaScript interprets (or unboxes) statements. When we use bracket notation, it ###### 107. What's its value? ```javascript -console.log('❤️' === '❤️'); +console.log("❤️" === "❤️"); ``` - A: `true` @@ -3492,14 +3492,14 @@ Under the hood, emojis are unicodes. The unicodes for the heart emoji is `"U+276 ###### 108. Which of these methods modifies the original array? ```javascript -const emojis = ['✨', '🥑', '😍']; +const emojis = ["✨", "🥑", "😍"]; -emojis.map(x => x + '✨'); -emojis.filter(x => x !== '🥑'); -emojis.find(x => x !== '🥑'); -emojis.reduce((acc, cur) => acc + '✨'); -emojis.slice(1, 2, '✨'); -emojis.splice(1, 2, '✨'); +emojis.map((x) => x + "✨"); +emojis.filter((x) => x !== "🥑"); +emojis.find((x) => x !== "🥑"); +emojis.reduce((acc, cur) => acc + "✨"); +emojis.slice(1, 2, "✨"); +emojis.splice(1, 2, "✨"); ``` - A: `All of them` @@ -3524,10 +3524,10 @@ With `splice` method, we modify the original array by deleting, replacing or add ###### 109. What's the output? ```javascript -const food = ['🍕', '🍫', '🥑', '🍔']; +const food = ["🍕", "🍫", "🥑", "🍔"]; const info = { favoriteFood: food[0] }; -info.favoriteFood = '🍝'; +info.favoriteFood = "🍝"; console.log(food); ``` @@ -3581,7 +3581,7 @@ const jsonArray = JSON.stringify([1, 2, 3]); // '[1, 2, 3]' JSON.parse(jsonArray); // [1, 2, 3] // Stringifying an object into valid JSON, then parsing the JSON string to a JavaScript value: -const jsonArray = JSON.stringify({ name: 'Lydia' }); // '{"name":"Lydia"}' +const jsonArray = JSON.stringify({ name: "Lydia" }); // '{"name":"Lydia"}' JSON.parse(jsonArray); // { name: 'Lydia' } ``` @@ -3593,11 +3593,11 @@ JSON.parse(jsonArray); // { name: 'Lydia' } ###### 111. What's the output? ```javascript -let name = 'Lydia'; +let name = "Lydia"; function getName() { console.log(name); - let name = 'Sarah'; + let name = "Sarah"; } getName(); @@ -3620,7 +3620,7 @@ Variables with the `let` keyword (and `const`) are hoisted, but unlike `var`, do If we wouldn't have declared the `name` variable within the `getName` function, the javascript engine would've looked down the _scope chain_. The outer scope has a variable called `name` with the value of `Lydia`. In that case, it would've logged `Lydia`. ```javascript -let name = 'Lydia'; +let name = "Lydia"; function getName() { console.log(name); @@ -3638,11 +3638,11 @@ getName(); // Lydia ```javascript function* generatorOne() { - yield ['a', 'b', 'c']; + yield ["a", "b", "c"]; } function* generatorTwo() { - yield* ['a', 'b', 'c']; + yield* ["a", "b", "c"]; } const one = generatorOne(); @@ -3688,7 +3688,7 @@ console.log(two.next().value); // undefined ###### 113. What's the output? ```javascript -console.log(`${(x => x)('I love')} to program`); +console.log(`${((x) => x)("I love")} to program`); ``` - A: `I love to program` @@ -3713,7 +3713,7 @@ Expressions within template literals are evaluated first. This means that the st ```javascript let config = { alert: setInterval(() => { - console.log('Alert!'); + console.log("Alert!"); }, 1000), }; @@ -3730,9 +3730,9 @@ config = null; #### Answer: C -Normally when we set objects equal to `null`, those objects get _garbage collected_ as there is no reference anymore to that object. However, since the callback function within `setInterval` is an arrow function (thus bound to the `config` object), the callback function still holds a reference to the `config` object. -As long as there is a reference, the object won't get garbage collected. -Since this is an interval, setting `config` to `null` or `delete`-ing `config.alert` won't garbage-collect the interval, so the interval will still be called. +Normally when we set objects equal to `null`, those objects get _garbage collected_ as there is no reference anymore to that object. However, since the callback function within `setInterval` is an arrow function (thus bound to the `config` object), the callback function still holds a reference to the `config` object. +As long as there is a reference, the object won't get garbage collected. +Since this is an interval, setting `config` to `null` or `delete`-ing `config.alert` won't garbage-collect the interval, so the interval will still be called. It should be cleared with `clearInterval(config.alert)` to remove it from memory. Since it was not cleared, the `setInterval` callback function will still get invoked every 1000ms (1s). @@ -3745,16 +3745,16 @@ Since it was not cleared, the `setInterval` callback function will still get inv ```javascript const myMap = new Map(); -const myFunc = () => 'greeting'; +const myFunc = () => "greeting"; -myMap.set(myFunc, 'Hello world!'); +myMap.set(myFunc, "Hello world!"); //1 -myMap.get('greeting'); +myMap.get("greeting"); //2 myMap.get(myFunc); //3 -myMap.get(() => 'greeting'); +myMap.get(() => "greeting"); ``` - A: 1 @@ -3781,14 +3781,14 @@ When adding a key/value pair using the `set` method, the key will be the value o ```javascript const person = { - name: 'Lydia', + name: "Lydia", age: 21, }; const changeAge = (x = { ...person }) => (x.age += 1); const changeAgeAndName = (x = { ...person }) => { x.age += 1; - x.name = 'Sarah'; + x.name = "Sarah"; }; changeAge(person); @@ -3847,7 +3847,7 @@ With the spread operator `...`, we can _spread_ iterables to individual elements ```javascript let num = 1; -const list = ['🥳', '🤠', '🥰', '🤪']; +const list = ["🥳", "🤠", "🥰", "🤪"]; console.log(list[(num += 1)]); ``` @@ -3873,11 +3873,11 @@ With the `+=` operand, we're incrementing the value of `num` by `1`. `num` had t ```javascript const person = { - firstName: 'Lydia', - lastName: 'Hallie', + firstName: "Lydia", + lastName: "Hallie", pet: { - name: 'Mara', - breed: 'Dutch Tulip Hound', + name: "Mara", + breed: "Dutch Tulip Hound", }, getFullName() { return `${this.firstName} ${this.lastName}`; @@ -3915,10 +3915,10 @@ With the optional chaining operator `?.`, we no longer have to explicitly check ###### 120. What's the output? ```javascript -const groceries = ['banana', 'apple', 'peanuts']; +const groceries = ["banana", "apple", "peanuts"]; -if (groceries.indexOf('banana')) { - console.log('We have to buy bananas!'); +if (groceries.indexOf("banana")) { + console.log("We have to buy bananas!"); } else { console.log(`We don't have to buy bananas!`); } @@ -3974,10 +3974,10 @@ The `language` method is a `setter`. Setters don't hold an actual value, their p ###### 122. What's the output? ```javascript -const name = 'Lydia Hallie'; +const name = "Lydia Hallie"; -console.log(!typeof name === 'object'); -console.log(!typeof name === 'string'); +console.log(!typeof name === "object"); +console.log(!typeof name === "string"); ``` - A: `false` `true` @@ -4002,7 +4002,7 @@ console.log(!typeof name === 'string'); ###### 123. What's the output? ```javascript -const add = x => y => z => { +const add = (x) => (y) => (z) => { console.log(x, y, z); return x + y + z; }; @@ -4092,20 +4092,20 @@ myFunc(1, 2, 3); ```javascript function getFine(speed, amount) { - const formattedSpeed = new Intl.NumberFormat('en-US', { - style: 'unit', - unit: 'mile-per-hour' + const formattedSpeed = new Intl.NumberFormat("en-US", { + style: "unit", + unit: "mile-per-hour", }).format(speed); - const formattedAmount = new Intl.NumberFormat('en-US', { - style: 'currency', - currency: 'USD' + const formattedAmount = new Intl.NumberFormat("en-US", { + style: "currency", + currency: "USD", }).format(amount); return `The driver drove ${formattedSpeed} and has to pay ${formattedAmount}`; } -console.log(getFine(130, 300)) +console.log(getFine(130, 300)); ``` - A: The driver drove 130 and has to pay 300 @@ -4128,8 +4128,8 @@ With the `Intl.NumberFormat` method, we can format numeric values to any locale. ###### 127. What's the output? ```javascript -const spookyItems = ['👻', '🎃', '🕸']; -({ item: spookyItems[3] } = { item: '💀' }); +const spookyItems = ["👻", "🎃", "🕸"]; +({ item: spookyItems[3] } = { item: "💀" }); console.log(spookyItems); ``` @@ -4154,7 +4154,7 @@ By destructuring objects, we can unpack values from the right-hand object, and a ###### 128. What's the output? ```javascript -const name = 'Lydia Hallie'; +const name = "Lydia Hallie"; const age = 21; console.log(Number.isNaN(name)); @@ -4190,7 +4190,7 @@ const randomValue = 21; function getInfo() { console.log(typeof randomValue); - const randomValue = 'Lydia Hallie'; + const randomValue = "Lydia Hallie"; } getInfo(); @@ -4216,7 +4216,7 @@ Variables declared with the `const` keyword are not referenceable before their i ###### 130. What's the output? ```javascript -const myPromise = Promise.resolve('Woah some cool data'); +const myPromise = Promise.resolve("Woah some cool data"); (async () => { try { @@ -4224,7 +4224,7 @@ const myPromise = Promise.resolve('Woah some cool data'); } catch { throw new Error(`Oops didn't work`); } finally { - console.log('Oh finally!'); + console.log("Oh finally!"); } })(); ``` @@ -4249,7 +4249,7 @@ In the `try` block, we're logging the awaited value of the `myPromise` variable: ###### 131. What's the output? ```javascript -const emojis = ['🥑', ['✨', '✨', ['🍕', '🍕']]]; +const emojis = ["🥑", ["✨", "✨", ["🍕", "🍕"]]]; console.log(emojis.flat(1)); ``` @@ -4322,19 +4322,19 @@ We invoke `counterTwo.increment()`, which sets `count` to `3`. Then, we log the ###### 133. What's the output? ```javascript -const myPromise = Promise.resolve(Promise.resolve('Promise')); +const myPromise = Promise.resolve(Promise.resolve("Promise")); function funcOne() { - setTimeout(() => console.log('Timeout 1!'), 0); - myPromise.then(res => res).then(res => console.log(`${res} 1!`)); - console.log('Last line 1!'); + setTimeout(() => console.log("Timeout 1!"), 0); + myPromise.then((res) => res).then((res) => console.log(`${res} 1!`)); + console.log("Last line 1!"); } async function funcTwo() { const res = await myPromise; - console.log(`${res} 2!`) - setTimeout(() => console.log('Timeout 2!'), 0); - console.log('Last line 2!'); + console.log(`${res} 2!`); + setTimeout(() => console.log("Timeout 2!"), 0); + console.log("Last line 2!"); } funcOne(); @@ -4355,7 +4355,7 @@ First, we invoke `funcOne`. On the first line of `funcOne`, we call the _asynchr Then we call the `myPromise` promise, which is an _asynchronous_ operation. -Both the promise and the timeout are asynchronous operations, the function keeps on running while it's busy completing the promise and handling the `setTimeout` callback. This means that `Last line 1!` gets logged first, since this is not an asynchonous operation. +Both the promise and the timeout are asynchronous operations, the function keeps on running while it's busy completing the promise and handling the `setTimeout` callback. This means that `Last line 1!` gets logged first, since this is not an asynchonous operation. Since the callstack is not empty yet, the `setTimeout` function and promise in `funcOne` cannot get added to the callstack yet. @@ -4379,7 +4379,7 @@ export default function sum(x) { } // index.js -import * as sum from './sum'; +import * as sum from "./sum"; ``` - A: `sum(4)` @@ -4396,12 +4396,12 @@ With the asterisk `*`, we import all exported values from that file, both defaul ```javascript // info.js -export const name = 'Lydia'; +export const name = "Lydia"; export const age = 21; -export default 'I love JavaScript'; +export default "I love JavaScript"; // index.js -import * as info from './info'; +import * as info from "./info"; console.log(info); ``` @@ -4432,13 +4432,13 @@ We can invoke this function, by calling `sum.default` ```javascript const handler = { - set: () => console.log('Added a new property!'), - get: () => console.log('Accessed a property!'), + set: () => console.log("Added a new property!"), + get: () => console.log("Accessed a property!"), }; const person = new Proxy({}, handler); -person.name = 'Lydia'; +person.name = "Lydia"; person.name; ``` @@ -4468,7 +4468,7 @@ Then, we access a property value on the proxy object, the `get` property on the ###### 136. Which of the following will modify the `person` object? ```javascript -const person = { name: 'Lydia Hallie' }; +const person = { name: "Lydia Hallie" }; Object.seal(person); ``` @@ -4496,9 +4496,9 @@ However, you can still modify the value of existing properties. ```javascript const person = { - name: 'Lydia Hallie', + name: "Lydia Hallie", address: { - street: '100 Main St', + street: "100 Main St", }, }; @@ -4527,7 +4527,7 @@ However, it only _shallowly_ freezes the object, meaning that only _direct_ prop ###### 138. What's the output? ```javascript -const add = x => x + x; +const add = (x) => x + x; function myFunc(num = 2, value = add(num)) { console.log(num, value); @@ -4560,21 +4560,21 @@ Then, we invoked `myFunc(3)` and passed the value `3` as the value for the argum ```javascript class Counter { - #number = 10 + #number = 10; increment() { - this.#number++ + this.#number++; } getNum() { - return this.#number + return this.#number; } } -const counter = new Counter() -counter.increment() +const counter = new Counter(); +counter.increment(); -console.log(counter.#number) +console.log(counter.#number); ``` - A: `10` @@ -4598,8 +4598,8 @@ In ES2020, we can add private variables in classes by using the `#`. We cannot a ```javascript const teams = [ - { name: 'Team 1', members: ['Paul', 'Lisa'] }, - { name: 'Team 2', members: ['Laura', 'Tim'] }, + { name: "Team 1", members: ["Paul", "Lisa"] }, + { name: "Team 2", members: ["Laura", "Tim"] }, ]; function* getMembers(members) { @@ -4642,8 +4642,8 @@ If we would've written `yield`, `return yield`, or `return`, the entire generato ```javascript const person = { - name: 'Lydia Hallie', - hobbies: ['coding'], + name: "Lydia Hallie", + hobbies: ["coding"], }; function addHobby(hobby, hobbies = person.hobbies) { @@ -4651,9 +4651,9 @@ function addHobby(hobby, hobbies = person.hobbies) { return hobbies; } -addHobby('running', []); -addHobby('dancing'); -addHobby('baking', person.hobbies); +addHobby("running", []); +addHobby("dancing"); +addHobby("baking", person.hobbies); console.log(person.hobbies); ``` @@ -4722,11 +4722,11 @@ We create the variable `pet` which is an instance of the `Flamingo` class. When ###### 143. Which of the options result(s) in an error? ```javascript -const emojis = ['🎄', '🎅🏼', '🎁', '⭐']; +const emojis = ["🎄", "🎅🏼", "🎁", "⭐"]; -/* 1 */ emojis.push('🦌'); +/* 1 */ emojis.push("🦌"); /* 2 */ emojis.splice(0, 2); -/* 3 */ emojis = [...emojis, '🥂']; +/* 3 */ emojis = [...emojis, "🥂"]; /* 4 */ emojis.length = 0; ``` @@ -4781,11 +4781,11 @@ Objects aren't iterable by default. An iterable is an iterable if the iterator p let count = 0; const nums = [0, 1, 2, 3]; -nums.forEach(num => { - if (num) count += 1 -}) +nums.forEach((num) => { + if (num) count += 1; +}); -console.log(count) +console.log(count); ``` - A: 1 @@ -4809,12 +4809,12 @@ The `if` condition within the `forEach` loop checks whether the value of `num` i ```javascript function getFruit(fruits) { - console.log(fruits?.[1]?.[1]) + console.log(fruits?.[1]?.[1]); } -getFruit([['🍊', '🍌'], ['🍍']]) -getFruit() -getFruit([['🍍'], ['🍊', '🍌']]) +getFruit([["🍊", "🍌"], ["🍍"]]); +getFruit(); +getFruit([["🍍"], ["🍊", "🍌"]]); ``` - A: `null`, `undefined`, 🍌 @@ -4827,11 +4827,11 @@ getFruit([['🍍'], ['🍊', '🍌']]) #### Answer: D -The `?` allows us to optionally access deeper nested properties within objects. We're trying to log the item on index `1` within the subarray that's on index `1` of the `fruits` array. If the subarray on index `1` in the `fruits` array doesn't exist, it'll simply return `undefined`. If the subarray on index `1` in the `fruits` array exists, but this subarray doesn't have an item on its `1` index, it'll also return `undefined`. +The `?` allows us to optionally access deeper nested properties within objects. We're trying to log the item on index `1` within the subarray that's on index `1` of the `fruits` array. If the subarray on index `1` in the `fruits` array doesn't exist, it'll simply return `undefined`. If the subarray on index `1` in the `fruits` array exists, but this subarray doesn't have an item on its `1` index, it'll also return `undefined`. First, we're trying to log the second item in the `['🍍']` subarray of `[['🍊', '🍌'], ['🍍']]`. This subarray only contains one item, which means there is no item on index `1`, and returns `undefined`. -Then, we're invoking the `getFruits` function without passing a value as an argument, which means that `fruits` has a value of `undefined` by default. Since we're conditionally chaining the item on index `1` of`fruits`, it returns `undefined` since this item on index `1` does not exist. +Then, we're invoking the `getFruits` function without passing a value as an argument, which means that `fruits` has a value of `undefined` by default. Since we're conditionally chaining the item on index `1` of`fruits`, it returns `undefined` since this item on index `1` does not exist. Lastly, we're trying to log the second item in the `['🍊', '🍌']` subarray of `['🍍'], ['🍊', '🍌']`. The item on index `1` within this subarray is `🍌`, which gets logged. @@ -4844,19 +4844,19 @@ Lastly, we're trying to log the second item in the `['🍊', '🍌']` subarray o ```javascript class Calc { - constructor() { - this.count = 0 - } + constructor() { + this.count = 0; + } - increase() { - this.count ++ - } + increase() { + this.count++; + } } -const calc = new Calc() -new Calc().increase() +const calc = new Calc(); +new Calc().increase(); -console.log(calc.count) +console.log(calc.count); ``` - A: `0` @@ -4880,25 +4880,25 @@ We set the variable `calc` equal to a new instance of the `Calc` class. Then, we ```javascript const user = { - email: "e@mail.com", - password: "12345" -} + email: "e@mail.com", + password: "12345", +}; const updateUser = ({ email, password }) => { - if (email) { - Object.assign(user, { email }) - } + if (email) { + Object.assign(user, { email }); + } - if (password) { - user.password = password - } + if (password) { + user.password = password; + } - return user -} + return user; +}; -const updatedUser = updateUser({ email: "new@email.com" }) +const updatedUser = updateUser({ email: "new@email.com" }); -console.log(updatedUser === user) +console.log(updatedUser === user); ``` - A: `false` @@ -4921,13 +4921,13 @@ The `updateUser` function updates the values of the `email` and `password` prope ###### 149. What's the output? ```javascript -const fruit = ['🍌', '🍊', '🍎'] +const fruit = ["🍌", "🍊", "🍎"]; -fruit.slice(0, 1) -fruit.splice(0, 1) -fruit.unshift('🍇') +fruit.slice(0, 1); +fruit.splice(0, 1); +fruit.unshift("🍇"); -console.log(fruit) +console.log(fruit); ``` - A: `['🍌', '🍊', '🍎']` @@ -4942,7 +4942,7 @@ console.log(fruit) First, we invoke the `slice` method on the fruit array. The slice method does not modify the original array, but returns the value that it sliced off the array: the banana emoji. Then, we invoke the `splice` method on the fruit array. The splice method does modify the original array, which means that the fruit array now consists of `['🍊', '🍎']`. -At last, we invoke the `unshift` method on the `fruit` array, which modifies the original array by adding the provided value, ‘🍇’ in this case, as the first element in the array. The fruit array now consists of `['🍇', '🍊', '🍎']`. +At last, we invoke the `unshift` method on the `fruit` array, which modifies the original array by adding the provided value, ‘🍇’ in this case, as the first element in the array. The fruit array now consists of `['🍇', '🍊', '🍎']`.

@@ -4953,13 +4953,13 @@ At last, we invoke the `unshift` method on the `fruit` array, which modifies the ```javascript const animals = {}; -let dog = { emoji: '🐶' } -let cat = { emoji: '🐈' } +let dog = { emoji: "🐶" }; +let cat = { emoji: "🐈" }; -animals[dog] = { ...dog, name: "Mara" } -animals[cat] = { ...cat, name: "Sara" } +animals[dog] = { ...dog, name: "Mara" }; +animals[cat] = { ...cat, name: "Sara" }; -console.log(animals[dog]) +console.log(animals[dog]); ``` - A: `{ emoji: "🐶", name: "Mara" }` @@ -4972,11 +4972,11 @@ console.log(animals[dog]) #### Answer: B -Object keys are converted to strings. +Object keys are converted to strings. -Since the value of `dog` is an object, `animals[dog]` actually means that we’re creating a new property called `"[object Object]"` equal to the new object. `animals["[object Object]"]` is now equal to `{ emoji: "🐶", name: "Mara"}`. +Since the value of `dog` is an object, `animals[dog]` actually means that we’re creating a new property called `"[object Object]"` equal to the new object. `animals["[object Object]"]` is now equal to `{ emoji: "🐶", name: "Mara"}`. -`cat` is also an object, which means that `animals[cat]` actually means that we’re overwriting the value of `animals["[object Object]"]` with the new cat properties. +`cat` is also an object, which means that `animals[cat]` actually means that we’re overwriting the value of `animals["[object Object]"]` with the new cat properties. Logging `animals[dog]`, or actually `animals["[object Object]"]` since converting the `dog` object to a string results `"[object Object]"`, returns the `{ emoji: "🐈", name: "Sara" }`. @@ -4989,14 +4989,14 @@ Logging `animals[dog]`, or actually `animals["[object Object]"]` since convertin ```javascript const user = { - email: "my@email.com", - updateEmail: email => { - this.email = email - } -} + email: "my@email.com", + updateEmail: (email) => { + this.email = email; + }, +}; -user.updateEmail("new@email.com") -console.log(user.email) +user.updateEmail("new@email.com"); +console.log(user.email); ``` - A: `my@email.com` @@ -5009,7 +5009,7 @@ console.log(user.email) #### Answer: A -The `updateEmail` function is an arrow function, and is not bound to the `user` object. This means that the `this` keyword is not referring to the `user` object, but refers to the global scope in this case. The value of `email` within the `user` object does not get updated. When logging the value of `user.email`, the original value of `my@email.com` gets returned. +The `updateEmail` function is an arrow function, and is not bound to the `user` object. This means that the `this` keyword is not referring to the `user` object, but refers to the global scope in this case. The value of `email` within the `user` object does not get updated. When logging the value of `user.email`, the original value of `my@email.com` gets returned.

@@ -5019,20 +5019,20 @@ The `updateEmail` function is an arrow function, and is not bound to the `user` ###### 152. What's the output? ```javascript -const promise1 = Promise.resolve('First') -const promise2 = Promise.resolve('Second') -const promise3 = Promise.reject('Third') -const promise4 = Promise.resolve('Fourth') +const promise1 = Promise.resolve("First"); +const promise2 = Promise.resolve("Second"); +const promise3 = Promise.reject("Third"); +const promise4 = Promise.resolve("Fourth"); const runPromises = async () => { - const res1 = await Promise.all([promise1, promise2]) - const res2 = await Promise.all([promise3, promise4]) - return [res1, res2] -} + const res1 = await Promise.all([promise1, promise2]); + const res2 = await Promise.all([promise3, promise4]); + return [res1, res2]; +}; runPromises() - .then(res => console.log(res)) - .catch(err => console.log(err)) + .then((res) => console.log(res)) + .catch((err) => console.log(err)); ``` - A: `[['First', 'Second'], ['Fourth']]` @@ -5045,23 +5045,26 @@ runPromises() #### Answer: D -The `Promise.all` method runs the passed promises in parallel. If one promise fails, the `Promise.all` method _rejects_ with the value of the rejected promise. In this case, `promise3` rejected with the value `"Third"`. We’re catching the rejected value in the chained `catch` method on the `runPromises` invocation to catch any errors within the `runPromises` function. Only `"Third"` gets logged, since `promise3` rejected with this value. +The `Promise.all` method runs the passed promises in parallel. If one promise fails, the `Promise.all` method _rejects_ with the value of the rejected promise. In this case, `promise3` rejected with the value `"Third"`. We’re catching the rejected value in the chained `catch` method on the `runPromises` invocation to catch any errors within the `runPromises` function. Only `"Third"` gets logged, since `promise3` rejected with this value.

--- -###### 153. What should the value of `method` be to log `{ name: "Lydia", age: 22 }`? +###### 153. What should the value of `method` be to log `{ name: "Lydia", age: 22 }`? ```javascript -const keys = ["name", "age"] -const values = ["Lydia", 22] +const keys = ["name", "age"]; +const values = ["Lydia", 22]; -const method = /* ?? */ -Object[method](keys.map((_, i) => { - return [keys[i], values[i]] -})) // { name: "Lydia", age: 22 } +const method = + /* ?? */ + Object[method]( + keys.map((_, i) => { + return [keys[i], values[i]]; + }) + ); // { name: "Lydia", age: 22 } ``` - A: `entries` @@ -5074,7 +5077,7 @@ Object[method](keys.map((_, i) => { #### Answer: C -The `fromEntries` method turns a 2d array into an object. The first element in each subarray will be the key, and the second element in each subarray will be the value. In this case, we’re mapping over the `keys` array, which returns an array which first element is the item on the key array on the current index, and the second element is the item of the values array on the current index. +The `fromEntries` method turns a 2d array into an object. The first element in each subarray will be the key, and the second element in each subarray will be the value. In this case, we’re mapping over the `keys` array, which returns an array which first element is the item on the key array on the current index, and the second element is the item of the values array on the current index. This creates an array of subarrays containing the correct keys and values, which results in `{ name: "Lydia", age: 22 }` @@ -5086,18 +5089,18 @@ This creates an array of subarrays containing the correct keys and values, which ###### 154. What's the output? ```javascript -const createMember = ({ email, address = {}}) => { - const validEmail = /.+\@.+\..+/.test(email) - if (!validEmail) throw new Error("Valid email pls") +const createMember = ({ email, address = {} }) => { + const validEmail = /.+\@.+\..+/.test(email); + if (!validEmail) throw new Error("Valid email pls"); - return { - email, - address: address ? address : null - } -} + return { + email, + address: address ? address : null, + }; +}; -const member = createMember({ email: "my@email.com" }) -console.log(member) +const member = createMember({ email: "my@email.com" }); +console.log(member); ``` - A: `{ email: "my@email.com", address: null }` @@ -5120,13 +5123,13 @@ The default value of `address` is an empty object `{}`. When we set the variable ###### 155. What's the output? ```javascript -let randomValue = { name: "Lydia" } -randomValue = 23 +let randomValue = { name: "Lydia" }; +randomValue = 23; if (!typeof randomValue === "string") { - console.log("It's not a string!") + console.log("It's not a string!"); } else { - console.log("Yay it's a string!") + console.log("Yay it's a string!"); } ``` From 44808d954348d25c75664f4cd3b9e3b5ff00809b Mon Sep 17 00:00:00 2001 From: Jacob Herper Date: Sun, 10 Sep 2023 15:43:58 +0100 Subject: [PATCH 179/193] undo formatting changes --- README.md | 618 +++++++++++++++++++++++++++--------------------------- 1 file changed, 309 insertions(+), 309 deletions(-) diff --git a/README.md b/README.md index 76e834d5..802f4dfc 100644 --- a/README.md +++ b/README.md @@ -57,7 +57,7 @@ From basic to advanced: test how well you know JavaScript, refresh your knowledg function sayHi() { console.log(name); console.log(age); - var name = "Lydia"; + var name = 'Lydia'; let age = 21; } @@ -153,7 +153,7 @@ There is no value `radius` on that object, which returns `NaN`. ```javascript +true; -!"Lydia"; +!'Lydia'; ``` - A: `1` and `false` @@ -178,11 +178,11 @@ The string `'Lydia'` is a truthy value. What we're actually asking, is "is this ```javascript const bird = { - size: "small", + size: 'small', }; const mouse = { - name: "Mickey", + name: 'Mickey', small: true, }; ``` @@ -213,11 +213,11 @@ However, with dot notation, this doesn't happen. `mouse` does not have a key cal ###### 6. What's the output? ```javascript -let c = { greeting: "Hey!" }; +let c = { greeting: 'Hey!' }; let d; d = c; -c.greeting = "Hello"; +c.greeting = 'Hello'; console.log(d.greeting); ``` @@ -287,13 +287,13 @@ class Chameleon { return this.newColor; } - constructor({ newColor = "green" } = {}) { + constructor({ newColor = 'green' } = {}) { this.newColor = newColor; } } -const freddie = new Chameleon({ newColor: "purple" }); -console.log(freddie.colorChange("orange")); +const freddie = new Chameleon({ newColor: 'purple' }); +console.log(freddie.colorChange('orange')); ``` - A: `orange` @@ -348,10 +348,10 @@ In order to avoid this, we can use `"use strict"`. This makes sure that you have ```javascript function bark() { - console.log("Woof!"); + console.log('Woof!'); } -bark.animal = "dog"; +bark.animal = 'dog'; ``` - A: Nothing, this is totally fine! @@ -381,8 +381,8 @@ function Person(firstName, lastName) { this.lastName = lastName; } -const member = new Person("Lydia", "Hallie"); -Person.getFullName = function () { +const member = new Person('Lydia', 'Hallie'); +Person.getFullName = function() { return `${this.firstName} ${this.lastName}`; }; @@ -399,12 +399,12 @@ console.log(member.getFullName()); #### Answer: A -In JavaScript, functions are objects, and therefore, the method `getFullName` gets added to the constructor function object itself. For that reason, we can call `Person.getFullName()`, but `member.getFullName` throws a `TypeError`. +In JavaScript, functions are objects, and therefore, the method `getFullName` gets added to the constructor function object itself. For that reason, we can call `Person.getFullName()`, but `member.getFullName` throws a `TypeError`. If you want a method to be available to all object instances, you have to add it to the prototype property: ```js -Person.prototype.getFullName = function () { +Person.prototype.getFullName = function() { return `${this.firstName} ${this.lastName}`; }; ``` @@ -422,8 +422,8 @@ function Person(firstName, lastName) { this.lastName = lastName; } -const lydia = new Person("Lydia", "Hallie"); -const sarah = Person("Sarah", "Smith"); +const lydia = new Person('Lydia', 'Hallie'); +const sarah = Person('Sarah', 'Smith'); console.log(lydia); console.log(sarah); @@ -493,7 +493,7 @@ function sum(a, b) { return a + b; } -sum(1, "2"); +sum(1, '2'); ``` - A: `NaN` @@ -560,7 +560,7 @@ function getPersonInfo(one, two, three) { console.log(three); } -const person = "Lydia"; +const person = 'Lydia'; const age = 21; getPersonInfo`${person} is ${age} years old`; @@ -587,9 +587,9 @@ If you use tagged template literals, the value of the first argument is always a ```javascript function checkAge(data) { if (data === { age: 18 }) { - console.log("You are an adult!"); + console.log('You are an adult!'); } else if (data == { age: 18 }) { - console.log("You are still an adult."); + console.log('You are still an adult.'); } else { console.log(`Hmm.. You don't have an age I guess`); } @@ -649,7 +649,7 @@ The rest parameter (`...args`) lets us "collect" all remaining arguments into an ```javascript function getAge() { - "use strict"; + 'use strict'; age = 21; console.log(age); } @@ -677,7 +677,7 @@ With `"use strict"`, you can make sure that you don't accidentally declare globa ###### 21. What's the value of `sum`? ```javascript -const sum = eval("10*10+5"); +const sum = eval('10*10+5'); ``` - A: `105` @@ -700,7 +700,7 @@ const sum = eval("10*10+5"); ###### 22. How long is cool_secret accessible? ```javascript -sessionStorage.setItem("cool_secret", 123); +sessionStorage.setItem('cool_secret', 123); ``` - A: Forever, the data doesn't get lost. @@ -753,12 +753,12 @@ You cannot do this with `let` or `const` since they're block-scoped. ###### 24. What's the output? ```javascript -const obj = { 1: "a", 2: "b", 3: "c" }; +const obj = { 1: 'a', 2: 'b', 3: 'c' }; const set = new Set([1, 2, 3, 4, 5]); -obj.hasOwnProperty("1"); +obj.hasOwnProperty('1'); obj.hasOwnProperty(1); -set.has("1"); +set.has('1'); set.has(1); ``` @@ -784,7 +784,7 @@ It doesn't work that way for a set. There is no `'1'` in our set: `set.has('1')` ###### 25. What's the output? ```javascript -const obj = { a: "one", b: "two", a: "three" }; +const obj = { a: 'one', b: 'two', a: 'three' }; console.log(obj); ``` @@ -853,12 +853,12 @@ The `continue` statement skips an iteration if a certain condition returns `true ```javascript String.prototype.giveLydiaPizza = () => { - return "Just give Lydia pizza already!"; + return 'Just give Lydia pizza already!'; }; -const name = "Lydia"; +const name = 'Lydia'; -console.log(name.giveLydiaPizza()); +console.log(name.giveLydiaPizza()) ``` - A: `"Just give Lydia pizza already!"` @@ -882,8 +882,8 @@ console.log(name.giveLydiaPizza()); ```javascript const a = {}; -const b = { key: "b" }; -const c = { key: "c" }; +const b = { key: 'b' }; +const c = { key: 'c' }; a[b] = 123; a[c] = 456; @@ -915,9 +915,9 @@ Then, we log `a[b]`, which is actually `a["[object Object]"]`. We just set that ###### 30. What's the output? ```javascript -const foo = () => console.log("First"); -const bar = () => setTimeout(() => console.log("Second")); -const baz = () => console.log("Third"); +const foo = () => console.log('First'); +const bar = () => setTimeout(() => console.log('Second')); +const baz = () => console.log('Third'); bar(); foo(); @@ -970,7 +970,9 @@ This is where an event loop starts to work. An **event loop** looks at the stack ```html
- +
``` @@ -996,7 +998,9 @@ The deepest nested element that caused the event is the target of the event. You ```html
-

Click here!

+

+ Click here! +

``` @@ -1020,7 +1024,7 @@ If we click `p`, we see two logs: `p` and `div`. During event propagation, there ###### 33. What's the output? ```javascript -const person = { name: "Lydia" }; +const person = { name: 'Lydia' }; function sayHi(age) { return `${this.name} is ${age}`; @@ -1070,6 +1074,7 @@ console.log(typeof sayHi()); #### Answer: B The `sayHi` function returns the returned value of the immediately invoked function expression (IIFE). This function returned `0`, which is type `"number"`. + FYI: `typeof` can return the following list of values: `undefined`, `boolean`, `number`, `bigint`, `string`, `symbol`, `function` and `object`. Note that `typeof null` returns `"object"`.

@@ -1082,8 +1087,8 @@ FYI: `typeof` can return the following list of values: `undefined`, `boolean`, ` ```javascript 0; new Number(0); -(""); -(" "); +(''); +(' '); new Boolean(false); undefined; ``` @@ -1232,14 +1237,11 @@ What differentiates a primitive from an object is that primitives do not have an ###### 40. What's the output? ```javascript -[ - [0, 1], - [2, 3], -].reduce( +[[0, 1], [2, 3]].reduce( (acc, cur) => { return acc.concat(cur); }, - [1, 2] + [1, 2], ); ``` @@ -1266,7 +1268,7 @@ Then, `[1, 2, 0, 1]` is `acc` and `[2, 3]` is `cur`. We concatenate them, and ge ```javascript !!null; -!!""; +!!''; !!1; ``` @@ -1294,7 +1296,7 @@ Then, `[1, 2, 0, 1]` is `acc` and `[2, 3]` is `cur`. We concatenate them, and ge ###### 42. What does the `setInterval` method return in the browser? ```javascript -setInterval(() => console.log("Hi"), 1000); +setInterval(() => console.log('Hi'), 1000); ``` - A: a unique id @@ -1317,7 +1319,7 @@ It returns a unique id. This id can be used to clear that interval with the `cle ###### 43. What does this return? ```javascript -[..."Lydia"]; +[...'Lydia']; ``` - A: `["L", "y", "d", "i", "a"]` @@ -1376,14 +1378,14 @@ Then, we invoke the function again with the `next()` method. It starts to contin ```javascript const firstPromise = new Promise((res, rej) => { - setTimeout(res, 500, "one"); + setTimeout(res, 500, 'one'); }); const secondPromise = new Promise((res, rej) => { - setTimeout(res, 100, "two"); + setTimeout(res, 100, 'two'); }); -Promise.race([firstPromise, secondPromise]).then((res) => console.log(res)); +Promise.race([firstPromise, secondPromise]).then(res => console.log(res)); ``` - A: `"one"` @@ -1406,7 +1408,7 @@ When we pass multiple promises to the `Promise.race` method, it resolves/rejects ###### 46. What's the output? ```javascript -let person = { name: "Lydia" }; +let person = { name: 'Lydia' }; const members = [person]; person = null; @@ -1446,7 +1448,7 @@ We are only modifying the value of the `person` variable, and not the first elem ```javascript const person = { - name: "Lydia", + name: 'Lydia', age: 21, }; @@ -1475,7 +1477,7 @@ With a `for-in` loop, we can iterate through object keys, in this case `name` an ###### 48. What's the output? ```javascript -console.log(3 + 4 + "5"); +console.log(3 + 4 + '5'); ``` - A: `"345"` @@ -1502,7 +1504,7 @@ Operator associativity is the order in which the compiler evaluates the expressi ###### 49. What's the value of `num`? ```javascript -const num = parseInt("7*6", 10); +const num = parseInt('7*6', 10); ``` - A: `42` @@ -1527,8 +1529,8 @@ Only the first numbers in the string is returned. Based on the _radix_ (the seco ###### 50. What's the output? ```javascript -[1, 2, 3].map((num) => { - if (typeof num === "number") return; +[1, 2, 3].map(num => { + if (typeof num === 'number') return; return num * 2; }); ``` @@ -1556,12 +1558,12 @@ However, we don’t return a value. When we don’t return a value from the func ```javascript function getInfo(member, year) { - member.name = "Lydia"; - year = "1998"; + member.name = 'Lydia'; + year = '1998'; } -const person = { name: "Sarah" }; -const birthYear = "1997"; +const person = { name: 'Sarah' }; +const birthYear = '1997'; getInfo(person, birthYear); @@ -1593,15 +1595,15 @@ The value of `person` is an object. The argument `member` has a (copied) referen ```javascript function greeting() { - throw "Hello world!"; + throw 'Hello world!'; } function sayHi() { try { const data = greeting(); - console.log("It worked!", data); + console.log('It worked!', data); } catch (e) { - console.log("Oh no an error:", e); + console.log('Oh no an error:', e); } } @@ -1631,8 +1633,8 @@ With the `catch` statement, we can specify what to do if an exception is thrown ```javascript function Car() { - this.make = "Lamborghini"; - return { make: "Maserati" }; + this.make = 'Lamborghini'; + return { make: 'Maserati' }; } const myCar = new Car(); @@ -1706,11 +1708,11 @@ class Dog { } } -Dog.prototype.bark = function () { +Dog.prototype.bark = function() { console.log(`Woof I am ${this.name}`); }; -const pet = new Dog("Mara"); +const pet = new Dog('Mara'); pet.bark(); @@ -1775,7 +1777,7 @@ export default counter; ```javascript // index.js -import myCounter from "./counter"; +import myCounter from './counter'; myCounter += 1; @@ -1804,7 +1806,7 @@ When we try to increment the value of `myCounter`, it throws an error: `myCounte ###### 58. What's the output? ```javascript -const name = "Lydia"; +const name = 'Lydia'; age = 21; console.log(delete name); @@ -1875,7 +1877,7 @@ This means that the value of `y` is equal to the first value in the array, which ###### 60. What's the output? ```javascript -const user = { name: "Lydia", age: 21 }; +const user = { name: 'Lydia', age: 21 }; const admin = { admin: true, ...user }; console.log(admin); @@ -1901,9 +1903,9 @@ It's possible to combine objects using the spread operator `...`. It lets you cr ###### 61. What's the output? ```javascript -const person = { name: "Lydia" }; +const person = { name: 'Lydia' }; -Object.defineProperty(person, "age", { value: 21 }); +Object.defineProperty(person, 'age', { value: 21 }); console.log(person); console.log(Object.keys(person)); @@ -1932,12 +1934,12 @@ Properties added using the `defineProperty` method are immutable by default. You ```javascript const settings = { - username: "lydiahallie", + username: 'lydiahallie', level: 19, health: 90, }; -const data = JSON.stringify(settings, ["level", "health"]); +const data = JSON.stringify(settings, ['level', 'health']); console.log(data); ``` @@ -1968,7 +1970,7 @@ If the replacer is a _function_, this function gets called on every property in let num = 10; const increaseNumber = () => num++; -const increasePassedNumber = (number) => number++; +const increasePassedNumber = number => number++; const num1 = increaseNumber(); const num2 = increasePassedNumber(num1); @@ -2125,12 +2127,12 @@ The `Labrador` class receives two arguments, `name` since it extends `Dog`, and ```javascript // index.js -console.log("running index.js"); -import { sum } from "./sum.js"; +console.log('running index.js'); +import { sum } from './sum.js'; console.log(sum(1, 2)); // sum.js -console.log("running sum.js"); +console.log('running sum.js'); export const sum = (a, b) => a + b; ``` @@ -2158,7 +2160,7 @@ This is a difference between `require()` in CommonJS and `import`! With `require ```javascript console.log(Number(2) === Number(2)); console.log(Boolean(false) === Boolean(false)); -console.log(Symbol("foo") === Symbol("foo")); +console.log(Symbol('foo') === Symbol('foo')); ``` - A: `true`, `true`, `false` @@ -2181,7 +2183,7 @@ Every Symbol is entirely unique. The purpose of the argument passed to the Symbo ###### 69. What's the output? ```javascript -const name = "Lydia Hallie"; +const name = 'Lydia Hallie'; console.log(name.padStart(13)); console.log(name.padStart(2)); ``` @@ -2208,7 +2210,7 @@ If the argument passed to the `padStart` method is smaller than the length of th ###### 70. What's the output? ```javascript -console.log("🥑" + "💻"); +console.log('🥑' + '💻'); ``` - A: `"🥑💻"` @@ -2232,11 +2234,11 @@ With the `+` operator, you can concatenate strings. In this case, we are concate ```javascript function* startGame() { - const answer = yield "Do you love JavaScript?"; - if (answer !== "Yes") { + const answer = yield 'Do you love JavaScript?'; + if (answer !== 'Yes') { return "Oh wow... Guess we're done here"; } - return "JavaScript loves you back ❤️"; + return 'JavaScript loves you back ❤️'; } const game = startGame(); @@ -2304,7 +2306,7 @@ In this case, the string is `Hello\nworld`, which gets logged. ```javascript async function getData() { - return await Promise.resolve("I made it!"); + return await Promise.resolve('I made it!'); } const data = getData(); @@ -2341,7 +2343,7 @@ function addToList(item, list) { return list.push(item); } -const result = addToList("apple", ["banana"]); +const result = addToList('apple', ['banana']); console.log(result); ``` @@ -2401,7 +2403,7 @@ Since `shape` is frozen, and since the value of `x` is not an object, we cannot ###### 76. What's the output? ```javascript -const { firstName: myName } = { firstName: "Lydia" }; +const { firstName: myName } = { firstName: 'Lydia' }; console.log(firstName); ``` @@ -2419,7 +2421,7 @@ console.log(firstName); By using [destructuring assignment](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment) syntax we can unpack values from arrays, or properties from objects, into distinct variables: ```javascript -const { firstName } = { firstName: "Lydia" }; +const { firstName } = { firstName: 'Lydia' }; // ES5 version: // var firstName = { firstName: 'Lydia' }.firstName; @@ -2429,7 +2431,7 @@ console.log(firstName); // "Lydia" Also, a property can be unpacked from an object and assigned to a variable with a different name than the object property: ```javascript -const { firstName: myName } = { firstName: "Lydia" }; +const { firstName: myName } = { firstName: 'Lydia' }; // ES5 version: // var myName = { firstName: 'Lydia' }.firstName; @@ -2442,11 +2444,12 @@ Therefore, `firstName` does not exist as a variable, thus attempting to access i **Note:** Be aware of the `global scope` properties: ```javascript -const { name: myName } = { name: "Lydia" }; +const { name: myName } = { name: 'Lydia' }; console.log(myName); // "lydia" console.log(name); // "" ----- Browser e.g. Chrome console.log(name); // ReferenceError: name is not defined ----- NodeJS + ``` Whenever Javascript is unable to find a variable within the _current scope_, it climbs up the [Scope chain](https://github.com/getify/You-Dont-Know-JS/blob/2nd-ed/scope-closures/ch3.md) and searches for it and if it reaches the top-level scope, aka **Global scope**, and still doesn't find it, it will throw a `ReferenceError`. @@ -2490,7 +2493,7 @@ The `sum` function always returns the same result. If we pass `1` and `2`, it wi ```javascript const add = () => { const cache = {}; - return (num) => { + return num => { if (num in cache) { return `From cache! ${cache[num]}`; } else { @@ -2535,7 +2538,7 @@ The third time, we pass `5 * 2` to the function which gets evaluated to `10`. Th ###### 79. What is the output? ```javascript -const myLifeSummedUp = ["☕", "💻", "🍷", "🍫"]; +const myLifeSummedUp = ['☕', '💻', '🍷', '🍫']; for (let item in myLifeSummedUp) { console.log(item); @@ -2631,13 +2634,13 @@ In this case, if we didn't pass a value or if we passed `undefined`, `name` woul ###### 82. What is the output? ```javascript -var status = "😎"; +var status = '😎'; setTimeout(() => { - const status = "😍"; + const status = '😍'; const data = { - status: "🥑", + status: '🥑', getStatus() { return this.status; }, @@ -2671,12 +2674,12 @@ With the `call` method, we can change the object to which the `this` keyword ref ```javascript const person = { - name: "Lydia", + name: 'Lydia', age: 21, }; let city = person.city; -city = "Amsterdam"; +city = 'Amsterdam'; console.log(person); ``` @@ -2740,9 +2743,9 @@ Variables with the `const` and `let` keyword are _block-scoped_. A block is anyt ###### 85. What kind of information would get logged? ```javascript -fetch("https://www.website.com/api/user/1") - .then((res) => res.json()) - .then((res) => console.log(res)); +fetch('https://www.website.com/api/user/1') + .then(res => res.json()) + .then(res => console.log(res)); ``` - A: The result of the `fetch` method. @@ -2796,7 +2799,7 @@ By setting `hasName` equal to `name`, you set `hasName` equal to whatever value ###### 87. What's the output? ```javascript -console.log("I want pizza"[0]); +console.log('I want pizza'[0]); ``` - A: `"""` @@ -2851,11 +2854,11 @@ If you're trying to set a default parameter's value equal to a parameter which i ```javascript // module.js -export default () => "Hello world"; -export const name = "Lydia"; +export default () => 'Hello world'; +export const name = 'Lydia'; // index.js -import * as data from "./module"; +import * as data from './module'; console.log(data); ``` @@ -2888,7 +2891,7 @@ class Person { } } -const member = new Person("John"); +const member = new Person('John'); console.log(typeof member); ``` @@ -2948,7 +2951,7 @@ Then, we try to use the `.push` method on `newList`. Since `newList` is the nume ```javascript function giveLydiaPizza() { - return "Here is pizza!"; + return 'Here is pizza!'; } const giveLydiaChocolate = () => @@ -2979,7 +2982,7 @@ Regular functions, such as the `giveLydiaPizza` function, have a `prototype` pro ```javascript const person = { - name: "Lydia", + name: 'Lydia', age: 21, }; @@ -3039,7 +3042,7 @@ function getItems(fruitList, favoriteFruit, ...args) { return [...fruitList, ...args, favoriteFruit]; } -getItems(["banana", "apple"], "pear", "orange"); +getItems(['banana', 'apple'], 'pear', 'orange'); ``` The above example works. This returns the array `[ 'banana', 'apple', 'orange', 'pear' ]` @@ -3053,9 +3056,9 @@ The above example works. This returns the array `[ 'banana', 'apple', 'orange', ```javascript function nums(a, b) { - if (a > b) console.log("a is bigger"); - else console.log("b is bigger"); - return; + if (a > b) console.log('a is bigger'); + else console.log('b is bigger'); + return a + b; } @@ -3094,13 +3097,13 @@ This means that `a + b` is never reached, since a function stops running after t ```javascript class Person { constructor() { - this.name = "Lydia"; + this.name = 'Lydia'; } } Person = class AnotherPerson { constructor() { - this.name = "Sarah"; + this.name = 'Sarah'; } }; @@ -3129,7 +3132,7 @@ We can set classes equal to other classes/function constructors. In this case, w ```javascript const info = { - [Symbol("a")]: "b", + [Symbol('a')]: 'b', }; console.log(info); @@ -3184,7 +3187,7 @@ The `getList` function receives an array as its argument. Between the parenthese With the rest parameter `...y`, we put all "remaining" arguments in an array. The remaining arguments are `2`, `3` and `4` in this case. The value of `y` is an array, containing all the rest parameters. The value of `x` is equal to `1` in this case, so when we log `[x, y]`, `[1, [2, 3, 4]]` gets logged. -The `getUser` function receives an object. With arrow functions, we don't _have_ to write curly brackets if we just return one value. However, if you want to instantly return an _object_ from an arrow function, you have to write it between parentheses, otherwise everything between the two braces will be interpreted as a block statement. In this case the code between the braces is not a valid JavaScript code, so a `SyntaxError` gets thrown. +The `getUser` function receives an object. With arrow functions, we don't _have_ to write curly brackets if we just return one value. However, if you want to instantly return an _object_ from an arrow function, you have to write it between parentheses, otherwise everything between the two braces will be interpreted as a block statement. In this case the code between the braces is not a valid JavaScript code, so a `SyntaxError` gets thrown. The following function would have returned an object: @@ -3198,7 +3201,7 @@ The following function would have returned an object: ###### 99. What's the output? ```javascript -const name = "Lydia"; +const name = 'Lydia'; console.log(name()); ``` @@ -3230,8 +3233,8 @@ ReferenceErrors get thrown when JavaScript isn't able to find a reference to a v ```javascript // 🎉✨ This is my 100th question! ✨🎉 -const output = `${[] && "Im"}possible! -You should${"" && `n't`} see a therapist after so much JavaScript lol`; +const output = `${[] && 'Im'}possible! +You should${'' && `n't`} see a therapist after so much JavaScript lol`; ``` - A: `possible! You should see a therapist after so much JavaScript lol` @@ -3257,7 +3260,7 @@ You should${"" && `n't`} see a therapist after so much JavaScript lol`; ```javascript const one = false || {} || null; -const two = null || false || ""; +const two = null || false || ''; const three = [] || 0 || true; console.log(one, two, three); @@ -3289,16 +3292,16 @@ With the `||` operator, we can return the first truthy operand. If all values ar ###### 102. What's the value of output? ```javascript -const myPromise = () => Promise.resolve("I have resolved!"); +const myPromise = () => Promise.resolve('I have resolved!'); function firstFunction() { - myPromise().then((res) => console.log(res)); - console.log("second"); + myPromise().then(res => console.log(res)); + console.log('second'); } async function secondFunction() { console.log(await myPromise()); - console.log("second"); + console.log('second'); } firstFunction(); @@ -3336,8 +3339,8 @@ This means that it waited for the `myPromise` to resolve with the value `I have const set = new Set(); set.add(1); -set.add("Lydia"); -set.add({ name: "Lydia" }); +set.add('Lydia'); +set.add({ name: 'Lydia' }); for (let item of set) { console.log(item + 2); @@ -3397,13 +3400,13 @@ In this case, we just passed the numerical value `5`. It returns a resolved prom ```javascript function compareMembers(person1, person2 = person) { if (person1 !== person2) { - console.log("Not the same!"); + console.log('Not the same!'); } else { - console.log("They are the same!"); + console.log('They are the same!'); } } -const person = { name: "Lydia" }; +const person = { name: 'Lydia' }; compareMembers(person); ``` @@ -3442,7 +3445,7 @@ const colorConfig = { yellow: false, }; -const colors = ["pink", "red", "blue"]; +const colors = ['pink', 'red', 'blue']; console.log(colorConfig.colors[1]); ``` @@ -3471,7 +3474,7 @@ JavaScript interprets (or unboxes) statements. When we use bracket notation, it ###### 107. What's its value? ```javascript -console.log("❤️" === "❤️"); +console.log('❤️' === '❤️'); ``` - A: `true` @@ -3492,14 +3495,14 @@ Under the hood, emojis are unicodes. The unicodes for the heart emoji is `"U+276 ###### 108. Which of these methods modifies the original array? ```javascript -const emojis = ["✨", "🥑", "😍"]; +const emojis = ['✨', '🥑', '😍']; -emojis.map((x) => x + "✨"); -emojis.filter((x) => x !== "🥑"); -emojis.find((x) => x !== "🥑"); -emojis.reduce((acc, cur) => acc + "✨"); -emojis.slice(1, 2, "✨"); -emojis.splice(1, 2, "✨"); +emojis.map(x => x + '✨'); +emojis.filter(x => x !== '🥑'); +emojis.find(x => x !== '🥑'); +emojis.reduce((acc, cur) => acc + '✨'); +emojis.slice(1, 2, '✨'); +emojis.splice(1, 2, '✨'); ``` - A: `All of them` @@ -3524,10 +3527,10 @@ With `splice` method, we modify the original array by deleting, replacing or add ###### 109. What's the output? ```javascript -const food = ["🍕", "🍫", "🥑", "🍔"]; +const food = ['🍕', '🍫', '🥑', '🍔']; const info = { favoriteFood: food[0] }; -info.favoriteFood = "🍝"; +info.favoriteFood = '🍝'; console.log(food); ``` @@ -3581,7 +3584,7 @@ const jsonArray = JSON.stringify([1, 2, 3]); // '[1, 2, 3]' JSON.parse(jsonArray); // [1, 2, 3] // Stringifying an object into valid JSON, then parsing the JSON string to a JavaScript value: -const jsonArray = JSON.stringify({ name: "Lydia" }); // '{"name":"Lydia"}' +const jsonArray = JSON.stringify({ name: 'Lydia' }); // '{"name":"Lydia"}' JSON.parse(jsonArray); // { name: 'Lydia' } ``` @@ -3593,11 +3596,11 @@ JSON.parse(jsonArray); // { name: 'Lydia' } ###### 111. What's the output? ```javascript -let name = "Lydia"; +let name = 'Lydia'; function getName() { console.log(name); - let name = "Sarah"; + let name = 'Sarah'; } getName(); @@ -3620,7 +3623,7 @@ Variables with the `let` keyword (and `const`) are hoisted, but unlike `var`, do If we wouldn't have declared the `name` variable within the `getName` function, the javascript engine would've looked down the _scope chain_. The outer scope has a variable called `name` with the value of `Lydia`. In that case, it would've logged `Lydia`. ```javascript -let name = "Lydia"; +let name = 'Lydia'; function getName() { console.log(name); @@ -3638,11 +3641,11 @@ getName(); // Lydia ```javascript function* generatorOne() { - yield ["a", "b", "c"]; + yield ['a', 'b', 'c']; } function* generatorTwo() { - yield* ["a", "b", "c"]; + yield* ['a', 'b', 'c']; } const one = generatorOne(); @@ -3688,7 +3691,7 @@ console.log(two.next().value); // undefined ###### 113. What's the output? ```javascript -console.log(`${((x) => x)("I love")} to program`); +console.log(`${(x => x)('I love')} to program`); ``` - A: `I love to program` @@ -3713,7 +3716,7 @@ Expressions within template literals are evaluated first. This means that the st ```javascript let config = { alert: setInterval(() => { - console.log("Alert!"); + console.log('Alert!'); }, 1000), }; @@ -3730,9 +3733,9 @@ config = null; #### Answer: C -Normally when we set objects equal to `null`, those objects get _garbage collected_ as there is no reference anymore to that object. However, since the callback function within `setInterval` is an arrow function (thus bound to the `config` object), the callback function still holds a reference to the `config` object. -As long as there is a reference, the object won't get garbage collected. -Since this is an interval, setting `config` to `null` or `delete`-ing `config.alert` won't garbage-collect the interval, so the interval will still be called. +Normally when we set objects equal to `null`, those objects get _garbage collected_ as there is no reference anymore to that object. However, since the callback function within `setInterval` is an arrow function (thus bound to the `config` object), the callback function still holds a reference to the `config` object. +As long as there is a reference, the object won't get garbage collected. +Since this is an interval, setting `config` to `null` or `delete`-ing `config.alert` won't garbage-collect the interval, so the interval will still be called. It should be cleared with `clearInterval(config.alert)` to remove it from memory. Since it was not cleared, the `setInterval` callback function will still get invoked every 1000ms (1s). @@ -3745,16 +3748,16 @@ Since it was not cleared, the `setInterval` callback function will still get inv ```javascript const myMap = new Map(); -const myFunc = () => "greeting"; +const myFunc = () => 'greeting'; -myMap.set(myFunc, "Hello world!"); +myMap.set(myFunc, 'Hello world!'); //1 -myMap.get("greeting"); +myMap.get('greeting'); //2 myMap.get(myFunc); //3 -myMap.get(() => "greeting"); +myMap.get(() => 'greeting'); ``` - A: 1 @@ -3781,14 +3784,14 @@ When adding a key/value pair using the `set` method, the key will be the value o ```javascript const person = { - name: "Lydia", + name: 'Lydia', age: 21, }; const changeAge = (x = { ...person }) => (x.age += 1); const changeAgeAndName = (x = { ...person }) => { x.age += 1; - x.name = "Sarah"; + x.name = 'Sarah'; }; changeAge(person); @@ -3847,7 +3850,7 @@ With the spread operator `...`, we can _spread_ iterables to individual elements ```javascript let num = 1; -const list = ["🥳", "🤠", "🥰", "🤪"]; +const list = ['🥳', '🤠', '🥰', '🤪']; console.log(list[(num += 1)]); ``` @@ -3873,11 +3876,11 @@ With the `+=` operand, we're incrementing the value of `num` by `1`. `num` had t ```javascript const person = { - firstName: "Lydia", - lastName: "Hallie", + firstName: 'Lydia', + lastName: 'Hallie', pet: { - name: "Mara", - breed: "Dutch Tulip Hound", + name: 'Mara', + breed: 'Dutch Tulip Hound', }, getFullName() { return `${this.firstName} ${this.lastName}`; @@ -3915,10 +3918,10 @@ With the optional chaining operator `?.`, we no longer have to explicitly check ###### 120. What's the output? ```javascript -const groceries = ["banana", "apple", "peanuts"]; +const groceries = ['banana', 'apple', 'peanuts']; -if (groceries.indexOf("banana")) { - console.log("We have to buy bananas!"); +if (groceries.indexOf('banana')) { + console.log('We have to buy bananas!'); } else { console.log(`We don't have to buy bananas!`); } @@ -3974,10 +3977,10 @@ The `language` method is a `setter`. Setters don't hold an actual value, their p ###### 122. What's the output? ```javascript -const name = "Lydia Hallie"; +const name = 'Lydia Hallie'; -console.log(!typeof name === "object"); -console.log(!typeof name === "string"); +console.log(!typeof name === 'object'); +console.log(!typeof name === 'string'); ``` - A: `false` `true` @@ -4002,7 +4005,7 @@ console.log(!typeof name === "string"); ###### 123. What's the output? ```javascript -const add = (x) => (y) => (z) => { +const add = x => y => z => { console.log(x, y, z); return x + y + z; }; @@ -4092,20 +4095,20 @@ myFunc(1, 2, 3); ```javascript function getFine(speed, amount) { - const formattedSpeed = new Intl.NumberFormat("en-US", { - style: "unit", - unit: "mile-per-hour", + const formattedSpeed = new Intl.NumberFormat('en-US', { + style: 'unit', + unit: 'mile-per-hour' }).format(speed); - const formattedAmount = new Intl.NumberFormat("en-US", { - style: "currency", - currency: "USD", + const formattedAmount = new Intl.NumberFormat('en-US', { + style: 'currency', + currency: 'USD' }).format(amount); return `The driver drove ${formattedSpeed} and has to pay ${formattedAmount}`; } -console.log(getFine(130, 300)); +console.log(getFine(130, 300)) ``` - A: The driver drove 130 and has to pay 300 @@ -4128,8 +4131,8 @@ With the `Intl.NumberFormat` method, we can format numeric values to any locale. ###### 127. What's the output? ```javascript -const spookyItems = ["👻", "🎃", "🕸"]; -({ item: spookyItems[3] } = { item: "💀" }); +const spookyItems = ['👻', '🎃', '🕸']; +({ item: spookyItems[3] } = { item: '💀' }); console.log(spookyItems); ``` @@ -4154,7 +4157,7 @@ By destructuring objects, we can unpack values from the right-hand object, and a ###### 128. What's the output? ```javascript -const name = "Lydia Hallie"; +const name = 'Lydia Hallie'; const age = 21; console.log(Number.isNaN(name)); @@ -4190,7 +4193,7 @@ const randomValue = 21; function getInfo() { console.log(typeof randomValue); - const randomValue = "Lydia Hallie"; + const randomValue = 'Lydia Hallie'; } getInfo(); @@ -4216,7 +4219,7 @@ Variables declared with the `const` keyword are not referenceable before their i ###### 130. What's the output? ```javascript -const myPromise = Promise.resolve("Woah some cool data"); +const myPromise = Promise.resolve('Woah some cool data'); (async () => { try { @@ -4224,7 +4227,7 @@ const myPromise = Promise.resolve("Woah some cool data"); } catch { throw new Error(`Oops didn't work`); } finally { - console.log("Oh finally!"); + console.log('Oh finally!'); } })(); ``` @@ -4249,7 +4252,7 @@ In the `try` block, we're logging the awaited value of the `myPromise` variable: ###### 131. What's the output? ```javascript -const emojis = ["🥑", ["✨", "✨", ["🍕", "🍕"]]]; +const emojis = ['🥑', ['✨', '✨', ['🍕', '🍕']]]; console.log(emojis.flat(1)); ``` @@ -4322,19 +4325,19 @@ We invoke `counterTwo.increment()`, which sets `count` to `3`. Then, we log the ###### 133. What's the output? ```javascript -const myPromise = Promise.resolve(Promise.resolve("Promise")); +const myPromise = Promise.resolve(Promise.resolve('Promise')); function funcOne() { - setTimeout(() => console.log("Timeout 1!"), 0); - myPromise.then((res) => res).then((res) => console.log(`${res} 1!`)); - console.log("Last line 1!"); + setTimeout(() => console.log('Timeout 1!'), 0); + myPromise.then(res => res).then(res => console.log(`${res} 1!`)); + console.log('Last line 1!'); } async function funcTwo() { const res = await myPromise; - console.log(`${res} 2!`); - setTimeout(() => console.log("Timeout 2!"), 0); - console.log("Last line 2!"); + console.log(`${res} 2!`) + setTimeout(() => console.log('Timeout 2!'), 0); + console.log('Last line 2!'); } funcOne(); @@ -4355,7 +4358,7 @@ First, we invoke `funcOne`. On the first line of `funcOne`, we call the _asynchr Then we call the `myPromise` promise, which is an _asynchronous_ operation. -Both the promise and the timeout are asynchronous operations, the function keeps on running while it's busy completing the promise and handling the `setTimeout` callback. This means that `Last line 1!` gets logged first, since this is not an asynchonous operation. +Both the promise and the timeout are asynchronous operations, the function keeps on running while it's busy completing the promise and handling the `setTimeout` callback. This means that `Last line 1!` gets logged first, since this is not an asynchonous operation. Since the callstack is not empty yet, the `setTimeout` function and promise in `funcOne` cannot get added to the callstack yet. @@ -4379,7 +4382,7 @@ export default function sum(x) { } // index.js -import * as sum from "./sum"; +import * as sum from './sum'; ``` - A: `sum(4)` @@ -4396,12 +4399,12 @@ With the asterisk `*`, we import all exported values from that file, both defaul ```javascript // info.js -export const name = "Lydia"; +export const name = 'Lydia'; export const age = 21; -export default "I love JavaScript"; +export default 'I love JavaScript'; // index.js -import * as info from "./info"; +import * as info from './info'; console.log(info); ``` @@ -4432,13 +4435,13 @@ We can invoke this function, by calling `sum.default` ```javascript const handler = { - set: () => console.log("Added a new property!"), - get: () => console.log("Accessed a property!"), + set: () => console.log('Added a new property!'), + get: () => console.log('Accessed a property!'), }; const person = new Proxy({}, handler); -person.name = "Lydia"; +person.name = 'Lydia'; person.name; ``` @@ -4468,7 +4471,7 @@ Then, we access a property value on the proxy object, the `get` property on the ###### 136. Which of the following will modify the `person` object? ```javascript -const person = { name: "Lydia Hallie" }; +const person = { name: 'Lydia Hallie' }; Object.seal(person); ``` @@ -4496,9 +4499,9 @@ However, you can still modify the value of existing properties. ```javascript const person = { - name: "Lydia Hallie", + name: 'Lydia Hallie', address: { - street: "100 Main St", + street: '100 Main St', }, }; @@ -4527,7 +4530,7 @@ However, it only _shallowly_ freezes the object, meaning that only _direct_ prop ###### 138. What's the output? ```javascript -const add = (x) => x + x; +const add = x => x + x; function myFunc(num = 2, value = add(num)) { console.log(num, value); @@ -4560,21 +4563,21 @@ Then, we invoked `myFunc(3)` and passed the value `3` as the value for the argum ```javascript class Counter { - #number = 10; + #number = 10 increment() { - this.#number++; + this.#number++ } getNum() { - return this.#number; + return this.#number } } -const counter = new Counter(); -counter.increment(); +const counter = new Counter() +counter.increment() -console.log(counter.#number); +console.log(counter.#number) ``` - A: `10` @@ -4598,8 +4601,8 @@ In ES2020, we can add private variables in classes by using the `#`. We cannot a ```javascript const teams = [ - { name: "Team 1", members: ["Paul", "Lisa"] }, - { name: "Team 2", members: ["Laura", "Tim"] }, + { name: 'Team 1', members: ['Paul', 'Lisa'] }, + { name: 'Team 2', members: ['Laura', 'Tim'] }, ]; function* getMembers(members) { @@ -4642,8 +4645,8 @@ If we would've written `yield`, `return yield`, or `return`, the entire generato ```javascript const person = { - name: "Lydia Hallie", - hobbies: ["coding"], + name: 'Lydia Hallie', + hobbies: ['coding'], }; function addHobby(hobby, hobbies = person.hobbies) { @@ -4651,9 +4654,9 @@ function addHobby(hobby, hobbies = person.hobbies) { return hobbies; } -addHobby("running", []); -addHobby("dancing"); -addHobby("baking", person.hobbies); +addHobby('running', []); +addHobby('dancing'); +addHobby('baking', person.hobbies); console.log(person.hobbies); ``` @@ -4722,11 +4725,11 @@ We create the variable `pet` which is an instance of the `Flamingo` class. When ###### 143. Which of the options result(s) in an error? ```javascript -const emojis = ["🎄", "🎅🏼", "🎁", "⭐"]; +const emojis = ['🎄', '🎅🏼', '🎁', '⭐']; -/* 1 */ emojis.push("🦌"); +/* 1 */ emojis.push('🦌'); /* 2 */ emojis.splice(0, 2); -/* 3 */ emojis = [...emojis, "🥂"]; +/* 3 */ emojis = [...emojis, '🥂']; /* 4 */ emojis.length = 0; ``` @@ -4781,11 +4784,11 @@ Objects aren't iterable by default. An iterable is an iterable if the iterator p let count = 0; const nums = [0, 1, 2, 3]; -nums.forEach((num) => { - if (num) count += 1; -}); +nums.forEach(num => { + if (num) count += 1 +}) -console.log(count); +console.log(count) ``` - A: 1 @@ -4809,12 +4812,12 @@ The `if` condition within the `forEach` loop checks whether the value of `num` i ```javascript function getFruit(fruits) { - console.log(fruits?.[1]?.[1]); + console.log(fruits?.[1]?.[1]) } -getFruit([["🍊", "🍌"], ["🍍"]]); -getFruit(); -getFruit([["🍍"], ["🍊", "🍌"]]); +getFruit([['🍊', '🍌'], ['🍍']]) +getFruit() +getFruit([['🍍'], ['🍊', '🍌']]) ``` - A: `null`, `undefined`, 🍌 @@ -4827,11 +4830,11 @@ getFruit([["🍍"], ["🍊", "🍌"]]); #### Answer: D -The `?` allows us to optionally access deeper nested properties within objects. We're trying to log the item on index `1` within the subarray that's on index `1` of the `fruits` array. If the subarray on index `1` in the `fruits` array doesn't exist, it'll simply return `undefined`. If the subarray on index `1` in the `fruits` array exists, but this subarray doesn't have an item on its `1` index, it'll also return `undefined`. +The `?` allows us to optionally access deeper nested properties within objects. We're trying to log the item on index `1` within the subarray that's on index `1` of the `fruits` array. If the subarray on index `1` in the `fruits` array doesn't exist, it'll simply return `undefined`. If the subarray on index `1` in the `fruits` array exists, but this subarray doesn't have an item on its `1` index, it'll also return `undefined`. First, we're trying to log the second item in the `['🍍']` subarray of `[['🍊', '🍌'], ['🍍']]`. This subarray only contains one item, which means there is no item on index `1`, and returns `undefined`. -Then, we're invoking the `getFruits` function without passing a value as an argument, which means that `fruits` has a value of `undefined` by default. Since we're conditionally chaining the item on index `1` of`fruits`, it returns `undefined` since this item on index `1` does not exist. +Then, we're invoking the `getFruits` function without passing a value as an argument, which means that `fruits` has a value of `undefined` by default. Since we're conditionally chaining the item on index `1` of`fruits`, it returns `undefined` since this item on index `1` does not exist. Lastly, we're trying to log the second item in the `['🍊', '🍌']` subarray of `['🍍'], ['🍊', '🍌']`. The item on index `1` within this subarray is `🍌`, which gets logged. @@ -4844,19 +4847,19 @@ Lastly, we're trying to log the second item in the `['🍊', '🍌']` subarray o ```javascript class Calc { - constructor() { - this.count = 0; - } + constructor() { + this.count = 0 + } - increase() { - this.count++; - } + increase() { + this.count ++ + } } -const calc = new Calc(); -new Calc().increase(); +const calc = new Calc() +new Calc().increase() -console.log(calc.count); +console.log(calc.count) ``` - A: `0` @@ -4880,25 +4883,25 @@ We set the variable `calc` equal to a new instance of the `Calc` class. Then, we ```javascript const user = { - email: "e@mail.com", - password: "12345", -}; + email: "e@mail.com", + password: "12345" +} const updateUser = ({ email, password }) => { - if (email) { - Object.assign(user, { email }); - } + if (email) { + Object.assign(user, { email }) + } - if (password) { - user.password = password; - } + if (password) { + user.password = password + } - return user; -}; + return user +} -const updatedUser = updateUser({ email: "new@email.com" }); +const updatedUser = updateUser({ email: "new@email.com" }) -console.log(updatedUser === user); +console.log(updatedUser === user) ``` - A: `false` @@ -4921,13 +4924,13 @@ The `updateUser` function updates the values of the `email` and `password` prope ###### 149. What's the output? ```javascript -const fruit = ["🍌", "🍊", "🍎"]; +const fruit = ['🍌', '🍊', '🍎'] -fruit.slice(0, 1); -fruit.splice(0, 1); -fruit.unshift("🍇"); +fruit.slice(0, 1) +fruit.splice(0, 1) +fruit.unshift('🍇') -console.log(fruit); +console.log(fruit) ``` - A: `['🍌', '🍊', '🍎']` @@ -4942,7 +4945,7 @@ console.log(fruit); First, we invoke the `slice` method on the fruit array. The slice method does not modify the original array, but returns the value that it sliced off the array: the banana emoji. Then, we invoke the `splice` method on the fruit array. The splice method does modify the original array, which means that the fruit array now consists of `['🍊', '🍎']`. -At last, we invoke the `unshift` method on the `fruit` array, which modifies the original array by adding the provided value, ‘🍇’ in this case, as the first element in the array. The fruit array now consists of `['🍇', '🍊', '🍎']`. +At last, we invoke the `unshift` method on the `fruit` array, which modifies the original array by adding the provided value, ‘🍇’ in this case, as the first element in the array. The fruit array now consists of `['🍇', '🍊', '🍎']`.

@@ -4953,13 +4956,13 @@ At last, we invoke the `unshift` method on the `fruit` array, which modifies the ```javascript const animals = {}; -let dog = { emoji: "🐶" }; -let cat = { emoji: "🐈" }; +let dog = { emoji: '🐶' } +let cat = { emoji: '🐈' } -animals[dog] = { ...dog, name: "Mara" }; -animals[cat] = { ...cat, name: "Sara" }; +animals[dog] = { ...dog, name: "Mara" } +animals[cat] = { ...cat, name: "Sara" } -console.log(animals[dog]); +console.log(animals[dog]) ``` - A: `{ emoji: "🐶", name: "Mara" }` @@ -4972,11 +4975,11 @@ console.log(animals[dog]); #### Answer: B -Object keys are converted to strings. +Object keys are converted to strings. -Since the value of `dog` is an object, `animals[dog]` actually means that we’re creating a new property called `"[object Object]"` equal to the new object. `animals["[object Object]"]` is now equal to `{ emoji: "🐶", name: "Mara"}`. +Since the value of `dog` is an object, `animals[dog]` actually means that we’re creating a new property called `"[object Object]"` equal to the new object. `animals["[object Object]"]` is now equal to `{ emoji: "🐶", name: "Mara"}`. -`cat` is also an object, which means that `animals[cat]` actually means that we’re overwriting the value of `animals["[object Object]"]` with the new cat properties. +`cat` is also an object, which means that `animals[cat]` actually means that we’re overwriting the value of `animals["[object Object]"]` with the new cat properties. Logging `animals[dog]`, or actually `animals["[object Object]"]` since converting the `dog` object to a string results `"[object Object]"`, returns the `{ emoji: "🐈", name: "Sara" }`. @@ -4989,14 +4992,14 @@ Logging `animals[dog]`, or actually `animals["[object Object]"]` since convertin ```javascript const user = { - email: "my@email.com", - updateEmail: (email) => { - this.email = email; - }, -}; + email: "my@email.com", + updateEmail: email => { + this.email = email + } +} -user.updateEmail("new@email.com"); -console.log(user.email); +user.updateEmail("new@email.com") +console.log(user.email) ``` - A: `my@email.com` @@ -5009,7 +5012,7 @@ console.log(user.email); #### Answer: A -The `updateEmail` function is an arrow function, and is not bound to the `user` object. This means that the `this` keyword is not referring to the `user` object, but refers to the global scope in this case. The value of `email` within the `user` object does not get updated. When logging the value of `user.email`, the original value of `my@email.com` gets returned. +The `updateEmail` function is an arrow function, and is not bound to the `user` object. This means that the `this` keyword is not referring to the `user` object, but refers to the global scope in this case. The value of `email` within the `user` object does not get updated. When logging the value of `user.email`, the original value of `my@email.com` gets returned.

@@ -5019,20 +5022,20 @@ The `updateEmail` function is an arrow function, and is not bound to the `user` ###### 152. What's the output? ```javascript -const promise1 = Promise.resolve("First"); -const promise2 = Promise.resolve("Second"); -const promise3 = Promise.reject("Third"); -const promise4 = Promise.resolve("Fourth"); +const promise1 = Promise.resolve('First') +const promise2 = Promise.resolve('Second') +const promise3 = Promise.reject('Third') +const promise4 = Promise.resolve('Fourth') const runPromises = async () => { - const res1 = await Promise.all([promise1, promise2]); - const res2 = await Promise.all([promise3, promise4]); - return [res1, res2]; -}; + const res1 = await Promise.all([promise1, promise2]) + const res2 = await Promise.all([promise3, promise4]) + return [res1, res2] +} runPromises() - .then((res) => console.log(res)) - .catch((err) => console.log(err)); + .then(res => console.log(res)) + .catch(err => console.log(err)) ``` - A: `[['First', 'Second'], ['Fourth']]` @@ -5045,26 +5048,23 @@ runPromises() #### Answer: D -The `Promise.all` method runs the passed promises in parallel. If one promise fails, the `Promise.all` method _rejects_ with the value of the rejected promise. In this case, `promise3` rejected with the value `"Third"`. We’re catching the rejected value in the chained `catch` method on the `runPromises` invocation to catch any errors within the `runPromises` function. Only `"Third"` gets logged, since `promise3` rejected with this value. +The `Promise.all` method runs the passed promises in parallel. If one promise fails, the `Promise.all` method _rejects_ with the value of the rejected promise. In this case, `promise3` rejected with the value `"Third"`. We’re catching the rejected value in the chained `catch` method on the `runPromises` invocation to catch any errors within the `runPromises` function. Only `"Third"` gets logged, since `promise3` rejected with this value.

--- -###### 153. What should the value of `method` be to log `{ name: "Lydia", age: 22 }`? +###### 153. What should the value of `method` be to log `{ name: "Lydia", age: 22 }`? ```javascript -const keys = ["name", "age"]; -const values = ["Lydia", 22]; +const keys = ["name", "age"] +const values = ["Lydia", 22] -const method = - /* ?? */ - Object[method]( - keys.map((_, i) => { - return [keys[i], values[i]]; - }) - ); // { name: "Lydia", age: 22 } +const method = /* ?? */ +Object[method](keys.map((_, i) => { + return [keys[i], values[i]] +})) // { name: "Lydia", age: 22 } ``` - A: `entries` @@ -5077,7 +5077,7 @@ const method = #### Answer: C -The `fromEntries` method turns a 2d array into an object. The first element in each subarray will be the key, and the second element in each subarray will be the value. In this case, we’re mapping over the `keys` array, which returns an array which first element is the item on the key array on the current index, and the second element is the item of the values array on the current index. +The `fromEntries` method turns a 2d array into an object. The first element in each subarray will be the key, and the second element in each subarray will be the value. In this case, we’re mapping over the `keys` array, which returns an array which first element is the item on the key array on the current index, and the second element is the item of the values array on the current index. This creates an array of subarrays containing the correct keys and values, which results in `{ name: "Lydia", age: 22 }` @@ -5089,18 +5089,18 @@ This creates an array of subarrays containing the correct keys and values, which ###### 154. What's the output? ```javascript -const createMember = ({ email, address = {} }) => { - const validEmail = /.+\@.+\..+/.test(email); - if (!validEmail) throw new Error("Valid email pls"); +const createMember = ({ email, address = {}}) => { + const validEmail = /.+\@.+\..+/.test(email) + if (!validEmail) throw new Error("Valid email pls") - return { - email, - address: address ? address : null, - }; -}; + return { + email, + address: address ? address : null + } +} -const member = createMember({ email: "my@email.com" }); -console.log(member); +const member = createMember({ email: "my@email.com" }) +console.log(member) ``` - A: `{ email: "my@email.com", address: null }` @@ -5123,13 +5123,13 @@ The default value of `address` is an empty object `{}`. When we set the variable ###### 155. What's the output? ```javascript -let randomValue = { name: "Lydia" }; -randomValue = 23; +let randomValue = { name: "Lydia" } +randomValue = 23 if (!typeof randomValue === "string") { - console.log("It's not a string!"); + console.log("It's not a string!") } else { - console.log("Yay it's a string!"); + console.log("Yay it's a string!") } ``` From b9ccdec1cf38c76390065db4a62d5e8e89c3bbb7 Mon Sep 17 00:00:00 2001 From: ihavecoke Date: Mon, 11 Sep 2023 00:47:52 +0800 Subject: [PATCH 180/193] Apply community guidelines for English and Chinese typography to format Simplified Chinese documentation --from https://sparanoid.com/note/chinese-copywriting-guidelines/ --- zh-CN/README-zh_CN.md | 562 +++++++++++++++++++++--------------------- 1 file changed, 281 insertions(+), 281 deletions(-) diff --git a/zh-CN/README-zh_CN.md b/zh-CN/README-zh_CN.md index 12b932e5..71f0f9df 100644 --- a/zh-CN/README-zh_CN.md +++ b/zh-CN/README-zh_CN.md @@ -30,7 +30,7 @@ sayHi()
答案

-#### 答案: D +#### 答案:D 在函数内部,我们首先通过 `var` 关键字声明了 `name` 变量。这意味着变量被提升了(内存空间在创建阶段就被设置好了),直到程序运行到定义变量位置之前默认值都是 `undefined`。因为当我们打印 `name` 变量时还没有执行到定义变量的位置,因此变量的值保持为 `undefined`。 @@ -60,7 +60,7 @@ for (let i = 0; i < 3; i++) {

答案

-#### 答案: C +#### 答案:C 由于 JavaScript 的事件循环,`setTimeout` 回调会在*遍历结束后*才执行。因为在第一个遍历中遍历 `i` 是通过 `var` 关键字声明的,所以这个值是全局作用域下的。在遍历过程中,我们通过一元操作符 `++` 来每次递增 `i` 的值。当 `setTimeout` 回调执行的时候,`i` 的值等于 3。 @@ -94,7 +94,7 @@ shape.perimeter()

答案

-#### 答案: B +#### 答案:B 注意 `diameter` 的值是一个常规函数,但是 `perimeter` 的值是一个箭头函数。 @@ -121,7 +121,7 @@ shape.perimeter()

答案

-#### 答案: A +#### 答案:A 一元操作符加号尝试将 bool 转为 number。`true` 转换为 number 的话为 `1`,`false` 为 `0`。 @@ -153,7 +153,7 @@ const mouse = {

答案

-#### 答案: A +#### 答案:A 在 JavaScript 中,所有对象的 keys 都是字符串(除非对象是 Symbol)。尽管我们可能不会定义它们为字符串,但它们在底层总会被转换为字符串。 @@ -188,7 +188,7 @@ console.log(d.greeting)

答案

-#### 答案: A +#### 答案:A 在 JavaScript 中,当设置两个对象彼此相等时,它们会通过*引用*进行交互。 @@ -223,7 +223,7 @@ console.log(b === c)

答案

-#### 答案: C +#### 答案:C `new Number()` 是一个内建的函数构造器。虽然它看着像是一个 number,但它实际上并不是一个真实的 number:它有一堆额外的功能并且它是一个对象。 @@ -262,7 +262,7 @@ freddie.colorChange('orange')

答案

-#### 答案: D +#### 答案:D `colorChange` 是一个静态方法。静态方法被设计为只能被创建它们的构造器使用(也就是 `Chameleon`),并且不能传递给实例。因为 `freddie` 是一个实例,静态方法不能被实例使用,因此抛出了 `TypeError` 错误。 @@ -286,7 +286,7 @@ console.log(greetign)

答案

-#### 答案: A +#### 答案:A 代码打印出了一个对象,这是因为我们在全局对象上创建了一个空对象!当我们将 `greeting` 写错成 `greetign` 时,JS 解释器实际在上浏览器中将它视为 `global.greetign = {}`(或者 `window.greetign = {}`)。 @@ -315,7 +315,7 @@ bark.animal = 'dog'

答案

-#### 答案: A +#### 答案:A 这在 JavaScript 中是可以的,因为函数是对象!(除了基本类型之外其他都是对象) @@ -350,7 +350,7 @@ console.log(member.getFullName());

答案

-#### 答案: A +#### 答案:A 你不能像常规对象那样,给构造函数添加属性。如果你想一次性给所有实例添加特性,你应该使用原型。因此本例中,使用如下方式: @@ -390,7 +390,7 @@ console.log(sarah)

答案

-#### 答案: A +#### 答案:A 对于 `sarah`,我们没有使用 `new` 关键字。当使用 `new` 时,`this` 引用我们创建的空对象。当未使用 `new` 时,`this` 引用的是**全局对象**(global object)。 @@ -411,7 +411,7 @@ console.log(sarah)

答案

-#### 答案: D +#### 答案:D 在**捕获**(capturing)阶段中,事件从祖先元素向下传播到目标元素。当事件达到**目标**(target)元素后,**冒泡**(bubbling)才开始。 @@ -430,7 +430,7 @@ console.log(sarah)

答案

-#### 答案: B +#### 答案:B 除了**基本对象**(base object),所有对象都有原型。基本对象可以访问一些方法和属性,比如 `.toString`。这就是为什么你可以使用内置的 JavaScript 方法!所有这些方法在原型上都是可用的。虽然 JavaScript 不能直接在对象上找到这些方法,但 JavaScript 会沿着原型链找到它们,以便于你使用。 @@ -457,7 +457,7 @@ sum(1, '2')

答案

-#### 答案: C +#### 答案:C JavaScript 是一种**动态类型语言**:我们不指定某些变量的类型。值可以在你不知道的情况下自动转换成另一种类型,这种类型称为**隐式类型转换**(implicit type coercion)。**Coercion** 是指将一种类型转换为另一种类型。 @@ -485,7 +485,7 @@ console.log(number)

答案

-#### 答案: C +#### 答案:C 一元**后自增**运算符 `++`: @@ -526,7 +526,7 @@ getPersonInfo`${person} is ${age} years old`

答案

-#### 答案: B +#### 答案:B 如果使用标记模板字面量,第一个参数的值总是包含字符串的数组。其余的参数获取的是传递的表达式的值! @@ -558,7 +558,7 @@ checkAge({ age: 18 })

答案

-#### 答案: C +#### 答案:C 在测试相等性时,基本类型通过它们的值(value)进行比较,而对象通过它们的引用(reference)进行比较。JavaScript 检查对象是否具有对内存中相同位置的引用。 @@ -589,7 +589,7 @@ getAge(21)

答案

-#### 答案: C +#### 答案:C 扩展运算符(`...args`)会返回实参组成的数组。而数组是对象,因此 `typeof args` 返回 `"object"`。 @@ -618,7 +618,7 @@ getAge()

答案

-#### 答案: C +#### 答案:C 使用 `"use strict"`,你可以确保不会意外地声明全局变量。我们从来没有声明变量 `age`,因为我们使用 `"use strict"`,它将抛出一个引用错误。如果我们不使用 `"use strict"`,它就会工作,因为属性 `age` 会被添加到全局对象中了。 @@ -641,7 +641,7 @@ const sum = eval('10*10+5')

答案

-#### 答案: A +#### 答案:A 代码以字符串形式传递进来,`eval` 对其求值。如果它是一个表达式,就像本例中那样,它对表达式求值。表达式是 `10 * 10 + 5`。这将返回数字 `105`。 @@ -664,7 +664,7 @@ sessionStorage.setItem('cool_secret', 123)

答案

-#### 答案: B +#### 答案:B 关闭 **tab 标签页** 后,`sessionStorage` 存储的数据才会删除。 @@ -692,7 +692,7 @@ console.log(num)

答案

-#### 答案: B +#### 答案:B 使用 `var` 关键字,你可以用相同的名称声明多个变量。然后变量将保存最新的值。 @@ -723,7 +723,7 @@ set.has(1)

答案

-#### 答案: C +#### 答案:C 所有对象的键(不包括 Symbol)在底层都是字符串,即使你自己没有将其作为字符串输入。这就是为什么 `obj.hasOwnProperty('1')` 也返回 `true`。 @@ -749,7 +749,7 @@ console.log(obj)

答案

-#### 答案: C +#### 答案:C 如果你有两个名称相同的键,则键会被替换掉。它仍然位于第一个键出现的位置,但是值是最后出现那个键的值。 @@ -767,7 +767,7 @@ console.log(obj)

答案

-#### 答案: A +#### 答案:A 基本执行上下文是全局执行上下文:它是代码中随处可访问的内容。 @@ -793,7 +793,7 @@ for (let i = 1; i < 5; i++) {

答案

-#### 答案: C +#### 答案:C 如果某个条件返回 `true`,则 `continue` 语句跳过本次迭代。 @@ -822,7 +822,7 @@ name.giveLydiaPizza()

答案

-#### 答案: A +#### 答案:A `String` 是内置的构造函数,我们可以向它添加属性。我只是在它的原型中添加了一个方法。基本类型字符串被自动转换为字符串对象,由字符串原型函数生成。因此,所有 string(string 对象) 都可以访问该方法! @@ -852,7 +852,7 @@ console.log(a[b])

答案

-#### 答案: B +#### 答案:B 对象的键被自动转换为字符串。我们试图将一个对象 `b` 设置为对象 `a` 的键,且相应的值为 `123`。 @@ -885,7 +885,7 @@ baz()

答案

-#### 答案: B +#### 答案:B 我们有一个 `setTimeout` 函数,并首先调用它。然而,它是最后打印日志的。 @@ -938,7 +938,7 @@ WebAPI 不能随时向栈内添加内容。相反,它将回调函数推到名

答案

-#### 答案: C +#### 答案:C 导致事件的最深嵌套的元素是事件的 target。你可以通过 `event.stopPropagation` 来停止冒泡。 @@ -965,7 +965,7 @@ WebAPI 不能随时向栈内添加内容。相反,它将回调函数推到名

答案

-#### 答案: A +#### 答案:A 如果我们点击 `p`,我们会看到两个日志:`p` 和 `div`。在事件传播期间,有三个阶段:捕获、目标和冒泡。默认情况下,事件处理程序在冒泡阶段执行(除非将 `useCapture` 设置为 `true`)。它从嵌套最深的元素向外传播。 @@ -995,7 +995,7 @@ sayHi.bind(person, 21)

答案

-#### 答案: D +#### 答案:D 使用这两种方法,我们都可以传递我们希望 `this` 关键字引用的对象。但是,`.call` 是**立即执行**的。 @@ -1024,11 +1024,11 @@ typeof sayHi()

答案

-#### 答案: B +#### 答案:B -`sayHi` 方法返回的是立即执行函数 (IIFE) 的返回值。此立即执行函数的返回值是 `0`, 类型是 `number` +`sayHi` 方法返回的是立即执行函数 (IIFE) 的返回值。此立即执行函数的返回值是 `0`,类型是 `number` -参考:只有 7 种内置类型:`null`,`undefined`,`boolean`,`number`,`string`,`object`, `symbol` 和 `bigint`。 ``function`` 不是一种类型,函数是对象,它的类型是``object``。 +参考:只有 7 种内置类型:`null`,`undefined`,`boolean`,`number`,`string`,`object`, `symbol` 和 `bigint`。``function`` 不是一种类型,函数是对象,它的类型是``object``。

@@ -1054,7 +1054,7 @@ undefined
答案

-#### 答案: A +#### 答案:A 只有 8 种 [falsy](https://developer.mozilla.org/zh-CN/docs/Glossary/Falsy) 值: @@ -1090,7 +1090,7 @@ console.log(typeof typeof 1)

答案

-#### 答案: B +#### 答案:B `typeof 1` 返回 `"number"`。 `typeof "number"` 返回 `"string"`。 @@ -1116,9 +1116,9 @@ console.log(numbers)

答案

-#### 答案: C +#### 答案:C -当你为数组设置超过数组长度的值的时候, JavaScript 会创建名为 "empty slots" 的东西。它们的值实际上是 `undefined`。你会看到以下场景: +当你为数组设置超过数组长度的值的时候,JavaScript 会创建名为 "empty slots" 的东西。它们的值实际上是 `undefined`。你会看到以下场景: `[1, 2, 3, 7 x empty, 11]` @@ -1153,13 +1153,13 @@ console.log(numbers)

答案

-#### 答案: A +#### 答案:A -`catch` 代码块接收参数 `x`。当我们传递参数时,这与之前定义的变量 `x` 不同 。这个 `x` 是属于 `catch` 块级作用域的。 +`catch` 代码块接收参数 `x`。当我们传递参数时,这与之前定义的变量 `x` 不同。这个 `x` 是属于 `catch` 块级作用域的。 然后,我们将块级作用域中的变量赋值为 `1`,同时也设置了变量 `y` 的值。现在,我们打印块级作用域中的变量 `x`,值为 `1`。 -`catch` 块之外的变量 `x` 的值仍为 `undefined`, `y` 的值为 `2`。当我们在 `catch` 块之外执行 `console.log(x)` 时,返回 `undefined`,`y` 返回 `2`。 +`catch` 块之外的变量 `x` 的值仍为 `undefined`,`y` 的值为 `2`。当我们在 `catch` 块之外执行 `console.log(x)` 时,返回 `undefined`,`y` 返回 `2`。

@@ -1176,7 +1176,7 @@ console.log(numbers)
答案

-#### 答案: A +#### 答案:A JavaScript 只有基本类型和对象。 @@ -1206,10 +1206,10 @@ JavaScript 只有基本类型和对象。

答案

-#### 答案: C +#### 答案:C -`[1, 2]`是初始值。初始值将会作为首次调用时第一个参数 `acc` 的值。在第一次执行时, `acc` 的值是 `[1, 2]`, `cur` 的值是 `[0, 1]`。合并它们,结果为 `[1, 2, 0, 1]`。 -第二次执行, `acc` 的值是 `[1, 2, 0, 1]`, `cur` 的值是 `[2, 3]`。合并它们,最终结果为 `[1, 2, 0, 1, 2, 3]` +`[1, 2]`是初始值。初始值将会作为首次调用时第一个参数 `acc` 的值。在第一次执行时,`acc` 的值是 `[1, 2]`,`cur` 的值是 `[0, 1]`。合并它们,结果为 `[1, 2, 0, 1]`。 +第二次执行,`acc` 的值是 `[1, 2, 0, 1]`,`cur` 的值是 `[2, 3]`。合并它们,最终结果为 `[1, 2, 0, 1, 2, 3]`

@@ -1232,13 +1232,13 @@ JavaScript 只有基本类型和对象。
答案

-#### 答案: B +#### 答案:B -`null` 是 [falsy](https://developer.mozilla.org/zh-CN/docs/Glossary/Falsy)。 `!null` 的值是 `true`。 `!true` 的值是 `false`。 +`null` 是 [falsy](https://developer.mozilla.org/zh-CN/docs/Glossary/Falsy)。`!null` 的值是 `true`。`!true` 的值是 `false`。 -`""` 是 [falsy](https://developer.mozilla.org/zh-CN/docs/Glossary/Falsy)。 `!""` 的值是 `true`。 `!true` 的值是 `false`。 +`""` 是 [falsy](https://developer.mozilla.org/zh-CN/docs/Glossary/Falsy)。`!""` 的值是 `true`。`!true` 的值是 `false`。 -`1` 是 [truthy](https://developer.mozilla.org/zh-CN/docs/Glossary/Truthy)。 `!1` 的值是 `false`。 `!false` 的值是 `true`。 +`1` 是 [truthy](https://developer.mozilla.org/zh-CN/docs/Glossary/Truthy)。`!1` 的值是 `false`。`!false` 的值是 `true`。

@@ -1259,7 +1259,7 @@ setInterval(() => console.log('Hi'), 1000)
答案

-#### 答案: A +#### 答案:A `setInterval` 返回一个唯一的 id。此 id 可被用于 `clearInterval` 函数来取消定时。 @@ -1282,7 +1282,7 @@ setInterval(() => console.log('Hi'), 1000)

答案

-#### 答案: A +#### 答案:A string 类型是可迭代的。扩展运算符将迭代的每个字符映射成一个元素。 @@ -1313,11 +1313,11 @@ console.log(gen.next().value);

答案

-#### 答案: C +#### 答案:C -一般的函数在执行之后是不能中途停下的。但是,生成器函数却可以中途 “停下”,之后可以再从停下的地方继续。当生成器遇到`yield`关键字的时候,会生成`yield`后面的值。注意,生成器在这种情况下不 _返回_ (_return_ ) 值,而是 _生成_ (_yield_) 值。 +一般的函数在执行之后是不能中途停下的。但是,生成器函数却可以中途“停下”,之后可以再从停下的地方继续。当生成器遇到`yield`关键字的时候,会生成`yield`后面的值。注意,生成器在这种情况下不 _返回_ (_return_ ) 值,而是 _生成_ (_yield_) 值。 -首先,我们用`10`作为参数`i`来初始化生成器函数。然后使用`next()`方法一步步执行生成器。第一次执行生成器的时候,`i`的值为`10`,遇到第一个`yield`关键字,它要生成`i`的值。此时,生成器 “暂停”,生成了`10`。 +首先,我们用`10`作为参数`i`来初始化生成器函数。然后使用`next()`方法一步步执行生成器。第一次执行生成器的时候,`i`的值为`10`,遇到第一个`yield`关键字,它要生成`i`的值。此时,生成器“暂停”,生成了`10`。 然后,我们再执行`next()`方法。生成器会从刚才暂停的地方继续,这个时候`i`还是`10`。于是我们走到了第二个`yield`关键字处,这时候需要生成的值是`i*2`,`i`为`10`,那么此时生成的值便是`20`。所以这道题的最终结果是`10,20`。 @@ -1347,7 +1347,7 @@ Promise.race([firstPromise, secondPromise]).then(res => console.log(res));

答案

-#### 答案: B +#### 答案:B 当我们向`Promise.race`方法中传入多个`Promise`时,会进行 _优先_ 解析。在这个例子中,我们用`setTimeout`给`firstPromise`和`secondPromise`分别设定了 500ms 和 100ms 的定时器。这意味着`secondPromise`会首先解析出字符串`two`。那么此时`res`参数即为`two`,是为输出结果。 @@ -1374,14 +1374,14 @@ console.log(members);

答案

-#### 答案: D +#### 答案:D 首先我们声明了一个拥有`name`属性的对象 `person`。 -然后我们又声明了一个变量`members`. 将首个元素赋值为变量`person`。 当设置两个对象彼此相等时,它们会通过 _引用_ 进行交互。但是当你将引用从一个变量分配至另一个变量时,其实只是执行了一个 _复制_ 操作。(注意一点,他们的引用 _并不相同_!) +然后我们又声明了一个变量`members`. 将首个元素赋值为变量`person`。当设置两个对象彼此相等时,它们会通过 _引用_ 进行交互。但是当你将引用从一个变量分配至另一个变量时,其实只是执行了一个 _复制_ 操作。(注意一点,他们的引用 _并不相同_!) @@ -1417,7 +1417,7 @@ for (const item in person) {

答案

-#### 答案: B +#### 答案:B 在`for-in`循环中,我们可以通过对象的 key 来进行迭代,也就是这里的`name`和`age`。在底层,对象的 key 都是字符串(如果他们不是 Symbol 的话)。在每次循环中,我们将`item`设定为当前遍历到的 key.所以一开始,`item`是`name`,之后 `item`输出的则是`age`。 @@ -1440,13 +1440,13 @@ console.log(3 + 4 + "5");

答案

-#### 答案: B +#### 答案:B 当所有运算符的 _优先级_ 相同时,计算表达式需要确定运算符的结合顺序,即从右到左还是从左往右。在这个例子中,我们只有一类运算符`+`,对于加法来说,结合顺序就是从左到右。 `3 + 4`首先计算,得到数字`7`. -由于类型的强制转换,`7 + '5'`的结果是`"75"`. JavaScript 将`7`转换成了字符串,可以参考问题 15.我们可以用`+`号把两个字符串连接起来。 `"7" + "5"` 就得到了`"75"`. +由于类型的强制转换,`7 + '5'`的结果是`"75"`. JavaScript 将`7`转换成了字符串,可以参考问题 15.我们可以用`+`号把两个字符串连接起来。`"7" + "5"` 就得到了`"75"`.

@@ -1467,7 +1467,7 @@ const num = parseInt("7*6", 10);
答案

-#### 答案: C +#### 答案:C 只返回了字符串中第一个字母。设定了 _进制_ 后 (也就是第二个参数,指定需要解析的数字是什么进制:十进制、十六机制、八进制、二进制等等……),`parseInt` 检查字符串中的字符是否合法。一旦遇到一个在指定进制中不合法的字符后,立即停止解析并且忽略后面所有的字符。 @@ -1495,7 +1495,7 @@ const num = parseInt("7*6", 10);

答案

-#### 答案: C +#### 答案:C 对数组进行映射的时候,`num`就是当前循环到的元素。在这个例子中,所有的映射都是 number 类型,所以 if 中的判断`typeof num === "number"`结果都是`true`.map 函数创建了新数组并且将函数的返回值插入数组。 @@ -1530,9 +1530,9 @@ console.log(person, birthYear);

答案

-#### 答案: A +#### 答案:A -普通参数都是 _值_ 传递的,而对象则不同,是 _引用_ 传递。所以说,`birthYear`是值传递,因为他是个字符串而不是对象。当我们对参数进行值传递时,会创建一份该值的 _复制_ 。(可以参考问题 46) +普通参数都是 _值_ 传递的,而对象则不同,是 _引用_ 传递。所以说,`birthYear`是值传递,因为他是个字符串而不是对象。当我们对参数进行值传递时,会创建一份该值的 _复制_。(可以参考问题 46) 变量`birthYear`有一个对`"1997"`的引用,而传入的参数也有一个对`"1997"`的引用,但二者的引用并不相同。当我们通过给 `year`赋值`"1998"`来更新`year`的值的时候我们只是更新了`year`(的引用)。此时`birthYear`仍然是`"1997"`. @@ -1570,9 +1570,9 @@ sayHi();

答案

-#### 答案: D +#### 答案:D -通过`throw`语句,我么可以创建自定义错误。 而通过它,我们可以抛出异常。异常可以是一个字符串,一个 数字,一个 布尔类型 或者是一个 对象。在本例中,我们的异常是字符串`'Hello world'`. +通过`throw`语句,我么可以创建自定义错误。而通过它,我们可以抛出异常。异常可以是一个字符串,一个 数字,一个 布尔类型 或者是一个 对象。在本例中,我们的异常是字符串`'Hello world'`. 通过 `catch`语句,我们可以设定当`try`语句块中抛出异常后应该做什么处理。在本例中抛出的异常是字符串`'Hello world'`. `e`就是这个字符串,因此被输出。最终结果就是`'Oh an error: Hello world'`. @@ -1601,7 +1601,7 @@ console.log(myCar.make);

答案

-#### 答案: B +#### 答案:B 返回属性的时候,属性的值等于 _返回的_ 值,而不是构造函数中设定的值。我们返回了字符串 `"Maserati"`,所以 `myCar.make`等于`"Maserati"`. @@ -1629,7 +1629,7 @@ console.log(typeof y);

答案

-#### 答案: A +#### 答案:A `let x = y = 10;` 是下面这个表达式的缩写: @@ -1638,11 +1638,11 @@ y = 10; let x = y; ``` -我们设定`y`等于`10`时,我们实际上增加了一个属性`y`给全局对象 (浏览器里的`window`, Nodejs 里的`global`)。在浏览器中, `window.y`等于`10`. +我们设定`y`等于`10`时,我们实际上增加了一个属性`y`给全局对象 (浏览器里的`window`, Nodejs 里的`global`)。在浏览器中,`window.y`等于`10`. 然后我们声明了变量`x`等于`y`,也是`10`.但变量是使用 `let`声明的,它只作用于 _块级作用域_,仅在声明它的块中有效;就是案例中的立即调用表达式 (IIFE)。使用`typeof`操作符时,操作值 `x`没有被定义:因为我们在`x`声明块的外部,无法调用它。这就意味着`x`未定义。未分配或是未声明的变量类型为`"undefined"`. `console.log(typeof x)`返回`"undefined"`. -而我们创建了全局变量`y`,并且设定`y`等于`10`.这个值在我们的代码各处都访问的到。 `y`已经被定义了,而且有一个`"number"`类型的值。 `console.log(typeof y)`返回`"number"`. +而我们创建了全局变量`y`,并且设定`y`等于`10`.这个值在我们的代码各处都访问的到。`y`已经被定义了,而且有一个`"number"`类型的值。`console.log(typeof y)`返回`"number"`.

@@ -1679,7 +1679,7 @@ pet.bark();
答案

-#### 答案: A +#### 答案:A 我们可以用`delete`关键字删除对象的属性,对原型也是适用的。删除了原型的属性后,该属性在原型链上就不可用了。在本例中,函数`bark`在执行了`delete Dog.prototype.bark`后不可用,然而后面的代码还在调用它。 @@ -1706,7 +1706,7 @@ console.log(set);

答案

-#### 答案: D +#### 答案:D `Set`对象是独一无二的值的集合:也就是说同一个值在其中仅出现一次。 @@ -1742,11 +1742,11 @@ console.log(myCounter);

答案

-#### 答案: C +#### 答案:C 引入的模块是 _只读_ 的:你不能修改引入的模块。只有导出他们的模块才能修改其值。 -当我们给`myCounter`增加一个值的时候会抛出一个异常: `myCounter`是只读的,不能被修改。 +当我们给`myCounter`增加一个值的时候会抛出一个异常:`myCounter`是只读的,不能被修改。

@@ -1771,9 +1771,9 @@ console.log(delete age);
答案

-#### 答案: A +#### 答案:A -`delete`操作符返回一个布尔值: `true`指删除成功,否则返回`false`. 但是通过 `var`, `const` 或 `let` 关键字声明的变量无法用 `delete` 操作符来删除。 +`delete`操作符返回一个布尔值:`true`指删除成功,否则返回`false`. 但是通过 `var`, `const` 或 `let` 关键字声明的变量无法用 `delete` 操作符来删除。 `name`变量由`const`关键字声明,所以删除不成功:返回 `false`. 而我们设定`age`等于`21`时,我们实际上添加了一个名为`age`的属性给全局对象。对象中的属性是可以删除的,全局对象也是如此,所以`delete age`返回`true`. @@ -1799,7 +1799,7 @@ console.log(y);

答案

-#### 答案: C +#### 答案:C 我们可以通过解构赋值来解析来自对象的数组或属性的值,比如说: @@ -1817,7 +1817,7 @@ console.log(y); -也就是说,`y`等于数组的第一个值就是数字`1`.我们输出`y`, 返回`1`. +也就是说,`y`等于数组的第一个值就是数字`1`.我们输出`y`,返回`1`.

@@ -1841,7 +1841,7 @@ console.log(admin);
答案

-#### 答案: B +#### 答案:B 扩展运算符`...`为对象的组合提供了可能。你可以复制对象中的键值对,然后把它们加到另一个对象里去。在本例中,我们复制了`user`对象键值对,然后把它们加入到`admin`对象中。`admin`对象就拥有了这些键值对,所以结果为`{ admin: true, name: "Lydia", age: 21 }`. @@ -1869,7 +1869,7 @@ console.log(Object.keys(person));

答案

-#### 答案: B +#### 答案:B 通过`defineProperty`方法,我们可以给对象添加一个新属性,或者修改已经存在的属性。而我们使用`defineProperty`方法给对象添加了一个属性之后,属性默认为 _不可枚举 (not enumerable)_. `Object.keys`方法仅返回对象中 _可枚举 (enumerable)_ 的属性,因此只剩下了`"name"`. @@ -1901,11 +1901,11 @@ console.log(data);

答案

-#### 答案: A +#### 答案:A `JSON.stringify`的第二个参数是 _替代者 (replacer)_. 替代者 (replacer) 可以是个函数或数组,用以控制哪些值如何被转换为字符串。 -如果替代者 (replacer) 是个 _数组_ ,那么就只有包含在数组中的属性将会被转化为字符串。在本例中,只有名为`"level"` 和 `"health"` 的属性被包括进来, `"username"`则被排除在外。 `data` 就等于 `"{"level":19, "health":90}"`. +如果替代者 (replacer) 是个 _数组_,那么就只有包含在数组中的属性将会被转化为字符串。在本例中,只有名为`"level"` 和 `"health"` 的属性被包括进来,`"username"`则被排除在外。`data` 就等于 `"{"level":19, "health":90}"`. 而如果替代者 (replacer) 是个 _函数_,这个函数将被对象的每个属性都调用一遍。 函数返回的值会成为这个属性的值,最终体现在转化后的 JSON 字符串中(译者注:Chrome 下,经过实验,如果所有属性均返回同一个值的时候有异常,会直接将返回值作为结果输出而不会输出 JSON 字符串),而如果返回值为`undefined`,则该属性会被排除在外。 @@ -1938,7 +1938,7 @@ console.log(num2);

答案

-#### 答案: A +#### 答案:A 一元操作符 `++` _先返回_ 操作值,_再累加_ 操作值。`num1`的值是`10`,因为`increaseNumber`函数首先返回`num`的值,也就是`10`,随后再进行 `num`的累加。 @@ -1972,15 +1972,15 @@ multiply(value);

答案

-#### 答案: C +#### 答案:C -在 ES6 中,我们可以使用默认值初始化参数。如果没有给函数传参,或者传的参值为 `"undefined"` ,那么参数的值将是默认值。上述例子中,我们将 `value` 对象进行了解构并传到一个新对象中,因此 `x` 的默认值为 `{number:10}` 。 +在 ES6 中,我们可以使用默认值初始化参数。如果没有给函数传参,或者传的参值为 `"undefined"`,那么参数的值将是默认值。上述例子中,我们将 `value` 对象进行了解构并传到一个新对象中,因此 `x` 的默认值为 `{number:10}`。 -默认参数在调用时才会进行计算,每次调用函数时,都会创建一个新的对象。我们前两次调用 `multiply` 函数且不传递值,那么每一次 `x` 的默认值都为 `{number:10}` ,因此打印出该数字的乘积值为`20`。 +默认参数在调用时才会进行计算,每次调用函数时,都会创建一个新的对象。我们前两次调用 `multiply` 函数且不传递值,那么每一次 `x` 的默认值都为 `{number:10}`,因此打印出该数字的乘积值为`20`。 -第三次调用 `multiply` 时,我们传递了一个参数,即对象`value`。 `*=`运算符实际上是`x.number = x.number * 2`的简写,我们修改了`x.number`的值,并打印出值`20`。 +第三次调用 `multiply` 时,我们传递了一个参数,即对象`value`。`*=`运算符实际上是`x.number = x.number * 2`的简写,我们修改了`x.number`的值,并打印出值`20`。 -第四次,我们再次传递`value`对象。 `x.number`之前被修改为`20`,所以`x.number * = 2`打印为`40`。 +第四次,我们再次传递`value`对象。`x.number`之前被修改为`20`,所以`x.number * = 2`打印为`40`。

@@ -2001,7 +2001,7 @@ multiply(value);
答案

-#### 答案: D +#### 答案:D `reducer` 函数接收 4 个参数: @@ -2018,9 +2018,9 @@ multiply(value); 在第一次调用时,累加器`x`为`1`,当前值`“y”`为`2`,打印出累加器和当前值:`1`和`2`。 -例子中我们的回调函数没有返回任何值,只是打印累加器的值和当前值。如果函数没有返回值,则默认返回`undefined`。 在下一次调用时,累加器为`undefined`,当前值为 “3”,因此`undefined`和`3`被打印出。 +例子中我们的回调函数没有返回任何值,只是打印累加器的值和当前值。如果函数没有返回值,则默认返回`undefined`。在下一次调用时,累加器为`undefined`,当前值为“3”,因此`undefined`和`3`被打印出。 -在第四次调用时,回调函数依然没有返回值。 累加器再次为 `undefined` ,当前值为 “4”。 `undefined`和`4`被打印出。 +在第四次调用时,回调函数依然没有返回值。累加器再次为 `undefined`,当前值为“4”。`undefined`和`4`被打印出。

@@ -2067,11 +2067,11 @@ class Labrador extends Dog {
答案

-#### 答案: B +#### 答案:B -在子类中,在调用`super`之前不能访问到`this`关键字。 如果这样做,它将抛出一个`ReferenceError`:1 和 4 将引发一个引用错误。 +在子类中,在调用`super`之前不能访问到`this`关键字。如果这样做,它将抛出一个`ReferenceError`:1 和 4 将引发一个引用错误。 -使用`super`关键字,需要用给定的参数来调用父类的构造函数。 父类的构造函数接收`name`参数,因此我们需要将`name`传递给`super`。 +使用`super`关键字,需要用给定的参数来调用父类的构造函数。父类的构造函数接收`name`参数,因此我们需要将`name`传递给`super`。 `Labrador`类接收两个参数,`name`参数是由于它继承了`Dog`,`size`作为`Labrador`类的额外属性,它们都需要传递给`Labrador`的构造函数,因此使用构造函数 2 正确完成。

@@ -2100,11 +2100,11 @@ export const sum = (a, b) => a + b;
答案

-#### 答案: B +#### 答案:B `import`命令是编译阶段执行的,在代码运行之前。因此这意味着被导入的模块会先运行,而导入模块的文件会后执行。 -这是 CommonJS 中`require()`和`import`之间的区别。使用`require()`,您可以在运行代码时根据需要加载依赖项。 如果我们使用`require`而不是`import`,`running index.js`,`running sum.js`,`3`会被依次打印。 +这是 CommonJS 中`require()`和`import`之间的区别。使用`require()`,您可以在运行代码时根据需要加载依赖项。如果我们使用`require`而不是`import`,`running index.js`,`running sum.js`,`3`会被依次打印。

@@ -2127,9 +2127,9 @@ console.log(Symbol('foo') === Symbol('foo'))
答案

-#### 答案: A +#### 答案:A -每个`Symbol`都是完全唯一的。传递给`Symbol`的参数只是给`Symbol`的一个描述。 `Symbol`的值不依赖于传递的参数。 当我们测试相等时,我们创建了两个全新的符号:第一个`Symbol('foo')`,第二个`Symbol('foo')`,这两个值是唯一的,彼此不相等,因此返回`false`。 +每个`Symbol`都是完全唯一的。传递给`Symbol`的参数只是给`Symbol`的一个描述。`Symbol`的值不依赖于传递的参数。当我们测试相等时,我们创建了两个全新的符号:第一个`Symbol('foo')`,第二个`Symbol('foo')`,这两个值是唯一的,彼此不相等,因此返回`false`。

@@ -2152,7 +2152,7 @@ console.log(name.padStart(2))
答案

-#### 答案: C +#### 答案:C 使用`padStart`方法,我们可以在字符串的开头添加填充。传递给此方法的参数是字符串的总长度(包含填充)。字符串`Lydia Hallie`的长度为`12`,因此`name.padStart(13)`在字符串的开头只会插入 1(`13 - 12 = 1`)个空格。 @@ -2177,9 +2177,9 @@ console.log("🥑" + "💻");

答案

-#### 答案: A +#### 答案:A -使用`+`运算符,您可以连接字符串。 上述情况,我们将字符串`“🥑”`与字符串`”💻“`连接起来,产生`”🥑💻“`。 +使用`+`运算符,您可以连接字符串。上述情况,我们将字符串`“🥑”`与字符串`”💻“`连接起来,产生`”🥑💻“`。

@@ -2210,9 +2210,9 @@ console.log(/* 2 */); // JavaScript loves you back ❤️
答案

-#### 答案: C +#### 答案:C -`generator`函数在遇到`yield`关键字时会 “暂停” 其执行。 首先,我们需要让函数产生字符串`Do you love JavaScript?`,这可以通过调用`game.next().value`来完成。上述函数的第一行就有一个`yield`关键字,那么运行立即停止了,`yield`表达式本身没有返回值,或者说总是返回`undefined`,这意味着此时变量 `答案` 为`undefined` +`generator`函数在遇到`yield`关键字时会“暂停”其执行。首先,我们需要让函数产生字符串`Do you love JavaScript?`,这可以通过调用`game.next().value`来完成。上述函数的第一行就有一个`yield`关键字,那么运行立即停止了,`yield`表达式本身没有返回值,或者说总是返回`undefined`,这意味着此时变量 `答案` 为`undefined` `next`方法可以带一个参数,该参数会被当作上一个 `yield` 表达式的返回值。当我们调用`game.next("Yes").value`时,先前的 `yield` 的返回值将被替换为传递给`next()`函数的参数`"Yes"`。此时变量 `答案` 被赋值为 `"Yes"`,`if`语句返回`false`,所以`JavaScript loves you back ❤️`被打印。 @@ -2235,7 +2235,7 @@ console.log(String.raw`Hello\nworld`);

答案

-#### 答案: C +#### 答案:C `String.raw`函数是用来获取一个模板字符串的原始字符串的,它返回一个字符串,其中忽略了转义符(`\n`,`\v`,`\t`等)。但反斜杠可能造成问题,因为你可能会遇到下面这种类似情况: @@ -2280,7 +2280,7 @@ console.log(data);

答案

-#### 答案: C +#### 答案:C 异步函数始终返回一个 promise。`await`仍然需要等待 promise 的解决:当我们调用`getData()`并将其赋值给`data`,此时`data`为`getData`方法返回的一个挂起的 promise,该 promise 并没有解决。 @@ -2314,9 +2314,9 @@ console.log(result);

答案

-#### 答案: B +#### 答案:B -`push()`方法返回新数组的长度。一开始,数组包含一个元素(字符串`"banana"`),长度为 1。 在数组中添加字符串`"apple"`后,长度变为 2,并将从`addToList`函数返回。 +`push()`方法返回新数组的长度。一开始,数组包含一个元素(字符串`"banana"`),长度为 1。在数组中添加字符串`"apple"`后,长度变为 2,并将从`addToList`函数返回。 `push`方法修改原始数组,如果你想从函数返回数组而不是数组长度,那么应该在 push `item`之后返回`list`。 @@ -2345,13 +2345,13 @@ console.log(shape)

答案

-#### 答案: B +#### 答案:B `Object.freeze`使得无法添加、删除或修改对象的属性(除非属性的值是另一个对象)。 当我们创建变量`shape`并将其设置为等于冻结对象`box`时,`shape`指向的也是冻结对象。你可以使用`Object.isFrozen`检查一个对象是否被冻结,上述情况,`Object.isFrozen(shape)`将返回`true`。 -由于`shape`被冻结,并且`x`的值不是对象,所以我们不能修改属性`x`。 `x`仍然等于`10`,`{x:10,y:20}`被打印。 +由于`shape`被冻结,并且`x`的值不是对象,所以我们不能修改属性`x`。`x`仍然等于`10`,`{x:10,y:20}`被打印。 注意,上述例子我们对属性`x`进行修改,可能会导致抛出 TypeError 异常(最常见但不仅限于严格模式下时)。 @@ -2376,7 +2376,7 @@ console.log(name);

答案

-#### 答案: D +#### 答案:D 当我们从右侧的对象解构属性`name`时,我们将其值`Lydia`分配给名为`myName`的变量。 @@ -2403,7 +2403,7 @@ function sum(a, b) {

答案

-#### 答案: A +#### 答案:A 纯函数在相同的输入值时,需产生相同的输出,其输出的结果,与输入值以外的其他隐藏信息或状态无关,也和由 I/O 设备产生的外部输出无关。 纯函数不会产生副作用。 @@ -2446,19 +2446,19 @@ console.log(addFunction(5 * 2));

答案

-#### 答案: C +#### 答案:C -`add`函数是一个记忆函数。 通过记忆化,我们可以缓存函数的结果,以加快其执行速度。上述情况,我们创建一个`cache`对象,用于存储先前返回过的值。 +`add`函数是一个记忆函数。通过记忆化,我们可以缓存函数的结果,以加快其执行速度。上述情况,我们创建一个`cache`对象,用于存储先前返回过的值。 如果我们使用相同的参数多次调用`addFunction`函数,它首先检查缓存中是否已有该值,如果有,则返回缓存值,这将节省执行时间。如果没有,那么它将计算该值,并存储在缓存中。 我们用相同的值三次调用了`addFunction`函数: -在第一次调用,`num`等于`10`时函数的值尚未缓存,if 语句`num in cache`返回`false`,else 块的代码被执行:`Calculated! 20`,并且其结果被添加到缓存对象,`cache`现在看起来像`{10:20}`。 +在第一次调用,`num`等于`10`时函数的值尚未缓存,if 语句`num in cache`返回`false`,else 块的代码被执行:`Calculated! 20`,并且其结果被添加到缓存对象,`cache`现在看起来像`{10:20}`。 -第二次,`cache`对象包含`10`的返回值。 if 语句 `num in cache` 返回`true`,`From cache! 20`被打印。 +第二次,`cache`对象包含`10`的返回值。if 语句 `num in cache` 返回`true`,`From cache! 20`被打印。 -第三次,我们将`5 * 2`(值为 10) 传递给函数。 `cache`对象包含`10`的返回值。 if 语句 `num in cache` 返回`true`,`From cache! 20`被打印。 +第三次,我们将`5 * 2`(值为 10) 传递给函数。`cache`对象包含`10`的返回值。if 语句 `num in cache` 返回`true`,`From cache! 20`被打印。

@@ -2487,9 +2487,9 @@ for (let item of myLifeSummedUp) {
答案

-#### 答案: A +#### 答案:A -通过`for-in`循环,我们可以遍历一个对象**自有的**、**继承的**、**可枚举的**、**非 Symbol 的**属性。 在数组中,可枚举属性是数组元素的 “键”, 即它们的索引。 类似于下面这个对象: +通过`for-in`循环,我们可以遍历一个对象**自有的**、**继承的**、**可枚举的**、**非 Symbol 的**属性。在数组中,可枚举属性是数组元素的“键”,即它们的索引。类似于下面这个对象: `{0: "☕", 1: "💻", 2: "🍷", 3: "🍫"}` @@ -2517,11 +2517,11 @@ console.log(list)

答案

-#### 答案: C +#### 答案:C -数组元素可以包含任何值。 数字,字符串,布尔值,对象,数组,`null`,`undefined`,以及其他表达式,如日期,函数和计算。 +数组元素可以包含任何值。数字,字符串,布尔值,对象,数组,`null`,`undefined`,以及其他表达式,如日期,函数和计算。 -元素将等于返回的值。 `1 + 2`返回`3`,`1 * 2`返回'2`,'1 / 2`返回`0.5`。 +元素将等于返回的值。`1 + 2`返回`3`,`1 * 2`返回'2`,'1 / 2`返回`0.5`。

@@ -2546,13 +2546,13 @@ console.log(sayHi())
答案

-#### 答案: B +#### 答案:B -默认情况下,如果不给函数传参,参数的值将为`undefined`。 上述情况,我们没有给参数`name`传值。 `name`等于`undefined`,并被打印。 +默认情况下,如果不给函数传参,参数的值将为`undefined`。上述情况,我们没有给参数`name`传值。`name`等于`undefined`,并被打印。 -在 ES6 中,我们可以使用默认参数覆盖此默认的`undefined`值。 例如: +在 ES6 中,我们可以使用默认参数覆盖此默认的`undefined`值。例如: -`function sayHi(name =“Lydia”){...}` +`function sayHi (name =“Lydia”){...}` 在这种情况下,如果我们没有传递值或者如果我们传递`undefined`,`name`总是等于字符串`Lydia` @@ -2589,11 +2589,11 @@ setTimeout(() => {

答案

-#### 答案: B +#### 答案:B -`this`关键字的指向取决于使用它的位置。 在**函数**中,比如`getStatus`,`this`指向的是调用它的对象,上述例子中`data`对象调用了`getStatus`,因此`this`指向的就是`data`对象。 当我们打印`this.status`时,`data`对象的`status`属性被打印,即`"🥑"`。 +`this`关键字的指向取决于使用它的位置。在**函数**中,比如`getStatus`,`this`指向的是调用它的对象,上述例子中`data`对象调用了`getStatus`,因此`this`指向的就是`data`对象。当我们打印`this.status`时,`data`对象的`status`属性被打印,即`"🥑"`。 -使用`call`方法,可以更改`this`指向的对象。`data.getStatus.call(this)`是将`this`的指向由`data`对象更改为全局对象。在全局对象上,有一个名为`status`的变量,其值为`”😎“`。 因此打印`this.status`时,会打印`“😎”`。 +使用`call`方法,可以更改`this`指向的对象。`data.getStatus.call(this)`是将`this`的指向由`data`对象更改为全局对象。在全局对象上,有一个名为`status`的变量,其值为`”😎“`。因此打印`this.status`时,会打印`“😎”`。

@@ -2621,13 +2621,13 @@ console.log(person)
答案

-#### 答案: A +#### 答案:A -我们将变量`city`设置为等于`person`对象上名为`city`的属性的值。 这个对象上没有名为`city`的属性,因此变量`city`的值为`undefined`。 +我们将变量`city`设置为等于`person`对象上名为`city`的属性的值。这个对象上没有名为`city`的属性,因此变量`city`的值为`undefined`。 请注意,我们没有引用`person`对象本身,只是将变量`city`设置为等于`person`对象上`city`属性的当前值。 -然后,我们将`city`设置为等于字符串`“Amsterdam”`。 这不会更改 person 对象:没有对该对象的引用。 +然后,我们将`city`设置为等于字符串`“Amsterdam”`。这不会更改 person 对象:没有对该对象的引用。 因此打印`person`对象时,会返回未修改的对象。 @@ -2660,9 +2660,9 @@ console.log(checkAge(21))

答案

-#### 答案: C +#### 答案:C -`const`和`let`声明的变量是具有**块级作用域**的,块是大括号(`{}`)之间的任何东西,即上述情况`if / else`语句的花括号。 由于块级作用域,我们无法在声明的块之外引用变量,因此抛出`ReferenceError`。 +`const`和`let`声明的变量是具有**块级作用域**的,块是大括号(`{}`)之间的任何东西,即上述情况`if / else`语句的花括号。由于块级作用域,我们无法在声明的块之外引用变量,因此抛出`ReferenceError`。

@@ -2685,9 +2685,9 @@ fetch('https://www.website.com/api/user/1')
答案

-#### 答案: C +#### 答案:C -第二个`.then`中`res`的值等于前一个`.then`中的回调函数返回的值。 你可以像这样继续链接`.then`,将值传递给下一个处理程序。 +第二个`.then`中`res`的值等于前一个`.then`中的回调函数返回的值。你可以像这样继续链接`.then`,将值传递给下一个处理程序。

@@ -2710,9 +2710,9 @@ function getName(name) {
答案

-#### 答案: A +#### 答案:A -使用逻辑非运算符`!`,将返回一个布尔值,使用`!! name`,我们可以确定`name`的值是真的还是假的。 如果`name`是真实的,那么`!name`返回`false`。 `!false`返回`true`。 +使用逻辑非运算符`!`,将返回一个布尔值,使用`!! name`,我们可以确定`name`的值是真的还是假的。如果`name`是真实的,那么`!name`返回`false`。`!false`返回`true`。 通过将`hasName`设置为`name`,可以将`hasName`设置为等于传递给`getName`函数的值,而不是布尔值`true`。 @@ -2737,11 +2737,11 @@ console.log("I want pizza"[0])

答案

-#### 答案: B +#### 答案:B -可以使用方括号表示法获取字符串中特定索引的字符,字符串中的第一个字符具有索引 0,依此类推。 在这种情况下,我们想要得到索引为 0 的元素,字符`'I'`被记录。 +可以使用方括号表示法获取字符串中特定索引的字符,字符串中的第一个字符具有索引 0,依此类推。在这种情况下,我们想要得到索引为 0 的元素,字符`'I'`被记录。 -请注意,IE7 及更低版本不支持此方法。 在这种情况下,应该使用`.charAt()` +请注意,IE7 及更低版本不支持此方法。在这种情况下,应该使用`.charAt()`

@@ -2766,9 +2766,9 @@ sum(10)
答案

-#### 答案: B +#### 答案:B -您可以将默认参数的值设置为函数的另一个参数,只要另一个参数定义在其之前即可。 我们将值`10`传递给`sum`函数。 如果`sum`函数只接收 1 个参数,则意味着没有传递`num2`的值,这种情况下,`num1`的值等于传递的值`10`。 `num2`的默认值是`num1`的值,即`10`。 ```num1 + num2```返回`20`。 +您可以将默认参数的值设置为函数的另一个参数,只要另一个参数定义在其之前即可。我们将值`10`传递给`sum`函数。如果`sum`函数只接收 1 个参数,则意味着没有传递`num2`的值,这种情况下,`num1`的值等于传递的值`10`。`num2`的默认值是`num1`的值,即`10`。```num1 + num2```返回`20`。 如果您尝试将默认参数的值设置为后面定义的参数,则可能导致参数的值尚未初始化,从而引发错误。比如: ```js @@ -2806,9 +2806,9 @@ console.log(data)

答案

-#### 答案: A +#### 答案:A -使用`import * as name`语法,我们将`module.js`文件中所有`export`导入到`index.js`文件中,并且创建了一个名为`data`的新对象。 在`module.js`文件中,有两个导出:默认导出和命名导出。 默认导出是一个返回字符串 “Hello World” 的函数,命名导出是一个名为`name`的变量,其值为字符串`“Lydia”`。 +使用`import * as name`语法,我们将`module.js`文件中所有`export`导入到`index.js`文件中,并且创建了一个名为`data`的新对象。在`module.js`文件中,有两个导出:默认导出和命名导出。默认导出是一个返回字符串“Hello World”的函数,命名导出是一个名为`name`的变量,其值为字符串`“Lydia”`。 `data`对象具有默认导出的`default`属性,其他属性具有指定 exports 的名称及其对应的值。 @@ -2838,7 +2838,7 @@ console.log(typeof member)

答案

-#### 答案: C +#### 答案:C 类是构造函数的语法糖,如果用构造函数的方式来重写`Person`类则将是: @@ -2871,11 +2871,11 @@ console.log(newList.push(5))

答案

-#### 答案: D +#### 答案:D -`.push`方法返回数组的长度,而不是数组本身! 通过将`newList`设置为`[1,2,3].push(4)`,实际上`newList`等于数组的新长度:`4`。 +`.push`方法返回数组的长度,而不是数组本身!通过将`newList`设置为`[1,2,3].push(4)`,实际上`newList`等于数组的新长度:`4`。 -然后,尝试在`newList`上使用`.push`方法。 由于`newList`是数值`4`,抛出 TypeError。 +然后,尝试在`newList`上使用`.push`方法。由于`newList`是数值`4`,抛出 TypeError。

@@ -2903,9 +2903,9 @@ console.log(giveLydiaChocolate.prototype)
答案

-#### 答案: D +#### 答案:D -常规函数,例如`giveLydiaPizza`函数,有一个`prototype`属性,它是一个带有`constructor`属性的对象(原型对象)。 然而,箭头函数,例如`giveLydiaChocolate`函数,没有这个`prototype`属性。 尝试使用`giveLydiaChocolate.prototype`访问`prototype`属性时会返回`undefined`。 +常规函数,例如`giveLydiaPizza`函数,有一个`prototype`属性,它是一个带有`constructor`属性的对象(原型对象)。然而,箭头函数,例如`giveLydiaChocolate`函数,没有这个`prototype`属性。尝试使用`giveLydiaChocolate.prototype`访问`prototype`属性时会返回`undefined`。

@@ -2933,12 +2933,12 @@ for (const [x, y] of Object.entries(person)) {
答案

-#### 答案: A +#### 答案:A `Object.entries()`方法返回一个给定对象自身可枚举属性的键值对数组,上述情况返回一个二维数组,数组每个元素是一个包含键和值的数组: -`[['name','Lydia'],['age',21]]` +`[['name','Lydia'],['age', 21]]` -使用`for-of`循环,我们可以迭代数组中的每个元素,上述情况是子数组。 我们可以使用`const [x,y]`在`for-of`循环中解构子数组。 `x`等于子数组中的第一个元素,`y`等于子数组中的第二个元素。 +使用`for-of`循环,我们可以迭代数组中的每个元素,上述情况是子数组。我们可以使用`const [x,y]`在`for-of`循环中解构子数组。`x`等于子数组中的第一个元素,`y`等于子数组中的第二个元素。 第一个子阵列是`[“name”,“Lydia”]`,其中`x`等于`name`,而`y`等于`Lydia`。 第二个子阵列是`[“age”,21]`,其中`x`等于`age`,而`y`等于`21`。 @@ -2966,7 +2966,7 @@ getItems(["banana", "apple"], "pear", "orange")

答案

-#### 答案: D +#### 答案:D `... args`是剩余参数,剩余参数的值是一个包含所有剩余参数的数组,**并且只能作为最后一个参数**。上述示例中,剩余参数是第二个参数,这是不可能的,并会抛出语法错误。 @@ -3009,7 +3009,7 @@ console.log(nums(1, 2))

答案

-#### 答案: B +#### 答案:B 在 JavaScript 中,我们不必显式地编写分号 (`;`),但是 JavaScript 引擎仍然在语句之后自动添加分号。这称为**自动分号插入**。例如,一个语句可以是变量,或者像`throw`、`return`、`break`这样的关键字。 @@ -3055,10 +3055,10 @@ console.log(member.name)

答案

-#### 答案: B +#### 答案:B -我们可以将类设置为等于其他类/函数构造函数。 在这种情况下,我们将`Person`设置为`AnotherPerson`。 这个构造函数的名字是`Sarah`,所以新的`Person`实例`member`上的 name 属性是`Sarah`。 +我们可以将类设置为等于其他类/函数构造函数。在这种情况下,我们将`Person`设置为`AnotherPerson`。这个构造函数的名字是`Sarah`,所以新的`Person`实例`member`上的 name 属性是`Sarah`。

@@ -3085,10 +3085,10 @@ console.log(Object.keys(info))
答案

-#### 答案: D +#### 答案:D -`Symbol`类型是不可枚举的。`Object.keys`方法返回对象上的所有可枚举的键属性。`Symbol`类型是不可见的,并返回一个空数组。 记录整个对象时,所有属性都是可见的,甚至是不可枚举的属性。 +`Symbol`类型是不可枚举的。`Object.keys`方法返回对象上的所有可枚举的键属性。`Symbol`类型是不可见的,并返回一个空数组。记录整个对象时,所有属性都是可见的,甚至是不可枚举的属性。 这是`Symbol`的众多特性之一:除了表示完全唯一的值(防止对象意外名称冲突,例如当使用 2 个想要向同一对象添加属性的库时),您还可以`隐藏`这种方式对象的属性(尽管不完全。你仍然可以使用`Object.getOwnPropertySymbols()`方法访问 `Symbol`。 @@ -3118,14 +3118,14 @@ console.log(getUser(user))

答案

-#### 答案: A +#### 答案:A -`getList`函数接收一个数组作为其参数。 在`getList`函数的括号之间,我们立即解构这个数组。 您可以将其视为: +`getList`函数接收一个数组作为其参数。在`getList`函数的括号之间,我们立即解构这个数组。您可以将其视为: `[x, ...y] = [1, 2, 3, 4]` -使用剩余的参数`... y`,我们将所有剩余参数放在一个数组中。 在这种情况下,其余的参数是`2`,`3`和`4`。 `y`的值是一个数组,包含所有其余参数。 在这种情况下,`x`的值等于`1`,所以当我们打印`[x,y]`时,会打印`[1,[2,3,4]]`。 +使用剩余的参数`... y`,我们将所有剩余参数放在一个数组中。在这种情况下,其余的参数是`2`,`3`和`4`。 `y`的值是一个数组,包含所有其余参数。在这种情况下,`x`的值等于`1`,所以当我们打印`[x,y]`时,会打印`[1,[2,3,4]]`。 `getUser`函数接收一个对象。对于箭头函数,如果只返回一个值,我们不必编写花括号。但是,如果您想从一个箭头函数返回一个对象,您必须将它写在圆括号之间,否则两个花括号之间的所有内容都将被解释为一个块语句!在这种情况下,花括号之间的代码不是有效的 JavaScript 代码,因此会抛出 SyntaxError。 @@ -3154,12 +3154,12 @@ console.log(name())

答案

-#### 答案: C +#### 答案:C 变量`name`保存字符串的值,该字符串不是函数,因此无法调用。 -当值不是预期类型时,会抛出`TypeErrors`。 JavaScript 期望`name`是一个函数,因为我们试图调用它。 但它是一个字符串,因此抛出`TypeError`:`name is not a function` +当值不是预期类型时,会抛出`TypeErrors`。JavaScript 期望`name`是一个函数,因为我们试图调用它。但它是一个字符串,因此抛出`TypeError`:`name is not a function` 当你编写了一些非有效的 JavaScript 时,会抛出语法错误,例如当你把`return`这个词写成`retrun`时。 当 JavaScript 无法找到您尝试访问的值的引用时,抛出`ReferenceErrors`。 @@ -3186,12 +3186,12 @@ You should${'' && `n't`} see a therapist after so much JavaScript lol`

答案

-#### 答案: B +#### 答案:B -`[]`是一个真值。 使用`&&`运算符,如果左侧值是真值,则返回右侧值。 在这种情况下,左侧值`[]`是一个真值,所以返回`Im`。 +`[]`是一个真值。使用`&&`运算符,如果左侧值是真值,则返回右侧值。在这种情况下,左侧值`[]`是一个真值,所以返回`Im`。 -`""`是一个假值。 如果左侧值是假的,则不返回任何内容。 `n't`不会被退回。 +`""`是一个假值。如果左侧值是假的,则不返回任何内容。`n't`不会被退回。

@@ -3216,15 +3216,15 @@ console.log(one, two, three)
答案

-#### 答案: C +#### 答案:C -使用`||`运算符,我们可以返回第一个真值。 如果所有值都是假值,则返回最后一个值。 +使用`||`运算符,我们可以返回第一个真值。如果所有值都是假值,则返回最后一个值。 -`(false || {} || null)`:空对象`{}`是一个真值。 这是第一个(也是唯一的)真值,它将被返回。`one`等于`{}`。 +`(false || {} || null)`:空对象`{}`是一个真值。这是第一个(也是唯一的)真值,它将被返回。`one`等于`{}`。 -`(null || false ||“”)`:所有值都是假值。 这意味着返回传递的值`""`。 `two`等于`""`。 +`(null || false ||“”)`:所有值都是假值。这意味着返回传递的值`""`。`two`等于`""`。 -`([] || 0 ||“”)`:空数组`[]`是一个真值。 这是第一个返回的真值。 `three`等于`[]`。 +`([] || 0 ||“”)`:空数组`[]`是一个真值。这是第一个返回的真值。`three`等于`[]`。

@@ -3258,12 +3258,12 @@ secondFunction()
答案

-#### 答案: D +#### 答案:D 有了 promise,我们通常会说:当我想要调用某个方法,但是由于它可能需要一段时间,因此暂时将它放在一边。只有当某个值被 resolved/rejected,并且执行栈为空时才使用这个值。 -我们可以在`async`函数中通过`.then`和`await`关键字获得该值。 尽管我们可以通过`.then`和`await`获得 promise 的价值,但是它们的工作方式有所不同。 +我们可以在`async`函数中通过`.then`和`await`关键字获得该值。尽管我们可以通过`.then`和`await`获得 promise 的价值,但是它们的工作方式有所不同。 在 `firstFunction`中,当运行到`myPromise`方法时我们将其放在一边,即 promise 进入微任务队列,其他后面的代码(`console.log('second')`)照常运行,因此`second`被打印出,`firstFunction`方法到此执行完毕,执行栈中宏任务队列被清空,此时开始执行微任务队列中的任务,`I have resolved`被打印出。 @@ -3297,15 +3297,15 @@ for (let item of set) {

答案

-#### 答案: C +#### 答案:C -“+” 运算符不仅用于添加数值,还可以使用它来连接字符串。 每当 JavaScript 引擎发现一个或多个值不是数字时,就会将数字强制为字符串。 +“+”运算符不仅用于添加数值,还可以使用它来连接字符串。每当 JavaScript 引擎发现一个或多个值不是数字时,就会将数字强制为字符串。 -第一个是数字 1。 1 + 2 返回数字 3。 +第一个是数字 1。1 + 2 返回数字 3。 -但是,第二个是字符串 “Lydia”。 “Lydia” 是一个字符串,2 是一个数字:2 被强制转换为字符串。 “Lydia” 和 “2” 被连接起来,产生字符串 “Lydia2”。 +但是,第二个是字符串“Lydia”。 “Lydia”是一个字符串,2 是一个数字:2 被强制转换为字符串。 “Lydia”和“2”被连接起来,产生字符串“Lydia2”。 -`{name:“ Lydia”}`是一个对象。 数字和对象都不是字符串,因此将二者都字符串化。 每当我们对常规对象进行字符串化时,它就会变成`[Object object]`。 与 “2” 串联的 “ [Object object]” 成为 “[Object object]2”。 +`{name:“Lydia”}`是一个对象。数字和对象都不是字符串,因此将二者都字符串化。每当我们对常规对象进行字符串化时,它就会变成`[Object object]`。与“2”串联的“ [Object object]”成为“[Object object]2”。

@@ -3326,9 +3326,9 @@ Promise.resolve(5)
答案

-#### 答案: C +#### 答案:C -我们可以将我们想要的任何类型的值传递`Promise.resolve`,无论是否`promise`。 该方法本身返回带有已解析值的`Promise` (``)。 如果您传递常规函数,它将是具有常规值的已解决`promise`。 如果你通过了 promise,它将是一个已经 resolved 的且带有传的值的 promise。 +我们可以将我们想要的任何类型的值传递`Promise.resolve`,无论是否`promise`。该方法本身返回带有已解析值的`Promise` (``)。如果您传递常规函数,它将是具有常规值的已解决`promise`。如果你通过了 promise,它将是一个已经 resolved 的且带有传的值的 promise。 上述情况,我们传了数字 5,因此返回一个 resolved 状态的 promise,resolve 值为`5` @@ -3360,15 +3360,15 @@ compareMembers(person)

答案

-#### 答案: B +#### 答案:B -对象通过引用传递。 当我们检查对象的严格相等性(===)时,我们正在比较它们的引用。 +对象通过引用传递。当我们检查对象的严格相等性(===)时,我们正在比较它们的引用。 -我们将 “person2” 的默认值设置为 “person” 对象,并将 “person” 对象作为 “person1” 的值传递。 +我们将“person2”的默认值设置为“person”对象,并将“person”对象作为“person1”的值传递。 这意味着两个值都引用内存中的同一位置,因此它们是相等的。 -运行 “ else” 语句中的代码块,并记录`They are the same!` 。 +运行“else”语句中的代码块,并记录`They are the same!`。

@@ -3400,14 +3400,14 @@ console.log(colorConfig.colors[1])
答案

-#### 答案: D +#### 答案:D -在 JavaScript 中,我们有两种访问对象属性的方法:括号表示法或点表示法。 在此示例中,我们使用点表示法(`colorConfig.colors`)代替括号表示法(`colorConfig [“ colors”]`)。 +在 JavaScript 中,我们有两种访问对象属性的方法:括号表示法或点表示法。在此示例中,我们使用点表示法(`colorConfig.colors`)代替括号表示法(`colorConfig [“colors”]`)。 -使用点表示法,JavaScript 会尝试使用该确切名称在对象上查找属性。 在此示例中,JavaScript 尝试在 colorConfig 对象上找到名为 colors 的属性。 没有名为 “colors” 的属性,因此返回 “undefined”。 -然后,我们尝试使用`[1]`访问第一个元素的值。 我们无法对未定义的值执行此操作,因此会抛出`Cannot read property '1' of undefined`。 +使用点表示法,JavaScript 会尝试使用该确切名称在对象上查找属性。在此示例中,JavaScript 尝试在 colorConfig 对象上找到名为 colors 的属性。没有名为“colors”的属性,因此返回“undefined”。 +然后,我们尝试使用`[1]`访问第一个元素的值。我们无法对未定义的值执行此操作,因此会抛出`Cannot read property '1' of undefined`。 -JavaScript 解释(或取消装箱)语句。 当我们使用方括号表示法时,它会看到第一个左方括号`[`并一直进行下去,直到找到右方括号`]`。 只有这样,它才会评估该语句。 如果我们使用了 colorConfig [colors [1]],它将返回 colorConfig 对象上 red 属性的值。 +JavaScript 解释(或取消装箱)语句。当我们使用方括号表示法时,它会看到第一个左方括号`[`并一直进行下去,直到找到右方括号`]`。只有这样,它才会评估该语句。如果我们使用了 colorConfig [colors [1]],它将返回 colorConfig 对象上 red 属性的值。

@@ -3427,9 +3427,9 @@ console.log('❤️' === '❤️')
答案

-#### 答案: A +#### 答案:A -在内部,表情符号是 unicode。 heat 表情符号的 unicode 是`“ U + 2764 U + FE0F”`。 对于相同的表情符号,它们总是相同的,因此我们将两个相等的字符串相互比较,这将返回 true。 +在内部,表情符号是 unicode。heat 表情符号的 unicode 是`“U + 2764 U + FE0F”`。对于相同的表情符号,它们总是相同的,因此我们将两个相等的字符串相互比较,这将返回 true。

@@ -3458,9 +3458,9 @@ emojis.splice(1, 2, '✨')
答案

-#### 答案: D +#### 答案:D -使用`splice`方法,我们通过删除,替换或添加元素来修改原始数组。 在这种情况下,我们从索引 1 中删除了 2 个元素(我们删除了`'🥑'`和`'😍'`),同时添加了✨emoji 表情。 +使用`splice`方法,我们通过删除,替换或添加元素来修改原始数组。在这种情况下,我们从索引 1 中删除了 2 个元素(我们删除了`'🥑'`和`'😍'`),同时添加了✨emoji 表情。 `map`,`filter`和`slice`返回一个新数组,`find`返回一个元素,而`reduce`返回一个减小的值。 @@ -3488,11 +3488,11 @@ console.log(food)

答案

-#### 答案: A +#### 答案:A -我们将`info`对象上的`favoriteFood`属性的值设置为披萨表情符号 “🍕” 的字符串。字符串是原始数据类型。在 JavaScript 中,原始数据类型通过值起作用 +我们将`info`对象上的`favoriteFood`属性的值设置为披萨表情符号“🍕”的字符串。字符串是原始数据类型。在 JavaScript 中,原始数据类型通过值起作用 -在这种情况下,我们将`info`对象上的`favoriteFood`属性的值设置为等于`food`数组中的第一个元素的值,字符串为披萨表情符号(`'🍕'` )。字符串是原始数据类型,并且通过值进行交互,我们更改`info`对象上`favoriteFood`属性的值。 food 数组没有改变,因为 favoriteFood 的值只是该数组中第一个元素的值的复制,并且与该元素上的元素没有相同的内存引用食物`[0]`。当我们记录食物时,它仍然是原始数组`['🍕','🍫','🥑','🍔']`。 +在这种情况下,我们将`info`对象上的`favoriteFood`属性的值设置为等于`food`数组中的第一个元素的值,字符串为披萨表情符号(`'🍕'`)。字符串是原始数据类型,并且通过值进行交互,我们更改`info`对象上`favoriteFood`属性的值。food 数组没有改变,因为 favoriteFood 的值只是该数组中第一个元素的值的复制,并且与该元素上的元素没有相同的内存引用食物`[0]`。当我们记录食物时,它仍然是原始数组`['🍕','🍫','🥑','🍔']`。

@@ -3513,7 +3513,7 @@ JSON.parse()
答案

-#### 答案: A +#### 答案:A 使用`JSON.parse()`方法,我们可以将 JSON 字符串解析为 JavaScript 值。 @@ -3557,13 +3557,13 @@ getName()

答案

-#### 答案: D +#### 答案:D -每个函数都有其自己的执行上下文。 `getName`函数首先在其自身的上下文(范围)内查找,以查看其是否包含我们尝试访问的变量`name`。 上述情况,`getName`函数包含其自己的`name`变量:我们用`let`关键字和`Sarah`的值声明变量`name`。 +每个函数都有其自己的执行上下文。`getName`函数首先在其自身的上下文(范围)内查找,以查看其是否包含我们尝试访问的变量`name`。上述情况,`getName`函数包含其自己的`name`变量:我们用`let`关键字和`Sarah`的值声明变量`name`。 -带有`let`关键字(和`const`)的变量被提升,但是与`var`不同,它不会被*** 初始化***。 在我们声明(初始化)它们之前,无法访问它们。 这称为 “暂时性死区”。 当我们尝试在声明变量之前访问变量时,JavaScript 会抛出`ReferenceError: Cannot access 'name' before initialization`。 +带有`let`关键字(和`const`)的变量被提升,但是与`var`不同,它不会被*** 初始化***。在我们声明(初始化)它们之前,无法访问它们。这称为“暂时性死区”。当我们尝试在声明变量之前访问变量时,JavaScript 会抛出`ReferenceError: Cannot access 'name' before initialization`。 -如果我们不在`getName`函数中声明`name`变量,则 javascript 引擎会查看原型链。会找到其外部作用域有一个名为`name`的变量,其值为`Lydia`。 在这种情况下,它将打印`Lydia`: +如果我们不在`getName`函数中声明`name`变量,则 javascript 引擎会查看原型链。会找到其外部作用域有一个名为`name`的变量,其值为`Lydia`。在这种情况下,它将打印`Lydia`: ```javascript let name = 'Lydia' @@ -3606,7 +3606,7 @@ console.log(two.next().value)

答案

-#### 答案: C +#### 答案:C 通过 `yield` 关键字,我们在 `Generator` 函数里执行`yield`表达式。通过 `yield*` 关键字,我们可以在一个`Generator` 函数里面执行(`yield`表达式)另一个 `Generator` 函数,或可遍历的对象 (如数组). @@ -3645,7 +3645,7 @@ console.log(`${(x => x)('I love')} to program`)

答案

-#### 答案: A +#### 答案:A 带有模板字面量的表达式首先被执行。相当于字符串会包含表达式,这个立即执行函数 `(x => x)('I love')` 返回的值。我们向箭头函数 `x => x` 传递 `'I love'` 作为参数。`x` 等价于返回的 `'I love'`。这就是结果 `I love to program`。 @@ -3674,7 +3674,7 @@ config = null

答案

-#### 答案: C +#### 答案:C 一般情况下当我们将对象赋值为 `null`,那些对象会被进行 _垃圾回收(garbage collected)_ 因为已经没有对这些对象的引用了。然而,`setInterval`的参数是一个箭头函数(所以上下文绑定到对象 `config` 了),回调函数仍然保留着对 `config`的引用。只要存在引用,对象就不会被垃圾回收。因为没有被垃圾回收,`setInterval` 的回调每 1000ms (1s) 会被调用一次。 @@ -3707,7 +3707,7 @@ myMap.get(() => 'greeting')

答案

-#### 答案: B +#### 答案:B 当通过 `set` 方法添加一个键值对,一个传递给 `set`方法的参数将会是键名,第二个参数将会是值。在这个 case 里,键名为 _函数_ `() => 'greeting'`,值为`'Hello world'`。 `myMap` 现在就是 `{ () => 'greeting' => 'Hello world!' }`。 @@ -3747,13 +3747,13 @@ console.log(person)

答案

-#### 答案: C +#### 答案:C 函数 `changeAge` 和函数 `changeAgeAndName` 有着不同的参数,定义一个 _新_ 生成的对象 `{ ...person }`。这个对象有着所有 `person` 对象 中 k/v 值的副本。 首项,我们调用 `changeAge` 函数并传递 `person` 对象作为它的参数。这个函数对 `age` 属性进行加一操作。`person` 现在是 `{ name: "Lydia", age: 22 }`。 -然后,我们调用函数 `changeAgeAndName` ,然而我们没有传递参数。取而代之,`x` 的值等价 _new_ 生成的对象:`{ ...person }`。因为它是一个新生成的对象,它并不会对对象 `person` 造成任何副作用。`person` 仍然等价于 `{ name: "Lydia", age: 22 }`。 +然后,我们调用函数 `changeAgeAndName`,然而我们没有传递参数。取而代之,`x` 的值等价 _new_ 生成的对象:`{ ...person }`。因为它是一个新生成的对象,它并不会对对象 `person` 造成任何副作用。`person` 仍然等价于 `{ name: "Lydia", age: 22 }`。

@@ -3776,9 +3776,9 @@ function sumValues(x, y, z) {
答案

-#### 答案: C +#### 答案:C -通过展开操作符 `...`,我们可以 _暂开_ 单个可迭代的元素。函数 `sumValues` function 接收三个参数: `x`, `y` 和 `z`。`...[1, 2, 3]` 的执行结果为 `1, 2, 3`,将会传递给函数 `sumValues`。 +通过展开操作符 `...`,我们可以 _暂开_ 单个可迭代的元素。函数 `sumValues` function 接收三个参数:`x`, `y` 和 `z`。`...[1, 2, 3]` 的执行结果为 `1, 2, 3`,将会传递给函数 `sumValues`。

@@ -3802,9 +3802,9 @@ console.log(list[(num += 1)]);
答案

-#### 答案: B +#### 答案:B -通过 `+=` 操作符,我们对值 `num` 进行加 `1` 操作。 `num` 有初始值 `1`,因此 `1 + 1` 的执行结果为 `2`。数组 `list` 的第二项为 🥰,`console.log(list[2])` 输出 🥰. +通过 `+=` 操作符,我们对值 `num` 进行加 `1` 操作。`num` 有初始值 `1`,因此 `1 + 1` 的执行结果为 `2`。数组 `list` 的第二项为 🥰,`console.log(list[2])` 输出 🥰.

@@ -3840,13 +3840,13 @@ console.log(member.getLastName?.());
答案

-#### 答案: B +#### 答案:B 通过 ES10 或 TS3.7+[可选链操作符 `?.`](https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Operators/%E5%8F%AF%E9%80%89%E9%93%BE),我们不再需要显式检测更深层的嵌套值是否有效。如果我们尝试获取 `undefined` 或 `null` 的值 (_nullish_),表达将会短路并返回 `undefined`. -`person.pet?.name`: `person` 有一个名为 `pet` 的属性: `person.pet` 不是 nullish。它有个名为 `name` 的属性,并返回字符串 `Mara`。 -`person.pet?.family?.name`: `person` 有一个名为 `pet` 的属性: `person.pet` 不是 nullish. `pet` _并没有_ 一个名为 `family` 的属性,`person.pet.family` 是 nullish。表达式返回 `undefined`。 -`person.getFullName?.()`: `person` 有一个名为 `getFullName` 的属性: `person.getFullName()` 不是 nullish 并可以被调用,返回字符串 `Lydia Hallie`。 +`person.pet?.name`:`person` 有一个名为 `pet` 的属性:`person.pet` 不是 nullish。它有个名为 `name` 的属性,并返回字符串 `Mara`。 +`person.pet?.family?.name`:`person` 有一个名为 `pet` 的属性:`person.pet` 不是 nullish. `pet` _并没有_ 一个名为 `family` 的属性,`person.pet.family` 是 nullish。表达式返回 `undefined`。 +`person.getFullName?.()`:`person` 有一个名为 `getFullName` 的属性:`person.getFullName()` 不是 nullish 并可以被调用,返回字符串 `Lydia Hallie`。 `member.getLastName?.()`: 变量`member` 不存在,因此会抛出错误`ReferenceError`。

@@ -3874,9 +3874,9 @@ if (groceries.indexOf("banana")) {
答案

-#### 答案: B +#### 答案:B -我们传递了一个状态 `groceries.indexOf("banana")` 给 if 条件语句。`groceries.indexOf("banana")` 返回 `0`, 一个 falsy 的值。因为 if 条件语句的状态为 falsy,`else` 块区内的代码执行,并且 `We don't have to buy bananas!` 被输出。 +我们传递了一个状态 `groceries.indexOf("banana")` 给 if 条件语句。`groceries.indexOf("banana")` 返回 `0`,一个 falsy 的值。因为 if 条件语句的状态为 falsy,`else` 块区内的代码执行,并且 `We don't have to buy bananas!` 被输出。

@@ -3904,9 +3904,9 @@ console.log(config.language);
答案

-#### 答案: D +#### 答案:D -方法 `language` 是一个 `setter`。Setters 并不保存一个实际值,它们的使命在于 _修改_ 属性。当调用方法 `setter`, 返回 `undefined`。 +方法 `language` 是一个 `setter`。Setters 并不保存一个实际值,它们的使命在于 _修改_ 属性。当调用方法 `setter`,返回 `undefined`。

@@ -3930,9 +3930,9 @@ console.log(!typeof name === "string");
答案

-#### 答案: C +#### 答案:C -`typeof name` 返回 `"string"`。字符串 `"string"` 是一个 truthy 的值,因此 `!typeof name` 返回一个布尔值 `false`。 `false === "object"` 和 `false === "string"` 都返回 `false`。 +`typeof name` 返回 `"string"`。字符串 `"string"` 是一个 truthy 的值,因此 `!typeof name` 返回一个布尔值 `false`。`false === "object"` 和 `false === "string"` 都返回 `false`。 (如果我们想检测一个值的类型,我们应该用 `!==` 而不是 `!typeof`) @@ -3960,7 +3960,7 @@ add(4)(5)(6);

答案

-#### 答案: A +#### 答案:A 函数 `add` 是一个返回 返回箭头函数的箭头函数 的箭头函数(still with me?)。第一个函数接收一个值为 `4` 的参数 `x`。我们调用第二个函数,它接收一个值为 `5` 的参数 `y`。然后我们调用第三个函数,它接收一个值为 `6` 的参数 `z`。当我们尝试在最后一个箭头函数中获取 `x`, `y` 和 `z` 的值,JS 引擎根据作用域链去找 `x` 和 `y` 的值。得到 `4` `5` `6`. @@ -3994,9 +3994,9 @@ async function* range(start, end) {

答案

-#### 答案: C +#### 答案:C -我们给 函数 range 传递: `Promise{1}`, `Promise{2}`, `Promise{3}`,Generator 函数 `range` 返回一个全是 async object promise 数组。我们将 async object 赋值给变量 `gen`,之后我们使用`for await ... of` 进行循环遍历。我们将返回的 Promise 实例赋值给 `item`: 第一个返回 `Promise{1}`, 第二个返回 `Promise{2}`,之后是 `Promise{3}`。因为我们正 _awaiting_ `item` 的值,resolved 状态的 promise,promise 数组的 resolved _值_ 以此为: `1`,`2`,`3`. +我们给 函数 range 传递:`Promise{1}`, `Promise{2}`, `Promise{3}`,Generator 函数 `range` 返回一个全是 async object promise 数组。我们将 async object 赋值给变量 `gen`,之后我们使用`for await ... of` 进行循环遍历。我们将返回的 Promise 实例赋值给 `item`:第一个返回 `Promise{1}`,第二个返回 `Promise{2}`,之后是 `Promise{3}`。因为我们正 _awaiting_ `item` 的值,resolved 状态的 promise,promise 数组的 resolved _值_ 以此为:`1`,`2`,`3`.

@@ -4021,9 +4021,9 @@ myFunc(1, 2, 3);
答案

-#### 答案: D +#### 答案:D -`myFunc` 期望接收一个包含 `x`, `y` 和 `z` 属性的对象作为它的参数。因为我们仅仅传递三个单独的数字值 (1, 2, 3) 而不是一个含有 `x`, `y` 和 `z` 属性的对象 ({x: 1, y: 2, z: 3}), `x`, `y` 和 `z` 有着各自的默认值 `undefined`. +`myFunc` 期望接收一个包含 `x`, `y` 和 `z` 属性的对象作为它的参数。因为我们仅仅传递三个单独的数字值 (1, 2, 3) 而不是一个含有 `x`, `y` 和 `z` 属性的对象 ({x: 1, y: 2, z: 3}),`x`, `y` 和 `z` 有着各自的默认值 `undefined`.

@@ -4058,7 +4058,7 @@ console.log(getFine(130, 300))
答案

-#### 答案: B +#### 答案:B 通过方法 `Intl.NumberFormat`,我们可以格式化任意区域的数字值。我们对数字值 `130` 进行 `mile-per-hour` 作为 `unit` 的 `en-US` 区域 格式化,结果为 `130 mph`。对数字值 `300` 进行 `USD` 作为 `currency` 的 `en-US` 区域格式化,结果为 `$300.00`. @@ -4084,7 +4084,7 @@ console.log(spookyItems);

答案

-#### 答案: B +#### 答案:B 通过解构对象们,我们可以从右手边的对象中拆出值,并且将拆出的值分配给左手边对象同名的属性。在这种情况下,我们将值 "💀" 分配给 `spookyItems[3]`。相当于我们正在篡改数组 `spookyItems`,我们给它添加了值 "💀"。当输出 `spookyItems` 时,结果为 `["👻", "🎃", "🕸", "💀"]`。 @@ -4114,11 +4114,11 @@ console.log(isNaN(age));

答案

-#### 答案: C +#### 答案:C 通过方法 `Number.isNaN`,你可以检测你传递的值是否为 _数字值_ 并且是否等价于 `NaN`。`name` 不是一个数字值,因此 `Number.isNaN(name)` 返回 `false`。`age` 是一个数字值,但它不等价于 `NaN`,因此 `Number.isNaN(age)` 返回 `false`. -通过方法 `isNaN`, 你可以检测你传递的值是否一个 number。`name` 不是一个 `number`,因此 `isNaN(name)` 返回 `true`. `age` 是一个 `number` 因此 `isNaN(age)` 返回 `false`. +通过方法 `isNaN`,你可以检测你传递的值是否一个 number。`name` 不是一个 `number`,因此 `isNaN(name)` 返回 `true`. `age` 是一个 `number` 因此 `isNaN(age)` 返回 `false`.

@@ -4146,9 +4146,9 @@ getInfo();
答案

-#### 答案: D +#### 答案:D -通过 `const` 关键字声明的变量在被初始化之前不可被引用:这被称之为 _暂时性死区_。在函数 `getInfo` 中,变量 `randomValue` 声明在`getInfo` 的作用域的此法环境中。在想要对 `typeof randomValue` 进行 log 之前,变量 `randomValue` 仍未被初始化: 错误`ReferenceError` 被抛出!JS 引擎并不会根据作用域链网上寻找该变量,因为我们已经在 `getInfo` 函数中声明了 `randomValue` 变量。 +通过 `const` 关键字声明的变量在被初始化之前不可被引用:这被称之为 _暂时性死区_。在函数 `getInfo` 中,变量 `randomValue` 声明在`getInfo` 的作用域的此法环境中。在想要对 `typeof randomValue` 进行 log 之前,变量 `randomValue` 仍未被初始化:错误`ReferenceError` 被抛出!JS 引擎并不会根据作用域链网上寻找该变量,因为我们已经在 `getInfo` 函数中声明了 `randomValue` 变量。

@@ -4179,9 +4179,9 @@ const myPromise = Promise.resolve("Woah some cool data");
答案

-#### 答案: C +#### 答案:C -在 `try` 块区,我们打印 `myPromise` 变量的 awaited 值: `"Woah some cool data"`。因为`try` 块区没有错误抛出,`catch` 块区的代码并不执行。`finally` 块区的代码 _总是_ 执行,`"Oh finally!"` 被输出。 +在 `try` 块区,我们打印 `myPromise` 变量的 awaited 值:`"Woah some cool data"`。因为`try` 块区没有错误抛出,`catch` 块区的代码并不执行。`finally` 块区的代码 _总是_ 执行,`"Oh finally!"` 被输出。

@@ -4204,9 +4204,9 @@ console.log(emojis.flat(1));
答案

-#### 答案: B +#### 答案:B -通过方法 `flat`, 我们可以创建一个新的,已被扁平化的数组。被扁平化的深度取决于我们传递的值。在这个 case 里,我们传递了值 `1` (并不必要,这是默认值),相当于只有第一层的数组才会被连接。即这个 case 里的 `['🥑']` and `['✨', '✨', ['🍕', '🍕']]`。连接这两个数组得到结果 `['🥑', '✨', '✨', ['🍕', '🍕']]`. +通过方法 `flat`,我们可以创建一个新的,已被扁平化的数组。被扁平化的深度取决于我们传递的值。在这个 case 里,我们传递了值 `1` (并不必要,这是默认值),相当于只有第一层的数组才会被连接。即这个 case 里的 `['🥑']` and `['✨', '✨', ['🍕', '🍕']]`。连接这两个数组得到结果 `['🥑', '✨', '✨', ['🍕', '🍕']]`.

@@ -4244,9 +4244,9 @@ console.log(counterOne.count);
答案

-#### 答案: D +#### 答案:D -`counterOne` 是类 `Counter` 的一个实例。类 Counter 包含一个`count` 属性在它的构造函数里, 和一个 `increment` 方法。首先,我们通过 `counterOne.increment()` 调用方法 `increment` 两次。现在,`counterOne.count` 为 `2`. +`counterOne` 是类 `Counter` 的一个实例。类 Counter 包含一个`count` 属性在它的构造函数里,和一个 `increment` 方法。首先,我们通过 `counterOne.increment()` 调用方法 `increment` 两次。现在,`counterOne.count` 为 `2`. @@ -4291,13 +4291,13 @@ funcTwo();

答案

-#### 答案: D +#### 答案:D 首先,我们调用 `funcOne`。在函数 `funcOne` 的第一行,我们调用`myPromise` promise _异步操作_。当 JS 引擎在忙于执行 promise,它继续执行函数 `funcOne`。下一行 _异步操作_ `setTimeout`,其回调函数被 Web API 调用。 (详情请参考我关于 event loop 的文章.) -promise 和 timeout 都是异步操作,函数继续执行当 JS 引擎忙于执行 promise 和 处理 `setTimeout` 的回调。相当于 `Last line!` 首先被输出, 因为它不是异步操作。执行完 `funcOne` 的最后一行,promise 状态转变为 resolved,`Promise!` 被打印。然而,因为我们调用了 `funcTwo()`,调用栈不为空,`setTimeout` 的回调仍不能入栈。 +promise 和 timeout 都是异步操作,函数继续执行当 JS 引擎忙于执行 promise 和 处理 `setTimeout` 的回调。相当于 `Last line!` 首先被输出,因为它不是异步操作。执行完 `funcOne` 的最后一行,promise 状态转变为 resolved,`Promise!` 被打印。然而,因为我们调用了 `funcTwo()`,调用栈不为空,`setTimeout` 的回调仍不能入栈。 -我们现在处于 `funcTwo`,先 _awaiting_ myPromise。通过 `await` 关键字, 我们暂停了函数的执行直到 promise 状态变为 resolved (或 rejected)。然后,我们输出 `res` 的 awaited 值(因为 promise 本身返回一个 promise)。 接着输出 `Promise!`。 +我们现在处于 `funcTwo`,先 _awaiting_ myPromise。通过 `await` 关键字,我们暂停了函数的执行直到 promise 状态变为 resolved (或 rejected)。然后,我们输出 `res` 的 awaited 值(因为 promise 本身返回一个 promise)。接着输出 `Promise!`。 下一行就是 _异步操作_ `setTimeout`,其回调函数被 Web API 调用。 @@ -4328,7 +4328,7 @@ import * as sum from "./sum";

答案

-#### 答案: C +#### 答案:C 使用符号 `*`,我们引入文件中的所有值,包括默认和具名。如果我们有以下文件: @@ -4388,7 +4388,7 @@ person.name;

答案

-#### 答案: C +#### 答案:C 使用 Proxy 对象,我们可以给一个对象添加自定义行为。在这个 case,我们传递一个包含以下属性的对象 `handler` : `set` and `get`。每当我们 _设置_ 属性值时 `set` 被调用,每当我们 _获取_ 时 `get` 被调用。 @@ -4419,7 +4419,7 @@ Object.seal(person);

答案

-#### 答案: A +#### 答案:A 使用 `Object.seal` 我们可以防止新属性 _被添加_,或者存在属性 _被移除_. @@ -4451,7 +4451,7 @@ Object.freeze(person);

答案

-#### 答案: C +#### 答案:C 使用方法 `Object.freeze` 对一个对象进行 _冻结_。不能对属性进行添加,修改,删除。 @@ -4483,7 +4483,7 @@ myFunc(3);

答案

-#### 答案: A +#### 答案:A 首先我们不传递任何参数调用 `myFunc()`。因为我们没有传递参数,`num` 和 `value` 获取它们各自的默认值:num 为 `2`,而 `value` 为函数 `add` 的返回值。对于函数 `add`,我们传递值为 2 的 `num` 作为参数。函数 `add` 返回 `4` 作为 `value` 的值。 @@ -4523,7 +4523,7 @@ console.log(counter.#number)

答案

-#### 答案: D +#### 答案:D 在 ES2020 中,通过 `#` 我们可以给 class 添加私有变量。在 class 的外部我们无法获取该值。当我们尝试输出 `counter.#number`,语法错误被抛出:我们无法在 class `Counter` 外部获取它! @@ -4565,7 +4565,7 @@ obj.next(); // { value: "Lisa", done: false }

答案

-#### 答案: B +#### 答案:B 为了遍历 `teams` 数组中对象的属性 `members` 中的每一项,我们需要将 `teams[i].members` 传递给 Generator 函数 `getMembers`。Generator 函数返回一个 generator 对象。为了遍历这个 generator 对象中的每一项,我们需要使用 `yield*`. @@ -4604,7 +4604,7 @@ console.log(person.hobbies);

答案

-#### 答案: C +#### 答案:C 函数 `addHobby` 接受两个参数,`hobby` 和有着对象 `person` 中数组 `hobbies` 默认值的 `hobbies`。 @@ -4648,7 +4648,7 @@ const pet = new Flamingo();

答案

-#### 答案: B +#### 答案:B 我们创建了类 `Flamingo` 的实例 `pet`。当我们实例化这个实例,`Flamingo` 中的 `constructor` 被调用。首相,输出 `"I'm pink. 🌸"`,之后我们调用`super()`。`super()` 调用父类的构造函数,`Bird`。`Bird` 的构造函数被调用,并输出 `"I'm a bird. 🦢"`。 @@ -4676,7 +4676,7 @@ const emojis = ["🎄", "🎅🏼", "🎁", "⭐"];

答案

-#### 答案: D +#### 答案:D `const` 关键字意味着我们不能 _重定义_ 变量中的值,它 _仅可读_。然而,值本身不可修改。数组 `emojis` 中的值可被修改,如 push 新的值,拼接,又或者将数组的长度设置为 0。 @@ -4704,7 +4704,7 @@ const person = {

答案

-#### 答案: C +#### 答案:C 对象默认并不是可迭代的。如果迭代规则被定义,则一个对象是可迭代的(An iterable is an iterable if the iterator protocol is present)。我们可以通过添加迭代器 symbol `[Symbol.iterator]` 来定义迭代规则,其返回一个 generator 对象,比如说构建一个 generator 函数 `*[Symbol.iterator]() {}`。如果我们想要返回数组 `["Lydia Hallie", 21]`: `yield* Object.values(this)`,这个 generator 函数一定要 yield 对象 `person` 的`Object.values`。 @@ -4732,9 +4732,9 @@ console.log(count)

答案

-#### 答案: C +#### 答案:C -在 `forEach` 循环内部的 `if` 会判断 `num` 的值是 truthy 或者是 falsy。因为 `nums` 数组的第一个数字是 `0`,一个 falsy 值, `if` 语句代码块不会被执行。`count` 仅仅在 `nums` 数组的其他 3 个数字 `1`,`2`,`3` 时加 1。因为 `count` 执行了 3 次加 `1` 运算,所以 `count` 的值为 `3`。 +在 `forEach` 循环内部的 `if` 会判断 `num` 的值是 truthy 或者是 falsy。因为 `nums` 数组的第一个数字是 `0`,一个 falsy 值,`if` 语句代码块不会被执行。`count` 仅仅在 `nums` 数组的其他 3 个数字 `1`,`2`,`3` 时加 1。因为 `count` 执行了 3 次加 `1` 运算,所以 `count` 的值为 `3`。

@@ -4761,15 +4761,15 @@ getFruit([['🍍'], ['🍊', '🍌']])
答案

-#### 答案: D +#### 答案:D -`?` 允许我们去选择性地访问对象内部更深层的嵌套属性。 我们尝试打印 `fruits` 数组索引值为 `1` 的子数组内部的索引值为 `1` 的元素。 如果在 `fruits` 数组索引值 为 `1` 的位置不存在元素,会直接返回 `undefined`。 如果 `fruits` 数组在索引值为 `1` 的位置存在元素,但是子数组在索引值为 `1` 的位置不存在元素,也会返回 `undefined`。 +`?` 允许我们去选择性地访问对象内部更深层的嵌套属性。我们尝试打印 `fruits` 数组索引值为 `1` 的子数组内部的索引值为 `1` 的元素。如果在 `fruits` 数组索引值 为 `1` 的位置不存在元素,会直接返回 `undefined`。如果 `fruits` 数组在索引值为 `1` 的位置存在元素,但是子数组在索引值为 `1` 的位置不存在元素,也会返回 `undefined`。 -首先,我们尝试打印 `[['🍊', '🍌'], ['🍍']]` 的子数组 `['🍍']` 的第 2 个元素。这个子数组只包含一个元素,也就意味着在索引值为 `1` 的位置不存在元素,所以返回的是 `undefined` 。 +首先,我们尝试打印 `[['🍊', '🍌'], ['🍍']]` 的子数组 `['🍍']` 的第 2 个元素。这个子数组只包含一个元素,也就意味着在索引值为 `1` 的位置不存在元素,所以返回的是 `undefined`。 -其次,我们在没有传入任何参数调用了 `getFruits` 函数,也就意味着形参 `fruits` 的默认值为`undefined`。因为我们选择性地链接了 `fruits` 在索引值为 `1` 的元素,因为在索引值为 `1` 的位置不存在元素,因此返回的是 `undefined` 。 +其次,我们在没有传入任何参数调用了 `getFruits` 函数,也就意味着形参 `fruits` 的默认值为`undefined`。因为我们选择性地链接了 `fruits` 在索引值为 `1` 的元素,因为在索引值为 `1` 的位置不存在元素,因此返回的是 `undefined`。 -最后,我们尝试打印 `['🍍'], ['🍊', '🍌']` 的子数组 `['🍊', '🍌']` 的第 2 个元素。子数组索引值为 `1`的位置为 `🍌` ,因此它被打印出了。 +最后,我们尝试打印 `['🍍'], ['🍊', '🍌']` 的子数组 `['🍊', '🍌']` 的第 2 个元素。子数组索引值为 `1`的位置为 `🍌`,因此它被打印出了。

@@ -4803,9 +4803,9 @@ console.log(calc.count)
答案

-#### 答案: A +#### 答案:A -我们设置 `calc` 变量为 `Calc` 类的一个新实例。 然后,我们初始化一个 `Calc` 的新实例,而且调用了这个实例的 `increase` 方法。因为 count 属性是在 `Calc` class 的 constructor 内部的,所以 count 属性不会在 `Calc` 的原型链上共享出去。这就意味着 calc 实例的 count 值不会被更新,count 仍然是 `0`。 +我们设置 `calc` 变量为 `Calc` 类的一个新实例。然后,我们初始化一个 `Calc` 的新实例,而且调用了这个实例的 `increase` 方法。因为 count 属性是在 `Calc` class 的 constructor 内部的,所以 count 属性不会在 `Calc` 的原型链上共享出去。这就意味着 calc 实例的 count 值不会被更新,count 仍然是 `0`。

@@ -4845,9 +4845,9 @@ console.log(updatedUser === user)
答案

-#### 答案: B +#### 答案:B - `updateUser` 函数更新 user 的 `email` 和 `password` 属性的值, 如果它们的值传入函数, 函数返回的就是 `user` 对象。 `updateUser` 函数的返回值是 `user` 对象,意味着 updatedUser 的值与 `user` 指向的是同一个 `user` 对象。`updatedUser === user` 为 `true`. + `updateUser` 函数更新 user 的 `email` 和 `password` 属性的值,如果它们的值传入函数,函数返回的就是 `user` 对象。`updateUser` 函数的返回值是 `user` 对象,意味着 updatedUser 的值与 `user` 指向的是同一个 `user` 对象。`updatedUser === user` 为 `true`.

@@ -4874,10 +4874,10 @@ console.log(fruit)
答案

-#### 答案: C +#### 答案:C -首先,我们在 fruit 数组上调用 `slice` 方法。 slice 方法不会修改原始数组,但是会返回从数组切片下来的值:香蕉 emoji。 -其次,我们在 fruit 数组上调用 `splice` 方法。 splice 方法会修改原始数组,也就意味着 fruit 数组此时为 `['🍊', '🍎']`。 +首先,我们在 fruit 数组上调用 `slice` 方法。slice 方法不会修改原始数组,但是会返回从数组切片下来的值:香蕉 emoji。 +其次,我们在 fruit 数组上调用 `splice` 方法。splice 方法会修改原始数组,也就意味着 fruit 数组此时为 `['🍊', '🍎']`。 最后,我们在 fruit 数组上调用 `unshift` 方法,通过添加一个值的方式改变了原始数组,添加的是'🍇',它成为了数组的第一个元素。现在 fruit 数组的组成为 `['🍇', '🍊', '🍎']`。

@@ -4906,15 +4906,15 @@ console.log(animals[dog])
答案

-#### 答案: B +#### 答案:B 对象的键会被转换为字符串。 -因为 `dog` 的值是一个对象, `animals[dog]` 实际上意味着我们创建了一个叫做 `"object Object"` 的属性来代表新的对象。 `animals["object Object"]` 现在等于 `{ emoji: "🐶", name: "Mara"}`。 +因为 `dog` 的值是一个对象,`animals[dog]` 实际上意味着我们创建了一个叫做 `"object Object"` 的属性来代表新的对象。`animals["object Object"]` 现在等于 `{ emoji: "🐶", name: "Mara"}`。 `cat` 也是一个对象,`animals[cat]` 实际上意味着我们在用新的 cat 的属性覆盖 `animals[``"``object Object``"``]` 的值。 -打印 `animals[dog]`,实际上是`animals["object Object"]`,这是因为转化`dog`对象为一个字符串结果 `"object Object"` ,所以返回 `{ emoji: "🐈", name: "Sara" }`。 +打印 `animals[dog]`,实际上是`animals["object Object"]`,这是因为转化`dog`对象为一个字符串结果 `"object Object"`,所以返回 `{ emoji: "🐈", name: "Sara" }`。

@@ -4943,9 +4943,9 @@ console.log(user.email)
答案

-#### 答案: A +#### 答案:A -`updateEmail` 函数是一个箭头函数,它没有和 `user` 对象绑定。这就意味着 `this` 关键字不会引用到 `user` 对象,但是会引用到全局对象。 `user` 对象内部的 `email` 的值不会更新。当打印 `user.email` 的时候, 原始值 `my@email.com` 被返回。 +`updateEmail` 函数是一个箭头函数,它没有和 `user` 对象绑定。这就意味着 `this` 关键字不会引用到 `user` 对象,但是会引用到全局对象。`user` 对象内部的 `email` 的值不会更新。当打印 `user.email` 的时候,原始值 `my@email.com` 被返回。

@@ -4979,9 +4979,9 @@ runPromises()
答案

-#### 答案: D +#### 答案:D - `Promise.all` 方法可以并行式运行 promise。如果其中一个 promise 失败了,`Promise.all` 方法会带上被 reject 的 promise 的值_rejects_。在这个例子中, `promise3` 带着 `"Third"` 值 reject。我们在调用 `runPromises` 时在 `runPromises` 函数内部的 `catch` 方法去捕获任意 error 从而捕获到被 reject 的值。因为 `promise3` 带着 `"Third"` 被 reject,所以只有 `"Third"` 打印。 + `Promise.all` 方法可以并行式运行 promise。如果其中一个 promise 失败了,`Promise.all` 方法会带上被 reject 的 promise 的值_rejects_。在这个例子中,`promise3` 带着 `"Third"` 值 reject。我们在调用 `runPromises` 时在 `runPromises` 函数内部的 `catch` 方法去捕获任意 error 从而捕获到被 reject 的值。因为 `promise3` 带着 `"Third"` 被 reject,所以只有 `"Third"` 打印。

@@ -5008,7 +5008,7 @@ Object[method](keys.map((_, i) => {
答案

-#### 答案: C +#### 答案:C `fromEntries` 方法可以将二维数组转换为对象。在每个子数组的第一个元素是 key,在每个子数组的第二个元素是 value。在这个例子中,我们映射了 `keys` 数组,它返回了一个数组,数组的第一个元素为 keys 数组当前索引的值,第二个元素为 values 数组当前索引的值。 @@ -5044,7 +5044,7 @@ console.log(member)

答案

-#### 答案: C +#### 答案:C `address` 的默认值是一个空对象 `{}`。当我们设置 `member` 变量为 `createMember` 函数返回的对象,我们没有为 address 参数传值,意味着 address 的值为默认的空对象 `{}`。一个空对象是一个 truthy 值,意味着 `address ? address : null` 条件会返回 `true`。address 的值为空对象 `{}`。 @@ -5074,11 +5074,11 @@ if (!typeof randomValue === "string") {

答案

-#### 答案: B +#### 答案:B - `if` 语句的条件判断 `!typeof randomValue` 的值是否等于 `"string"`。 `!` 操作符将这个值转化为一个布尔值。如果值是 truthy 的话,返回值会是 `false`,如果值是 falsy,返回值会是 `true`。在这里, `typeof randomValue` 的返回值是一个 truthy 值 `"number"`,意味着 `!typeof randomValue` 的值是一个布尔值 `false`。 + `if` 语句的条件判断 `!typeof randomValue` 的值是否等于 `"string"`。`!` 操作符将这个值转化为一个布尔值。如果值是 truthy 的话,返回值会是 `false`,如果值是 falsy,返回值会是 `true`。在这里,`typeof randomValue` 的返回值是一个 truthy 值 `"number"`,意味着 `!typeof randomValue` 的值是一个布尔值 `false`。 - `!typeof randomValue === "string"` 总是返回 false,因为我们实际上是在执行 `false === "string"`。因为条件返回的是 `false`,所以 `else` 语句中的代码块会被运行,因此打印 `Yay it's a string!` 。 + `!typeof randomValue === "string"` 总是返回 false,因为我们实际上是在执行 `false === "string"`。因为条件返回的是 `false`,所以 `else` 语句中的代码块会被运行,因此打印 `Yay it's a string!`。

From 936401200cacae524f65b53f7df26d2437b19375 Mon Sep 17 00:00:00 2001 From: ihavecoke Date: Mon, 11 Sep 2023 01:00:14 +0800 Subject: [PATCH 181/193] Optimize zh-TW lang format --- zh-TW/README_zh-TW.md | 696 +++++++++++++++++++++--------------------- 1 file changed, 348 insertions(+), 348 deletions(-) diff --git a/zh-TW/README_zh-TW.md b/zh-TW/README_zh-TW.md index 08c171df..c171b62f 100644 --- a/zh-TW/README_zh-TW.md +++ b/zh-TW/README_zh-TW.md @@ -17,7 +17,7 @@ --- -歡迎在項目中使用它們 😃 我 _真的_ 很感激這個repo的參考,我創造了問題和解釋(是的,我很傷心lol),社區幫助我如此之多地維護和改進它!我很喜歡這個repo。 💪🏼 謝謝你,祝你玩得開心! +歡迎在項目中使用它們 😃 我 _真的_ 很感激這個 repo 的參考,我創造了問題和解釋(是的,我很傷心 lol),社區幫助我如此之多地維護和改進它!我很喜歡這個 repo。 💪🏼 謝謝你,祝你玩得開心! --- @@ -278,7 +278,7 @@ freddie.colorChange('orange') #### 答案:D -`colorChange` 是一個靜態方法。靜態方法被設計爲只能被創造它們的建構子使用(也就是 `Chameleon` 中的 `constructor` ),並且不能傳遞給實例。因為 `freddie` 是一個實例,而靜態方法不能被實例使用,因此會抛出 `TypeError` 錯誤。 +`colorChange` 是一個靜態方法。靜態方法被設計爲只能被創造它們的建構子使用(也就是 `Chameleon` 中的 `constructor`),並且不能傳遞給實例。因為 `freddie` 是一個實例,而靜態方法不能被實例使用,因此會抛出 `TypeError` 錯誤。

@@ -289,7 +289,7 @@ freddie.colorChange('orange') ```javascript let greeting -greetign = {} // 手殘打錯變數名稱! +greetign = {} // 手殘打錯變數名稱! console.log(greetign) ``` @@ -302,7 +302,7 @@ console.log(greetign) #### 答案:A -程式碼印出了一個物件,這是因為我們在全域物件上建立了一個空物件!當我們將 `greeting` 寫錯成 `greetign` 時,JS 解譯器實際上將它視爲 `global.greetign = {}` (或者在瀏覽器中視為 `window.greetign = {}`)。 +程式碼印出了一個物件,這是因為我們在全域物件上建立了一個空物件!當我們將 `greeting` 寫錯成 `greetign` 時,JS 解譯器實際上將它視爲 `global.greetign = {}`(或者在瀏覽器中視為 `window.greetign = {}`)。 為了避免這個狀況,我們可以使用 `"use strict"`,來確保當你宣告變數時,必須賦值。 @@ -374,7 +374,7 @@ Person.prototype.getFullName = function () { } ``` -這樣一來, `member.getFullName()` 就能有效。這樣做有什麼好處?假設我們真的能如題將這個方法新增到建構函式本身,並不是每個 `Person` 實例都需要這個方法,但每個實例卻仍然擁有該属性,代表著這將佔據每個實例的記憶體,造成大量的記憶體空間因此浪費掉了。相反,如果我們只將它新增在原型中,那麼它只存在記憶體中的一個位置,而所有實例都可以使用它! +這樣一來,`member.getFullName()` 就能有效。這樣做有什麼好處?假設我們真的能如題將這個方法新增到建構函式本身,並不是每個 `Person` 實例都需要這個方法,但每個實例卻仍然擁有該属性,代表著這將佔據每個實例的記憶體,造成大量的記憶體空間因此浪費掉了。相反,如果我們只將它新增在原型中,那麼它只存在記憶體中的一個位置,而所有實例都可以使用它!

@@ -499,12 +499,12 @@ console.log(number); #### 答案:C -一元運算子 `++` 加在變數後方: +一元運算子 `++` 加在變數後方: 1. 回傳值 (這個值是 `0`) 2. 新增值 (變數 `number` 的值現在是 `1`) -一元運算子 `++` 加在變數前方: +一元運算子 `++` 加在變數前方: 1. 新增值 (變數 `number` 的值現在是 `2`) 2. 回傳值 (這個值是 `2`) @@ -576,7 +576,7 @@ checkAge({ age: 18 }); 題目中,我們比較的兩個物件擁有不同的記憶體位置:一個物件是作為參數傳遞的物件,它的記憶體位置與另一個拿來判斷是否相等的物件並不相同。 -這就是 `{ age: 18 } === { age: 18 }` 與 `{ age: 18 } == { age: 18 }` 會回傳 `false` 的原因. +這就是 `{ age: 18 } === { age: 18 }` 與 `{ age: 18 } == { age: 18 }` 會回傳 `false` 的原因。

@@ -603,7 +603,7 @@ getAge(21); #### 答案:C -其餘參數(`...args`) 會蒐集傳進來剩下來未使用的參數,成為一個「陣列」。 陣列的型別是「物件」,所以透過 `typeof args` 將會回傳該值的型別,將是 `"object"`。 +其餘參數(`...args`)會蒐集傳進來剩下來未使用的參數,成為一個「陣列」。陣列的型別是「物件」,所以透過 `typeof args` 將會回傳該值的型別,將是 `"object"`。

@@ -775,7 +775,7 @@ console.log(obj);
答案

-#### 答案: A +#### 答案:A 基本执行上下文是全局执行上下文:它是代码中随处可访问的内容。 基底的執行環境是全域的:代表它在程式碼中,可被隨處使用。 @@ -802,7 +802,7 @@ for (let i = 1; i < 5; i++) {

答案

-#### 答案: C +#### 答案:C 當 `if` 條件成立時會回傳 `true`,執行 `continue` 語句,代表忽略本次迭代(`console.log(i)`)。 @@ -831,7 +831,7 @@ console.log(name.giveLydiaPizza())

答案

-#### 答案: A +#### 答案:A `String` 是內建的建構函式,我們可以向它新增属性。我只是在它的原型中加上一個方法。基本型別字串被自動轉換成字串物件,由字串原型函式生成。因此,所有 string(string 物件)都可以使用 `giveLydiaPizza` 方法! @@ -861,7 +861,7 @@ console.log(a[b]);

答案

-#### 答案: B +#### 答案:B 物件的 key 自動轉為字串型別。我們正嘗試將物件 `b` 的 key 設為物件 `a` 的 key,其值爲 `123`。 @@ -894,7 +894,7 @@ baz();

答案

-#### 答案: B +#### 答案:B 我們有一個 `setTimeout` 函式,首先呼叫它。然而,它的執行順序是最後執行的。 @@ -942,21 +942,21 @@ WebAPI 不能隨時向堆疊内新增内容。相反,它會將回呼函式彈 - A: 第一層的 `div` - B: 第二層的 `div` - C: `button` 本身 -- D: 一個包含此巢狀元件的陣列. +- D: 一個包含此巢狀元件的陣列。

答案

-#### 答案: C +#### 答案:C -產生事件(event)的元件即為此事件的 target,您可以透過 `event.stopPropagation` 來停止事件的冒泡(bubbling) +產生事件 (event) 的元件即為此事件的 target,您可以透過 `event.stopPropagation` 來停止事件的冒泡 (bubbling)

--- -###### 32. 點擊標籤 p(paragraph)時, 將會輸出什麼內容? +###### 32. 點擊標籤 p(paragraph) 時,將會輸出什麼內容? ```html
@@ -974,10 +974,10 @@ WebAPI 不能隨時向堆疊内新增内容。相反,它會將回呼函式彈
答案

-#### 答案: A +#### 答案:A -輸出內容是 `p` 及 `div`。在事件傳播(event propagation) 期間,分為三個階段:捕獲(capturing),目標(target) 和冒泡(bubbling)。 -預設情況下,事件處理(event handlers) 在冒泡階段執行(除非您將useCapture設置為true)。 它從巢狀元素的最深層向外層。 +輸出內容是 `p` 及 `div`。在事件傳播 (event propagation) 期間,分為三個階段:捕獲 (capturing),目標 (target) 和冒泡 (bubbling)。 +預設情況下,事件處理 (event handlers) 在冒泡階段執行(除非您將 useCapture 設置為 true)。它從巢狀元素的最深層向外層。

@@ -1005,10 +1005,10 @@ console.log(sayHi.bind(person, 21));
答案

-#### 答案: D +#### 答案:D 通過 `.call` 及 `.bind`,我們可以將想要 `this` 關鍵字引用的物件傳遞給它。 -然而,`.call` 會 _立即執行_! `.bind.` 則是會回傳一份函式(function)的 _複製_ 且不會立即執行。 +然而,`.call` 會 _立即執行_! `.bind.` 則是會回傳一份函式 (function) 的 _複製_ 且不會立即執行。

@@ -1033,10 +1033,10 @@ console.log(typeof sayHi());
答案

-#### 答案: B +#### 答案:B -`sayHi` 函數會回傳立即執行函式表示式(IIFE)的回傳值。 該函數回傳類型為 `"number"` 的 `0`。 -FYI: JS只有7種原生類型(type) : `null`, `undefined`, `boolean`, `number`, `string`, `object`, `symbol`, 和 `bigint`. `"function"` 不是一種類型而是物件。 +`sayHi` 函數會回傳立即執行函式表示式 (IIFE)的回傳值。該函數回傳類型為 `"number"` 的 `0`。 +FYI: JS 只有 7 種原生類型 (type) : `null`, `undefined`, `boolean`, `number`, `string`, `object`, `symbol`, 和 `bigint`. `"function"` 不是一種類型而是物件。

@@ -1062,7 +1062,7 @@ undefined;
答案

-#### 答案: A +#### 答案:A 只有八個值是 falsy @@ -1075,7 +1075,7 @@ undefined; - `-0` - `0n` (BigInt(0)) -函式建構式(Function constructors) 如 `new Number` 和 `new Boolean` 都為 truthy。 +函式建構式 (Function constructors) 如 `new Number` 和 `new Boolean` 都為 truthy。

@@ -1096,7 +1096,7 @@ console.log(typeof typeof 1);
答案

-#### 答案: B +#### 答案:B `typeof 1` 回傳 `"number"` `typeof "number"` 回傳 `"string"` @@ -1122,11 +1122,11 @@ console.log(numbers);

答案

-#### 答案: C +#### 答案:C -當您設置的元素其位置大過陣列長度時,JavaScript 會建立一個叫做 "empty slots" 的物件, 它們的值實際上為 `undefined`。 +當您設置的元素其位置大過陣列長度時,JavaScript 會建立一個叫做 "empty slots" 的物件,它們的值實際上為 `undefined`。 -但您會看到類似的輸出內容 : `[1, 2, 3, 7 x empty, 11]`。實際執行環境會使其輸出內容略微不同 (瀏覽器, node... 等) +但您會看到類似的輸出內容 : `[1, 2, 3, 7 x empty, 11]`。實際執行環境會使其輸出內容略微不同 (瀏覽器,node... 等)

@@ -1158,13 +1158,13 @@ console.log(numbers);
答案

-#### 答案: A +#### 答案:A -程式中的 `catch` 區塊捕獲了一個例外情況且賦殖予 argument `x`。這個 `x` 是在區塊內產生的,其有效範圍只在區塊內(block-scoped),它跟 `console.log` 中所傳入的 `x` 並不是同一個。 +程式中的 `catch` 區塊捕獲了一個例外情況且賦殖予 argument `x`。這個 `x` 是在區塊內產生的,其有效範圍只在區塊內 (block-scoped),它跟 `console.log` 中所傳入的 `x` 並不是同一個。 -接著我們將此區塊變數 `x` 設置為等於 `1`,並設置變數 `y` 的值, 現在我們 console.log 區塊變數 `x`,無意外地它輸出 `1`。 +接著我們將此區塊變數 `x` 設置為等於 `1`,並設置變數 `y` 的值,現在我們 console.log 區塊變數 `x`,無意外地它輸出 `1`。 -而在 `catch` 區塊之外的 `x` 仍然是 `undefined` 且 `y` 是 `2`。 因此當我們想在 `catch` 區塊之外使用 `console.log(x)` 時,它回傳 `undefined`,而 `y` 回傳 `2`。 +而在 `catch` 區塊之外的 `x` 仍然是 `undefined` 且 `y` 是 `2`。因此當我們想在 `catch` 區塊之外使用 `console.log(x)` 時,它回傳 `undefined`,而 `y` 回傳 `2`。

@@ -1181,16 +1181,16 @@ console.log(numbers);
答案

-#### 答案: A +#### 答案:A JavaScript 只有 primitive types 和 objects. 而 Primitive types 包含 `boolean`, `null`, `undefined`, `bigint`, `number`, `string`, 和 `symbol`. -Primitive 不同於 object 的是它沒有任何的屬性(properties) 和方法(methods); 沒有方法的情況下為何 `'foo'.toUpperCase()` (string) 是輸出 `'FOO'` 而不是 `TypeError` ? -這是因為當您嘗試訪問 primitive types (例如字串) 的屬性或方法時,JavaScript會使用其中一個 wrapper classes 包裝該 primitive type。 +Primitive 不同於 object 的是它沒有任何的屬性 (properties) 和方法 (methods); 沒有方法的情況下為何 `'foo'.toUpperCase()` (string) 是輸出 `'FOO'` 而不是 `TypeError` ? +這是因為當您嘗試訪問 primitive types (例如字串) 的屬性或方法時,JavaScript 會使用其中一個 wrapper classes 包裝該 primitive type。 -例如使用了 `String` 包裝 primitive type `string`, 接著在 expression 被 evaluates 後拋棄該包裝。 所有 primitives 除了 `null` 和 `undefined` 外都是遵循此行為。 +例如使用了 `String` 包裝 primitive type `string`,接著在 expression 被 evaluates 後拋棄該包裝。所有 primitives 除了 `null` 和 `undefined` 外都是遵循此行為。

@@ -1216,9 +1216,9 @@ Primitive 不同於 object 的是它沒有任何的屬性(properties) 和方法(
答案

-#### 答案: C +#### 答案:C -`[1, 2]` 為初始值,同時也是第一個 `acc`。 在第一輪中, `acc` 是 `[1,2]` 且 `cur` 是 `[0, 1]`,兩陣列連接後的結果是 `[1, 2, 0, 1]`。 +`[1, 2]` 為初始值,同時也是第一個 `acc`。在第一輪中,`acc` 是 `[1,2]` 且 `cur` 是 `[0, 1]`,兩陣列連接後的結果是 `[1, 2, 0, 1]`。 接著 `[1, 2, 0, 1]` 是 `acc` 且 `[2, 3]` 是 `cur`,兩陣列連接後的結果是 `[1, 2, 0, 1, 2, 3]`。 @@ -1243,7 +1243,7 @@ Primitive 不同於 object 的是它沒有任何的屬性(properties) 和方法(

答案

-#### 答案: B +#### 答案:B `null` 是 falsy. `!null` 回傳 `true`. `!true` 回傳 `false`. @@ -1270,7 +1270,7 @@ setInterval(() => console.log('Hi'), 1000);

答案

-#### 答案: A +#### 答案:A 會回傳一個唯一的 id,並可用於 `clearInterval()` 以清除該 interval。 @@ -1293,9 +1293,9 @@ setInterval(() => console.log('Hi'), 1000);

答案

-#### 答案: A +#### 答案:A -字串(string) 類別是可以被迭代的(iterable), 展開運算子(spread operator) 將可迭代的字元(character) 映射(map) 置一個元素(element) 上。 +字串 (string) 類別是可以被迭代的 (iterable),展開運算子 (spread operator) 將可迭代的字元 (character) 映射 (map) 置一個元素 (element) 上。

@@ -1324,16 +1324,16 @@ console.log(gen.next().value);
答案

-#### 答案: C +#### 答案:C -一般函式不能在被呼叫後中途停止。但是, generator 可以在中途 "停止" 且之後可以從停止的位置繼續執行。 -每當一個 generator 函式遇到一個 `yield` 關鍵字時,該函式就會產生其後指定的值。 請注意,在這種情況下,generator 函式不是 _return_ 值,而是 _yields_ 值。 +一般函式不能在被呼叫後中途停止。但是,generator 可以在中途 "停止" 且之後可以從停止的位置繼續執行。 +每當一個 generator 函式遇到一個 `yield` 關鍵字時,該函式就會產生其後指定的值。請注意,在這種情況下,generator 函式不是 _return_ 值,而是 _yields_ 值。 -首先,我們使用等於 "10" 的 "i" 初始化 generator 函式。 我們使用 "next()" 方法呼叫 generator 函式。 第一次呼叫 generator 函式時, "i" 等於 "10"。 -它遇到第一個 `yield` 關鍵字:它產生 `i` 的值。 現在,generator 已 "暫停", 並且記錄了 "10"。 +首先,我們使用等於 "10" 的 "i" 初始化 generator 函式。我們使用 "next()" 方法呼叫 generator 函式。第一次呼叫 generator 函式時, "i" 等於 "10"。 +它遇到第一個 `yield` 關鍵字:它產生 `i` 的值。現在,generator 已 "暫停",並且記錄了 "10"。 -然後,我們使用 `next()` 方法再次呼叫該函式。 它將從先前停止的地方繼續,仍然是 "i" 等於 "10"。 現在,它遇到下一個 `yield` 關鍵字,並產生 `i * 2` 。 -"i" 等於 "10",因此回傳 "10 * 2",即 "20"。 故結果為10、20。 +然後,我們使用 `next()` 方法再次呼叫該函式。它將從先前停止的地方繼續,仍然是 "i" 等於 "10"。現在,它遇到下一個 `yield` 關鍵字,並產生 `i * 2`。 +"i" 等於 "10",因此回傳 "10 * 2",即 "20"。故結果為 10、20。

@@ -1362,10 +1362,10 @@ Promise.race([firstPromise, secondPromise]).then(res => console.log(res));
答案

-#### 答案: B +#### 答案:B 當我們向 Promise.race 方法傳遞多個 promise 時,它將 resolves / rejects _最先的_ promise。 -在 setTimeout 方法中,我們傳遞了一個計時器:第一個 promise(firstPromise)為500毫秒,第二個 promise(secondPromise)為100毫秒。 這意味著 "secondPromise" 將先用 "two" 的值進行resolves。 現在, `res` 擁有 'two' 的值且該值被 console.log。 +在 setTimeout 方法中,我們傳遞了一個計時器:第一個 promise(firstPromise)為 500 毫秒,第二個 promise(secondPromise)為 100 毫秒。這意味著 "secondPromise" 將先用 "two" 的值進行 resolves。現在,`res` 擁有 'two' 的值且該值被 console.log。

@@ -1390,7 +1390,7 @@ console.log(members);
答案

-#### 答案: D +#### 答案:D 首先,我們宣告一個物件變數 `person` 包含 `name` 屬性以及值 `Lydia`。 @@ -1434,10 +1434,10 @@ for (const item in person) {

答案

-#### 答案: B +#### 答案:B -通過 `for-in` 循環,我們可以遍歷物件的鍵,在這個題目中的鍵是 `name` 和 `age`。 在內部,物件鍵是字串(strings)(如果它們不是 Symbol)。 -在每次循環中,我們將 `item` 的值設置為等於其迭代的當前鍵。 第一輪循環中,`item` 等於 `name`,並輸出內容。 接著, `item` 等於 `age`,並輸出內容。 +通過 `for-in` 循環,我們可以遍歷物件的鍵,在這個題目中的鍵是 `name` 和 `age`。在內部,物件鍵是字串 (strings)(如果它們不是 Symbol)。 +在每次循環中,我們將 `item` 的值設置為等於其迭代的當前鍵。第一輪循環中,`item` 等於 `name`,並輸出內容。接著,`item` 等於 `age`,並輸出內容。

@@ -1458,21 +1458,21 @@ console.log(3 + 4 + '5');
答案

-#### 答案: B +#### 答案:B 運算子關聯性是編譯器計算表達式的順序,從左到右或從右到左。僅適用於所有運算子具有 _相同_ 優先級時,才會發生這種情況。 -在這裡我們只有一種類型的運算子:+。 而其關聯性是從左到右。 +在這裡我們只有一種類型的運算子:+。而其關聯性是從左到右。 -首先計算 `3 + 4`。 結果為數字7。 +首先計算 `3 + 4`。結果為數字 7。 -由於強制(coercion) ,`7 +'5'` 會導致結果為 `75`。JavaScript將數字 `7` 轉換型態成字串,請參閱問題15。我們可以使用 `+` 運算子將兩個字串連接起來。 `7` + `5` 產生 `75`。 +由於強制 (coercion) ,`7 +'5'` 會導致結果為 `75`。JavaScript 將數字 `7` 轉換型態成字串,請參閱問題 15。我們可以使用 `+` 運算子將兩個字串連接起來。`7` + `5` 產生 `75`。

--- -###### 49. `num` 的值會是什麼? +###### 49. `num` 的值會是什麼? ```javascript const num = parseInt('7*6', 10); @@ -1486,9 +1486,9 @@ const num = parseInt('7*6', 10);
答案

-#### 答案: C +#### 答案:C -僅會回傳字串中的第一個數字。 基於 _radix_ (第二個參數,用於指定我們要將其解析為哪種類型的數字:以10為基數,十六進制,八進制,二進制等),`parseInt` 檢查字串中的字元是否有效。 +僅會回傳字串中的第一個數字。基於 _radix_ (第二個參數,用於指定我們要將其解析為哪種類型的數字:以 10 為基數,十六進制,八進制,二進制等),`parseInt` 檢查字串中的字元是否有效。 一旦遇到基數中無效數字的字元,它將停止解析並忽略以下字元。 `*` 不是合法的 `number`,所以程式僅將字串形態的 `"7"` 轉換至 decimal 形態的 `7`,故 `num` 現在的值為 `7`。 @@ -1515,9 +1515,9 @@ const num = parseInt('7*6', 10);

答案

-#### 答案: C +#### 答案:C -當對陣列做映射(map) 時,`num` 的值等同於它當前正在循環的元素。在這種情況中元素均為 numbers,所以條件式 `typeof num === "number"` 會回傳 `true` 的值。 +當對陣列做映射 (map) 時,`num` 的值等同於它當前正在循環的元素。在這種情況中元素均為 numbers,所以條件式 `typeof num === "number"` 會回傳 `true` 的值。 map 函式會建立一個新陣列,並插入該函式回傳的值。 但是我們不回傳任何值。當我們不從函式回傳值時,函式將回傳 `undefined`。由於陣列中的每個元素都會呼叫該函式,因此對於每個元素,我們都回傳 `undefined`。 @@ -1551,15 +1551,15 @@ console.log(person, birthYear);

答案

-#### 答案: A +#### 答案:A -參數是透過 _value_ 傳遞,除非它們是一個物件(object),物件則由透過 _reference_ 傳遞。 `birthYear` 是透過值傳遞的,因為它是字串不是物件。 當我們按值傳遞參數時,將建立該值的 _copy_ (請參閱問題46)。 +參數是透過 _value_ 傳遞,除非它們是一個物件 (object),物件則由透過 _reference_ 傳遞。`birthYear` 是透過值傳遞的,因為它是字串不是物件。當我們按值傳遞參數時,將建立該值的 _copy_ (請參閱問題 46)。 變數 `birthYear` 具有對值 `1997` 的 reference。參數 `year` 也有對值 `1997` 的 reference,但與變數 `birthYear` 所 reference 的不同。 -因此當我們通過將 `year` 設置為等於 `1998` 來更新 `year` 的值時,我們僅更新了 `year` 的值。 `birthYear` 仍然等於 `"1997"`。 +因此當我們通過將 `year` 設置為等於 `1998` 來更新 `year` 的值時,我們僅更新了 `year` 的值。`birthYear` 仍然等於 `"1997"`。 -`person` 的值是一個物件。 參數 `member` 具有(複製的)reference 指向 _相同_ 物件。 -因此當我們修改物件 `member` 的屬性時, `person` 的值也會被修改,因為它們都 reference 了相同的物件。 `person` 的 `name` 屬性現在等於值 `"Lydia"`。 +`person` 的值是一個物件。參數 `member` 具有(複製的)reference 指向 _相同_ 物件。 +因此當我們修改物件 `member` 的屬性時,`person` 的值也會被修改,因為它們都 reference 了相同的物件。`person` 的 `name` 屬性現在等於值 `"Lydia"`。

@@ -1593,13 +1593,13 @@ sayHi();
答案

-#### 答案: D +#### 答案:D -使用 `throw` 語句,我們可以建立自定義的錯誤。 使用此語句,您可以觸發例外(exception)。例外可以是 `string`,`number`,`boolean` 或 `object`。 +使用 `throw` 語句,我們可以建立自定義的錯誤。使用此語句,您可以觸發例外 (exception)。例外可以是 `string`,`number`,`boolean` 或 `object`。 在這種情況下,我們的例外是字串 `Hello world`。 -通過 `catch` 語句,我們可以指定如果在 `try` 的程式區塊中拋出例外時該怎麼辦。 例如拋出例外:字串 `'Hello world'`。 -現在, `e` 等於我們記錄的字串。 因此輸出結果將會是 `'Oh an error: Hello world'`。 +通過 `catch` 語句,我們可以指定如果在 `try` 的程式區塊中拋出例外時該怎麼辦。例如拋出例外:字串 `'Hello world'`。 +現在,`e` 等於我們記錄的字串。因此輸出結果將會是 `'Oh an error: Hello world'`。

@@ -1626,9 +1626,9 @@ console.log(myCar.make);
答案

-#### 答案: B +#### 答案:B -當您回傳屬性(property) 時,該屬性的值等於 _returned_ 的值,而不是在函式建構式(constructor function)中設置的值。 我們回傳字串 `Maserati`,因此 `myCar.make` 等於 `Maserati`。 +當您回傳屬性 (property) 時,該屬性的值等於 _returned_ 的值,而不是在函式建構式 (constructor function) 中設置的值。我們回傳字串 `Maserati`,因此 `myCar.make` 等於 `Maserati`。

@@ -1654,7 +1654,7 @@ console.log(typeof y);
答案

-#### 答案: A +#### 答案:A `let x = y = 10;` 實際上是 shorthand for: @@ -1663,13 +1663,13 @@ y = 10; let x = y; ``` -當我們將 `y `設置為等於 `10` 時,我們實際上將屬性 `y` 加入到 global object 中(瀏覽器中的 `window`,Node中的 `global`)。 現在,瀏覽器中 `window.y` 現在等於 `10`。 +當我們將 `y `設置為等於 `10` 時,我們實際上將屬性 `y` 加入到 global object 中(瀏覽器中的 `window`,Node 中的 `global`)。現在,瀏覽器中 `window.y` 現在等於 `10`。 -接著我們宣告一個變數 `x`,並將其值賦予為 `y`,即 `10`。 用` let` 關鍵字宣告的變數是 _block scoped_ ,它們僅在宣告它們的區塊中定義; 另外此案例的函示是,立即函示表達式(IIFE)。 -當我們使用 `typeof` 運算子時, `x` 並未被定義:我們試圖在宣告它的區塊外訪問 `x`。這將獲得 `x` 並未被定義的結果。 未分配值或未宣告的值的類型為 `"undefined"`。 `console.log(typeof x)` 回傳 `"undefined"`。 +接著我們宣告一個變數 `x`,並將其值賦予為 `y`,即 `10`。用` let` 關鍵字宣告的變數是 _block scoped_,它們僅在宣告它們的區塊中定義;另外此案例的函示是,立即函示表達式(IIFE)。 +當我們使用 `typeof` 運算子時,`x` 並未被定義:我們試圖在宣告它的區塊外訪問 `x`。這將獲得 `x` 並未被定義的結果。未分配值或未宣告的值的類型為 `"undefined"`。`console.log(typeof x)` 回傳 `"undefined"`。 -但是,當將 `y` 設置為 `10` 時,我們建立了global variable `y`。 在我們程式中的任何位置均可訪問此值。 -`y` 被定義,並且為類型 `number` 的值。 因此 `console.log(typeof y` 回傳 `"number"`。 +但是,當將 `y` 設置為 `10` 時,我們建立了 global variable `y`。在我們程式中的任何位置均可訪問此值。 +`y` 被定義,並且為類型 `number` 的值。因此 `console.log(typeof y` 回傳 `"number"`。

@@ -1706,12 +1706,12 @@ pet.bark();
答案

-#### 答案: A +#### 答案:A -透過 `delete` 關鍵字,我們可以從物件中刪除它的屬性。同樣適用在原型(prototype)。通過刪除原型上的屬性,該屬性在原型鏈中將不可再被使用。 -在這個案例中, `bark` 函式在 `delete Dog.prototype.bark` 之後的原型上不再可用,但是我們仍然嘗試訪問它。 +透過 `delete` 關鍵字,我們可以從物件中刪除它的屬性。同樣適用在原型 (prototype)。通過刪除原型上的屬性,該屬性在原型鏈中將不可再被使用。 +在這個案例中,`bark` 函式在 `delete Dog.prototype.bark` 之後的原型上不再可用,但是我們仍然嘗試訪問它。 -因此當我們嘗試呼叫不是函式的東西時,程式將拋出 `TypeError`。 在這個案例中,將為 `TypeError: pet.bark is not a function` ,因為 `pet.bark` 是 `undefined`。 +因此當我們嘗試呼叫不是函式的東西時,程式將拋出 `TypeError`。在這個案例中,將為 `TypeError: pet.bark is not a function`,因為 `pet.bark` 是 `undefined`。

@@ -1734,9 +1734,9 @@ console.log(set);
答案

-#### 答案: D +#### 答案:D -`Set` 物件是 _唯一_ 值的集合: 任何存在於 `Set` 的值均為唯一的,不會存在相同的值(重複的值將會由後出現的覆蓋已出現的)。 +`Set` 物件是 _唯一_ 值的集合:任何存在於 `Set` 的值均為唯一的,不會存在相同的值 (重複的值將會由後出現的覆蓋已出現的)。 陣列 `[1, 1, 2, 3, 4]` 中有重複的值 `1`,因此結果會是 `{1, 2, 3, 4}`。 @@ -1770,11 +1770,11 @@ console.log(myCounter);

答案

-#### 答案: C +#### 答案:C -被引用(imported) 的模組(module) 是 _唯讀_ 的: 您無法修改被引用模組中項目,只有輸出(export) 該項目的模組可以更改它的值。 +被引用 (imported) 的模組 (module) 是 _唯讀_ 的:您無法修改被引用模組中項目,只有輸出 (export) 該項目的模組可以更改它的值。 -因此當我們嘗試增加 `myCounter` 的值時,他將拋出錯誤: `myCounter` is read-only and cannot be modified。 +因此當我們嘗試增加 `myCounter` 的值時,他將拋出錯誤:`myCounter` is read-only and cannot be modified。

@@ -1799,11 +1799,11 @@ console.log(delete age);
答案

-#### 答案: A +#### 答案:A -`delete` 運算子會回傳一個布林值: 成功刪除物件的情況下會回傳 `true`,反之則為 `false`。 但是經由 `var`,`const` 或是 `let` 關鍵字所宣告的變數是無法使用 `delete` 運算子刪除的。 +`delete` 運算子會回傳一個布林值:成功刪除物件的情況下會回傳 `true`,反之則為 `false`。但是經由 `var`,`const` 或是 `let` 關鍵字所宣告的變數是無法使用 `delete` 運算子刪除的。 -此處, `name` 無法成功刪除且會回傳 `false`,因為它是經由 `const` 所宣告。當我們宣告 `age` 的值為 `21` 時,實際上我們做的是將一個名為 `age` 的屬性為添加到了全球物件中,您可以透過 `delete` 來刪除物件中的屬性,因此您也能刪除全球物件中的屬性,故將回傳 `true`。 +此處,`name` 無法成功刪除且會回傳 `false`,因為它是經由 `const` 所宣告。當我們宣告 `age` 的值為 `21` 時,實際上我們做的是將一個名為 `age` 的屬性為添加到了全球物件中,您可以透過 `delete` 來刪除物件中的屬性,因此您也能刪除全球物件中的屬性,故將回傳 `true`。

@@ -1827,9 +1827,9 @@ console.log(y);
答案

-#### 答案: C +#### 答案:C -我們可以通過解構(destructuring) 從陣列或物件的屬性中獲得值。例如: +我們可以通過解構 (destructuring) 從陣列或物件的屬性中獲得值。例如: ```javascript [a, b] = [1, 2]; @@ -1837,7 +1837,7 @@ console.log(y); -a 的值現在為 `1` 且b 的值現在為`2`。我們針對此問題所做的動作為: +a 的值現在為 `1` 且 b 的值現在為`2`。我們針對此問題所做的動作為: ```javascript [y] = [1, 2, 3, 4, 5]; @@ -1869,9 +1869,9 @@ console.log(admin);

答案

-#### 答案: B +#### 答案:B -使用 spread 運算子可以合併物件(`...`)。它使您可以建立一個物件的鍵/值的複製,並將其添加到另一物件中。 +使用 spread 運算子可以合併物件 (`...`)。它使您可以建立一個物件的鍵/值的複製,並將其添加到另一物件中。 在這裡我們建立了 `user` 物件的複製並將其添加至 `admin` 物件。因此將輸出 `{ admin: true, name: "Lydia", age: 21 }`。

@@ -1898,9 +1898,9 @@ console.log(Object.keys(person));
答案

-#### 答案: B +#### 答案:B -透過 `defineProperty`,我們可以對物件增加新的屬性或是修改已經存在的屬性。當我們使用 `defineProperty` 增加物件的屬性時,它們被預設為 _不可 enumerable_ 。 +透過 `defineProperty`,我們可以對物件增加新的屬性或是修改已經存在的屬性。當我們使用 `defineProperty` 增加物件的屬性時,它們被預設為 _不可 enumerable_。 `Object.keys` 方法僅回傳物件中所有 _可 enumerable_ 的屬性名稱,這個案例中只有 `"name"`。 預設下,使用 `defineProperty `方法增加的屬性是不可變的。但您可以覆蓋這個行為透過 `writable`,`configurable` 及 `enumerable` 屬性。 @@ -1932,14 +1932,14 @@ console.log(data);

答案

-#### 答案: A +#### 答案:A -`JSON.stringify` 的第二個參數是 _替換者 (replacer)_ ,替換者可以是函式,也可以是陣列,並允許您控制值要如何獲怎麼串化(stringified)。 +`JSON.stringify` 的第二個參數是 _替換者 (replacer)_,替換者可以是函式,也可以是陣列,並允許您控制值要如何獲怎麼串化 (stringified)。 -如果替換者是 _陣列_ ,僅將陣列中包含的屬性名稱加到 JSON 字串中。 +如果替換者是 _陣列_,僅將陣列中包含的屬性名稱加到 JSON 字串中。 此案例中,僅有 `"level"` and `"health"` 被包含,`"username"` 沒有被包含在內,因此 `data` 的值將為 `"{"level":19, "health":90}"`。 -如果替換者是 _函式_ ,在要字串化的每個物件屬性上將會呼叫此函式。從此函式回傳的值將是加到 JSON 字串中的屬性的值。如果值為 `undefined`,則此屬性從 JSON 字串中排除。 +如果替換者是 _函式_,在要字串化的每個物件屬性上將會呼叫此函式。從此函式回傳的值將是加到 JSON 字串中的屬性的值。如果值為 `undefined`,則此屬性從 JSON 字串中排除。

@@ -1969,11 +1969,11 @@ console.log(num2);
答案

-#### 答案: A +#### 答案:A -單元運算子 `++` 首先 _回傳_ 操作數的值,然後 _遞增_ 操作數的值。 `num1` 的值是 `10`,因為 `increaseNumber` 函式首先回傳 `num` 的值,即 `10`,之後才遞增 `num` 的值。 +單元運算子 `++` 首先 _回傳_ 操作數的值,然後 _遞增_ 操作數的值。`num1` 的值是 `10`,因為 `increaseNumber` 函式首先回傳 `num` 的值,即 `10`,之後才遞增 `num` 的值。 -`num2` 是 `10`, 因為我們將 `num1` 傳遞給了 `increasePassedNumber`。 `number` 等於 `10`( `num1` 的值。同樣,單元運算子 `++` 首先 _回傳_ 操作數的值,然後 _遞增_ 操作數的值。 +`num2` 是 `10`,因為我們將 `num1` 傳遞給了 `increasePassedNumber`。`number` 等於 `10`(`num1` 的值。同樣,單元運算子 `++` 首先 _回傳_ 操作數的值,然後 _遞增_ 操作數的值。 `number` 的值是 `10`,因此 `num2` 等於 `10`。

@@ -2004,15 +2004,15 @@ multiply(value);
答案

-#### 答案: C +#### 答案:C -在ES6中,我們可以使用預設值初始化參數。如果沒有其他值傳遞給該函式或是傳入的參數是 `undefined`,則該參數的值為預設值。此案例中,我們將 `value` 物件的屬性擴展到一個新物件中,因此 `x` 具有預設值 `{number:10}`。 +在 ES6 中,我們可以使用預設值初始化參數。如果沒有其他值傳遞給該函式或是傳入的參數是 `undefined`,則該參數的值為預設值。此案例中,我們將 `value` 物件的屬性擴展到一個新物件中,因此 `x` 具有預設值 `{number:10}`。 預設值是在 _呼叫_ 時被 evaluated。每次呼叫該函式時,都會建立一個 _新_ 物件。我們在沒有傳遞值的情況下呼叫了 `multiply` 函式兩次:`x` 的預設值是 `{{number:10}`。因此,我們輸出該數字的相乘值,即 `20`。 -第三次呼叫時,我們確實傳遞了一個參數:名為 `value` 的物件。 `*=` 運算子實際上是 `x.number = x.number * 2` 的簡寫:因此我們修改了 `x.number` 的值,並記錄相乘後的值 `20`。 +第三次呼叫時,我們確實傳遞了一個參數:名為 `value` 的物件。`*=` 運算子實際上是 `x.number = x.number * 2` 的簡寫:因此我們修改了 `x.number` 的值,並記錄相乘後的值 `20`。 -第四次,我們再次傳遞名為 `value` 的物件。 `x.number` 先前已修改為 `20`,因此 `x.number * = 2` 為 `40`。 +第四次,我們再次傳遞名為 `value` 的物件。`x.number` 先前已修改為 `20`,因此 `x.number * = 2` 為 `40`。

@@ -2033,19 +2033,19 @@ multiply(value);
答案

-#### 答案: D +#### 答案:D -`reduce` 方法接收的第一個參數是 _累加器(accumulator)_ ,在這種情況下是 `x`。 第二個參數是 _current value_ `y`。 使用 `reduce` 方法,我們對陣列中的每個元素執行一個 callback 函式,並在最終回一個值。 +`reduce` 方法接收的第一個參數是 _累加器 (accumulator)_,在這種情況下是 `x`。第二個參數是 _current value_ `y`。使用 `reduce` 方法,我們對陣列中的每個元素執行一個 callback 函式,並在最終回一個值。 在此示例中,我們不回傳任何值,僅記錄了累加器的值和當前值。 -累加器的值等於 callback 函式先前回傳的值。 如果沒有 `initialValue` 參數傳遞給 `reduce` 方法,則累加器的初始值將會等於第一個元素。 +累加器的值等於 callback 函式先前回傳的值。如果沒有 `initialValue` 參數傳遞給 `reduce` 方法,則累加器的初始值將會等於第一個元素。 -在第一個呼叫中,累加器(`x`)為`1`,當前值(`y`)為`2`。 我們不從 callback 函式回傳,而是輸出累加器和當前值:`1` 和 `2`。 +在第一個呼叫中,累加器(`x`)為`1`,當前值(`y`)為`2`。我們不從 callback 函式回傳,而是輸出累加器和當前值:`1` 和 `2`。 -如果您不從 callback 函式回傳值,則它將回傳 `undefined`。 在下一次呼叫時,累加器為 `undefined`,當前值為 `3`。 於是 `undefined` 和 `3` 被輸出。 +如果您不從 callback 函式回傳值,則它將回傳 `undefined`。在下一次呼叫時,累加器為 `undefined`,當前值為 `3`。於是 `undefined` 和 `3` 被輸出。 -在第四次呼叫中,我們再次不從 callback 函式回傳。 累加器再次為 `undefined`,當前值為 `4`。於是 `undefined` 和 `4` 被輸出。 +在第四次呼叫中,我們再次不從 callback 函式回傳。累加器再次為 `undefined`,當前值為 `4`。於是 `undefined` 和 `4` 被輸出。

@@ -2093,13 +2093,13 @@ class Labrador extends Dog {
答案

-#### 答案: B +#### 答案:B -在子類別中,在呼叫 `super` 前不能存取 `this` 關鍵字,如果你這麼做,它將拋出一個 `ReferenceError`,建構式1與4會引發這個錯誤。 +在子類別中,在呼叫 `super` 前不能存取 `this` 關鍵字,如果你這麼做,它將拋出一個 `ReferenceError`,建構式 1 與 4 會引發這個錯誤。 使用 `super` 關鍵字時,我們要提供參數給父類別呼叫其建構式。父類別需要接受一個 `name` 參數,所以我們需要把 `name` 傳給 `super`。 -`Labrador` 類別接收兩個參數, `name` 參數是由於它繼承了 `Dog` , `size` 作為`Labrador` 類的額外屬性,它們都需要傳遞給 `Labrador` 的建構式,因此使用建構式2是正確答案。 +`Labrador` 類別接收兩個參數,`name` 參數是由於它繼承了 `Dog`,`size` 作為`Labrador` 類的額外屬性,它們都需要傳遞給 `Labrador` 的建構式,因此使用建構式 2 是正確答案。

@@ -2127,11 +2127,11 @@ export const sum = (a, b) => a + b;
答案

-#### 答案: B +#### 答案:B `import` 命令是 _編譯階段_ 執行的。這代表被引入的模組會優先執行,而引入模組的檔案會 _之後執行_。 -這是 `CommonJS` 中 `require()` 和 `import` 之間的區別!使用 `require()`,您可以在執行程式時根據需要戴入依賴的項目。如果我們使用 `require` 而不是 `import` 來執行此題, 結果將會依 `running index.js`,`running sum.js`,`3` 的順序輸出。 +這是 `CommonJS` 中 `require()` 和 `import` 之間的區別!使用 `require()`,您可以在執行程式時根據需要戴入依賴的項目。如果我們使用 `require` 而不是 `import` 來執行此題,結果將會依 `running index.js`,`running sum.js`,`3` 的順序輸出。

@@ -2153,9 +2153,9 @@ console.log(Symbol('foo') === Symbol('foo'));
答案

-#### 答案: A +#### 答案:A -每個 Symbol 都是完全唯一的。傳遞給 Symbol 的參數只是給 Symbol 的一個描述。 Symbol 的值不依賴於傳遞的參數。當我們建立兩個全新的 Symbol 去比較時:第一個`Symbol('foo')`,第二個`Symbol('foo')`, 因這兩個值是唯一的,彼此不相等,因此 `Symbol('foo') === Symbol('foo')` 會得到 `false`。 +每個 Symbol 都是完全唯一的。傳遞給 Symbol 的參數只是給 Symbol 的一個描述。Symbol 的值不依賴於傳遞的參數。當我們建立兩個全新的 Symbol 去比較時:第一個`Symbol('foo')`,第二個`Symbol('foo')`, 因這兩個值是唯一的,彼此不相等,因此 `Symbol('foo') === Symbol('foo')` 會得到 `false`。

@@ -2178,9 +2178,9 @@ console.log(name.padStart(2));
答案

-#### 答案: C +#### 答案:C -使用 `padStart` 函數,我們可以在字串的前面加上填充字串。傳遞給此函數的參數是字串的總長度(包含填充字串)。字串 Lydia Hallie 的長度為 `12` , 因此 `name.padStart(13)` 在字串的開頭只會插入1個空格,因為 12 + 1 等於 13。 +使用 `padStart` 函數,我們可以在字串的前面加上填充字串。傳遞給此函數的參數是字串的總長度(包含填充字串)。字串 Lydia Hallie 的長度為 `12` , 因此 `name.padStart(13)` 在字串的開頭只會插入 1 個空格,因為 12 + 1 等於 13。 如果傳給 `padStart` 函數的參數小於字串的長度,則不會加上填充字串。 @@ -2197,13 +2197,13 @@ console.log('🥑' + '💻'); - A: `"🥑💻"` - B: `257548` -- C: 一個包含碼位(code point)的字串 +- C: 一個包含碼位 (code point) 的字串 - D: 錯誤

答案

-#### 答案: A +#### 答案:A 使用 `+` 運算元,你可以連接字串。在此例,我們將字串“🥑”與字串”💻“連接起來,產生”🥑💻“。 @@ -2216,7 +2216,7 @@ console.log('🥑' + '💻'); ```javascript function* startGame() { - const answer = yield '你喜歡 JavaScript 嗎?'; + const answer = yield '你喜歡 JavaScript 嗎?'; if (answer !== 'Yes') { return "哦,我想我們該走了"; } @@ -2224,7 +2224,7 @@ function* startGame() { } const game = startGame(); -console.log(/* 1 */); // 你喜歡 JavaScript 嗎? +console.log(/* 1 */); // 你喜歡 JavaScript 嗎? console.log(/* 2 */); // JavaScript 也愛你 ❤️ ``` @@ -2236,13 +2236,13 @@ console.log(/* 2 */); // JavaScript 也愛你 ❤️

答案

-#### 答案: C +#### 答案:C -`generator` 函數在遇到 yield 關鍵字時會 “暫停” 執行。首先,我們需要讓函數產生字串 "你喜歡 JavaScript 嗎?",這可以透過呼叫 `game.next().value` 來完成。 +`generator` 函數在遇到 yield 關鍵字時會“暫停”執行。首先,我們需要讓函數產生字串 "你喜歡 JavaScript 嗎?",這可以透過呼叫 `game.next().value` 來完成。 -`startGame()` 函數會一行一行執行直到遇到 `yield` 關鍵字,在函數裡第一個就有一個 `yield` 關鍵字:所以執行到第一行就停止了! _此時answer變數還尚未定義_ +`startGame()` 函數會一行一行執行直到遇到 `yield` 關鍵字,在函數裡第一個就有一個 `yield` 關鍵字:所以執行到第一行就停止了!_此時 answer 變數還尚未定義_ -當我們呼叫 `game.next("Yes").value`,前一個 `yield` 被傳遞給 `next()` 的參數值所取代。此例我們使用 `Yes`。變數 `answer` 的值現在等於 `Yes`。 if 語句的條件回傳 `false`,並且會回傳 `JavaScript 也愛你 ❤️` 。 +當我們呼叫 `game.next("Yes").value`,前一個 `yield` 被傳遞給 `next()` 的參數值所取代。此例我們使用 `Yes`。變數 `answer` 的值現在等於 `Yes`。if 語句的條件回傳 `false`,並且會回傳 `JavaScript 也愛你 ❤️`。

@@ -2263,9 +2263,9 @@ console.log(String.raw`Hello\nworld`);
答案

-#### 答案: C +#### 答案:C -`String.raw`會回傳一個字串,其中轉義符(`/n`, `/v`, `/t`等)被忽略! 反斜線可能是一個問題,因為你可能會有這樣的結果。 +`String.raw`會回傳一個字串,其中轉義符 (`/n`, `/v`, `/t`等) 被忽略!反斜線可能是一個問題,因為你可能會有這樣的結果。 `const path = "C:\Documents\Projects\table.html"`。 @@ -2303,9 +2303,9 @@ console.log(data);

答案

-#### 答案: C +#### 答案:C -一個異步函數總是回傳一個 promise 。 `await` 仍然要等待 promise 的 resolve:當我們呼叫 `getData()` 等於 `data` 時,會得到一個等待的 promise。 +一個異步函數總是回傳一個 promise。 `await` 仍然要等待 promise 的 resolve:當我們呼叫 `getData()` 等於 `data` 時,會得到一個等待的 promise。 如果我們想獲取 resolve 後的值`"I made it"`,我們可以在`data`上使用`.then()`函數: @@ -2337,11 +2337,11 @@ console.log(result);

答案

-#### 答案: B +#### 答案:B `.push()`函數回傳的是陣列的長度!原本陣列包含一個元素(字串`"香蕉"`),長度為`1`。後來將字串 `"apple"` 加到陣列中後,陣列包含兩個元素。所以會從`addToList`函數中得到,長度為 `"2"`。 -`push`函數修改了原來的陣列。如果你想從函數中回傳 _陣列_ 而不是 _陳列的長度_ ,你應該在加完`item`到陣列後,回傳`list`。 +`push`函數修改了原來的陣列。如果你想從函數中回傳 _陣列_ 而不是 _陳列的長度_,你應該在加完`item`到陣列後,回傳`list`。

@@ -2369,13 +2369,13 @@ console.log(shape);
答案

-#### 答案: B +#### 答案:B -`Object.freeze` 使我們無法增加、刪除或修改Object的屬性(除非該屬性的值是另一個Object)。 +`Object.freeze` 使我們無法增加、刪除或修改 Object 的屬性(除非該屬性的值是另一個 Object)。 -當我們建立變數`shape`並等同被凍結的Object`box`時,`shape`也是指一個被凍結的Object。你可以透過使用`Object.isFrozen`檢查一個Object是否被凍結。在這種情況下,`Object.isFrozen(shape)`回傳true,因為變數`shape`也指向一個凍結Object。 +當我們建立變數`shape`並等同被凍結的 Object`box`時,`shape`也是指一個被凍結的 Object。你可以透過使用`Object.isFrozen`檢查一個 Object 是否被凍結。在這種情況下,`Object.isFrozen(shape)`回傳 true,因為變數`shape`也指向一個凍結 Object。 -由於`shape`是被凍結的,而且`x`的值不是一個Object,所以我們不能修改`x`的屬性。 `x`仍然等於`10`,於是`{ x: 10, y: 20 }`被記錄下來。 +由於`shape`是被凍結的,而且`x`的值不是一個 Object,所以我們不能修改`x`的屬性。`x`仍然等於`10`,於是`{ x: 10, y: 20 }`被記錄下來。

@@ -2398,11 +2398,11 @@ console.log(name);
答案

-#### 答案: D +#### 答案:D 當我們從右側的物件解構屬性`name`時,我們將其值`Lydia`分配給名為`myName`的變數。 -使用`{name:myName}`,我們是在告訴JavaScript我們要建立一個名為`myName`的新變數,並且其值是右側物件的`name`屬性的值。 +使用`{name:myName}`,我們是在告訴 JavaScript 我們要建立一個名為`myName`的新變數,並且其值是右側物件的`name`屬性的值。 當我們嘗試輸出`name`,一個未定義的變數時,就會引發`ReferenceError`。 @@ -2411,7 +2411,7 @@ console.log(name); --- -###### 77. 以下是純函數嗎? +###### 77. 以下是純函數嗎? ```javascript function sum(a, b) { @@ -2425,7 +2425,7 @@ function sum(a, b) {

答案

-#### 答案: B +#### 答案:B 純函數一種若輸入參數相同,則永遠會得到相同輸出的函數。 @@ -2474,7 +2474,7 @@ console.log(addFunction(5 * 2));

答案

-#### 答案: C +#### 答案:C `add`函數是一個記憶函數。通過記憶化,我們可以暫存函數的結果,以加快其執行速度。上述情況,我們建立一個`cache`物件,用於存儲先前存過的值。 @@ -2482,11 +2482,11 @@ console.log(addFunction(5 * 2)); 我們用相同的值三次呼叫了`addFunction`函數: -在第一次呼叫,`num`等於`10`時函數的值尚未暫存,if語句`num in cache`回傳`false`,else塊的代碼被執行:`Calculated! 20`,並且其結果被添加到暫存物件,`cache`現在看起來像`{10:20}`。 +在第一次呼叫,`num`等於`10`時函數的值尚未暫存,if 語句`num in cache`回傳`false`,else 塊的代碼被執行:`Calculated! 20`,並且其結果被添加到暫存物件,`cache`現在看起來像`{10:20}`。 -第二次,`cache`物件包含`10`的回傳值。 if語句 `num in cache` 回傳`true`,印出`From cache! 20`。 +第二次,`cache`物件包含`10`的回傳值。if 語句 `num in cache` 回傳`true`,印出`From cache! 20`。 -第三次,我們將`5 * 2`(值為10)傳遞給函數。 `cache`物件包含`10`的回傳值。 if語句 `num in cache` 回傳`true`,印出`From cache! 20`。 +第三次,我們將`5 * 2`(值為 10) 傳遞給函數。`cache`物件包含`10`的回傳值。if 語句 `num in cache` 回傳`true`,印出`From cache! 20`。

@@ -2514,9 +2514,9 @@ for (let item of myLifeSummedUp) {
答案

-#### 答案: A +#### 答案:A -透過`for-in`迴圈,我們可以遍歷一個物件**自有的**、**繼承的**、**可列舉的**、**非Symbol的**屬性。在陣列中,可列舉屬性是陣列元素的“鍵”, 即它們的索引。類似於下面這個物件: +透過`for-in`迴圈,我們可以遍歷一個物件**自有的**、**繼承的**、**可列舉的**、**非 Symbol 的**屬性。在陣列中,可列舉屬性是陣列元素的“鍵”,即它們的索引。類似於下面這個物件: `{0: "☕", 1: "💻", 2: "🍷", 3: "🍫"}` @@ -2544,11 +2544,11 @@ console.log(list)

答案

-#### 答案: C +#### 答案:C 陣列元素可以包含任何值。數字,字符,布林,物件,陣列,`null`,`undefined`, 以及其他表達式,如日期,函數和計算式。 -元素將等於回傳的值。 `1 + 2`回傳`3`,`1 * 2`回傳'2`,'1 / 2`回傳`0.5`。 +元素將等於回傳的值。`1 + 2`回傳`3`,`1 * 2`回傳'2`,'1 / 2`回傳`0.5`。

@@ -2572,13 +2572,13 @@ console.log(sayHi())
答案

-#### 答案: B +#### 答案:B -預設情況下,如果不傳參數給函數,函數內參數的值將為`undefined`。上述情況,我們沒有給參數`name`傳值。 `name`等於`undefined`,並被印出。 +預設情況下,如果不傳參數給函數,函數內參數的值將為`undefined`。上述情況,我們沒有給參數`name`傳值。`name`等於`undefined`,並被印出。 -在ES6中,我們可以使用預設參數覆蓋此預設的`undefined`值。例如: +在 ES6 中,我們可以使用預設參數覆蓋此預設的`undefined`值。例如: -`function sayHi(name =“Lydia”){...}` +`function sayHi (name =“Lydia”){...}` 在這種情況下,如果我們沒有傳遞值或者如果我們傳遞`undefined`,`name`總是等於字符`Lydia` @@ -2614,11 +2614,11 @@ setTimeout(() => {

答案

-#### 答案: B +#### 答案:B `this`關鍵字的指向取決於使用它的位置。在**函數**中,比如`getStatus`,`this`指向的是呼叫它的物件,上述例子中`data`物件呼叫了`getStatus`,因此`this`指向的就是`data`物件。當我們輸出`this.status`時,`data`物件的`status`屬性被輸出,即`"🥑"`。 -使用`call`方法,可以更改`this`指向的物件。 `data.getStatus.call(this)`是將`this`的指向由`data`物件更改為全局物件。在全局物件上,有一個名為`status`的變數,其值為`”😎“`。因此輸出`this.status`時,會輸出`“😎”`。 +使用`call`方法,可以更改`this`指向的物件。`data.getStatus.call(this)`是將`this`的指向由`data`物件更改為全局物件。在全局物件上,有一個名為`status`的變數,其值為`”😎“`。因此輸出`this.status`時,會輸出`“😎”`。

@@ -2645,13 +2645,13 @@ console.log(person)
答案

-#### 答案: A +#### 答案:A 我們將變數`city`設置為等於`person`物件上名為`city`的屬性的值。這個物件上沒有名為`city`的屬性,因此變數`city`的值為`undefined`。 請注意,我們沒有引用`person`物件本身,只是將變數`city`設置為等於`person`物件上`city`屬性的當前值。 -然後,我們將`city`設置為等於字串`“Amsterdam”`。這不會更改person物件:沒有對該物件的引用。 +然後,我們將`city`設置為等於字串`“Amsterdam”`。這不會更改 person 物件:沒有對該物件的引用。 因此輸出`person`物件時,會回傳未修改的物件。 @@ -2683,9 +2683,9 @@ console.log(checkAge(21))

答案

-#### 答案: C +#### 答案:C -`const`和`let`定義的變數是具有**區塊作用域**的,區塊是大括號(`{}`)之間的任何東西, 即上述情況`if / else`語句的大括號。由於區塊作用域,我們無法在定義的塊之外引用變數,因此拋出`ReferenceError`。 +`const`和`let`定義的變數是具有**區塊作用域**的,區塊是大括號(`{}`)之間的任何東西,即上述情況`if / else`語句的大括號。由於區塊作用域,我們無法在定義的塊之外引用變數,因此拋出`ReferenceError`。

@@ -2707,7 +2707,7 @@ fetch('https://www.website.com/api/user/1')
答案

-#### 答案: C +#### 答案:C 第二個`.then`中`res`的值等於前一個`.then`中函數回傳的值。你可以像這樣繼續連接`.then`,將值傳遞給下一個處理程序。 @@ -2715,7 +2715,7 @@ fetch('https://www.website.com/api/user/1')

--- -###### 86. 哪個選項是將`hasName`設為`true`的方法,前提是不能將`true`作為參數傳遞? +###### 86. 哪個選項是將`hasName`設為`true`的方法,前提是不能將`true`作為參數傳遞? ```javascript function getName(name) { @@ -2731,9 +2731,9 @@ function getName(name) {
答案

-#### 答案: A +#### 答案:A -使用邏輯非運算子`!`,將回傳一個布林值,使用`!! name`,我們可以確定`name`的值是`true`還是`false`。如果`name`是`true`,那麼`!name`回傳`false`。 `!false`回傳`true`。 +使用邏輯非運算子`!`,將回傳一個布林值,使用`!! name`,我們可以確定`name`的值是`true`還是`false`。如果`name`是`true`,那麼`!name`回傳`false`。`!false`回傳`true`。 通過將`hasName`設置為`name`,可以將`hasName`設置為等於傳遞給`getName`函數的值,而不是布林值`true`。 @@ -2759,11 +2759,11 @@ console.log("I want pizza"[0])

答案

-#### 答案: B +#### 答案:B -可以使用雙括號表示法獲取字串中特定索引的字串,字串中的第一個字串具有索引0,依此類推。在這種情況下,我們想要得到索引為0的元素,字串`'I'`被記錄。 +可以使用雙括號表示法獲取字串中特定索引的字串,字串中的第一個字串具有索引 0,依此類推。在這種情況下,我們想要得到索引為 0 的元素,字串`'I'`被記錄。 -請注意,IE7及更低版本不支援此方法。應該使用`.charAt()` +請注意,IE7 及更低版本不支援此方法。應該使用`.charAt()`

@@ -2787,9 +2787,9 @@ sum(10)
答案

-#### 答案: B +#### 答案:B -您可以將預設參數的值設置為函數的另一個參數,只要另一個參數定義在其之前即可。我們將值`10`傳遞給`sum`函數。如果`sum`函數只接收1個參數,則意味著沒有傳遞`num2`的值,這種情況下,`num1`的值等於傳遞的值`10`。 `num2`的預設值是`num1`的值,即`10`。 ```num1 + num2```回傳`20`。 +您可以將預設參數的值設置為函數的另一個參數,只要另一個參數定義在其之前即可。我們將值`10`傳遞給`sum`函數。如果`sum`函數只接收 1 個參數,則意味著沒有傳遞`num2`的值,這種情況下,`num1`的值等於傳遞的值`10`。`num2`的預設值是`num1`的值,即`10`。```num1 + num2```回傳`20`。 如果您嘗試將預設參數的值設置為後面定義的參數,則可能導致參數的值尚未初始化,從而引發錯誤。比如: ```js @@ -2826,11 +2826,11 @@ console.log(data)

答案

-#### 答案: A +#### 答案:A 使用`import * as name`語法,我們將`module.js`文件中所有`export`匯入到`index.js`文件中,並且建立了一個名為`data`的新物件。在`module.js`文件中,有兩個匯出:預設匯出和命名匯出。預設匯出是一個回傳字串“Hello World”的函數,命名匯出是一個名為`name`的變數,其值為字串`“Lydia”`。 -`data`物件具有預設匯出的`default`屬性,其他屬性具有指定exports的名稱及其對應的值。 +`data`物件具有預設匯出的`default`屬性,其他屬性具有指定 exports 的名稱及其對應的值。

@@ -2857,9 +2857,9 @@ console.log(typeof member)
答案

-#### 答案: C +#### 答案:C -class是建構函數的語法糖,如果用建構函數的方式來重寫`Person`class則會是: +class 是建構函數的語法糖,如果用建構函數的方式來重寫`Person`class 則會是: ```javascript function Person() { @@ -2889,11 +2889,11 @@ console.log(newList.push(5))

答案

-#### 答案: D +#### 答案:D `.push`函數回傳陣列的長度,而不是陣列本身!通過將`newList`設置為`[1,2,3].push(4)`,實際上`newList`等於陣列的新長度:`4`。 -然後,嘗試在`newList`上使用`.push`函數。由於`newList`是數值`4`,拋出TypeError。 +然後,嘗試在`newList`上使用`.push`函數。由於`newList`是數值`4`,拋出 TypeError。

@@ -2920,7 +2920,7 @@ console.log(giveLydiaChocolate.prototype)
答案

-#### 答案: D +#### 答案:D 正規式函數,例如`giveLydiaPizza`函數,有一個`prototype`屬性,它是一個帶有`constructor`屬性的物件(原型物件)。然而,箭頭函數,例如`giveLydiaChocolate`函數,沒有這個`prototype`屬性。嘗試使用`giveLydiaChocolate.prototype`存取`prototype`屬性時會得到`undefined`。 @@ -2949,12 +2949,12 @@ for (const [x, y] of Object.entries(person)) {

答案

-#### 答案: A +#### 答案:A `Object.entries()`函數回傳一個給定物件本身可枚舉屬性的鍵值對陣列,上述情況回傳一個二維陣列,陣列每個元素是一個包含鍵和值的陣列: -`[['name','Lydia'],['age',21]]` +`[['name','Lydia'],['age', 21]]` -使用`for-of`循環,我們可以迭代陣列中的每個元素,上述情況是子陣列。我們可以使用`const [x,y]`在`for-of`循環中解構子陣列。 `x`等於子陣列中的第一個元素,`y`等於子陣列中的第二個元素。 +使用`for-of`循環,我們可以迭代陣列中的每個元素,上述情況是子陣列。我們可以使用`const [x,y]`在`for-of`循環中解構子陣列。`x`等於子陣列中的第一個元素,`y`等於子陣列中的第二個元素。 第一個子陣列是`[“name”,“Lydia”]`,其中`x`等於`name`,而`y`等於`Lydia`。 第二個子陣列是`[“age”,21]`,其中`x`等於`age`,而`y`等於`21`。 @@ -2981,7 +2981,7 @@ getItems(["banana", "apple"], "pear", "orange")

答案

-#### 答案: D +#### 答案:D `... args`是剩餘參數,剩餘參數的值是一個包含所有剩餘參數的陣列,**並且只能作為最後一個參數**。上面示範中,剩餘參數是第二個參數,這是不可能的,並會拋出語法錯誤。 @@ -3023,19 +3023,19 @@ console.log(nums(1, 2))

答案

-#### 答案: B +#### 答案:B -在JavaScript中,我們不必硬性寫分號(`;`),但是JavaScript引擎仍然在語法之後自動補上分號。這稱為**自動分號插入**。例如,一個語法可以是變數,或者像`throw`、`return`、`break`這樣的關鍵字。 +在 JavaScript 中,我們不必硬性寫分號 (`;`),但是 JavaScript 引擎仍然在語法之後自動補上分號。這稱為**自動分號插入**。例如,一個語法可以是變數,或者像`throw`、`return`、`break`這樣的關鍵字。 -在這裡,我們在新的一行上寫了一個`return`語法和另一個值`a + b `。然而,由於它是一個新的一行,引擎並不知道它實際上是我們想要回傳的值。相反,它會在`return`後面自動補上分號。你可以這樣看: +在這裡,我們在新的一行上寫了一個`return`語法和另一個值`a + b `。然而,由於它是一個新的一行,引擎並不知道它實際上是我們想要回傳的值。相反,它會在`return`後面自動補上分號。你可以這樣看: ```javascript return; a + b ``` -這意味著永遠不會到達`a + b`,因為函數在`return`關鍵字之後停止執行。如果沒有回傳值,就像這裡,函數回傳`undefined`。注意,在`if/else`語法之後沒有自動插入! +這意味著永遠不會到達`a + b`,因為函數在`return`關鍵字之後停止執行。如果沒有回傳值,就像這裡,函數回傳`undefined`。注意,在`if/else`語法之後沒有自動插入!

@@ -3068,7 +3068,7 @@ console.log(member.name)
答案

-#### 答案: B +#### 答案:B 我們可以將class設置為等於其他class/函數建構函數。在這種情況下,我們將`Person`設置為`AnotherPerson`。這個建構函數的名字是`Sarah`,所以新的`Person`實例`member`上的name屬性是`Sarah`。 @@ -3097,12 +3097,12 @@ console.log(Object.keys(info))

答案

-#### 答案: D +#### 答案:D -`Symbol`類型是不可枚舉的。 `Object.keys`函數回傳物件上的所有可枚舉的鍵屬性。 `Symbol`類型是不可見的,並回傳一個空陣列。記錄整個物件時,所有屬性都是可見的,甚至是不可枚舉的屬性。 +`Symbol`類型是不可枚舉的。`Object.keys`函數回傳物件上的所有可枚舉的鍵屬性。`Symbol`類型是不可見的,並回傳一個空陣列。記錄整個物件時,所有屬性都是可見的,甚至是不可枚舉的屬性。 -這是`Symbol`的眾多特性之一:除了表示完全唯一的值(防止物件意外名稱衝突,例如當使用2個想要向同一物件添加屬性的庫時),您還可以`隱藏`這種方式物件的屬性(儘管不完全。你仍然可以使用`Object.getOwnPropertySymbols()`函數存取`Symbol`。 +這是`Symbol`的眾多特性之一:除了表示完全唯一的值(防止物件意外名稱衝突,例如當使用 2 個想要向同一物件添加屬性的庫時),您還可以`隱藏`這種方式物件的屬性(儘管不完全。你仍然可以使用`Object.getOwnPropertySymbols()`函數存取`Symbol`。

@@ -3129,7 +3129,7 @@ console.log(getUser(user))
答案

-#### 答案: A +#### 答案:A `getList`函數接收一個陣列作為其參數。在`getList`函數的括號之間,我們立即解構這個陣列。您可以這樣表達: @@ -3138,7 +3138,7 @@ console.log(getUser(user)) 使用剩餘的參數`... y`,我們將所有剩餘參數放在一個陣列中。在這種情況下,其餘的參數是`2`,`3`和`4`。 `y`的值是一個陣列,包含所有其餘參數。在這種情況下,`x`的值等於`1`,所以當我們輸出`[x,y]`時,會輸出`[1,[2,3,4]]`。 - `getUser`函數接收一個物件。對於箭頭函數,如果只回傳一個值,我們不必編寫大括號。但是,如果您想從一個箭頭函數回傳一個物件,您必須在小括號之間編寫它,否則不會回傳任何值!下面的函數將回傳一個物件: + `getUser`函數接收一個物件。對於箭頭函數,如果只回傳一個值,我們不必編寫大括號。但是,如果您想從一個箭頭函數回傳一個物件,您必須在小括號之間編寫它,否則不會回傳任何值!下面的函數將回傳一個物件: ```const getUser = user => ({ name: user.name, age: user.age })``` @@ -3164,14 +3164,14 @@ console.log(name())

答案

-#### 答案: C +#### 答案:C 變數`name`保存字串的值,該字串不是函數,因此無法呼叫。 -當值不是預期類型時,會拋出`TypeErrors`。 JavaScript期望`name`是一個函數,因為我們試圖呼叫它。但它是一個字串,因此拋出`TypeError`:`name is not a function` +當值不是預期類型時,會拋出`TypeErrors`。JavaScript 期望`name`是一個函數,因為我們試圖呼叫它。但它是一個字串,因此拋出`TypeError`:`name is not a function` -當你編寫了一些非有效的JavaScript時,會拋出語法錯誤,例如當你把`return`這個詞寫成`retrun`時。 -當JavaScript無法找到您嘗試存取的值的引用時,拋出`ReferenceErrors`。 +當你編寫了一些非有效的 JavaScript 時,會拋出語法錯誤,例如當你把`return`這個詞寫成`retrun`時。 +當 JavaScript 無法找到您嘗試存取的值的引用時,拋出`ReferenceErrors`。

@@ -3180,7 +3180,7 @@ console.log(name()) ###### 100. 將會輸出什麽內容? ```javascript -// 🎉✨ 耶! 我終於翻到100題了! 噢耶! ✨🎉 +// 🎉✨ 耶!我終於翻到 100 題了!噢耶!✨🎉 const output = `${[] && 'Im'}possible! You should${'' && `n't`} see a therapist after so much JavaScript lol` @@ -3194,12 +3194,12 @@ You should${'' && `n't`} see a therapist after so much JavaScript lol`
答案

-#### 答案: B +#### 答案:B `[]`是一個真值。使用`&&`運算子,如果左側值是真值,則回傳右側值。在這種情況下,左側值`[]`是一個真值,所以回傳`Im`。 -`""`是一個假值。如果左側值是假的,則不回傳任何內容。 `n't`不會被退回。 +`""`是一個假值。如果左側值是假的,則不回傳任何內容。`n't`不會被退回。

@@ -3223,15 +3223,15 @@ console.log(one, two, three)
答案

-#### 答案: C +#### 答案:C 使用`||`運算子,我們可以得到第一個真值。如果所有值都是假值,則得到最後一個值。 -`(false || {} || null)`:空物件`{}`是一個真值。這是第一個(也是唯一的)真值,它將被得到。 `one`等於`{}`。 +`(false || {} || null)`:空物件`{}`是一個真值。這是第一個(也是唯一的)真值,它將被得到。`one`等於`{}`。 -`(null || false ||“”)`:所有值都是假值。這意味著得到傳遞的值`""`。 `two`等於`""`。 +`(null || false ||“”)`:所有值都是假值。這意味著得到傳遞的值`""`。`two`等於`""`。 -`([] || 0 ||“”)`:空陣列`[]`是一個真值。這是第一個得到的真值。 `three`等於`[]`。 +`([] || 0 ||“”)`:空陣列`[]`是一個真值。這是第一個得到的真值。`three`等於`[]`。

@@ -3264,14 +3264,14 @@ secondFunction()
答案

-#### 答案: D +#### 答案:D -有了promise,我們通常會說:當我想要呼叫某個函數,但是由於它可能需要一段時間,因此暫時將它放在一邊。只有當某個值被resolved/rejected,並且執行序為空時才使用這個值。 +有了 promise,我們通常會說:當我想要呼叫某個函數,但是由於它可能需要一段時間,因此暫時將它放在一邊。只有當某個值被 resolved/rejected,並且執行序為空時才使用這個值。 -我們可以在`async`函數中通過`.then`和`await`關鍵字獲得該值。儘管我們可以通過`.then`和`await`獲得promise的值,但是它們的運作方式不同。 +我們可以在`async`函數中通過`.then`和`await`關鍵字獲得該值。儘管我們可以通過`.then`和`await`獲得 promise 的值,但是它們的運作方式不同。 -在`firstFunction`中,當執行到`myPromise`函數時我們將其放在一邊,即promise進入微任務佇列,其他後面的程式(`console.log('second')`)照常執行,因此`second `被輸出,`firstFunction`函數到此執行完畢,執行序中任務佇列被清空,此時開始執行微任務佇列中的任務,`I have resolved`被輸出。 +在`firstFunction`中,當執行到`myPromise`函數時我們將其放在一邊,即 promise 進入微任務佇列,其他後面的程式(`console.log('second')`)照常執行,因此`second `被輸出,`firstFunction`函數到此執行完畢,執行序中任務佇列被清空,此時開始執行微任務佇列中的任務,`I have resolved`被輸出。 在`secondFunction`函數中,我們通過`await`關鍵字,暫停了後面程式的執行,直到異步函數的值被解析才開始後面程式的執行。這意味著,它會等著直到 `myPromise` 以值`I have resolved`被`resolve`之後,下一行`second`才開始執行。 @@ -3302,15 +3302,15 @@ for (let item of set) {

答案

-#### 答案: C +#### 答案:C -“+”運算子不僅用於相加數字,還可以使用它來連接字串。每當JavaScript引擎發現一個或多個值不是數字時,就會將數字強制為字串。 +“+”運算子不僅用於相加數字,還可以使用它來連接字串。每當 JavaScript 引擎發現一個或多個值不是數字時,就會將數字強制為字串。 -第一個是數字1。 1 + 2得到數字3。 +第一個是數字 1。1 + 2 得到數字 3。 -但是,第二個是字串“Lydia”。 “Lydia”是一個字串,2是一個數字:2被強制轉換為字串。 “Lydia”和“2”被連接起來,產生字串“Lydia2”。 +但是,第二個是字串“Lydia”。 “Lydia”是一個字串,2 是一個數字:2 被強制轉換為字串。 “Lydia”和“2”被連接起來,產生字串“Lydia2”。 -`{name:“ Lydia”}`是一個物件。數字和物件都不是字串,因此將二者都字串化。每當我們對正規式物件進行字串化時,它就會變成`[Object object]`。與“2”串聯的“ [Object object]”成為“[Object object]2”。 +`{name:“Lydia”}`是一個物件。數字和物件都不是字串,因此將二者都字串化。每當我們對正規式物件進行字串化時,它就會變成`[Object object]`。與“2”串聯的“ [Object object]”成為“[Object object]2”。

@@ -3330,11 +3330,11 @@ Promise.resolve(5)
答案

-#### 答案: C +#### 答案:C -我們可以將我們想要的任何類型的值傳遞`Promise.resolve`,無論是否`promise`。該函數本身回傳帶有已解析值的`Promise` (``)。如果您傳遞正規式函數,它將是具有正規式值的已解決`promise`。如果你通過了promise,它將是一個已經resolved的且帶有傳的值的promise。 +我們可以將我們想要的任何類型的值傳遞`Promise.resolve`,無論是否`promise`。該函數本身回傳帶有已解析值的`Promise` (``)。如果您傳遞正規式函數,它將是具有正規式值的已解決`promise`。如果你通過了 promise,它將是一個已經 resolved 的且帶有傳的值的 promise。 -上述情況,我們傳了數字5,因此回傳一個resolved狀態的promise,resolve值為`5` +上述情況,我們傳了數字 5,因此回傳一個 resolved 狀態的 promise,resolve 值為`5`

@@ -3364,7 +3364,7 @@ compareMembers(person)
答案

-#### 答案: B +#### 答案:B 物件通過參考位址傳遞。當我們檢查物件的嚴格相等性(===)時,我們正在比較它們的參考位址。 @@ -3372,7 +3372,7 @@ compareMembers(person) 這意味著兩個值都引用緩存中的同一位置,因此它們是相等的。 -執行“ else”語句中的代碼塊,並記錄`They are the same!` 。 +執行“else”語句中的代碼塊,並記錄`They are the same!`。

@@ -3403,14 +3403,14 @@ console.log(colorConfig.colors[1])
答案

-#### 答案: D +#### 答案:D -在JavaScript中,我們有兩種存取物件屬性的方法:括號表示法或點表示法。在此範例中,我們使用點表示法(`colorConfig.colors`)代替括號表示法(`colorConfig [“ colors”]`)。 +在 JavaScript 中,我們有兩種存取物件屬性的方法:括號表示法或點表示法。在此範例中,我們使用點表示法(`colorConfig.colors`)代替括號表示法(`colorConfig [“colors”]`)。 -使用點表示法,JavaScript會嘗試使用該確切名稱在物件上查找屬性。在此範例中,JavaScript嘗試在colorConfig物件上找到名為colors的屬性。沒有名為“colors”的屬性,因此得到“undefined”。 +使用點表示法,JavaScript 會嘗試使用該確切名稱在物件上查找屬性。在此範例中,JavaScript 嘗試在 colorConfig 物件上找到名為 colors 的屬性。沒有名為“colors”的屬性,因此得到“undefined”。 然後,我們嘗試使用`[1]`存取第一個元素的值。我們無法對未定義的值執行此操作,因此會拋出`Cannot read property '1' of undefined`。 -JavaScript解釋(或取消裝箱)語句。當我們使用中括號表示法時,它會看到第一個左方括號`[`並一直進行下去,直到找到右方括號`]`。只有這樣,它才會評估該語句。如果我們使用了colorConfig [colors [1]],它將得到colorConfig物件上red屬性的值。 +JavaScript 解釋(或取消裝箱)語句。當我們使用中括號表示法時,它會看到第一個左方括號`[`並一直進行下去,直到找到右方括號`]`。只有這樣,它才會評估該語句。如果我們使用了 colorConfig [colors [1]],它將得到 colorConfig 物件上 red 屬性的值。

@@ -3429,15 +3429,15 @@ console.log('❤️' === '❤️')
答案

-#### 答案: A +#### 答案:A -在內部,表情符號是unicode。 heat表情符號的unicode是`“ U + 2764 U + FE0F”`。對於相同的表情符號,它們總是相同的,因此我們將兩個相等的字串相互比較,這將回傳true。 +在內部,表情符號是 unicode。heat 表情符號的 unicode 是`“U + 2764 U + FE0F”`。對於相同的表情符號,它們總是相同的,因此我們將兩個相等的字串相互比較,這將回傳 true。

--- -###### 108. 哪些函數修改了原本的陣列? +###### 108. 哪些函數修改了原本的陣列? ```javascript @@ -3459,9 +3459,9 @@ emojis.splice(1, 2, '✨')
答案

-#### 答案: D +#### 答案:D -使用`splice`方法,我們透過刪除,取代或增加元素來修改原始陣列。在這種情況下,我們從索引1中刪除了2個元素(我們刪除了`'🥑'`和`'😍'`),同時增加了✨emoji表情。 +使用`splice`方法,我們透過刪除,取代或增加元素來修改原始陣列。在這種情況下,我們從索引 1 中刪除了 2 個元素(我們刪除了`'🥑'`和`'😍'`),同時增加了✨emoji 表情。 `map`,`filter`和`slice`回傳一個新陣列,`find`回傳一個元素,而`reduce`回傳一個計算過的值。 @@ -3488,11 +3488,11 @@ console.log(food)

答案

-#### 答案: A +#### 答案:A -我們將`info`物件上的`favoriteFood`屬性的值設置為披薩表情符號“🍕”的字串。字串是原始內容類型。在JavaScript中,原始內容類型通過值起作用 +我們將`info`物件上的`favoriteFood`屬性的值設置為披薩表情符號“🍕”的字串。字串是原始內容類型。在 JavaScript 中,原始內容類型通過值起作用 -在這種情況下,我們將`info`物件上的`favoriteFood`屬性的值設置為等於`food`陣列中的第一個元素的值,字串為披薩表情符號(`'🍕'` )。字串是原始內容類型,並且通過值進行交換,我們更改`info`物件上`favoriteFood`屬性的值。 food陣列沒有改變,因為favoriteFood的值只是該陣列中第一個元素的值的複製,並且與該元素上的元素沒有相同的緩存引用食物`[0]`。當我們記錄食物時,它仍然是原始陣列`['🍕','🍫','🥑','🍔']`。 +在這種情況下,我們將`info`物件上的`favoriteFood`屬性的值設置為等於`food`陣列中的第一個元素的值,字串為披薩表情符號(`'🍕'`)。字串是原始內容類型,並且通過值進行交換,我們更改`info`物件上`favoriteFood`屬性的值。food 陣列沒有改變,因為 favoriteFood 的值只是該陣列中第一個元素的值的複製,並且與該元素上的元素沒有相同的緩存引用食物`[0]`。當我們記錄食物時,它仍然是原始陣列`['🍕','🍫','🥑','🍔']`。

@@ -3512,20 +3512,20 @@ JSON.parse()
答案

-#### 答案: A +#### 答案:A -使用`JSON.parse()`函數,我們可以將JSON字串解析為JavaScript值。 +使用`JSON.parse()`函數,我們可以將 JSON 字串解析為 JavaScript 值。 ```javascript -// 將數字字串化為有效的JSON,然後將JSON字串解析為JavaScript值: +// 將數字字串化為有效的 JSON,然後將 JSON 字串解析為 JavaScript 值: const jsonNumber = JSON.stringify(4) // '4' JSON.parse(jsonNumber) // 4 -// 將陣列值字串化為有效的JSON,然後將JSON字串解析為JavaScript值: +// 將陣列值字串化為有效的 JSON,然後將 JSON 字串解析為 JavaScript 值: const jsonArray = JSON.stringify([1, 2, 3]) // '[1, 2, 3]' JSON.parse(jsonArray) // [1, 2, 3] -// 將物件字串化為有效的JSON,然後將JSON字串解析為JavaScript值: +// 將物件字串化為有效的 JSON,然後將 JSON 字串解析為 JavaScript 值: const jsonArray = JSON.stringify({ name: "Lydia" }) // '{"name":"Lydia"}' JSON.parse(jsonArray) // { name: 'Lydia' } ``` @@ -3554,13 +3554,13 @@ getName()

答案

-#### 答案: D +#### 答案:D -每個函數都有其自己的執行上下文。 `getName`函數首先在其自身的上下文(範圍)內查找,以查看其是否包含我們嘗試存取的變數`name`。上述情況,`getName`函數包含其自己的`name`變數:我們用`let`關鍵字和`Sarah`的值定義變數`name`。 +每個函數都有其自己的執行上下文。`getName`函數首先在其自身的上下文(範圍)內查找,以查看其是否包含我們嘗試存取的變數`name`。上述情況,`getName`函數包含其自己的`name`變數:我們用`let`關鍵字和`Sarah`的值定義變數`name`。 -帶有`let`關鍵字(和`const`)的變數被提升,但是與`var`不同,它不會被***初始化***。在我們定義(初始化)它們之前,無法存取它們。這稱為“暫時性死區”。當我們嘗試在定義變數之前存取變數時,JavaScript會拋出`ReferenceError: Cannot access 'name' before initialization`。 +帶有`let`關鍵字(和`const`)的變數被提升,但是與`var`不同,它不會被***初始化***。在我們定義(初始化)它們之前,無法存取它們。這稱為“暫時性死區”。當我們嘗試在定義變數之前存取變數時,JavaScript 會拋出`ReferenceError: Cannot access 'name' before initialization`。 -如果我們不在`getName`函數中定義`name`變數,則javascript引擎會查看原型鏈。會找到其外部作用域有一個名為`name`的變數,其值為`Lydia`。在這種情況下,它將輸出`Lydia`: +如果我們不在`getName`函數中定義`name`變數,則 javascript 引擎會查看原型鏈。會找到其外部作用域有一個名為`name`的變數,其值為`Lydia`。在這種情況下,它將輸出`Lydia`: ```javascript let name = 'Lydia' @@ -3602,18 +3602,18 @@ console.log(two.next().value)

答案

-#### 答案: C +#### 答案:C -透過`yield` 關鍵字, 我們在`Generator` 函數裡執行`yield`語法. 透過`yield*` 關鍵字, 我們可以在一個`Generator` 函數裡面執行(`yield`語法)另一個`Generator ` 函數, 或可遍歷的物件(如陣列). +透過`yield` 關鍵字,我們在`Generator` 函數裡執行`yield`語法。透過`yield*` 關鍵字,我們可以在一個`Generator` 函數裡面執行(`yield`語法)另一個`Generator ` 函數,或可遍歷的物件 (如陣列). -在函數 `generatorOne` 中, 我們透過 `yield` 關鍵字 yield 了一個完整的陣列 `['a', 'b', 'c']`。函數`one`透過`next`方法回傳的物件的`value` 屬性的值 (`one.next().value`) 等價於陣列 `['a', 'b', 'c']`. +在函數 `generatorOne` 中,我們透過 `yield` 關鍵字 yield 了一個完整的陣列 `['a', 'b', 'c']`。函數`one`透過`next`方法回傳的物件的`value` 屬性的值 (`one.next().value`) 等價於陣列 `['a', 'b', 'c']`. ```javascript console.log(one.next().value) // ['a', 'b', 'c'] console.log(one.next().value) // undefined ``` -在函數 `generatorTwo` 中, 我們使用 `yield*` 關鍵字。就相當於函數`two`第一個`yield`的值, 等價於在迭代器中第一個 `yield` 的值。陣列`['a', 'b', 'c']`就是這個迭代器. 第一個`yield` 的值就是`a`, 所以我們第一次呼叫`two.next().value`時, 就回傳`a`。 +在函數 `generatorTwo` 中,我們使用 `yield*` 關鍵字。就相當於函數`two`第一個`yield`的值,等價於在迭代器中第一個 `yield` 的值。陣列`['a', 'b', 'c']`就是這個迭代器。第一個`yield` 的值就是`a`, 所以我們第一次呼叫`two.next().value`時,就回傳`a`。 ```javascript console.log(two.next().value) // 'a' @@ -3641,9 +3641,9 @@ console.log(`${(x => x)('I love')} to program`)

答案

-#### 答案: A +#### 答案:A -帶有模板字面量的表達式優先被執行。相當於字串會包含表達式,這個立即執行函數`(x => x)('I love')` 回傳的值. 我們向箭頭函數`x => x` 傳遞`'I love'` 作為參數。 `x` 等價於回傳的 `'I love'`。這就是結果 `I love to program`。 +帶有模板字面量的表達式優先被執行。相當於字串會包含表達式,這個立即執行函數`(x => x)('I love')` 回傳的值。我們向箭頭函數`x => x` 傳遞`'I love'` 作為參數。 `x` 等價於回傳的 `'I love'`。這就是結果 `I love to program`。

@@ -3669,9 +3669,9 @@ config = null
答案

-#### 答案: C +#### 答案:C -一般情況下當我們將物件賦值為 `null`, 那些物件會被進行 _垃圾回收(garbage collected)_ 因為已經沒有對這些物件的引用了。然而,`setInterval`的參數是一個箭頭函數(所以上下文綁定到物件 `config` 了),函數仍然保留著對 `config`的引用。只要存在引用,物件就不會被垃圾回收。因為沒有被垃圾回收,`setInterval` 的每1000ms (1s)會被呼叫一次。 +一般情況下當我們將物件賦值為 `null`, 那些物件會被進行 _垃圾回收(garbage collected)_ 因為已經沒有對這些物件的引用了。然而,`setInterval`的參數是一個箭頭函數(所以上下文綁定到物件 `config` 了),函數仍然保留著對 `config`的引用。只要存在引用,物件就不會被垃圾回收。因為沒有被垃圾回收,`setInterval` 的每 1000ms (1s) 會被呼叫一次。

@@ -3701,9 +3701,9 @@ myMap.get(() => 'greeting')
答案

-#### 答案: B +#### 答案:B -當透過 `set` 函數增加一個鍵值對,一個傳遞給 `set`函數的參數將會是鍵名,第二個參數將會是值。在這個case裡,鍵名為 _函數_ `() => 'greeting'`,值為`'Hello world'`。 `myMap` 現在就是 `{ () => 'greeting' => 'Hello world!' }`。 +當透過 `set` 函數增加一個鍵值對,一個傳遞給 `set`函數的參數將會是鍵名,第二個參數將會是值。在這個 case 裡,鍵名為 _函數_ `() => 'greeting'`,值為`'Hello world'`。 `myMap` 現在就是 `{ () => 'greeting' => 'Hello world!' }`。 1 是錯的,因為鍵名不是 `'greeting'` 而是 `() => 'greeting'`。 3 是錯的,因為我們給`get` 函數傳遞了一個新的函數。物件受 _引用_ 影響。函數也是物件,因此兩個函數嚴格上並不等價,儘管他們相同:他們有兩個不同的緩存引用地址。 @@ -3740,13 +3740,13 @@ console.log(person)

答案

-#### 答案: C +#### 答案:C 函數 `changeAge` 和函數 `changeAgeAndName` 有著不同的參數,定義一個 _新_ 生成的物件 `{ ...person }`。這個物件有著所有 `person` 物件 中 k/v 值的副本。 -首項, 我們呼叫 `changeAge` 函數並傳遞 `person` 物件作為它的參數。這個函數對 `age` 屬性進行加一操作。 `person` 現在是 `{ name: "Lydia", age: 22 }`。 +首項,我們呼叫 `changeAge` 函數並傳遞 `person` 物件作為它的參數。這個函數對 `age` 屬性進行加一操作。`person` 現在是 `{ name: "Lydia", age: 22 }`。 -然後,我們呼叫函數 `changeAgeAndName` ,然而我們沒有傳遞參數。取而代之,`x` 的值等價 _new_ 生成的物件: `{ ...person }`。因為它是一個新生成的物件,它並不會對物件 `person` 造成任何副作用。 `person` 仍然等價於 `{ name: "Lydia", age: 22 }`。 +然後,我們呼叫函數 `changeAgeAndName`,然而我們沒有傳遞參數。取而代之,`x` 的值等價 _new_ 生成的物件:`{ ...person }`。因為它是一個新生成的物件,它並不會對物件 `person` 造成任何副作用。`person` 仍然等價於 `{ name: "Lydia", age: 22 }`。

@@ -3768,9 +3768,9 @@ function sumValues(x, y, z) {
答案

-#### 答案: C +#### 答案:C -通過展開語法 `...`,我們可以 _展開_ 單個可迭代的元素。函數 `sumValues` function 接收三個參數: `x`, `y` 和 `z`。 `...[1, 2, 3]` 的執行結果為 `1, 2, 3`,將會傳遞給函數 `sumValues`。 +通過展開語法 `...`,我們可以 _展開_ 單個可迭代的元素。函數 `sumValues` function 接收三個參數:`x`, `y` 和 `z`。`...[1, 2, 3]` 的執行結果為 `1, 2, 3`,將會傳遞給函數 `sumValues`。

@@ -3793,9 +3793,9 @@ console.log(list[(num += 1)]);
答案

-#### 答案: B +#### 答案:B -透過 `+=` 運算子,我們對變數 `num` 進行加 `1` 操作。 `num` 有初始值 `1`,因此 `1 + 1` 的執行結果為 `2`。陣列 `list` 的第二項為 🥰,`console.log(list[2])` 輸出 🥰. +透過 `+=` 運算子,我們對變數 `num` 進行加 `1` 操作。`num` 有初始值 `1`,因此 `1 + 1` 的執行結果為 `2`。陣列 `list` 的第二項為 🥰,`console.log(list[2])` 輸出 🥰.

@@ -3830,13 +3830,13 @@ console.log(member.getLastName?.());
答案

-#### 答案: B +#### 答案:B -通過ES10 或TS3.7+[可選鏈運算子`?.`](https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Operators/%E5%8F%AF% E9%80%89%E9%93%BE),我們不再需要顯式檢測更深層的嵌套值是否有效。如果我們嘗試存取 `undefined` 或 `null` 的值 (_nullish_),表達將會短路並回傳 `undefined`. +通過 ES10 或 TS3.7+[可選鏈運算子`?.`](https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Operators/%E5%8F%AF% E9%80%89%E9%93%BE),我們不再需要顯式檢測更深層的嵌套值是否有效。如果我們嘗試存取 `undefined` 或 `null` 的值 (_nullish_),表達將會短路並回傳 `undefined`. -`person.pet?.name`: `person` 有一個名為 `pet` 的屬性: `person.pet` 不是 nullish。它有個名為 `name` 的屬性,並回傳字串 `Mara`。 -`person.pet?.family?.name`: `person` 有一個名為`pet` 的屬性: `person.pet` 不是nullish. `pet` _並沒有_ 一個名為`family` 的屬性, ` person.pet.family` 是nullish。表達式回傳 `undefined`。 -`person.getFullName?.()`: `person` 有一個名為 `getFullName` 的屬性: `person.getFullName()` 不是 nullish 並可以被呼叫,回傳字串 `Lydia Hallie`。 +`person.pet?.name`:`person` 有一個名為 `pet` 的屬性:`person.pet` 不是 nullish。它有個名為 `name` 的屬性,並回傳字串 `Mara`。 +`person.pet?.family?.name`:`person` 有一個名為`pet` 的屬性:`person.pet` 不是 nullish. `pet` _並沒有_ 一個名為`family` 的屬性,` person.pet.family` 是 nullish。表達式回傳 `undefined`。 +`person.getFullName?.()`:`person` 有一個名為 `getFullName` 的屬性:`person.getFullName()` 不是 nullish 並可以被呼叫,回傳字串 `Lydia Hallie`。 `member.getLastName?.()`: `member` is not defined: `member.getLastName()` is nullish. The expression returns `undefined`.

@@ -3863,9 +3863,9 @@ if (groceries.indexOf("banana")) {
答案

-#### 答案: B +#### 答案:B -我們傳遞了一個狀態 `groceries.indexOf("banana")` 給if語法。 `groceries.indexOf("banana")` 回傳 `0`, 一個 falsy 的值。因為if語法的狀態為 falsy,`else` 塊區內的代碼執行,並且 `We don't have to buy bananas!` 被輸出. +我們傳遞了一個狀態 `groceries.indexOf("banana")` 給 if 語法。`groceries.indexOf("banana")` 回傳 `0`,一個 falsy 的值。因為 if 語法的狀態為 falsy,`else` 塊區內的代碼執行,並且 `We don't have to buy bananas!` 被輸出。

@@ -3892,9 +3892,9 @@ console.log(config.language);
答案

-#### 答案: D +#### 答案:D -函數 `language` 是一個 `setter`。 Setters 並不保存一個實際值,它們的使命在於 _修改_ 屬性。當呼叫函數 `setter`, 回傳 `undefined`。 +函數 `language` 是一個 `setter`。Setters 並不保存一個實際值,它們的使命在於 _修改_ 屬性。當呼叫函數 `setter`,回傳 `undefined`。

@@ -3918,9 +3918,9 @@ console.log(!typeof name === "string");
答案

-#### 答案: C +#### 答案:C -`typeof name` 回傳 `"string"`。字串 `"string"` 是一個 truthy 的值,因此 `!typeof name` 回傳一個布林值 `false`。 `false === "object"` 和 `false === "string"` 都回傳 `false`。 +`typeof name` 回傳 `"string"`。字串 `"string"` 是一個 truthy 的值,因此 `!typeof name` 回傳一個布林值 `false`。`false === "object"` 和 `false === "string"` 都回傳 `false`。 (如果我們想檢測一個值的類型,我們應該用 `!==` 而不是 `!typeof`) @@ -3947,7 +3947,7 @@ add(4)(5)(6);

答案

-#### 答案: A +#### 答案:A 函數 `add` 是一個回傳 回傳箭頭函數的箭頭函數 的箭頭函數(still with me?)。第一個函數接收一個值為 `4` 的參數 `x`。我們呼叫第二個函數,它接收一個值為 `5` 的參數 `y`。然後我們呼叫第三個函數,它接收一個值為 `6` 的參數 `z`。當我們嘗試在最後一個箭頭函數中獲取 `x`, `y` 和 `z` 的值,JS 引擎根據作用域鏈去找 `x` 和 `y` 的值。得到 `4` `5` `6`. @@ -3980,9 +3980,9 @@ async function* range(start, end) {

答案

-#### 答案: C +#### 答案:C -我們給 函數range 傳遞: `Promise{1}`, `Promise{2}`, `Promise{3}`,Generator 函數 `range` 回傳一個全是 async object promise 陣列。我們將 async object 賦值給變數 `gen`,之後我們使用`for await ... of` 進行循環遍歷。我們將回傳的 Promise 實例賦值給 `item`: 第一個回傳 `Promise{1}`, 第二個回傳 `Promise{2}`,之後是 `Promise{3}`。因為我們正 _awaiting_ `item` 的值,resolved 狀態的 promise,promise陣列的resolved _值_ 以此為: `1`,`2`,`3`. +我們給 函數 range 傳遞:`Promise{1}`, `Promise{2}`, `Promise{3}`,Generator 函數 `range` 回傳一個全是 async object promise 陣列。我們將 async object 賦值給變數 `gen`,之後我們使用`for await ... of` 進行循環遍歷。我們將回傳的 Promise 實例賦值給 `item`:第一個回傳 `Promise{1}`,第二個回傳 `Promise{2}`,之後是 `Promise{3}`。因為我們正 _awaiting_ `item` 的值,resolved 狀態的 promise,promise 陣列的 resolved _值_ 以此為:`1`,`2`,`3`.

@@ -4006,9 +4006,9 @@ myFunc(1, 2, 3);
答案

-#### 答案: D +#### 答案:D -`myFunc` 預期接收一個包含 `x`, `y` 和 `z` 屬性的物件作為它的參數。因為我們僅僅傳遞三個單獨的數字值(1, 2, 3) 而不是一個含有`x`, `y` 和`z` 屬性的物件({x: 1, y: 2, z: 3}) , `x`, `y` 和`z` 有著各自的預設值`undefined`. +`myFunc` 預期接收一個包含 `x`, `y` 和 `z` 屬性的物件作為它的參數。因為我們僅僅傳遞三個單獨的數字值 (1, 2, 3) 而不是一個含有`x`, `y` 和`z` 屬性的物件 ({x: 1, y: 2, z: 3}) ,`x`, `y` 和`z` 有著各自的預設值`undefined`.

@@ -4042,7 +4042,7 @@ console.log(getFine(130, 300))
答案

-#### 答案: B +#### 答案:B 通過函數 `Intl.NumberFormat`,我們可以格式化任意區域的數字值。我們對數字值 `130` 進行 `mile-per-hour` 作為 `unit` 的 `en-US` 區域 格式化,結果為 `130 mph`。對數字值 `300` 進行 `USD` 作為 `currency` 的 `en-US` 區域格式化,結果為 `$300.00`. @@ -4068,7 +4068,7 @@ console.log(spookyItems);

答案

-#### 答案: B +#### 答案:B 通過解構物件們,我們可以從右手邊的物件中拆出值,並且將拆出的值分配給左手邊物件同名的屬性。在這種情況下,我們將值 "💀" 分配給 `spookyItems[3]`。相當於我們正在篡改陣列 `spookyItems`,我們給它添加了值 "💀"。當輸出 `spookyItems` 時,結果為 `["👻", "🎃", "🕸", "💀"]`。 @@ -4098,11 +4098,11 @@ console.log(isNaN(age));

答案

-#### 答案: C +#### 答案:C -通過函數 `Number.isNaN`,你可以檢測你傳遞的值是否為 _數字值_ 並且是否等於 `NaN`。 `name` 不是一個數字值,因此 `Number.isNaN(name)` 回傳 `false`。 `age` 是一個數字值,但它不等於 `NaN`,因此 `Number.isNaN(age)` 回傳 `false`. +通過函數 `Number.isNaN`,你可以檢測你傳遞的值是否為 _數字值_ 並且是否等於 `NaN`。`name` 不是一個數字值,因此 `Number.isNaN(name)` 回傳 `false`。`age` 是一個數字值,但它不等於 `NaN`,因此 `Number.isNaN(age)` 回傳 `false`. -通過函數 `isNaN`, 你可以檢測你傳遞的值是否一個 number。 `name` 不是一個 `number`,因此 `isNaN(name)` 回傳 `true`. `age` 是一個 `number` 因此 `isNaN(age)` 回傳 `false`. +通過函數 `isNaN`,你可以檢測你傳遞的值是否一個 number。`name` 不是一個 `number`,因此 `isNaN(name)` 回傳 `true`. `age` 是一個 `number` 因此 `isNaN(age)` 回傳 `false`.

@@ -4130,9 +4130,9 @@ getInfo();
答案

-#### 答案: D +#### 答案:D -通過 `const` 關鍵字定義的變數在被初始化之前不可被引用:這被稱之為 _暫時性死區_。在函數 `getInfo` 中, 變數 `randomValue` 定義在`getInfo` 的作用域的此法環境中。在想要對`typeof randomValue` 進行log之前,變數`randomValue` 仍未被初始化: 錯誤`ReferenceError` 被拋出! JS引擎並不會根據作用域鍊網上尋找該變數,因為我們已經在`getInfo`函數中定義了`randomValue` 變數。 +通過 `const` 關鍵字定義的變數在被初始化之前不可被引用:這被稱之為 _暫時性死區_。在函數 `getInfo` 中,變數 `randomValue` 定義在`getInfo` 的作用域的此法環境中。在想要對`typeof randomValue` 進行 log 之前,變數`randomValue` 仍未被初始化:錯誤`ReferenceError` 被拋出!JS 引擎並不會根據作用域鍊網上尋找該變數,因為我們已經在`getInfo`函數中定義了`randomValue` 變數。

@@ -4163,9 +4163,9 @@ const myPromise = Promise.resolve("Woah some cool data");
答案

-#### 答案: C +#### 答案:C -在 `try` 塊區,我們輸出 `myPromise` 變數的 awaited 值: `"Woah some cool data"`。因為`try` 塊區沒有錯誤拋出,`catch` 塊區的代碼並不執行。 `finally` 塊區的代碼 _總是_ 執行,`"Oh finally!"` 被輸出。 +在 `try` 塊區,我們輸出 `myPromise` 變數的 awaited 值:`"Woah some cool data"`。因為`try` 塊區沒有錯誤拋出,`catch` 塊區的代碼並不執行。`finally` 塊區的代碼 _總是_ 執行,`"Oh finally!"` 被輸出。

@@ -4188,9 +4188,9 @@ console.log(emojis.flat(1));
答案

-#### 答案: B +#### 答案:B -通過函數 `flat`, 我們可以建立一個新的, 已被扁平化的陣列。被扁平化的深度取決於我們傳遞的值。在這個case裡,我們傳遞了值 `1` (並不必要,這是預設值),相當於只有第一層的陣列才會被連接。即這個 case 裡的 `['🥑']` and `['✨', '✨', ['🍕', '🍕']]`。連接這兩個陣列得到結果 `['🥑', '✨', '✨', ['🍕', '🍕']]`. +通過函數 `flat`,我們可以建立一個新的,已被扁平化的陣列。被扁平化的深度取決於我們傳遞的值。在這個 case 裡,我們傳遞了值 `1` (並不必要,這是預設值),相當於只有第一層的陣列才會被連接。即這個 case 裡的 `['🥑']` and `['✨', '✨', ['🍕', '🍕']]`。連接這兩個陣列得到結果 `['🥑', '✨', '✨', ['🍕', '🍕']]`.

@@ -4228,15 +4228,15 @@ console.log(counterOne.count);
答案

-#### 答案: D +#### 答案:D -`counterOne` 是類 `Counter` 的一個實例。類 Counter 包含一個`count` 屬性在它的建構函數里, 和一個 `increment` 函數。首先,我們通過 `counterOne.increment()` 呼叫函數 `increment` 兩次。現在, `counterOne.count` 為 `2`. +`counterOne` 是類 `Counter` 的一個實例。類 Counter 包含一個`count` 屬性在它的建構函數里,和一個 `increment` 函數。首先,我們通過 `counterOne.increment()` 呼叫函數 `increment` 兩次。現在,`counterOne.count` 為 `2`. 然後,我們建立一個新的變數 `counterTwo` 並將 `counterOne` 的引用地址賦值給它。因為物件受引用地址的影響,我們剛剛建立了一個新的物件,其引用地址和 `counterOne` 的等價。因此它們指向同一塊緩存地址,任何對其的副作用都會影響 `counterTwo`。現在 `counterTwo.count` 為 `2`。 -我們呼叫 `counterTwo.increment()` 將 `count` 的值設為 `3`。然後,我們輸出 `counterOne` 裡的count,結果為 `3`。 +我們呼叫 `counterTwo.increment()` 將 `count` 的值設為 `3`。然後,我們輸出 `counterOne` 裡的 count,結果為 `3`。 @@ -4275,13 +4275,13 @@ funcTwo();

答案

-#### 答案: D +#### 答案:D -首先,我們呼叫 `funcOne`。在函數 `funcOne` 的第一行,我們呼叫`myPromise` promise _異步操作_。當JS引擎在忙於執行 promise,它繼續執行函數 `funcOne`。下一行 _異步操作_ `setTimeout`,其回呼函數被 Web API 呼叫。 (詳情請參考我關於event loop的文章.) +首先,我們呼叫 `funcOne`。在函數 `funcOne` 的第一行,我們呼叫`myPromise` promise _異步操作_。當 JS 引擎在忙於執行 promise,它繼續執行函數 `funcOne`。下一行 _異步操作_ `setTimeout`,其回呼函數被 Web API 呼叫。 (詳情請參考我關於 event loop 的文章.) -promise 和 timeout 都是異步操作,函數繼續執行當JS引擎忙於執行promise 和 處理 `setTimeout` 的呼叫。相當於 `Last line!` 首先被輸出, 因為它不是異步操作。執行完 `funcOne` 的最後一行,promise 狀態轉變為 resolved,`Promise!` 被輸出。然而,因為我們呼叫了 `funcTwo()`, 呼叫堆疊不為空,`setTimeout` 的回呼仍不能入堆疊。 +promise 和 timeout 都是異步操作,函數繼續執行當 JS 引擎忙於執行 promise 和 處理 `setTimeout` 的呼叫。相當於 `Last line!` 首先被輸出,因為它不是異步操作。執行完 `funcOne` 的最後一行,promise 狀態轉變為 resolved,`Promise!` 被輸出。然而,因為我們呼叫了 `funcTwo()`, 呼叫堆疊不為空,`setTimeout` 的回呼仍不能入堆疊。 -我們現在處於 `funcTwo`,先 _awaiting_ myPromise。通過 `await` 關鍵字, 我們暫停了函數的執行直到 promise 狀態變為 resolved (或 rejected)。然後,我們輸出 `res` 的 awaited 值(因為 promise 本身回傳一個 promise)。接著輸出 `Promise!`。 +我們現在處於 `funcTwo`,先 _awaiting_ myPromise。通過 `await` 關鍵字,我們暫停了函數的執行直到 promise 狀態變為 resolved (或 rejected)。然後,我們輸出 `res` 的 awaited 值(因為 promise 本身回傳一個 promise)。接著輸出 `Promise!`。 下一行就是 _異步操作_ `setTimeout`,其回呼函數被 Web API 呼叫。 @@ -4312,7 +4312,7 @@ import * as sum from "./sum";

答案

-#### 答案: C +#### 答案:C 使用符號 `*`,我們引入文件中的所有值,包括預設和具名。如果我們有以下文件: @@ -4372,13 +4372,13 @@ person.name;

答案

-#### 答案: C +#### 答案:C 使用 Proxy 物件,我們可以給一個物件添加自定義行為。在這個 case,我們傳遞一個包含以下屬性的物件 `handler` : `set` and `get`。每當我門 _設置_ 屬性值時 `set` 被呼叫,每當我們 _獲取_ 時 `get` 被呼叫。 -第一個參數是一個空物件 `{}`,作為 `person` 的值。對於這個物件,自定義行為被定義在物件 `handler`。如果我們向物件 `person` 添加屬性,`set` 將被呼叫。如果我們獲取 `person` 的屬性, `get` 將被呼叫。 +第一個參數是一個空物件 `{}`,作為 `person` 的值。對於這個物件,自定義行為被定義在物件 `handler`。如果我們向物件 `person` 添加屬性,`set` 將被呼叫。如果我們獲取 `person` 的屬性,`get` 將被呼叫。 -首先,我們向 proxy 物件(`person.name = "Lydia"`)添加一個屬性 `name`。 `set` 被呼叫並輸出 `"Added a new property!"`。 +首先,我們向 proxy 物件 (`person.name = "Lydia"`) 添加一個屬性 `name`。`set` 被呼叫並輸出 `"Added a new property!"`。 然後,我們獲取 proxy 物件的一個屬性,物件 handler 的屬性 `get` 被呼叫。輸出 `"Accessed a property!"`。 @@ -4403,7 +4403,7 @@ Object.seal(person);

答案

-#### 答案: A +#### 答案:A 使用 `Object.seal` 我們可以防止新屬性 _被添加_,或者存在屬性 _被移除_. @@ -4435,7 +4435,7 @@ Object.freeze(person);

答案

-#### 答案: C +#### 答案:C 使用函數 `Object.freeze` 對一個物件進行 _凍結_。不能對屬性進行添加,修改,刪除。 @@ -4467,11 +4467,11 @@ myFunc(3);

答案

-#### 答案: A +#### 答案:A -首先我們不傳遞任何參數呼叫 `myFunc()`。因為我們沒有傳遞參數,`num` 和 `value` 獲取它們各自的預設值:num 為 `2`, 而 `value` 為函數 `add` 的回傳值。對於函數 `add`,我們傳遞值為2的 `num` 作為參數。函數 `add` 回傳 `4` 作為 `value` 的值。 +首先我們不傳遞任何參數呼叫 `myFunc()`。因為我們沒有傳遞參數,`num` 和 `value` 獲取它們各自的預設值:num 為 `2`, 而 `value` 為函數 `add` 的回傳值。對於函數 `add`,我們傳遞值為 2 的 `num` 作為參數。函數 `add` 回傳 `4` 作為 `value` 的值。 -然後,我們呼叫 `myFunc(3)` 並傳遞值 `3` 參數 `num` 的值。我們沒有給 `value` 傳遞值。因為我們沒有給參數 `value` 傳遞值,它獲取預設值:函數 `add` 的回傳值。對於函數 `add`,我們傳遞值為3的 `num`給它。函數 `add` 回傳 `6` 作為 `value` 的值。 +然後,我們呼叫 `myFunc(3)` 並傳遞值 `3` 參數 `num` 的值。我們沒有給 `value` 傳遞值。因為我們沒有給參數 `value` 傳遞值,它獲取預設值:函數 `add` 的回傳值。對於函數 `add`,我們傳遞值為 3 的 `num`給它。函數 `add` 回傳 `6` 作為 `value` 的值。

@@ -4507,9 +4507,9 @@ console.log(counter.#number)
答案

-#### 答案: D +#### 答案:D -在 ES2020 中,通過 `#` 我們可以給 class 添加私有變數。在 class 的外部我們無法存取該值。當我們嘗試輸出 `counter.#number`,語法錯誤被拋出:我們無法在 class `Counter` 外部存取它! +在 ES2020 中,通過 `#` 我們可以給 class 添加私有變數。在 class 的外部我們無法存取該值。當我們嘗試輸出 `counter.#number`,語法錯誤被拋出:我們無法在 class `Counter` 外部存取它!

@@ -4549,11 +4549,11 @@ obj.next(); // { value: "Lisa", done: false }
答案

-#### 答案: B +#### 答案:B -為了遍歷 `teams` 陣列中物件的屬性 `members` 中的每一項,我們需要將 `teams[i].members` 傳遞給 Generator 函數 `getMembers`。 Generator 函數回傳一個 generator 物件。為了遍歷這個 generator 物件中的每一項,我們需要使用 `yield*`. +為了遍歷 `teams` 陣列中物件的屬性 `members` 中的每一項,我們需要將 `teams[i].members` 傳遞給 Generator 函數 `getMembers`。Generator 函數回傳一個 generator 物件。為了遍歷這個 generator 物件中的每一項,我們需要使用 `yield*`. -如果我們沒有寫 `yield`,`return yield` 或者 `return`,整個 Generator 函數不會第一時間 return 當我們呼叫 `next` 函數. +如果我們沒有寫 `yield`,`return yield` 或者 `return`,整個 Generator 函數不會第一時間 return 當我們呼叫 `next` 函數。

@@ -4588,7 +4588,7 @@ console.log(person.hobbies);
答案

-#### 答案: C +#### 答案:C 函數 `addHobby` 接受兩個參數,`hobby` 和有著物件 `person` 中陣列 `hobbies` 預設值的 `hobbies`。 @@ -4632,9 +4632,9 @@ const pet = new Flamingo();

答案

-#### 答案: B +#### 答案:B -我們建立了class `Flamingo` 的實例 `pet`。當我們實例化這個實例,`Flamingo` 中的 `constructor` 被呼叫。首相,輸出 `"I'm pink. 🌸"`, 之後我們呼叫`super()`。 `super()` 呼叫父class的建構函數,`Bird`。 `Bird` 的建構函數被呼叫,並輸出 `"I'm a bird. 🦢"`。 +我們建立了 class `Flamingo` 的實例 `pet`。當我們實例化這個實例,`Flamingo` 中的 `constructor` 被呼叫。首相,輸出 `"I'm pink. 🌸"`, 之後我們呼叫`super()`。`super()` 呼叫父 class 的建構函數,`Bird`。`Bird` 的建構函數被呼叫,並輸出 `"I'm a bird. 🦢"`。

@@ -4660,9 +4660,9 @@ const emojis = ["🎄", "🎅🏼", "🎁", "⭐"];
答案

-#### 答案: D +#### 答案:D -`const` 關鍵字意味著我們不能 _重定義_ 變數中的值,它 _僅可讀_。然而,值本身不可修改。陣列 `emojis` 中的值可被修改,如 push 新的值, 拼接,又或者將陣列的長度設置為0。 +`const` 關鍵字意味著我們不能 _重定義_ 變數中的值,它 _僅可讀_。然而,值本身不可修改。陣列 `emojis` 中的值可被修改,如 push 新的值,拼接,又或者將陣列的長度設置為 0。

@@ -4688,9 +4688,9 @@ const person = {
答案

-#### 答案: C +#### 答案:C -物件預設並不是可迭代的。如果迭代規則被定義,則一個物件是可迭代的(An iterable is an iterable if the iterator protocol is present)。我們可以通過添加迭代器symbol `[Symbol.iterator]` 來定義迭代規則,其回傳一個 generator 物件,比如說構建一個 generator 函數 `*[Symbol.iterator]() {}`。如果我們想要回傳陣列 `["Lydia Hallie", 21]`: `yield* Object.values(this)`,這個 generator 函數一定要 yield 物件 `person` 的`Object.values`。 +物件預設並不是可迭代的。如果迭代規則被定義,則一個物件是可迭代的(An iterable is an iterable if the iterator protocol is present)。我們可以通過添加迭代器 symbol `[Symbol.iterator]` 來定義迭代規則,其回傳一個 generator 物件,比如說構建一個 generator 函數 `*[Symbol.iterator]() {}`。如果我們想要回傳陣列 `["Lydia Hallie", 21]`: `yield* Object.values(this)`,這個 generator 函數一定要 yield 物件 `person` 的`Object.values`。

@@ -4716,9 +4716,9 @@ console.log(count)
答案

-#### 答案: C +#### 答案:C -在 `forEach` 循環內部的 `if` 會判斷 `num` 的值是truthy或者是falsy。因為 `nums` 陣列的第一個數字是 `0`,一個falsy值, `if` 語句代碼塊不會被執行。 `count` 僅僅在 `nums` 陣列的其他3個數字 `1`,`2`,`3` 時加1。因為 `count` 執行了3次加 `1` 運算,所以 `count` 的值為 `3`。 +在 `forEach` 循環內部的 `if` 會判斷 `num` 的值是 truthy 或者是 falsy。因為 `nums` 陣列的第一個數字是 `0`,一個 falsy 值,`if` 語句代碼塊不會被執行。`count` 僅僅在 `nums` 陣列的其他 3 個數字 `1`,`2`,`3` 時加 1。因為 `count` 執行了 3 次加 `1` 運算,所以 `count` 的值為 `3`。

@@ -4745,15 +4745,15 @@ getFruit([['🍍'], ['🍊', '🍌']])
答案

-#### 答案: D +#### 答案:D `?` 允許我們去選擇性地訪問物件內部更深層的嵌套屬性。我們嘗試輸出 `fruits` 陣列索引值為 `1` 的子陣列內部的索引值為 `1` 的元素。如果在 `fruits` 陣列索引值 為 `1` 的位置不存在元素,會直接回傳 `undefined`。如果 `fruits` 陣列在索引值為 `1` 的位置存在元素,但是子陣列在索引值為 `1` 的位置不存在元素,也會回傳 `undefined`。 -首先,我們嘗試輸出 `[['🍊', '🍌'], ['🍍']]` 的子陣列 `['🍍']` 的第2個元素。這個子陣列只包含一個元素,也就意味著在索引值為 `1` 的位置不存在元素,所以回傳的是 `undefined` 。 +首先,我們嘗試輸出 `[['🍊', '🍌'], ['🍍']]` 的子陣列 `['🍍']` 的第 2 個元素。這個子陣列只包含一個元素,也就意味著在索引值為 `1` 的位置不存在元素,所以回傳的是 `undefined`。 -其次,我們在沒有傳入任何參數呼叫了 `getFruits` 函數,也就意味著形參 `fruits` 的預設值為`undefined`。因為我們選擇性地鏈接了 `fruits` 在索引值為 `1` 的元素,因為在索引值為 `1` 的位置不存在元素,因此回傳的是 `undefined` 。 +其次,我們在沒有傳入任何參數呼叫了 `getFruits` 函數,也就意味著形參 `fruits` 的預設值為`undefined`。因為我們選擇性地鏈接了 `fruits` 在索引值為 `1` 的元素,因為在索引值為 `1` 的位置不存在元素,因此回傳的是 `undefined`。 -最後,我們嘗試輸出 `['🍍'], ['🍊', '🍌']` 的子陣列 `['🍊', '🍌']` 的第2個元素。子陣列索引值為 `1`的位置為 `🍌` ,因此它被輸出出了。 +最後,我們嘗試輸出 `['🍍'], ['🍊', '🍌']` 的子陣列 `['🍊', '🍌']` 的第 2 個元素。子陣列索引值為 `1`的位置為 `🍌`,因此它被輸出出了。

@@ -4787,9 +4787,9 @@ console.log(calc.count)
答案

-#### 答案: A +#### 答案:A -我們設置 `calc` 變數為 `Calc` 類的一個新實例。然後,我們初始化一個 `Calc` 的新實例,而且呼叫了這個實例的 `increase` 函數。因為count屬性是在 `Calc` class的constructor內部的,所以count屬性不會在 `Calc` 的原型鏈上共享出去。這就意味著calc實例的count值不會被更新,count仍然是 `0`。 +我們設置 `calc` 變數為 `Calc` 類的一個新實例。然後,我們初始化一個 `Calc` 的新實例,而且呼叫了這個實例的 `increase` 函數。因為 count 屬性是在 `Calc` class 的 constructor 內部的,所以 count 屬性不會在 `Calc` 的原型鏈上共享出去。這就意味著 calc 實例的 count 值不會被更新,count 仍然是 `0`。

@@ -4829,9 +4829,9 @@ console.log(updatedUser === user)
答案

-#### 答案: B +#### 答案:B - `updateUser` 函數更新user的 `email` 和 `password` 屬性的值, 如果它們的值傳入函數, 函數回傳的就是 `user` 物件。 `updateUser` 函數的回傳值是 `user` 物件,意味著updatedUser的值與 `user` 指向的是同一個 `user` 物件。 `updatedUser === user` 為 `true`. + `updateUser` 函數更新 user 的 `email` 和 `password` 屬性的值,如果它們的值傳入函數,函數回傳的就是 `user` 物件。`updateUser` 函數的回傳值是 `user` 物件,意味著 updatedUser 的值與 `user` 指向的是同一個 `user` 物件。`updatedUser === user` 為 `true`.

@@ -4858,11 +4858,11 @@ console.log(fruit)
答案

-#### 答案: C +#### 答案:C -首先,我們在fruit陣列上呼叫 `slice` 函數。 slice函數不會修改原始陣列,但是會回傳從陣列切片下來的值:香蕉emoji。 -其次,我們在fruit陣列上呼叫 `splice` 函數。 splice函數會修改原始陣列,也就意味著fruit陣列此時為 `['🍊', '🍎']`。 -最後,我們在fruit陣列上呼叫 `unshift` 函數,通過添加一個值的方式改變了原始陣列,添加的是'🍇',它成為了陣列的第一個元素。現在fruit陣列的組成為 `['🍇', '🍊', '🍎']`。 +首先,我們在 fruit 陣列上呼叫 `slice` 函數。slice 函數不會修改原始陣列,但是會回傳從陣列切片下來的值:香蕉 emoji。 +其次,我們在 fruit 陣列上呼叫 `splice` 函數。splice 函數會修改原始陣列,也就意味著 fruit 陣列此時為 `['🍊', '🍎']`。 +最後,我們在 fruit 陣列上呼叫 `unshift` 函數,通過添加一個值的方式改變了原始陣列,添加的是'🍇',它成為了陣列的第一個元素。現在 fruit 陣列的組成為 `['🍇', '🍊', '🍎']`。

@@ -4890,15 +4890,15 @@ console.log(animals[dog])
答案

-#### 答案: B +#### 答案:B 物件的鍵會被轉換為字符串。 -因為 `dog` 的值是一個物件, `animals[dog]` 實際上意味著我們建立了一個叫做 `"object Object"` 的屬性來代表新的物件。 `animals["object Object"]` 現在等於 `{ emoji: "🐶", name: "Mara"}`。 +因為 `dog` 的值是一個物件,`animals[dog]` 實際上意味著我們建立了一個叫做 `"object Object"` 的屬性來代表新的物件。`animals["object Object"]` 現在等於 `{ emoji: "🐶", name: "Mara"}`。 -`cat` 也是一個物件,`animals[cat]` 實際上意味著我們在用新的cat的屬性覆蓋 `animals[``"``object Object``"``]` 的值。 +`cat` 也是一個物件,`animals[cat]` 實際上意味著我們在用新的 cat 的屬性覆蓋 `animals[``"``object Object``"``]` 的值。 -輸出`animals[dog]`,實際上是`animals["object Object"]`,這是因為轉化`dog`物件為一個字符串結果`"object Object"` ,所以回傳`{ emoji: "🐈" , name: "Sara" }`。 +輸出`animals[dog]`,實際上是`animals["object Object"]`,這是因為轉化`dog`物件為一個字符串結果`"object Object"`,所以回傳`{ emoji: "🐈" , name: "Sara" }`。

@@ -4927,9 +4927,9 @@ console.log(user.email)
答案

-#### 答案: A +#### 答案:A -`updateEmail` 函數是一個箭頭函數,它沒有和 `user` 物件綁定。這就意味著 `this` 關鍵字不會引用到 `user` 物件,但是會引用到全局物件。 `user` 物件內部的 `email` 的值不會更新。當輸出​​ `user.email` 的時候, 原始值 `my@email.com` 被回傳。 +`updateEmail` 函數是一個箭頭函數,它沒有和 `user` 物件綁定。這就意味著 `this` 關鍵字不會引用到 `user` 物件,但是會引用到全局物件。`user` 物件內部的 `email` 的值不會更新。當輸出​​ `user.email` 的時候,原始值 `my@email.com` 被回傳。

@@ -4963,9 +4963,9 @@ runPromises()
答案

-#### 答案: D +#### 答案:D - `Promise.all` 函數可以並行式執行promise。如果其中一個promise失敗了,`Promise.all` 函數會帶上被reject的promise的值_rejects_。在這個例子中, `promise3` 帶著 `"Third"` 值reject。我們在呼叫 `runPromises` 時在 `runPromises` 函數內部的 `catch` 函數去捕獲任意error從而捕獲到被reject的值。因為 `promise3` 帶著 `"Third"` 被reject,所以只有 `"Third"` 輸出。 + `Promise.all` 函數可以並行式執行 promise。如果其中一個 promise 失敗了,`Promise.all` 函數會帶上被 reject 的 promise 的值_rejects_。在這個例子中,`promise3` 帶著 `"Third"` 值 reject。我們在呼叫 `runPromises` 時在 `runPromises` 函數內部的 `catch` 函數去捕獲任意 error 從而捕獲到被 reject 的值。因為 `promise3` 帶著 `"Third"` 被 reject,所以只有 `"Third"` 輸出。

@@ -4992,11 +4992,11 @@ Object[method](keys.map((_, i) => {
答案

-#### 答案: C +#### 答案:C -`fromEntries` 函數可以將二維陣列轉換為物件。在每個子陣列的第一個元素是key,在每個子陣列的第二個元素是value。在這個例子中,我們映射了 `keys` 陣列,它回傳了一個陣列,陣列的第一個元素為keys陣列當前索引的值,第二個元素為values陣列當前索引的值。 +`fromEntries` 函數可以將二維陣列轉換為物件。在每個子陣列的第一個元素是 key,在每個子陣列的第二個元素是 value。在這個例子中,我們映射了 `keys` 陣列,它回傳了一個陣列,陣列的第一個元素為 keys 陣列當前索引的值,第二個元素為 values 陣列當前索引的值。 -這樣就建立了一個包含正確keys和values的子陣列的陣列,因此結果為`{ name: "Lydia", age: 22 }`。 +這樣就建立了一個包含正確 keys 和 values 的子陣列的陣列,因此結果為`{ name: "Lydia", age: 22 }`。

@@ -5028,9 +5028,9 @@ console.log(member)
答案

-#### 答案: C +#### 答案:C - `address` 的預設值是一個空物件 `{}`。當我們設置 `member` 變數為 `createMember` 函數回傳的物件,我們沒有為address參數傳值,意味著address的值為預設的空物件 `{}`。一個空物件是一個truthy值,意味著 `address ? address : null` 條件會回傳 `true`。 address的值為空物件 `{}`。 + `address` 的預設值是一個空物件 `{}`。當我們設置 `member` 變數為 `createMember` 函數回傳的物件,我們沒有為 address 參數傳值,意味著 address 的值為預設的空物件 `{}`。一個空物件是一個 truthy 值,意味著 `address ? address : null` 條件會回傳 `true`。address 的值為空物件 `{}`。

@@ -5058,11 +5058,11 @@ if (!typeof randomValue === "string") {
答案

-#### 答案: B +#### 答案:B - `if` 語句的條件判斷 `!typeof randomValue` 的值是否等於 `"string"`。 `!` 操作符將這個值轉化為一個布林值。如果值是truthy的話,回傳值會是 `false`,如果值是falsy,回傳值會是 `true`。在這裡, `typeof randomValue` 的回傳值是一個truthy值 `"number"`,意味著 `!typeof randomValue` 的值是一個布林值 `false`。 + `if` 語句的條件判斷 `!typeof randomValue` 的值是否等於 `"string"`。`!` 操作符將這個值轉化為一個布林值。如果值是 truthy 的話,回傳值會是 `false`,如果值是 falsy,回傳值會是 `true`。在這裡,`typeof randomValue` 的回傳值是一個 truthy 值 `"number"`,意味著 `!typeof randomValue` 的值是一個布林值 `false`。 - `!typeof randomValue === "string"` 總是回傳false,因為我們實際上是在執行 `false === "string"`。因為條件回傳的是 `false`,所以 `else` 語句中的代碼塊會被執行,因此輸出 `Yay it's a string!` 。 + `!typeof randomValue === "string"` 總是回傳 false,因為我們實際上是在執行 `false === "string"`。因為條件回傳的是 `false`,所以 `else` 語句中的代碼塊會被執行,因此輸出 `Yay it's a string!`。

\ No newline at end of file From 784c99765eb0f234ebb6587b3edb72292efe7d10 Mon Sep 17 00:00:00 2001 From: fountainpen Date: Sat, 16 Sep 2023 15:09:56 +0200 Subject: [PATCH 182/193] Update README-bs_BS.md --- bs-BS/README-bs_BS.md | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/bs-BS/README-bs_BS.md b/bs-BS/README-bs_BS.md index eeeb7ea3..7abe7c1d 100644 --- a/bs-BS/README-bs_BS.md +++ b/bs-BS/README-bs_BS.md @@ -5,8 +5,8 @@ Svakodnevno postavljam JavaScript pitanja s višestrukim izborom na moj [Instagram](https://www.instagram.com/theavocoder), koja također objavljujem ovdje! -Od osnovnog do naprednog: testirajte koliko dobro znate JavaScript, osvježite svoj -znanje malo, ili pripremiti za svoj intervju! :muscle: :rocket: +Od osnovnog do naprednog: testirajte koliko dobro znate JavaScript, malo osvježite +svoje znanje, ili se pripremite za svoj intervju! :muscle: :rocket: Ovaj tjedni repo ažuriram s novim pitanjima. Odgovori su jednostavno dijelovima ispod pitanja @@ -184,7 +184,7 @@ Niz '' Lydia '' je istinita vrijednost. Ono što zapravo tražimo jest * * * * * -###### 5. Koja je istina? +###### 5. Što je od ovoga istina? ```javascript const bird = { @@ -212,9 +212,9 @@ iako ih možda ne * upisujemo kao * nizove, oni se uvijek pretvaraju u String ispod "haube". JavaScript tumači (ili odlaže) izjave. Kada koristimo zagradu -notacija, on vidi prvu otvarnu zagradu ```i nastavlja dalje do nje +notacija, on vidi prvu otvorenu zagradu ```i nastavlja dalje do nje pronalazi završnu zagradu `]`. Tek tada će procijeniti -izjava. +izjavu. `mouse [bird.size]`: Prvo procjenjuje `bird.size`, što je` `small``. `mouse [" small "]` vraća "true" @@ -401,8 +401,8 @@ Ovo je moguće u JavaScriptu, jer su funkcije objekti! (Sve osim primitivnih tipova su objekti) function je posebna vrsta objekta. Kod koji sami napišete -nije stvarna funkcija. function je objekt sa svojstvima. -Ova nekretnina je nepovratna. +nije stvarna funkcija. Function je objekt sa svojstvima. +To svojstvo je nepovratna.

@@ -484,8 +484,8 @@ console.log(sarah); #### Odgovor: A -Za `sarah` nismo koristili ključnu riječ` new`. Kada koristite "new", to -odnosi se na new prazni objekt koji stvaramo. Međutim, ako ne dodate +Za `Sarah` nismo koristili ključnu riječ` new`. Kada koristite "new", to +odnosi se na novi prazni objekt koji stvaramo. Međutim, ako ne dodate `new` se odnosi na ** globalni objekt **! Rekli smo da je "this.ime" jednako "Sarah" i `this.prezime` From a899330eef7dd87503fafa53de960bb9135f40d7 Mon Sep 17 00:00:00 2001 From: fountainpen Date: Sat, 16 Sep 2023 15:59:19 +0200 Subject: [PATCH 183/193] Update README-bs_BS.md --- bs-BS/README-bs_BS.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/bs-BS/README-bs_BS.md b/bs-BS/README-bs_BS.md index 7abe7c1d..33f0384f 100644 --- a/bs-BS/README-bs_BS.md +++ b/bs-BS/README-bs_BS.md @@ -402,7 +402,7 @@ Ovo je moguće u JavaScriptu, jer su funkcije objekti! function je posebna vrsta objekta. Kod koji sami napišete nije stvarna funkcija. Function je objekt sa svojstvima. -To svojstvo je nepovratna. +To svojstvo je nepovratno.

From cd69479869f678ef5de942f9db38c35a08db00f1 Mon Sep 17 00:00:00 2001 From: Abdullah Date: Thu, 21 Sep 2023 04:08:32 +0300 Subject: [PATCH 184/193] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 802f4dfc..23b2422a 100644 --- a/README.md +++ b/README.md @@ -3865,7 +3865,7 @@ console.log(list[(num += 1)]); #### Answer: B -With the `+=` operand, we're incrementing the value of `num` by `1`. `num` had the initial value `1`, so `1 + 1` is `2`. The item on the second index in the `list` array is 🥰, `console.log(list[2])` prints 🥰. +With the `+=` operator, we're incrementing the value of `num` by `1`. `num` had the initial value `1`, so `1 + 1` is `2`. The item on the second index in the `list` array is 🥰, `console.log(list[2])` prints 🥰.

From 700a1b75cf42fd592dd376bbbdc88233df6e2617 Mon Sep 17 00:00:00 2001 From: Mohammed Nasif <99568326+Mohammed-Nasif@users.noreply.github.com> Date: Sun, 24 Sep 2023 12:35:45 -0700 Subject: [PATCH 185/193] Update line 742 Q.23 --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 7627f92e..a4310c34 100644 --- a/README.md +++ b/README.md @@ -739,7 +739,7 @@ console.log(num); With the `var` keyword, you can declare multiple variables with the same name. The variable will then hold the latest value. -You cannot do this with `let` or `const` since they couldn't be redeclared. +You cannot do this with `let` or `const` since they're block-scoped and therefore can't be redeclared.

From b6f9bfc44fa2ca658e1f41b2c1b5e301bcbd781c Mon Sep 17 00:00:00 2001 From: Lukasz Jasionowski Date: Wed, 18 Oct 2023 13:24:26 +0200 Subject: [PATCH 186/193] Add note and modify content with current from English version --- pl-PL/README.md | 13 +++++++++---- 1 file changed, 9 insertions(+), 4 deletions(-) diff --git a/pl-PL/README.md b/pl-PL/README.md index 31d8e974..2d381955 100644 --- a/pl-PL/README.md +++ b/pl-PL/README.md @@ -1,16 +1,21 @@

Pytania dotyczące JavaScript

+
+ +> [!NOTE] +> To repozytorium zostało utworzone w 2019 roku, a zatem pytania tutaj zawarte są oparte na składni i zachowaniu JavaScript w tym czasie. Ponieważ JavaScript jest stale rozwijającym się językiem, istnieją nowsze funkcje językowe, które nie są objęte pytaniami tutaj. --- -Publikuję pytania wielokrotnego wyboru dotyczące JavaScriptu na swoich [Instagram](https://www.instagram.com/theavocoder) **stories**, które również zamieszczę tutaj! Ostatnia aktualizacja: 27 Czerwca +

+Od podstawowych do zaawansowanych: sprawdź, jak dobrze znasz JavaScript, odśwież swoją wiedzę lub przygotuj się do rozmowy kwalifikacyjnej! :muscle: :rocket: Regularnie aktualizuję to repozytorium nowymi pytaniami. Odpowiedzi znajdują się w ukrytych zakładkach poniżej pytań - po prostu kliknij, aby je rozwinięć. To dla zabawy, powodzenia! :heart:

-Od podstawowych do zaawansowanych: sprawdź, jak dobrze znasz JavaScript, odśwież swoją wiedzę lub przygotuj się do rozmowy kwalifikacyjnej! :muscle: :rocket: Regularnie aktualizuję to repozytorium nowymi pytaniami. Odpowiedzi znajdują się w ukrytych zakładkach poniżej pytań - po prostu kliknij, aby je rozwinięć. To dla zabawy, powodzenia! :heart:
+

Nie krępuj się ze mną kontaktować! 😊

-Nie krępuj się ze mną kontaktować! 😊
+

Instagram || Twitter || LinkedIn || Blog -

+

| Śmiało używaj ich w projekcie! 😃 Byłabym _bardzo_ wdzięczna za referencje do tego repozytorium, tworzę pytania i wyjaśnienia (tak, jestem smutna lol) i społeczność bardzo mi pomaga w utrzymaniu i ulepszaniu go! 💪🏼 Dziękuję i baw się dobrze! | |---| From a665b9edd8da1d5a2f0af2d9b00c1f1e47ccd295 Mon Sep 17 00:00:00 2001 From: Lukasz Jasionowski Date: Thu, 19 Oct 2023 12:49:43 +0200 Subject: [PATCH 187/193] Add 10 translated questions | Total translated: 60 --- pl-PL/README.md | 344 ++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 344 insertions(+) diff --git a/pl-PL/README.md b/pl-PL/README.md index 2d381955..0f558221 100644 --- a/pl-PL/README.md +++ b/pl-PL/README.md @@ -1550,5 +1550,349 @@ Podczas mapowania tablicy, wartość `num` jest równa elementowi, nad którym a Nie zwracamy jednak żadnej wartości. Gdy nie zwracamy wartości z funkcji, funkcja zwraca `undefined`. Dla każdego elementu w tablicy wywoływany jest blok funkcji, więc dla każdego elementu zwracamy `undefined`. +

+
+ +--- + +###### 51. Jaki jest wynik? + +```javascript +function getInfo(member, year) { + member.name = 'Lydia'; + year = '1998'; +} + +const person = { name: 'Sarah' }; +const birthYear = '1997'; + +getInfo(person, birthYear); + +console.log(person, birthYear); +``` + +- A: `{ name: "Lydia" }, "1997"` +- B: `{ name: "Sarah" }, "1998"` +- C: `{ name: "Lydia" }, "1998"` +- D: `{ name: "Sarah" }, "1997"` + +
Odpowiedź +

+ +#### Odpowiedź: A + +Argumenty są przekazywane przez _wartość_, chyba że ich wartość jest obiektem, wtedy są przekazywane przez _referencję_. Argument `birthYear` jest przekazywany przez wartość, ponieważ jest ciągiem znaków, a nie obiektem. Kiedy przekazujemy argumenty przez wartość, tworzona jest _kopia_ tej wartości (patrz pytanie 46). + +Zmienna `birthYear` posiada referencję do wartości `"1997"`. Argument `year` również posiada referencję do wartości `"1997"`, ale nie jest to ta sama wartość, do której odnosi się `birthYear`. Kiedy aktualizujemy wartość `year` ustawiając `year` na `"1998"`, aktualizujemy tylko wartość `year`. Wartość `birthYear` jest wciąż równa `1997`. + +Wartość `person` jest obiektem. Argument `member` posiada (skopiowaną) referencję do _tego samego_ obiektu. Gdy zmodyfikujemy właściwość obiektu, do którego odwołuje się `member`, wartość `person` również zostanie zmodyfikowana, ponieważ oba mają odwołanie do tego samego obiektu. Właściwość `name` obiektu `person` jest teraz równa wartości `"Lydia"`. + +

+
+ +--- + +###### 52. Jaki jest wynik? + +```javascript +function greeting() { + throw 'Hello world!'; +} + +function sayHi() { + try { + const data = greeting(); + console.log('It worked!', data); + } catch (e) { + console.log('Oh no an error:', e); + } +} + +sayHi(); +``` + +- A: `It worked! Hello world!` +- B: `Oh no an error: undefined` +- C: `SyntaxError: can only throw Error objects` +- D: `Oh no an error: Hello world!` + +
Odpowiedź +

+ +#### Odpowiedź: D + +Za pomocą instrukcji `throw` możemy tworzyć niestandardowe błędy. Za pomocą tej instrukcji można rzucać wyjątki string, number, boolean lub object. W tym przypadku, naszym wyjątkiem jest ciąg znaków `'Hello world!".` + +Za pomocą instrukcji `catch` możemy określić, co należy zrobić, jeśli wyjątek zostanie rzucony w bloku `try`. Wyjątkiem może być: string `'Hello world!'`. `e` jest teraz równe temu ciągowi, który wyświetlamy w konsoli. Skutkuje to `'Oh an error: Hello world!'`. + +

+
+ +--- + +###### 53. Jaki jest wynik? + +```javascript +function Car() { + this.make = 'Lamborghini'; + return { make: 'Maserati' }; +} + +const myCar = new Car(); +console.log(myCar.make); +``` + +- A: `"Lamborghini"` +- B: `"Maserati"` +- C: `ReferenceError` +- D: `TypeError` + +
Odpowiedź +

+ +#### Odpowiedź: B + +Kiedy zwracasz właściwość, wartość właściwości jest równa _zwróconej_ wartości, a nie wartości ustawionej w funkcji konstruktora. Zwracamy ciąg `"Maserati"`, więc `myCar.make` jest równe `"Maserati"`. + +

+
+ +--- + +###### 54. Jaki jest wynik? + +```javascript +(() => { + let x = (y = 10); +})(); + +console.log(typeof x); +console.log(typeof y); +``` + +- A: `"undefined", "number"` +- B: `"number", "number"` +- C: `"object", "number"` +- D: `"number", "undefined"` + +
Odpowiedź +

+ +#### Odpowiedź: A + +`let x = (y = 10);` jest w rzeczywistości skrótem od: + +```javascript +y = 10; +let x = y; +``` + +Kiedy ustawiamy `y` równe `10`, w rzeczywistości dodajemy właściwość `y` do globalnego obiektu (`window` w przeglądarce, `global` w Node). W przeglądarce, `window.y` jest teraz równe `10`. + +Następnie deklarujemy zmienną `x` z wartością `y`, która wynosi `10`. Zmienne zadeklarowane za pomocą słowa kluczowego `let` są _block scoped_ i są definiowane tylko w bloku, w którym zostały zadeklarowane; w tym przypadku natychmiast wywołane wyrażenie funkcji (IIFE). Kiedy używamy operatora `typeof`, operand `x` nie jest zdefiniowany: próbujemy uzyskać dostęp do `x` poza blokiem, w którym został zadeklarowany. Oznacza to, że `x` nie jest zdefiniowane. Wartości, które nie zostały przypisane lub zadeklarowane są typu "undefined". `console.log(typeof x)` zwraca `"undefined"`. + +Jednakże, utworzyliśmy globalną zmienną `y` podczas ustawiania `y` równego `10`. Wartość ta jest dostępna w dowolnym miejscu naszego kodu. Zmienna `y` jest zdefiniowana i przechowuje wartość typu `"number"`. `console.log(typeof y)` zwraca `"number"`. + +

+
+ +--- + +###### 55. Jaki jest wynik? + +```javascript +class Dog { + constructor(name) { + this.name = name; + } +} + +Dog.prototype.bark = function() { + console.log(`Woof I am ${this.name}`); +}; + +const pet = new Dog('Mara'); + +pet.bark(); + +delete Dog.prototype.bark; + +pet.bark(); +``` + +- A: `"Woof I am Mara"`, `TypeError` +- B: `"Woof I am Mara"`, `"Woof I am Mara"` +- C: `"Woof I am Mara"`, `undefined` +- D: `TypeError`, `TypeError` + +
Odpowiedź +

+ +#### Odpowiedź: A + +Możemy usuwać właściwości z obiektów za pomocą słowa kluczowego `delete`, również na prototypie. Usuwając właściwość z prototypu, nie jest ona już dostępna w łańcuchu prototypów. W tym przypadku funkcja `bark` nie jest już dostępna w prototypie po `delete Dog.prototype.bark`, a mimo to wciąż próbujemy uzyskać do niej dostęp. + +Kiedy próbujemy wywołać coś, co nie jest funkcją, rzucany jest `TypeError`. W tym przypadku `TypeError: pet.bark is not a function`, ponieważ `pet.bark` jest `undefined`. + +

+
+ +--- + +###### 56. Jaki jest wynik? + +```javascript +const set = new Set([1, 1, 2, 3, 4]); + +console.log(set); +``` + +- A: `[1, 1, 2, 3, 4]` +- B: `[1, 2, 3, 4]` +- C: `{1, 1, 2, 3, 4}` +- D: `{1, 2, 3, 4}` + +
Odpowiedź +

+ +#### Odpowiedź: D + +Obiekt `Set` jest zbiorem _unikalnych_ wartości: wartość może wystąpić tylko raz w zbiorze. + +Przekazaliśmy iterowalne `[1, 1, 2, 3, 4]` ze zduplikowaną wartością `1`.Ponieważ nie możemy mieć dwóch takich samych wartości w zbiorze, jedna z nich jest usuwana. Wynikiem jest `{1, 2, 3, 4}`. + +

+
+ +--- + +###### 57. Jaki jest wynik? + +```javascript +// counter.js +let counter = 10; +export default counter; +``` + +```javascript +// index.js +import myCounter from './counter'; + +myCounter += 1; + +console.log(myCounter); +``` + +- A: `10` +- B: `11` +- C: `Error` +- D: `NaN` + +
Odpowiedź +

+ +#### Odpowiedź: C + +Zaimportowany moduł jest _tylko do odczytu_: nie można modyfikować zaimportowanego modułu. Tylko moduł, który go eksportuje może zmienić jego wartość. + +Kiedy próbujemy zwiększyć wartość `myCounter`, wyrzuca błąd: `myCounter` jest tylko do odczytu i nie może być modyfikowany. + +

+
+ +--- + +###### 58. Jaki jest wynik? + +```javascript +const name = 'Lydia'; +age = 21; + +console.log(delete name); +console.log(delete age); +``` + +- A: `false`, `true` +- B: `"Lydia"`, `21` +- C: `true`, `true` +- D: `undefined`, `undefined` + +
Odpowiedź +

+ +#### Odpowiedź: A + +Operator `delete` zwraca wartość logiczną: `true` po pomyślnym usunięciu, w przeciwnym razie zwróci `false`. Jednakże, zmienne zadeklarowane ze słowem kluczowym `var`, `const` lub `let` nie mogą być usunięte za pomocą operatora `delete`. + +Zmienna `name` została zadeklarowana ze słowem kluczowym `const`, więc jej usunięcie nie powiedzie się: Zwracane jest `false`. Kiedy ustawiliśmy wartość `age` równą `21`, w rzeczywistości dodaliśmy właściwość o nazwie `age` do obiektu globalnego. W ten sposób można pomyślnie usunąć właściwości z obiektów, również z obiektu globalnego, więc `delete age` zwraca `true`. + +

+
+ +--- + +###### 59. Jaki jest wynik? + +```javascript +const numbers = [1, 2, 3, 4, 5]; +const [y] = numbers; + +console.log(y); +``` + +- A: `[[1, 2, 3, 4, 5]]` +- B: `[1, 2, 3, 4, 5]` +- C: `1` +- D: `[1]` + +
Odpowiedź +

+ +#### Odpowiedź: C + +Możemy rozpakować wartości z tablic lub właściwości z obiektów poprzez destrukturyzację. Na przykład: + +```javascript +[a, b] = [1, 2]; +``` + + + +Wartość `a` wynosi teraz `1`, a wartość `b` wynosi teraz `2`.To, co faktycznie zrobiliśmy w pytaniu, to: + +```javascript +[y] = [1, 2, 3, 4, 5]; +``` + + + +Oznacza to, że wartość `y` jest równa pierwszej wartości w tablicy, którą jest liczba `1`.Kiedy logujemy `y`, zwracana jest wartość `1`. + +

+
+ +--- + +###### 60. Jaki jest wynik? + +```javascript +const user = { name: 'Lydia', age: 21 }; +const admin = { admin: true, ...user }; + +console.log(admin); +``` + +- A: `{ admin: true, user: { name: "Lydia", age: 21 } }` +- B: `{ admin: true, name: "Lydia", age: 21 }` +- C: `{ admin: true, user: ["Lydia", 21] }` +- D: `{ admin: true }` + +
Odpowiedź +

+ +#### Odpowiedź: B + +Możliwe jest łączenie obiektów za pomocą operatora rozprzestrzeniania `...`.Umożliwia on tworzenie kopii par klucz/wartość jednego obiektu i dodawanie ich do innego obiektu. W tym przypadku tworzymy kopie obiektu `user` i dodajemy je do obiektu `admin`. Obiekt `admin` zawiera teraz skopiowane pary klucz/wartość, czego wynikiem jest `{ admin: true, name: "Lydia", age: 21 }`. +

\ No newline at end of file From e5bee7b1eabc9bdd6e4f7b49aa3329cece24b8cf Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C5=81ukasz=20Jasionowski?= Date: Sat, 21 Oct 2023 12:58:51 +0200 Subject: [PATCH 188/193] Add 10 translated questions | Total translated: 70 --- pl-PL/README.md | 329 ++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 329 insertions(+) diff --git a/pl-PL/README.md b/pl-PL/README.md index 0f558221..02bfc687 100644 --- a/pl-PL/README.md +++ b/pl-PL/README.md @@ -1894,5 +1894,334 @@ console.log(admin); Możliwe jest łączenie obiektów za pomocą operatora rozprzestrzeniania `...`.Umożliwia on tworzenie kopii par klucz/wartość jednego obiektu i dodawanie ich do innego obiektu. W tym przypadku tworzymy kopie obiektu `user` i dodajemy je do obiektu `admin`. Obiekt `admin` zawiera teraz skopiowane pary klucz/wartość, czego wynikiem jest `{ admin: true, name: "Lydia", age: 21 }`. +

+
+ +--- + +###### 61. Jaki jest wynik? + +```javascript +const person = { name: 'Lydia' }; + +Object.defineProperty(person, 'age', { value: 21 }); + +console.log(person); +console.log(Object.keys(person)); +``` + +- A: `{ name: "Lydia", age: 21 }`, `["name", "age"]` +- B: `{ name: "Lydia", age: 21 }`, `["name"]` +- C: `{ name: "Lydia"}`, `["name", "age"]` +- D: `{ name: "Lydia"}`, `["age"]` + +
Odpowiedź +

+ +#### Odpowiedź: B + +Za pomocą metody `defineProperty` możemy dodawać nowe właściwości do obiektu lub modyfikować istniejące. Kiedy dodajemy właściwość do obiektu za pomocą metody `defineProperty`, są one domyślnie _niewyliczalne_. Metoda `Object.keys` zwraca wszystkie _wyliczalne_ nazwy właściwości z obiektu, w tym przypadku tylko `"name"`. + +Właściwości dodane przy użyciu metody `defineProperty` są domyślnie niezmienne. Możesz nadpisać to zachowanie używając właściwości `writable`, `configurable` i `enumerable`. W ten sposób metoda `defineProperty` daje dużo większą kontrolę nad właściwościami dodawanymi do obiektu. + +

+
+ +--- + +###### 62. Jaki jest wynik? + +```javascript +const settings = { + username: 'lydiahallie', + level: 19, + health: 90, +}; + +const data = JSON.stringify(settings, ['level', 'health']); +console.log(data); +``` + +- A: `"{"level":19, "health":90}"` +- B: `"{"username": "lydiahallie"}"` +- C: `"["level", "health"]"` +- D: `"{"username": "lydiahallie", "level":19, "health":90}"` + +
Odpowiedź +

+ +#### Odpowiedź: A + +Drugim argumentem `JSON.stringify` jest _replacer_. Zamiennik może być funkcją lub tablicą i pozwala kontrolować, co i w jaki sposób wartości powinny być łańcuchowane. + +Jeśli zamiennik jest _tablicą_, tylko nazwy właściwości zawarte w tablicy zostaną dodane do łańcucha JSON. W tym przypadku tylko właściwości o nazwach `"level"` i `"health"` są uwzględnione, `"username"` jest wykluczone. `data` jest teraz równa `"{"level":19, "health":90}"`. + +Jeśli zamiennik jest _funkcją_, funkcja ta jest wywoływana na każdej właściwości obiektu, który stringujesz. Wartość zwrócona z tej funkcji będzie wartością właściwości, gdy zostanie ona dodana do łańcucha JSON. Jeśli wartość jest `undefined`, właściwość ta zostanie wykluczona z łańcucha JSON. + +

+
+ +--- + +###### 63. Jaki jest wynik? + +```javascript +let num = 10; + +const increaseNumber = () => num++; +const increasePassedNumber = number => number++; + +const num1 = increaseNumber(); +const num2 = increasePassedNumber(num1); + +console.log(num1); +console.log(num2); +``` + +- A: `10`, `10` +- B: `10`, `11` +- C: `11`, `11` +- D: `11`, `12` + +
Odpowiedź +

+ +#### Odpowiedź: A + +Operator jednoargumentowy `++` _najpierw zwraca_ wartość operandu, _potem zwiększa_ wartość operandu. Wartość `num1` to `10`, ponieważ funkcja `increaseNumber` najpierw zwraca wartość `num`, czyli `10`, a dopiero potem zwiększa wartość `num`. + +`num2` jest równe `10`, ponieważ przekazaliśmy `num1` do `increasePassedNumber`.`number` jest równe `10` (wartość `num1`). Ponownie, operator jednoargumentowy `++` _najpierw zwraca_ wartość operandu, _następnie zwiększa_ wartość operandu. Wartość `liczba` wynosi `10`, więc `liczba2` jest równa `10`. + +

+
+ +--- + +###### 64. Jaki jest wynik? + +```javascript +const value = { number: 10 }; + +const multiply = (x = { ...value }) => { + console.log((x.number *= 2)); +}; + +multiply(); +multiply(); +multiply(value); +multiply(value); +``` + +- A: `20`, `40`, `80`, `160` +- B: `20`, `40`, `20`, `40` +- C: `20`, `20`, `20`, `40` +- D: `NaN`, `NaN`, `20`, `40` + +
Odpowiedź +

+ +#### Odpowiedź: C + +W ES6 możemy inicjować parametry z wartością domyślną. Wartość parametru będzie wartością domyślną, jeśli żadna inna wartość nie została przekazana do funkcji lub jeśli wartość parametru jest `"undefined". W tym przypadku, rozkładamy właściwości obiektu `value` na nowy obiekt, więc `x` ma domyślną wartość `{ number: 10 }`. + +Domyślny argument jest obliczany w _call time_! Za każdym razem, gdy wywołujemy funkcję, tworzony jest _nowy_ obiekt. Wywołujemy funkcję `multiply` dwa pierwsze razy bez przekazywania wartości: `x` ma wartość domyślną `{ number: 10 }`. Następnie rejestrujemy pomnożoną wartość tej liczby, która wynosi `20`. + +Za trzecim razem, gdy wywołujemy multiply, przekazujemy argument: obiekt o nazwie `value`. Operator `*=` jest w rzeczywistości skrótem od `x.number = x.number * 2`: modyfikujemy wartość `x.number` i rejestrujemy pomnożoną wartość `20`. + +Za czwartym razem ponownie przekazujemy obiekt `value`. `x.number` zostało wcześniej zmodyfikowane do `20`, więc `x.number *= 2` loguje `40`. + +

+
+ +--- + +###### 65. Jaki jest wynik? + +```javascript +[1, 2, 3, 4].reduce((x, y) => console.log(x, y)); +``` + +- A: `1` `2` and `3` `3` and `6` `4` +- B: `1` `2` and `2` `3` and `3` `4` +- C: `1` `undefined` and `2` `undefined` and `3` `undefined` and `4` `undefined` +- D: `1` `2` and `undefined` `3` and `undefined` `4` + +
Odpowiedź +

s + +#### Odpowiedź: D + +Pierwszym argumentem, który otrzymuje metoda `reduce` jest _accumulator_, w tym przypadku `x`. Drugim argumentem jest _bieżąca wartość_, `y`. Za pomocą metody reduce wykonujemy funkcję wywołania zwrotnego na każdym elemencie tablicy, co ostatecznie może skutkować jedną wartością. W tym przykładzie nie zwracamy żadnych wartości, po prostu rejestrujemy wartości akumulatora i wartości bieżącej. + +Wartość akumulatora jest równa poprzednio zwróconej wartości funkcji zwrotnej. Jeśli nie przekażesz opcjonalnego argumentu `initialValue` do metody `reduce`, akumulator jest równy pierwszemu elementowi przy pierwszym wywołaniu. + +Przy pierwszym wywołaniu, wartość akumulatora (`x`) wynosi `1`, a wartość bieżąca (`y`) wynosi `2`. Nie wracamy z funkcji zwrotnej, rejestrujemy akumulator i bieżącą wartość: `1` i `2` są rejestrowane. + +Jeśli nie zwrócisz wartości z funkcji, zwróci ona `undefined`. Przy następnym wywołaniu, akumulatorem jest `undefined`, a bieżącą wartością jest `3`. `undefined` i `3` są rejestrowane. + +Przy czwartym wywołaniu ponownie nie wracamy z funkcji zwrotnej. Akumulator jest ponownie `undefined`, a aktualna wartość to `4`. `undefined` i `4` są rejestrowane. + +

+
+ +--- + +###### 66. Za pomocą którego konstruktora możemy z powodzeniem rozszerzyć klasę `Dog`? + +```javascript +class Dog { + constructor(name) { + this.name = name; + } +}; + +class Labrador extends Dog { + // 1 + constructor(name, size) { + this.size = size; + } + // 2 + constructor(name, size) { + super(name); + this.size = size; + } + // 3 + constructor(size) { + super(name); + this.size = size; + } + // 4 + constructor(name, size) { + this.name = name; + this.size = size; + } + +}; +``` + +- A: 1 +- B: 2 +- C: 3 +- D: 4 + +
Odpowiedź +

+ +#### Odpowiedź: B + +W klasie pochodnej nie można uzyskać dostępu do słowa kluczowego `this` przed wywołaniem `super`. Jeśli spróbujesz to zrobić, zostanie wyświetlony ReferenceError: 1 i 4 wyrzuci błąd referencji. + +Za pomocą słowa kluczowego `super` wywołujemy konstruktor klasy nadrzędnej z podanymi argumentami. Konstruktor rodzica otrzymuje argument `name`, więc musimy przekazać `name` do `super`. + +Klasa `Labrador` otrzymuje dwa argumenty, `name` ponieważ rozszerza klasę `Dog`, oraz `size` jako dodatkową właściwość klasy `Labrador`. Oba muszą być przekazane do funkcji konstruktora na `Labrador`, co jest zrobione poprawnie przy użyciu konstruktora 2. + +

+
+ +--- + +###### 67. Jaki jest wynik? + +```javascript +// index.js +console.log('running index.js'); +import { sum } from './sum.js'; +console.log(sum(1, 2)); + +// sum.js +console.log('running sum.js'); +export const sum = (a, b) => a + b; +``` + +- A: `running index.js`, `running sum.js`, `3` +- B: `running sum.js`, `running index.js`, `3` +- C: `running sum.js`, `3`, `running index.js` +- D: `running index.js`, `undefined`, `running sum.js` + +
Odpowiedź +

+ +#### Odpowiedź: B + +Ze słowem kluczowym `import`, wszystkie zaimportowane moduły są _pre-parsed_. Oznacza to, że zaimportowane moduły są uruchamiane _najpierw_, a kod w pliku, który importuje moduł jest wykonywany _potem_. + +Jest to różnica pomiędzy `require()` w CommonJS i `import`! +Dzięki `require()` można ładować zależności na żądanie podczas wykonywania kodu. Jeśli użylibyśmy `require` zamiast `import`, w konsoli zostałoby wyświetlone `running index.js`, `running sum.js`, `3`. + +

+
+ +--- + +###### 68. Jaki jest wynik? + +```javascript +console.log(Number(2) === Number(2)); +console.log(Boolean(false) === Boolean(false)); +console.log(Symbol('foo') === Symbol('foo')); +``` + +- A: `true`, `true`, `false` +- B: `false`, `true`, `false` +- C: `true`, `false`, `true` +- D: `true`, `true`, `true` + +
Odpowiedź +

+ +#### Odpowiedź: A + +Każdy Symbol jest całkowicie unikalny. Celem argumentu przekazywanego do Symbolu jest nadanie Symbolowi opisu. Wartość Symbolu nie zależy od przekazanego argumentu. Testując równość, tworzymy dwa zupełnie nowe symbole: pierwszy `Symbol('foo')` i drugi `Symbol('foo')`. Te dwie wartości są unikalne i nie są sobie równe, `Symbol('foo') == Symbol('foo')` zwraca `false`. + +

+
+ +--- + +###### 69. Jaki jest wynik? + +```javascript +const name = 'Lydia Hallie'; +console.log(name.padStart(13)); +console.log(name.padStart(2)); +``` + +- A: `"Lydia Hallie"`, `"Lydia Hallie"` +- B: `" Lydia Hallie"`, `" Lydia Hallie"` (`"[13x whitespace]Lydia Hallie"`, `"[2x whitespace]Lydia Hallie"`) +- C: `" Lydia Hallie"`, `"Lydia Hallie"` (`"[1x whitespace]Lydia Hallie"`, `"Lydia Hallie"`) +- D: `"Lydia Hallie"`, `"Lyd"`, + +
Odpowiedź +

+ +#### Odpowiedź: C + +Za pomocą metody `padStart` możemy dodać dopełnienie na początku ciągu znaków. Wartością przekazywaną do tej metody jest _całkowita_ długość łańcucha wraz z dopełnieniem. Ciąg `"Lydia Hallie"` ma długość `12`. Metoda `name.padStart(13)` wstawia 1 spację na początku łańcucha, ponieważ 12 + 1 to 13. + +Jeśli argument przekazany do metody `padStart` jest mniejszy niż długość tablicy, dopełnienie nie zostanie dodane. + +

+
+ +--- + +###### 70. Jaki jest wynik? + +```javascript +console.log('🥑' + '💻'); +``` + +- A: `"🥑💻"` +- B: `257548` +- C: A string containing their code points +- D: Error + +
Odpowiedź +

+ +#### Odpowiedź: A + +Za pomocą operatora `+` można łączyć ciągi znaków. W tym przypadku łączymy ciąg `"🥑"` z ciągiem `"💻"`, otrzymując `"🥑💻"`. +

\ No newline at end of file From 5305be3008a9f30b62512203d3f82d71c282c053 Mon Sep 17 00:00:00 2001 From: Lukasz Jasionowski Date: Fri, 27 Oct 2023 10:58:04 +0200 Subject: [PATCH 189/193] Add 5 translated questions | Total translated: 75 --- pl-PL/README.md | 164 ++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 164 insertions(+) diff --git a/pl-PL/README.md b/pl-PL/README.md index 02bfc687..ef1c71d6 100644 --- a/pl-PL/README.md +++ b/pl-PL/README.md @@ -2223,5 +2223,169 @@ console.log('🥑' + '💻'); Za pomocą operatora `+` można łączyć ciągi znaków. W tym przypadku łączymy ciąg `"🥑"` z ciągiem `"💻"`, otrzymując `"🥑💻"`. +

+
+ +--- + +###### 71. Jak możemy rejestrować wartości, które są komentowane po instrukcji console.log? + +```javascript +function* startGame() { + const answer = yield 'Do you love JavaScript?'; + if (answer !== 'Yes') { + return "Oh wow... Guess we're done here"; + } + return 'JavaScript loves you back ❤️'; +} + +const game = startGame(); +console.log(/* 1 */); // Do you love JavaScript? +console.log(/* 2 */); // JavaScript loves you back ❤️ +``` + +- A: `game.next("Yes").value` and `game.next().value` +- B: `game.next.value("Yes")` and `game.next.value()` +- C: `game.next().value` and `game.next("Yes").value` +- D: `game.next.value()` and `game.next.value("Yes")` + +
Odpowiedź +

+ +#### Odpowiedź: C + +Funkcja generatora "wstrzymuje" swoje wykonanie, gdy widzi słowo kluczowe `yield`. Najpierw musimy pozwolić funkcji na wygenerowanie ciągu "Do you love JavaScript?", co można zrobić poprzez wywołanie `game.next().value`. + +Każda linia jest wykonywana, dopóki nie znajdzie pierwszego słowa kluczowego `yield`. W pierwszej linii funkcji znajduje się słowo kluczowe `yield`: wykonywanie zatrzymuje się wraz z pierwszym yield! Oznacza to, że zmienna `answer` nie jest jeszcze zdefiniowana! + +Kiedy wywołamy `game.next("Yes").value`, poprzedni `yield` zostanie zastąpiony wartością parametrów przekazanych do funkcji `next()`, w tym przypadku `"Yes``. Wartość zmiennej `answer` jest teraz równa `"Yes"`. Warunek instrukcji if zwraca `false`, a `JavaScript loves you back ❤️` zostaje zalogowany. + +

+
+ +--- + +###### 72. Jaki jest wynik? + +```javascript +console.log(String.raw`Hello\nworld`); +``` + +- A: `Hello world!` +- B: `Hello`
     `world` +- C: `Hello\nworld` +- D: `Hello\n`
     `world` + +
Odpowiedź +

+ +#### Odpowiedź: C + +`String.raw` zwraca ciąg znaków, w którym znaki specjalne (`\n`, `\v`, `\t` itd.) są ignorowane! Backslashe mogą być problemem, ponieważ można skończyć z czymś takim jak:`` const path = `C:\Documents\Projects\table.html` `` + +Co skutkowałoby: + +`"C:DocumentsProjects able.html"`Z `String.raw`, po prostu zignorowałby ucieczkę i wyświetliłby: + +`C:\Documents\Projects\table.html`. + +W tym przypadku ciąg to `Hello\nworld`, który zostanie wyświetlony. + +

+
+ +--- + +###### 73. Jaki jest wynik? + +```javascript +async function getData() { + return await Promise.resolve('I made it!'); +} + +const data = getData(); +console.log(data); +``` + +- A: `"I made it!"` +- B: `Promise {: "I made it!"}` +- C: `Promise {}` +- D: `undefined` + +
Odpowiedź +

+ +#### Odpowiedź: C + +Funkcja asynchroniczna zawsze zwraca obietnicę. Funkcja `await` wciąż musi czekać na rozwiązanie obietnicy: oczekująca obietnica zostanie zwrócona, gdy wywołamy `getData()` w celu ustawienia `data` równym tej obietnicy. + +Jeśli chcielibyśmy uzyskać dostęp do rozwiązanej wartości `"I made it"`, moglibyśmy użyć metody `.then()` na `data`:`data.then(res => console.log(res))`. + +To wyświtliłoby w konsoli `"Udało mi się!"`. + +

+
+ +--- + +###### 74. Jaki jest wynik? + +```javascript +function addToList(item, list) { + return list.push(item); +} + +const result = addToList('apple', ['banana']); +console.log(result); +``` + +- A: `['apple', 'banana']` +- B: `2` +- C: `true` +- D: `undefined` + +
Odpowiedź +

+ +#### Odpowiedź: B + +Metoda `.push()` zwraca _długość_ nowej tablicy! Poprzednio tablica zawierała jeden element (string `"banan"`) i miała długość `1`. Po dodaniu stringa `"apple"` do tablicy, tablica zawiera dwa elementy i ma długość `2`. Jest to zwracane przez funkcję `addToList`. Metoda `push` modyfikuje oryginalną tablicę. + +Jeśli chciałeś zwrócić _array_ z funkcji, a nie _length of the array_, powinieneś był zwrócić `list` po dodaniu do niej `item`. + +

+
+ +--- + +###### 75. Jaki jest wynik? + +```javascript +const box = { x: 10, y: 20 }; + +Object.freeze(box); + +const shape = box; +shape.x = 100; + +console.log(shape); +``` + +- A: `{ x: 100, y: 20 }` +- B: `{ x: 10, y: 20 }` +- C: `{ x: 100 }` +- D: `ReferenceError` + +
Odpowiedź +

+ +#### Odpowiedź: B + +`Object.freeze` uniemożliwia dodawanie, usuwanie lub modyfikowanie właściwości obiektu (chyba że wartością właściwości jest inny obiekt). + +Kiedy tworzymy zmienną `shape` i ustawiamy ją jako równą zamrożonemu obiektowi `box`, `shape` również odnosi się do zamrożonego obiektu. Możesz sprawdzić czy obiekt jest zamrożony używając `Object.isFrozen`. W tym przypadku, `Object.isFrozen(shape)` zwróciłby true, ponieważ zmienna `shape` posiada referencję do zamrożonego obiektu. + +Ponieważ `shape` jest zamrożony, a wartość `x` nie jest obiektem, nie możemy modyfikować właściwości `x`.`x` jest nadal równe `10`, a `{ x: 10, y: 20 }` zostaje wyświetlone w konsoli. +

\ No newline at end of file From 7d529663e346113a3827b4d3dac491a97ee83262 Mon Sep 17 00:00:00 2001 From: Gustavo Iha Date: Mon, 27 Nov 2023 13:36:48 -0300 Subject: [PATCH 190/193] docs: make question 3 explanation more comprehensive --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index ba440c7c..3e75bae8 100644 --- a/README.md +++ b/README.md @@ -142,7 +142,7 @@ Note that the value of `diameter` is a regular function, whereas the value of `p With arrow functions, the `this` keyword refers to its current surrounding scope, unlike regular functions! This means that when we call `perimeter`, it doesn't refer to the shape object, but to its surrounding scope (window for example). -There is no value `radius` on that object, which returns `NaN`. +Since there is no value `radius` in the scope of the arrow function, `this.radius` returns `undefined` which, when multiplied by `2 * Math.PI`, results in `NaN`.

From 06de0f48d19af990e0abc03672db8c135683828e Mon Sep 17 00:00:00 2001 From: Alexander Krikunov Date: Mon, 4 Dec 2023 15:18:47 +0300 Subject: [PATCH 191/193] 133 clarification For me it was unclear why "Promise 2" is printed before "Promise 1". --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index ba440c7c..708299b9 100644 --- a/README.md +++ b/README.md @@ -4356,13 +4356,13 @@ funcTwo(); First, we invoke `funcOne`. On the first line of `funcOne`, we call the _asynchronous_ `setTimeout` function, from which the callback is sent to the Web API. (see my article on the event loop here.) -Then we call the `myPromise` promise, which is an _asynchronous_ operation. +Then we call the `myPromise` promise, which is an _asynchronous_ operation. Pay attention, that now only the first then clause was added to the microtask queue. Both the promise and the timeout are asynchronous operations, the function keeps on running while it's busy completing the promise and handling the `setTimeout` callback. This means that `Last line 1!` gets logged first, since this is not an asynchonous operation. Since the callstack is not empty yet, the `setTimeout` function and promise in `funcOne` cannot get added to the callstack yet. -In `funcTwo`, the variable `res` gets `Promise` because `Promise.resolve(Promise.resolve('Promise'))` is equivalent to `Promise.resolve('Promise')` since resolving a promise just resolves it's value. The `await` in this line stops the execution of the function until it receives the resolution of the promise and then keeps on running synchronously until completion, so `Promise 2!` and then `Last line 2!` are logged and the `setTimeout` is sent to the Web API. +In `funcTwo`, the variable `res` gets `Promise` because `Promise.resolve(Promise.resolve('Promise'))` is equivalent to `Promise.resolve('Promise')` since resolving a promise just resolves it's value. The `await` in this line stops the execution of the function until it receives the resolution of the promise and then keeps on running synchronously until completion, so `Promise 2!` and then `Last line 2!` are logged and the `setTimeout` is sent to the Web API. If the first then clause in `funcOne` had its own log statement, it would be printed before `Promise 2!`. Howewer, it executed silently and put the second then clause in microtask queue. So, the second clause will be printed after `Promise 2!`. Then the call stack is empty. Promises are _microtasks_ so they are resolved first when the call stack is empty so `Promise 1!` gets to be logged. From 73a534df457ef216acc7dcad4b48d08dfa367e7d Mon Sep 17 00:00:00 2001 From: Abbas Roholamin Date: Sat, 3 Feb 2024 23:20:45 +0430 Subject: [PATCH 192/193] Update README.md Fixing the typos and grammar mistakes --- README.md | 62 +++++++++++++++++++++++++++---------------------------- 1 file changed, 31 insertions(+), 31 deletions(-) diff --git a/README.md b/README.md index ba440c7c..4cb8dd0a 100644 --- a/README.md +++ b/README.md @@ -4,12 +4,12 @@ > [!NOTE] -> This repo was created in 2019 and the questions provided here are therefore based on the JavaScript syntax and behaviour at that time. Since JavaScript is a constantly evolving language, there are newer language features that are not covered by the questions here. +> This repo was created in 2019 and the questions provided here are therefore based on the JavaScript syntax and behavior at that time. Since JavaScript is a constantly evolving language, there are newer language features that are not covered by the questions here. ---

-From basic to advanced: test how well you know JavaScript, refresh your knowledge a bit, or prepare for your coding interview! :muscle: :rocket: I update this repo regularly with new questions. I added the answers in the **collapsed sections** below the questions, simply click on them to expand it. It's just for fun, good luck! :heart:

+From basic to advanced: test how well you know JavaScript, refresh your knowledge a bit or prepare for your coding interview! :muscle: :rocket: I update this repo regularly with new questions. I added the answers in the **collapsed sections** below the questions, simply click on them to expand it. It's just for fun, good luck! :heart:

Feel free to reach out to me! 😊

@@ -167,7 +167,7 @@ There is no value `radius` on that object, which returns `NaN`. The unary plus tries to convert an operand to a number. `true` is `1`, and `false` is `0`. -The string `'Lydia'` is a truthy value. What we're actually asking, is "is this truthy value falsy?". This returns `false`. +The string `'Lydia'` is a truthy value. What we're actually asking, is "Is this truthy value falsy?". This returns `false`.

@@ -690,7 +690,7 @@ const sum = eval('10*10+5'); #### Answer: A -`eval` evaluates codes that's passed as a string. If it's an expression, like in this case, it evaluates the expression. The expression is `10 * 10 + 5`. This returns the number `105`. +`eval` evaluates code that's passed as a string. If it's an expression, like in this case, it evaluates the expression. The expression is `10 * 10 + 5`. This returns the number `105`.

@@ -871,7 +871,7 @@ console.log(name.giveLydiaPizza()) #### Answer: A -`String` is a built-in constructor, which we can add properties to. I just added a method to its prototype. Primitive strings are automatically converted into a string object, generated by the string prototype function. So, all strings (string objects) have access to that method! +`String` is a built-in constructor, that we can add properties to. I just added a method to its prototype. Primitive strings are automatically converted into a string object, generated by the string prototype function. So, all strings (string objects) have access to that method!

@@ -1014,7 +1014,7 @@ The deepest nested element that caused the event is the target of the event. You #### Answer: A -If we click `p`, we see two logs: `p` and `div`. During event propagation, there are 3 phases: capturing, target, and bubbling. By default, event handlers are executed in the bubbling phase (unless you set `useCapture` to `true`). It goes from the deepest nested element outwards. +If we click `p`, we see two logs: `p` and `div`. During event propagation, there are 3 phases: capturing, targeting, and bubbling. By default, event handlers are executed in the bubbling phase (unless you set `useCapture` to `true`). It goes from the deepest nested element outwards.

@@ -1227,7 +1227,7 @@ JavaScript only has primitive types and objects. Primitive types are `boolean`, `null`, `undefined`, `bigint`, `number`, `string`, and `symbol`. -What differentiates a primitive from an object is that primitives do not have any properties or methods; however, you'll note that `'foo'.toUpperCase()` evaluates to `'FOO'` and does not result in a `TypeError`. This is because when you try to access a property or method on a primitive like a string, JavaScript will implicitly wrap the primitive type using one of the wrapper classes, i.e. `String`, and then immediately discard the wrapper after the expression evaluates. All primitives except for `null` and `undefined` exhibit this behaviour. +What differentiates a primitive from an object is that primitives do not have any properties or methods; however, you'll note that `'foo'.toUpperCase()` evaluates to `'FOO'` and does not result in a `TypeError`. This is because when you try to access a property or method on a primitive like a string, JavaScript will implicitly wrap the primitive type using one of the wrapper classes, i.e. `String`, and then immediately discard the wrapper after the expression evaluates. All primitives except for `null` and `undefined` exhibit this behavior.

@@ -1517,7 +1517,7 @@ const num = parseInt('7*6', 10); #### Answer: C -Only the first numbers in the string is returned. Based on the _radix_ (the second argument in order to specify what type of number we want to parse it to: base 10, hexadecimal, octal, binary, etc.), the `parseInt` checks whether the characters in the string are valid. Once it encounters a character that isn't a valid number in the radix, it stops parsing and ignores the following characters. +Only the first number in the string is returned. Based on the _radix_ (the second argument in order to specify what type of number we want to parse it to: base 10, hexadecimal, octal, binary, etc.), the `parseInt` checks whether the characters in the string are valid. Once it encounters a character that isn't a valid number in the radix, it stops parsing and ignores the following characters. `*` is not a valid number. It only parses `"7"` into the decimal `7`. `num` now holds the value of `7`. @@ -1688,7 +1688,7 @@ y = 10; let x = y; ``` -When we set `y` equal to `10`, we actually add a property `y` to the global object (`window` in browser, `global` in Node). In a browser, `window.y` is now equal to `10`. +When we set `y` equal to `10`, we actually add a property `y` to the global object (`window` in the browser, `global` in Node). In a browser, `window.y` is now equal to `10`. Then, we declare a variable `x` with the value of `y`, which is `10`. Variables declared with the `let` keyword are _block scoped_, they are only defined within the block they're declared in; the immediately invoked function expression (IIFE) in this case. When we use the `typeof` operator, the operand `x` is not defined: we are trying to access `x` outside of the block it's declared in. This means that `x` is not defined. Values who haven't been assigned a value or declared are of type `"undefined"`. `console.log(typeof x)` returns `"undefined"`. @@ -1823,7 +1823,7 @@ console.log(delete age); #### Answer: A -The `delete` operator returns a boolean value: `true` on a successful deletion, else it'll return `false`. However, variables declared with the `var`, `const` or `let` keyword cannot be deleted using the `delete` operator. +The `delete` operator returns a boolean value: `true` on a successful deletion, else it'll return `false`. However, variables declared with the `var`, `const`, or `let` keywords cannot be deleted using the `delete` operator. The `name` variable was declared with a `const` keyword, so its deletion is not successful: `false` is returned. When we set `age` equal to `21`, we actually added a property called `age` to the global object. You can successfully delete properties from objects this way, also the global object, so `delete age` returns `true`. @@ -1989,7 +1989,7 @@ console.log(num2); #### Answer: A -The unary operator `++` _first returns_ the value of the operand, _then increments_ the value of the operand. The value of `num1` is `10`, since the `increaseNumber` function first returns the value of `num`, which is `10`, and only increments the value of `num` afterwards. +The unary operator `++` _first returns_ the value of the operand, _then increments_ the value of the operand. The value of `num1` is `10`, since the `increaseNumber` function first returns the value of `num`, which is `10`, and only increments the value of `num` afterward. `num2` is `10`, since we passed `num1` to the `increasePassedNumber`. `number` is equal to `10`(the value of `num1`). Again, the unary operator `++` _first returns_ the value of the operand, _then increments_ the value of the operand. The value of `number` is `10`, so `num2` is equal to `10`. @@ -2058,7 +2058,7 @@ In this example, we are not returning any values, we are simply logging the valu The value of the accumulator is equal to the previously returned value of the callback function. If you don't pass the optional `initialValue` argument to the `reduce` method, the accumulator is equal to the first element on the first call. -On the first call, the accumulator (`x`) is `1`, and the current value (`y`) is `2`. We don't return from the callback function, we log the accumulator and current value: `1` and `2` get logged. +On the first call, the accumulator (`x`) is `1`, and the current value (`y`) is `2`. We don't return from the callback function, we log the accumulator, and the current values: `1` and `2` get logged. If you don't return a value from a function, it returns `undefined`. On the next call, the accumulator is `undefined`, and the current value is `3`. `undefined` and `3` get logged. @@ -2146,9 +2146,9 @@ export const sum = (a, b) => a + b; #### Answer: B -With the `import` keyword, all imported modules are _pre-parsed_. This means that the imported modules get run _first_, the code in the file which imports the module gets executed _after_. +With the `import` keyword, all imported modules are _pre-parsed_. This means that the imported modules get run _first_, and the code in the file that imports the module gets executed _after_. -This is a difference between `require()` in CommonJS and `import`! With `require()`, you can load dependencies on demand while the code is being run. If we would have used `require` instead of `import`, `running index.js`, `running sum.js`, `3` would have been logged to the console. +This is a difference between `require()` in CommonJS and `import`! With `require()`, you can load dependencies on demand while the code is being run. If we had used `require` instead of `import`, `running index.js`, `running sum.js`, `3` would have been logged to the console.

@@ -2454,7 +2454,7 @@ console.log(name); // ReferenceError: name is not defined ----- NodeJS Whenever Javascript is unable to find a variable within the _current scope_, it climbs up the [Scope chain](https://github.com/getify/You-Dont-Know-JS/blob/2nd-ed/scope-closures/ch3.md) and searches for it and if it reaches the top-level scope, aka **Global scope**, and still doesn't find it, it will throw a `ReferenceError`. -- In **Browsers** such as _Chrome_, `name` is a _deprecated global scope property_. In this example, the code is running inside _global scope_ and there is no user defined local variable for `name`, therefore it searches the predefined _variables/properties_ in the global scope which is in case of browsers, it searches through `window` object and it will extract the [window.name](https://developer.mozilla.org/en-US/docs/Web/API/Window/name) value which is equal to an **empty string**. +- In **Browsers** such as _Chrome_, `name` is a _deprecated global scope property_. In this example, the code is running inside _global scope_ and there is no user-defined local variable for `name`, therefore it searches the predefined _variables/properties_ in the global scope which is in the case of browsers, it searches through `window` object and it will extract the [window.name](https://developer.mozilla.org/en-US/docs/Web/API/Window/name) value which is equal to an **empty string**. - In **NodeJS**, there is no such property on the `global` object, thus attempting to access a non-existent variable will raise a [ReferenceError](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/Not_defined). @@ -2522,7 +2522,7 @@ console.log(addFunction(5 * 2)); The `add` function is a _memoized_ function. With memoization, we can cache the results of a function in order to speed up its execution. In this case, we create a `cache` object that stores the previously returned values. -If we call the `addFunction` function again with the same argument, it first checks whether it has already gotten that value in its cache. If that's the case, the caches value will be returned, which saves on execution time. Else, if it's not cached, it will calculate the value and store it afterwards. +If we call the `addFunction` function again with the same argument, it first checks whether it has already gotten that value in its cache. If that's the case, the cache value will be returned, which saves execution time. Otherwise, if it's not cached, it will calculate the value and store it afterward. We call the `addFunction` function three times with the same value: on the first invocation, the value of the function when `num` is equal to `10` isn't cached yet. The condition of the if-statement `num in cache` returns `false`, and the else block gets executed: `Calculated! 20` gets logged, and the value of the result gets added to the cache object. `cache` now looks like `{ 10: 20 }`. @@ -2733,7 +2733,7 @@ console.log(checkAge(21)); #### Answer: C -Variables with the `const` and `let` keyword are _block-scoped_. A block is anything between curly brackets (`{ }`). In this case, the curly brackets of the if/else statements. You cannot reference a variable outside of the block it's declared in, a ReferenceError gets thrown. +Variables with the `const` and `let` keywords are _block-scoped_. A block is anything between curly brackets (`{ }`). In this case, the curly brackets of the if/else statements. You cannot reference a variable outside of the block it's declared in, a ReferenceError gets thrown.

@@ -2783,7 +2783,7 @@ function getName(name) { #### Answer: A -With `!!name`, we determine whether the value of `name` is truthy or falsy. If name is truthy, which we want to test for, `!name` returns `false`. `!false` (which is what `!!name` practically is) returns `true`. +With `!!name`, we determine whether the value of `name` is truthy or falsy. If the name is truthy, which we want to test for, `!name` returns `false`. `!false` (which is what `!!name` practically is) returns `true`. By setting `hasName` equal to `name`, you set `hasName` equal to whatever value you passed to the `getName` function, not the boolean value `true`. @@ -2843,7 +2843,7 @@ sum(10); You can set a default parameter's value equal to another parameter of the function, as long as they've been defined _before_ the default parameter. We pass the value `10` to the `sum` function. If the `sum` function only receives 1 argument, it means that the value for `num2` is not passed, and the value of `num1` is equal to the passed value `10` in this case. The default value of `num2` is the value of `num1`, which is `10`. `num1 + num2` returns `20`. -If you're trying to set a default parameter's value equal to a parameter which is defined _after_ (to the right), the parameter's value hasn't been initialized yet, which will throw an error. +If you're trying to set a default parameter's value equal to a parameter that is defined _after_ (to the right), the parameter's value hasn't been initialized yet, which will throw an error.

@@ -2873,7 +2873,7 @@ console.log(data); #### Answer: A -With the `import * as name` syntax, we import _all exports_ from the `module.js` file into the `index.js` file as a new object called `data` is created. In the `module.js` file, there are two exports: the default export, and a named export. The default export is a function which returns the string `"Hello World"`, and the named export is a variable called `name` which has the value of the string `"Lydia"`. +With the `import * as name` syntax, we import _all exports_ from the `module.js` file into the `index.js` file as a new object called `data` is created. In the `module.js` file, there are two exports: the default export, and a named export. The default export is a function that returns the string `"Hello World"`, and the named export is a variable called `name` which has the value of the string `"Lydia"`. The `data` object has a `default` property for the default export, other properties have the names of the named exports and their corresponding values. @@ -3216,7 +3216,7 @@ console.log(name()); #### Answer: C -The variable `name` holds the value of a string, which is not a function, thus cannot invoke. +The variable `name` holds the value of a string, which is not a function, and thus cannot be invoked. TypeErrors get thrown when a value is not of the expected type. JavaScript expected `name` to be a function since we're trying to invoke it. It was a string however, so a TypeError gets thrown: name is not a function! @@ -3320,7 +3320,7 @@ secondFunction(); With a promise, we basically say _I want to execute this function, but I'll put it aside for now while it's running since this might take a while. Only when a certain value is resolved (or rejected), and when the call stack is empty, I want to use this value._ -We can get this value with both `.then` and the `await` keyword in an `async` function. Although we can get a promise's value with both `.then` and `await`, they work a bit differently. +We can get this value with both `.then` and the `await` keywords in an `async` function. Although we can get a promise's value with both `.then` and `await`, they work a bit differently. In the `firstFunction`, we (sort of) put the myPromise function aside while it was running, but continued running the other code, which is `console.log('second')` in this case. Then, the function resolved with the string `I have resolved`, which then got logged after it saw that the callstack was empty. @@ -3773,7 +3773,7 @@ myMap.get(() => 'greeting'); When adding a key/value pair using the `set` method, the key will be the value of the first argument passed to the `set` function, and the value will be the second argument passed to the `set` function. The key is the _function_ `() => 'greeting'` in this case, and the value `'Hello world'`. `myMap` is now `{ () => 'greeting' => 'Hello world!' }`. 1 is wrong, since the key is not `'greeting'` but `() => 'greeting'`. -3 is wrong, since we're creating a new function by passing it as a parameter to the `get` method. Object interact by _reference_. Functions are objects, which is why two functions are never strictly equal, even if they are identical: they have a reference to a different spot in memory. +3 is wrong, since we're creating a new function by passing it as a parameter to the `get` method. Object interacts by _reference_. Functions are objects, which is why two functions are never strictly equal, even if they are identical: they have a reference to a different spot in memory.

@@ -3908,7 +3908,7 @@ With the optional chaining operator `?.`, we no longer have to explicitly check `person.pet?.name`: `person` has a property named `pet`: `person.pet` is not nullish. It has a property called `name`, and returns `Mara`. `person.pet?.family?.name`: `person` has a property named `pet`: `person.pet` is not nullish. `pet` does _not_ have a property called `family`, `person.pet.family` is nullish. The expression returns `undefined`. `person.getFullName?.()`: `person` has a property named `getFullName`: `person.getFullName()` is not nullish and can get invoked, which returns `Lydia Hallie`. -`member.getLastName?.()`: variable `member` is non existent therefore a `ReferenceError` gets thrown! +`member.getLastName?.()`: variable `member` is non-existent therefore a `ReferenceError` gets thrown!

@@ -4455,13 +4455,13 @@ person.name; #### Answer: C -With a Proxy object, we can add custom behavior to an object that we pass to it as the second argument. In this case, we pass the `handler` object which contained two properties: `set` and `get`. `set` gets invoked whenever we _set_ property values, `get` gets invoked whenever we _get_ (access) property values. +With a Proxy object, we can add custom behavior to an object that we pass to it as the second argument. In this case, we pass the `handler` object which contains two properties: `set` and `get`. `set` gets invoked whenever we _set_ property values, and `get` gets invoked whenever we _get_ (access) property values. The first argument is an empty object `{}`, which is the value of `person`. To this object, the custom behavior specified in the `handler` object gets added. If we add a property to the `person` object, `set` will get invoked. If we access a property on the `person` object, `get` gets invoked. First, we added a new property `name` to the proxy object (`person.name = "Lydia"`). `set` gets invoked, and logs `"Added a new property!"`. -Then, we access a property value on the proxy object, the `get` property on the handler object got invoked. `"Accessed a property!"` gets logged. +Then, we access a property value on the proxy object, and the `get` property on the handler object is invoked. `"Accessed a property!"` gets logged.

@@ -4550,7 +4550,7 @@ myFunc(3); #### Answer: A -First, we invoked `myFunc()` without passing any arguments. Since we didn't pass arguments, `num` and `value` got their default values: num is `2`, and `value` the returned value of the function `add`. To the `add` function, we pass `num` as an argument, which had the value of `2`. `add` returns `4`, which is the value of `value`. +First, we invoked `myFunc()` without passing any arguments. Since we didn't pass arguments, `num` and `value` got their default values: num is `2`, and `value` is the returned value of the function `add`. To the `add` function, we pass `num` as an argument, which had the value of `2`. `add` returns `4`, which is the value of `value`. Then, we invoked `myFunc(3)` and passed the value `3` as the value for the argument `num`. We didn't pass an argument for `value`. Since we didn't pass a value for the `value` argument, it got the default value: the returned value of the `add` function. To `add`, we pass `num`, which has the value of `3`. `add` returns `6`, which is the value of `value`. @@ -4590,7 +4590,7 @@ console.log(counter.#number) #### Answer: D -In ES2020, we can add private variables in classes by using the `#`. We cannot access these variables outside of the class. When we try to log `counter.#number`, a SyntaxError gets thrown: we cannot acccess it outside the `Counter` class! +In ES2020, we can add private variables in classes by using the `#`. We cannot access these variables outside of the class. When we try to log `counter.#number`, a SyntaxError gets thrown: we cannot access it outside the `Counter` class!

@@ -5048,7 +5048,7 @@ runPromises() #### Answer: D -The `Promise.all` method runs the passed promises in parallel. If one promise fails, the `Promise.all` method _rejects_ with the value of the rejected promise. In this case, `promise3` rejected with the value `"Third"`. We’re catching the rejected value in the chained `catch` method on the `runPromises` invocation to catch any errors within the `runPromises` function. Only `"Third"` gets logged, since `promise3` rejected with this value. +The `Promise.all` method runs the passed promises in parallel. If one promise fails, the `Promise.all` method _rejects_ with the value of the rejected promise. In this case, `promise3` is rejected with the value `"Third"`. We’re catching the rejected value in the chained `catch` method on the `runPromises` invocation to catch any errors within the `runPromises` function. Only `"Third"` gets logged, since `promise3` is rejected with this value.

@@ -5077,7 +5077,7 @@ Object[method](keys.map((_, i) => { #### Answer: C -The `fromEntries` method turns a 2d array into an object. The first element in each subarray will be the key, and the second element in each subarray will be the value. In this case, we’re mapping over the `keys` array, which returns an array which first element is the item on the key array on the current index, and the second element is the item of the values array on the current index. +The `fromEntries` method turns a 2d array into an object. The first element in each subarray will be the key, and the second element in each subarray will be the value. In this case, we’re mapping over the `keys` array, which returns an array that the first element is the item on the key array on the current index, and the second element is the item of the values array on the current index. This creates an array of subarrays containing the correct keys and values, which results in `{ name: "Lydia", age: 22 }` @@ -5113,7 +5113,7 @@ console.log(member) #### Answer: C -The default value of `address` is an empty object `{}`. When we set the variable `member` equal to the object returned by the `createMember` function, we didn't pass a value for address, which means that the value of address is the default empty object `{}`. An empty object is a truthy value, which means that the condition of the `address ? address : null` conditional returns `true`. The value of address is the empty object `{}`. +The default value of `address` is an empty object `{}`. When we set the variable `member` equal to the object returned by the `createMember` function, we didn't pass a value for the address, which means that the value of the address is the default empty object `{}`. An empty object is a truthy value, which means that the condition of the `address ? address : null` conditional returns `true`. The value of the address is the empty object `{}`.

From d76e0320fe6391d6b7fa39b61e849e462ad106c1 Mon Sep 17 00:00:00 2001 From: singlexyz Date: Sun, 10 Mar 2024 22:44:51 +0800 Subject: [PATCH 193/193] Fix Question 147 typo. --- README.md | 2 +- id-ID/README.md | 2 +- it-IT/README.md | 2 +- ko-KR/README-ko_KR.md | 2 +- ro-RO/README.ro.md | 4 ++-- ru-RU/README.md | 2 +- sq-KS/README_sq_KS.md | 2 +- vi-VI/README-vi.md | 2 +- zh-CN/README-zh_CN.md | 2 +- zh-TW/README_zh-TW.md | 4 ++-- 10 files changed, 12 insertions(+), 12 deletions(-) diff --git a/README.md b/README.md index ba440c7c..c4f58253 100644 --- a/README.md +++ b/README.md @@ -4852,7 +4852,7 @@ class Calc { } increase() { - this.count ++ + this.count++ } } diff --git a/id-ID/README.md b/id-ID/README.md index 482955fb..2f238d06 100644 --- a/id-ID/README.md +++ b/id-ID/README.md @@ -4788,7 +4788,7 @@ class Calc { } increase() { - this.count ++ + this.count++ } } diff --git a/it-IT/README.md b/it-IT/README.md index 23d43ea2..13e465c6 100644 --- a/it-IT/README.md +++ b/it-IT/README.md @@ -4823,7 +4823,7 @@ class Calc { } increase() { - this.count ++ + this.count++ } } diff --git a/ko-KR/README-ko_KR.md b/ko-KR/README-ko_KR.md index 96d75bf7..51411b6b 100644 --- a/ko-KR/README-ko_KR.md +++ b/ko-KR/README-ko_KR.md @@ -4804,7 +4804,7 @@ class Calc { } increase() { - this.count ++ + this.count++ } } diff --git a/ro-RO/README.ro.md b/ro-RO/README.ro.md index 0907fa94..93fc1f4e 100644 --- a/ro-RO/README.ro.md +++ b/ro-RO/README.ro.md @@ -4849,7 +4849,7 @@ class Calc { } increase() { - this.count ++ + this.count++ } } @@ -5145,4 +5145,4 @@ Condiția din instrucțiunea `if` verifică dacă valoarea lui `!typeof randomVa `!typeof randomValue === "string"` întotdeauna returnează `false`, deoarece de fapt verificăm `false === "string"`. Deoarece condiția returnează `false`, blocul de cod al instrucțiunii `else` se execută, iar `Yay it's a string!` este înregistrat.

-
\ No newline at end of file +
diff --git a/ru-RU/README.md b/ru-RU/README.md index 2df08edb..ace3f67a 100644 --- a/ru-RU/README.md +++ b/ru-RU/README.md @@ -4847,7 +4847,7 @@ class Calc { } increase() { - this.count ++ + this.count++ } } diff --git a/sq-KS/README_sq_KS.md b/sq-KS/README_sq_KS.md index 19508cf7..2392abb4 100644 --- a/sq-KS/README_sq_KS.md +++ b/sq-KS/README_sq_KS.md @@ -4846,7 +4846,7 @@ class Calc { } increase() { - this.count ++ + this.count++ } } diff --git a/vi-VI/README-vi.md b/vi-VI/README-vi.md index fa974a44..f8ab661d 100644 --- a/vi-VI/README-vi.md +++ b/vi-VI/README-vi.md @@ -4785,7 +4785,7 @@ class Calc { } increase() { - this.count ++ + this.count++ } } diff --git a/zh-CN/README-zh_CN.md b/zh-CN/README-zh_CN.md index 71f0f9df..52ca1ee0 100644 --- a/zh-CN/README-zh_CN.md +++ b/zh-CN/README-zh_CN.md @@ -4785,7 +4785,7 @@ class Calc { } increase() { - this.count ++ + this.count++ } } diff --git a/zh-TW/README_zh-TW.md b/zh-TW/README_zh-TW.md index c171b62f..b6bf9c06 100644 --- a/zh-TW/README_zh-TW.md +++ b/zh-TW/README_zh-TW.md @@ -4769,7 +4769,7 @@ class Calc { } increase() { - this.count ++ + this.count++ } } @@ -5065,4 +5065,4 @@ if (!typeof randomValue === "string") { `!typeof randomValue === "string"` 總是回傳 false,因為我們實際上是在執行 `false === "string"`。因為條件回傳的是 `false`,所以 `else` 語句中的代碼塊會被執行,因此輸出 `Yay it's a string!`。

-
\ No newline at end of file +