From 218db1a8473957357a06dd27d24fc813abb9daa6 Mon Sep 17 00:00:00 2001 From: Azarias Boutin Date: Thu, 13 Jun 2019 15:30:05 +0200 Subject: [PATCH 001/915] Missing console.log Question is "what's the output" but console.log is not called --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 035ce096..8f5a893b 100644 --- a/README.md +++ b/README.md @@ -804,7 +804,7 @@ String.prototype.giveLydiaPizza = () => { const name = "Lydia"; -name.giveLydiaPizza(); +console.log(name.giveLydiaPizza()); ``` - A: `"Just give Lydia pizza already!"` From 8d4a71711f4bdcd60b874d3bdb4a303f2aee13ec Mon Sep 17 00:00:00 2001 From: Azarias Boutin Date: Thu, 13 Jun 2019 15:34:42 +0200 Subject: [PATCH 002/915] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 8f5a893b..5b742ac1 100644 --- a/README.md +++ b/README.md @@ -1006,7 +1006,7 @@ function sayHi() { return (() => 0)(); } -typeof sayHi(); +console.log(typeof sayHi()); ``` - A: `"object"` From a750ee9418c2c3c12d0eab055bc8dfb3803956ef Mon Sep 17 00:00:00 2001 From: Kiesun Date: Mon, 17 Jun 2019 15:33:21 +0800 Subject: [PATCH 003/915] fix: proofreading translation --- README-zh_CN.md | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/README-zh_CN.md b/README-zh_CN.md index 6f4ecb36..f5295966 100644 --- a/README-zh_CN.md +++ b/README-zh_CN.md @@ -393,7 +393,7 @@ console.log(sarah) #### 答案: A -对于 `sarah`,我们没有使用 `new` 关键字。当使用 `new` 时,`this` 引用我们创建的空对象。当使用了 `new`,`this` 引用的是**全局对象**(global object)。 +对于 `sarah`,我们没有使用 `new` 关键字。当使用 `new` 时,`this` 引用我们创建的空对象;当未使用 `new` 时,`this` 引用的是**全局对象**(global object)。 我们说 `this.firstName` 等于 `"Sarah"`,并且 `this.lastName` 等于 `"Smith"`。实际上我们做的是,定义了 `global.firstName = 'Sarah'` 和 `global.lastName = 'Smith'`。而 `sarah` 本身是 `undefined`。 @@ -402,7 +402,7 @@ console.log(sarah) --- -###### 13. 事件冒泡的三个阶段是什么? +###### 13. 事件传播的三个阶段是什么? - A: Target > Capturing > Bubbling - B: Bubbling > Target > Capturing @@ -529,7 +529,7 @@ getPersonInfo`${person} is ${age} years old` #### 答案: B -如果使用标记模板字面量,第一个参数的值总是字符串值的数组。其余的参数获取的是传递的表达式的值! +如果使用标记模板字面量,第一个参数的值总是包含字符串的数组。其余的参数获取的是传递的表达式的值!

@@ -1171,15 +1171,15 @@ console.log(numbers) - B: function or object - C: trick question! only objects - D: number or object -- +-
答案

#### 答案: A -JavaScript 只有原始类型和对象。 +JavaScript 只有基本类型和对象。 -原始类型包括 `boolean`, `null`, `undefined`, `bigint`, `number`, `string`, `symbol`。 +基本类型包括 `boolean`, `null`, `undefined`, `bigint`, `number`, `string`, `symbol`。

From d2224eaaf12616ca3e304c3c57d9f0a542a5c29f Mon Sep 17 00:00:00 2001 From: Seonggwon Yoon Date: Mon, 17 Jun 2019 18:42:40 +0900 Subject: [PATCH 004/915] Fix typo Signed-off-by: Seonggwon Yoon --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 2e06edad..ad45ee46 100644 --- a/README.md +++ b/README.md @@ -461,7 +461,7 @@ sum(1, "2"); #### Answer: C -JavaScript is a **dynamimcally 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. +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"`. From 7254980188e4daa911d9000238c1f98bea1f5d9a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Adri=C3=A1n?= <22575055+aguadotzn@users.noreply.github.com> Date: Mon, 17 Jun 2019 16:45:34 +0200 Subject: [PATCH 005/915] Add list of languages --- README.md | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index ad45ee46..f5bb6259 100644 --- a/README.md +++ b/README.md @@ -6,7 +6,10 @@ From basic to advanced: test how well you know JavaScript, refresh your knowledg The answers are in the collapsed sections below the questions, simply click on them to expand it. Good luck :heart: -[中文版本](./README-zh_CN.md) +--- +List of a available languages: +* 🇨🇳[中文版本](./README-zh_CN.md) +* 🇪🇸[Versión en español](./README-ES.md) --- From 4f22f11bdbeeb86c3995070ba83e788750067e84 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Adri=C3=A1n?= <22575055+aguadotzn@users.noreply.github.com> Date: Mon, 17 Jun 2019 17:01:33 +0200 Subject: [PATCH 006/915] First commit --- README-ES.md | 1296 ++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 1296 insertions(+) create mode 100644 README-ES.md diff --git a/README-ES.md b/README-ES.md new file mode 100644 index 00000000..391673e1 --- /dev/null +++ b/README-ES.md @@ -0,0 +1,1296 @@ + +# 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í! + + 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 ❤️ + +--- +Lista de lenguajes disponibles: +* 🇬🇧[English version](./README.md) +* 🇨🇳[中文版本](./README-zh_CN.md) + + +--- + +###### 1. ¿Qué devuelve la siguiente función? + +```javascript +function sayHi() { + console.log(name); + console.log(age); + var name = "Lydia"; + let age = 21; +} + +sayHi(); +``` + +- A: `Lydia` y `undefined` +- B: `Lydia` y `ReferenceError` +- C: `ReferenceError` y `21` +- D: `undefined` y `ReferenceError` + +
Answer +

+ +#### Respuesta: D + +Within the function, we first declare the `name` variable with the `var` keyword. This means that the variable gets hoisted (memory space is set up during the creation phase) with the default value of `undefined`, until we actually get to the line where we define the variable. We haven't defined the variable yet on the line where we try to log the `name` variable, so it still holds the value of `undefined`. + +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`. + +

+
+ +--- + +###### 2. ¿Qué devuelve la siguiente función? + +```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` + +
Answer +

+ +#### Respuesta: C + +Because of the event queue in JavaScript, the `setTimeout` function is called _after_ the loop has been executed. Since the variable `i` in the first loop was declared using the `var` keyword, this value was global. During the loop, we incremented the value of `i` by `1` each time, using the unary operator `++`. By the time the `setTimeout` function was invoked, `i` was equal to `3` in the first example. + +In the second loop, the variable `i` was declared using the `let` keyword: variables declared with the `let` (and `const`) keyword are block-scoped (a block is anything between `{ }`). During each iteration, `i` will have a new value, and each value is scoped inside the loop. + +

+
+ +--- + +###### 3. ¿Qué devuelve la siguiente función? + +```javascript +const shape = { + radius: 10, + diameter() { + return this.radius * 2; + }, + perimeter: () => 2 * Math.PI * this.radius +}; + +shape.diameter(); +shape.perimeter(); +``` + +- A: `20` and `62.83185307179586` +- B: `20` and `NaN` +- C: `20` and `63` +- D: `NaN` and `63` + +
Answer +

+ +#### Answer: B + +Note that the value of `diameter` is a regular function, whereas the value of `perimeter` is an arrow function. + +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 `undefined`. + +

+
+ +--- + +###### 4. What's the output? + +```javascript ++true; +!"Lydia"; +``` + +- A: `1` and `false` +- B: `false` and `NaN` +- C: `false` and `false` + +
Answer +

+ +#### Answer: A + +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`. + +

+
+ +--- + +###### 5. Which one is NOT valid? + +```javascript +const bird = { + size: "small" +}; + +const mouse = { + name: "Mickey", + small: true +}; +``` + +- A: `mouse.bird.size` +- B: `mouse[bird.size]` +- C: `mouse[bird["size"]]` +- D: All of them are valid + +
Answer +

+ +#### Answer: A + +In JavaScript, all object keys are strings (unless it's a Symbol). Even though we might not _type_ them as strings, they are always converted into strings under the hood. + +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. + +`mouse[bird.size]`: First it evaluates `bird.size`, which is `"small"`. `mouse["small"]` returns `true` + +However, with dot notation, this doesn't happen. `mouse` does not have a key called `bird`, which means that `mouse.bird` is `undefined`. Then, we ask for the `size` using dot notation: `mouse.bird.size`. Since `mouse.bird` is `undefined`, we're actually asking `undefined.size`. This isn't valid, and will throw an error similar to `Cannot read property "size" of undefined`. + +

+
+ +--- + +--- + +###### 6. What's the output? + +```javascript +let c = { greeting: "Hey!" }; +let d; + +d = c; +c.greeting = "Hello"; +console.log(d.greeting); +``` + +- A: `Hello` +- B: `undefined` +- C: `ReferenceError` +- D: `TypeError` + +
Answer +

+ +#### Answer: A + +In JavaScript, all objects interact by _reference_ when setting them equal to each other. + +First, variable `c` holds a value to an object. Later, we assign `d` with the same reference that `c` has to the object. + + + +When you change one object, you change all of them. + +

+
+ +--- + +###### 7. What's the 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` + +
Answer +

+ +#### Answer: 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`. + +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.` + +

+
+ +--- + +###### 8. What's the 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" }); +freddie.colorChange("orange"); +``` + +- A: `orange` +- B: `purple` +- C: `green` +- D: `TypeError` + +
Answer +

+ +#### 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. + +

+
+ +--- + +###### 9. What's the output? + +```javascript +let greeting; +greetign = {}; // Typo! +console.log(greetign); +``` + +- A: `{}` +- B: `ReferenceError: greetign is not defined` +- C: `undefined` + +
Answer +

+ +#### 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). + +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. + +

+
+ +--- + +###### 10. What happens when we do this? + +```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: `undefined` +- D: `ReferenceError` + +
Answer +

+ +#### Answer: A + +This is possible in JavaScript, because functions are objects! (Everything besides primitive types are objects) + +A function is a special type of object. The code you write yourself isn't the actual function. The function is an object with properties. This property is invocable. + +

+
+ +--- + +###### 11. What's the 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` + +
Answer +

+ +#### Answer: A + +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 () { + return `${this.firstName} ${this.lastName}`; +} +``` + +would have made `member.getFullName()` work. Why is this beneficial? Say that we added this method to the constructor itself. Maybe not every `Person` instance needed this method. This would waste a lot of memory space, since they would still have that property, which takes of memory space for each instance. Instead, if we only add it to the prototype, we just have it at one spot in memory, yet they all have access to it! + +

+
+ +--- + +###### 12. What's the 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` + +
Answer +

+ +#### Answer: A + +For `sarah`, we didn't use the `new` keyword. When using `new`, it refers to the new empty object we create. However, if you don't add `new` it 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`. + +

+
+ +--- + +###### 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 + +
Answer +

+ +#### Answer: 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 + +
Answer +

+ +#### Answer: B + +All objects have prototypes, except for the **base object**. 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. What's the output? + +```javascript +function sum(a, b) { + return a + b; +} + +sum(1, "2"); +``` + +- A: `NaN` +- B: `TypeError` +- C: `"12"` +- D: `3` + +
Answer +

+ +#### Answer: 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. What's the 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` + +
Answer +

+ +#### Answer: 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. What's the 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` + +
Answer +

+ +#### Answer: 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. What's the 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` + +
Answer +

+ +#### Answer: 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. What's the output? + +```javascript +function getAge(...args) { + console.log(typeof args); +} + +getAge(21); +``` + +- A: `"number"` +- B: `"array"` +- C: `"object"` +- D: `"NaN"` + +
Answer +

+ +#### Answer: C + +The spread operator (`...args`.) returns an array with arguments. An array is an object, so `typeof args` returns `"object"` + +

+
+ +--- + +###### 20. What's the output? + +```javascript +function getAge() { + "use strict"; + age = 21; + console.log(age); +} + +getAge(); +``` + +- A: `21` +- B: `undefined` +- C: `ReferenceError` +- D: `TypeError` + +
Answer +

+ +#### Answer: 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 value of `sum`? + +```javascript +const sum = eval("10*10+5"); +``` + +- A: `105` +- B: `"105"` +- C: `TypeError` +- D: `"10*10+5"` + +
Answer +

+ +#### 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`. + +

+
+ +--- + +###### 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. + +
Answer +

+ +#### Answer: 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. What's the output? + +```javascript +var num = 8; +var num = 10; + +console.log(num); +``` + +- A: `8` +- B: `10` +- C: `SyntaxError` +- D: `ReferenceError` + +
Answer +

+ +#### Answer: 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. What's the 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` + +
Answer +

+ +#### Answer: 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. What's the 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` + +
Answer +

+ +#### Answer: 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 + +
Answer +

+ +#### Answer: A + +The base execution context is the global execution context: it's what's accessible everywhere in your code. + +

+
+ +--- + +###### 27. What's the 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` + +
Answer +

+ +#### Answer: C + +The `continue` statement skips an iteration if a certain condition returns `true`. + +

+
+ +--- + +###### 28. What's the 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` + +
Answer +

+ +#### 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! + +

+
+ +--- + +###### 29. What's the 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` + +
Answer +

+ +#### Answer: 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. What's the 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` + +
Answer +

+ +#### Answer: 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. + +
Answer +

+ +#### Answer: 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` + +
Answer +

+ +#### 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. + +

+
+ +--- + +###### 33. What's the output? + +```javascript +const person = { name: "Lydia" }; + +function sayHi(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` + +
Answer +

+ +#### Answer: 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. What's the output? + +```javascript +function sayHi() { + return (() => 0)(); +} + +typeof sayHi(); +``` + +- A: `"object"` +- B: `"number"` +- C: `"function"` +- D: `"undefined"` + +
Answer +

+ +#### Answer: B + +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`, and `symbol`. `"function"` is not a type, since functions are objects, it's of type `"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 + +
Answer +

+ +#### Answer: A + +There are only six falsy values: + +- `undefined` +- `null` +- `NaN` +- `0` +- `''` (empty string) +- `false` + +Function constructors, like `new Number` and `new Boolean` are truthy. + +

+
+ +--- + +###### 36. What's the output? + +```javascript +console.log(typeof typeof 1); +``` + +- A: `"number"` +- B: `"string"` +- C: `"object"` +- D: `"undefined"` + +
Answer +

+ +#### Answer: B + +`typeof 1` returns `"number"`. +`typeof "number"` returns `"string"` + +

+
+ +--- + +###### 37. What's the 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` + +
Answer +

+ +#### Answer: 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, 7 x empty, 11]` + +depending on where you run it (it's different for every browser, node, etc.) + +

+
+ +--- + +###### 38. What's the 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` + +
Answer +

+ +#### Answer: 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 + +
Answer +

+ +#### Answer: 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 implicity wrap the object 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. What's the 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]` + +
Answer +

+ +#### Answer: 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. What's the output? + +```javascript +!!null; +!!""; +!!1; +``` + +- A: `false` `true` `false` +- B: `false` `false` `true` +- C: `false` `true` `true` +- D: `true` `true` `false` + +
Answer +

+ +#### Answer: 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? + +```javascript +setInterval(() => console.log("Hi"), 1000); +``` + +- A: a unique id +- B: the amount of milliseconds specified +- C: the passed function +- D: `undefined` + +
Answer +

+ +#### Answer: 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"]]` + +
Answer +

+ +#### Answer: A + +A string is an iterable. The spread operator maps every character of an iterable to one element. + +

+
From d2596b731aa51356463757ae78974064997e4551 Mon Sep 17 00:00:00 2001 From: karataev Date: Tue, 18 Jun 2019 12:49:53 +0700 Subject: [PATCH 007/915] Translate questions 1-10 to russian --- README_ru-RU.md | 1293 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 1293 insertions(+) create mode 100644 README_ru-RU.md diff --git a/README_ru-RU.md b/README_ru-RU.md new file mode 100644 index 00000000..131f2099 --- /dev/null +++ b/README_ru-RU.md @@ -0,0 +1,1293 @@ +# Список (продвинутых) вопросов по JavaScript + +Я ежедевно публикую вопросы по JavaScript с вариантами ответов в своем [Instagram](https://www.instagram.com/theavocoder), которые дублируются в этом репозитории. + +От азов к сложным вопросам: провеь как хорошо ты знаешь JavaScript, освежи свои знания или приготовься к собеседованию! :muscle: :rocket: Я дополняю этот репозиторий каждую неделю новыми вопросами. + +Ответы находятся в свернутой секции ниже вопросов. Просто нажми на ответ, чтобы развернуть. Удачи! :heart: + +[中文版本](./README-zh_CN.md) +[Русский](./README_ru-RU.md) + +--- + +###### 1. Что будет в консоли? + +```javascript +function sayHi() { + console.log(name); + console.log(age); + var name = "Lydia"; + let age = 21; +} + +sayHi(); +``` + +- A: `Lydia` и `undefined` +- B: `Lydia` и `ReferenceError` +- C: `ReferenceError` и `21` +- D: `undefined` и `ReferenceError` + +
Ответ +

+ +#### Ответ: D + +Внутри функции мы сперва определям переменную `name` с помощью ключевого слова `var`. Это означает, что переменная будет поднята (область памяти под переменную будет выделена во время фазы создания) со значением `undefined` по умолчанию, до тех пора пока исполнение кода не дойдет до строчки, где определяется переменная. Мы еще не определили значение `name` когда пытаемся вывести её в консоль, поэтому в консоли будет `undefined`. + +Переменные, определенные с помощью `let` (и `const`), также поднимаются, но в отличие от `var`, не инициализируются. Доступ к ним не возможен до тех пор, пока не выполнится строка их определения (инициализации). Это называется "временная мертвая зона". Когда мы пытаемся обратиться к переменным до того момента как они определены, JavaScript выбрасывает исключение `ReferenceError`. + +

+
+ +--- + +###### 2. Что будет в консоли? + +```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` и `0 1 2` +- B: `0 1 2` и `3 3 3` +- C: `3 3 3` и `0 1 2` + +
Ответ +

+ +#### Ответ: C + +Из-за очереди событий в JavaScript, функция `setTimeout` вызывается _после_ того как цикл будет завершен. Так как переменная `i` в первом цикле была определена с помощью `var`, она будет глобальной. В цикле мы каждый раз увеличиваем значение `i` на `1`, используя унарный оператор `++`. К моменту выполнения функции `setTimeout` значение `i` будет равно `3` в первом примере. + +Во втором цикле переменная `i` определена с помощью `let`. Такие переменные (а также `const`) имеют блочную область видимости (блок это что угодно между `{ }`). С каждой итерацией `i` будет иметь новое значение, и каждое значение будет замкнуто в своей области видимости внутри цикла. + +

+
+ +--- + +###### 3. Что будет в консоли? + +```javascript +const shape = { + radius: 10, + diameter() { + return this.radius * 2; + }, + perimeter: () => 2 * Math.PI * this.radius +}; + +shape.diameter(); +shape.perimeter(); +``` + +- A: `20` и `62.83185307179586` +- B: `20` и `NaN` +- C: `20` и `63` +- D: `NaN` и `63` + +
Ответ +

+ +#### Ответ: B + +Заметь, что `diameter` это обычная функция, в то время как `perimeter` это стрелочная функция. + +У стрелочных функций значение `this` указывает на окружающую область видимости, в отличие от обычных функций! Это значит, что при вызове `perimeter` значение `this` у этой функции указывает не на объект `shape`, а на внешнюю область видимости (например, window). + +У этого объекта нет ключа `radius`, поэтому возвращается `undefined`. + +

+
+ +--- + +###### 4. Что будет в консоли? + +```javascript ++true; +!"Lydia"; +``` + +- A: `1` и `false` +- B: `false` и `NaN` +- C: `false` и `false` + +
Ответ +

+ +#### Ответ: A + +Унарный плюс приводит операнд к числу. `true` это `1`, а `false` это `0`. + +Строка `'Lydia'` это "истинное" значение. На самом деле мы спрашиваем "является ли это истинное значение ложным"? Ответ: `false`. + +

+
+ +--- + +###### 5. Что НЕ является валидным? + +```javascript +const bird = { + size: "small" +}; + +const mouse = { + name: "Mickey", + small: true +}; +``` + +- A: `mouse.bird.size` +- B: `mouse[bird.size]` +- C: `mouse[bird["size"]]` +- D: Все варианты валидны + +
Ответ +

+ +#### Ответ: A + +В JavaScript все ключи объекта являются строками (кроме Symbol). И хотя мы не _набираем_ их как строки, они всегда преобразовываются к строкам под капотом. + +JavaScript интерпретирует (или распаковывает) операторы. При использовании квадратных скобок JS замечает `[` и продолжает пока не встретит `]`. Только после этого он вычислит то, что находится внутри скобок. + +`mouse[bird.size]`: Сперва определяется `bird.size`, которое равно `"small"`. `mouse["small"]` возвращает `true`. + +Но с записью через точку так не происходит. У `mouse` нет ключа `bird`. Таким образом, `mouse.bird` равно `undefined`. Затем мы запрашиваем ключ `size`, используя точечную нотацию: `mouse.bird.size`. Так как `mouse.bird` это `undefined`, мы запрашиваем `undefined.size`. Это не является валидным, и мы получаем ошибку типа `Cannot read property "size" of undefined`. + +

+
+ +--- + +--- + +###### 6. Что будет в консоли? + +```javascript +let c = { greeting: "Hey!" }; +let d; + +d = c; +c.greeting = "Hello"; +console.log(d.greeting); +``` + +- A: `Hello` +- B: `undefined` +- C: `ReferenceError` +- D: `TypeError` + +
Ответ +

+ +#### Ответ: A + +В JavaScript все объекты являются _ссылочными_ типами данных. + +Сперва переменная `c` указывает на объект. Затем мы указываем переменной `d` ссылаться на тот же объект, что и `c`. + + + +Когда ты изменяешь один объект, то изменяются значения всех ссылок, указывающих на этот объект. + +

+
+ +--- + +###### 7. Что будет в консоли? + +```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` + +
Ответ +

+ +#### Ответ: C + +`new Number()` это встроенный конструктор функции. И хотя он выглядит как число, это не настоящее число: у него есть ряд дополнительных фич и это объект. + +Оператор `==` разрешает приведение типов, он проверяет равенство _значений_. Оба значения равны `3`, поэтому возвращается `true`. + +При использвании оператора `===` значение _и_ тип должны быть одинаковыми. Но в нашем случае это не так: `new Number()` это не число, это **объект**. Оба возвращают `false`. + +

+
+ +--- + +###### 8. Каким будет результат? + +```javascript +class Chameleon { + 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` + +
Ответ +

+ +#### Ответ: D + +Функция `colorChange` является статичной. Статичные методы не имеют доступа к экземплярам класса. Так как `freddie` это экземпляр, то статичный метод там не доступен. Поэтому выбрасывается ошибка `TypeError`. + +

+
+ +--- + +###### 9. Что будет в консоли? + +```javascript +let greeting; +greetign = {}; // Опечатка! +console.log(greetign); +``` + +- A: `{}` +- B: `ReferenceError: greetign is not defined` +- C: `undefined` + +
Ответ +

+ +#### Ответ: A + +В консоли выведется объект, потому что мы только что создали пустой объект в глобальном объекте! Когда мы вместо `greeting` написали `greetign`, интерпретатор JS на самом деле выполнил `global.greetign = {}` (или `window.greetign = {}` в браузере). + +Нужно использовать `"use strict"`, чтобы избежать такого поведения. Эта запись поможет быть уверенным в том, что переменная была определена перед тем как ей присвоили значение. + +

+
+ +--- + +###### 10. Что произойдет? + +```javascript +function bark() { + console.log("Woof!"); +} + +bark.animal = "dog"; +``` + +- A: Ничего, всё в порядке! +- B: `SyntaxError`. Нельзя добавлять свойства функциям таким способом. +- C: `undefined` +- D: `ReferenceError` + +
Ответ +

+ +#### Ответ: A + +В JavaScript это возможно, т.к. функции это объекты! (Всё есть объект кроме примитивов). + +Функция это специальный тип объекта, который можно вызвать. Функция это объект со свойствами. +A function is a special type of object. The code you write yourself isn't the actual function. The function is an object with properties. This property is invocable. + +

+
+ +--- + +###### 11. What's the 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` + +
Answer +

+ +#### Answer: A + +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 () { + return `${this.firstName} ${this.lastName}`; +} +``` + +would have made `member.getFullName()` work. Why is this beneficial? Say that we added this method to the constructor itself. Maybe not every `Person` instance needed this method. This would waste a lot of memory space, since they would still have that property, which takes of memory space for each instance. Instead, if we only add it to the prototype, we just have it at one spot in memory, yet they all have access to it! + +

+
+ +--- + +###### 12. What's the 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` + +
Answer +

+ +#### Answer: A + +For `sarah`, we didn't use the `new` keyword. When using `new`, it refers to the new empty object we create. However, if you don't add `new` it 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`. + +

+
+ +--- + +###### 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 + +
Answer +

+ +#### Answer: 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 + +
Answer +

+ +#### Answer: B + +All objects have prototypes, except for the **base object**. 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. What's the output? + +```javascript +function sum(a, b) { + return a + b; +} + +sum(1, "2"); +``` + +- A: `NaN` +- B: `TypeError` +- C: `"12"` +- D: `3` + +
Answer +

+ +#### Answer: 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. What's the 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` + +
Answer +

+ +#### Answer: 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. What's the 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` + +
Answer +

+ +#### Answer: 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. What's the 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` + +
Answer +

+ +#### Answer: 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. What's the output? + +```javascript +function getAge(...args) { + console.log(typeof args); +} + +getAge(21); +``` + +- A: `"number"` +- B: `"array"` +- C: `"object"` +- D: `"NaN"` + +
Answer +

+ +#### Answer: C + +The spread operator (`...args`.) returns an array with arguments. An array is an object, so `typeof args` returns `"object"` + +

+
+ +--- + +###### 20. What's the output? + +```javascript +function getAge() { + "use strict"; + age = 21; + console.log(age); +} + +getAge(); +``` + +- A: `21` +- B: `undefined` +- C: `ReferenceError` +- D: `TypeError` + +
Answer +

+ +#### Answer: 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 value of `sum`? + +```javascript +const sum = eval("10*10+5"); +``` + +- A: `105` +- B: `"105"` +- C: `TypeError` +- D: `"10*10+5"` + +
Answer +

+ +#### 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`. + +

+
+ +--- + +###### 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. + +
Answer +

+ +#### Answer: 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. What's the output? + +```javascript +var num = 8; +var num = 10; + +console.log(num); +``` + +- A: `8` +- B: `10` +- C: `SyntaxError` +- D: `ReferenceError` + +
Answer +

+ +#### Answer: 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. What's the 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` + +
Answer +

+ +#### Answer: 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. What's the 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` + +
Answer +

+ +#### Answer: 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 + +
Answer +

+ +#### Answer: A + +The base execution context is the global execution context: it's what's accessible everywhere in your code. + +

+
+ +--- + +###### 27. What's the 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` + +
Answer +

+ +#### Answer: C + +The `continue` statement skips an iteration if a certain condition returns `true`. + +

+
+ +--- + +###### 28. What's the 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` + +
Answer +

+ +#### 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! + +

+
+ +--- + +###### 29. What's the 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` + +
Answer +

+ +#### Answer: 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. What's the 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` + +
Answer +

+ +#### Answer: 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. + +
Answer +

+ +#### Answer: 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` + +
Answer +

+ +#### 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. + +

+
+ +--- + +###### 33. What's the output? + +```javascript +const person = { name: "Lydia" }; + +function sayHi(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` + +
Answer +

+ +#### Answer: 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. What's the output? + +```javascript +function sayHi() { + return (() => 0)(); +} + +typeof sayHi(); +``` + +- A: `"object"` +- B: `"number"` +- C: `"function"` +- D: `"undefined"` + +
Answer +

+ +#### Answer: B + +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`, and `symbol`. `"function"` is not a type, since functions are objects, it's of type `"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 + +
Answer +

+ +#### Answer: A + +There are only six falsy values: + +- `undefined` +- `null` +- `NaN` +- `0` +- `''` (empty string) +- `false` + +Function constructors, like `new Number` and `new Boolean` are truthy. + +

+
+ +--- + +###### 36. What's the output? + +```javascript +console.log(typeof typeof 1); +``` + +- A: `"number"` +- B: `"string"` +- C: `"object"` +- D: `"undefined"` + +
Answer +

+ +#### Answer: B + +`typeof 1` returns `"number"`. +`typeof "number"` returns `"string"` + +

+
+ +--- + +###### 37. What's the 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` + +
Answer +

+ +#### Answer: 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, 7 x empty, 11]` + +depending on where you run it (it's different for every browser, node, etc.) + +

+
+ +--- + +###### 38. What's the 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` + +
Answer +

+ +#### Answer: 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 + +
Answer +

+ +#### Answer: 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 implicity wrap the object 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. What's the 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]` + +
Answer +

+ +#### Answer: 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. What's the output? + +```javascript +!!null; +!!""; +!!1; +``` + +- A: `false` `true` `false` +- B: `false` `false` `true` +- C: `false` `true` `true` +- D: `true` `true` `false` + +
Answer +

+ +#### Answer: 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? + +```javascript +setInterval(() => console.log("Hi"), 1000); +``` + +- A: a unique id +- B: the amount of milliseconds specified +- C: the passed function +- D: `undefined` + +
Answer +

+ +#### Answer: 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"]]` + +
Answer +

+ +#### Answer: A + +A string is an iterable. The spread operator maps every character of an iterable to one element. + +

+
From a992034bb7f1c14b79cce55422133ba28fab6b92 Mon Sep 17 00:00:00 2001 From: karataev Date: Tue, 18 Jun 2019 14:02:06 +0700 Subject: [PATCH 008/915] Translate questions 11-20 to russian --- README_ru-RU.md | 134 ++++++++++++++++++++++++------------------------ 1 file changed, 67 insertions(+), 67 deletions(-) diff --git a/README_ru-RU.md b/README_ru-RU.md index 131f2099..a462ecb0 100644 --- a/README_ru-RU.md +++ b/README_ru-RU.md @@ -330,7 +330,7 @@ A function is a special type of object. The code you write yourself isn't the ac --- -###### 11. What's the output? +###### 11. Что будет в консоли? ```javascript function Person(firstName, lastName) { @@ -351,12 +351,12 @@ console.log(member.getFullName()); - C: `Lydia Hallie` - D: `undefined` `undefined` -
Answer +
Ответ

-#### Answer: A +#### Ответ: A -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 () { @@ -364,14 +364,14 @@ Person.prototype.getFullName = function () { } ``` -would have made `member.getFullName()` work. Why is this beneficial? Say that we added this method to the constructor itself. Maybe not every `Person` instance needed this method. This would waste a lot of memory space, since they would still have that property, which takes of memory space for each instance. Instead, if we only add it to the prototype, we just have it at one spot in memory, yet they all have access to it! +сделает метод `member.getFullName()` рабочим. В чем тут преимущество? Предположим, что мы добавили этот метод к конструктору. Возможно, не каждому экземпляру `Person` нужен этот метод. Это приведет к большим потерям памяти, т.к. все экземпляры будут иметь это свойство. Напротив, если мы добавим этот метод только к прототипу, у нас будет только одно место в памяти, к которому смогут обращаться все экземпляры!

--- -###### 12. What's the output? +###### 12. Что будет в консоли? ```javascript function Person(firstName, lastName) { @@ -386,38 +386,38 @@ 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` +- A: `Person {firstName: "Lydia", lastName: "Hallie"}` и `undefined` +- B: `Person {firstName: "Lydia", lastName: "Hallie"}` и `Person {firstName: "Sarah", lastName: "Smith"}` +- C: `Person {firstName: "Lydia", lastName: "Hallie"}` и `{}` +- D:`Person {firstName: "Lydia", lastName: "Hallie"}` и `ReferenceError` -
Answer +
Ответ

-#### Answer: A +#### Ответ: A -For `sarah`, we didn't use the `new` keyword. When using `new`, it refers to the new empty object we create. However, if you don't add `new` it refers to the **global object**! +Для `sarah` мы не использовали ключевое слово `new`. Использование `new` приводит к созданию нового объекта. Но без `new` он указывает на **глобальный объект**! -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`. +Мы указали, что `this.firstName` равно `"Sarah"` и `this.lastName` равно `"Smith"`. На самом деле мы определили `global.firstName = 'Sarah'` и `global.lastName = 'Smith'`. `sarah` осталась `undefined`.

--- -###### 13. What are the three phases of event propagation? +###### 13. Назовите три фазы распространения событий -- A: Target > Capturing > Bubbling -- B: Bubbling > Target > Capturing -- C: Target > Bubbling > Capturing -- D: Capturing > Target > Bubbling +- A: Цель > Захват > Всплытие +- B: Всплытие > Цель > Захват +- C: Цель > Всплытие > Захват +- D: Захват > Цель > Всплытие -
Answer +
Ответ

-#### Answer: D +#### Ответ: 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. +Во время фазы **захвата** событие распространяется с элементов родителей до элемента цели. После достижения **цели** начинается фаза **всплытия**. @@ -426,24 +426,24 @@ During the **capturing** phase, the event goes through the ancestor elements dow --- -###### 14. All object have prototypes. +###### 14. Все объекты имют прототипы -- A: true -- B: false +- A: Да +- B: Нет -

Answer +
Ответ

-#### Answer: B +#### Ответ: B -All objects have prototypes, except for the **base object**. 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. +Все объекты имеют прототипы, кроме **базового объекта**. Базовый объект имеет доступ до некоторых методов и свойств, таких как `.toString`. Именно поэтому мы можем использовать встроенные методы JavaScript! Все эти методы доступны в прототипе. Если JavaScript не может найти метод непосредственно у объекта, он продолжает поиск по цепочке прототипов пока не найдет.

--- -###### 15. What's the output? +###### 15. Каким будет результат? ```javascript function sum(a, b) { @@ -458,21 +458,21 @@ sum(1, "2"); - C: `"12"` - D: `3` -
Answer +
Ответ

-#### Answer: C +#### Ответ: 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. +JavaScript это **динамически типизированный язык**: мы не определяем тип переменных. Переменные могут автоматически быть преобразованы из одного типа в другой без нашего участия, что называется _неявным приведением типов_. **Приведение** это преобразование из одного типа в другой. -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"`. +В этом примере JavaScript сконвертировал число `1` в строку, чтобы операция внутри функции имела смысл и вернула значение. Во время сложения числа (`1`) и строки (`'2'`) число преобразовывается к строке. Мы можем конкатенировать строки вот так: `"Hello" + "World"`. Таким образом, `"1" + "2"` возвращает `"12"`.

--- -###### 16. What's the output? +###### 16. Что будет в консоли? ```javascript let number = 0; @@ -486,29 +486,29 @@ console.log(number); - C: `0` `2` `2` - D: `0` `1` `2` -
Answer +
Ответ

-#### Answer: C +#### Ответ: C -The **postfix** unary operator `++`: +**Постфиксный** унарный оператор `++`: -1. Returns the value (this returns `0`) -2. Increments the value (number is now `1`) +1. Возвращает значение (`0`) +2. Инкрементирует значение (теперь число равно `1`) -The **prefix** unary operator `++`: +**Префиксный** унарный оператор `++`: -1. Increments the value (number is now `2`) -2. Returns the value (this returns `2`) +1. Инкрементирует значение (число теперь равно `2`) +2. Возвращает значение (`2`) -This returns `0 2 2`. +Результат: `0 2 2`.

--- -###### 17. What's the output? +###### 17. Что будет в консоли? ```javascript function getPersonInfo(one, two, three) { @@ -527,55 +527,55 @@ getPersonInfo`${person} is ${age} years old`; - B: `["", " is ", " years old"]` `"Lydia"` `21` - C: `"Lydia"` `["", " is ", " years old"]` `21` -
Answer +
Ответ

-#### Answer: B +#### Ответ: 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. What's the output? +###### 18. Что будет в консоли? ```javascript function checkAge(data) { if (data === { age: 18 }) { - console.log("You are an adult!"); + console.log("Ты взрослый!"); } else if (data == { age: 18 }) { - console.log("You are still an adult."); + console.log("Ты все еще взрослый."); } else { - console.log(`Hmm.. You don't have an age I guess`); + console.log(`Хмм.. Кажется, у тебя нет возраста.`); } } 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: `Ты взрослый!` +- B: `Ты все еще взрослый.` +- C: `Хмм.. Кажется, у тебя нет возраста.` -
Answer +
Ответ

-#### Answer: C +#### Ответ: 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. +В операциях сравнения примитивы сравниваются по их _значениям_, а объекты по _ссылкам_. JavaScript проверяет, чтобы объекты указывали на одну и ту же область памяти. -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`. +Поэтому `{ age: 18 } === { age: 18 }` и `{ age: 18 } == { age: 18 }` возвращают `false`.

--- -###### 19. What's the output? +###### 19. Что будет в консоли? ```javascript function getAge(...args) { @@ -590,19 +590,19 @@ getAge(21); - C: `"object"` - D: `"NaN"` -
Answer +
Ответ

-#### Answer: C +#### Ответ: C -The spread operator (`...args`.) returns an array with arguments. An array is an object, so `typeof args` returns `"object"` +Оператор распространения (`...args`) возвращает массив с аргументами. Массив это объект, поэтому `typeof args` возвращает `"object"`.

--- -###### 20. What's the output? +###### 20. Что будет в консоли? ```javascript function getAge() { @@ -619,12 +619,12 @@ getAge(); - C: `ReferenceError` - D: `TypeError` -
Answer +
Ответ

-#### Answer: C +#### Ответ: 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. +Используя `"use strict"`, можно быть уверенным, что мы по ошибке не побъявим глобальные переменные. Мы ранее нигде не объявляли переменную `age`, поэтому с использованием `"use strict"` возникнет `ReferenceError`. Без использования `"use strict"` ошибки не возникнет, а переменная `age` добавится в глобальный объект.

From a5fc8a389513a6745114965cbb004cf1984223f1 Mon Sep 17 00:00:00 2001 From: Lydia Date: Tue, 18 Jun 2019 09:04:56 +0200 Subject: [PATCH 009/915] Update question 2 --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index ad45ee46..accad562 100644 --- a/README.md +++ b/README.md @@ -63,7 +63,7 @@ for (let i = 0; i < 3; i++) { #### Answer: C -Because of the event queue in JavaScript, the `setTimeout` function is called _after_ the loop has been executed. Since the variable `i` in the first loop was declared using the `var` keyword, this value was global. During the loop, we incremented the value of `i` by `1` each time, using the unary operator `++`. By the time the `setTimeout` function was invoked, `i` was equal to `3` in the first example. +Because of the event queue in JavaScript, the `setTimeout` callback function is called _after_ the loop has been executed. Since the variable `i` in the first loop was declared using the `var` keyword, this value was global. During the loop, we incremented the value of `i` by `1` each time, using the unary operator `++`. By the time the `setTimeout` callback function was invoked, `i` was equal to `3` in the first example. In the second loop, the variable `i` was declared using the `let` keyword: variables declared with the `let` (and `const`) keyword are block-scoped (a block is anything between `{ }`). During each iteration, `i` will have a new value, and each value is scoped inside the loop. From b39e10c1ceb4c4d8da137e8443eb8adbb50da429 Mon Sep 17 00:00:00 2001 From: Lydia Date: Tue, 18 Jun 2019 09:05:18 +0200 Subject: [PATCH 010/915] Rephrase question 5 --- README.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index accad562..652b5688 100644 --- a/README.md +++ b/README.md @@ -133,7 +133,7 @@ The string `'Lydia'` is a truthy value. What we're actually asking, is "is this --- -###### 5. Which one is NOT valid? +###### 5. Which one is true? ```javascript const bird = { @@ -146,9 +146,9 @@ const mouse = { }; ``` -- A: `mouse.bird.size` -- B: `mouse[bird.size]` -- C: `mouse[bird["size"]]` +- 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
Answer From 9176a67048e37bb98e6b81014cf65a89609b6a55 Mon Sep 17 00:00:00 2001 From: Lydia Date: Tue, 18 Jun 2019 09:06:03 +0200 Subject: [PATCH 011/915] Add extra option question 6 --- README.md | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 652b5688..20e61a7e 100644 --- a/README.md +++ b/README.md @@ -183,9 +183,10 @@ console.log(d.greeting); ``` - A: `Hello` -- B: `undefined` -- C: `ReferenceError` -- D: `TypeError` +- B: `Hey` +- C: `undefined` +- D: `ReferenceError` +- E: `TypeError`
Answer

From 89011880f6257fd3180e56a24271702745c8e8f1 Mon Sep 17 00:00:00 2001 From: Lydia Date: Tue, 18 Jun 2019 09:06:17 +0200 Subject: [PATCH 012/915] Remove spaces --- README.md | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/README.md b/README.md index 20e61a7e..681b8e86 100644 --- a/README.md +++ b/README.md @@ -2,7 +2,7 @@ I post daily multiple choice JavaScript questions on my [Instagram](https://www.instagram.com/theavocoder), which I'll also post 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 weekly with new questions. +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 weekly with new questions. The answers are in the collapsed sections below the questions, simply click on them to expand it. Good luck :heart: @@ -338,9 +338,9 @@ function Person(firstName, lastName) { } const member = new Person("Lydia", "Hallie"); -Person.getFullName = function () { +Person.getFullName = function() { return `${this.firstName} ${this.lastName}`; -} +}; console.log(member.getFullName()); ``` @@ -358,9 +358,9 @@ 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}`; -} +}; ``` would have made `member.getFullName()` work. Why is this beneficial? Say that we added this method to the constructor itself. Maybe not every `Person` instance needed this method. This would waste a lot of memory space, since they would still have that property, which takes of memory space for each instance. Instead, if we only add it to the prototype, we just have it at one spot in memory, yet they all have access to it! From 531dbadab2bee3fb0d058a004e9224a647ea5003 Mon Sep 17 00:00:00 2001 From: karataev Date: Tue, 18 Jun 2019 14:41:19 +0700 Subject: [PATCH 013/915] Translate questions 21-30 to russian --- README_ru-RU.md | 118 ++++++++++++++++++++++++------------------------ 1 file changed, 59 insertions(+), 59 deletions(-) diff --git a/README_ru-RU.md b/README_ru-RU.md index a462ecb0..fcff362b 100644 --- a/README_ru-RU.md +++ b/README_ru-RU.md @@ -631,7 +631,7 @@ getAge(); --- -###### 21. What's value of `sum`? +###### 21. Чему будет равно `sum`? ```javascript const sum = eval("10*10+5"); @@ -642,44 +642,44 @@ const sum = eval("10*10+5"); - C: `TypeError` - D: `"10*10+5"` -

Answer +
Ответ

-#### Answer: A +#### Ответ: 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` выполняет код, переданный в виде строки. Если это выражение (как в данном случае), то вычисляется выражение. Выражение `10 * 10 + 5` вернет число `105`.

--- -###### 22. How long is cool_secret accessible? +###### 22. Как долго будет доступен cool_secret? ```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. +- A: Всегда, данные не потеряются. +- B: Пока пользователь не закроет вкладку. +- C: Пока пользователь не закроет браузер, а не только вкладку. +- D: Пока пользователь не выключит компьютер. -
Answer +
Ответ

-#### Answer: B +#### Ответ: B -The data stored in `sessionStorage` is removed after closing the _tab_. +Данные, сохраненные в `sessionStorage` очищаются после закрытия _вкладки_. -If you used `localStorage`, the data would've been there forever, unless for example `localStorage.clear()` is invoked. +При использовании `localStorage` данные сохраняются навсегда. Очистить их можно, например, используя `localStorage.clear()`.

--- -###### 23. What's the output? +###### 23. Что будет в консоли? ```javascript var num = 8; @@ -693,21 +693,21 @@ console.log(num); - C: `SyntaxError` - D: `ReferenceError` -
Answer +
Ответ

-#### Answer: B +#### Ответ: B -With the `var` keyword, you can declare multiple variables with the same name. The variable will then hold the latest value. +С помощью ключевого слова `var` можно определять сколько угодно переменных с одним и тем же именем. Переменная будет хранить последнее присвоенное значение. -You cannot do this with `let` or `const` since they're block-scoped. +Но такой трюк нельзя проделать с `let` и `const`, т.к. у них блочная область видимости.

--- -###### 24. What's the output? +###### 24. Каким будет результат? ```javascript const obj = { 1: "a", 2: "b", 3: "c" }; @@ -724,21 +724,21 @@ set.has(1); - C: `true` `true` `false` `true` - D: `true` `true` `true` `true` -
Answer +
Ответ

-#### Answer: C +#### Ответ: 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. +Все ключи объектов (кроме Symbols) являются строками, даже если заданы не в виде строк. Поэтому `obj.hasOwnProperty('1')` так же возвращает 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`. +Но это не работает для `set`. Значения `'1'` нет в `set`: `set.has('1')` возвращает `false`. Но `set.has(1)` вернет `true`.

--- -###### 25. What's the output? +###### 25. Что будет в консоли? ```javascript const obj = { a: "one", b: "two", a: "three" }; @@ -750,37 +750,37 @@ console.log(obj); - C: `{ a: "three", b: "two" }` - D: `SyntaxError` -
Answer +
Ответ

-#### Answer: C +#### Ответ: 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. +###### 26. Глобальный контекст исполнения создает две вещи: глобальный объект и `this` -- A: true -- B: false -- C: it depends +- A: Да +- B: Нет +- C: Это зависит -
Answer +
Ответ

-#### Answer: A +#### Ответ: A -The base execution context is the global execution context: it's what's accessible everywhere in your code. +Базовый контекст исполнения это глобальный контекст исполнения: это то, что доступно где угодно в твоем коде.

--- -###### 27. What's the output? +###### 27. Что будет в консоли? ```javascript for (let i = 1; i < 5; i++) { @@ -794,19 +794,19 @@ for (let i = 1; i < 5; i++) { - C: `1` `2` `4` - D: `1` `3` `4` -
Answer +
Ответ

-#### Answer: C +#### Ответ: C -The `continue` statement skips an iteration if a certain condition returns `true`. +Оператор `continue` пропускает итерацию, если условие возвращает `true`.

--- -###### 28. What's the output? +###### 28. Каким будет результат? ```javascript String.prototype.giveLydiaPizza = () => { @@ -823,19 +823,19 @@ name.giveLydiaPizza(); - C: `SyntaxError` - D: `undefined` -
Answer +
Ответ

-#### Answer: A +#### Ответ: 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` это встроенный конструктор, к которому можно добавлять свойства. Я добавила метод к его прототипу. Строки-примитивы автоматически конвертируются к строкам-объектам. Поэтому все строки (строковые объекты) имеют доступ к этому методу!

--- -###### 29. What's the output? +###### 29. Что будет в консоли? ```javascript const a = {}; @@ -853,23 +853,23 @@ console.log(a[b]); - C: `undefined` - D: `ReferenceError` -
Answer +
Ответ

-#### Answer: B +#### Ответ: 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`. +Ключи объекта автоматически конвертируются в строки. Мы собираемся добавить объект в качестве ключа к объекту `a` со значением `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`. +Тем не менее, когда мы приводим объект к строке, он становится `"[object Object]"`. Таким образом, мы говорим, что `a["Object object"] = 123`. Потом мы делаем то же самое. `c` это другой объект, который мы неявно приводим к строке. Поэтому `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`. +Затем, когда мы выводим `a[b]`, мы имеем в виду `a["Object object"]`. Мы только что установили туда значение `456`, поэтому в результате получаем `456`.

--- -###### 30. What's the output? +###### 30. Каким будет результат? ```javascript const foo = () => console.log("First"); @@ -886,36 +886,36 @@ baz(); - C: `Second` `First` `Third` - D: `Second` `Third` `First` -
Answer +
Ответ

-#### Answer: B +#### Ответ: B -We have a `setTimeout` function and invoked it first. Yet, it was logged last. +Мы вызываем функцию `setTimeout` первой. Тем не менее, она выводится в консоль последней -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. +Это происходит из-за того, что в браузерах у нас есть не только рантайм движок, но и `WebAPI`. `WebAPI` предоставляет нам функцию `setTimeout` и много других возможностей. Например, DOM. -After the _callback_ is pushed to the WebAPI, the `setTimeout` function itself (but not the callback!) is popped off the stack. +После того как _коллбек_ отправлен в `WebAPI`, функция `setTimeout` (но не коллбек!) вынимается из стека. -Now, `foo` gets invoked, and `"First"` is being logged. +Теперь вызывается `foo`, и `"First"` выводится в консоль. -`foo` is popped off the stack, and `baz` gets invoked. `"Third"` gets logged. +`foo` достается из стека, и вызывается `baz`. `"Third"` выводится в консоль. -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_. +WebAPI не может добавлять содержимое в стек когда захочет. Вместо этого он отправляет коллбек-функцию в так называемую _очередь_. -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. +Здесь на сцену выходит цикл событий (event loop). **Event loop** проверяет стек и очередь задач. Если стек пустой, то он берет первый элемент из очереди и отправляет его в стек. -`bar` gets invoked, `"Second"` gets logged, and it's popped off the stack. +Вызывается `bar`, в консоль выводится `"Second"` и эта функция достается из стека.

From 02a615221593d94fb057c10beee2145bae0ce9ea Mon Sep 17 00:00:00 2001 From: karataev Date: Tue, 18 Jun 2019 15:44:10 +0700 Subject: [PATCH 014/915] =?UTF-8?q?Translation=20is=20done=20=F0=9F=8E=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README_ru-RU.md | 155 ++++++++++++++++++++++++------------------------ 1 file changed, 78 insertions(+), 77 deletions(-) diff --git a/README_ru-RU.md b/README_ru-RU.md index fcff362b..a4eb0829 100644 --- a/README_ru-RU.md +++ b/README_ru-RU.md @@ -922,41 +922,41 @@ WebAPI не может добавлять содержимое в стек ко --- -###### 31. What is the event.target when clicking the button? +###### 31. Что будет в event.target после клика на кнопку? ```html
``` -- A: Outer `div` -- B: Inner `div` +- A: Внешний `div` +- B: Внутренний `div` - C: `button` -- D: An array of all nested elements. +- D: Массив со всеми вложенными элементами -
Answer +
Ответ

-#### Answer: C +#### Ответ: C -The deepest nested element that caused the event is the target of the event. You can stop bubbling by `event.stopPropagation` +Целью события является самый глубокий вложенный элемент. Остановить распространение событий можно с помощью `event.stopPropagation`

--- -###### 32. When you click the paragraph, what's the logged output? +###### 32. Что будет в консоли после клика по параграфу? ```html

- Click here! + Кликни меня!

``` @@ -966,19 +966,19 @@ The deepest nested element that caused the event is the target of the event. You - C: `p` - D: `div` -
Answer +
Ответ

-#### Answer: A +#### Ответ: 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. +После клика по `p` будет выведено `p` и `div`. В цикле жизни события есть три фазы: захват, цель и всплытие. По умолчанию обработчики событий выполняются на фазе всплытия (если не установлен параметр `useCapture` в `true`). Всплытие идет с самого глубокого элемента вверх.

--- -###### 33. What's the output? +###### 33. Что будет в консоли? ```javascript const person = { name: "Lydia" }; @@ -996,21 +996,21 @@ sayHi.bind(person, 21); - C: `Lydia is 21` `Lydia is 21` - D: `Lydia is 21` `function` -
Answer +
Ответ

-#### Answer: D +#### Ответ: D -With both, we can pass the object to which we want the `this` keyword to refer to. However, `.call` is also _executed immediately_! +В обоих случаях мы мы передаем объект, на который будет указывать `this`. Но `.call` _выполняется сразу же_! -`.bind.` returns a _copy_ of the function, but with a bound context! It is not executed immediately. +`.bind` возвращает _копию_ функции, но с привязанным контекстом. Она не выполняется незамедлительно.

--- -###### 34. What's the output? +###### 34. Каким будет результат? ```javascript function sayHi() { @@ -1025,21 +1025,21 @@ typeof sayHi(); - C: `"function"` - D: `"undefined"` -
Answer +
Ответ

-#### Answer: B +#### Ответ: B -The `sayHi` function returns the returned value of the immediately invoked function (IIFE). This function returned `0`, which is type `"number"`. +Функция `sayHi` возвращает значение, возвращаемое из немедленно вызываемого функционального выражения (IIFE). Результатом является `0` типа `"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"`. +Для информации: в JS 7 встроенных типов: `null`, `undefined`, `boolean`, `number`, `string`, `object`, и `symbol`. `"function"` не является отдельным типом, т.к. функции являются объектами типа `"object"`.

--- -###### 35. Which of these values are falsy? +###### 35. Какие из этих значений являются "ложными"? ```javascript 0; @@ -1053,14 +1053,14 @@ 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: Все являются "ложными" -
Answer +
Ответ

-#### Answer: A +#### Ответ: A -There are only six falsy values: +Есть только шесть "ложных" значений: - `undefined` - `null` @@ -1069,14 +1069,14 @@ There are only six falsy values: - `''` (empty string) - `false` -Function constructors, like `new Number` and `new Boolean` are truthy. +Конструкторы функций, такие как `new Number` и `new Boolean` являются "истинными".

--- -###### 36. What's the output? +###### 36. Что будет в консоли ```javascript console.log(typeof typeof 1); @@ -1087,20 +1087,20 @@ console.log(typeof typeof 1); - C: `"object"` - D: `"undefined"` -
Answer +
Ответ

-#### Answer: B +#### Ответ: B -`typeof 1` returns `"number"`. -`typeof "number"` returns `"string"` +`typeof 1` возвращает `"number"`. +`typeof "number"` возвращает `"string"`

--- -###### 37. What's the output? +###### 37. Что будет в консоли? ```javascript const numbers = [1, 2, 3]; @@ -1113,23 +1113,23 @@ console.log(numbers); - C: `[1, 2, 3, 7 x empty, 11]` - D: `SyntaxError` -
Answer +
Ответ

-#### Answer: C +#### Ответ: 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: +Когда в массив добавляется значение, которое выходит за пределы длины массива, JavaScript создает так называемые "пустые ячейки". На самом деле они имеют значения `undefined`, но в консоли выводятся так: `[1, 2, 3, 7 x empty, 11]` -depending on where you run it (it's different for every browser, node, etc.) +в зависимости от окружения (может отличаться для браузеров, Node, и т.д.).

--- -###### 38. What's the output? +###### 38. Что будет в консоли? ```javascript (() => { @@ -1150,46 +1150,46 @@ depending on where you run it (it's different for every browser, node, etc.) - C: `1` `1` `2` - D: `1` `undefined` `undefined` -
Answer +
Ответ

-#### Answer: A +#### Ответ: 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. +Блок `catch` получает аргумент `x`. Это не тот же `x`, который определен в качестве переменной перед строкой `try {` -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`. +Затем мы присваиваем этому аргументу значение `1` и устанавливаем значение для переменной `y`. Потом выводим в консоль значение аргумента `x`, которое равно `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`. +За пределами блока `catch` переменная `x` все еще `undefined`, а `y` равно `2`. Когда мы вызываем `console.log(x)` за пределами блока `catch`, этот вызов возвращает `undefined`, а `y` возвращает `2`.

--- -###### 39. Everything in JavaScript is either a... +###### 39. Всё в JavaScript это -- A: primitive or object -- B: function or object -- C: trick question! only objects -- D: number or object +- A: примитив или объект +- B: функция или объект +- C: вопрос с подвохом! только объекты +- D: число или объект -
Answer +
Ответ

-#### Answer: A +#### Ответ: A -JavaScript only has primitive types and objects. +В JavaScript есть только примитивы и объекты. -Primitive types are `boolean`, `null`, `undefined`, `bigint`, `number`, `string`, and `symbol`. +Типы примитивов: `boolean`, `null`, `undefined`, `bigint`, `number`, `string`, и `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 implicity wrap the object 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. +Отличием примитива от объекта является то, что примитивы не имеют свойств или методов. Тем не менее, `'foo'.toUpperCase()` преобразуется в `'FOO'` и не вызывает `TypeError`. Это происходит потому, что при попытке получения свойства или метода у примитива (например, строки), JavaScript неявно обернет примитив объектом, используя один из классов-оберток (например, `String`), а затем сразу же уничтожет обертку после вычисления выражения. Все примитивы кроме `null` и `undefined` ведут себя таким образом.

--- -###### 40. What's the output? +###### 40. Каким будет результат? ```javascript [[0, 1], [2, 3]].reduce( @@ -1205,21 +1205,22 @@ What differentiates a primitive from an object is that primitives do not have an - C: `[1, 2, 0, 1, 2, 3]` - D: `[1, 2, 6]` -
Answer +
Ответ

-#### Answer: C +#### Ответ: C + +`[1, 2]` - начальное значение, с которым инициализируется переменная `acc`. После первого прохода `acc` будет равно `[1,2]`, а `cur` будет `[0,1]`. После конкатенации результат будет `[1, 2, 0, 1]`. -`[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]` +Затем `acc` равно `[1, 2, 0, 1]`, а `cur` равно `[2, 3]`. После слияния получим `[1, 2, 0, 1, 2, 3]`.

--- -###### 41. What's the output? +###### 41. Каким будет результат? ```javascript !!null; @@ -1232,46 +1233,46 @@ Then, `[1, 2, 0, 1]` is `acc` and `[2, 3]` is `cur`. We concatenate them, and ge - C: `false` `true` `true` - D: `true` `true` `false` -
Answer +
Ответ

-#### Answer: B +#### Ответ: B -`null` is falsy. `!null` returns `true`. `!true` returns `false`. +`null` - "ложный". `!null` возвращает `true`. `!true` возвращает `false`. -`""` is falsy. `!""` returns `true`. `!true` returns `false`. +`""` - "ложный". `!""` возвращает `true`. `!true` возвращает `false`. -`1` is truthy. `!1` returns `false`. `!false` returns `true`. +`1` - "истинный". `!1` возвращает `false`. `!false` возвращает `true`.

--- -###### 42. What does the `setInterval` method return? +###### 42. Что возвращает метод `setInterval`? ```javascript setInterval(() => console.log("Hi"), 1000); ``` -- A: a unique id -- B: the amount of milliseconds specified -- C: the passed function +- A: уникальный id +- B: указанное количество миллисекунд +- C: переданную функцию - D: `undefined` -
Answer +
Ответ

-#### Answer: A +#### Ответ: A -It returns a unique id. This id can be used to clear that interval with the `clearInterval()` function. +Это метод возвращает уникальный id. Этот id может быть использован для очищения интервала с помощью функции `clearInterval()`.

--- -###### 43. What does this return? +###### 43. Каким будет результат? ```javascript [..."Lydia"]; @@ -1282,12 +1283,12 @@ It returns a unique id. This id can be used to clear that interval with the `cle - C: `[[], "Lydia"]` - D: `[["L", "y", "d", "i", "a"]]` -
Answer +
Ответ

-#### Answer: A +#### Ответ: A -A string is an iterable. The spread operator maps every character of an iterable to one element. +Строка является итерируемой сущностью. Оператор распространения преобразовывает каждый символ в отдельный элемент.

From 11d7224c7c7111c1c28ca5b8927e7ef915a2cee0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Adri=C3=A1n?= <22575055+aguadotzn@users.noreply.github.com> Date: Tue, 18 Jun 2019 16:10:40 +0200 Subject: [PATCH 015/915] Questions 1 to 10. --- README-ES.md | 131 +++++++++++++++++++++++++-------------------------- 1 file changed, 65 insertions(+), 66 deletions(-) diff --git a/README-ES.md b/README-ES.md index 391673e1..a1f667c6 100644 --- a/README-ES.md +++ b/README-ES.md @@ -33,15 +33,14 @@ sayHi(); - C: `ReferenceError` y `21` - D: `undefined` y `ReferenceError` -
Answer +
Solución

-#### Respuesta: D - -Within the function, we first declare the `name` variable with the `var` keyword. This means that the variable gets hoisted (memory space is set up during the creation phase) with the default value of `undefined`, until we actually get to the line where we define the variable. We haven't defined the variable yet on the line where we try to log the `name` variable, so it still holds the value of `undefined`. +#### Respuesta Correcta: D -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`. +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`

@@ -59,18 +58,18 @@ for (let i = 0; i < 3; i++) { } ``` -- A: `0 1 2` and `0 1 2` -- B: `0 1 2` and `3 3 3` -- C: `3 3 3` and `0 1 2` +- A: `0 1 2` y `0 1 2` +- B: `0 1 2` y `3 3 3` +- C: `3 3 3` y `0 1 2` -
Answer +
Solución

-#### Respuesta: C +#### Respuesta Correcta: C -Because of the event queue in JavaScript, the `setTimeout` function is called _after_ the loop has been executed. Since the variable `i` in the first loop was declared using the `var` keyword, this value was global. During the loop, we incremented the value of `i` by `1` each time, using the unary operator `++`. By the time the `setTimeout` function was invoked, `i` was equal to `3` in the first example. +Debido a la cola de eventos en JavaScript, la función `setTimeout` se llama una vez el ciclo se ha ejecutado. Dado que la variable `i` en el primer bucle se declaró utilizando la palabra reservada ` var`, este valor es global. Durante el bucle, incrementamos el valor de `i` en` 1` cada vez, utilizando el operador unario `++`. Cuando se invocó la función `setTimeout`,` i` era igual a `3` en el primer ejemplo. -In the second loop, the variable `i` was declared using the `let` keyword: variables declared with the `let` (and `const`) keyword are block-scoped (a block is anything between `{ }`). During each iteration, `i` will have a new value, and each value is scoped inside the loop. +En el segundo bucle, la variable `i` se declaró utilizando la palabra reservada` let`: las variables declaradas con la palabra reservada `let` (y` const`) tienen un ámbito de bloque (un bloque es lo que se encuentra entre `{}`). Durante cada iteración, `i` tendrá un nuevo valor, y cada valor se encuentra dentro del bucle.

@@ -92,53 +91,53 @@ shape.diameter(); shape.perimeter(); ``` -- A: `20` and `62.83185307179586` -- B: `20` and `NaN` -- C: `20` and `63` -- D: `NaN` and `63` +- A: `20` y `62.83185307179586` +- B: `20` y `NaN` +- C: `20` y `63` +- D: `NaN` y `63` -
Answer +
Solución

-#### Answer: B +#### Respuesta Correcta: B -Note that the value of `diameter` is a regular function, whereas the value of `perimeter` is an arrow function. +Hay que tener en cuenta aqui que el valor de `diámetro` es una función regular o _normal_, mientras que el valor de `perímetro` es una función de flecha. -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). +Con las funciones de flecha, la palabra clave `this` se refiere a su ámbito actual, a diferencia de las funciones regulares. Esto significa que cuando llamamos "perímetro", no se refiere al objeto en sí mismo, sino a su ámbito circundante (ventana por ejemplo). -There is no value `radius` on that object, which returns `undefined`. +No hay valor `radius` en ese objeto, que devuelve` undefined`.

--- -###### 4. What's the output? +###### 4. ¿Qué devuelve la siguiente función? ```javascript +true; !"Lydia"; ``` -- A: `1` and `false` -- B: `false` and `NaN` -- C: `false` and `false` +- A: `1` y `false` +- B: `false` y `NaN` +- C: `false` y `false` -
Answer +
Solución

-#### Answer: A +#### Respuesta Correcta: A -The unary plus tries to convert an operand to a number. `true` is `1`, and `false` is `0`. +En el primera caso se intenta convertir un operando en un número. `true` es` 1`, y `false` es` 0`. -The string `'Lydia'` is a truthy value. What we're actually asking, is "is this truthy value falsy?". This returns `false`. +En el segundo caso la cadena `'Lydia'` es un valor verdadero. Lo que realmente estamos preguntando es "¿es este verdadero valor falso?". Esto devuelve `false`.

--- -###### 5. Which one is NOT valid? +###### 5. ¿Cuál NO es válida? ```javascript const bird = { @@ -154,20 +153,20 @@ const mouse = { - A: `mouse.bird.size` - B: `mouse[bird.size]` - C: `mouse[bird["size"]]` -- D: All of them are valid +- D: Todas son correctas -
Answer +
Solución

-#### Answer: A +#### Respuesta Correcta: A -In JavaScript, all object keys are strings (unless it's a Symbol). Even though we might not _type_ them as strings, they are always converted into strings under the hood. +En JavaScript, todas las _keys_ son cadenas (a menos que sea un símbolo). A pesar de que no podríamos escribirlos como cadenas, siempre funcionan como cadenas de manera interna. -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. +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]`: First it evaluates `bird.size`, which is `"small"`. `mouse["small"]` returns `true` +`mouse [bird.size]`: Primero evalúa `bird.size`, que es` "small" `. `mouse [" small "]` devuelve `true` -However, with dot notation, this doesn't happen. `mouse` does not have a key called `bird`, which means that `mouse.bird` is `undefined`. Then, we ask for the `size` using dot notation: `mouse.bird.size`. Since `mouse.bird` is `undefined`, we're actually asking `undefined.size`. This isn't valid, and will throw an error similar to `Cannot read property "size" of undefined`. +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 `No se puede leer la propiedad" tamaño "de undefined`

@@ -176,7 +175,7 @@ However, with dot notation, this doesn't happen. `mouse` does not have a key cal --- -###### 6. What's the output? +###### 6. ¿Qué devuelve la siguiente función? ```javascript let c = { greeting: "Hey!" }; @@ -192,25 +191,25 @@ console.log(d.greeting); - C: `ReferenceError` - D: `TypeError` -
Answer +
Solución

-#### Answer: A +#### Respuesta Correcta: A -In JavaScript, all objects interact by _reference_ when setting them equal to each other. +En JavaScript, TODOS los objetos interactúan por referencia, de modo que cuando se establecen iguales o pasan a una función, todos apuntan a la misma ubicación, de modo que cuando cambia un objeto, los cambia a todos. -First, variable `c` holds a value to an object. Later, we assign `d` with the same reference that `c` has to the object. +Primero, la variable `c` tiene un valor para un objeto. Más tarde, asignamos `d` con la misma referencia que` c` tiene al objeto. - + -When you change one object, you change all of them. +Cuando cambias un objeto, cambias todos ellos.

--- -###### 7. What's the output? +###### 7. ¿Qué devuelve la siguiente función? ```javascript let a = 3; @@ -227,23 +226,23 @@ console.log(b === c); - C: `true` `false` `false` - D: `false` `true` `true` -
Answer +
Solución

-#### Answer: C +#### Respuesta Correcta: 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. +`new Number ()` es un constructor de funciones incorporado. Aunque parece un número, no es realmente un número: tiene muchas características adicionales y es un objeto. -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`. +Cuando usamos el operador `==`, solo verifica si tiene el mismo _valor_. Ambos tienen el valor de `3`, por lo que devuelve` 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.` +Sin embargo, cuando usamos el operador `===`, tanto el valor _ como el tipo deben ser iguales. No es: `new Number ()` no es un número, es un ** objeto **. Ambos devuelven "falso".

--- -###### 8. What's the output? +###### 8. ¿Qué devuelve la siguiente función? ```javascript class Chameleon { @@ -266,19 +265,19 @@ freddie.colorChange("orange"); - C: `green` - D: `TypeError` -
Answer +
Solución

-#### Answer: D +#### Respuesta Correcta: 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. +La función `colorChange` es estática. Los métodos estáticos están diseñados para _vivir_ solo en el constructor en el que se crean y no se pueden transmitir a ningún elemento secundario. Como `freddie` es un niño, la función no se transmite y no está disponible en la instancia de` freddie`: por lo tanto se lanza un `TypeError`.

--- -###### 9. What's the output? +###### 9. ¿Qué devuelve la siguiente función? ```javascript let greeting; @@ -290,21 +289,21 @@ console.log(greetign); - B: `ReferenceError: greetign is not defined` - C: `undefined` -
Answer +
Solución

-#### Answer: A +#### Respuesta Correcta: 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). +Lo que hace JS aquí es registrar el objeto debido a que acabamos de crear un objeto vacío en el objeto global. Cuando escribimos erróneamente `greeting` como` greetign`, el intérprete de JS ve esto como `global.greetign = {}` (o `window.greetign = {}` en un navegador). -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. +Para evitar esto, podemos usar el ["uso estricto"](https://developer.mozilla.org/es/docs/Web/JavaScript/Referencia/Modo_estricto). Esto asegura que se haya declarado una variable antes de establecerla igual a cualquier cosa.

--- -###### 10. What happens when we do this? +###### 10. ¿Qué ocurre cuando hacemos esto? ```javascript function bark() { @@ -314,19 +313,19 @@ function bark() { bark.animal = "dog"; ``` -- A: Nothing, this is totally fine! -- B: `SyntaxError`. You cannot add properties to a function this way. +- A: No pasa nada, es totalmente correcto. +- B: `SyntaxError`. No es posible agregar propiedades a una función de esta manera. - C: `undefined` - D: `ReferenceError` -
Answer +
Solución

-#### Answer: A +#### Respuesta Correcta: A -This is possible in JavaScript, because functions are objects! (Everything besides primitive types are objects) +Esto es perfectamente posible en JavaScript, porque las funciones son objetos (Recuerda: Todo aparte de los tipos primitivos son objetos en JS) -A function is a special type of object. The code you write yourself isn't the actual function. The function is an object with properties. This property is invocable. +Una función es un tipo especial de objeto. El código que escribes tú mismo no es la función real. La función es un objeto con propiedades. Esta propiedad es invocable.

From 1ff34117dacb7eb6b7149943a17e65ee74912434 Mon Sep 17 00:00:00 2001 From: karataev Date: Tue, 18 Jun 2019 23:13:51 +0700 Subject: [PATCH 016/915] Add link to the RU translation --- README.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index ad45ee46..1b199dec 100644 --- a/README.md +++ b/README.md @@ -6,7 +6,8 @@ From basic to advanced: test how well you know JavaScript, refresh your knowledg The answers are in the collapsed sections below the questions, simply click on them to expand it. Good luck :heart: -[中文版本](./README-zh_CN.md) +[中文版本](./README-zh_CN.md) +[Русский](./README_ru-RU.md) --- From b570e862fcdd74da621f9a9ed07f4376b54df826 Mon Sep 17 00:00:00 2001 From: nedimf <24845593+nedimf@users.noreply.github.com> Date: Tue, 18 Jun 2019 19:42:29 +0200 Subject: [PATCH 017/915] Translated on South balkan languages (BS,CRO,SRB) Readme translation for south balkan language area.Enjoy! --- README.md | 1689 +++++++++++++++++++++++++++++------------------------ 1 file changed, 926 insertions(+), 763 deletions(-) diff --git a/README.md b/README.md index 681b8e86..3c980a03 100644 --- a/README.md +++ b/README.md @@ -1,245 +1,293 @@ -# List of (Advanced) JavaScript Questions +Popis (naprednih) JavaScript pitanja +======================================= -I post daily multiple choice JavaScript questions on my [Instagram](https://www.instagram.com/theavocoder), which I'll also post here! +Svakodnevno postavljam JavaScript pitanja s višestrukim izborom na moj +[Instagram] (https://www.instagram.com/theavocoder), koja također objavljujem +ovdje! -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 weekly with new questions. +Od osnovnog do naprednog: testirajte koliko dobro znate JavaScript, osvježite svoj +znanje malo, ili pripremiti za svoj intervju! : :: rocket: +Ovaj tjedni repo ažuriram s newm pitanjima. -The answers are in the collapsed sections below the questions, simply click on them to expand it. Good luck :heart: +Odgovori su jednostavno dijelovima ispod pitanja +kliknite na njih da biste ih proširili. Sretno: srce: -[中文版本](./README-zh_CN.md) +[中文 版本] (./ README-zh_CN.md) ---- +* * * * * -###### 1. What's the output? +###### 1. Što je izlaz? -```javascript -function sayHi() { - console.log(name); - console.log(age); - var name = "Lydia"; - let age = 21; +`` `{.javascript} +function sayHi () { + console.log (ime); + console.log (starosti); + var ime = "Lydia"; + let starost = 21; } sayHi(); -``` +`` ` -- A: `Lydia` and `undefined` -- B: `Lydia` and `ReferenceError` -- C: `ReferenceError` and `21` -- D: `undefined` and `ReferenceError` +- A: "Lydia" i "undefined" +- B: "Lydia" i "ReferenceError" +- C: "ReferenceError" i "21" +- D: `undefined` i` ReferenceError` -
Answer +
Odgovor

-#### Answer: D +#### Odgovor: D -Within the function, we first declare the `name` variable with the `var` keyword. This means that the variable gets hoisted (memory space is set up during the creation phase) with the default value of `undefined`, until we actually get to the line where we define the variable. We haven't defined the variable yet on the line where we try to log the `name` variable, so it still holds the value of `undefined`. +Unutar funkcije, najprije deklarišemo varijablu `name` s` var` +ključne riječi. To znači da se varijabla podiže (memorijski prostor je postavljen +tijekom faze izrade) sa zadanom vrijednošću `undefined`, +dok zapravo ne dođemo do linije gdje definiramo varijablu. Mi +još nismo definirali varijablu na liniji gdje pokušavamo prijaviti +varijabla `name`, tako da još uvijek sadrži vrijednost` undefined`. -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`. +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". +Kada pokušamo pristupiti varijablama prije nego što budu deklarirane, +JavaScript iz bacuje `ReferenceError`.

-
+ ---- +* * * * * -###### 2. What's the output? +###### 2. Što je izlaz? -```javascript -for (var i = 0; i < 3; i++) { - setTimeout(() => console.log(i), 1); +`` `{.javascript} +za (var i = 0; i <3; i ++) { + setTimeout (() => console.log (i), 1); } -for (let i = 0; i < 3; i++) { - setTimeout(() => console.log(i), 1); +za (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` +- A: `0 1 2` i` 0 1 2` +- B: "0 1 2" i "3 3 3" +- C: "3 3 3" i "0 1 2" -
Answer -

+

Odgovor +

-#### Answer: C +#### Odgovor: C -Because of the event queue in JavaScript, the `setTimeout` callback function is called _after_ the loop has been executed. Since the variable `i` in the first loop was declared using the `var` keyword, this value was global. During the loop, we incremented the value of `i` by `1` each time, using the unary operator `++`. By the time the `setTimeout` callback function was invoked, `i` was equal to `3` in the first example. +Zbog reda događaja u JavaScriptu, povratni poziv `setTimeout` +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 +Pozvana je function povratnog poziva `setTimeout`,` i` je bila jednaka `3` u +u prvom primjeru. -In the second loop, the variable `i` was declared using the `let` keyword: variables declared with the `let` (and `const`) keyword are block-scoped (a block is anything between `{ }`). During each iteration, `i` will have a new value, and each value is scoped inside the loop. +U drugoj petlji, varijabla `i` je deklarirana pomoću` let` +ključna riječ: varijable deklarirane s ključnom riječi `let` (i` const`) su +block-scoped (blok je sve između `{}`). Tijekom svake iteracije, +`i` će imati novu vrijednost, a svaka vrijednost će biti obuhvaćena unutar petlje. -

-
+ + ---- +* * * * * -###### 3. What's the output? +###### 3. Što je izlaz? -```javascript -const shape = { - radius: 10, - diameter() { +`` `{.javascript} +const oblik = { + radijus: 10, + promjer() { return this.radius * 2; - }, - perimeter: () => 2 * Math.PI * this.radius + } + perimetar: () => 2 * Math.PI * this.radius }; -shape.diameter(); -shape.perimeter(); -``` +oblik.radijus (); +oblik.promjer (); +`` ` -- A: `20` and `62.83185307179586` -- B: `20` and `NaN` -- C: `20` and `63` -- D: `NaN` and `63` +- A: "20" i "62.83185307179586" +- B: "20" i "NaN" +- C: "20" i "63" +- D: "NaN" i "63" -
Answer -

+

Odgovor +

-#### Answer: B +#### Odgovor: B -Note that the value of `diameter` is a regular function, whereas the value of `perimeter` is an arrow function. +Imajte na umu da je vrijednost "promjera" uobičajena function, dok je vrijednost promjera +vrijednost "perimetra" je function strelice. -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). +Sa functionma strelica, ključna riječ "this" odnosi se na njegovo trenutno +okolno područje, za razliku od uobičajenih function! To znači kada +nazovemo 'perimetar', ne odnosi se na objekt oblika, već na njegov +okruženje (primjerice, prozor). -There is no value `radius` on that object, which returns `undefined`. +Na tom objektu nema vrijednosti `radius` koja vraća` undefined`. -

-
+ + ---- +* * * * * -###### 4. What's the output? +###### 4. Što je izlaz? -```javascript -+true; -!"Lydia"; -``` +`` `{.javascript} ++ True; +! "Lydia"; +`` ` -- A: `1` and `false` -- B: `false` and `NaN` -- C: `false` and `false` +- A: "1" i "false" +- B: "false" i "NaN" +- C: "false" i "false" -
Answer -

+

Odgovor +

-#### Answer: A +#### Odgovor: A -The unary plus tries to convert an operand to a number. `true` is `1`, and `false` is `0`. +Unary plus pokušava pretvoriti operand u broj. "true" je "1", +i "false" je "0". -The string `'Lydia'` is a truthy value. What we're actually asking, is "is this truthy value falsy?". This returns `false`. +Niz '' Lydia '' je istinita vrijednost. Ono što zapravo tražimo jest +"je li ta istinita vrijednost lažna?". Ovo vraća "false". -

-
+ + ---- +* * * * * -###### 5. Which one is true? +###### 5. Koja je istina? -```javascript +`` `{.javascript} const bird = { size: "small" }; const mouse = { - name: "Mickey", + ime: "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 +- A: `mouse.bird.size 'nije valjan +- B: `mouse [bird.size]` nije važeća +- C: `miš [ptica [" veličina "]]` nije važeća +- D: Svi su valjani -
Answer -

+

Odgovor +

-#### Answer: A +#### Odgovor: A -In JavaScript, all object keys are strings (unless it's a Symbol). Even though we might not _type_ them as strings, they are always converted into strings under the hood. +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 +u String ispod "haube". -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. +JavaScript tumači (ili odlaže) izjave. Kada koristimo zagradu +notacija, on vidi prvu otvarnu zagradu `` `i nastavlja dalje do nje +pronalazi završnu zagradu `]`. Tek tada će procijeniti +izjava. -`mouse[bird.size]`: First it evaluates `bird.size`, which is `"small"`. `mouse["small"]` returns `true` +`mouse [bird.size]`: Prvo procjenjuje `bird.size`, što je` `small``. +`mouse [" small "]` vraća "true" -However, with dot notation, this doesn't happen. `mouse` does not have a key called `bird`, which means that `mouse.bird` is `undefined`. Then, we ask for the `size` using dot notation: `mouse.bird.size`. Since `mouse.bird` is `undefined`, we're actually asking `undefined.size`. This isn't valid, and will throw an error similar to `Cannot read property "size" of undefined`. +Međutim, s točkastom notacijom, to se ne događa. `miša 'nema a +key naziva se 'bird', što znači da je `mouse.bird`` undefined`. Zatim, +tražimo "veličinu" koristeći točkovni zapis: `mouse.bird.size '. Od +`mouse.bird` je` undefined`, zapravo pitamo `undefined.size`. +To nije valjano, a bit će u pitanju pogreška slična onoj +`Cannot read property "size" of undefined`. -

-
+ + ---- +* * * * * ---- +* * * * * -###### 6. What's the output? +###### 6. Što je izlaz? -```javascript -let c = { greeting: "Hey!" }; +`` `{.javascript} +let c = {greeting: "Hej!" }; let d; d = c; -c.greeting = "Hello"; -console.log(d.greeting); -``` +c.greeting = "Pozdrav"; +console.log (d.greeting); +`` ` -- A: `Hello` -- B: `Hey` +- A: "Zdravo" +- B: 'Hej' - C: `undefined` -- D: `ReferenceError` +- D: "ReferenceError" - E: `TypeError` -
Answer -

+

Odgovor +

-#### Answer: A +#### Odgovor: A -In JavaScript, all objects interact by _reference_ when setting them equal to each other. +U JavaScriptu, svi objekti međusobno djeluju * referencom * kada ih postavljaju +jednaki. -First, variable `c` holds a value to an object. Later, we assign `d` with the same reference that `c` has to the object. +Prvo, varijabla `c` sadrži vrijednost objekta. Kasnije dodijelimo `d` +s istom referencom koju `c 'ima na objekt. - + -When you change one object, you change all of them. +Kada promijenite jedan objekt, mijenjate ih sve. -

-
+ + ---- +* * * * * -###### 7. What's the output? +###### 7. Što je izlaz? -```javascript -let a = 3; -let b = new Number(3); -let c = 3; +`` `{.javascript} +let je a = 3; +let je b = new broj (3); +let je 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` -- 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` -
Answer -

+

Odgovor +

-#### Answer: C +#### Odgovor: 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. +`new Number ()` je ugrađeni konstruktor function. Iako izgleda +kao broj, to zapravo nije broj: ima gomilu ekstra dodataka +pa je zbog toga objekt. -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`. +Kada koristimo `==` operatora, on samo provjerava ima li isti +*vrijednost*. Obje imaju vrijednost `3`, pa se vraća '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.` +Međutim, kada koristimo `===` operator, obje vrijednosti * i * trebaju biti +isto. To nije: `new Number ()` nije broj, to je ** objekt **. +Oba vraćaju "false" -

-
+ + ---- +* * * * * -###### 8. What's the output? +###### 8. Što je izlaz? ```javascript class Chameleon { @@ -248,7 +296,7 @@ class Chameleon { return this.newColor; } - constructor({ newColor = "green" } = {}) { + constructor({ newColor = "zelena" } = {}) { this.newColor = newColor; } } @@ -257,50 +305,58 @@ const freddie = new Chameleon({ newColor: "purple" }); freddie.colorChange("orange"); ``` -- A: `orange` -- B: `purple` -- C: `green` +- A: 'narančasta' +- B: "ljubičasta" +- C: "zelena" - D: `TypeError` -
Answer -

+

Odgovor +

-#### Answer: D +#### Odgovor: 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. +function `colorChange` je statična. Namijenjene su statičkim metodama +ž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`. -

-
+ + ---- +* * * * * -###### 9. What's the output? +###### 9. Što je izlaz? -```javascript -let greeting; -greetign = {}; // Typo! -console.log(greetign); -``` +`` `{.javascript} +let pozdravi; +greeting = {}; // Typo! +console.log (greetign); +`` ` - A: `{}` -- B: `ReferenceError: greetign is not defined` +- B: `ReferenceError: greetign nije definiran ' - C: `undefined` -
Answer -

+

Odgovor +

-#### Answer: A +#### Odgovor: 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). +Zapisuje objekt, jer smo upravo stvorili prazan objekt na +globalni objekt! Kada smo pogrešno ukucali `pozdrav` kao` greeting`, JS +interpreter je zapravo to vidio kao `global.greeting = {}` (ili +`window.greeting = {}` u pregledniku). -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. +Kako bismo to izbjegli, možemo koristiti `` use strict ''. To osigurava to +da ste deklarirali varijablu prije nego je postavite na bilo što. -

-
+ + ---- +* * * * * -###### 10. What happens when we do this? +###### 10. Što se događa kada to učinimo? ```javascript function bark() { @@ -310,983 +366,1090 @@ function bark() { bark.animal = "dog"; ``` -- A: Nothing, this is totally fine! -- B: `SyntaxError`. You cannot add properties to a function this way. +- A: Ništa, ovo je u redu! +- B: `SyntaxError`. Na ovaj način ne možete dodavati svojstva funkciji. - C: `undefined` -- D: `ReferenceError` +- D: "ReferenceError" -
Answer -

+

Odgovor +

-#### Answer: A +#### Odgovor: A -This is possible in JavaScript, because functions are objects! (Everything besides primitive types are objects) +To je moguće u JavaScriptu, jer su funkcije objekti! +(Sve osim primitivnih tipova su objekti) -A function is a special type of object. The code you write yourself isn't the actual function. The function is an object with properties. This property is invocable. +function je posebna vrsta objekta. Kod koji sami napišete +nije stvarna function. function je objekt sa svojstvima. +Ova nekretnina je nepovratna. -

-
+ + ---- +* * * * * -###### 11. What's the output? +###### 11. Kakav je rezultat? -```javascript -function Person(firstName, lastName) { - this.firstName = firstName; - this.lastName = lastName; +`` `{.javascript} +function Person (ime, prezime) { + this.ime = ime; + this.prezime = prezime; } -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.ime} $ {this.prezime}`; }; -console.log(member.getFullName()); -``` +console.log (member.getFullName ()); +`` ` - A: `TypeError` - B: `SyntaxError` -- C: `Lydia Hallie` -- D: `undefined` `undefined` +- C: "Lydia Hallie" +- D: `undefined`` undefined` -
Answer -

+

Odgovor +

-#### Answer: A +#### Odgovor: A -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, +Ne možete dodati svojstva konstruktoru kao što možete s uobičajenim +objekti. Ako želite dodati značajku svim objektima odjednom, imate +umjesto toga koristiti prototip. Dakle, u ovom slučaju, -```js -Person.prototype.getFullName = function() { - return `${this.firstName} ${this.lastName}`; +`` `{.js} +Person.prototype.getFullName = function () { + return `$ {this.ime} $ {this.prezime}`; }; -``` +`` ` -would have made `member.getFullName()` work. Why is this beneficial? Say that we added this method to the constructor itself. Maybe not every `Person` instance needed this method. This would waste a lot of memory space, since they would still have that property, which takes of memory space for each instance. Instead, if we only add it to the prototype, we just have it at one spot in memory, yet they all have access to it! +bi učinio `member.getFullName ()`. Zašto je to korisno? Reći će mo +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! -

-
+ + ---- +* * * * * -###### 12. What's the output? +###### 12. Što je izlaz? -```javascript -function Person(firstName, lastName) { - this.firstName = firstName; - this.lastName = lastName; +`` `{.javascript} +function Person (ime, prezime) { + this.ime = ime; + this.prezime = prezime; } -const lydia = new Person("Lydia", "Hallie"); -const sarah = Person("Sarah", "Smith"); +const lydia = new Person ("Lydia", "Hallie"); +const sarah = Person ("Sara", "Smith"); -console.log(lydia); -console.log(sarah); -``` +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` +- A: `Person {ime:" Lydia ", prezime:" Hallie "} i` undefined` +- B: `Person {ime:" Lydia ", prezime:" Hallie "} i + `Person {ime:" Sarah ", prezime:" Smith "}` +- C: `Person {ime:" Lydia ", prezime:" Hallie "}` i `{}` +- D: `Person {ime:" Lydia ", prezime:" Hallie "} i + `ReferenceError` -
Answer -

+

Odgovor +

-#### Answer: A +#### Odgovor: A -For `sarah`, we didn't use the `new` keyword. When using `new`, it refers to the new empty object we create. However, if you don't add `new` it refers to the **global object**! +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 +`new` se odnosi na ** globalni objekt **! -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`. +Rekli smo da je "this.ime" jednako "Sarah" i `this.prezime` +jednak je "Smithu". Ono što smo zapravo učinili jest definiranje +`global.ime = 'Sarah'` i` global.prezime =' Smith'`. `sarah` +sam je ostavljen 'undefined'. -

-
+ + ---- +* * * * * -###### 13. What are the three phases of event propagation? +###### 13. Koje su tri faze propagiranja događaja? - A: Target > Capturing > Bubbling - B: Bubbling > Target > Capturing - C: Target > Bubbling > Capturing - D: Capturing > Target > Bubbling -
Answer -

-#### Answer: D +

Odgovor +

-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. +#### Odgovor: D - +Tijekom ** capturing ** događaj prolazi kroz pretka +elemente do ciljnog elementa. Zatim doseže ** target ** +i ** bubbling **. -

-
+ ---- + + -###### 14. All object have prototypes. +* * * * * -- A: true -- B: false +###### 14. Svi objekti imaju prototipove. -
Answer -

+- Istinito +- B: lažno -#### Answer: B +

Odgovor +

-All objects have prototypes, except for the **base object**. 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. +#### Odgovor: B -

-
+Svi objekti imaju prototipove, osim ** osnovnog objekta **. Uporište +objekt ima pristup nekim metodama i svojstvima, kao što je `.toString`. +To je razlog zašto možete koristiti ugrađene JavaScript metode! Sve od +takve su metode dostupne na prototipu. Iako JavaScript ne može +pronaći ga izravno na vašem objektu, ide niz lanac prototipa i +nalazi ga tamo, što ga čini dostupnim. ---- + + -###### 15. What's the output? +* * * * * -```javascript -function sum(a, b) { +###### 15. Što je izlaz? + +`` `{.javascript} +function sum (a, b) { return a + b; } -sum(1, "2"); -``` +sum (1, "2"); +`` ` -- A: `NaN` +- A: "NaN" - B: `TypeError` -- C: `"12"` +- C: "12" - D: `3` -
Answer -

+

Odgovor +

-#### Answer: C +#### Odgovor: 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. +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. -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"`. +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 "`. -

-
+ + ---- +* * * * * -###### 16. What's the output? +###### 16. Što je izlaz? -```javascript -let number = 0; -console.log(number++); -console.log(++number); -console.log(number); -``` +`` `{.javascript} +let je broj = 0; +console.log (broj ++); +console.log (++ broj); +console.log (broj); +`` ` -- 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` -
Answer -

+

Odgovor +

-#### Answer: C +#### Odgovor: C -The **postfix** unary operator `++`: +** postfix ** unarni operator `++`: -1. Returns the value (this returns `0`) -2. Increments the value (number is now `1`) +1. Vraća vrijednost (ovo vraća `0`) +2. Povećava vrijednost (broj je sada `1`) -The **prefix** unary operator `++`: +** prefiks ** unary operator `++`: -1. Increments the value (number is now `2`) -2. Returns the value (this returns `2`) +1. Povećava vrijednost (broj je sada `2`) +2. Vraća vrijednost (ovo vraća `2`) -This returns `0 2 2`. +Ovo vraća `0 2 2`. -

-
+ + ---- +* * * * * -###### 17. What's the output? +###### 17. Što je izlaz? -```javascript -function getPersonInfo(one, two, three) { - console.log(one); - console.log(two); - console.log(three); +`` `{.javascript} +function getPersonInfo (one, two, tree) { + console.log (one); + console.log (two); + console.log (tree); } -const person = "Lydia"; +const Person = "Lydia"; const age = 21; -getPersonInfo`${person} is ${age} years old`; -``` +getPersonInfo` $ {Person} je $ {old} godina '; +`` ` -- A: `"Lydia"` `21` `["", " is ", " years old"]` -- B: `["", " is ", " years old"]` `"Lydia"` `21` -- C: `"Lydia"` `["", " is ", " years old"]` `21` +- A: `` Lydia` `` `` `` `` `` `` `` `` `` `` `` `` `` `` `` `` `` `` `` +- B: `` `` `` `` `` `` `` `` `` `` `` `` `` `` `` `` `` `` `` `` `` `` `` `` `` `` `` `` `` `` `` `` `` `` `` `` `` ` +- C: `` Lydia` `` `` `` `` `` `` `` `` `` `` `` `` `` `` `` `` `` `` `` `` `` `` `` `` `` `` `` `` `` -
Answer -

+

Odgovor +

-#### Answer: B +#### Odgovor: 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! +Ako koristite literale s oznakom predložaka, vrijednost prvog argumenta je +uvijek niz vrijednosti vrijednosti niza. Preostali argumenti dobivaju +vrijednosti prošlih izraza! -

-
+ + ---- +* * * * * -###### 18. What's the output? +###### 18. Što je izlaz? -```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."); +`` `{.javascript} +function checkAge (podaci) { + ako (podaci === {age: 18}) { + console.log ("Vi ste odrasla osoba!"); + } else if (data == {age: 18}) { + console.log ("Vi ste još uvijek odrasla osoba."); } else { - console.log(`Hmm.. You don't have an age I guess`); + console.log (`Hmm .. Nemate dobnu pretpostavku`); } } -checkAge({ age: 18 }); -``` +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: "Vi ste odrasla osoba!" +- B: "Vi ste još uvijek odrasla osoba." +- C: 'Hmm .. Nemam godina za koju pretpostavljam' -
Answer -

+

Odgovor +

-#### Answer: C +#### Odgovor: 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. +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. -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. +Dva predmeta koje uspoređujemo nemaju: objekt mi +proslijeđeno kao parametar odnosi se na drugo mjesto u memoriji od +objekt koji smo koristili kako bismo provjerili jednakost. -This is why both `{ age: 18 } === { age: 18 }` and `{ age: 18 } == { age: 18 }` return `false`. +Zato i `{age: 18} === {age: 18}` i +`{age: 18} == {age: 18}` return `false '. -

-
+ + ---- +* * * * * -###### 19. What's the output? +###### 19. Što je izlaz? -```javascript -function getAge(...args) { - console.log(typeof args); +`` `{.javascript} +function getAge (... args) { + console.log (vrsta argumenta); } -getAge(21); -``` +getAge (21); +`` ` -- A: `"number"` -- B: `"array"` -- C: `"object"` -- D: `"NaN"` +- A: `" broj " +- B: `` niz '' +- C: `` objekt '' +- D: "NaN" -
Answer -

+

Odgovor +

-#### Answer: C +#### Odgovor: C -The spread operator (`...args`.) returns an array with arguments. An array is an object, so `typeof args` returns `"object"` +Operator spread (`... args`.) Vraća niz s argumentima. +array je objekt, pa `typeof args` vraća` `objekt '` -

-
+ + ---- +* * * * * -###### 20. What's the output? +###### 20. Što je izlaz? -```javascript -function getAge() { - "use strict"; - age = 21; - console.log(age); +`` `{.javascript} +function getAge () { + "koristite strogi"; + starost = 21; + console.log (starosti); } -getAge(); -``` +getAge (); +`` ` - A: `21` - B: `undefined` -- C: `ReferenceError` +- C: "ReferenceError" - D: `TypeError` -
Answer -

+

Odgovor +

-#### Answer: C +#### Odgovor: 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. +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 +nije koristio "" strict ", to bi išlo od vlasništva +`age` bi se dodao u globalni objekt. -

-
+ + ---- +* * * * * -###### 21. What's value of `sum`? +###### 21. Što je vrijednost `suma '? -```javascript -const sum = eval("10*10+5"); -``` +`` `{.javascript} +const sum = eval ("10x10 + 5"); +`` ` -- A: `105` -- B: `"105"` +- A: "105" +- B: `" 105 "` - C: `TypeError` -- D: `"10*10+5"` +- D: `" 10 * 10 + 5 "` -
Answer -

+

Odgovor +

-#### Answer: A +#### Odgovor: 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` procjenjuje kodove koji su prošli kao niz. Ako je to izraz, +kao u ovom slučaju, on ocjenjuje izraz. Izraz je +`10 * 10 + 5`. Ovo vraća broj "105". -

-
+ + ---- +* * * * * -###### 22. How long is cool_secret accessible? +###### 22. Koliko dugo je cool \ _secret dostupan? -```javascript -sessionStorage.setItem("cool_secret", 123); -``` +`` `{.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. +O: Podaci se zauvijek ne izgube. +- B: Kada korisnik zatvori karticu. +- C: Kada korisnik zatvori cijeli preglednik, ne samo karticu. +- D: Kada korisnik isključi svoje računalo. -
Answer -

+

Odgovor +

-#### Answer: B +#### Odgovor: B -The data stored in `sessionStorage` is removed after closing the _tab_. +Podaci spremljeni u `sessionStorage` se uklanjaju nakon zatvaranja * tab *. -If you used `localStorage`, the data would've been there forever, unless for example `localStorage.clear()` is invoked. +Ako ste koristili `localStorage`, podaci bi bili tamo zauvijek, osim ako +na primjer, `localStorage.clear ()` je pozvan. -

-
+ + ---- +* * * * * -###### 23. What's the output? +###### 23. Što je izlaz? -```javascript +`` `{.javascript} var num = 8; var num = 10; -console.log(num); -``` +console.log (num); +`` ` - A: `8` -- B: `10` +- B: "10" - C: `SyntaxError` -- D: `ReferenceError` +- D: "ReferenceError" -
Answer -

+

Odgovor +

-#### Answer: B +#### Odgovor: B -With the `var` keyword, you can declare multiple variables with the same name. The variable will then hold the latest value. +Pomoću ključne riječi `var` možete deklarirati više varijabli s istom +Ime. Varijabla će tada sadržavati zadnju vrijednost. -You cannot do this with `let` or `const` since they're block-scoped. +To ne možete učiniti s `let` ili` const` jer su blokirani. -

-
+ + ---- +* * * * * -###### 24. What's the output? +###### 24. Što je izlaz? -```javascript -const obj = { 1: "a", 2: "b", 3: "c" }; -const set = new Set([1, 2, 3, 4, 5]); +`` `{.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); -``` +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` +- A: `false`` true` `false`` true` +- B: `false`` true` `true`` true` +- C: `true`` true` `false`` true` +- D: `true`` true` `true`` true` -
Answer -

+

Odgovor +

-#### Answer: C +#### Odgovor: 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. +Sve tipke objekta (osim simbola) su žice ispod haube, čak i ako +ne upisujete sami kao niz znakova. To je razlog zašto +`obj.hasOwnProperty ('1')` također vraća 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`. +To ne radi tako za skup. U našem setu ne postoji "1": +`set.has ('1')` vraća `false`. Ima numerički tip "1", +`set.has (1)` vraća `true`. -

-
+ + ---- +* * * * * -###### 25. What's the output? +###### 25. Što je izlaz? -```javascript -const obj = { a: "one", b: "two", a: "three" }; -console.log(obj); -``` +`` `{.javascript} +const obj = {a: "jedan", b: "dva", a: "tri"}; +console.log (obj); +`` ` -- A: `{ a: "one", b: "two" }` -- B: `{ b: "two", a: "three" }` -- C: `{ a: "three", b: "two" }` +- A: `{a:" jedan ", b:" dva "}` +- B: `{b:" dva ", a:" tri "}` +- C: `{a:" tri ", b:" dva "}` - D: `SyntaxError` -
Answer -

+

Odgovor +

-#### Answer: C +#### Odgovor: 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. +Ako imate dva ključa s istim imenom, ključ će biti zamijenjen. To +i dalje će biti na prvom mjestu, ali s posljednjom navedenom vrijednošću. -

-
+ + ---- +* * * * * -###### 26. The JavaScript global execution context creates two things for you: the global object, and the "this" keyword. +###### 26. Globalni kontekst izvođenja JavaScripta za vas stvara dvije stvari: globalni objekt i "ovu" ključnu riječ. -- A: true -- B: false -- C: it depends +- Istina +- B: lažno +- C: to ovisi -
Answer -

+

Odgovor +

-#### Answer: A +#### Odgovor: A -The base execution context is the global execution context: it's what's accessible everywhere in your code. +Kontekst izvršenja baze je kontekst globalnog izvršavanja: to je ono što je +dostupno svugdje u vašem kodu. -

-
+ + ---- +* * * * * -###### 27. What's the output? +###### 27. Što je izlaz? -```javascript -for (let i = 1; i < 5; i++) { - if (i === 3) continue; - console.log(i); +`` `{.javascript} +za (let i = 1; i <5; i ++) { + ako (i === 3) nastavite; + 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` -
Answer -

+

Odgovor +

-#### Answer: C +#### Odgovor: C -The `continue` statement skips an iteration if a certain condition returns `true`. +Izjava `continue` preskače iteraciju ako je određeno stanje +vraća "true". -

-
+ + ---- +* * * * * -###### 28. What's the output? +###### 28. Što je izlaz? -```javascript +`` `{.javascript} String.prototype.giveLydiaPizza = () => { - return "Just give Lydia pizza already!"; + povratak "Dajte već picu Lydiju!"; }; -const name = "Lydia"; +const ime = "Lydia"; -name.giveLydiaPizza(); -``` +name.giveLydiaPizza (); +`` ` -- A: `"Just give Lydia pizza already!"` -- B: `TypeError: not a function` +- A: `` Već daj Lizijinu pizzu! `` +- B: `TypeError: nije function` - C: `SyntaxError` - D: `undefined` -
Answer -

+

Odgovor +

-#### Answer: A +#### Odgovor: 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 'je ugrađeni konstruktor, kojem možemo dodati svojstva. ja +samo je dodao metodu u svoj prototip. Primitivni nizovi su +automatski se pretvara u string objekt, generiran stringom +prototipna function. Dakle, svi nizovi (objekti stringova) imaju pristup tome +način! -

-
+ + ---- +* * * * * -###### 29. What's the output? +###### 29. Što je izlaz? -```javascript +`` `{.javascript} const a = {}; -const b = { key: "b" }; -const c = { key: "c" }; +const b = {ključ: "b"}; +const c = {ključ: "c"}; -a[b] = 123; -a[c] = 456; +a [b] = 123; +a [c] = 456; -console.log(a[b]); -``` +console.log (a [b]); +`` ` -- A: `123` -- B: `456` +- A: '123' +- B: "456" - C: `undefined` -- D: `ReferenceError` +- D: "ReferenceError" -
Answer -

+

Odgovor +

-#### Answer: B +#### Odgovor: 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`. +Tipke objekta automatski se pretvaraju u nizove. Pokušavamo +postavite objekt kao ključ za objekt "a", s vrijednošću "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`. +Međutim, kada stringificiramo objekt, on postaje `` [Objekt objekt] '`. Tako +ono što ovdje govorimo je da je `a [" Objekt objekt "] = 123`. Onda, mi +može ponovno pokušati učiniti isto. "c" je još jedan objekt koji jesmo +implicitno ograničavaju. Dakle, `a [" Objekt objekt "] = 456`. -Then, we log `a[b]`, which is actually `a["Object object"]`. We just set that to `456`, so it returns `456`. +Zatim zapisujemo `a [b]`, što je zapravo `a [" Objekt objekt "]`. Upravo smo postavili +da na `456`, tako da se vraća` 456`. -

-
+ + ---- +* * * * * -###### 30. What's the output? +###### 30. Što je izlaz? -```javascript -const foo = () => console.log("First"); -const bar = () => setTimeout(() => console.log("Second")); -const baz = () => console.log("Third"); +`` `{.javascript} +const foo = () => console.log ("Prvo"); +const bar = () => setTimeout (() => console.log ("Drugi")); +const baz = () => console.log ("Treći"); bar(); -foo(); -baz(); -``` +foo (); +baz (); +`` ` -- A: `First` `Second` `Third` -- B: `First` `Third` `Second` -- C: `Second` `First` `Third` -- D: `Second` `Third` `First` +- A: `Prvi`` Drugi` `Treći` +- B: `Prvi`` Treći` `Drugi` +- C: `Drugi`` Prvi` `Treći` +- D: `Drugi`` Treći` `Prvi` -
Answer -

+

Odgovor +

-#### Answer: B +#### Odgovor: B -We have a `setTimeout` function and invoked it first. Yet, it was logged last. +Imamo funkciju "setTimeout" i prvo je pozvali. Ipak, bio je prijavljen +posljednji. -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. +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. -After the _callback_ is pushed to the WebAPI, the `setTimeout` function itself (but not the callback!) is popped off the stack. +Nakon što je * callback * preusmjeren na WebAPI, function `setTimeout` +sam (ali ne i povratni poziv!) iskače iz stog. - + -Now, `foo` gets invoked, and `"First"` is being logged. +Sada se `foo` poziva i` `Prvo`` se bilježi. - + -`foo` is popped off the stack, and `baz` gets invoked. `"Third"` gets logged. +`foo` je iskačen iz stog, i` baz` se poziva. "Treći" dobiva +prijavljeni. - + -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_. +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*. - + -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. +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. - + -`bar` gets invoked, `"Second"` gets logged, and it's popped off the stack. +`bar` se priziva,` `Second`` se bilježi, i on se pojavio +stog. -

-
+ + ---- +* * * * * -###### 31. What is the event.target when clicking the button? +###### 31. Što je event.target kada kliknete na gumb? -```html -
-
- -
-
-``` +`` `{.html} +
+
+
* * * * * @@ -131,8 +131,8 @@ okruženje (primjerice, prozor). Na tom objektu nema vrijednosti `radius` koja vraća` undefined`. - - +

+
* * * * * @@ -158,8 +158,8 @@ i "false" je "0". Niz '' Lydia '' je istinita vrijednost. Ono što zapravo tražimo jest "je li ta istinita vrijednost lažna?". Ovo vraća "false". - - +

+
* * * * * @@ -205,8 +205,8 @@ tražimo "veličinu" koristeći točkovni zapis: `mouse.bird.size '. Od To nije valjano, a bit će u pitanju pogreška slična onoj `Cannot read property "size" of undefined`. - - +

+
* * * * * @@ -244,8 +244,8 @@ s istom referencom koju `c 'ima na objekt. Kada promijenite jedan objekt, mijenjate ih sve. - - +

+
* * * * * @@ -282,8 +282,8 @@ Međutim, kada koristimo `===` operator, obje vrijednosti * i * trebaju biti isto. To nije: `new Number ()` nije broj, to je ** objekt **. Oba vraćaju "false" - - +

+
* * * * * @@ -321,8 +321,8 @@ 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`. - - +

+
* * * * * @@ -351,8 +351,8 @@ interpreter je zapravo to vidio kao `global.greeting = {}` (ili Kako bismo to izbjegli, možemo koristiti `` use strict ''. To osigurava to da ste deklarirali varijablu prije nego je postavite na bilo što. - - +

+
* * * * * @@ -383,8 +383,8 @@ function je posebna vrsta objekta. Kod koji sami napišete nije stvarna function. function je objekt sa svojstvima. Ova nekretnina je nepovratna. - - +

+
* * * * * @@ -431,8 +431,8 @@ 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! - - +

+
* * * * * @@ -472,8 +472,8 @@ jednak je "Smithu". Ono što smo zapravo učinili jest definiranje `global.ime = 'Sarah'` i` global.prezime =' Smith'`. `sarah` sam je ostavljen 'undefined'. - - +

+
* * * * * @@ -496,8 +496,8 @@ i ** bubbling **. - - +

+
* * * * * @@ -518,8 +518,8 @@ takve su metode dostupne na prototipu. Iako JavaScript ne može pronaći ga izravno na vašem objektu, ide niz lanac prototipa i nalazi ga tamo, što ga čini dostupnim. - - +

+
* * * * * @@ -555,8 +555,8 @@ se tretira kao niz. Možemo slično spojiti "" Zdravo "+" Svijet "`, tako da se ovdje događa `````````````````` vraća `" 12 "`. - - +

+
* * * * * @@ -591,8 +591,8 @@ console.log (broj); Ovo vraća `0 2 2`. - - +

+
* * * * * @@ -624,8 +624,8 @@ Ako koristite literale s oznakom predložaka, vrijednost prvog argumenta je uvijek niz vrijednosti vrijednosti niza. Preostali argumenti dobivaju vrijednosti prošlih izraza! - - +

+
* * * * * @@ -665,8 +665,8 @@ objekt koji smo koristili kako bismo provjerili jednakost. Zato i `{age: 18} === {age: 18}` i `{age: 18} == {age: 18}` return `false '. - - +

+
* * * * * @@ -693,8 +693,8 @@ getAge (21); Operator spread (`... args`.) Vraća niz s argumentima. array je objekt, pa `typeof args` vraća` `objekt '` - - +

+
* * * * * @@ -726,8 +726,8 @@ budući da koristimo `` use strict '', ona će načiniti referentnu pogrešku. A nije koristio "" strict ", to bi išlo od vlasništva `age` bi se dodao u globalni objekt. - - +

+
* * * * * @@ -751,8 +751,8 @@ const sum = eval ("10x10 + 5"); kao u ovom slučaju, on ocjenjuje izraz. Izraz je `10 * 10 + 5`. Ovo vraća broj "105". - - +

+
* * * * * @@ -777,8 +777,8 @@ 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. - - +

+
* * * * * @@ -806,8 +806,8 @@ Ime. Varijabla će tada sadržavati zadnju vrijednost. To ne možete učiniti s `let` ili` const` jer su blokirani. - - +

+
* * * * * @@ -841,8 +841,8 @@ To ne radi tako za skup. U našem setu ne postoji "1": `set.has ('1')` vraća `false`. Ima numerički tip "1", `set.has (1)` vraća `true`. - - +

+
* * * * * @@ -866,8 +866,8 @@ console.log (obj); Ako imate dva ključa s istim imenom, ključ će biti zamijenjen. To i dalje će biti na prvom mjestu, ali s posljednjom navedenom vrijednošću. - - +

+
* * * * * @@ -885,8 +885,8 @@ i dalje će biti na prvom mjestu, ali s posljednjom navedenom vrijednošću. Kontekst izvršenja baze je kontekst globalnog izvršavanja: to je ono što je dostupno svugdje u vašem kodu. - - +

+
* * * * * @@ -912,8 +912,8 @@ za (let i = 1; i <5; i ++) { Izjava `continue` preskače iteraciju ako je određeno stanje vraća "true". - - +

+
* * * * * @@ -945,8 +945,8 @@ automatski se pretvara u string objekt, generiran stringom prototipna function. Dakle, svi nizovi (objekti stringova) imaju pristup tome način! - - +

+
* * * * * @@ -984,8 +984,8 @@ implicitno ograničavaju. Dakle, `a [" Objekt objekt "] = 456`. Zatim zapisujemo `a [b]`, što je zapravo `a [" Objekt objekt "]`. Upravo smo postavili da na `456`, tako da se vraća` 456`. - - +

+
* * * * * @@ -1047,8 +1047,8 @@ stvar u redu i gura je u stog. `bar` se priziva,` `Second`` se bilježi, i on se pojavio stog. - - +

+
* * * * * @@ -1077,8 +1077,8 @@ stog. Najdublji ugniježđeni element koji je uzrokovao događaj je cilj događaj. Možete zaustaviti mjehuriće 'event.stopPropagation' - - +

+
* * * * * @@ -1088,7 +1088,7 @@ događaj. Možete zaustaviti mjehuriće 'event.stopPropagation'

Kliknite ovdje! - +

``` @@ -1108,8 +1108,8 @@ zadani, rukovatelji događaja izvršavaju se u fazi mjehurića (osim ako vi postavite `useCapture` na` true`). Ide od najdubljih ugniježđenih elemenata van. - - +

+
* * * * * @@ -1142,8 +1142,8 @@ odnosi se na. Međutim, `.call` se također * izvršava odmah *! `.bind.` vraća * copy * funkcije, ali s vezanim kontekstom! To se ne izvršava odmah. - - +

+
* * * * * @@ -1175,8 +1175,8 @@ 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 '`. - - +

+
* * * * * @@ -1212,8 +1212,8 @@ Postoji samo šest krivotvorenih vrijednosti: Konstruktori function, kao što su 'new Number' i 'new Boolean' su istiniti. - - +

+
* * * * * @@ -1235,8 +1235,8 @@ console.log (vrsta tipa 1); `typeof 1` vraća` `broj ''. `typeof" number "` return `` string "` - - +

+
* * * * * @@ -1267,8 +1267,8 @@ zapravo imaju vrijednost `undefined`, ali vidjet ćete nešto poput: ovisno o tome gdje ga pokrećete (razlikuje se za svaki preglednik, čvor, itd) - - +

+
* * * * * @@ -1309,8 +1309,8 @@ 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`. - - +

+
* * * * * @@ -1340,8 +1340,8 @@ koristeći jednu od klasa omotača, tj. `String ', a zatim odmah odbacite omotač nakon što se izraz procijeni. Svi primitivci osim "null" i "undefined" pokazuju ovo ponašanje. - - +

+
* * * * * @@ -1374,8 +1374,8 @@ i `cur` je` [0, 1] `. Spojimo ih, što rezultira Tada je `[1, 2, 0, 1]` `acc` i` [2, 3] `````. Ulančavamo se i dobiti `[1, 2, 0, 1, 2, 3]` - - +

+
* * * * * @@ -1403,8 +1403,8 @@ i dobiti `[1, 2, 0, 1, 2, 3]` "1" je istina. `! 1` vraća 'false'. `! false 'vraća' true '. - - +

+
* * * * * @@ -1427,8 +1427,8 @@ setInterval (() => console.log ("Hi"), 1000); Vraća jedinstveni ID. Taj se ID može koristiti za brisanje tog intervala `clearInterval ()` function. - - +

+
* * * * * @@ -1451,5 +1451,5 @@ Vraća jedinstveni ID. Taj se ID može koristiti za brisanje tog intervala Niz je iterabilan. Operator širenja mapira svaki znak iterabilan na jedan element. - - +

+
From fa69a524fb30f846708482e2c7cfcb0948480802 Mon Sep 17 00:00:00 2001 From: nedimf <24845593+nedimf@users.noreply.github.com> Date: Tue, 18 Jun 2019 19:56:57 +0200 Subject: [PATCH 020/915] Update README.md --- README.md | 168 +++++++++++++++++++++++++++--------------------------- 1 file changed, 84 insertions(+), 84 deletions(-) diff --git a/README.md b/README.md index b7c2095a..34fc40b5 100644 --- a/README.md +++ b/README.md @@ -73,8 +73,8 @@ za (let i = 0; i <3; i ++) { - B: "0 1 2" i "3 3 3" - C: "3 3 3" i "0 1 2" -
Odgovor -

+

Odgovor +

#### Odgovor: C @@ -116,8 +116,8 @@ oblik.promjer (); - C: "20" i "63" - D: "NaN" i "63" -

Odgovor -

+

Odgovor +

#### Odgovor: B @@ -147,8 +147,8 @@ Na tom objektu nema vrijednosti `radius` koja vraća` undefined`. - B: "false" i "NaN" - C: "false" i "false" -
Odgovor -

+

Odgovor +

#### Odgovor: A @@ -181,8 +181,8 @@ const mouse = { - C: `miš [ptica [" veličina "]]` nije važeća - D: Svi su valjani -
Odgovor -

+

Odgovor +

#### Odgovor: A @@ -229,8 +229,8 @@ console.log (d.greeting); - D: "ReferenceError" - E: `TypeError` -
Odgovor -

+

Odgovor +

#### Odgovor: A @@ -266,8 +266,8 @@ console.log (b === c); - C: `true`` false` `false` - D: `false`` true` `true` -
Odgovor -

+

Odgovor +

#### Odgovor: C @@ -310,8 +310,8 @@ freddie.colorChange("orange"); - C: "zelena" - D: `TypeError` -
Odgovor -

+

Odgovor +

#### Odgovor: D @@ -338,8 +338,8 @@ console.log (greetign); - B: `ReferenceError: greetign nije definiran ' - C: `undefined` -
Odgovor -

+

Odgovor +

#### Odgovor: A @@ -371,8 +371,8 @@ bark.animal = "dog"; - C: `undefined` - D: "ReferenceError" -
Odgovor -

+

Odgovor +

#### Odgovor: A @@ -409,8 +409,8 @@ console.log (member.getFullName ()); - C: "Lydia Hallie" - D: `undefined`` undefined` -
Odgovor -

+

Odgovor +

#### Odgovor: A @@ -458,8 +458,8 @@ console.log (sarah); - D: `Person {ime:" Lydia ", prezime:" Hallie "} i `ReferenceError` -
Odgovor -

+

Odgovor +

#### Odgovor: A @@ -485,8 +485,8 @@ sam je ostavljen 'undefined'. - D: Capturing > Target > Bubbling -
Odgovor -

+

Odgovor +

#### Odgovor: D @@ -506,8 +506,8 @@ i ** bubbling **. - Istinito - B: lažno -
Odgovor -

+

Odgovor +

#### Odgovor: B @@ -538,8 +538,8 @@ sum (1, "2"); - C: "12" - D: `3` -
Odgovor -

+

Odgovor +

#### Odgovor: C @@ -574,8 +574,8 @@ console.log (broj); - C: `0`` 2` `2` - D: `0`` 1` `2` -
Odgovor -

+

Odgovor +

#### Odgovor: C @@ -615,8 +615,8 @@ getPersonInfo` $ {Person} je $ {old} godina '; - B: ``````````````````````````````````````````````````````````````````````````` - C: `` Lydia` `````````````````````````````````````````````````````````` -
Odgovor -

+

Odgovor +

#### Odgovor: B @@ -649,8 +649,8 @@ checkAge ({age: 18}); - B: "Vi ste još uvijek odrasla osoba." - C: 'Hmm .. Nemam godina za koju pretpostavljam' -
Odgovor -

+

Odgovor +

#### Odgovor: C @@ -685,8 +685,8 @@ getAge (21); - C: `` objekt '' - D: "NaN" -
Odgovor -

+

Odgovor +

#### Odgovor: C @@ -715,8 +715,8 @@ getAge (); - C: "ReferenceError" - D: `TypeError` -
Odgovor -

+

Odgovor +

#### Odgovor: C @@ -742,8 +742,8 @@ const sum = eval ("10x10 + 5"); - C: `TypeError` - D: `" 10 * 10 + 5 "` -
Odgovor -

+

Odgovor +

#### Odgovor: A @@ -767,8 +767,8 @@ O: Podaci se zauvijek ne izgube. - C: Kada korisnik zatvori cijeli preglednik, ne samo karticu. - D: Kada korisnik isključi svoje računalo. -
Odgovor -

+

Odgovor +

#### Odgovor: B @@ -796,8 +796,8 @@ console.log (num); - C: `SyntaxError` - D: "ReferenceError" -
Odgovor -

+

Odgovor +

#### Odgovor: B @@ -828,8 +828,8 @@ set.has (1); - C: `true`` true` `false`` true` - D: `true`` true` `true`` true` -
Odgovor -

+

Odgovor +

#### Odgovor: C @@ -858,8 +858,8 @@ console.log (obj); - C: `{a:" tri ", b:" dva "}` - D: `SyntaxError` -
Odgovor -

+

Odgovor +

#### Odgovor: C @@ -877,8 +877,8 @@ i dalje će biti na prvom mjestu, ali s posljednjom navedenom vrijednošću. - B: lažno - C: to ovisi -
Odgovor -

+

Odgovor +

#### Odgovor: A @@ -904,8 +904,8 @@ za (let i = 1; i <5; i ++) { - C: `1`` 2` `4` - D: `1`` 3` `4` -
Odgovor -

+

Odgovor +

#### Odgovor: C @@ -934,8 +934,8 @@ name.giveLydiaPizza (); - C: `SyntaxError` - D: `undefined` -
Odgovor -

+

Odgovor +

#### Odgovor: A @@ -968,8 +968,8 @@ console.log (a [b]); - C: `undefined` - D: "ReferenceError" -
Odgovor -

+

Odgovor +

#### Odgovor: B @@ -1006,8 +1006,8 @@ baz (); - C: `Drugi`` Prvi` `Treći` - D: `Drugi`` Treći` `Prvi` -
Odgovor -

+

Odgovor +

#### Odgovor: B @@ -1069,8 +1069,8 @@ stog. - C: `gumb ' - D: Niz svih ugniježđenih elemenata. -
Odgovor -

+

Odgovor +

#### Odgovor: C @@ -1097,8 +1097,8 @@ događaj. Možete zaustaviti mjehuriće 'event.stopPropagation' - C: p - D: "div" -
Odgovor -

+

Odgovor +

#### Odgovor: A @@ -1131,8 +1131,8 @@ sayHi.bind (Person, 21); - C: `Lydia je 21`` Lydia je 21` - D: `Lydia je 21`` function` -
Odgovor -

+

Odgovor +

#### Odgovor: D @@ -1162,8 +1162,8 @@ vrsta rečiHi (); - C: function "" - D: `" undefined "` -
Odgovor -

+

Odgovor +

#### Odgovor: B @@ -1196,8 +1196,8 @@ nedefiniran; - C: `0`,` '' `,` new Boolean (false) `,` undefined` - D: Svi su oni lažni -
Odgovor -

+

Odgovor +

#### Odgovor: A @@ -1228,8 +1228,8 @@ console.log (vrsta tipa 1); - C: `` objekt '' - D: `" undefined "` -
Odgovor -

+

Odgovor +

#### Odgovor: B @@ -1253,8 +1253,8 @@ console.log (br); - C: `[1, 2, 3, 7 x prazno, 11]` - D: `SyntaxError` -
Odgovor -

+

Odgovor +

#### Odgovor: C @@ -1293,8 +1293,8 @@ itd) - C: `1`` 1` `2` - D: `1`` undefined` `undefined` -
Odgovor -

+

Odgovor +

#### Odgovor: A @@ -1321,8 +1321,8 @@ vraća `undefined` i` y` vraća `2`. - C: trik pitanje! samo objekti - D: broj ili objekt -
Odgovor -

+

Odgovor +

#### Odgovor: A @@ -1361,8 +1361,8 @@ osim "null" i "undefined" pokazuju ovo ponašanje. - C: "[1, 2, 0, 1, 2, 3]" - D: `[1, 2, 6]` -
Odgovor -

+

Odgovor +

#### Odgovor: C @@ -1392,8 +1392,8 @@ i dobiti `[1, 2, 0, 1, 2, 3]` - C: `false`` true` `true` - D: `true`` true` `false` -
Odgovor -

+

Odgovor +

#### Odgovor: B @@ -1419,8 +1419,8 @@ setInterval (() => console.log ("Hi"), 1000); - C: prošla function - D: `undefined` -
Odgovor -

+

Odgovor +

#### Odgovor: A @@ -1443,8 +1443,8 @@ Vraća jedinstveni ID. Taj se ID može koristiti za brisanje tog intervala - C: `[[]," Lydia "]` - D: `[[" L "," y "," d "," i "," a "]]` -
Odgovor -

+

Odgovor +

#### Odgovor: A From 6ff9cefe2e5df395f39a37e94afe9b6596ac9acc Mon Sep 17 00:00:00 2001 From: nedimf <24845593+nedimf@users.noreply.github.com> Date: Tue, 18 Jun 2019 20:06:03 +0200 Subject: [PATCH 021/915] Update README.md --- README.md | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/README.md b/README.md index 34fc40b5..f146f212 100644 --- a/README.md +++ b/README.md @@ -252,9 +252,9 @@ Kada promijenite jedan objekt, mijenjate ih sve. ###### 7. Što je izlaz? ```javascript -let je a = 3; -let je b = new broj (3); -let je c = 3; +let a = 3; +let b = new broj (3); +let c = 3; console.log (a == b); console.log (a === b); @@ -563,7 +563,7 @@ vraća `" 12 "`. ###### 16. Što je izlaz? ```javascript -let je broj = 0; +let broj = 0; console.log (broj ++); console.log (++ broj); console.log (broj); @@ -1059,9 +1059,9 @@ stog.
+
+ ``` - A: Vanjski 'div' @@ -1089,7 +1089,7 @@ događaj. Možete zaustaviti mjehuriće 'event.stopPropagation'

Kliknite ovdje!

- + ``` - A: `p`` div` @@ -1187,7 +1187,7 @@ budući da su funkcije objekti, to je tipa `` objekta '`. new broj (0); ( ""); (""); -new logički (false); +new boolean (false); nedefiniran; ``` From 3e8479530d8644bd6c15d051ea2c47dc49e0d6ff Mon Sep 17 00:00:00 2001 From: nedimf <24845593+nedimf@users.noreply.github.com> Date: Tue, 18 Jun 2019 20:09:41 +0200 Subject: [PATCH 022/915] Update README.md --- README.md | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/README.md b/README.md index f146f212..a9e12927 100644 --- a/README.md +++ b/README.md @@ -60,18 +60,18 @@ JavaScript iz bacuje `ReferenceError`. ###### 2. Što je izlaz? ```javascript -za (var i = 0; i <3; i ++) { +for (var i = 0; i <3; i ++) { setTimeout (() => console.log (i), 1); } -za (let i = 0; i <3; i ++) { +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" +- A: `0 1 2` and `0 1 2` +- B: `0 1 2` and `3 3 3` +- C: `3 3 3` and `0 1 2`
Odgovor

@@ -611,9 +611,9 @@ const age = 21; getPersonInfo` $ {Person} je $ {old} godina '; ``` -- A: `` Lydia` `````````````````````````````````````` -- B: ``````````````````````````````````````````````````````````````````````````` -- C: `` Lydia` `````````````````````````````````````````````````````````` +- A: `"Lydia"` `21` `["", " is ", " years old"]` +- B: `["", " is ", " years old"]` `"Lydia"` `21` +- C: `"Lydia"` `["", " is ", " years old"]` `21`

Odgovor

From b70e3bdb766420578c619fd994de117487d0caf5 Mon Sep 17 00:00:00 2001 From: nedimf <24845593+nedimf@users.noreply.github.com> Date: Tue, 18 Jun 2019 20:12:34 +0200 Subject: [PATCH 023/915] Update README.md --- README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/README.md b/README.md index a9e12927..52b92054 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,8 @@ # Popis (naprednih) JavaScript pitanja ======================================= +###### Pošto je cilj bio što prije izbaciti domaću verziju ovog odličnog repozitorija vjerovatno je došlo do sitnih gramatičkih i sintatičkih grešaka.Hvala na razumjevanju! + Svakodnevno postavljam JavaScript pitanja s višestrukim izborom na moj [Instagram](https://www.instagram.com/theavocoder), koja također objavljujem ovdje! From 18e18a7bbf56435970de9ed0af0d29078e06c537 Mon Sep 17 00:00:00 2001 From: nedimf <24845593+nedimf@users.noreply.github.com> Date: Tue, 18 Jun 2019 20:50:20 +0200 Subject: [PATCH 024/915] Update and rename README.md to README-bs.md --- README.md => README-bs.md | 4 ++++ 1 file changed, 4 insertions(+) rename README.md => README-bs.md (99%) diff --git a/README.md b/README-bs.md similarity index 99% rename from README.md rename to README-bs.md index 52b92054..46a5455d 100644 --- a/README.md +++ b/README-bs.md @@ -16,6 +16,10 @@ kliknite na njih da biste ih proširili. Sretno :heart: [中文版本](./README-zh_CN.md) + +[WESTERN BALKAN](./README-bs.md) + + * * * * * ###### 1. Što je izlaz? From 1db2ac8425b3ecf738896115ad0e28df9e9c27ef Mon Sep 17 00:00:00 2001 From: nedimf <24845593+nedimf@users.noreply.github.com> Date: Tue, 18 Jun 2019 20:51:38 +0200 Subject: [PATCH 025/915] Main English --- README.md | 1292 +++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 1292 insertions(+) create mode 100644 README.md diff --git a/README.md b/README.md new file mode 100644 index 00000000..681b8e86 --- /dev/null +++ b/README.md @@ -0,0 +1,1292 @@ +# List of (Advanced) JavaScript Questions + +I post daily multiple choice JavaScript questions on my [Instagram](https://www.instagram.com/theavocoder), which I'll also post 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 weekly with new questions. + +The answers are in the collapsed sections below the questions, simply click on them to expand it. Good luck :heart: + +[中文版本](./README-zh_CN.md) + +--- + +###### 1. What's the output? + +```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` + +
Answer +

+ +#### Answer: D + +Within the function, we first declare the `name` variable with the `var` keyword. This means that the variable gets hoisted (memory space is set up during the creation phase) with the default value of `undefined`, until we actually get to the line where we define the variable. We haven't defined the variable yet on the line where we try to log the `name` variable, so it still holds the value of `undefined`. + +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`. + +

+
+ +--- + +###### 2. What's the 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` and `0 1 2` +- B: `0 1 2` and `3 3 3` +- C: `3 3 3` and `0 1 2` + +
Answer +

+ +#### Answer: C + +Because of the event queue in JavaScript, the `setTimeout` callback function is called _after_ the loop has been executed. Since the variable `i` in the first loop was declared using the `var` keyword, this value was global. During the loop, we incremented the value of `i` by `1` each time, using the unary operator `++`. By the time the `setTimeout` callback function was invoked, `i` was equal to `3` in the first example. + +In the second loop, the variable `i` was declared using the `let` keyword: variables declared with the `let` (and `const`) keyword are block-scoped (a block is anything between `{ }`). During each iteration, `i` will have a new value, and each value is scoped inside the loop. + +

+
+ +--- + +###### 3. What's the output? + +```javascript +const shape = { + radius: 10, + diameter() { + return this.radius * 2; + }, + perimeter: () => 2 * Math.PI * this.radius +}; + +shape.diameter(); +shape.perimeter(); +``` + +- A: `20` and `62.83185307179586` +- B: `20` and `NaN` +- C: `20` and `63` +- D: `NaN` and `63` + +
Answer +

+ +#### Answer: B + +Note that the value of `diameter` is a regular function, whereas the value of `perimeter` is an arrow function. + +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 `undefined`. + +

+
+ +--- + +###### 4. What's the output? + +```javascript ++true; +!"Lydia"; +``` + +- A: `1` and `false` +- B: `false` and `NaN` +- C: `false` and `false` + +
Answer +

+ +#### Answer: A + +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`. + +

+
+ +--- + +###### 5. Which one is true? + +```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 + +
Answer +

+ +#### Answer: A + +In JavaScript, all object keys are strings (unless it's a Symbol). Even though we might not _type_ them as strings, they are always converted into strings under the hood. + +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. + +`mouse[bird.size]`: First it evaluates `bird.size`, which is `"small"`. `mouse["small"]` returns `true` + +However, with dot notation, this doesn't happen. `mouse` does not have a key called `bird`, which means that `mouse.bird` is `undefined`. Then, we ask for the `size` using dot notation: `mouse.bird.size`. Since `mouse.bird` is `undefined`, we're actually asking `undefined.size`. This isn't valid, and will throw an error similar to `Cannot read property "size" of undefined`. + +

+
+ +--- + +--- + +###### 6. What's the 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` + +
Answer +

+ +#### Answer: A + +In JavaScript, all objects interact by _reference_ when setting them equal to each other. + +First, variable `c` holds a value to an object. Later, we assign `d` with the same reference that `c` has to the object. + + + +When you change one object, you change all of them. + +

+
+ +--- + +###### 7. What's the 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` + +
Answer +

+ +#### Answer: 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`. + +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.` + +

+
+ +--- + +###### 8. What's the 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" }); +freddie.colorChange("orange"); +``` + +- A: `orange` +- B: `purple` +- C: `green` +- D: `TypeError` + +
Answer +

+ +#### 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. + +

+
+ +--- + +###### 9. What's the output? + +```javascript +let greeting; +greetign = {}; // Typo! +console.log(greetign); +``` + +- A: `{}` +- B: `ReferenceError: greetign is not defined` +- C: `undefined` + +
Answer +

+ +#### 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). + +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. + +

+
+ +--- + +###### 10. What happens when we do this? + +```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: `undefined` +- D: `ReferenceError` + +
Answer +

+ +#### Answer: A + +This is possible in JavaScript, because functions are objects! (Everything besides primitive types are objects) + +A function is a special type of object. The code you write yourself isn't the actual function. The function is an object with properties. This property is invocable. + +

+
+ +--- + +###### 11. What's the 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` + +
Answer +

+ +#### Answer: A + +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() { + return `${this.firstName} ${this.lastName}`; +}; +``` + +would have made `member.getFullName()` work. Why is this beneficial? Say that we added this method to the constructor itself. Maybe not every `Person` instance needed this method. This would waste a lot of memory space, since they would still have that property, which takes of memory space for each instance. Instead, if we only add it to the prototype, we just have it at one spot in memory, yet they all have access to it! + +

+
+ +--- + +###### 12. What's the 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` + +
Answer +

+ +#### Answer: A + +For `sarah`, we didn't use the `new` keyword. When using `new`, it refers to the new empty object we create. However, if you don't add `new` it 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`. + +

+
+ +--- + +###### 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 + +
Answer +

+ +#### Answer: 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 + +
Answer +

+ +#### Answer: B + +All objects have prototypes, except for the **base object**. 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. What's the output? + +```javascript +function sum(a, b) { + return a + b; +} + +sum(1, "2"); +``` + +- A: `NaN` +- B: `TypeError` +- C: `"12"` +- D: `3` + +
Answer +

+ +#### Answer: 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. What's the 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` + +
Answer +

+ +#### Answer: 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. What's the 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` + +
Answer +

+ +#### Answer: 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. What's the 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` + +
Answer +

+ +#### Answer: 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. What's the output? + +```javascript +function getAge(...args) { + console.log(typeof args); +} + +getAge(21); +``` + +- A: `"number"` +- B: `"array"` +- C: `"object"` +- D: `"NaN"` + +
Answer +

+ +#### Answer: C + +The spread operator (`...args`.) returns an array with arguments. An array is an object, so `typeof args` returns `"object"` + +

+
+ +--- + +###### 20. What's the output? + +```javascript +function getAge() { + "use strict"; + age = 21; + console.log(age); +} + +getAge(); +``` + +- A: `21` +- B: `undefined` +- C: `ReferenceError` +- D: `TypeError` + +
Answer +

+ +#### Answer: 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 value of `sum`? + +```javascript +const sum = eval("10*10+5"); +``` + +- A: `105` +- B: `"105"` +- C: `TypeError` +- D: `"10*10+5"` + +
Answer +

+ +#### 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`. + +

+
+ +--- + +###### 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. + +
Answer +

+ +#### Answer: 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. What's the output? + +```javascript +var num = 8; +var num = 10; + +console.log(num); +``` + +- A: `8` +- B: `10` +- C: `SyntaxError` +- D: `ReferenceError` + +
Answer +

+ +#### Answer: 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. What's the 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` + +
Answer +

+ +#### Answer: 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. What's the 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` + +
Answer +

+ +#### Answer: 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 + +
Answer +

+ +#### Answer: A + +The base execution context is the global execution context: it's what's accessible everywhere in your code. + +

+
+ +--- + +###### 27. What's the 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` + +
Answer +

+ +#### Answer: C + +The `continue` statement skips an iteration if a certain condition returns `true`. + +

+
+ +--- + +###### 28. What's the 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` + +
Answer +

+ +#### 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! + +

+
+ +--- + +###### 29. What's the 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` + +
Answer +

+ +#### Answer: 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. What's the 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` + +
Answer +

+ +#### Answer: 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. + +
Answer +

+ +#### Answer: 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` + +
Answer +

+ +#### 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. + +

+
+ +--- + +###### 33. What's the output? + +```javascript +const person = { name: "Lydia" }; + +function sayHi(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` + +
Answer +

+ +#### Answer: 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. What's the output? + +```javascript +function sayHi() { + return (() => 0)(); +} + +typeof sayHi(); +``` + +- A: `"object"` +- B: `"number"` +- C: `"function"` +- D: `"undefined"` + +
Answer +

+ +#### Answer: B + +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`, and `symbol`. `"function"` is not a type, since functions are objects, it's of type `"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 + +
Answer +

+ +#### Answer: A + +There are only six falsy values: + +- `undefined` +- `null` +- `NaN` +- `0` +- `''` (empty string) +- `false` + +Function constructors, like `new Number` and `new Boolean` are truthy. + +

+
+ +--- + +###### 36. What's the output? + +```javascript +console.log(typeof typeof 1); +``` + +- A: `"number"` +- B: `"string"` +- C: `"object"` +- D: `"undefined"` + +
Answer +

+ +#### Answer: B + +`typeof 1` returns `"number"`. +`typeof "number"` returns `"string"` + +

+
+ +--- + +###### 37. What's the 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` + +
Answer +

+ +#### Answer: 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, 7 x empty, 11]` + +depending on where you run it (it's different for every browser, node, etc.) + +

+
+ +--- + +###### 38. What's the 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` + +
Answer +

+ +#### Answer: 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 + +
Answer +

+ +#### Answer: 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 implicity wrap the object 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. What's the 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]` + +
Answer +

+ +#### Answer: 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. What's the output? + +```javascript +!!null; +!!""; +!!1; +``` + +- A: `false` `true` `false` +- B: `false` `false` `true` +- C: `false` `true` `true` +- D: `true` `true` `false` + +
Answer +

+ +#### Answer: 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? + +```javascript +setInterval(() => console.log("Hi"), 1000); +``` + +- A: a unique id +- B: the amount of milliseconds specified +- C: the passed function +- D: `undefined` + +
Answer +

+ +#### Answer: 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"]]` + +
Answer +

+ +#### Answer: A + +A string is an iterable. The spread operator maps every character of an iterable to one element. + +

+
From a14dd1d6e4d1700d69705cf74cfaaae25442fe75 Mon Sep 17 00:00:00 2001 From: nedimf <24845593+nedimf@users.noreply.github.com> Date: Tue, 18 Jun 2019 20:52:31 +0200 Subject: [PATCH 026/915] Update README.md --- README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/README.md b/README.md index 681b8e86..2e09708a 100644 --- a/README.md +++ b/README.md @@ -8,6 +8,8 @@ The answers are in the collapsed sections below the questions, simply click on t [中文版本](./README-zh_CN.md) +[WESTERN BALKAN](./README-bs.md) + --- ###### 1. What's the output? From 6cbfbb4e3daacc670ed2314db758b4b790362006 Mon Sep 17 00:00:00 2001 From: Lydia Hallie Date: Wed, 19 Jun 2019 08:24:45 +0200 Subject: [PATCH 027/915] Update README.md --- README.md | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/README.md b/README.md index 1bf55f38..13e06d50 100644 --- a/README.md +++ b/README.md @@ -8,8 +8,7 @@ The answers are in the collapsed sections below the questions, simply click on t [中文版本](./README-zh_CN.md) [Русский](./README_ru-RU.md) - -[WESTERN BALKAN](./README-bs.md) +[Western Balkan](./README-bs.md) --- From 9abd0ac5b9c4fff82f7fcb43ff6c1020a11648ca Mon Sep 17 00:00:00 2001 From: Lydia Hallie Date: Wed, 19 Jun 2019 08:25:07 +0200 Subject: [PATCH 028/915] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 13e06d50..f6fb9dc4 100644 --- a/README.md +++ b/README.md @@ -7,7 +7,7 @@ From basic to advanced: test how well you know JavaScript, refresh your knowledg The answers are in the collapsed sections below the questions, simply click on them to expand it. Good luck :heart: [中文版本](./README-zh_CN.md) -[Русский](./README_ru-RU.md) +[Русский](./README_ru-RU.md) [Western Balkan](./README-bs.md) --- From cb89eabaeb369e6600a64fb611347e41b6cdc61a Mon Sep 17 00:00:00 2001 From: Do Trung Kien Date: Wed, 19 Jun 2019 15:52:30 +0700 Subject: [PATCH 029/915] Translate into Vietnamese --- README-vi.md | 1294 ++++++++++++++++++++++++++++++++++++++++++++++++++ README.md | 4 +- 2 files changed, 1296 insertions(+), 2 deletions(-) create mode 100644 README-vi.md diff --git a/README-vi.md b/README-vi.md new file mode 100644 index 00000000..b9b7c3be --- /dev/null +++ b/README-vi.md @@ -0,0 +1,1294 @@ +# Những câu hỏi JavaScript trình độ Advanced + +Hàng ngày tôi sẽ post các câu hỏi multichoice lên [Instagram](https://www.instagram.com/theavocoder) của tôi và tại đây nữa! + +Các câu hỏi sẽ từ cơ bản đến nâng cao: kiểm tra trình độ JavaScript của bạn, làm mới một chút về kiến thức, hay chuẩn bị cho cuộc phỏng vấn lập trình! :muscle: :rocket: Tôi sẽ cập nhật các câu hỏi mới hàng tuần. + +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: + +[English Version](./README.md) + +--- + +###### 1. Ouput là gì? + +```javascript +function sayHi() { + console.log(name); + console.log(age); + var name = "Lydia"; + let age = 21; +} + +sayHi(); +``` + +- A: `Lydia` và `undefined` +- B: `Lydia` và `ReferenceError` +- C: `ReferenceError` và `21` +- D: `undefined` và `ReferenceError` + +
Đáp án +

+ +#### Đáp án: D + +Trong hàm chúng ta đã khai báo biến `name` với `var`. Điều đó có nghĩa là biến này sẽ được hoisted (một vùng nhớ sẽ được set up khi biến được khởi tạo) với giá trị mặc định là `undefined`, cho tới khi chúng ta thực sự định nghĩa biến đó. Trong hàm này, chúng ta chưa hề định nghĩa biến `name` tại dòng mà ta log ra, vậy nên giá trị mặc định của nó vẫn là `undefined`. + +Các biến được khai báo với keyword `let` (và `const`) cũng được hoisted nhưng không giống như `var`, chúng không được khởi tạo. Chúng ta sẽ không thể truy cập chúng cho tới khi chúng ta khai báo (khởi tạo) chúng. Người ta gọi đó là "temporal dead zone". Khi ta truy cập đến một giá trị trước khi chúng được khai báo, JavaScript sẽ throws một `ReferenceError`. + +

+
+ +--- + +###### 2. Output sẽ là gì? + +```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` + +
Đáp án +

+ +#### Đáp án: C + +Bởi vì event queue trong JavaScript, hàm `setTimeout` callback sẽ được gọi _sau khi_ vòng lặp được thực hiện. Bời vì biến `i` trong vòng lặp đầu tiên được khai báo với từ khóa `var`, nên nó sẽ là một biến global. Trong suốt vòng lặp, mỗi lần chúng ta tăng giá trị của `i` lên `1`, sử dụng phép toán `++`. Cho tới khi callback `setTimeout` được gọi, giá trị của `i` đã trở thành `3` rồi. + +Trong vòng lặp thứ 2, biến `i` được khai báo với từ khóa `let`, có nghĩa nó là một biến block-scoped (block là những gì được viết bên trong cặp ngoặc `{ }`). Tại mỗi vòng lặp, `i` sẽ là một biến mới có một giá trị mới, và giá trị đó có scope là bên trong vòng lặp mà thôi. + +

+
+ +--- + +###### 3. Output sẽ là gì? + +```javascript +const shape = { + radius: 10, + diameter() { + return this.radius * 2; + }, + perimeter: () => 2 * Math.PI * this.radius +}; + +shape.diameter(); +shape.perimeter(); +``` + +- A: `20` and `62.83185307179586` +- B: `20` and `NaN` +- C: `20` and `63` +- D: `NaN` and `63` + +
Đáp án +

+ +#### Đáp án: B + +Chú ý rằng giá trị `diameter` là một hàm thông thường, còn `perimeter` là một _arrow function_. + +Không giống như hàm thông thường, với _arrow function_, biến`this` sẽ trỏ tới surrounding scope! Có nghĩa là khi chúng ta gọi `perimeter`, nó sẽ không được gọi bởi shape object, mà nó được gọi bởi object nào đó tại surrounding scope (ví dụ `window` chẳng hạn). + +Khi không có giá trị `radius` tại object đó, nó sẽ trả về `undefined`. + +

+
+ +--- + +###### 4. Ouput là gì? + +```javascript ++true; +!"Lydia"; +``` + +- A: `1` and `false` +- B: `false` and `NaN` +- C: `false` and `false` + +
Đáp án +

+ +#### Đáp án: A + +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. + +

+
+ +--- + +###### 5. Cái nào đúng? + +```javascript +const bird = { + size: "small" +}; + +const mouse = { + name: "Mickey", + small: true +}; +``` + +- A: `mouse.bird.size` không hợp lệ +- B: `mouse[bird.size]` không hợp lệ +- C: `mouse[bird["size"]]` không hợp lệ +- D: Tất cả đều hợp lệ + +
Đáp án +

+ +#### Đáp án: A + +Trong JavaScript thì tất cả keys của các object đều là string (ngoại trừ khi nó là một Symbol). Dù chúng ta không viết chúng như một string, về cơ bản chúng sẽ luôn được convert sang dạng string. + +JavaScript thông dịch (hay unboxes) từng câu lệnh. Khi chúng ta sử dụng cặp dấu ngoặc `[]`, nó sẽ tìm kiếm dấu mở ngoặc đầu tiên `[`, và sẽ tiếp tục tìm kiếm cho tới khi gặp dấu đóng ngoặc `]`. Chỉ khi đó thì câu lệnh mới được thực thi. + +`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`. + +

+
+ +--- + +--- + +###### 6. Ouput là gì? + +```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 án +

+ +#### Đá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. + +Đầ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. + + + +Khi ta thay đổi giá trị của object, tất cả các biến tham chiếu cũng đều thay đổi giá trị theo. + +

+
+ +--- + +###### 7. Ouput là gì? + +```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 án +

+ +#### Đáp án: C + +`new Number()` là một hàm built-in constructor. Mặc dù nó trông có vẻ giống như là một số, nhưng không phải: nó thực sự là một object với hàng tá những thông số khác nữa. + +Khi ta sử dụng phép so sánh `==`, nó đơn thuần chỉ kiểm tra xem 2 biến có _giá trị_ giống nhau. Chúng đều có giá trị là `3`, vậy nên phép toán đầu trả về `true`. + +Tuy nhiên khi sử dụng phép so sánh `===`, cả _giá trị_ và _kiểu_ đều phải giống nhau. Rõ ràng: `new Number()` không phải là một số, nó là một **object**. Cả 2 phép toán sau đều trả về `false.` + +

+
+ +--- + +###### 8. Ouput là gì? + +```javascript +class Chameleon { + 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` + +
Đáp án +

+ +#### Đáp án: D + +Hàm `colorChange` là một hàm static (hàm tĩnh). Hàm static được thiết kế để chỉ để tồn tại ở mức class, và không thể truyền cho bất cứ instance con nào. Vì `freddie` là một instance con, hàm static này sẽ không được truyền xuống, và do đó không thể gọi được tại `freddie` instance: nó sẽ throw ra một `TypeError`. + +

+
+ +--- + +###### 9. Ouput là gì? + +```javascript +let greeting; +greetign = {}; // Lỗi đánh máy! +console.log(greetign); +``` + +- A: `{}` +- B: `ReferenceError: greetign is not defined` +- C: `undefined` + +
Đáp án +

+ +#### Đáp án: A + +Nó sẽ log ra object `greetign`, bởi vì chúng ta vừa khởi tạo một global object! Khi chúng ta đánh máy nhầm `greeting` thành `greetign`, trình thông dịch của JS sẽ coi nó như là `global.greetign = {}` (hay `window.greetign = {}` nếu chạy trên browser). + +Để tránh điều này chúng ta có thể sử dụng `"use strict"`. Nó sẽ đảm bảo rẳng các biến đều phải được khai báo trước khi sử dụng. + +

+
+ +--- + +###### 10. Điều gì sẽ xảy ra khi chúng ta làm thế này? + +```javascript +function bark() { + console.log("Woof!"); +} + +bark.animal = "dog"; +``` + +- A: Hoàn toàn không có vấn đề gì! +- B: `SyntaxError`. Bạn không thể thêm thuộc tính theo cách này. +- C: `undefined` +- D: `ReferenceError` + +
Đáp án +

+ +#### Đá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) + +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. + +

+
+ +--- + +###### 11. Ouput là gì? + +```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 án +

+ +#### Đáp án: A + +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() { + return `${this.firstName} ${this.lastName}`; +}; +``` + +khi này `member.getFullName()` sẽ hoạt động. Tại sao nên làm vậy? Hãy thử thêm chúng trực tiếp vào constructor xem sao. Không phải mọi instance `Person` đều cần phương thức này. Nó sẽ dẫn tới việc lãng phí rất nhiều bộ nhớ, khi chúng đều phải lưu trữ thuộc tính này cho mỗi instance. Thay vì thế, nếu ta chỉ thêm chúng vào `prototype`, ta sẽ chỉ tốn bộ nhớ _một lần_ mà thôi, và mọi object khác đều có thể truy cập đến nó! + +

+
+ +--- + +###### 12. Ouput là gì? + +```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"}` và `undefined` +- B: `Person {firstName: "Lydia", lastName: "Hallie"}` và `Person {firstName: "Sarah", lastName: "Smith"}` +- C: `Person {firstName: "Lydia", lastName: "Hallie"}` và `{}` +- D:`Person {firstName: "Lydia", lastName: "Hallie"}` và `ReferenceError` + +
Đáp án +

+ +#### Đáp án: A + +Với `sarah`, chúng ta khai báo mà không có từ khóa `new`. Khi sử dụng `new`, nó sẽ trỏ đến một object mới mà ta vừa tạo ra. Tuy nhiên nếu ta không dùng `new` thì nó sẽ trỏ tới **global object**! + +Chúng ta cho rằng `this.firstName` là `"Sarah"` và `this.lastName` là `"Smith"`. Tuy nhiên sự thực là chúng ta đã định nghĩa `global.firstName = 'Sarah'` và `global.lastName = 'Smith'`. Bản thân biến `sarah` vẫn là `undefined`. + +

+
+ +--- + +###### 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 + +
Đáp án +

+ +#### Đáp án: D + +Trong **capturing** phase, event được truyền từ các phần tử cha cho tới phần tử target. Sau khi tới được phần tử **target** thì **bubbling** sẽ bắt đầu. + + + +

+
+ +--- + +###### 14. Tất cả các object đều có prototypes. + +- A: đúng +- B: sai + +
Đáp án +

+ +#### Đáp án: B + +Tất cả các object đều có prototypes, ngoại trừ **base object**. Object base có thể truy cập đến vài methods và properties, ví dụ như `.toString`. Đó là lý do tại sao chúng ta có thể sử dụng được các built-in methods trong JavaScript! Tất cả các phương thức đó đều có trong prototype. Mặc dù JavaScript không thể tìm thấy chúng trong object một cách trực tiếp, nó sẽ được truyền xuống thông qua prototype chain và xuống tới object, tại đây chúng ta có thể truy cập được nó. + +

+ +
--- + + +###### 15. Ouput là gì? + +```javascript +function sum(a, b) { + return a + b; +} + +sum(1, "2"); +``` + +- A: `NaN` +- B: `TypeError` +- C: `"12"` +- D: `3` + +
Đáp án +

+ +#### Đáp án: C + +JavaScript là một ngôn ngữ **dynamically typed**: chúng ta không khai báo kiểu dữ liệu khi khai báo biến. Giá trị có thể bị tự động convert sang một kiểu dữ liệu khác mà ta không hề hay biết, điều này được gọi là __implicit type coercion_. **Coercion** có nghĩa là convert từ kiểu này sang kiểu khác. + +Trong ví dụ này, JavaScript sẽ convert số `1` sang dạng string. Mỗi khi ta cộng một số (`1`) với một string (`'2'`), số sẽ luôn được xem như là một string. Kết quả sẽ là một phép nối chuỗi giống như `"Hello" + "World"`, vậy nên `"1" + "2"` sẽ trả về là `"12"`. + +

+
+ +--- + +###### 16. Ouput là gì? + +```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 án +

+ +#### Đáp án: C + +Khi phép toán `++` nằm ở **đằng sau** (**postfix**): + +1. Trả về giá trị (trả về `0`) +2. Tăng giá trị lên (number giờ là `1`) + +Khi phép toán `++` nằm ở **đằng trước** (**prefix**): + +1. Tăng giá trị lên (number giờ là `2`) +2. Trả về giá trị (trả về `2`) + +Vậy kết quả là `0 2 2`. + +

+
+ +--- + +###### 17. Ouput là gì? + +```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 án +

+ +#### Đáp án: B + +Nếu bạn dùng _tagged template literals_, giá trị của đối số đầu tiên luôn luôn là một mảng các string. Những đối số còn lại sẽ lấy giá trị từ biểu thức đưa vào! + +

+
+ +--- + +###### 18. Ouput là gì? + +```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 án +

+ +#### Đáp án: C + +Khi test sự bằng nhau, các kiểu dữ liệu cơ bản sẽ so sánh _giá trị_ của chúng, còn object thì so sánh _tham chiếu_. JavaScript sẽ kiểm tra xem các object đó có trỏ đến những vùng nhớ giống nhau hay không. + +Hai object chúng ta đang so sánh không có được điều đó: object đối số tham chiếu đến một vùng nhớ khác với object chúng ta dùng để kiểm tra sự bằng nhau. + +Đó là lý do tại sao cả `{ age: 18 } === { age: 18 }` và `{ age: 18 } == { age: 18 }` đều trả về `false`. + +

+
+ +--- + +###### 19. Ouput là gì? + +```javascript +function getAge(...args) { + console.log(typeof args); +} + +getAge(21); +``` + +- A: `"number"` +- B: `"array"` +- C: `"object"` +- D: `"NaN"` + +
Đáp án +

+ +#### Đáp án: C + +_Spread operator_ (`...args`.) sẽ trả về một mảng các đối số. Mảng thực chất là một object, vậy nên `typeof args` sẽ trả về `"object"`. + +

+
+ +--- + +###### 20. Ouput là gì? + +```javascript +function getAge() { + "use strict"; + age = 21; + console.log(age); +} + +getAge(); +``` + +- A: `21` +- B: `undefined` +- C: `ReferenceError` +- D: `TypeError` + +
Đáp án +

+ +#### Đáp án: C + +Với `"use strict"`, chúng ta sẽ đảm bảo được rằng ta sẽ không bao giờ khai báo biến global một cách vô ý. Tại đây chúng ta chưa khai báo biến `age`, và khi dùng `"use strict"`, nó sẽ throw ra một _reference error_. Nếu như không dùng `"use strict"`, nó sẽ vẫn hoạt động, vì thuộc tính `age` sẽ được thêm vào global object. + +

+
+ +--- + +###### 21. What's value of `sum`? + +```javascript +const sum = eval("10*10+5"); +``` + +- A: `105` +- B: `"105"` +- C: `TypeError` +- D: `"10*10+5"` + +
Đáp án +

+ +#### Đáp án: A + +`eval` sẽ đánh giá đoạn code bên trong string. Nếu nó là một biểu thức, giống như trong trường hợp này, nó sẽ tính toán giá trị đó. Biểu thức là `10 * 10 + 5`, kết quả sẽ là `105`. + +

+
+ +--- + +###### 22. Biến cool_secret sẽ truy cập được trong bao lâu? + +```javascript +sessionStorage.setItem("cool_secret", 123); +``` + +- A: Mãi mãi, dữ liệu sẽ không bao giờ mất. +- B: Khi user đóng tab lại. +- C: Khi user không chỉ là đóng tab, mà đóng browser lại. +- D: Khi user tắt máy tính đi. + +
Đáp án +

+ +#### Đáp án: B + +Dữ liệu được lưu trữ trong `sessionStorage` sẽ được xóa khi đóng _tab_. + +Nếu chúng ta dùng `localStorage`, data sẽ được lưu trữ mãi mãi, trừ phi hàm `localStorage.clear()` được gọi. + +

+
+ +--- + +###### 23. Ouput là gì? + +```javascript +var num = 8; +var num = 10; + +console.log(num); +``` + +- A: `8` +- B: `10` +- C: `SyntaxError` +- D: `ReferenceError` + +
Đáp án +

+ +#### Đáp án: B + +Với từ khóa `var` bạn có thể khai báo bao nhiêu biến trùng tên tùy thích. Biến đó sẽ có giá trị là lần cuối khai báo. + +Bạn không thể làm điều tương tự với `let` hay `const` vì chúng là _block-scoped_. + +

+
+ +--- + +###### 24. Ouput là gì? + +```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 án +

+ +#### Đáp án: C + +Tất cả các keys của object (ngoại trừ Symbols) về bản chất đều là string, dù chúng ta có viết chúng ra dạng string hay không. Nó là lý do tại sao `obj.hasOwnProperty('1')` cũng trả về `true`. + +Tuy nhiên điều đó không đúng với `set`. Không hề có `'1'` trong set của chúng ta: `set.has('1')` trả về `false`. Có số `1` trong set, nên `set.has(1)` trả về `true`. + +

+
+ +--- + +###### 25. Ouput là gì? + +```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 án +

+ +#### Đáp án: C + +Nếu chúng ta có 2 keys giống nhau, thì chúng sẽ bị replace. Nó sẽ vẫn nằm ở vị trí đầu tiên chúng được khai báo, nhưng giá trị thì sẽ là giá trị lần cuối. + +

+
+ +--- + +###### 26. Ngữ cảnh thực thi global của JavaScript tạo ra 2 thứ cho chúng ta: global object, và từ khóa "this". + +- A: đúng +- B: sai +- C: còn tùy + +
Đáp án +

+ +#### Đáp án: A + +Ngữ cảnh thực thi cơ bản chính là ngữ cảnh global: nó là thứ mà chúng ta có thể truy cập được ở bất cứ đâu trong code. + +

+
+ +--- + +###### 27. Ouput là gì? + +```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 án +

+ +#### Đáp án: C + +Lệnh `continue` sẽ bỏ qua một vòng lặp nếu điều kiện của nó là `true`. + +

+
+ +--- + +###### 28. Ouput là gì? + +```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` + +
Đáp án +

+ +#### Đáp án: A + +`String` là một built-in constructor, có nghĩa là chúng ta có thể thêm các thuộc tính vào đó. Ta vừa thêm vào đó một thuộc tính. Kiểu String cơ bản sẽ được convert sang dạng object bởi hàm string prototype. Vì thế nên tất cả các string object đều có thể truy cập đến hàm `giveLydiaPizza` này! + +

+
+ +--- + +###### 29. Ouput là gì? + +```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 án +

+ +#### Đáp án: B + +Object keys sẽ tự động được convert sang dạng string. Chúng ta đang set một object như là một key cho object `a`, với giá trị là `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`. +Tuy nhiên khi ta string hóa một object, nó sẽ trở thành `"[Object object]"`. Nên tại đây phép gán này thực chất chính là `a["Object object"] = 123`. Phép gán tiếp theo cũng giống hệt vậy. `c` là một object khác mà chúng ta đang string hóa nó. Theo đó, `a["Object object"] = 456`. + +Cuối cùng khi gọi `a[b]`, thực chất chính là gọi `a["Object object"]`. Giá trị của nó là `456`, nên trả về là `456`. + +

+
+ +--- + +###### 30. Ouput là gì? + +```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 án +

+ +#### Đáp án: B + +Chúng ta có một hàm `setTimeout` được gọi đầu tiên. Nên, nó sẽ được log ra cuối cùng. + +Điều đó bởi vì trên browser, chúng ta không hề có runtime engine, đơn thuần chỉ có `WebAPI`. `WebAPI` cho chúng ta một hàm `setTimeout`, ta hãy ví dụ nó trên DOM. + +Sau khi _callback_ được gửi tới WebAPI, bản thân hàm `setTimeout` (nhưng không phải callback nhé!) sẽ được đưa ra khỏi stack. + + + +Giờ đây, `foo` được gọi, và `"First"` được log ra. + + + +`foo` được đưa ra khỏi stack, và `baz` được gọi. `"Third"` được log ra. + + + +WebAPI không thể thêm thứ gì đó vào stack cho tới khi nó được sẵn sàng. Thay vào đó, nó đẩy callback function đến một nơi gọi là _queue_. + + + +Đó chính là nơi mà **event loop** làm việc. Một **event loop** sẽ quan sát stack và task queue. Nếu stack trở nên rỗng, nó sẽ lấy giá trị đầu tiên trong queue để đưa tiếp vào stack. + + + +`bar` được gọi, `"Second"` được log ra, và nó được đưa ra khói stack. + +

+
+ +--- + +###### 31. What is the event.target when clicking the button? + +```html +
+
+ +
+
+``` + +- A: Outer `div` +- B: Inner `div` +- C: `button` +- D: Một mảng với toàn bộ các phần tử lồng nhau. + +
Đáp án +

+ +#### Đáp án: C + +Phần tử sâu nhất trong các phần tử lồng nhau sẽ là target của event. Bạn có thể ngăn việc đó lại bằng cách sử dụng `event.stopPropagation` + +

+
+ +--- + +###### 32. Khi bạn click vào đoạn văn, cái gì sẽ được ghi ra output? + +```html +
+

+ Click here! +

+
+``` + +- A: `p` `div` +- B: `div` `p` +- C: `p` +- D: `div` + +
Đáp án +

+ +#### Đáp án: A + +Nếu ta click vào `p`, ta sẽ thấy hai log: `p` và `div`. Trong chuỗi event sẽ có 3 phases: capturing, target, và bubbling. Mặc định thì event handlers sẽ được thực hiện tại bubbling phase (trừ phi chúng ta khai báo `useCapture` là `true`). Chúng sẽ đi từ phần tử sâu nhất ra đến bên ngoài. + +

+
+ +--- + +###### 33. Ouput là gì? + +```javascript +const person = { name: "Lydia" }; + +function sayHi(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` + +
Đáp án +

+ +#### Đáp án: D + +Với cả hai, chúng ta có thể đưa vào object để sử dụng từ khóa `this`. Tuy nhiên, `.call` có nghĩa là _thực hiện ngay lập tức_! + +`.bind.` trả về một bản _copy_ của function, với context kèm theo! Nó sẽ không thực hiện ngay lập tức. + +

+
+ +--- + +###### 34. Ouput là gì? + +```javascript +function sayHi() { + return (() => 0)(); +} + +typeof sayHi(); +``` + +- A: `"object"` +- B: `"number"` +- C: `"function"` +- D: `"undefined"` + +
Đáp án +

+ +#### Đáp án: B + +`sayHi` function trả về giá trị của một _hàm gọi ngay lập tức_ (immediately invoked function - IIFE). Function này trả về `0`, kiểu dữ liệu `"number"`. + +FYI: chỉ có 7 kiểu dữ liệu built-in: `null`, `undefined`, `boolean`, `number`, `string`, `object`, and `symbol`. `"function"` không phải là một kiểu, mà là objects, kiểu dữ liệu là `"object"`. + +

+
+ +--- + +###### 35. Giá trị nào trong các giá trị dưới đây là 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 + +
Đáp án +

+ +#### Đáp án: A + +Chỉ có 6 giá trị _falsy_: + +- `undefined` +- `null` +- `NaN` +- `0` +- `''` (chuỗi rỗng) +- `false` + +Function constructors như `new Number` và `new Boolean` đều là _truthy_. + +

+
+ +--- + +###### 36. Ouput là gì? + +```javascript +console.log(typeof typeof 1); +``` + +- A: `"number"` +- B: `"string"` +- C: `"object"` +- D: `"undefined"` + +
Đáp án +

+ +#### Đáp án: B + +`typeof 1` trả về `"number"`. +`typeof "number"` trả về `"string"` + +

+
+ +--- + +###### 37. Ouput là gì? + +```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` + +
Đáp án +

+ +#### Đáp án: C + +Mỗi khi chúng ta set một giá trị cho một phần tử trong mảng mà vượt quá độ dài của mảng, JavaScript sẽ tạo ra những "empty slots". Chúng sẽ có giá trị là `undefined`, nhưng khi ghi ra thì chúng ta sẽ thấy dạng: + +`[1, 2, 3, 7 x empty, 11]` + +phụ thuộc vào nơi mà chúng ta chạy chúng (có thể khác nhau tùy môi trường browser, node, etc.) + +

+
+ +--- + +###### 38. Ouput là gì? + +```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 án +

+ +#### Đáp án: A + +`catch` block nhận về giá trị `x`. Đây không phải là giá trị `x` mà ta khai báo với từ khóa `let` ở bên trên. Đây là biến `x` trong _block-scoped_. + +Tiếp đó, chúng ta set giá trị của biến block-scoped này là `1`, và đồng thời cũng set giá trị cho biến `y`. Giờ đây chúng ta log ra giá trị của biến block-scoped variable `x`, bằng `1`. + +Bên ngoài `catch` block, `x` vẫn là `undefined`, và `y` là `2`. Khi gọi `console.log(x)` bên ngoài `catch` block, nó sẽ trả về `undefined`, và `y` trả về `2`. + +

+
+ +--- + +###### 39. Mọi thứ trong JavaScript đều là... + +- A: primitives hoặc object +- B: function hoặc object +- C: hỏi mẹo khó đấy! chỉ _object_ thôi +- D: number hoặc object + +
Đáp án +

+ +#### Đáp án: A + +JavaScript chỉ có primitive types và objects. + +Primitive types là `boolean`, `null`, `undefined`, `bigint`, `number`, `string`, and `symbol`. + +Điểm khác nhau giữa primitive và object chính là primitives không có thuộc tính hay phương thức; tuy nhiên, chúng ta để ý rằng là `'foo'.toUpperCase()` sẽ trả về `'FOO'` mà không phải là một `TypeError`. Đó là bởi vì khi chúng ta truy cập các thuộc tính hay phương thức của một primitive như là string, JavaScript sẽ ngầm bao nó bởi một `wrapper class`, ví dụ `String`, và sau đó sẽ hủy việc bao đó ngay sau khi thực hiện xong. Mọi primitives ngoại trừ `null` và `undefine` đều hoạt động giống như vậy. + +

+
+ +--- + +###### 40. Ouput là gì? + +```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 án +

+ +#### Đáp án: 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]`. +`[1, 2]` là giá trị khởi tạo. Đây là giá trị chúng ta bắt đầu, và cũng là giá trị đầu tiên của `acc`. Tại vòng đầu tiên, `acc` là `[1,2]`, và `cur` là `[0, 1]`. Ta nối chúng lại tạo ra `[1, 2, 0, 1]`. + +Tiếp tục, `[1, 2, 0, 1]` là `acc` và `[2, 3]` là `cur`. Ta nối chúng lại tạo ra `[1, 2, 0, 1, 2, 3]`. + +

+
+ +--- + +###### 41. Ouput là gì? + +```javascript +!!null; +!!""; +!!1; +``` + +- A: `false` `true` `false` +- B: `false` `false` `true` +- C: `false` `true` `true` +- D: `true` `true` `false` + +
Đáp án +

+ +#### Đáp án: B + +`null` là falsy. `!null` trả về `true`. `!true` trả về `false`. + +`""` là falsy. `!""` trả về `true`. `!true` trả về `false`. + +`1` là truthy. `!1` trả về `fase`. `!false` trả về `true`. + +

+
+ +--- + +###### 42. Hàm `setInterval` trả về cái gì? + +```javascript +setInterval(() => console.log("Hi"), 1000); +``` + +- A: một id duy nhất +- B: số lượng milliseconds +- C: function truyền vào +- D: `undefined` + +
Đáp án +

+ +#### Đáp án: A + +Nó trả về một id duy nhất. Id này dùng để clear interval sau này với hàm `clearInterval()`. + +

+
+ +--- + +###### 43. Giá trị trả về là gì? + +```javascript +[..."Lydia"]; +``` + +- A: `["L", "y", "d", "i", "a"]` +- B: `["Lydia"]` +- C: `[[], "Lydia"]` +- D: `[["L", "y", "d", "i", "a"]]` + +
Đáp án +

+ +#### Đáp án: A + +String là một _iterable_. Thế nên _spread operator_ sẽ map toàn bộ các ký tự trong chuỗi lại thành một mảng. + +

+
diff --git a/README.md b/README.md index f6fb9dc4..fe70cc8c 100644 --- a/README.md +++ b/README.md @@ -8,8 +8,8 @@ The answers are in the collapsed sections below the questions, simply click on t [中文版本](./README-zh_CN.md) [Русский](./README_ru-RU.md) -[Western Balkan](./README-bs.md) - +[Western Balkan](./README-bs.md) +[Tiếng Việt](./README-vi.md) --- ###### 1. What's the output? From cd3af3fa436247403704772f91cf814192f56d5b Mon Sep 17 00:00:00 2001 From: Jacob Herper Date: Wed, 19 Jun 2019 12:28:17 +0100 Subject: [PATCH 030/915] German translation added --- README-de_DE.md | 1296 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 1296 insertions(+) create mode 100644 README-de_DE.md diff --git a/README-de_DE.md b/README-de_DE.md new file mode 100644 index 00000000..cefffd01 --- /dev/null +++ b/README-de_DE.md @@ -0,0 +1,1296 @@ +# JavaScript Fragen (für Fortgeschrittene) + +Täglich poste ich mehrere Multiple-Choice-Fragen über JavaScript auf meinem [Instagram](https://www.instagram.com/theavocoder), die ich nun auch hier veröffentlichen werde. + +Von einfach bis fortgeschritten: teste wie gut du JavaScript kennst, frische dein Wissen auf oder bereite dich auf ein Vorstellungsgespräch vor! :muscle: :rocket: Ich werde dieses Repo wöchentlich mit neuen Fragen aktualisieren. + +Die Antworten sind unterhalb der Fragen versteckt. Du kannst einfach auf den Pfeil klicken um die Antworten zu sehen. Viel Glück :heart: + +[English](./README.md) +[中文版本](./README-zh_CN.md) +[Русский](./README_ru-RU.md) +[Western Balkan](./README-bs.md) + +--- + +###### 1. Was ist der Output? + +```javascript +function sayHi() { + 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` + +
Antwort +

+ +#### Antwort: D + +Innerhalb der Funktion wird zuerst der `name` mit dem `var` Keyword gesetzt. Das bedeuted, dass die Variable mit dem Standardwert `undefined` gehoisted wird (Speicherplatz wird während der Erstellung bereitgestellt), bis zu der Zeile, wo wir die Variable definieren. Da wir die Variable auf der Zeile, wo wir den `name` loggen noch nicht gesetzt haben, ist dieser noch `undefined`. + +Variablen mit dem `let` (oder `const`) Keyword werden ebenfalls gehoisted, aber im Gegensatz zu `var` werden diese nicht initialisiert. Auf sie können wir daher nicht zugreifen, bevor sie definiert worden sind. JavaScript wirft einen `ReferenceError` aus. + +

+
+ +--- + +###### 2. Was ist der 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` und `0 1 2` +- B: `0 1 2` und `3 3 3` +- C: `3 3 3` und `0 1 2` + +
Antwort +

+ +#### Antwort: C + +Aufgrund der Event Queue in JavaScript, wird die callback function in `setTimeout` _nach_ der Schleife ausgeführt. Da die Variable `i` in der ersten Schleife mit dem `var` Keyword definiert wurde, ist dieser Wert global verfügbar. Während der Schleife wird der Wert von `i` jedesmal mithilfe des `++` Operators um `1` erhöht. Zu dem Zeitpunkt, wenn die callback function in `setTimeout` aufgerufen wird, ist `i` gleich `3` im ersten Beispiel. + +In der zweiten Schleife wurde die Variable `i` mit dem `let` Keyword definiert: Variablen, die mit `let` (oder `const`) deklariert werden sind block-scoped (Ein Block ist alles zwischen `{ }`). Während jedem Durchlauf bekommt `i` einen neuen Wert zugewiesen, der jeweils innerhalb des Scopes der Schleife liegt. + +

+
+ +--- + +###### 3. Was ist der Output? + +```javascript +const shape = { + 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` + +
Antwort +

+ +#### Antwort: B + +Merke, dass der Wert von `diameter` eine reguläre Funktion ist, während der Wert von `perimeter` eine Arrow Function ist. + +In Arrow Functions bezieht sich das `this` Keyword auf den aktuellen Scope, was bei regulären Funktionen nicht der Fall ist. Das bedeutet, wenn wir `perimeter` aufrufen, bezieht es sich nicht auf das shape Object, sondern auf den umliegenden Scope (zum Beispiel `window`). + +Es gibt keinen Wert `radius` in dem Object, daher wird `undefined` zurückgegeben. + +

+
+ +--- + +###### 4. Was ist der Output? + +```javascript +;+true +!"Lydia" +``` + +- A: `1` und `false` +- B: `false` und `NaN` +- C: `false` und `false` + +
Antwort +

+ +#### Antwort: A + +Das unäre Plus versucht einen Operand zu einer Nummer umzuwandeln. `true` ist `1` und `false` ist `0`. + +Der String `'Lydia'` ist truthy. Was wir eigentlich fragen ist: "ist dieser truthy Wert falsy?". Die Antwort ist `false`. + +

+
+ +--- + +###### 5. Was ist wahr? + +```javascript +const bird = { + size: "small", +} + +const mouse = { + 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. + +
Antwort +

+ +#### Antwort: A + +In JavaScript sind alle Object Keys strings (außer bei Symbols). Selbst wenn diese nicht als strings _getyped_ sind, werden sie im Endeffekt zu Strings konvertiert. + +JavaScript interpretiert lediglich Aussagen. Wenn wir Bracket Notation verwenden, sieht JavaScript so zuerst eine öffnende eckige Klammer `[` und geht weiter, bis es eine schließende eckige Klammer `]` findet. Erst dann wird die Aussage evaluiert. + +`mouse[bird.size]`: Erst wird `bird.size` evaluiert, was `"small"` zurück gibt. `mouse["small"]` gibt `true` zurück. + +Mit der Dot Notation ist das nicht der Fall. `mouse` hat keinen Key namens `bird`, was bedeutet, dass `mouse.bird` `undefined` ist. Dann fragen wir nach der `size` mit Dot Notation: `mouse.bird.size`. Da `mouse.bird` `undefined` ist, fragen wir eigentlich nach `undefined.size`. Das ist fehlerhaft und wirft daher einen Fehler, wie zum Beispiel `Cannot read property "size" of undefined` zurück. + +

+
+ +--- + +--- + +###### 6. Was ist der 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` + +
Antwort +

+ +#### Antwort: A + +In JavaScript interagieren alle Objekte durch _Referenz_, wenn diese gleich sind. + +Zuerst hält die Variable `c` ein Object. Später wird `d` die selbe Referenz zugewiesen wie `c`. + + + +Wenn ein Object geändert wird, werden alle Referenzen zu diesem Object ebenfalls aktualisiert. + +

+
+ +--- + +###### 7. Was ist der 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` + +
Antwort +

+ +#### Antwort: C + +`new Number()` ist ein eingebauter Function Constructor. Auch wenn der Wert wie eine Nummer aussieht, ist es in Wirklichkeit keine Nummer, sondern beinhaltet eine Menge zusätzlicher Werte und ist daher ein Object. + +Wenn wir `==` nutzen wird nur geprüft, ob der _Wert_ gleich ist. Da beide den Wert `3` haben wird `true` zurückgegeben. + +Wenn wir aber `===` nutzen müssen sowohl der Wert _als auch_ der Typ übereinstimmen. Das ist `false`, da `new Number()` keine Nummer, sondern ein **Object** ist. + +

+
+ +--- + +###### 8. Was ist der 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" }) +freddie.colorChange("orange") +``` + +- A: `orange` +- B: `purple` +- C: `green` +- D: `TypeError` + +
Antwort +

+ +#### Antwort: D + +Die `colorChange` Funktion ist statisch (`static`). Statische Methoden existieren nur am Constructor wo sie erstellt wurden und können nicht an ihre Kinder weitergegeben werden. Da `freddie` ein Kind ist, wird die Funktion nicht runter gereicht und ist daher auch nicht in der `freddie` Instanz verfügbar. Ein `TypeError` wird zurückgeworfen. + +

+
+ +--- + +###### 9. Was ist der Output? + +```javascript +let greeting +greetign = {} // Typo! +console.log(greetign) +``` + +- A: `{}` +- B: `ReferenceError: greetign is not defined` +- C: `undefined` + +
Antwort +

+ +#### Antwort: A + +Das Object wird geloggt, da wir ein leeres Object am globalen Object erstellt haben. Als wir uns bei `greeting` verschrieben haben (als `greetign`) hat JavaScript das als neues Objekt `global.greetign = {}` (oder `window.greetign = {}` im Browser) angesehen. + +Um das zu verhindern, können wir `"use strict"` verwenden. Das stellt sicher, dass eine Variable erst definiert sein muss, bevor dieser ein Wert zugewiesen werden kann. + +

+
+ +--- + +###### 10. Was passiert, wenn wir das tun? + +```javascript +function bark() { + 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` + +
Antwort +

+ +#### Antwort: A + +In JavaScript ist das ohne Weiteres möglich, da Funktionen Objekte sind. (Alle Typen außer primitiven Typen sind Objekte) + +Eine Funktion ist ein spezieller Typ eines Objekts. Der Code, den wir schreiben ist keine eigentliche Funktion, sondern ein Object mit Properties. Die Property ist aufrufbar. + +

+
+ +--- + +###### 11. Was ist der 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` + +
Antwort +

+ +#### Antwort: A + +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}` +} +``` + +So hätte `member.getFullName()` funktioniert. Warum ist das von Vorteil? Sagen wir, wir hätten diese Methode dem Constructor selbst zugewiesen, aber vielleicht benötigt nicht jede Instanz von `Person` diese Methode. So hätte das eine Menge Arbeitsspeicher verschwendet, weil jede Instanz die Property zugewiesen bekommt, auch wenn sie diese garnicht benötigt. +Stattdessen haben wir sie nur dem Prototype zugewiesen, sodass sie nur an einer Stelle im Arbeitsspeicher hinterlegt ist, aber dennoch haben alle Instanzen Zugriff darauf. + +

+
+ +--- + +###### 12. Was ist der 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` + +
Antwort +

+ +#### Antwort: A + +Für `sarah` haben wir nicht das `new` Keyword verwendet. Wenn wir `new` verwenden, bezieht sich das auf das neue, leere Object, welches wir erstellen. Wenn wir allerdings das `new` Keyword nicht verwenden, bezieht es sich auf das **globale Objekt**. + +Wir haben `this.firstName` den Wert `"Sarah"` zugewiesen und `this.lastName` den Wert `"Smith"`. Was wir damit eigentlich zugewiesen haben ist `global.firstName = 'Sarah'` und `global.lastName = 'Smith'`. `sarah` selbst ist daher `undefined`. + +

+
+ +--- + +###### 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 + +
Antwort +

+ +#### Antwort: D + +Während der **capturing** Phase geht das Event durch die Elternelemente bis hin zum Zielelement. Wenn dann das Ziel (**target**) erreicht ist beginnt die **bubbling** Phase. + + + +

+
+ +--- + +###### 14. Alle Objekte haben Prototypes. + +- A: wahr +- B: falsch + +
Antwort +

+ +#### Antwort: B + +Alle Objekte haben Prototypes, außer dem **Basis Objekt**. Das Basis Objekt hat Zugriff auf einige Methoden und Properties, wie zum Beispiel `.toString`. Das ist der Grund, warum wir eingebaute JavaScript Methoden nutzen können. All diese Methoden sind am Prototype verfügbar. Obwohl JavaScript diese nicht direkt am Objekt finden kann, folgt es der Prototype Chain, bis es die Property findet und damit verfügbar macht. + +

+
+ +--- + +###### 15. Was ist der Output? + +```javascript +function sum(a, b) { + return a + b +} + +sum(1, "2") +``` + +- A: `NaN` +- B: `TypeError` +- C: `"12"` +- D: `3` + +
Antwort +

+ +#### Antwort: C + +JavaScript ist eine **Sprache mit dynamischen Typen**, was bedeutet, dass wir Variablen keine spezifischen Typen zuweisen. Werte können automatisch in einen anderen Typ umgewandelt werden, was _implicit type coercion_ genannt wird. **Coercion** (dt. "Zwang") ist die Umwandlung von einem Typ zu einem anderen. + +In diesem Beispiel wandelt JavaScript die Nummer `1` in einem String um, sodass die Funktion Sinn ergibt und einen Wert zurück werfen kann. Während der Addition eines numerischen Types (`1`) mit einem String (`'2'`) wird die Nummer wie ein String behandelt. Wir können Strings mit einem Plus Symbol zusammensetzen, zum Beispiel: `"Hello" + "World"`. Genau das passiert hier, sodass `"1" + "2"` einen Wert von `"12"` zurück wirft. + +

+
+ +--- + +###### 16. Was ist der 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` + +
Antwort +

+ +#### Antwort: C + +Der **Postfix** Unary Operator `++`: + +1. gibt den Wert zurück (hier: `0`) +2. erhöht den Wert (`number` ist jetzt `1`) + +Der **Prefix** Unary Operator `++`: + +1. erhöht den Wert (`number` ist jetzt `2`) +2. gibt den Wert zurück (hier: `2`) + +Der Output ist daher `0 2 2`. + +

+
+ +--- + +###### 17. Was ist der 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` + +
Antwort +

+ +#### Antwort: B + +Wenn man Template Literals verwendet ist das erste Argument immer ein Array der String Werte. Die restlichen Argumente bekommen die Werte der übergebenen Expressions zugewiesen. + +

+
+ +--- + +###### 18. Was ist der 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` + +
Antwort +

+ +#### Antwort: C + +Wenn man prüft, ob Werte gleich sind werden Primitives immer anhand ihrer _Value_ verglichen, während Objects anhand der _Referenz_ verglichen werden. JavaScript prüft, ob die Objekte eine Referenz zur gleichen Stelle im Speicher haben. + +Die beiden Objekte, die wir hier vergleichen haben das nicht. Das Objekt, welches wir als Parameter übergeben haben bezieht sich auf eine andere Stelle im Speicher, als das Objekt, welches wir verwendet haben um die Werte zu vergleichen. + +Deshalb werfen sowohl `{ age: 18 } === { age: 18 }` als auch `{ age: 18 } == { age: 18 }` den Wert `false` zurück. + +

+
+ +--- + +###### 19. Was ist der Output? + +```javascript +function getAge(...args) { + console.log(typeof args) +} + +getAge(21) +``` + +- A: `"number"` +- B: `"array"` +- C: `"object"` +- D: `"NaN"` + +
Antwort +

+ +#### Antwort: C + +Der Spread Operator (`...args`) gibt ein Array mit Argumenten zurück. Ein Array ist ein Objekt, sodass `typeof args` `"object"` ausgibt. + +

+
+ +--- + +###### 20. Was ist der Output? + +```javascript +function getAge() { + "use strict" + age = 21 + console.log(age) +} + +getAge() +``` + +- A: `21` +- B: `undefined` +- C: `ReferenceError` +- D: `TypeError` + +
Antwort +

+ +#### Antwort: C + +Durch `"use strict"` kann man sicher stellen, dass man nicht versehentlich globale Variablen definiert. Da wir die Variable `age` nie definiert haben und `"use strict"` verwenden wirft JavaScript einen reference error aus. Hätten wir `"use strict"` nicht verwendet, so hätte es funktioniert, da die property `age` dem globalen Objekt zugewiesen worden wäre. + +

+
+ +--- + +###### 21. Was ist der Wert von `sum`? + +```javascript +const sum = eval("10*10+5") +``` + +- A: `105` +- B: `"105"` +- C: `TypeError` +- D: `"10*10+5"` + +
Antwort +

+ +#### Antwort: A + +`eval` evaluiert Code, der als String übergeben wurde. Falls es, wie in diesem Fall, eine Expression ist, so wird diese Expression auch evaluiert. Die Expression `10 * 10 + 5` gibt damit die nummer `105` aus. + +

+
+ +--- + +###### 22. Wie lange ist cool_secret verfügbar? + +```javascript +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. + +
Antwort +

+ +#### Antwort: B + +Der Wert in `sessionStorage` geht verloren, wenn der _Tab_ geschlossen wird. + +Wenn man stattdessen `localStorage` verwendet, bleibt der Wert für immer bestehend, es sei denn `localStorage.clear()` wird ausgeführt. + +

+
+ +--- + +###### 23. Was ist der Output? + +```javascript +var num = 8 +var num = 10 + +console.log(num) +``` + +- A: `8` +- B: `10` +- C: `SyntaxError` +- D: `ReferenceError` + +
Antwort +

+ +#### Antwort: B + +Mit dem `var` Keyword kann man mehrere Variablen mit dem selben Namen definieren. Die Variable hält dann den letzt gesetzten Wert. + +Das ist nicht möglich mit `let` oder `const`, da diese dem Block Scope unterliegen. + +

+
+ +--- + +###### 24. Was ist der 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` + +
Antwort +

+ +#### Antwort: C + +Alle Object Keys (außgenommen Symbols) sind im Endeffekt Strings, selbst, wenn man diese nicht explizit als String definiert. Deshalb gibt `obj.hasOwnProperty('1')` auch `true` zurück. + +Das funktioniert nicht für Set. Da wir keine `'1'` in unserem Set haben wirft `set.has('1')` den Wert `false` zurück. Der Typ von `1` ist numerisch und `set.has(1)` gibt daher `true` zurück. + +

+
+ +--- + +###### 25. Was ist der 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` + +
Antwort +

+ +#### Antwort: C + +Wenn man zwei Keys mit dem selben Namen hat, wird der erste Key ersetzt. Er wird immernoch an erster Stelle sein, allerdings mit dem zuletzt gesetzten Wert. + +

+
+ +--- + +###### 26. Der JavaScript Global Execution Context erstellt zwei Dinge: das globale Objekt und das "this" Keyword. + +- A: wahr +- B: falsch +- C: kommt darauf an + +
Antwort +

+ +#### Antwort: A + +Der Base Execution Context entspricht dem Global Execution Context und ist überall in unserem Code verfügbar. + +

+
+ +--- + +###### 27. Was ist der 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` + +
Antwort +

+ +#### Antwort: C + +`continue` überspringt einen Durchlauf, wenn eine gewisse Bedingung erfüllt ist und `true` zurück gibt. + +

+
+ +--- + +###### 28. Was ist der 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` + +
Antwort +

+ +#### Antwort: A + +`String` ist ein eingebauter Constructor, dem wir Properties zuweisen können. Wir haben hier seinem Prototype eine Methode hinzugefügt. Primitive strings werden automatisch durch die String Prototype Function in ein String Objekt umgewandelt. Daher haben alle Strings (String Objects) Zugriff auf diese Methode. + +

+
+ +--- + +###### 29. Was ist der 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` + +
Antwort +

+ +#### Antwort: B + +Objekt Keys werden automatisch in Strings umgewandelt. Wir versuchen ein Objekt mit dem Wert `123` als Key dem Objekt `a` zuzuweisen. + +Allerdings wird ein Object, wenn es in einen String umgewandelt wird als `"[Object object]"` ausgegeben. Was wir hier also sagen ist, dass `a["Object object"] = 123` ist. Wir versuchen das gleiche erneut - `c` ist ein anderes Objekt, welches wir implizit zu einem String umwandeln, sodass `a["Object object"] = 456` ist. + +Dann loggen wir `a[b]`, was eigentlich `a["Object object"]` ist und gerade von uns zu `456` gesetzt wurde, sodass `456` ausgegeben wird. + +

+
+ +--- + +###### 30. Was ist der 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` + +
Antwort +

+ +#### Antwort: B + +Wir haben eine `setTimeout` Funktion, die zuerst ausgeführt wird und dennoch als letztes ausgegeben wird. + +Der Grund dafür ist, dass Browser nicht nur die Runtime Engine, sondern auch eine `WebAPI` haben. Die `WebAPI` stellt uns `setTimeout` bereit. + +Nachdem die _Callback Function_ an die WebAPI übergeben wurde wird `setTimeout` (aber nicht die Callback Function) ausgeführt und aus dem Stack entfernt. + + + +Jetzt wird `foo` ausgeführt und `"First"` geloggt. + + + +`foo` wird aus dem Stack entfernt und `baz` wird ausgeführt. `"Third"` wird geloggt. + + + +Die WebAPI kann nicht einfach Dinge zum Stack hinzufügen, wenn sie bereit ist, stattdessen wird die Callback Function zur _queue_ hinzugefügt. + + + +Das ist, wo die Event Loop ins Spiel kommt. Die **Event Loop** betrachtet den Stack und die Task Queue. Wenn der Stack leer ist wird das erste Element in der Queue zum Stack übertragen. + + + +`bar` wird ausgeführt, `"Second"` wird geloggt und aus dem Stack entfernt. + +

+
+ +--- + +###### 31. Was ist event.target wenn ein Button geklickt wird? + +```html +
+
+ +
+
+``` + +- A: Äußerer `div` +- B: Innerer `div` +- C: `button` +- D: Ein Array mit allen genesteten Elementen + +
Antwort +

+ +#### Antwort: C + +Das am tiefsten genestete Element, welches das Event auslöst ist das Event Target. Man kann den Bubbling Prozess mit `event.stopPropagation` anhalten. + +

+
+ +--- + +###### 32. Was ist der geloggte Output, wenn man auf den Paragraph klickt? + +```html +
+

+ Click here! +

+
+``` + +- A: `p` `div` +- B: `div` `p` +- C: `p` +- D: `div` + +
Antwort +

+ +#### Antwort: A + +Wenn wir auf den Paragraph klicken, sehen wir zwei logs: `p` und `div`. Während der Event Propagation werden drei Phasen ausgeführt: capturing, target und bubbling. Standardmäßig werden Event Handler in der Bubbling Phase ausgeführt (es sei denn man setzt `useCapture` auf `true`). Die Ausführung beginnt vom tiefsten Element nach Außen. + +

+
+ +--- + +###### 33. Was ist der Output? + +```javascript +const person = { name: "Lydia" } + +function sayHi(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` + +
Antwort +

+ +#### Antwort: D + +In beiden Fällen können wir das Objekt weiter reichen, auf welches sich das `this` Keyword beziehen soll. Allerdings wird `.call` _sofort ausgeführt_. + +`.bind.` gibt eine _Kopie_ der Funktion mit gebundenem Context zurück und wird daher nicht sofort ausgeführt. + +

+
+ +--- + +###### 34. Was ist der Output? + +```javascript +function sayHi() { + return (() => 0)() +} + +typeof sayHi() +``` + +- A: `"object"` +- B: `"number"` +- C: `"function"` +- D: `"undefined"` + +
Antwort +

+ +#### Antwort: B + +Die `sayHi` Funktion gibt den Wert der sofort ausgeführten Funktion (IIFE) zurück. Die Funktion gibt `0` zurück, was vom Typ `"number"` ist. + +Es gibt nur 7 eingebaute Typen in JavaScript: `null`, `undefined`, `boolean`, `number`, `string`, `object`, und `symbol`. `"function"` ist kein Typ, weil Funktionen Objekte sind und daher dem Typ `"object"` entsprechen. + +

+
+ +--- + +###### 35. Welcher dieser Werte ist 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: Alle sind falsy + +
Antwort +

+ +#### Antwort: A + +Es gibt nur 6 falsy typen: + +- `undefined` +- `null` +- `NaN` +- `0` +- `''` (leerer String) +- `false` + +Funktions-Constructor, wie `new Number` und `new Boolean` sind truthy. + +

+
+ +--- + +###### 36. Was ist der Output? + +```javascript +console.log(typeof typeof 1) +``` + +- A: `"number"` +- B: `"string"` +- C: `"object"` +- D: `"undefined"` + +
Antwort +

+ +#### Antwort: B + +`typeof 1` gibt `"number"` zurück. +`typeof "number"` gibt `"string"` zurück. + +

+
+ +--- + +###### 37. Was ist der 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` + +
Antwort +

+ +#### Antwort: C + +Wenn Werte einem Element in einem Array zugewiesen werden, die die Länge des Arrays übersteigen, so erstellt JavaScript "empty slots" (leere Stellen). Diese haben den Wert `undefined`, aber das Array sieht dann in etwa so aus: + +`[1, 2, 3, 7 x empty, 11]` + +abhängig davon wo das Array ausgeführt wird (die Ausgabe ist unterschiedlich für verschiedene Browser, Node, etc.) + +

+
+ +--- + +###### 38. Was ist der 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` + +
Antwort +

+ +#### Antwort: A + +Der `catch` Block erhält ein Argument `x`. Das ist nicht das selbe `x` wie die Variable, der wir Argumente zuweisen. Die Variable `x` ist block-scoped. + +Später setzen wir die block-scoped Variable gleich `1`, und setzen ebenfalls den Wert der Variable `y`. Jetzt loggen wir die block-scoped Variable `x` mit dem Wert `1`. + +Außerhalb des `catch` Blocks ist `x` noch immer `undefined` und `y` ist `2`. Wenn wir `console.log(x)` außerhalb des `catch` Block ausführen, wird für `x` der Wert `undefined` und für `y` der Wert `2` geloggt. + +

+
+ +--- + +###### 39. Alles in JavaScript ist entweder ein ... + +- A: Primitive oder Object +- B: Function oder Object +- C: Fangfrage: nur Objects! +- D: Number oder Object + +
Antwort +

+ +#### Antwort: A + +JavaScript hat nur primitive Typen und Objekte. + +Primitive Typen sind `boolean`, `null`, `undefined`, `bigint`, `number`, `string`, und `symbol`. + +Was einen primitiven Typ von einem Objekt unterscheidet ist, dass Primitive keine Properties oder Methoden haben, obwohl zum Beispiel `'foo'.toUpperCase()` zu `'FOO'` wird und keinen `TypeError` auswirft. Der Grund dafür ist, wenn man eine Property oder Method an einem primitiven Typ wie einem String ausführt, legt JavaScript eine Wrapper Class um das String Objekt, die danach sofort wieder entfernt wird, wenn die Expression ausgeführt wurde. Alle primitiven Typen außer `null` und `undefined` weisen dieses Verhalten auf. + +

+
+ +--- + +###### 40. Was ist der 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]` + +
Antwort +

+ +#### Antwort: C + +`[1, 2]` ist unser ursprünglicher Wert. Zusammen mit dem ersten `acc` ist das der Wert, mit dem wir beginnen. Während dem ersten Durchlauf ist `acc` gleich `[1, 2]`, und `cur` ist `[0, 1]`. Wir verbinden diese, was `[1, 2, 0, 1]` ergibt. + +Dann entspricht `acc` gleich `[1, 2, 0, 1]` und `cur` ist gleich `[2, 3]`. Wir verbinden diese und bekommen `[1, 2, 0, 1, 2, 3]`. + +

+
+ +--- + +###### 41. Was ist der Output? + +```javascript +!!null +!!"" +!!1 +``` + +- A: `false` `true` `false` +- B: `false` `false` `true` +- C: `false` `true` `true` +- D: `true` `true` `false` + +
Antwort +

+ +#### Antwort: B + +`null` ist falsy. `!null` gibt `true` zurück. `!true` gibt `false` zurück. + +`""` ist falsy. `!""` gibt `true` zurück. `!true` gibt `false` zurück. + +`1` ist truthy. `!1` gibt `false` zurück. `!false` gibt `true` zurück. + +

+
+ +--- + +###### 42. Was gibt die `setInterval` Method zurück? + +```javascript +setInterval(() => console.log("Hi"), 1000) +``` + +- A: Eine unique id +- B: Die definierte Anzahl von Millisekunden +- C: Die Callback Function +- D: `undefined` + +
Antwort +

+ +#### Antwort: A + +Es gibt eine unique id zurück. Diese id kann zum Beispiel verwendet werden um das Interval mit der `clearInterval()` Funktion zu leeren. + +

+
+ +--- + +###### 43. Was wird hier ausgegeben? + +```javascript +;[..."Lydia"] +``` + +- A: `["L", "y", "d", "i", "a"]` +- B: `["Lydia"]` +- C: `[[], "Lydia"]` +- D: `[["L", "y", "d", "i", "a"]]` + +
Antwort +

+ +#### Antwort: A + +Ein String ist ein Iterable. Der Spread Operator mappt jedes Zeichen eines Iterables zu einem eigenen Element. + +

+
From f0ecad3ab4702a75ccbbca937bf3ca1481cb1874 Mon Sep 17 00:00:00 2001 From: Tanguy Coppin Date: Wed, 19 Jun 2019 13:35:23 +0200 Subject: [PATCH 031/915] Start translating in French --- README-fr.md | 1295 ++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 1295 insertions(+) create mode 100644 README-fr.md diff --git a/README-fr.md b/README-fr.md new file mode 100644 index 00000000..07406dfd --- /dev/null +++ b/README-fr.md @@ -0,0 +1,1295 @@ +# Liste de questions JavaScript (Avancée) + +Je poste quotidiennement des questions à choix multiple sur mon [Instagram](https://www.instagram.com/theavocoder), que je posterai aussi ici ! + +Des basiques au avancée: testez vos connaissances en JavaScript, rafraichissez vos connaissances, ou préparez vous pour un entretien de code ! :muscle: :rocket: Je mets à jour ce dépôt chaque semaine avec des nouvelles questions. + +Les réponses se trouvent dans les sections fermées en dessous des questions, cliquez simplement dessus pour les faire apparaitre. Bonne chance :heart: + +[English](./README.md) +[中文版本](./README-zh_CN.md) +[Русский](./README_ru-RU.md) +[Western Balkan](./README-bs.md) + +--- + +###### 1. Quelle est la sortie ? + +```javascript +function sayHi() { + console.log(name); + console.log(age); + var name = "Lydia"; + let age = 21; +} + +sayHi(); +``` + +- A: `Lydia` et `undefined` +- B: `Lydia` et `ReferenceError` +- C: `ReferenceError` et `21` +- D: `undefined` et `ReferenceError` + +
Réponse +

+ +#### Réponse: D + +Within the function, we first declare the `name` variable with the `var` keyword. This means that the variable gets hoisted (memory space is set up during the creation phase) with the default value of `undefined`, until we actually get to the line where we define the variable. We haven't defined the variable yet on the line where we try to log the `name` variable, so it still holds the value of `undefined`. + +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`. + +

+
+ +--- + +###### 2. Quelle est la sortie ? + +```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` et `0 1 2` +- B: `0 1 2` et `3 3 3` +- C: `3 3 3` et `0 1 2` + +
Réponse +

+ +#### Réponse: C + +Because of the event queue in JavaScript, the `setTimeout` callback function is called _after_ the loop has been executed. Since the variable `i` in the first loop was declared using the `var` keyword, this value was global. During the loop, we incremented the value of `i` by `1` each time, using the unary operator `++`. By the time the `setTimeout` callback function was invoked, `i` was equal to `3` in the first example. + +In the second loop, the variable `i` was declared using the `let` keyword: variables declared with the `let` (and `const`) keyword are block-scoped (a block is anything between `{ }`). During each iteration, `i` will have a new value, and each value is scoped inside the loop. + +

+
+ +--- + +###### 3. Quelle est la sortie ? + +```javascript +const shape = { + radius: 10, + diameter() { + return this.radius * 2; + }, + perimeter: () => 2 * Math.PI * this.radius +}; + +shape.diameter(); +shape.perimeter(); +``` + +- A: `20` et `62.83185307179586` +- B: `20` et `NaN` +- C: `20` et `63` +- D: `NaN` et `63` + +
Réponse +

+ +#### Réponse: B + +Note that the value of `diameter` is a regular function, whereas the value of `perimeter` is an arrow function. + +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 `undefined`. + +

+
+ +--- + +###### 4. Quelle est la sortie ? + +```javascript ++true; +!"Lydia"; +``` + +- A: `1` et `false` +- B: `false` et `NaN` +- C: `false` et `false` + +
Réponse +

+ +#### Réponse: A + +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`. + +

+
+ +--- + +###### 5. Which one is true? + +```javascript +const bird = { + size: "small" +}; + +const mouse = { + name: "Mickey", + small: true +}; +``` + +- A: `mouse.bird.size` n'est pas valide +- B: `mouse[bird.size]` n'est pas valide +- C: `mouse[bird["size"]]` n'est pas valide +- D: Toutes sont valides + +
Réponse +

+ +#### Réponse: A + +In JavaScript, all object keys are strings (unless it's a Symbol). Even though we might not _type_ them as strings, they are always converted into strings under the hood. + +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. + +`mouse[bird.size]`: First it evaluates `bird.size`, which is `"small"`. `mouse["small"]` returns `true` + +However, with dot notation, this doesn't happen. `mouse` does not have a key called `bird`, which means that `mouse.bird` is `undefined`. Then, we ask for the `size` using dot notation: `mouse.bird.size`. Since `mouse.bird` is `undefined`, we're actually asking `undefined.size`. This isn't valid, and will throw an error similar to `Cannot read property "size" of undefined`. + +

+
+ +--- + +--- + +###### 6. Quelle est la sortie ? + +```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éponse +

+ +#### Réponse: A + +In JavaScript, all objects interact by _reference_ when setting them equal to each other. + +First, variable `c` holds a value to an object. Later, we assign `d` with the same reference that `c` has to the object. + + + +When you change one object, you change all of them. + +

+
+ +--- + +###### 7. Quelle est la sortie ? + +```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éponse +

+ +#### Réponse: 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`. + +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.` + +

+
+ +--- + +###### 8. Quelle est la sortie ? + +```javascript +class Chameleon { + 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` + +
Réponse +

+ +#### Réponse: 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. + +

+
+ +--- + +###### 9. Quelle est la sortie ? + +```javascript +let greeting; +greetign = {}; // Typo! +console.log(greetign); +``` + +- A: `{}` +- B: `ReferenceError: greetign is not defined` +- C: `undefined` + +
Réponse +

+ +#### Réponse: 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). + +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. + +

+
+ +--- + +###### 10. Que ce passe-t-il lorsque nous faisons ça ? + +```javascript +function bark() { + console.log("Woof!"); +} + +bark.animal = "dog"; +``` + +- A: Rien, c'est tout à fait bon ! +- B: `SyntaxError`. Vous ne pouvez pas ajouter de propriétés à une fonction de cette façon. +- C: `undefined` +- D: `ReferenceError` + +
Réponse +

+ +#### Réponse: A + +This is possible in JavaScript, because functions are objects! (Everything besides primitive types are objects) + +A function is a special type of object. The code you write yourself isn't the actual function. The function is an object with properties. This property is invocable. + +

+
+ +--- + +###### 11. Quelle est la sortie ? + +```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éponse +

+ +#### Réponse: A + +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() { + return `${this.firstName} ${this.lastName}`; +}; +``` + +would have made `member.getFullName()` work. Why is this beneficial? Say that we added this method to the constructor itself. Maybe not every `Person` instance needed this method. This would waste a lot of memory space, since they would still have that property, which takes of memory space for each instance. Instead, if we only add it to the prototype, we just have it at one spot in memory, yet they all have access to it! + +

+
+ +--- + +###### 12. Quelle est la sortie ? + +```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"}` et `undefined` +- B: `Person {firstName: "Lydia", lastName: "Hallie"}` et `Person {firstName: "Sarah", lastName: "Smith"}` +- C: `Person {firstName: "Lydia", lastName: "Hallie"}` et `{}` +- D:`Person {firstName: "Lydia", lastName: "Hallie"}` et `ReferenceError` + +
Réponse +

+ +#### Réponse: A + +For `sarah`, we didn't use the `new` keyword. When using `new`, it refers to the new empty object we create. However, if you don't add `new` it 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`. + +

+
+ +--- + +###### 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 + +
Réponse +

+ +#### Réponse: 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. Tous les objects ont des prototypes. + +- A: true +- B: false + +
Réponse +

+ +#### Réponse: B + +All objects have prototypes, except for the **base object**. 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. Quelle est la sortie ? + +```javascript +function sum(a, b) { + return a + b; +} + +sum(1, "2"); +``` + +- A: `NaN` +- B: `TypeError` +- C: `"12"` +- D: `3` + +
Réponse +

+ +#### Réponse: 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. Quelle est la sortie ? + +```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éponse +

+ +#### Réponse: 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. Quelle est la sortie ? + +```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éponse +

+ +#### Réponse: 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. Quelle est la sortie ? + +```javascript +function checkAge(data) { + if (data === { age: 18 }) { + console.log("Vous êtes un adulte !"); + } else if (data == { age: 18 }) { + console.log("Vous êtes toujours un adulte."); + } else { + console.log(`Hmm.. Vous n'avez pas l'âge, je suppose.`); + } +} + +checkAge({ age: 18 }); +``` + +- A: `Vous êtes un adulte !` +- B: `Vous êtes toujours un adulte.` +- C: `Hmm.. Vous n'avez pas l'âge, je suppose.` + +
Réponse +

+ +#### Réponse: 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. Quelle est la sortie ? + +```javascript +function getAge(...args) { + console.log(typeof args); +} + +getAge(21); +``` + +- A: `"number"` +- B: `"array"` +- C: `"object"` +- D: `"NaN"` + +
Réponse +

+ +#### Réponse: C + +The spread operator (`...args`.) returns an array with arguments. An array is an object, so `typeof args` returns `"object"` + +

+
+ +--- + +###### 20. Quelle est la sortie ? + +```javascript +function getAge() { + "use strict"; + age = 21; + console.log(age); +} + +getAge(); +``` + +- A: `21` +- B: `undefined` +- C: `ReferenceError` +- D: `TypeError` + +
Réponse +

+ +#### Réponse: 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. Quelle est la valeur de `sum` ? + +```javascript +const sum = eval("10*10+5"); +``` + +- A: `105` +- B: `"105"` +- C: `TypeError` +- D: `"10*10+5"` + +
Réponse +

+ +#### Réponse: 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. Pendant combien de temps `cool_secret` sera-t'il accessible ? + +```javascript +sessionStorage.setItem("cool_secret", 123); +``` + +- A: Pour toujours, les données ne seront pas perdues. +- B: Jusqu'à ce que l'utilisateur ferme l'onglet. +- C: Jusqu'à ce que l'utilisateur ferme son navigateur en entier, pas seulement son onglet. +- D: Jusqu'à ce que l'utilisateur éteindra son ordinateur. + +
Réponse +

+ +#### Réponse: 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. Quelle est la sortie ? + +```javascript +var num = 8; +var num = 10; + +console.log(num); +``` + +- A: `8` +- B: `10` +- C: `SyntaxError` +- D: `ReferenceError` + +
Réponse +

+ +#### Réponse: 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. Quelle est la sortie ? + +```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éponse +

+ +#### Réponse: 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. Quelle est la sortie ? + +```javascript +const obj = { a: "un", b: "deux", a: "trois" }; +console.log(obj); +``` + +- A: `{ a: "un", b: "deux" }` +- B: `{ b: "deux", a: "trois" }` +- C: `{ a: "trois", b: "deux" }` +- D: `SyntaxError` + +
Réponse +

+ +#### Réponse: 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: Vrai +- B: Faux +- C: Ça dépends + +
Réponse +

+ +#### Réponse: A + +The base execution context is the global execution context: it's what's accessible everywhere in your code. + +

+
+ +--- + +###### 27. Quelle est la sortie ? + +```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éponse +

+ +#### Réponse: C + +The `continue` statement skips an iteration if a certain condition returns `true`. + +

+
+ +--- + +###### 28. Quelle est la sortie ? + +```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` + +
Réponse +

+ +#### Réponse: 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. Quelle est la sortie ? + +```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éponse +

+ +#### Réponse: 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. Quelle est la sortie ? + +```javascript +const foo = () => console.log("Premier"); +const bar = () => setTimeout(() => console.log("Second")); +const baz = () => console.log("Troisième"); + +bar(); +foo(); +baz(); +``` + +- A: `Premier` `Second` `Troisième` +- B: `Premier` `Troisième` `Second` +- C: `Second` `Premier` `Troisième` +- D: `Second` `Troisième` `Premier` + +
Réponse +

+ +#### Réponse: 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. + +
Réponse +

+ +#### Réponse: 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` + +
Réponse +

+ +#### Réponse: 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. Quelle est la sortie ? + +```javascript +const person = { name: "Lydia" }; + +function sayHi(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` + +
Réponse +

+ +#### Réponse: 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. Quelle est la sortie ? + +```javascript +function sayHi() { + return (() => 0)(); +} + +typeof sayHi(); +``` + +- A: `"object"` +- B: `"number"` +- C: `"function"` +- D: `"undefined"` + +
Réponse +

+ +#### Réponse: B + +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`, and `symbol`. `"function"` is not a type, since functions are objects, it's of type `"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 + +
Réponse +

+ +#### Réponse: A + +There are only six falsy values: + +- `undefined` +- `null` +- `NaN` +- `0` +- `''` (empty string) +- `false` + +Function constructors, like `new Number` and `new Boolean` are truthy. + +

+
+ +--- + +###### 36. Quelle est la sortie ? + +```javascript +console.log(typeof typeof 1); +``` + +- A: `"number"` +- B: `"string"` +- C: `"object"` +- D: `"undefined"` + +
Réponse +

+ +#### Réponse: B + +`typeof 1` returns `"number"`. +`typeof "number"` returns `"string"` + +

+
+ +--- + +###### 37. Quelle est la sortie ? + +```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` + +
Réponse +

+ +#### Réponse: 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, 7 x empty, 11]` + +depending on where you run it (it's different for every browser, node, etc.) + +

+
+ +--- + +###### 38. Quelle est la sortie ? + +```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éponse +

+ +#### Réponse: 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 + +
Réponse +

+ +#### Réponse: 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 implicity wrap the object 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. Quelle est la sortie ? + +```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éponse +

+ +#### Réponse: 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. Quelle est la sortie ? + +```javascript +!!null; +!!""; +!!1; +``` + +- A: `false` `true` `false` +- B: `false` `false` `true` +- C: `false` `true` `true` +- D: `true` `true` `false` + +
Réponse +

+ +#### Réponse: 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? + +```javascript +setInterval(() => console.log("Hi"), 1000); +``` + +- A: a unique id +- B: the amount of milliseconds specified +- C: the passed function +- D: `undefined` + +
Réponse +

+ +#### Réponse: 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"]]` + +
Réponse +

+ +#### Réponse: A + +A string is an iterable. The spread operator maps every character of an iterable to one element. + +

+
From e76de07a67f976217d29bde8dc42f6e272d06fdd Mon Sep 17 00:00:00 2001 From: madbbb Date: Wed, 19 Jun 2019 15:52:56 +0300 Subject: [PATCH 032/915] Update README.md c.greeting is "Hey!" --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index f6fb9dc4..6aee9c96 100644 --- a/README.md +++ b/README.md @@ -185,7 +185,7 @@ console.log(d.greeting); ``` - A: `Hello` -- B: `Hey` +- B: `Hey!` - C: `undefined` - D: `ReferenceError` - E: `TypeError` From 75a1aab59bb7d91735725080bb0ff0607018fda9 Mon Sep 17 00:00:00 2001 From: Jacob Herper Date: Wed, 19 Jun 2019 14:06:29 +0100 Subject: [PATCH 033/915] German added to README.md --- README.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index f6fb9dc4..c27af63a 100644 --- a/README.md +++ b/README.md @@ -8,7 +8,8 @@ The answers are in the collapsed sections below the questions, simply click on t [中文版本](./README-zh_CN.md) [Русский](./README_ru-RU.md) -[Western Balkan](./README-bs.md) +[Western Balkan](./README-bs.md) +[Deutsch](./README-de_DE.md) --- From 5a327a7c097e5ebede83d51723bc395c73fdd561 Mon Sep 17 00:00:00 2001 From: Lydia Hallie Date: Wed, 19 Jun 2019 16:14:32 +0200 Subject: [PATCH 034/915] Rephrase question 42 --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index f6fb9dc4..36d38371 100644 --- a/README.md +++ b/README.md @@ -1249,7 +1249,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? +###### 42. What does the `setInterval` method return in the browser? ```javascript setInterval(() => console.log("Hi"), 1000); From 3e8dbe73ea5b380b515bec2ea01e4fbd9f52fee2 Mon Sep 17 00:00:00 2001 From: nedimf <24845593+nedimf@users.noreply.github.com> Date: Wed, 19 Jun 2019 17:38:28 +0200 Subject: [PATCH 035/915] Update README.md --- README.md | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index 2e09708a..14cc6042 100644 --- a/README.md +++ b/README.md @@ -6,9 +6,10 @@ From basic to advanced: test how well you know JavaScript, refresh your knowledg The answers are in the collapsed sections below the questions, simply click on them to expand it. Good luck :heart: -[中文版本](./README-zh_CN.md) - -[WESTERN BALKAN](./README-bs.md) +[中文版本](./README-zh_CN.md) +[Русский](./README_ru-RU.md) +[Western Balkan](./README-bs.md) +[Deutsch](./README-de_DE.md) --- @@ -1249,7 +1250,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? +###### 42. What does the `setInterval` method return in the browser? ```javascript setInterval(() => console.log("Hi"), 1000); From 606410ee882fe752a3d2d380d4c61ba9cc2473d7 Mon Sep 17 00:00:00 2001 From: nedimf <24845593+nedimf@users.noreply.github.com> Date: Wed, 19 Jun 2019 17:40:02 +0200 Subject: [PATCH 036/915] Update README.md --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 14cc6042..3d03ecd2 100644 --- a/README.md +++ b/README.md @@ -7,9 +7,9 @@ From basic to advanced: test how well you know JavaScript, refresh your knowledg The answers are in the collapsed sections below the questions, simply click on them to expand it. Good luck :heart: [中文版本](./README-zh_CN.md) -[Русский](./README_ru-RU.md) +[Русский](https://github.com/lydiahallie/javascript-questions/blob/master/README_ru-RU.md) [Western Balkan](./README-bs.md) -[Deutsch](./README-de_DE.md) +[Deutsch](https://github.com/lydiahallie/javascript-questions/blob/master/README-de_DE.md) --- From 7ad07146f7fa50a7d6d75a4e65b90db587ca36e4 Mon Sep 17 00:00:00 2001 From: nedimf <24845593+nedimf@users.noreply.github.com> Date: Wed, 19 Jun 2019 17:42:59 +0200 Subject: [PATCH 037/915] Renamed file so it matches other translations --- README-bs.md => README-bs_BS.md | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename README-bs.md => README-bs_BS.md (100%) diff --git a/README-bs.md b/README-bs_BS.md similarity index 100% rename from README-bs.md rename to README-bs_BS.md From 3eafee2587c3c5b82caa927c8b55bd664e16b797 Mon Sep 17 00:00:00 2001 From: nedimf <24845593+nedimf@users.noreply.github.com> Date: Wed, 19 Jun 2019 17:51:05 +0200 Subject: [PATCH 038/915] Update README-bs_BS.md --- README-bs_BS.md | 302 ++++++++++++++++++++++++------------------------ 1 file changed, 153 insertions(+), 149 deletions(-) diff --git a/README-bs_BS.md b/README-bs_BS.md index 46a5455d..c7ef4628 100644 --- a/README-bs_BS.md +++ b/README-bs_BS.md @@ -1,8 +1,6 @@ # Popis (naprednih) JavaScript pitanja ======================================= -###### Pošto je cilj bio što prije izbaciti domaću verziju ovog odličnog repozitorija vjerovatno je došlo do sitnih gramatičkih i sintatičkih grešaka.Hvala na razumjevanju! - Svakodnevno postavljam JavaScript pitanja s višestrukim izborom na moj [Instagram](https://www.instagram.com/theavocoder), koja također objavljujem ovdje! @@ -15,21 +13,21 @@ Odgovori su jednostavno dijelovima ispod pitanja kliknite na njih da biste ih proširili. Sretno :heart: -[中文版本](./README-zh_CN.md) - -[WESTERN BALKAN](./README-bs.md) - +[中文版本](./README-zh_CN.md) +[Русский](./README_ru-RU.md) +[Western Balkan](./README-bs_BS.md) +[Deutsch](./README-de_DE.md) * * * * * ###### 1. Što je izlaz? ```javascript -function sayHi () { - console.log (ime); - console.log (starosti); - var ime = "Lydia"; - let starost = 21; +function sayHi() { + console.log(name); + console.log(age); + var name = "Lydia"; + let age = 21; } sayHi(); @@ -66,18 +64,18 @@ JavaScript iz bacuje `ReferenceError`. ###### 2. Što je izlaz? ```javascript -for (var i = 0; i <3; i ++) { - setTimeout (() => console.log (i), 1); +for (var i = 0; i < 3; i++) { + setTimeout(() => console.log(i), 1); } -for (let 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` +- A: `0 1 2` i` 0 1 2` +- B: "0 1 2" i "3 3 3" +- C: "3 3 3" i "0 1 2"
Odgovor

@@ -105,16 +103,16 @@ block-scoped (blok je sve između `{}`). Tijekom svake iteracije, ###### 3. Što je izlaz? ```javascript -const oblik = { - radijus: 10, - promjer() { +const shape = { + radius: 10, + diameter() { return this.radius * 2; - } - perimetar: () => 2 * Math.PI * this.radius + }, + perimeter: () => 2 * Math.PI * this.radius }; -oblik.radijus (); -oblik.promjer (); +shape.diameter(); +shape.perimeter(); ``` - A: "20" i "62.83185307179586" @@ -145,8 +143,8 @@ Na tom objektu nema vrijednosti `radius` koja vraća` undefined`. ###### 4. Što je izlaz? ```javascript -+ True; -! "Lydia"; ++true; +!"Lydia"; ``` - A: "1" i "false" @@ -177,14 +175,14 @@ const bird = { }; const mouse = { - ime: "Mickey", + name: "Mickey", small: true }; ``` - A: `mouse.bird.size 'nije valjan - B: `mouse [bird.size]` nije važeća -- C: `miš [ptica [" veličina "]]` nije važeća +- C: `miš [bird [" veličina "]]` nije važeća - D: Svi su valjani

Odgovor @@ -221,12 +219,12 @@ To nije valjano, a bit će u pitanju pogreška slična onoj ###### 6. Što je izlaz? ```javascript -let c = {greeting: "Hej!" }; +let c = { greeting: "Hey!" }; let d; d = c; -c.greeting = "Pozdrav"; -console.log (d.greeting); +c.greeting = "Hello"; +console.log(d.greeting); ``` - A: "Zdravo" @@ -259,12 +257,12 @@ Kada promijenite jedan objekt, mijenjate ih sve. ```javascript let a = 3; -let b = new broj (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` @@ -302,7 +300,7 @@ class Chameleon { return this.newColor; } - constructor({ newColor = "zelena" } = {}) { + constructor({ newColor = "green" } = {}) { this.newColor = newColor; } } @@ -335,9 +333,10 @@ Izbačen je `TypeError`. ###### 9. Što je izlaz? ```javascript -let pozdravi; -greeting = {}; // Typo! -console.log (greetign); +let greeting; +greetign = {}; // Typo! +console.log(greetign); + ``` - A: `{}` @@ -397,17 +396,17 @@ Ova nekretnina je nepovratna. ###### 11. Kakav je rezultat? ```javascript -function Person (ime, prezime) { - this.ime = ime; - this.prezime = prezime; +function Person(firstName, lastName) { + this.firstName = firstName; + this.lastName = lastName; } -const member = new Person ("Lydia", "Hallie"); -Person.getFullName = function () { - return `$ {this.ime} $ {this.prezime}`; +const member = new Person("Lydia", "Hallie"); +Person.getFullName = function() { + return `${this.firstName} ${this.lastName}`; }; -console.log (member.getFullName ()); +console.log(member.getFullName()); ``` - A: `TypeError` @@ -445,16 +444,16 @@ scopa za svaku instancu. Umjesto toga, ako ga samo dodamo prototipu, mi ###### 12. Što je izlaz? ```javascript -function Person (ime, prezime) { - this.ime = ime; - this.prezime = prezime; +function Person(firstName, lastName) { + this.firstName = firstName; + this.lastName = lastName; } -const lydia = new Person ("Lydia", "Hallie"); -const sarah = Person ("Sara", "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 {ime:" Lydia ", prezime:" Hallie "} i` undefined` @@ -532,11 +531,11 @@ nalazi ga tamo, što ga čini dostupnim. ###### 15. Što je izlaz? ```javascript -function sum (a, b) { +function sum(a, b) { return a + b; } -sum (1, "2"); +sum(1, "2"); ``` - A: "NaN" @@ -569,10 +568,10 @@ vraća `" 12 "`. ###### 16. Što je izlaz? ```javascript -let broj = 0; -console.log (broj ++); -console.log (++ broj); -console.log (broj); +let number = 0; +console.log(number++); +console.log(++number); +console.log(number); ``` - A: `1`` 1` `2` @@ -605,21 +604,21 @@ Ovo vraća `0 2 2`. ###### 17. Što je izlaz? ```javascript -function getPersonInfo (one, two, tree) { - console.log (one); - console.log (two); - console.log (tree); +function getPersonInfo(one, two, three) { + console.log(one); + console.log(two); + console.log(three); } -const Person = "Lydia"; +const person = "Lydia"; const age = 21; -getPersonInfo` $ {Person} je $ {old} godina '; +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` `````````````````````````````````````` +- B: ``````````````````````````````````````````````````````````````````````````` +- C: `` Lydia` ``````````````````````````````````````````````````````````
Odgovor

@@ -638,17 +637,17 @@ vrijednosti prošlih izraza! ###### 18. Što je izlaz? ```javascript -function checkAge (podaci) { - ako (podaci === {age: 18}) { - console.log ("Vi ste odrasla osoba!"); - } else if (data == {age: 18}) { - console.log ("Vi ste još uvijek odrasla osoba."); +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 .. Nemate dobnu pretpostavku`); + console.log(`Hmm.. You don't have an age I guess`); } } -checkAge ({age: 18}); +checkAge({ age: 18 }); ``` - A: "Vi ste odrasla osoba!" @@ -679,11 +678,12 @@ Zato i `{age: 18} === {age: 18}` i ###### 19. Što je izlaz? ```javascript -function getAge (... args) { - console.log (vrsta argumenta); + +function getAge(...args) { + console.log(typeof args); } -getAge (21); +getAge(21); ``` - A: `" broj " @@ -707,13 +707,13 @@ array je objekt, pa `typeof args` vraća` `objekt '` ###### 20. Što je izlaz? ```javascript -function getAge () { - "koristite strogi"; - starost = 21; - console.log (starosti); +function getAge() { + "use strict"; + age = 21; + console.log(age); } -getAge (); +getAge(); ``` - A: `21` @@ -740,7 +740,7 @@ nije koristio "" strict ", to bi išlo od vlasništva ###### 21. Što je vrijednost `suma '? ```javascript -const sum = eval ("10x10 + 5"); +const sum = eval("10*10+5"); ``` - A: "105" @@ -765,10 +765,10 @@ kao u ovom slučaju, on ocjenjuje izraz. Izraz je ###### 22. Koliko dugo je cool \ _secret dostupan? ```javascript -sessionStorage.setItem ("cool_secret", 123); +sessionStorage.setItem("cool_secret", 123); ``` -O: Podaci se zauvijek ne izgube. +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. @@ -794,7 +794,7 @@ na primjer, `localStorage.clear ()` je pozvan. var num = 8; var num = 10; -console.log (num); +console.log(num); ``` - A: `8` @@ -820,13 +820,13 @@ To ne možete učiniti s `let` ili` const` jer su blokirani. ###### 24. Što je izlaz? ```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` @@ -855,8 +855,8 @@ To ne radi tako za skup. U našem setu ne postoji "1": ###### 25. Što je izlaz? ```javascript -const obj = {a: "jedan", b: "dva", a: "tri"}; -console.log (obj); +const obj = { a: "one", b: "two", a: "three" }; +console.log(obj); ``` - A: `{a:" jedan ", b:" dva "}` @@ -899,10 +899,11 @@ dostupno svugdje u vašem kodu. ###### 27. Što je izlaz? ```javascript -za (let i = 1; i <5; i ++) { - ako (i === 3) nastavite; - console.log (i); +for (let i = 1; i < 5; i++) { + if (i === 3) continue; + console.log(i); } + ``` - A: `1`` 2` @@ -927,12 +928,12 @@ vraća "true". ```javascript String.prototype.giveLydiaPizza = () => { - povratak "Dajte već picu Lydiju!"; + return "Just give Lydia pizza already!"; }; -const ime = "Lydia"; +const name = "Lydia"; -name.giveLydiaPizza (); +name.giveLydiaPizza(); ``` - A: `` Već daj Lizijinu pizzu! `` @@ -960,13 +961,13 @@ način! ```javascript const a = {}; -const b = {ključ: "b"}; -const c = {ključ: "c"}; +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' @@ -998,13 +999,13 @@ da na `456`, tako da se vraća` 456`. ###### 30. Što je izlaz? ```javascript -const foo = () => console.log ("Prvo"); -const bar = () => setTimeout (() => console.log ("Drugi")); -const baz = () => console.log ("Treći"); +const foo = () => console.log("First"); +const bar = () => setTimeout(() => console.log("Second")); +const baz = () => console.log("Third"); bar(); -foo (); -baz (); +foo(); +baz(); ``` - A: `Prvi`` Drugi` `Treći` @@ -1061,13 +1062,15 @@ stog. ###### 31. Što je event.target kada kliknete na gumb? ```{.html} -
-
-
+ ``` - A: Vanjski 'div' @@ -1091,9 +1094,9 @@ događaj. Možete zaustaviti mjehuriće 'event.stopPropagation' ###### 32. Kada kliknete na paragraf, što je zapisani izlaz? ```{.html} -
-

- Kliknite ovdje! +

+

+ Click here!

``` @@ -1122,14 +1125,14 @@ van. ###### 33. Što je izlaz? ```javascript -const Person = {ime: "Lydia"}; +const person = { name: "Lydia" }; -function sayHi (dob) { - console.log (`$ {this.name} je $ {age}`); +function sayHi(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 je 21` @@ -1156,11 +1159,11 @@ se ne izvršava odmah. ###### 34. Što je izlaz? ```javascript -function sayHi () { - return (() => 0) (); +function sayHi() { + return (() => 0)(); } -vrsta rečiHi (); +typeof sayHi(); ``` - A: `" objekt "` @@ -1190,11 +1193,11 @@ budući da su funkcije objekti, to je tipa `` objekta '`. ```javascript 0; -new broj (0); -( ""); +new Number(0); (""); -new boolean (false); -nedefiniran; +(" "); +new Boolean(false); +undefined; ``` - A: `0`,` ```,` undefined` @@ -1226,7 +1229,8 @@ Konstruktori function, kao što su 'new Number' i 'new Boolean' su istiniti. ###### 36. Što je izlaz? ```javascript -console.log (vrsta tipa 1); +console.log(typeof typeof 1); + ``` - A: `" broj " @@ -1249,9 +1253,9 @@ console.log (vrsta tipa 1); ###### 37. Što je izlaz? ```javascript -const brojevi = [1, 2, 3]; -brojevi [10] = 11; -console.log (br); +const numbers = [1, 2, 3]; +numbers[10] = 11; +console.log(numbers); ``` - A: `[1, 2, 3, 7 x null, 11]` @@ -1283,15 +1287,15 @@ itd) ```javascript (() => { let x, y; - pokušaj { - baciti novu pogrešku (); + try { + throw new Error(); } catch (x) { (x = 1), (y = 2); - console.log (x); + console.log(x); } - console.log (x); - console.log (y); -}) (); + console.log(x); + console.log(y); +})(); ``` - A: `1`` undefined `` 2` @@ -1354,10 +1358,10 @@ osim "null" i "undefined" pokazuju ovo ponašanje. ###### 40. Što je izlaz? ```javascript -[[0, 1], [2, 3]]. +[[0, 1], [2, 3]].reduce( (acc, cur) => { - povratak acc.concat (cur); - } + return acc.concat(cur); + }, [1, 2] ); ``` @@ -1388,9 +1392,9 @@ i dobiti `[1, 2, 0, 1, 2, 3]` ###### 41. Što je izlaz? ```javascript -!! null; -!! ""; -!! 1; +!!null; +!!""; +!!1; ``` - A: `false`` true` `false` @@ -1417,7 +1421,7 @@ i dobiti `[1, 2, 0, 1, 2, 3]` ###### 42. Što se vraća metoda `setInterval`? ```javascript -setInterval (() => console.log ("Hi"), 1000); +setInterval(() => console.log("Hi"), 1000); ``` - A: jedinstveni ID @@ -1441,7 +1445,7 @@ Vraća jedinstveni ID. Taj se ID može koristiti za brisanje tog intervala ###### 43. Što se to vraća? ```javascript -[... "Lydia"]; +[..."Lydia"]; ``` - A: `[" L "," y "," d "," i "," a "]` From cb522e012de2682a31edf50101306f46a0810f98 Mon Sep 17 00:00:00 2001 From: nedimf <24845593+nedimf@users.noreply.github.com> Date: Wed, 19 Jun 2019 18:03:23 +0200 Subject: [PATCH 039/915] Languages changed to required language Languages changed to required language --- README-bs_BS.md | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/README-bs_BS.md b/README-bs_BS.md index c7ef4628..8f7f2058 100644 --- a/README-bs_BS.md +++ b/README-bs_BS.md @@ -13,10 +13,11 @@ Odgovori su jednostavno dijelovima ispod pitanja kliknite na njih da biste ih proširili. Sretno :heart: -[中文版本](./README-zh_CN.md) -[Русский](./README_ru-RU.md) -[Western Balkan](./README-bs_BS.md) -[Deutsch](./README-de_DE.md) +[Kineski 中文版本](./README-zh_CN.md) +[Ruski](./README_ru-RU.md) +[Zapadni balkan](./README-bs_BS.md) +[Njemački](./README-de_DE.md) +[Vijetnamski](./README-vi.md) * * * * * From 04e68a9ffe9e9a7887bab62539f9f4ddb617b169 Mon Sep 17 00:00:00 2001 From: nedimf <24845593+nedimf@users.noreply.github.com> Date: Wed, 19 Jun 2019 18:03:53 +0200 Subject: [PATCH 040/915] Update README-bs_BS.md --- README-bs_BS.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README-bs_BS.md b/README-bs_BS.md index 8f7f2058..7f6bb10f 100644 --- a/README-bs_BS.md +++ b/README-bs_BS.md @@ -17,6 +17,7 @@ kliknite na njih da biste ih proširili. Sretno :heart: [Ruski](./README_ru-RU.md) [Zapadni balkan](./README-bs_BS.md) [Njemački](./README-de_DE.md) + [Vijetnamski](./README-vi.md) * * * * * From 828cb3de88698eabc9db2574514c157981fd7cb9 Mon Sep 17 00:00:00 2001 From: nedimf <24845593+nedimf@users.noreply.github.com> Date: Wed, 19 Jun 2019 18:04:23 +0200 Subject: [PATCH 041/915] Update README-bs_BS.md --- README-bs_BS.md | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/README-bs_BS.md b/README-bs_BS.md index 7f6bb10f..75e47080 100644 --- a/README-bs_BS.md +++ b/README-bs_BS.md @@ -16,8 +16,7 @@ kliknite na njih da biste ih proširili. Sretno :heart: [Kineski 中文版本](./README-zh_CN.md) [Ruski](./README_ru-RU.md) [Zapadni balkan](./README-bs_BS.md) -[Njemački](./README-de_DE.md) - +[Njemački](./README-de_DE.md)
[Vijetnamski](./README-vi.md) * * * * * From 54b14fb7dff02bce978790eca83e9b640364ed45 Mon Sep 17 00:00:00 2001 From: nedimf <24845593+nedimf@users.noreply.github.com> Date: Wed, 19 Jun 2019 18:34:46 +0200 Subject: [PATCH 042/915] Western Balkan link was outdated Fixed Western Balkan link --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index f1d14d90..916fa133 100644 --- a/README.md +++ b/README.md @@ -8,7 +8,7 @@ The answers are in the collapsed sections below the questions, simply click on t [中文版本](./README-zh_CN.md) [Русский](./README_ru-RU.md) -[Western Balkan](./README-bs.md) +[Western Balkan](./README-bs_BS.md) [Deutsch](./README-de_DE.md) [Tiếng Việt](./README-vi.md) From c3856a6407646bf5f8ad303437868605bd9a6971 Mon Sep 17 00:00:00 2001 From: heyitskippy Date: Wed, 19 Jun 2019 19:41:21 +0300 Subject: [PATCH 043/915] README-ru_RU.md: fix question 10 - answer A + update the translation list --- README_ru-RU.md | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/README_ru-RU.md b/README_ru-RU.md index a4eb0829..4cd821f5 100644 --- a/README_ru-RU.md +++ b/README_ru-RU.md @@ -7,7 +7,10 @@ Ответы находятся в свернутой секции ниже вопросов. Просто нажми на ответ, чтобы развернуть. Удачи! :heart: [中文版本](./README-zh_CN.md) -[Русский](./README_ru-RU.md) +[Русский](./README_ru-RU.md) +[Western Balkan](./README-bs.md) +[Deutsch](./README-de_DE.md) +[Tiếng Việt](./README-vi.md) --- @@ -322,8 +325,7 @@ bark.animal = "dog"; В JavaScript это возможно, т.к. функции это объекты! (Всё есть объект кроме примитивов). -Функция это специальный тип объекта, который можно вызвать. Функция это объект со свойствами. -A function is a special type of object. The code you write yourself isn't the actual function. The function is an object with properties. This property is invocable. +Функция — это специальный тип объекта, который можно вызвать. Кроме того, функция — это объект со свойствами. Свойство такого объекта нельзя вызвать, так как оно не является функцией.

From fffc6d180b9867792ed8fa3995b82e6abf51cdef Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Adri=C3=A1n?= <22575055+aguadotzn@users.noreply.github.com> Date: Wed, 19 Jun 2019 23:12:20 +0200 Subject: [PATCH 044/915] Questions 10-20 --- README-ES.md | 126 +++++++++++++++++++++++++-------------------------- 1 file changed, 62 insertions(+), 64 deletions(-) diff --git a/README-ES.md b/README-ES.md index a1f667c6..e9cb0a1b 100644 --- a/README-ES.md +++ b/README-ES.md @@ -36,7 +36,7 @@ sayHi();
Solución

-#### Respuesta Correcta: D +#### Respuesta correcta: D 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`. @@ -65,7 +65,7 @@ for (let i = 0; i < 3; i++) {

Solución

-#### Respuesta Correcta: C +#### Respuesta correcta: C Debido a la cola de eventos en JavaScript, la función `setTimeout` se llama una vez el ciclo se ha ejecutado. Dado que la variable `i` en el primer bucle se declaró utilizando la palabra reservada ` var`, este valor es global. Durante el bucle, incrementamos el valor de `i` en` 1` cada vez, utilizando el operador unario `++`. Cuando se invocó la función `setTimeout`,` i` era igual a `3` en el primer ejemplo. @@ -99,7 +99,7 @@ shape.perimeter();

Solución

-#### Respuesta Correcta: B +#### Respuesta correcta: B Hay que tener en cuenta aqui que el valor de `diámetro` es una función regular o _normal_, mientras que el valor de `perímetro` es una función de flecha. @@ -126,7 +126,7 @@ No hay valor `radius` en ese objeto, que devuelve` undefined`.

Solución

-#### Respuesta Correcta: A +#### Respuesta correcta: A En el primera caso se intenta convertir un operando en un número. `true` es` 1`, y `false` es` 0`. @@ -158,7 +158,7 @@ const mouse = {

Solución

-#### Respuesta Correcta: A +#### Respuesta correcta: A En JavaScript, todas las _keys_ son cadenas (a menos que sea un símbolo). A pesar de que no podríamos escribirlos como cadenas, siempre funcionan como cadenas de manera interna. @@ -173,8 +173,6 @@ Sin embargo, con la notación de puntos, esto no sucede. `mouse` no tiene una cl --- ---- - ###### 6. ¿Qué devuelve la siguiente función? ```javascript @@ -194,7 +192,7 @@ console.log(d.greeting);

Solución

-#### Respuesta Correcta: A +#### Respuesta correcta: A En JavaScript, TODOS los objetos interactúan por referencia, de modo que cuando se establecen iguales o pasan a una función, todos apuntan a la misma ubicación, de modo que cuando cambia un objeto, los cambia a todos. @@ -229,7 +227,7 @@ console.log(b === c);

Solución

-#### Respuesta Correcta: C +#### Respuesta correcta: C `new Number ()` es un constructor de funciones incorporado. Aunque parece un número, no es realmente un número: tiene muchas características adicionales y es un objeto. @@ -268,7 +266,7 @@ freddie.colorChange("orange");

Solución

-#### Respuesta Correcta: D +#### Respuesta correcta: D La función `colorChange` es estática. Los métodos estáticos están diseñados para _vivir_ solo en el constructor en el que se crean y no se pueden transmitir a ningún elemento secundario. Como `freddie` es un niño, la función no se transmite y no está disponible en la instancia de` freddie`: por lo tanto se lanza un `TypeError`. @@ -292,7 +290,7 @@ console.log(greetign);

Solución

-#### Respuesta Correcta: A +#### Respuesta correcta: A Lo que hace JS aquí es registrar el objeto debido a que acabamos de crear un objeto vacío en el objeto global. Cuando escribimos erróneamente `greeting` como` greetign`, el intérprete de JS ve esto como `global.greetign = {}` (o `window.greetign = {}` en un navegador). @@ -321,7 +319,7 @@ bark.animal = "dog";

Solución

-#### Respuesta Correcta: A +#### Respuesta correcta: A Esto es perfectamente posible en JavaScript, porque las funciones son objetos (Recuerda: Todo aparte de los tipos primitivos son objetos en JS) @@ -332,7 +330,7 @@ Una función es un tipo especial de objeto. El código que escribes tú mismo no --- -###### 11. What's the output? +###### 11. ¿Qué devuelve la siguiente función? ```javascript function Person(firstName, lastName) { @@ -353,27 +351,27 @@ console.log(member.getFullName()); - C: `Lydia Hallie` - D: `undefined` `undefined` -

Answer +
Solución

-#### Answer: A +#### Respuesta correcta: A -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, +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, ```js -Person.prototype.getFullName = function () { - return `${this.firstName} ${this.lastName}`; +Persona.prototipo.getFullName = función () {) + devuelve `${este.nombre} ${este.apellido}`; } ``` -would have made `member.getFullName()` work. Why is this beneficial? Say that we added this method to the constructor itself. Maybe not every `Person` instance needed this method. This would waste a lot of memory space, since they would still have that property, which takes of memory space for each instance. Instead, if we only add it to the prototype, we just have it at one spot in memory, yet they all have access to it! +habría hecho que `member.getFullName()` funcionara. ¿Por qué es bueno? Imaginemos que añadimos este método al constructor. Quizás no todas las "personas" necesitaban este método. Esto desperdiciaría mucho espacio de memoria, ya que todavía tendrían esa propiedad, que ocupa espacio de memoria para cada caso. En cambio, si sólo lo añadimos al prototipo, sólo lo tenemos en un lugar en la memoria, ¡pero todos ellos tienen acceso a él!

--- -###### 12. What's the output? +###### 12. ¿Qué devuelve la siguiente función? ```javascript function Person(firstName, lastName) { @@ -393,33 +391,33 @@ console.log(sarah); - C: `Person {firstName: "Lydia", lastName: "Hallie"}` and `{}` - D:`Person {firstName: "Lydia", lastName: "Hallie"}` and `ReferenceError` -
Answer +
Solución

-#### Answer: A +#### Respuesta correcta: A -For `sarah`, we didn't use the `new` keyword. When using `new`, it refers to the new empty object we create. However, if you don't add `new` it refers to the **global object**! +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**! -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`. +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`.

--- -###### 13. What are the three phases of event propagation? +###### 13. ¿Cuáles son las tres fases de la propagación de eventos? - A: Target > Capturing > Bubbling - B: Bubbling > Target > Capturing - C: Target > Bubbling > Capturing - D: Capturing > Target > Bubbling -
Answer +
Solución

-#### Answer: D +#### Respuesta correcta: 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. +Durante la fase de **Capturing**, el evento pasa a través de los elementos ancestrales hasta el elemento objetivo. A continuación, alcanza el elemento **Target** y comienza el **bubbling**. Más información [aquí](https://www.sitepoint.com/event-bubbling-javascript/). @@ -433,19 +431,19 @@ During the **capturing** phase, the event goes through the ancestor elements dow - A: true - B: false -

Answer +
Solución

-#### Answer: B +#### Respuesta correcta: B -All objects have prototypes, except for the **base object**. 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. +Todos los objetos tienen prototipos, excepto el **objeto base** (Más info [aquí](https://stackoverflow.com/questions/56659303/what-is-base-object-in-javascript)). El componente tiene acceso a algunos métodos y propiedades, como `.toString`. Esta es la razón principal por la que se puede utilizar los métodos JavaScript incorporados. Todos estos métodos están disponibles en el prototipo. Aunque JavaScript no puede encontrar de manera directa en su objeto, baja por la cadena de prototipos y lo encuentra allí, lo que lo hace accesible para poder usarse posteriormente.

--- -###### 15. What's the output? +###### 15. ¿Qué devuelve la siguiente función? ```javascript function sum(a, b) { @@ -460,21 +458,21 @@ sum(1, "2"); - C: `"12"` - D: `3` -
Answer +
Solución

-#### Answer: C +#### Respuesta correcta: 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. +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.** -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"`. +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"`

--- -###### 16. What's the output? +###### 16. ¿Qué devuelve la siguiente función? ```javascript let number = 0; @@ -488,29 +486,29 @@ console.log(number); - C: `0` `2` `2` - D: `0` `1` `2` -
Answer +
Solución

-#### Answer: C +#### Respuesta correcta: C -The **postfix** unary operator `++`: +El operador **postfix** unario `++`: -1. Returns the value (this returns `0`) -2. Increments the value (number is now `1`) +1. Devuelve el valor (esto devuelve `0`) +2. Incrementa el valor (el número es ahora `1`) -The **prefix** unary operator `++`: +El operador unario **prefix** `++`: -1. Increments the value (number is now `2`) -2. Returns the value (this returns `2`) +1. Incrementa el valor (el número es ahora `2`) +2. Devuelve el valor (esto devuelve `2`) -This returns `0 2 2`. +Por lo tanto, devuelve `0 2 2 2`.

--- -###### 17. What's the output? +###### 17. ¿Qué devuelve la siguiente función? ```javascript function getPersonInfo(one, two, three) { @@ -529,19 +527,19 @@ getPersonInfo`${person} is ${age} years old`; - B: `["", " is ", " years old"]` `"Lydia"` `21` - C: `"Lydia"` `["", " is ", " years old"]` `21` -
Answer +
Solución

-#### Answer: B +#### Respuesta correcta: 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! +_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.

--- -###### 18. What's the output? +###### 18. ¿Qué devuelve la siguiente función? ```javascript function checkAge(data) { @@ -561,23 +559,23 @@ checkAge({ age: 18 }); - B: `You are still an adult.` - C: `Hmm.. You don't have an age I guess` -
Answer +
Solución

-#### Answer: C +#### Respuesta correcta: 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. +Al probar la igualdad, las primitivas se comparan por su _valor_, mientras que los objetos se comparan por su _referencia_. JavaScript comprueba si los objetos tienen una referencia a la misma ubicación en la memoria. -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. +Los dos objetos que estamos comparando no tienen eso: el objeto que pasamos como parámetro se refiere a una ubicación diferente en la memoria que el objeto que usamos para comprobar la igualdad. -This is why both `{ age: 18 } === { age: 18 }` and `{ age: 18 } == { age: 18 }` return `false`. +Esta es la razón por la que ambos `{ edad: 18 } === { edad: 18 }` y `{ edad: 18 }} == { edad: 18 }` devuelven `false`

--- -###### 19. What's the output? +###### 19. ¿Qué devuelve la siguiente función? ```javascript function getAge(...args) { @@ -592,19 +590,19 @@ getAge(21); - C: `"object"` - D: `"NaN"` -
Answer +
Solución

-#### Answer: C +#### Respuesta correcta: C -The spread operator (`...args`.) returns an array with arguments. An array is an object, so `typeof args` returns `"object"` +El operador spread (`...args`.) devuelve un array con argumentos. Una matriz es un objeto, así que `typeof args` devuelve `"object"`

--- -###### 20. What's the output? +###### 20. ¿Qué devuelve la siguiente función? ```javascript function getAge() { @@ -621,12 +619,12 @@ getAge(); - C: `ReferenceError` - D: `TypeError` -
Answer +
Solución

-#### Answer: C +#### Respuesta correcta: 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. +Con `"use strict"`, es posible asegurarse de que no se declara accidentalmente variables globales. Nunca declaramos la variable `age`, y como usamos `"use strict"`, nos dará un error de referencia. Si no hubiéramos usado `"use strict"`, habría funcionado, ya que la propiedad `age` se habría añadido al objeto global.

From 5068bc52fba5e0dbb9820d9526331885a2f65234 Mon Sep 17 00:00:00 2001 From: Ihor Sychevskyi <26163841+Arhell@users.noreply.github.com> Date: Thu, 20 Jun 2019 01:07:55 +0300 Subject: [PATCH 045/915] Fix typo, Ru --- README_ru-RU.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README_ru-RU.md b/README_ru-RU.md index a4eb0829..afdbb8b2 100644 --- a/README_ru-RU.md +++ b/README_ru-RU.md @@ -2,7 +2,7 @@ Я ежедевно публикую вопросы по JavaScript с вариантами ответов в своем [Instagram](https://www.instagram.com/theavocoder), которые дублируются в этом репозитории. -От азов к сложным вопросам: провеь как хорошо ты знаешь JavaScript, освежи свои знания или приготовься к собеседованию! :muscle: :rocket: Я дополняю этот репозиторий каждую неделю новыми вопросами. +От азов к сложным вопросам: проверь как хорошо ты знаешь JavaScript, освежи свои знания или приготовься к собеседованию! :muscle: :rocket: Я дополняю этот репозиторий каждую неделю новыми вопросами. Ответы находятся в свернутой секции ниже вопросов. Просто нажми на ответ, чтобы развернуть. Удачи! :heart: From 294ab31520e531f64f20371ffb6f82e3e7839744 Mon Sep 17 00:00:00 2001 From: Guilherme Nogara Date: Wed, 19 Jun 2019 20:03:41 -0300 Subject: [PATCH 046/915] started pt_BR README --- README_pt_BR.md | 1298 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 1298 insertions(+) create mode 100644 README_pt_BR.md diff --git a/README_pt_BR.md b/README_pt_BR.md new file mode 100644 index 00000000..6c3cfd85 --- /dev/null +++ b/README_pt_BR.md @@ -0,0 +1,1298 @@ +# Lista de questões (avançadas) sobre JavaScript + +Posto questões de múltipla escolha sobre JavaScript no meu [Instagram](https://www.instagram.com/theavocoder), as quais também posto aqui! + +Do básico ao avançado: Teste quão bem você conhece o JavaScript, refresce um pouco do seu conhecimento, ou se prepare para uma entrevista! :muscle: :rocket: Eu atualizo esse repositório semanalmente com novas questões. + +As respostas estão em seções recolhidas abaixo das questões, basta clicar nelas para expandir. Boa sorte :heart: + +[English](./README.md) +[中文版本](./README-zh_CN.md) +[Русский](./README_ru-RU.md) +[Western Balkan](./README-bs.md) +[Deutsch](./README-de_DE.md) +[Tiếng Việt](./README-vi.md) + + +--- + +###### 1. Qual é a saída? + +```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` + +
Answer +

+ +#### Resposta: D + +Dentro da função, nós primeiro declaramos a variável `name` usando a palavra-chave `var`. Isso significa que a variavel é elevada(hoisted) (O espaço na memória é separado durante a fase de criação) com o valor padrão `undefined`, até que chegue na linha onde definimos a variável. Ainda não definimos a variável na linha onde tentamos usar colocar no log o valor da variável `name`, portanto ela ainda tem o valor `undefined`. + +Variáveis com a palavra-chave `let` (e `const`) são elevadas, mas diferente de `var`, não são inicializadas. Elas não acessíveis antes da linha em que as declaramos (ou inicializamos). Esse é um conceito chamado de "temporal dead zone". Quando tentamos acessar essas variáveis antes de serem declaradas, o JavaScript lança um `ReferenceError` + +

+
+ +--- + +###### 2. What's the 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` and `0 1 2` +- B: `0 1 2` and `3 3 3` +- C: `3 3 3` and `0 1 2` + +
Answer +

+ +#### Answer: C + +Because of the event queue in JavaScript, the `setTimeout` callback function is called _after_ the loop has been executed. Since the variable `i` in the first loop was declared using the `var` keyword, this value was global. During the loop, we incremented the value of `i` by `1` each time, using the unary operator `++`. By the time the `setTimeout` callback function was invoked, `i` was equal to `3` in the first example. + +In the second loop, the variable `i` was declared using the `let` keyword: variables declared with the `let` (and `const`) keyword are block-scoped (a block is anything between `{ }`). During each iteration, `i` will have a new value, and each value is scoped inside the loop. + +

+
+ +--- + +###### 3. What's the output? + +```javascript +const shape = { + radius: 10, + diameter() { + return this.radius * 2; + }, + perimeter: () => 2 * Math.PI * this.radius +}; + +shape.diameter(); +shape.perimeter(); +``` + +- A: `20` and `62.83185307179586` +- B: `20` and `NaN` +- C: `20` and `63` +- D: `NaN` and `63` + +
Answer +

+ +#### Answer: B + +Note that the value of `diameter` is a regular function, whereas the value of `perimeter` is an arrow function. + +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 `undefined`. + +

+
+ +--- + +###### 4. What's the output? + +```javascript ++true; +!"Lydia"; +``` + +- A: `1` and `false` +- B: `false` and `NaN` +- C: `false` and `false` + +
Answer +

+ +#### Answer: A + +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`. + +

+
+ +--- + +###### 5. Which one is true? + +```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 + +
Answer +

+ +#### Answer: A + +In JavaScript, all object keys are strings (unless it's a Symbol). Even though we might not _type_ them as strings, they are always converted into strings under the hood. + +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. + +`mouse[bird.size]`: First it evaluates `bird.size`, which is `"small"`. `mouse["small"]` returns `true` + +However, with dot notation, this doesn't happen. `mouse` does not have a key called `bird`, which means that `mouse.bird` is `undefined`. Then, we ask for the `size` using dot notation: `mouse.bird.size`. Since `mouse.bird` is `undefined`, we're actually asking `undefined.size`. This isn't valid, and will throw an error similar to `Cannot read property "size" of undefined`. + +

+
+ +--- + +--- + +###### 6. What's the 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` + +
Answer +

+ +#### Answer: A + +In JavaScript, all objects interact by _reference_ when setting them equal to each other. + +First, variable `c` holds a value to an object. Later, we assign `d` with the same reference that `c` has to the object. + + + +When you change one object, you change all of them. + +

+
+ +--- + +###### 7. What's the 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` + +
Answer +

+ +#### Answer: 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`. + +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.` + +

+
+ +--- + +###### 8. What's the 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" }); +freddie.colorChange("orange"); +``` + +- A: `orange` +- B: `purple` +- C: `green` +- D: `TypeError` + +
Answer +

+ +#### 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. + +

+
+ +--- + +###### 9. What's the output? + +```javascript +let greeting; +greetign = {}; // Typo! +console.log(greetign); +``` + +- A: `{}` +- B: `ReferenceError: greetign is not defined` +- C: `undefined` + +
Answer +

+ +#### 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). + +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. + +

+
+ +--- + +###### 10. What happens when we do this? + +```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: `undefined` +- D: `ReferenceError` + +
Answer +

+ +#### Answer: A + +This is possible in JavaScript, because functions are objects! (Everything besides primitive types are objects) + +A function is a special type of object. The code you write yourself isn't the actual function. The function is an object with properties. This property is invocable. + +

+
+ +--- + +###### 11. What's the 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` + +
Answer +

+ +#### Answer: A + +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() { + return `${this.firstName} ${this.lastName}`; +}; +``` + +would have made `member.getFullName()` work. Why is this beneficial? Say that we added this method to the constructor itself. Maybe not every `Person` instance needed this method. This would waste a lot of memory space, since they would still have that property, which takes of memory space for each instance. Instead, if we only add it to the prototype, we just have it at one spot in memory, yet they all have access to it! + +

+
+ +--- + +###### 12. What's the 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` + +
Answer +

+ +#### Answer: A + +For `sarah`, we didn't use the `new` keyword. When using `new`, it refers to the new empty object we create. However, if you don't add `new` it 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`. + +

+
+ +--- + +###### 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 + +
Answer +

+ +#### Answer: 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 + +
Answer +

+ +#### Answer: B + +All objects have prototypes, except for the **base object**. 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. What's the output? + +```javascript +function sum(a, b) { + return a + b; +} + +sum(1, "2"); +``` + +- A: `NaN` +- B: `TypeError` +- C: `"12"` +- D: `3` + +
Answer +

+ +#### Answer: 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. What's the 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` + +
Answer +

+ +#### Answer: 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. What's the 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` + +
Answer +

+ +#### Answer: 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. What's the 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` + +
Answer +

+ +#### Answer: 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. What's the output? + +```javascript +function getAge(...args) { + console.log(typeof args); +} + +getAge(21); +``` + +- A: `"number"` +- B: `"array"` +- C: `"object"` +- D: `"NaN"` + +
Answer +

+ +#### Answer: C + +The spread operator (`...args`.) returns an array with arguments. An array is an object, so `typeof args` returns `"object"` + +

+
+ +--- + +###### 20. What's the output? + +```javascript +function getAge() { + "use strict"; + age = 21; + console.log(age); +} + +getAge(); +``` + +- A: `21` +- B: `undefined` +- C: `ReferenceError` +- D: `TypeError` + +
Answer +

+ +#### Answer: 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 value of `sum`? + +```javascript +const sum = eval("10*10+5"); +``` + +- A: `105` +- B: `"105"` +- C: `TypeError` +- D: `"10*10+5"` + +
Answer +

+ +#### 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`. + +

+
+ +--- + +###### 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. + +
Answer +

+ +#### Answer: 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. What's the output? + +```javascript +var num = 8; +var num = 10; + +console.log(num); +``` + +- A: `8` +- B: `10` +- C: `SyntaxError` +- D: `ReferenceError` + +
Answer +

+ +#### Answer: 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. What's the 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` + +
Answer +

+ +#### Answer: 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. What's the 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` + +
Answer +

+ +#### Answer: 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 + +
Answer +

+ +#### Answer: A + +The base execution context is the global execution context: it's what's accessible everywhere in your code. + +

+
+ +--- + +###### 27. What's the 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` + +
Answer +

+ +#### Answer: C + +The `continue` statement skips an iteration if a certain condition returns `true`. + +

+
+ +--- + +###### 28. What's the 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` + +
Answer +

+ +#### 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! + +

+
+ +--- + +###### 29. What's the 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` + +
Answer +

+ +#### Answer: 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. What's the 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` + +
Answer +

+ +#### Answer: 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. + +
Answer +

+ +#### Answer: 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` + +
Answer +

+ +#### 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. + +

+
+ +--- + +###### 33. What's the output? + +```javascript +const person = { name: "Lydia" }; + +function sayHi(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` + +
Answer +

+ +#### Answer: 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. What's the output? + +```javascript +function sayHi() { + return (() => 0)(); +} + +typeof sayHi(); +``` + +- A: `"object"` +- B: `"number"` +- C: `"function"` +- D: `"undefined"` + +
Answer +

+ +#### Answer: B + +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`, and `symbol`. `"function"` is not a type, since functions are objects, it's of type `"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 + +
Answer +

+ +#### Answer: A + +There are only six falsy values: + +- `undefined` +- `null` +- `NaN` +- `0` +- `''` (empty string) +- `false` + +Function constructors, like `new Number` and `new Boolean` are truthy. + +

+
+ +--- + +###### 36. What's the output? + +```javascript +console.log(typeof typeof 1); +``` + +- A: `"number"` +- B: `"string"` +- C: `"object"` +- D: `"undefined"` + +
Answer +

+ +#### Answer: B + +`typeof 1` returns `"number"`. +`typeof "number"` returns `"string"` + +

+
+ +--- + +###### 37. What's the 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` + +
Answer +

+ +#### Answer: 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, 7 x empty, 11]` + +depending on where you run it (it's different for every browser, node, etc.) + +

+
+ +--- + +###### 38. What's the 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` + +
Answer +

+ +#### Answer: 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 + +
Answer +

+ +#### Answer: 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 implicity wrap the object 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. What's the 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]` + +
Answer +

+ +#### Answer: 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. What's the output? + +```javascript +!!null; +!!""; +!!1; +``` + +- A: `false` `true` `false` +- B: `false` `false` `true` +- C: `false` `true` `true` +- D: `true` `true` `false` + +
Answer +

+ +#### Answer: 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` + +
Answer +

+ +#### Answer: 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"]]` + +
Answer +

+ +#### Answer: A + +A string is an iterable. The spread operator maps every character of an iterable to one element. + +

+
From 967481a4c47fb7fba3c538d169fb2cd981f13014 Mon Sep 17 00:00:00 2001 From: Guilherme Nogara Date: Wed, 19 Jun 2019 20:39:48 -0300 Subject: [PATCH 047/915] Questions 1-3 done --- README_pt_BR.md | 38 +++++++++++++++++++------------------- 1 file changed, 19 insertions(+), 19 deletions(-) diff --git a/README_pt_BR.md b/README_pt_BR.md index 6c3cfd85..3a6f20de 100644 --- a/README_pt_BR.md +++ b/README_pt_BR.md @@ -34,7 +34,7 @@ sayHi(); - C: `ReferenceError` e `21` - D: `undefined` e `ReferenceError` -
Answer +
Resposta

#### Resposta: D @@ -48,7 +48,7 @@ Variáveis com a palavra-chave `let` (e `const`) são elevadas, mas diferente de --- -###### 2. What's the output? +###### 2. Qual é a saída? ```javascript for (var i = 0; i < 3; i++) { @@ -60,25 +60,25 @@ for (let i = 0; i < 3; i++) { } ``` -- A: `0 1 2` and `0 1 2` -- B: `0 1 2` and `3 3 3` -- C: `3 3 3` and `0 1 2` +- A: `0 1 2` e `0 1 2` +- B: `0 1 2` e `3 3 3` +- C: `3 3 3` e `0 1 2` -

Answer +
Resposta

-#### Answer: C +#### Resposta: C -Because of the event queue in JavaScript, the `setTimeout` callback function is called _after_ the loop has been executed. Since the variable `i` in the first loop was declared using the `var` keyword, this value was global. During the loop, we incremented the value of `i` by `1` each time, using the unary operator `++`. By the time the `setTimeout` callback function was invoked, `i` was equal to `3` in the first example. +Por causa da fila de eventos em JavaScript, a callback de `setTimeout` é chamada depois do laço ter sido executado. Já que a variável `i` no primeiro laço foi declarada usando a palavra-chave `var`, seu valor era global. Durante o laço, incrementamos o valor de `i` por `1` em cada repetição, usando o operador unário `++`. Quando a callback de `setTimeout` foi chamada, `i` valia `3`. -In the second loop, the variable `i` was declared using the `let` keyword: variables declared with the `let` (and `const`) keyword are block-scoped (a block is anything between `{ }`). During each iteration, `i` will have a new value, and each value is scoped inside the loop. +No segundo laço, a variável `i` foi declarada usando a palavra-chave `let`: Variáveis declaradas com `let` (e `const`) só são acessíveis nos escopos de seus blocos (um bloco é qualquer código entre `{ }`). Durante cada repetição do laço, `i` vai ter um novo valor, e cada valor tem seu escopo dentro do laço.

--- -###### 3. What's the output? +###### 3. Qual é a saída? ```javascript const shape = { @@ -93,21 +93,21 @@ shape.diameter(); shape.perimeter(); ``` -- A: `20` and `62.83185307179586` -- B: `20` and `NaN` -- C: `20` and `63` -- D: `NaN` and `63` +- A: `20` e `62.83185307179586` +- B: `20` e `NaN` +- C: `20` e `63` +- D: `NaN` e `63` -
Answer +
Resposta

-#### Answer: B +#### Resposta: B -Note that the value of `diameter` is a regular function, whereas the value of `perimeter` is an arrow function. +Perceba que o valor de `diameter` é uma função normal, enquanto que o valor de `perimeter` é uma arrow function. -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). +Com arrow functions, a palavra-chave `this` faz referência ao escopo atual em que está inserida, diferente de funções normais! Isso significa que quando nós chamamos `perimeter`, ela não faz referência ao objeto shape, mas ao seu escopo atual (por exemplo, window). -There is no value `radius` on that object, which returns `undefined`. +Não há `radius` fora de shape, então retorna `undefined`.

From b6fa9fbe0280ab967127ce9c5383255801b749dc Mon Sep 17 00:00:00 2001 From: Guilherme Nogara Date: Wed, 19 Jun 2019 20:39:48 -0300 Subject: [PATCH 048/915] Questions 1-3 done MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit [english] e [中文版本] tem quebra de linha entre os dois. --- README_pt_BR.md | 40 ++++++++++++++++++++-------------------- 1 file changed, 20 insertions(+), 20 deletions(-) diff --git a/README_pt_BR.md b/README_pt_BR.md index 6c3cfd85..60b85219 100644 --- a/README_pt_BR.md +++ b/README_pt_BR.md @@ -6,7 +6,7 @@ Do básico ao avançado: Teste quão bem você conhece o JavaScript, refresce um As respostas estão em seções recolhidas abaixo das questões, basta clicar nelas para expandir. Boa sorte :heart: -[English](./README.md) +[English](./README.md) [中文版本](./README-zh_CN.md) [Русский](./README_ru-RU.md) [Western Balkan](./README-bs.md) @@ -34,7 +34,7 @@ sayHi(); - C: `ReferenceError` e `21` - D: `undefined` e `ReferenceError` -
Answer +
Resposta

#### Resposta: D @@ -48,7 +48,7 @@ Variáveis com a palavra-chave `let` (e `const`) são elevadas, mas diferente de --- -###### 2. What's the output? +###### 2. Qual é a saída? ```javascript for (var i = 0; i < 3; i++) { @@ -60,25 +60,25 @@ for (let i = 0; i < 3; i++) { } ``` -- A: `0 1 2` and `0 1 2` -- B: `0 1 2` and `3 3 3` -- C: `3 3 3` and `0 1 2` +- A: `0 1 2` e `0 1 2` +- B: `0 1 2` e `3 3 3` +- C: `3 3 3` e `0 1 2` -

Answer +
Resposta

-#### Answer: C +#### Resposta: C -Because of the event queue in JavaScript, the `setTimeout` callback function is called _after_ the loop has been executed. Since the variable `i` in the first loop was declared using the `var` keyword, this value was global. During the loop, we incremented the value of `i` by `1` each time, using the unary operator `++`. By the time the `setTimeout` callback function was invoked, `i` was equal to `3` in the first example. +Por causa da fila de eventos em JavaScript, a callback de `setTimeout` é chamada depois do laço ter sido executado. Já que a variável `i` no primeiro laço foi declarada usando a palavra-chave `var`, seu valor era global. Durante o laço, incrementamos o valor de `i` por `1` em cada repetição, usando o operador unário `++`. Quando a callback de `setTimeout` foi chamada, `i` valia `3`. -In the second loop, the variable `i` was declared using the `let` keyword: variables declared with the `let` (and `const`) keyword are block-scoped (a block is anything between `{ }`). During each iteration, `i` will have a new value, and each value is scoped inside the loop. +No segundo laço, a variável `i` foi declarada usando a palavra-chave `let`: Variáveis declaradas com `let` (e `const`) só são acessíveis nos escopos de seus blocos (um bloco é qualquer código entre `{ }`). Durante cada repetição do laço, `i` vai ter um novo valor, e cada valor tem seu escopo dentro do laço.

--- -###### 3. What's the output? +###### 3. Qual é a saída? ```javascript const shape = { @@ -93,21 +93,21 @@ shape.diameter(); shape.perimeter(); ``` -- A: `20` and `62.83185307179586` -- B: `20` and `NaN` -- C: `20` and `63` -- D: `NaN` and `63` +- A: `20` e `62.83185307179586` +- B: `20` e `NaN` +- C: `20` e `63` +- D: `NaN` e `63` -
Answer +
Resposta

-#### Answer: B +#### Resposta: B -Note that the value of `diameter` is a regular function, whereas the value of `perimeter` is an arrow function. +Perceba que o valor de `diameter` é uma função normal, enquanto que o valor de `perimeter` é uma arrow function. -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). +Com arrow functions, a palavra-chave `this` faz referência ao escopo atual em que está inserida, diferente de funções normais! Isso significa que quando nós chamamos `perimeter`, ela não faz referência ao objeto shape, mas ao seu escopo atual (por exemplo, window). -There is no value `radius` on that object, which returns `undefined`. +Não há `radius` fora de shape, então retorna `undefined`.

From c1add6d66c9e09da325e6cb13320a1cdb2a09848 Mon Sep 17 00:00:00 2001 From: zeayal Date: Thu, 20 Jun 2019 10:12:43 +0800 Subject: [PATCH 049/915] Update README-zh_CN.md remove extra symbol. --- README-zh_CN.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README-zh_CN.md b/README-zh_CN.md index bc21b456..770a6eb5 100644 --- a/README-zh_CN.md +++ b/README-zh_CN.md @@ -1270,7 +1270,7 @@ setInterval(() => console.log('Hi'), 1000) ###### 43. 输出是什么? ```javascript -;[...'Lydia'] +[...'Lydia'] ``` - A: `["L", "y", "d", "i", "a"]` From 6199ad7207509e48056c2558372a960be553754b Mon Sep 17 00:00:00 2001 From: Do Trung Kien Date: Thu, 20 Jun 2019 09:23:57 +0700 Subject: [PATCH 050/915] correct typo and improve tranlation --- README-vi.md | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/README-vi.md b/README-vi.md index b9b7c3be..d38d7a35 100644 --- a/README-vi.md +++ b/README-vi.md @@ -439,8 +439,9 @@ Tất cả các object đều có prototypes, ngoại trừ **base object**. Obj

-
--- +
+--- ###### 15. Ouput là gì? @@ -859,7 +860,6 @@ console.log(a[b]); Object keys sẽ tự động được convert sang dạng string. Chúng ta đang set một object như là một key cho object `a`, với giá trị là `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`. Tuy nhiên khi ta string hóa một object, nó sẽ trở thành `"[Object object]"`. Nên tại đây phép gán này thực chất chính là `a["Object object"] = 123`. Phép gán tiếp theo cũng giống hệt vậy. `c` là một object khác mà chúng ta đang string hóa nó. Theo đó, `a["Object object"] = 456`. Cuối cùng khi gọi `a[b]`, thực chất chính là gọi `a["Object object"]`. Giá trị của nó là `456`, nên trả về là `456`. @@ -915,7 +915,7 @@ WebAPI không thể thêm thứ gì đó vào stack cho tới khi nó được s -`bar` được gọi, `"Second"` được log ra, và nó được đưa ra khói stack. +`bar` được gọi, `"Second"` được log ra, và nó được đưa ra khỏi stack.

@@ -1053,7 +1053,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: Tất cả đều là falsy
Đáp án

@@ -1210,7 +1210,6 @@ Primitive types là `boolean`, `null`, `undefined`, `bigint`, `number`, `string` #### Đáp án: 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]`. `[1, 2]` là giá trị khởi tạo. Đây là giá trị chúng ta bắt đầu, và cũng là giá trị đầu tiên của `acc`. Tại vòng đầu tiên, `acc` là `[1,2]`, và `cur` là `[0, 1]`. Ta nối chúng lại tạo ra `[1, 2, 0, 1]`. Tiếp tục, `[1, 2, 0, 1]` là `acc` và `[2, 3]` là `cur`. Ta nối chúng lại tạo ra `[1, 2, 0, 1, 2, 3]`. From 3e26a20c59865a56fbb286959a60a8a0a4c84b75 Mon Sep 17 00:00:00 2001 From: fanfan1609 Date: Thu, 20 Jun 2019 12:01:31 +0900 Subject: [PATCH 051/915] Update README-vi.md Update question 13. --- README-vi.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README-vi.md b/README-vi.md index b9b7c3be..ba3fa2d0 100644 --- a/README-vi.md +++ b/README-vi.md @@ -404,7 +404,7 @@ Chúng ta cho rằng `this.firstName` là `"Sarah"` và `this.lastName` là `"Sm --- -###### 13. What are the three phases of event propagation? +###### 13. 3 giai đoạn của event propagation là gì? - A: Target > Capturing > Bubbling - B: Bubbling > Target > Capturing From 6e5415c67386c680478469c2cacc485dfe218a0d Mon Sep 17 00:00:00 2001 From: Guilherme Nogara Date: Thu, 20 Jun 2019 01:12:58 -0300 Subject: [PATCH 052/915] 3-15 done --- README_pt_BR.md | 142 +++++++++++++++++++++++++----------------------- 1 file changed, 73 insertions(+), 69 deletions(-) diff --git a/README_pt_BR.md b/README_pt_BR.md index 60b85219..0c5ab777 100644 --- a/README_pt_BR.md +++ b/README_pt_BR.md @@ -114,7 +114,7 @@ Não há `radius` fora de shape, então retorna `undefined`. --- -###### 4. What's the output? +###### 4. Qual é a saída? ```javascript +true; @@ -125,21 +125,22 @@ Não há `radius` fora de shape, então retorna `undefined`. - B: `false` and `NaN` - C: `false` and `false` -

Answer +
Resposta

-#### Answer: A +#### Resposta: A -The unary plus tries to convert an operand to a number. `true` is `1`, and `false` is `0`. +O operador unário `+` tenta converter um operando para um número. `true` é `1`, e `false` é `0`. -The string `'Lydia'` is a truthy value. What we're actually asking, is "is this truthy value falsy?". This returns `false`. +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 é falsey, que são valores que podem ser convertidos em um booleano `false`. Para fins de consistência, mantenho os termos originais.

--- -###### 5. Which one is true? +###### 5. Qual é a alternativa correta? ```javascript const bird = { @@ -152,23 +153,23 @@ const mouse = { }; ``` -- 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 +- A: `mouse.bird.size` não é válido +- B: `mouse[bird.size]` não é válido +- C: `mouse[bird["size"]]` não é válido +- D: Todos são válidos -
Answer +
Resposta

-#### Answer: A +#### Resposta: A -In JavaScript, all object keys are strings (unless it's a Symbol). Even though we might not _type_ them as strings, they are always converted into strings under the hood. +No JavaScript, todas chaves dos objetos são strings (a não ser que sejam um símbolo). Ainda que não possamos digitá-las como strings, elas são sempre convertidas para string sob o capô. -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. +JavaScript interpreta afirmações. Quando usamos a notação de colchetes, ele vê o colchete de abertura `[` e continua lendo até encontrar o colchete que o fecha `]`. Só então vai avaliar e rodar as afirmações. -`mouse[bird.size]`: First it evaluates `bird.size`, which is `"small"`. `mouse["small"]` returns `true` +`mouse[bird.size]`: Primeiro avalia `bird.size`, que é `"small"`. `mouse["small"]` retorna `true` -However, with dot notation, this doesn't happen. `mouse` does not have a key called `bird`, which means that `mouse.bird` is `undefined`. Then, we ask for the `size` using dot notation: `mouse.bird.size`. Since `mouse.bird` is `undefined`, we're actually asking `undefined.size`. This isn't valid, and will throw an error similar to `Cannot read property "size" of undefined`. +Por outro lado, com a notação de ponto `.`, isso não acontece. `mouse` não tem uma chave chamada `bird`, o que significa que `mouse.bird` é `undefined`. Então, pedimos pelo `size` usando a notação de ponto: `mouse.bird.size`. Uma vez que `mouse.bird` é `undefined`, estamos realmente pedindo `undefined.size`. Isso não é válido, e irá gerar um erro similar a `Cannot read property "size" of undefined`.

@@ -177,7 +178,7 @@ However, with dot notation, this doesn't happen. `mouse` does not have a key cal --- -###### 6. What's the output? +###### 6. Quais são as saídas? ```javascript let c = { greeting: "Hey!" }; @@ -194,25 +195,25 @@ console.log(d.greeting); - D: `ReferenceError` - E: `TypeError` -
Answer +
Resposta

-#### Answer: A +#### Resposta: A -In JavaScript, all objects interact by _reference_ when setting them equal to each other. +Em JavaScript, todos objetos interagem por referência quando os colocamos um igual ao outro. -First, variable `c` holds a value to an object. Later, we assign `d` with the same reference that `c` has to the object. +Primeiro, a variável `c` guarda o valor de um objeto. Depois, declaramos `d` com a mesma referencia que `c` tem para o objeto. -When you change one object, you change all of them. +Quando você muda um objeto, você muda todos eles.

--- -###### 7. What's the output? +###### 7. Qual é a saída? ```javascript let a = 3; @@ -229,23 +230,23 @@ console.log(b === c); - C: `true` `false` `false` - D: `false` `true` `true` -
Answer +
Resposta

-#### Answer: C +#### Resposta: 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. +`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. -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`. +Quando usamos o operador `==`, só conferimos se ambas tem o mesmo valor. Ambas tem o valor de `3`, então retorna `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.` +Contudo, quando usamos o operador `===`, ambos valor e tipo tem de ser o mesmo. E não é: `new Number()` não é um número, é um **objeto**. Ambos retornam `false`.

--- -###### 8. What's the output? +###### 8. Qual é a saída? ```javascript class Chameleon { @@ -268,23 +269,24 @@ freddie.colorChange("orange"); - C: `green` - D: `TypeError` -
Answer +
Resposta

-#### Answer: D +#### Resposta: 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. +A função `colorChange` é estática. Métodos estáticos são designados para viver somente nos construtores em que são criados, e filhos não herdam esses métodos. +Já que `freddie` é filho de `Chameleon`, a função não é herdada, e não está disponível para `freddie`: Um erro `TypeError` é gerado.

--- -###### 9. What's the output? +###### 9. Qual é a saída? ```javascript let greeting; -greetign = {}; // Typo! +greetign = {}; // Erro de digitação! console.log(greetign); ``` @@ -292,21 +294,21 @@ console.log(greetign); - B: `ReferenceError: greetign is not defined` - C: `undefined` -
Answer +
Resposta

-#### Answer: A +#### Resposta: 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). +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). -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. +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.

--- -###### 10. What happens when we do this? +###### 10. O que acontece quando fazemos isso? ```javascript function bark() { @@ -316,26 +318,26 @@ function bark() { bark.animal = "dog"; ``` -- A: Nothing, this is totally fine! -- B: `SyntaxError`. You cannot add properties to a function this way. +- A: Nada, isso é ok! +- B: `SyntaxError`. Não se pode adicionar propriedades em uma função dessa maneira. - C: `undefined` - D: `ReferenceError` -
Answer +
Resposta

-#### Answer: A +#### Resposta: A -This is possible in JavaScript, because functions are objects! (Everything besides primitive types are objects) +Isso é possível em JavaScript, pois funções são objetos! (Tudo menos tipos primitivos são objetos) -A function is a special type of object. The code you write yourself isn't the actual function. The function is an object with properties. This property is invocable. +Uma função é um tipo especial de objeto. O código que você escreve não é a verdadeira função. A função é um objeto com propriedades. E essa propriedade é invocável.

--- -###### 11. What's the output? +###### 11. Qual é a saída? ```javascript function Person(firstName, lastName) { @@ -356,12 +358,14 @@ console.log(member.getFullName()); - C: `Lydia Hallie` - D: `undefined` `undefined` -
Answer +
Resposta

-#### Answer: A +#### Resposta: A + +Você não pode adicionar propriedades para um construtor igual aos objetos normais. Se você quer adicionar uma funcionalidade para todos objetos ao mesmo tempo, você deve usar o prototype. -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, +Então nesse caso ```js Person.prototype.getFullName = function() { @@ -369,14 +373,14 @@ Person.prototype.getFullName = function() { }; ``` -would have made `member.getFullName()` work. Why is this beneficial? Say that we added this method to the constructor itself. Maybe not every `Person` instance needed this method. This would waste a lot of memory space, since they would still have that property, which takes of memory space for each instance. Instead, if we only add it to the prototype, we just have it at one spot in memory, yet they all have access to it! +faria `member.getFullName()` funcionar. Por quê isso é beneficial? Digamos que tivéssemos esse método ao próprio construtor. Talvez nem toda instância de `Person` precisasse desse método. Isso gastaria muita memória, uma vez que cada instância teria esse propriedade e teria seu espaço alocado. Ao invés disso, se adicionarmos somente ao protótipo, alocamos somente um único espaço na memória, e todas instâncias de `Person`ainda tem acesso ao método.

--- -###### 12. What's the output? +###### 12. Qual é a saída? ```javascript function Person(firstName, lastName) { @@ -391,38 +395,38 @@ 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` +- A: `Person {firstName: "Lydia", lastName: "Hallie"}` e `undefined` +- B: `Person {firstName: "Lydia", lastName: "Hallie"}` e `Person {firstName: "Sarah", lastName: "Smith"}` +- C: `Person {firstName: "Lydia", lastName: "Hallie"}` e `{}` +- D:`Person {firstName: "Lydia", lastName: "Hallie"}` e `ReferenceError` -
Answer +
Resposta

-#### Answer: A +#### Resposta: A -For `sarah`, we didn't use the `new` keyword. When using `new`, it refers to the new empty object we create. However, if you don't add `new` it refers to the **global object**! +Na `sarah`, não usamos a palavra-chave `new`. Quando usamos `new`, se refere ao novo objeto vazio que criamos. Contudo, se não usarmos `new`, nos referimos ao **objeto global**! -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`. +Afirmamos que `this.firstName` vale `"Sarah"` e `this.lastName` vale `"Smith"`. O que realmente fizemos foi definir `global.firstName = 'Sarah'` e `global.lastName = 'Smith'`. A `sarah` ainda é `undefined`.

--- -###### 13. What are the three phases of event propagation? +###### 13. Quais são as três fases na propagação de eventos? - A: Target > Capturing > Bubbling - B: Bubbling > Target > Capturing - C: Target > Bubbling > Capturing - D: Capturing > Target > Bubbling -
Answer +
Resposta

-#### Answer: D +#### Resposta: 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. +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. @@ -431,17 +435,17 @@ During the **capturing** phase, the event goes through the ancestor elements dow --- -###### 14. All object have prototypes. +###### 14. Todos objetos tem protótipos. -- A: true -- B: false +- A: Verdadeiro +- B: Falso -

Answer +
Resposta

-#### Answer: B +#### Resposta: B -All objects have prototypes, except for the **base object**. 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. +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.

From 762072e0a73e71352c513496ef1e71bf8d86ecc2 Mon Sep 17 00:00:00 2001 From: Alexander Ivanov Date: Thu, 20 Jun 2019 07:24:47 +0300 Subject: [PATCH 053/915] Add edits --- README_ru-RU.md | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/README_ru-RU.md b/README_ru-RU.md index a4eb0829..690d4bf0 100644 --- a/README_ru-RU.md +++ b/README_ru-RU.md @@ -2,12 +2,16 @@ Я ежедевно публикую вопросы по JavaScript с вариантами ответов в своем [Instagram](https://www.instagram.com/theavocoder), которые дублируются в этом репозитории. -От азов к сложным вопросам: провеь как хорошо ты знаешь JavaScript, освежи свои знания или приготовься к собеседованию! :muscle: :rocket: Я дополняю этот репозиторий каждую неделю новыми вопросами. +От азов к сложным вопросам: проверь, как хорошо ты знаешь JavaScript, освежи свои знания или приготовься к собеседованию! :muscle: :rocket: Я дополняю этот репозиторий каждую неделю новыми вопросами. -Ответы находятся в свернутой секции ниже вопросов. Просто нажми на ответ, чтобы развернуть. Удачи! :heart: +Ответы находятся в свернутой секции ниже вопросов. Просто нажми на "Ответ", чтобы развернуть. Удачи! :heart: -[中文版本](./README-zh_CN.md) +[中文版本](./README-zh_CN.md) [Русский](./README_ru-RU.md) +[Western Balkan](./README-bs.md) +[Deutsch](./README-de_DE.md) +[Tiếng Việt](./README-vi.md) + --- @@ -1212,7 +1216,6 @@ console.log(numbers); `[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]`.

From bdc27a8684193cfe1812c34f45babeff17702060 Mon Sep 17 00:00:00 2001 From: Dima Yavorskiy <33015386+yavorskiydima@users.noreply.github.com> Date: Thu, 20 Jun 2019 09:24:53 +0500 Subject: [PATCH 054/915] ru-syntax-errors --- README_ru-RU.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README_ru-RU.md b/README_ru-RU.md index a4eb0829..a63b6545 100644 --- a/README_ru-RU.md +++ b/README_ru-RU.md @@ -1,8 +1,8 @@ # Список (продвинутых) вопросов по JavaScript -Я ежедевно публикую вопросы по JavaScript с вариантами ответов в своем [Instagram](https://www.instagram.com/theavocoder), которые дублируются в этом репозитории. +Я ежедневно публикую вопросы по JavaScript с вариантами ответов в своем [Instagram](https://www.instagram.com/theavocoder), которые дублируются в этом репозитории. -От азов к сложным вопросам: провеь как хорошо ты знаешь JavaScript, освежи свои знания или приготовься к собеседованию! :muscle: :rocket: Я дополняю этот репозиторий каждую неделю новыми вопросами. +От азов к сложным вопросам: проверь как хорошо ты знаешь JavaScript, освежи свои знания или приготовься к собеседованию! :muscle: :rocket: Я дополняю этот репозиторий каждую неделю новыми вопросами. Ответы находятся в свернутой секции ниже вопросов. Просто нажми на ответ, чтобы развернуть. Удачи! :heart: From c8b5e24b3869f6f000c9270e0f7950b97af795a6 Mon Sep 17 00:00:00 2001 From: Alexander Ivanov Date: Thu, 20 Jun 2019 07:34:21 +0300 Subject: [PATCH 055/915] Fix a typo Signed-off-by: Alexander Ivanov --- README_ru-RU.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README_ru-RU.md b/README_ru-RU.md index 690d4bf0..369e90d7 100644 --- a/README_ru-RU.md +++ b/README_ru-RU.md @@ -1,6 +1,6 @@ # Список (продвинутых) вопросов по JavaScript -Я ежедевно публикую вопросы по JavaScript с вариантами ответов в своем [Instagram](https://www.instagram.com/theavocoder), которые дублируются в этом репозитории. +Я ежедневно публикую вопросы по JavaScript с вариантами ответов в своем [Instagram](https://www.instagram.com/theavocoder), которые дублируются в этом репозитории. От азов к сложным вопросам: проверь, как хорошо ты знаешь JavaScript, освежи свои знания или приготовься к собеседованию! :muscle: :rocket: Я дополняю этот репозиторий каждую неделю новыми вопросами. From 72307bf0cc7beb985c3527aafabdc039081c1520 Mon Sep 17 00:00:00 2001 From: Dima Yavorskiy <33015386+yavorskiydima@users.noreply.github.com> Date: Thu, 20 Jun 2019 09:38:32 +0500 Subject: [PATCH 056/915] typo 2 --- README_ru-RU.md | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/README_ru-RU.md b/README_ru-RU.md index a63b6545..1dc9bafe 100644 --- a/README_ru-RU.md +++ b/README_ru-RU.md @@ -34,7 +34,7 @@ sayHi(); #### Ответ: D -Внутри функции мы сперва определям переменную `name` с помощью ключевого слова `var`. Это означает, что переменная будет поднята (область памяти под переменную будет выделена во время фазы создания) со значением `undefined` по умолчанию, до тех пора пока исполнение кода не дойдет до строчки, где определяется переменная. Мы еще не определили значение `name` когда пытаемся вывести её в консоль, поэтому в консоли будет `undefined`. +Внутри функции мы сперва определяем переменную `name` с помощью ключевого слова `var`. Это означает, что переменная будет поднята (область памяти под переменную будет выделена во время фазы создания) со значением `undefined` по умолчанию, до тех пора пока исполнение кода не дойдет до строчки, где определяется переменная. Мы еще не определили значение `name` когда пытаемся вывести её в консоль, поэтому в консоли будет `undefined`. Переменные, определенные с помощью `let` (и `const`), также поднимаются, но в отличие от `var`, не инициализируются. Доступ к ним не возможен до тех пор, пока не выполнится строка их определения (инициализации). Это называется "временная мертвая зона". Когда мы пытаемся обратиться к переменным до того момента как они определены, JavaScript выбрасывает исключение `ReferenceError`. @@ -232,7 +232,7 @@ console.log(b === c); Оператор `==` разрешает приведение типов, он проверяет равенство _значений_. Оба значения равны `3`, поэтому возвращается `true`. -При использвании оператора `===` значение _и_ тип должны быть одинаковыми. Но в нашем случае это не так: `new Number()` это не число, это **объект**. Оба возвращают `false`. +При использовании оператора `===` значение _и_ тип должны быть одинаковыми. Но в нашем случае это не так: `new Number()` это не число, это **объект**. Оба возвращают `false`.

@@ -426,7 +426,7 @@ console.log(sarah); --- -###### 14. Все объекты имют прототипы +###### 14. Все объекты имеют прототипы - A: Да - B: Нет @@ -1001,7 +1001,7 @@ sayHi.bind(person, 21); #### Ответ: D -В обоих случаях мы мы передаем объект, на который будет указывать `this`. Но `.call` _выполняется сразу же_! +В обоих случаях мы передаем объект, на который будет указывать `this`. Но `.call` _выполняется сразу же_! `.bind` возвращает _копию_ функции, но с привязанным контекстом. Она не выполняется незамедлительно. @@ -1182,7 +1182,7 @@ console.log(numbers); Типы примитивов: `boolean`, `null`, `undefined`, `bigint`, `number`, `string`, и `symbol`. -Отличием примитива от объекта является то, что примитивы не имеют свойств или методов. Тем не менее, `'foo'.toUpperCase()` преобразуется в `'FOO'` и не вызывает `TypeError`. Это происходит потому, что при попытке получения свойства или метода у примитива (например, строки), JavaScript неявно обернет примитив объектом, используя один из классов-оберток (например, `String`), а затем сразу же уничтожет обертку после вычисления выражения. Все примитивы кроме `null` и `undefined` ведут себя таким образом. +Отличием примитива от объекта является то, что примитивы не имеют свойств или методов. Тем не менее, `'foo'.toUpperCase()` преобразуется в `'FOO'` и не вызывает `TypeError`. Это происходит потому, что при попытке получения свойства или метода у примитива (например, строки), JavaScript неявно обернет примитив объектом, используя один из классов-оберток (например, `String`), а затем сразу же уничтожит обертку после вычисления выражения. Все примитивы кроме `null` и `undefined` ведут себя таким образом.

From 75444d84a07f9ddc09259b8965fc5b49cd25ea4b Mon Sep 17 00:00:00 2001 From: Dmitry Yevlakhov Date: Thu, 20 Jun 2019 13:09:28 +0300 Subject: [PATCH 057/915] translated to ukrainian --- README-bs_BS.md | 1 + README-de_DE.md | 3 +- README-ua_UA.md | 1296 +++++++++++++++++++++++++++++++++++++++++++++++ README-vi.md | 3 +- README.md | 1 + README_ru-RU.md | 11 +- 6 files changed, 1308 insertions(+), 7 deletions(-) create mode 100644 README-ua_UA.md diff --git a/README-bs_BS.md b/README-bs_BS.md index 75e47080..8566ce9c 100644 --- a/README-bs_BS.md +++ b/README-bs_BS.md @@ -18,6 +18,7 @@ kliknite na njih da biste ih proširili. Sretno :heart: [Zapadni balkan](./README-bs_BS.md) [Njemački](./README-de_DE.md)
[Vijetnamski](./README-vi.md) +[Українська мова](./README-ua_UA.md) * * * * * diff --git a/README-de_DE.md b/README-de_DE.md index cefffd01..37966ada 100644 --- a/README-de_DE.md +++ b/README-de_DE.md @@ -9,7 +9,8 @@ Die Antworten sind unterhalb der Fragen versteckt. Du kannst einfach auf den Pfe [English](./README.md) [中文版本](./README-zh_CN.md) [Русский](./README_ru-RU.md) -[Western Balkan](./README-bs.md) +[Western Balkan](./README-bs.md) +[Українська мова](./README-ua_UA.md) --- diff --git a/README-ua_UA.md b/README-ua_UA.md new file mode 100644 index 00000000..18f2d4af --- /dev/null +++ b/README-ua_UA.md @@ -0,0 +1,1296 @@ +# Список (просунутих) питань з JavaScript + +Я публікую щодня завдання з JavaScript в моєму [Instagram](https://www.instagram.com/theavocoder), які також додаю тут! + +Від базового до просунутого: перевірте, наскільки добре ви знаєте JavaScript, трохи оновлюйте свої знання або підготуйтеся до інтерв'ю! :muscle: :rocket: Щотижня я доповнюю цей репозиторій новими питаннями. + +Відповіді знаходяться в згорнутої секції нижче питань. Просто натисни на відповідь, щоб розгорнути. Успіхів! :heart: + +[中文版本](./README-zh_CN.md) +[Русский](./README_ru-RU.md) +[Western Balkan](./README-bs.md) +[Deutsch](./README-de_DE.md) +[Tiếng Việt](./README-vi.md) + +--- + +###### 1. Що буде в консолі? + +```javascript +function sayHi() { + console.log(name); + console.log(age); + var name = "Lydia"; + let age = 21; +} + +sayHi(); +``` + +- A: `Lydia` та `undefined` +- B: `Lydia` та `ReferenceError` +- C: `ReferenceError` та `21` +- D: `undefined` та `ReferenceError` + +
Відповідь +

+ +#### Відповідь: D + +Усередині функції ми спершу визначаємо змінну `name` за допомогою ключового слова `var`. Це означає, що змінна буде знайдена (область пам'яті під змінну буде виділена під час створення) зі значенням `undefined` за замовчуванням, до тих пора поки виконання коду не дійде до рядка, де визначається змінна. Ми ще не визначили значення name, коли намагаємося вивести її в консоль, тому в консолі буде `undefined`. + +Змінні, визначені за допомогою `let` (і `const`), також знаходяться, але на відміну від `var`, не створюються. Доступ до них неможливий до тих пір, поки не виконається рядок їх визначення (ініціалізації). Це називається "тимчасова мертва зона". Коли ми намагаємося звернутися до змінних до того моменту як вони визначені, JavaScript видає `ReferenceError`. + +

+
+ +--- + +###### 2. Що буде в консолі? + +```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` та `0 1 2` +- B: `0 1 2` та `3 3 3` +- C: `3 3 3` та `0 1 2` + +
Відповідь +

+ +#### Відповідь: C + +Через черги подій в JavaScript, функція `setTimeout` викликається _після того_ як цикл буде завершено. Так як змінна `i` в першому циклі була визначена за допомогою `var`, вона буде глобальною. У циклі ми кожен раз збільшуємо значення `i` на `1`, використовуючи унарний оператор `++.` До моменту виконання функції `setTimeout` значення `i` дорівнюватиме `3`, як показано в першому прикладі. + +У другому циклі змінна `i` визначена за допомогою `let`. Такі змінні (а також `const`) мають блочну область видимості (блок це що завгодно між `{}`). З кожної итерацией `i` матиме нове значення, і кожне значення буде замкнуто в своїй області видимості всередині циклу. + +

+
+ +--- + +###### 3. Що буде в консолі? + +```javascript +const shape = { + radius: 10, + diameter() { + return this.radius * 2; + }, + perimeter: () => 2 * Math.PI * this.radius +}; + +shape.diameter(); +shape.perimeter(); +``` + +- A: `20` та `62.83185307179586` +- B: `20` та `NaN` +- C: `20` та `63` +- D: `NaN` та `63` + +
Відповідь +

+ +#### Відповідь: B + +Зауваж, що `diameter` це звичайна функція, в той час як `perimeter` це функція стрілки. + +У стрілочних функцій значення `this` вказує на навколишню область видимості, на відміну від звичайних функцій! Це означає, що при виклику `perimeter` значення `this` у цій функції вказує не на об'єкт `shape`, а на зовнішню область видимості (наприклад, window). + +У цього об'єкта немає ключа `radius`, тому повертається `undefined`. + +

+
+ +--- + +###### 4. Що буде в консолі? + +```javascript ++true; +!"Lydia"; +``` + +- A: `1` та `false` +- B: `false` та `NaN` +- C: `false` та `false` + +
Відповідь +

+ +#### Відповідь: A + +Унарний плюс призводить операнд до числа. `true` це `1`, а `false` це `0`. + +Строка `'Lydia'` це "справжнє" значення. Ми запитуємо "справжнє значення є помилковим"? Відповідь: `false`. + +

+
+ +--- + +###### 5. Що з цього не є коректним? + +```javascript +const bird = { + size: "small" +}; + +const mouse = { + name: "Mickey", + small: true +}; +``` + +- A: `mouse.bird.size` не є коректно +- B: `mouse[bird.size]` не є коректно +- C: `mouse[bird["size"]]` не є коректно +- D: Все варіант коректні + +
Відповідь +

+ +#### Відповідь: A + +В JavaScript все ключі об'єкта є рядками (крім `Symbol`). І хоча ми не _набираємо_ їх як рядки, вони завжди перетворюються до рядків під капотом. + +JavaScript інтерпретує (або розпаковує) оператори. При використанні квадратних дужок JS зауважує `[` і продовжує поки не зустріне `]`. Тільки після цього він вирахує то, що знаходиться всередині дужок. + +`mouse[bird.size]`: Спершу визначається `bird.size`, що дорівнює `"small"`. `mouse["small"]` повертає `true`. + +Але із записом через точку так не відбувається. У `mouse` немає ключа `bird`. Таким чином, `mouse.bird` дорівнює `undefined`. Потім ми запитуємо ключ `size`, використовуючи точкову нотацію: `mouse.bird.size`. Так як `mouse.bird` це `undefined`, ми запитуємо `undefined.size`. Це не є дійсним, і ми отримуємо помилку типу: `Can not read property "size" of undefined`. + +

+
+ +--- + +--- + +###### 6. Що буде в консолі? + +```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` + +
Відповідь +

+ +#### Відповідь: A + +В JavaScript всі об'єкти є _посилальними_ типами даних. + +Спершу змінна `c` вказує на об'єкт. Потім ми вказуємо змінної `d` посилатися на той самий об'єкт, що і `c`. + + + +Коли ти змінюєш один об'єкт, то змінюються значення всіх посилань, що вказують на цей об'єкт. + +

+
+ +--- + +###### 7. Що буде в консолі? + +```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` + +
Відповідь +

+ +#### Відповідь: C + +`new Number()` це вбудований конструктор функції. І хоча він виглядає як число, це не справжнє число: у нього є ряд додаткових фіч і це об'єкт. + +Оператор `==` призводить типи даних до якогось одного і перевіряє рівність _значень_. Обидва значення рівні `3`, тому повертається `true`. + +При використанні оператора `===` значення і тип повинні бути однаковими. Але в нашому випадку це не так: `new Number()` це не число, це **об'єкт**. Тому обидва повертають `false`. + +

+
+ +--- + +###### 8. Яким буде результат? + +```javascript +class Chameleon { + 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` + +
Відповідь +

+ +#### Відповідь: D + +Функція `colorChange` є статичною. Статичні методи не мають доступу до екземплярів класу. Так як `freddie` це екземпляр, то статичний метод там не доступний. Тому результатом є помилка `TypeError`. + +

+
+ +--- + +###### 9. Що буде в консолі? + +```javascript +let greeting; +greetign = {}; // Typo! +console.log(greetign); +``` + +- A: `{}` +- B: `ReferenceError: greetign is not defined` +- C: `undefined` + +
Відповідь +

+ +#### Відповідь: A + +В консолі виведеться об'єкт, тому що ми тільки що створили порожній об'єкт в глобальному об'єкті! Коли ми замість `greeting` написали `greetign`, інтерпретатор JS насправді виконав `global.greetign = {}` (або `window.greetign = {}` в браузері). + +Потрібно використовувати `"use strict"`, щоб уникнути такої поведінки. Ця запис допоможе бути впевненим в тому, що змінна була визначена перед тим як їй присвоїли значення. + +

+
+ +--- + +###### 10. Що станеться? + +```javascript +function bark() { + console.log("Woof!"); +} + +bark.animal = "dog"; +``` + +- A: Нічого, все ок. +- B: `SyntaxError`. Не можна додавати властивості функцій таким способом. +- C: `undefined` +- D: `ReferenceError` + +
Відповідь +

+ +#### Відповідь: A + +В JavaScript це можливо, тому що функції це об'єкти! (Все є об'єктами крім примітивів). + +Функція - це спеціальний тип об'єкта, який можна викликати. Крім того, функція - це об'єкт з властивостями. Властивість такого об'єкта не можна викликати, так як воно не є функцією. + +

+
+ +--- + +###### 11. Що буде в консолі? + +```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` + +
Відповідь +

+ +#### Відповідь: A + +Не можна додавати властивості конструктору, як звичайному об'єкту. Якщо потрібно додати фичу всіх об'єктах, то необхідно використовувати прототипи. В даному випадку, + +```js +Person.prototype.getFullName = function() { + return `${this.firstName} ${this.lastName}`; +}; +``` + +зробить метод `member.getFullName()` чинним. У чому тут перевага? Припустимо, що ми додали цей метод до конструктора. Можливо, не кожному екземпляру `Person` потрібен цей метод. Це призведе до великих втрат пам'яті, тому що всі екземпляри будуть мати цю властивість. Навпаки, якщо ми додамо цей метод тільки до прототипу, у нас буде тільки одне місце в пам'яті, до якого зможуть звертатися всі екземпляри! + +

+
+ +--- + +###### 12. Що буде в консолі? + +```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"}` та `undefined` +- B: `Person {firstName: "Lydia", lastName: "Hallie"}` та `Person {firstName: "Sarah", lastName: "Smith"}` +- C: `Person {firstName: "Lydia", lastName: "Hallie"}` та `{}` +- D:`Person {firstName: "Lydia", lastName: "Hallie"}` та `ReferenceError` + +
Відповідь +

+ +#### Відповідь: A + +Для `sarah` ми не використали ключове слово `new`. Використання `new` призводить до створення нового об'єкта. Але без `new` він вказує на **глобальний об'єкт**! + +Ми вказали, що `this.firstName` дорівнює `"Sarah"` і `this.lastName` дорівнює `"Smith"`. Насправді ми визначили `global.firstName = 'Sarah'` і `global.lastName = 'Smith'`. `sarah` залишилася `undefined`. + +

+
+ +--- + +###### 13. Назвіть три фази поширення подій + +- A: Мета (Target) > Захоплення (Capturing) > Всплиття (Bubbling) +- B: Всплиття (Bubbling) > Мета (Target) > Захоплення (Capturing) +- C: Мета (Target) > Всплиття (Bubbling) > Захоплення (Capturing) +- D: Захоплення (Capturing) > Мета (Target) > Всплиття (Bubbling) + +
Відповідь +

+ +#### Відповідь: D + +Під час фази **захоплення** подія поширюється з елементів батьків до елемента мети. Після досягнення **мети** починається фаза **спливання**. + + + +

+
+ +--- + +###### 14. Все объекты имеют прототипы? + +- A: Так +- B: Ні + +
Відповідь +

+ +#### Відповідь: B + +Всі об'єкти мають прототипи, крім **базового об'єкта**. Базовий об'єкт має доступ до деяких методів і властивостей, таких як `.toString`. Саме тому ми можемо використовувати вбудовані методи JavaScript! Всі ці методи доступні в прототипі. Якщо JavaScript не може знайти метод безпосередньо у об'єкту, він продовжує пошук по ланцюжку прототипів поки не знайде. + +

+
+ +--- + +###### 15. Результат коду? + +```javascript +function sum(a, b) { + return a + b; +} + +sum(1, "2"); +``` + +- A: `NaN` +- B: `TypeError` +- C: `"12"` +- D: `3` + +
Відповідь +

+ +#### Відповідь: C + +JavaScript це **динамічно тіпізірованна мова**: ми не визначаємо тип змінних. Змінні можуть автоматично бути перетворені з одного типу в інший без нашої участі, що називається _неявним приведенням типів_. **Приведення** це перетворення з одного типу в інший. + +У цьому прикладі, JavaScript конвертувати число `1` в рядок, щоб операція усередині функції мала сенс і повернула значення. Під час складання числа (`1`) і рядки (`'2'`) число перетворюється до рядка. Ми можемо конкатеніровать рядки ось так: `"Hello" + "World"`. Таким чином, "`1"` + `"2"` повертає "`12"`. + +

+
+ +--- + +###### 16. Що буде в консолі? + +```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` + +
Відповідь +

+ +#### Відповідь: C + +**Постфіксний** унарний оператор `++`: + +1. Повертає значення (`0`) +2. Інкрементує значення (тепер число дорівнює `1`) + +**Префіксний** унарний оператор `++`: + +1. Інкрементує значення (тепер число дорівнює `1`) +2. Повертає значення (`0`) + +Результат: `0 2 2`. + +

+
+ +--- + +###### 17. Що буде в консолі? + +```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` + +
Відповідь +

+ +#### Відповідь: B + +При використанні тегованих шаблонних литералов першим аргументом завжди буде масив строкових значень. Залишилися аргументами будуть значення переданих виразів! + +

+
+ +--- + +###### 18. Що буде в консолі? + +```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` + +
Відповідь +

+ +#### Відповідь: C + +В операціях порівняння примітиви порівнюються за їх _значенням_, а об'єкти по _посиланнях_. JavaScript перевіряє, щоб об'єкти вказували на одну і ту ж область пам'яті. + +Порівнянні об'єкти в нашому прикладі не такі: об'єкт, переданий як параметр, вказує на іншу область пам'яті, ніж об'єкти, що використовуються в порівняннях. + +Тому `{age: 18} === {age: 18}` і `{age: 18} == {age: 18}` повертають `false`. + +

+
+ +--- + +###### 19. Що буде в консолі? + +```javascript +function getAge(...args) { + console.log(typeof args); +} + +getAge(21); +``` + +- A: `"number"` +- B: `"array"` +- C: `"object"` +- D: `"NaN"` + +
Відповідь +

+ +#### Відповідь: C + +Оператор поширення (`... args`) повертає масив з аргументами. Масив це об'єкт, тому `typeof args` повертає `"object"`. + +

+
+ +--- + +###### 20. Що буде в консолі? + +```javascript +function getAge() { + "use strict"; + age = 21; + console.log(age); +} + +getAge(); +``` + +- A: `21` +- B: `undefined` +- C: `ReferenceError` +- D: `TypeError` + +
Відповідь +

+ +#### Відповідь: C + +Використовуючи `"use strict"`, можна бути впевненим, що ми помилково не оголосимо глобальні змінні. Ми раніше ніде не оголошували змінну `age`, тому з використанням `"use strict"` виникне ReferenceError. Без використання `"use strict"` помилки не виникне, а змінна `age` додасться в глобальний об'єкт. + +

+
+ +--- + +###### 21. Чому дорівнюватиме sum? + +```javascript +const sum = eval("10*10+5"); +``` + +- A: `105` +- B: `"105"` +- C: `TypeError` +- D: `"10*10+5"` + +
Відповідь +

+ +#### Відповідь: A + +`eval` виконує код, переданий у вигляді рядка. Якщо цей вислів (як в даному випадку), то обчислюється вираз. Вираз `10 * 10 + 5` поверне число `105`. + +

+
+ +--- + +###### 22. Як довго буде доступний cool_secret? + +```javascript +sessionStorage.setItem("cool_secret", 123); +``` + +- A: Завжди, дані не загубляться. +- B: Поки користувач не закриває вкладку. +- C: Поки користувач не закриє браузер, а не тільки вкладку. +- D: Поки користувач не вимикає комп'ютер. + +
Відповідь +

+ +#### Відповідь: B + +Дані, збережені в `sessionStorage` очищаються після закриття _вкладки_. + +При використанні `localStorage` дані зберігаються назавжди. Очистити їх можна, наприклад, використовуючи `localStorage.clear()`. + +

+
+ +--- + +###### 23. Що буде в консолі? + +```javascript +var num = 8; +var num = 10; + +console.log(num); +``` + +- A: `8` +- B: `10` +- C: `SyntaxError` +- D: `ReferenceError` + +
Відповідь +

+ +#### Відповідь: B + +За допомогою ключового слова `var`, можна визначати скільки завгодно змінних з одним і тим же ім'ям. Змінна зберігатиме останнім присвоєне значення. + +Ви не можете зробити це з `let` або` const`, оскільки вони блочні. + +

+
+ +--- + +###### 24. Що буде в консолі? + +```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` + +
Відповідь +

+ +#### Відповідь: C + +Всі ключі об'єктів (крім `Symbols`) є рядками, навіть якщо задано не в вигляді рядків. Тому `obj.hasOwnProperty('1')` так само повертає `true`. + +Але це не працює для `set`. Значення `"1"` немає в `set`: `set.has ('1')`, тому повертається `false`. Але `set.has(1)` поверне `true`. + +

+
+ +--- + +###### 25. Що буде в консолі? + +```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` + +
Відповідь +

+ +#### Відповідь: C + +Якщо є два ключі з однаковим ім'ям, то ключ буде перезаписан. Його позиція збережеться, але значенням буде встановлено останнім. + +

+
+ +--- + +###### 26. Глобальний контекст виконання створює дві речі: глобальний об'єкт і this + +- A: Так +- B: Ні +- C: В залежності від ситуації + +
Відповідь +

+ +#### Відповідь: A + +Базовий контекст виконання це глобальний контекст виконання: це те, що є де завгодно в твоєму коді. + +

+
+ +--- + +###### 27. Що буде в консолі? + +```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` + +
Відповідь +

+ +#### Відповідь: C + +Оператор `continue` пропускає ітерацію, якщо умова повертає `true`. + +

+
+ +--- + +###### 28. Яким буде результат? + +```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` + +
Відповідь +

+ +#### Відповідь: A + +`String` це вбудований конструктор, до якого можна додавати властивості. Я додала метод до його прототипу. Рядки-примітиви автоматично конвертуються до рядків-об'єктів. Тому всі рядки (строкові об'єкти) мають доступ до цього методу! + +

+
+ +--- + +###### 29. Що буде в консолі? + +```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` + +
Відповідь +

+ +#### Відповідь: B + +Ключі об'єкта автоматично конвертуються в рядки. Ми збираємося додати об'єкт в якості ключа до об'єкта `a` зі значенням `123`. + +Проте, коли ми наводимо об'єкт до рядка, він стає `"[object Object]"`. Таким чином, ми говоримо, що `a["Object object"] = 123`. Потім ми робимо те ж саме. `c` це інший об'єкт, який ми неявно наводимо до рядка. Тому `a["Object object"] = 456`. + +Потім, коли ми виводимо `a[b]`, ми маємо на увазі `a["Object object"]`. Ми тільки що встановили туди значення `456`, тому в результаті отримуємо `456`. + +

+
+ +--- + +###### 30. Яким буде результат? + +```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` + +
Відповідь +

+ +#### Відповідь: B + +Ми викликаємо функцію `setTimeout` першої. Тим не менш, вона виводиться в консоль останньої + +Це відбувається через те, що в браузерах у нас є не тільки рантайм движок, але і `WebAPI`. `WebAPI` надає нам функцію `setTimeout` і багато інших можливостей. Наприклад, DOM. + +Після того як _коллбек_ відправлений в `WebAPI`, функція `setTimeout` (але не коллбек!) виймається з стека. + + + +Тепер викликається `foo`, і `"First"` виводиться в консоль. + + + +`foo` дістається з стека, і викликається `baz`. `"Third"` виводиться в консоль. + + + +`WebAPI` не може додавати вміст в стек коли захоче. Замість цього він відправляє коллбек-функцію в так звану _чергу_. + + + +Тут на сцену виходить цикл подій (event loop). **Event loop** перевіряє стек і черга завдань. Якщо стек порожній, то він бере перший елемент з черги і відправляє його в стек. + + + +Викликається `bar`, в консоль виводиться `"Second"` і ця функція дістається з стека. + +

+
+ +--- + +###### 31. Що буде в `event.target` після кліка на кнопку? + +```html +
+
+ +
+
+``` + +- A: Зовнішній `div` +- B: Внутрішній `div` +- C: `button` +- D: Масив з усіма вкладеними елементами + +
Відповідь +

+ +#### Відповідь: C + +Метою події є **найглибший** вкладений елемент. Зупинити поширення подій можна за допомогою `event.stopPropagation` + +

+
+ +--- + +###### 32. Що буде в консолі після кліка по параграфу? + +```html +
+

+ Click here! +

+
+``` + +- A: `p` `div` +- B: `div` `p` +- C: `p` +- D: `div` + +
Відповідь +

+ +#### Відповідь: A + +Після кліка по `p` буде виведено `p` та `div`. У циклі життя події є три фази: **захоплення**, **мета** і **спливання**. За замовчуванням обробники подій виконуються на фазі спливання (якщо не встановлено параметр `useCapture` в `true`). Спливання йде з найглибшого елемента вгору. + +

+
+ +--- + +###### 33. Що буде в консолі? + +```javascript +const person = { name: "Lydia" }; + +function sayHi(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` + +
Відповідь +

+ +#### Відповідь: D + +В обох випадках ми передаємо об'єкт, на який буде вказувати `this`. Але `.call` виконується _відразу ж_! + +`.bind` повертає _копію_ функції, але з прив'язаним контекстом. Вона не виконується негайно. + +

+
+ +--- + +###### 34. Яким буде результат? + +```javascript +function sayHi() { + return (() => 0)(); +} + +typeof sayHi(); +``` + +- A: `"object"` +- B: `"number"` +- C: `"function"` +- D: `"undefined"` + +
Відповідь +

+ +#### Відповідь: B + +Функція `sayHi` повертає значення, що повертається з _негайно викликаного функціонального вираза_ (IIFE). Результатом є `0` типу `"number"`. + +Для інформації: в JS 7 вбудованих типів: `null`, `undefined`, `boolean`, `number`, `string`, `object`, та `symbol`. `"Function"` не є окремим типом, тому що функції є об'єктами типу `"object"`. + +

+
+ +--- + +###### 35. Які з цих значень є "помилковими"? + +```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: Всі значення. + +
Відповідь +

+ +#### Відповідь: A + +Є тільки шість "помилкових" значень: + +- `undefined` +- `null` +- `NaN` +- `0` +- `''` (порожній рядок) +- `false` + +Конструктори функцій, такі як new `Number` та `new Boolean` є "істинними". + +

+
+ +--- + +###### 36. Що буде в консолі? + +```javascript +console.log(typeof typeof 1); +``` + +- A: `"number"` +- B: `"string"` +- C: `"object"` +- D: `"undefined"` + +
Відповідь +

+ +#### Відповідь: B + +`typeof 1` повертає `"number"`. +`typeof "number"` повертає `"string"` + +

+
+ +--- + +###### 37. Що буде в консолі? + +```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` + +
Відповідь +

+ +#### Відповідь: C + +Коли в масив додається значення, яке виходить за межі довжини масиву, JavaScript створює так звані "порожні клітинки". Насправді вони мають значення `undefined`, але в консолі виводяться так: + +`[1, 2, 3, 7 x empty, 11]` + +в залежності від місця використання (може відрізнятися для браузерів, Node, і т.д.). + +

+
+ +--- + +###### 38. Що буде в консолі? + +```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` + +
Відповідь +

+ +#### Відповідь: A + +Блок `catch` отримує аргумент `x`. Це не той же `x`, який визначено в якості змінної перед рядком `try`. + +Потім ми присвоюємо цього аргументу значення `1` та встановлюємо значення для змінної `y`. Потім виводимо в консоль значення аргументу `x`, що дорівнює `1`. + +За межами блоку `catch` змінна `x` все ще `undefined`, а `y` дорівнює `2`. Коли ми викликаємо` console.log(x)` за межами блоку `catch`, цей виклик повертає `undefined`, а `y` повертає `2`. + +

+
+ +--- + +###### 39. Все в JavaScript це... + +- A: примітив або об'єкт +- B: функція або об'єкт +- C: питання з підступом! тільки об'єкти +- D: число або об'єкт + +
Відповідь +

+ +#### Відповідь: A + +В JavaScript є тільки примітиви і об'єкти. + +Типи примітивів: `boolean`, `null`, `undefined`, `bigint`, `number`, `string`, та `symbol`. + +Відмінністю примітиву від об'єкта є те, що примітиви не мають властивостей або методів. Проте, `'foo'.toUpperCase()` перетворюється в `'FOO'` та не викликає `TypeError`. Це відбувається тому, що при спробі отримання властивості або методу у примітиву (наприклад, рядки), JavaScript неявно оберне примітив об'єктом, використовуючи один з класів-обгорток (наприклад, `String`), а потім відразу ж знищить обгортку після обчислення виразу. Всі примітиви крім `null` та `undefined` поводяться таким чином. + +

+
+ +--- + +###### 40. Що буде в консолі? + +```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]` + +
Відповідь +

+ +#### Відповідь: 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]`. + +

+
+ +--- + +###### 41. Що буде в консолі? + +```javascript +!!null; +!!""; +!!1; +``` + +- A: `false` `true` `false` +- B: `false` `false` `true` +- C: `false` `true` `true` +- D: `true` `true` `false` + +
Відповідь +

+ +#### Відповідь: B + +`null` "НЕправдивий". `!null` повертає `true`. `!true` повертає `false`. + +`""` "НЕправдивий". `!""` повертає `true`. `!true` повертає `false`. + +`1` "правдивий". `!1` повертає `false`. `!false` повертає `true`. + +

+
+ +--- + +###### 42. Що повертає метод `setInterval`? + +```javascript +setInterval(() => console.log("Hi"), 1000); +``` + +- A: унікальний id +- B: вказану кількість мілісекунд +- C: передану функцію +- D: `undefined` + +
Відповідь +

+ +#### Відповідь: A + +Це метод повертає унікальний id. Цей id може бути використаний для очищення інтервалу за допомогою функції `clearInterval()`. + +

+
+ +--- + +###### 43. What does this return? + +```javascript +[..."Lydia"]; +``` + +- A: `["L", "y", "d", "i", "a"]` +- B: `["Lydia"]` +- C: `[[], "Lydia"]` +- D: `[["L", "y", "d", "i", "a"]]` + +
Відповідь +

+ +#### Відповідь: A + +Рядок є ітеріруемой сутністю. Оператор поширення перетворює кожен символ в окремий елемент. + +

+
diff --git a/README-vi.md b/README-vi.md index b9b7c3be..69bb004d 100644 --- a/README-vi.md +++ b/README-vi.md @@ -6,7 +6,8 @@ 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: -[English Version](./README.md) +[English Version](./README.md) +[Українська мова](./README-ua_UA.md) --- diff --git a/README.md b/README.md index 916fa133..8d31ae8d 100644 --- a/README.md +++ b/README.md @@ -11,6 +11,7 @@ The answers are in the collapsed sections below the questions, simply click on t [Western Balkan](./README-bs_BS.md) [Deutsch](./README-de_DE.md) [Tiếng Việt](./README-vi.md) +[Українська мова](./README-ua_UA.md) --- diff --git a/README_ru-RU.md b/README_ru-RU.md index b8e918df..34ab16a5 100644 --- a/README_ru-RU.md +++ b/README_ru-RU.md @@ -6,11 +6,12 @@ Ответы находятся в свернутой секции ниже вопросов. Просто нажми на "Ответ", чтобы развернуть. Удачи! :heart: -[中文版本](./README-zh_CN.md) -[Русский](./README_ru-RU.md) -[Western Balkan](./README-bs.md) -[Deutsch](./README-de_DE.md) -[Tiếng Việt](./README-vi.md) +[中文版本](./README-zh_CN.md) +[Русский](./README_ru-RU.md) +[Western Balkan](./README-bs.md) +[Deutsch](./README-de_DE.md) +[Tiếng Việt](./README-vi.md) +[Українська мова](./README-ua_UA.md) --- From 2551a7da286424e983bec43eaabf467554c62444 Mon Sep 17 00:00:00 2001 From: Antoine Nozeret Date: Thu, 20 Jun 2019 12:10:21 +0200 Subject: [PATCH 058/915] feat(question-8): Add console.log to make the answer less obvious --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 916fa133..68533ba3 100644 --- a/README.md +++ b/README.md @@ -259,7 +259,7 @@ class Chameleon { } const freddie = new Chameleon({ newColor: "purple" }); -freddie.colorChange("orange"); +console.log(freddie.colorChange("orange")); ``` - A: `orange` From 1ca20d0c1a4a67fae2bf0e507dffe5850cdba4e5 Mon Sep 17 00:00:00 2001 From: 0xflotus <0xflotus@gmail.com> Date: Thu, 20 Jun 2019 15:16:29 +0200 Subject: [PATCH 059/915] Update README-de_DE.md --- README-de_DE.md | 24 ++++++++++++------------ 1 file changed, 12 insertions(+), 12 deletions(-) diff --git a/README-de_DE.md b/README-de_DE.md index cefffd01..39f25be5 100644 --- a/README-de_DE.md +++ b/README-de_DE.md @@ -36,9 +36,9 @@ sayHi() #### Antwort: D -Innerhalb der Funktion wird zuerst der `name` mit dem `var` Keyword gesetzt. Das bedeuted, dass die Variable mit dem Standardwert `undefined` gehoisted wird (Speicherplatz wird während der Erstellung bereitgestellt), bis zu der Zeile, wo wir die Variable definieren. Da wir die Variable auf der Zeile, wo wir den `name` loggen noch nicht gesetzt haben, ist dieser noch `undefined`. +Innerhalb der Funktion wird zuerst der `name` mit dem `var` Keyword gesetzt. Das bedeutet, dass die Variable mit dem Standardwert `undefined` gehoisted wird (Speicherplatz wird während der Erstellung bereitgestellt), bis zu der Zeile, wo wir die Variable definieren. Da wir die Variable auf der Zeile, wo wir den `name` loggen noch nicht gesetzt haben, ist dieser noch `undefined`. -Variablen mit dem `let` (oder `const`) Keyword werden ebenfalls gehoisted, aber im Gegensatz zu `var` werden diese nicht initialisiert. Auf sie können wir daher nicht zugreifen, bevor sie definiert worden sind. JavaScript wirft einen `ReferenceError` aus. +Variablen mit dem `let` (oder `const`) Keyword werden ebenfalls gehoisted, aber im Gegensatz zu `var` werden diese nicht initialisiert. Auf sie können wir daher nicht zugreifen, bevor sie definiert worden sind. JavaScript wirft einen `ReferenceError`.

@@ -66,7 +66,7 @@ for (let i = 0; i < 3; i++) { #### Antwort: C -Aufgrund der Event Queue in JavaScript, wird die callback function in `setTimeout` _nach_ der Schleife ausgeführt. Da die Variable `i` in der ersten Schleife mit dem `var` Keyword definiert wurde, ist dieser Wert global verfügbar. Während der Schleife wird der Wert von `i` jedesmal mithilfe des `++` Operators um `1` erhöht. Zu dem Zeitpunkt, wenn die callback function in `setTimeout` aufgerufen wird, ist `i` gleich `3` im ersten Beispiel. +Aufgrund der Event Queue in JavaScript, wird die Callback Funktion in `setTimeout` _nach_ der Schleife ausgeführt. Da die Variable `i` in der ersten Schleife mit dem `var` Keyword definiert wurde, ist dieser Wert global verfügbar. Während der Schleife wird der Wert von `i` jedesmal mithilfe des `++` Operators um `1` erhöht. Zu dem Zeitpunkt, wenn die Callback Funktion in `setTimeout` aufgerufen wird, ist `i` gleich `3` im ersten Beispiel. In der zweiten Schleife wurde die Variable `i` mit dem `let` Keyword definiert: Variablen, die mit `let` (oder `const`) deklariert werden sind block-scoped (Ein Block ist alles zwischen `{ }`). Während jedem Durchlauf bekommt `i` einen neuen Wert zugewiesen, der jeweils innerhalb des Scopes der Schleife liegt. @@ -233,7 +233,7 @@ console.log(b === c) `new Number()` ist ein eingebauter Function Constructor. Auch wenn der Wert wie eine Nummer aussieht, ist es in Wirklichkeit keine Nummer, sondern beinhaltet eine Menge zusätzlicher Werte und ist daher ein Object. -Wenn wir `==` nutzen wird nur geprüft, ob der _Wert_ gleich ist. Da beide den Wert `3` haben wird `true` zurückgegeben. +Wenn wir `==` nutzen wird nur geprüft, ob der _Wert_ gleich ist. Da beide den Wert `3` haben, wird `true` zurückgegeben. Wenn wir aber `===` nutzen müssen sowohl der Wert _als auch_ der Typ übereinstimmen. Das ist `false`, da `new Number()` keine Nummer, sondern ein **Object** ist. @@ -366,7 +366,7 @@ Person.prototype.getFullName = function() { } ``` -So hätte `member.getFullName()` funktioniert. Warum ist das von Vorteil? Sagen wir, wir hätten diese Methode dem Constructor selbst zugewiesen, aber vielleicht benötigt nicht jede Instanz von `Person` diese Methode. So hätte das eine Menge Arbeitsspeicher verschwendet, weil jede Instanz die Property zugewiesen bekommt, auch wenn sie diese garnicht benötigt. +So hätte `member.getFullName()` funktioniert. Warum ist das von Vorteil? Sagen wir, wir hätten diese Methode dem Constructor selbst zugewiesen, aber vielleicht benötigt nicht jede Instanz von `Person` diese Methode. So hätte das eine Menge Arbeitsspeicher verschwendet, weil jede Instanz die Property zugewiesen bekommt, auch wenn sie diese gar nicht benötigt. Stattdessen haben wir sie nur dem Prototype zugewiesen, sodass sie nur an einer Stelle im Arbeitsspeicher hinterlegt ist, aber dennoch haben alle Instanzen Zugriff darauf.

@@ -389,10 +389,10 @@ 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` +- 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

@@ -401,7 +401,7 @@ console.log(sarah) Für `sarah` haben wir nicht das `new` Keyword verwendet. Wenn wir `new` verwenden, bezieht sich das auf das neue, leere Object, welches wir erstellen. Wenn wir allerdings das `new` Keyword nicht verwenden, bezieht es sich auf das **globale Objekt**. -Wir haben `this.firstName` den Wert `"Sarah"` zugewiesen und `this.lastName` den Wert `"Smith"`. Was wir damit eigentlich zugewiesen haben ist `global.firstName = 'Sarah'` und `global.lastName = 'Smith'`. `sarah` selbst ist daher `undefined`. +Wir haben `this.firstName` den Wert `"Sarah"` zugewiesen und `this.lastName` den Wert `"Smith"`. Was wir damit eigentlich zugewiesen haben, ist `global.firstName = 'Sarah'` und `global.lastName = 'Smith'`. `sarah` selbst ist daher `undefined`.

@@ -420,7 +420,7 @@ Wir haben `this.firstName` den Wert `"Sarah"` zugewiesen und `this.lastName` den #### Antwort: D -Während der **capturing** Phase geht das Event durch die Elternelemente bis hin zum Zielelement. Wenn dann das Ziel (**target**) erreicht ist beginnt die **bubbling** Phase. +Während der **capturing** Phase geht das Event durch die Elternelemente bis hin zum Zielelement. Wenn dann das Ziel (**target**) erreicht ist, beginnt die **bubbling** Phase. @@ -468,7 +468,7 @@ sum(1, "2") JavaScript ist eine **Sprache mit dynamischen Typen**, was bedeutet, dass wir Variablen keine spezifischen Typen zuweisen. Werte können automatisch in einen anderen Typ umgewandelt werden, was _implicit type coercion_ genannt wird. **Coercion** (dt. "Zwang") ist die Umwandlung von einem Typ zu einem anderen. -In diesem Beispiel wandelt JavaScript die Nummer `1` in einem String um, sodass die Funktion Sinn ergibt und einen Wert zurück werfen kann. Während der Addition eines numerischen Types (`1`) mit einem String (`'2'`) wird die Nummer wie ein String behandelt. Wir können Strings mit einem Plus Symbol zusammensetzen, zum Beispiel: `"Hello" + "World"`. Genau das passiert hier, sodass `"1" + "2"` einen Wert von `"12"` zurück wirft. +In diesem Beispiel wandelt JavaScript die Nummer `1` in einem String um, sodass die Funktion Sinn ergibt und einen Wert zurückgeben kann. Während der Addition eines numerischen Types (`1`) mit einem String (`'2'`) wird die Nummer wie ein String behandelt. Wir können Strings mit einem Plus Symbol zusammensetzen, zum Beispiel: `"Hello" + "World"`. Genau das passiert hier, sodass `"1" + "2"` einen Wert von `"12"` zurückgibt.

From 82aa62d22f4f350316aeb883d7d74c47260d2e2d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Adri=C3=A1n?= <22575055+aguadotzn@users.noreply.github.com> Date: Thu, 20 Jun 2019 16:34:22 +0200 Subject: [PATCH 060/915] Questions 20-30 --- README-ES.md | 114 +++++++++++++++++++++++++-------------------------- 1 file changed, 57 insertions(+), 57 deletions(-) diff --git a/README-ES.md b/README-ES.md index e9cb0a1b..96b2c57c 100644 --- a/README-ES.md +++ b/README-ES.md @@ -631,7 +631,7 @@ Con `"use strict"`, es posible asegurarse de que no se declara accidentalmente v --- -###### 21. What's value of `sum`? +###### 21. ¿Cuál es el valor de `sum`? ```javascript const sum = eval("10*10+5"); @@ -642,44 +642,44 @@ const sum = eval("10*10+5"); - C: `TypeError` - D: `"10*10+5"` -
Answer +
Solución

-#### Answer: A +#### Respuesta correcta: 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` evalúa los códigos que se pasan como una cadena. Si es una expresión, como en este caso, evalúa la expresión. La expresión es `10 * 10 + 5`. Esto devuelve el número `105`.

--- -###### 22. How long is cool_secret accessible? +###### 22. ¿Cuánto tiempo es accesible cool_secret? ```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. +- A: Para siempre, los datos no se pierden. +- B: Cuando el usuario cierra la pestaña. +- C: Cuando el usuario cierra todo el navegador, no sólo la pestaña. +- D: Cuando el usuario apaga su ordenador. -
Answer +
Solución

-#### Answer: B +#### Respuesta correcta: B -The data stored in `sessionStorage` is removed after closing the _tab_. +Los datos almacenados en `sessionStorage` se eliminan después de cerrar la pestaña. -If you used `localStorage`, the data would've been there forever, unless for example `localStorage.clear()` is invoked. +Si se usó `localStorage`, los datos habrían estado allí siempre, a menos que por ejemplo `localStorage.clear()` sea invocado.

--- -###### 23. What's the output? +###### 23. ¿Qué devuelve la siguiente función? ```javascript var num = 8; @@ -693,21 +693,21 @@ console.log(num); - C: `SyntaxError` - D: `ReferenceError` -
Answer +
Solución

-#### Answer: B +#### Respuesta correcta: B -With the `var` keyword, you can declare multiple variables with the same name. The variable will then hold the latest value. +Con la palabra reservada `var`, se pueden declarar múltiples variables con el mismo nombre. La variable tendrá entonces el último valor. -You cannot do this with `let` or `const` since they're block-scoped. +No es posible hacer esto con `let` o `const` ya que tienen un alcance de bloque.

--- -###### 24. What's the output? +###### 24. ¿Qué devuelve la siguiente función? ```javascript const obj = { 1: "a", 2: "b", 3: "c" }; @@ -724,21 +724,22 @@ set.has(1); - C: `true` `true` `false` `true` - D: `true` `true` `true` `true` -
Answer +
Solución

-#### Answer: C +#### Respuesta correcta: 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. +Todas las claves de un objeto (excepto los símbolos) actúan como cadenas, incluso si no son escritas como una cadena. Es por eso que `obj.hasOwnProperty('1')` también devuelve verdadero. + +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`. -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. What's the output? +###### 25. ¿Qué devuelve la siguiente función? ```javascript const obj = { a: "one", b: "two", a: "three" }; @@ -750,37 +751,37 @@ console.log(obj); - C: `{ a: "three", b: "two" }` - D: `SyntaxError` -
Answer +
Solución

-#### Answer: C +#### Respuesta correcta: 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. +Si tiene dos claves con el mismo nombre, la clave será reemplazada. Seguirá estando en su primera posición, pero con el último valor especificado

--- -###### 26. The JavaScript global execution context creates two things for you: the global object, and the "this" keyword. +###### 26. El contexto de ejecución de JS crea dos cosas: el objecto global y la palabra reservada "this". - A: true - B: false - C: it depends -
Answer +
Solución

-#### Answer: A +#### Respuesta correcta: A -The base execution context is the global execution context: it's what's accessible everywhere in your code. +El contexto de ejecución base es el contexto de ejecución global: es accesible en todo el código.

--- -###### 27. What's the output? +###### 27. ¿Qué devuelve la siguiente función? ```javascript for (let i = 1; i < 5; i++) { @@ -794,19 +795,18 @@ for (let i = 1; i < 5; i++) { - C: `1` `2` `4` - D: `1` `3` `4` -
Answer +
Solución

-#### Answer: C - -The `continue` statement skips an iteration if a certain condition returns `true`. +#### Respuesta correcta: C +La sentencia `continue` omite una iteración si una cierta condición, en este caso `(i === 3)`, devuelve `true`.

--- -###### 28. What's the output? +###### 28. ¿Qué devuelve la siguiente función? ```javascript String.prototype.giveLydiaPizza = () => { @@ -823,19 +823,19 @@ name.giveLydiaPizza(); - C: `SyntaxError` - D: `undefined` -
Answer +
Solución

-#### Answer: A +#### Respuesta correcta: 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` es un constructor incorporado, al que podemos añadir propiedades. En este caso concreto, añadimos un método a su prototipo. Las cadenas primitivas se convierten automáticamente en un objeto de cadena, generado por la función de prototipo de cadena. Por lo tanto, todas las cadenas (objetos de cadena) tienen acceso a ese método.

--- -###### 29. What's the output? +###### 29. ¿Qué devuelve la siguiente función? ```javascript const a = {}; @@ -853,23 +853,23 @@ console.log(a[b]); - C: `undefined` - D: `ReferenceError` -
Answer +
Solución

-#### Answer: B +#### Respuesta correcta: 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`. +Las claves se convierten automáticamente en strings. Estamos tratando en este pregunta de establecer un objeto como clave para el objeto `a`, con el valor de `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`. +Sin embargo, cuando se _stringfy_ (compleja traducción) un objeto, se convierte en `"[Object object]"`. Así que lo que estamos diciendo aquí, es que `a["Object object"] = 123`. Entonces, podemos intentar hacer lo mismo de nuevo. `c` es otro objeto que estamos implícitamente encadenando. Entonces, `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`. +Para finalizar, registramos `a[b]`, que en realidad es `a["Object"]`. Acabamos de ponerlo en `456`, así que devuelve `456`.

--- -###### 30. What's the output? +###### 30. ¿Qué devuelve la siguiente función? ```javascript const foo = () => console.log("First"); @@ -886,36 +886,36 @@ baz(); - C: `Second` `First` `Third` - D: `Second` `Third` `First` -
Answer +
Solución

-#### Answer: B +#### Respuesta correcta: B -We have a `setTimeout` function and invoked it first. Yet, it was logged last. +Tenemos una función `setTimeout` y la invocamos primero. Sin embargo, fue el último en ser registrado. -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. +Esto se debe a que en los navegadores, no sólo tenemos el motor de tiempo de ejecución, también tenemos algo llamado `WebAPI`. El `WebAPI` nos da la función `setTimeout` para empezar, y por ejemplo el DOM. -After the _callback_ is pushed to the WebAPI, the `setTimeout` function itself (but not the callback!) is popped off the stack. +Después de que la _callback_ es empujada a la WebAPI, la función `setTimeout` en sí misma (¡pero no la callback!) es removida de la pila. -Now, `foo` gets invoked, and `"First"` is being logged. +Ahora, `foo` es invocado, y ``"First"`` está siendo registrado. -`foo` is popped off the stack, and `baz` gets invoked. `"Third"` gets logged. +`Foo` se quita de la pila, y `Baz` es invocado. `Third` se registra. -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_. +La WebAPI no puede simplemente añadir cosas a la pila cuando está lista. En su lugar, empuja la función de devolución de llamada a algo llamado la _queue_ (cola en español). -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. +Aquí es donde un bucle de eventos comienza a funcionar. Un **lazo de evento** mira la pila y la cola de tareas. Si la pila está vacía, toma lo primero que encuentra en la cola y la empuja sobre la pila. -`bar` gets invoked, `"Second"` gets logged, and it's popped off the stack. +Se invoca el `bar`, se registra el ``"Second"`` y se quita de la pila.

From e5f5af03fb34c6b7cfb0d98ac91be655a9406ce5 Mon Sep 17 00:00:00 2001 From: panicdragon Date: Fri, 21 Jun 2019 02:17:29 +0900 Subject: [PATCH 061/915] Translate to Japanese --- README-ja_JA.md | 1335 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 1335 insertions(+) create mode 100644 README-ja_JA.md diff --git a/README-ja_JA.md b/README-ja_JA.md new file mode 100644 index 00000000..9ffde70a --- /dev/null +++ b/README-ja_JA.md @@ -0,0 +1,1335 @@ +# JavaScript (高度な) 問題集 + +私は毎日、JavaScriptに関する選択問題を [Instagram](https://www.instagram.com/theavocoder)に投稿していますが、ここにも投稿します。 + +初級から上級まで: JavaScriptの知識のテストを行ったり、知識を少し深めたり、コーディング面接の準備をしてください。:muscle: :rocket: 私はこのレポを毎週新しい質問で更新します。 + +答えは質問の下の折りたたまれたセクションにあります、クリックすればそれを広げられます。幸運を祈ります。:heart: + + +[中文版本](./README-zh_CN.md) +[Русский](./README_ru-RU.md) +[Western Balkan](./README-bs_BS.md) +[Deutsch](./README-de_DE.md) +[Tiếng Việt](./README-vi.md) +[日本語](./README-ja_JA.md) + +--- + +###### 1. 何が出力されるでしょうか? + +```javascript +function sayHi() { + console.log(name); + console.log(age); + var name = "Lydia"; + let age = 21; +} + +sayHi(); +``` + +- A: `Lydia` と `undefined` +- B: `Lydia` と `ReferenceError` +- C: `ReferenceError` と `21` +- D: `undefined` と `ReferenceError` + +
答え +

+ +#### 答え: D + +関数内で、まず `var`キーワードを使って `name`変数を宣言します。これは、変数が定義されている行に実際に到達するまで、変数がデフォルト値の `undefined`で初期化される(作成時にメモリ空間が設定される)ことを意味します。 + +`name`変数をログ出力を実行している行では、まだ変数を定義していませんので、`undefined`の値を保持しています。 + +`let`キーワード(または`const`)を持つ変数は持ち上げられますが、 `var`とは異なり、初期化されません。それらを宣言(初期化)する行の前にはアクセスできません。これは"temporal dead zone"と呼ばれます。 + +宣言される前に変数にアクセスしようとすると、JavaScriptは `ReferenceError`を投げます。 + +

+
+ +--- + +###### 2. 何が出力されるでしょうか? + +```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` と `0 1 2` +- B: `0 1 2` と `3 3 3` +- C: `3 3 3` と `0 1 2` + +
答え +

+ +#### 答え: C + +JavaScriptのイベントキューのため、`setTimeout`コールバック関数はループが実行された後に呼び出されます。最初のループの変数 `i`は`var`キーワードを使って宣言されているので、この値はグローバル変数となります。ループの間、単項演算子 `++`を使用して、毎回 `i`の値を`1`ずつインクリメントしました。 最初の例では `setTimeout`コールバック関数が呼び出されるまでに`i`は`3`となりました。 + +2番目のループでは、変数 `i`が `let`キーワードを使って宣言されました。 `let`(または`const`)キーワードで宣言された変数はブロックスコープです(ブロックは `{}`の間のものです)。それぞれの繰り返しの間、 `i`は新しい値を持ち、それぞれの値はループの内側にあります。 + +

+
+ +--- + +###### 3. 何が出力されるでしょうか? + +```javascript +const shape = { + radius: 10, + diameter() { + return this.radius * 2; + }, + perimeter: () => 2 * Math.PI * this.radius +}; + +shape.diameter(); +shape.perimeter(); +``` + +- A: `20` と `62.83185307179586` +- B: `20` と `NaN` +- C: `20` と `63` +- D: `NaN` と `63` + +
答え +

+ +#### 答え: B + +`diameter`の値は正則関数であり、`perimeter`の値はアロー関数です。 + +アロー関数では、`this`キーワードは通常の関数とは異なり、現在の周囲の範囲を参照します。これは、`perimeter`関数を呼ぶと、shapeオブジェクトではなく、その周囲の範囲(例えば window)を参照することを意味します。 + +そのオブジェクトには`radius`という値はなく、`undefined`を返します。 + +

+
+ +--- + +###### 4. 何が出力されるでしょうか? + +```javascript ++true; +!"Lydia"; +``` + +- A: `1` と `false` +- B: `false` と `NaN` +- C: `false` と `false` + +
答え +

+ +#### 答え: A + +単項プラスは、オペランドを数値に変換しようとします。`true`は`1`、`false`は`0`です + +文字列「Lydia」は truthy valueです。ここで求めているのは、「このtruthy valueは、falsyなのか」ということです。これは `false`を返します。 + +

+
+ +--- + +###### 5. 正解はどれでしょう? + +```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: これらすべて有効です + +
答え +

+ +#### 答え: A + +JavaScriptでは、すべてのオブジェクトキーは文字列です(Symbolでない限り)。たとえそれを文字列として入力していなくても、それらは常にフードの下で文字列に変換されます。 + +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`ような、エラーをスローします。 + +

+
+ +--- + +--- + +###### 6. 何が出力されるでしょうか? + +```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` + +
答え +

+ +#### 答え: A + +JavaScriptでは、すべてのオブジェクトは互いに等しく設定すると参照によって相互作用します。 + +まず、変数`c`は、オブジェクトに対する値を保持します。その後、`c`オブジェクトに対して持っている値と同じ参照で`d`に代入します。 + + + +1つのオブジェクトを変更すると、それらすべてが変更されます。 + +

+
+ +--- + +###### 7. 何が出力されるでしょうか? + +```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` + +
答え +

+ +#### 答え: C + +`new Number()`は、組み込み関数のコンストラクタです。数字のように見えますが、実際には数字ではありません。たくさんの追加機能があり、それはオブジェクトとなります。 + +`==`演算子を使うとき、同じ値を持っているかどうか? をチェックするだけとなります。それらは両方とも`3`の値を持っているので、それは`true`を返します。 + +しかし、`===`演算子を使う時は、値と型は同じであるべきです。 そうでないので: `new Number()`は数値ではなく、**オブジェクト**となります。なので、両方ともfalseを返します。 + +

+
+ +--- + +###### 8. 何が出力されるでしょうか? + +```javascript +class Chameleon { + 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` + +
答え +

+ +#### 答え: D + +`colorChange`関数は静的です。静的メソッドは、それらが作成されたコンストラクタ上でのみ動作するように設計されており、どの子達にも受け継がれません。 `freddie`は子となりますので、この関数は受け継がれず、`freddie`インスタンスでは利用できません。 + +その結果、`TypeError`が投げられます。 + +

+
+ +--- + +###### 9. 何が出力されるでしょうか? + +```javascript +let greeting; +greetign = {}; // Typo! +console.log(greetign); +``` + +- A: `{}` +- B: `ReferenceError: greetign is not defined` +- C: `undefined` + +
答え +

+ +#### 答え: A + +グローバルオブジェクトに、空のオブジェクトを作成したばかりなので、オブジェクトはログ出力されます。`greeting`を`greetign`と誤って入力した場合、JSインタプリタは実際にこれを `global.greetign = {}`(またはブラウザの `window.greetign = {}`)と見なします。 + +これを避けるために、"use strict"を使用する事ができます。これにより、変数を何かに設定する前に、変数宣言したことを確認できます。 + +

+
+ +--- + +###### 10. これを行うと、どうなりますか? + +```javascript +function bark() { + console.log("Woof!"); +} + +bark.animal = "dog"; +``` + +- A: 何も起こらない、これは全く問題ない! +- B: `SyntaxError`. この方法で関数にプロパティを追加することはできません。 +- C: `undefined` +- D: `ReferenceError` + +
答え +

+ +#### 答え: A + +関数はオブジェクトとなるので、これはJavaScriptで可能です。(プリミティブ型以外はすべてオブジェクトです。) + +関数は特別な種類のオブジェクトです。自分で書いたコードは実際の機能ではありません。関数はプロパティを持つオブジェクトです。よって、このプロパティは呼び出し可能となります。 + +

+
+ +--- + +###### 11. 何が出力されるでしょうか? + +```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` + +
答え +

+ +#### 答え: A + +通常のオブジェクトのようにコンストラクタにプロパティを追加することはできません。一度にすべてのオブジェクトに機能を追加したい場合は、代わりにプロトタイプを使用する必要があります。だからこの場合は、 + +```js +Person.prototype.getFullName = function() { + return `${this.firstName} ${this.lastName}`; +}; +``` + +で、`member.getFullName()`が、機能するはずです。これはなぜ有益なのでしょうか。例えば、このメソッドをコンストラクタ自体に追加したとします。すべての`Person`インスタンスがこのメソッドを必要としなかったのかもしれません。 + +その場合、多くのメモリスペースを浪費する事でしょう。なぜならそれらはまだその特性を持ち、それは各インスタンスのためにメモリスペースを消費するからです。 + +その代わりに、プロトタイプに追加するだけであれば、メモリ内の1箇所に配置するだけで、すべてのユーザーがアクセスできます。 + +

+
+ +--- + +###### 12. 何が出力されるでしょうか? + +```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"}` と `undefined` +- B: `Person {firstName: "Lydia", lastName: "Hallie"}` と `Person {firstName: "Sarah", lastName: "Smith"}` +- C: `Person {firstName: "Lydia", lastName: "Hallie"}` と `{}` +- D:`Person {firstName: "Lydia", lastName: "Hallie"}` と `ReferenceError` + +
答え +

+ +#### 答え: A + +`sarah`では、`new`キーワードを使いませんでした。`new`を使用した場合、作成した新しい空のオブジェクトを参照します。しかし、`new`を追加しなければ、それは**グローバルオブジェクト**を参照することとなります。 + +`this.firstName`に`"Sarah"`を代入、`this.lastName`に`"Smith"`を代入したつもりでしたが、実際に行った事は、`global.firstName = 'Sarah'` と、`global.lastName = 'Smith'`を定義したのです。 + +`sarah`自体は` undefined`のままです。 + +

+
+ +--- + +###### 13. イベント伝播の3つの段階はどれですか? + +- A: Target > Capturing > Bubbling +- B: Bubbling > Target > Capturing +- C: Target > Bubbling > Capturing +- D: Capturing > Target > Bubbling + +
答え +

+ +#### 答え: D + +**capture**フェーズの間、イベントは先祖の要素を通過してターゲットの要素になります。それから**target**要素に達した後、**バブリング**が開始されます。 + + + +

+
+ +--- + +###### 14. すべてのオブジェクトはプロトタイプを持っています。 + +- A: true +- B: false + +
答え +

+ +#### 答え: B + +**基本オブジェクト**を除き、すべてのオブジェクトにプロトタイプがあります。ベースオブジェクトは`.toString`のようないくつかのメソッドとプロパティにアクセスできます。 + +これが、組み込みのJavaScriptメソッドを使用できる理由です。このような方法はすべてプロトタイプで利用できます。 + +JavaScriptはそれをあなたのオブジェクト上で直接見つけることはできませんが、プロトタイプチェーンをたどり、見つけます。 + +

+
+ +--- + +###### 15. 何が出力されるでしょうか? + +```javascript +function sum(a, b) { + return a + b; +} + +sum(1, "2"); +``` + +- A: `NaN` +- B: `TypeError` +- C: `"12"` +- D: `3` + +
答え +

+ +#### 答え: C + +JavaScriptは、**動的に型付けされた言語**です。: 特定の変数がどんな型であるかは指定しません。知らないうちに、値が自動的に別の型に変換されることがあります。この事を`implicit type coercion`と呼ばれてます。 **Coercion**は、ある型から別の型に変換しています。 + +この例では、関数が意味を成して値を返すために、JavaScriptは数字の`1`を文字列に変換します。数値型(`1`)と 文字列型(`'2'`)の追加中は、数字は文字列として扱われます。 + +`"Hello"+"World"`のように文字列を連結することができるので、ここで起こっているのは`"1"+"2"`で、これは `"12"`を返します。 + +

+
+ +--- + +###### 16. 何が出力されるでしょうか? + +```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` + +
答え +

+ +#### 答え: C + +**接尾辞** 単項演算子 `++`: + +1.値を返す(これは`0`を返す) +2.値を増やす(numberは現在`1`です) + +**接頭辞** 単項演算子 `++`: + +1.値を増やす(数値は2になります) +2.値を返す(これは`2`を返します) + +これは`0 2 2`を返します。 + +

+
+ +--- + +###### 17. 何が出力されるでしょうか? + +```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` + +
答え +

+ +#### 答え: B + +タグ付きテンプレートリテラルを使用する場合、最初の引数の値は常に文字列値の配列です。残りの引数は渡された式の値を取得します。 + +

+
+ +--- + +###### 18. 何が出力されるでしょうか? + +```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` + +
答え +

+ +#### 答え: C + +等価性をテストするとき、プリミティブはそれらの値によって比較され、オブジェクトはそれらの参照によって比較されます。 JavaScriptは、オブジェクトがメモリ内の同じ場所への参照を持っているかどうかを確認します。 + +比較している2つのオブジェクトにはそれがありません。パラメータとして渡したオブジェクトが、等価性を確認するために使用したオブジェクトとは異なるメモリ内の場所を参照しています。 + +これが `{ age: 18 } === { age: 18 }`と、`{ age: 18 } == { age: 18 }`の両方が、`false`を返す理由です。 + +

+
+ +--- + +###### 19. 何が出力されるでしょうか? + +```javascript +function getAge(...args) { + console.log(typeof args); +} + +getAge(21); +``` + +- A: `"number"` +- B: `"array"` +- C: `"object"` +- D: `"NaN"` + +
答え +

+ +#### 答え: C + +スプレッド演算子(`... args`.)は、引数付きの配列を返します。配列はオブジェクトなので、`typeof args`は、`"object"`を返します。 + +

+
+ +--- + +###### 20. 何が出力されるでしょうか? + +```javascript +function getAge() { + "use strict"; + age = 21; + console.log(age); +} + +getAge(); +``` + +- A: `21` +- B: `undefined` +- C: `ReferenceError` +- D: `TypeError` + +
答え +

+ +#### 答え: C + +`"use strict"`を使うと、誤ってグローバル変数を宣言しないようにすることができます。変数`age`を宣言したことは一度もありませんし、`"use strict"`を使っているので参照エラーになります。 + +`"use strict"`を使用しなかった場合は、プロパティ`age`がグローバルオブジェクトに追加されたことになるので、それは機能します。 + +

+
+ +--- + +###### 21. sumの値は何? + +```javascript +const sum = eval("10*10+5"); +``` + +- A: `105` +- B: `"105"` +- C: `TypeError` +- D: `"10*10+5"` + +
答え +

+ +#### 答え: A + +`eval`は文字列として渡されたコードを評価します。この場合のように式であれば、その式を評価します。表現は`10 * 10 + 5`です。これは`105`を返します。 + +

+
+ +--- + +###### 22. cool_secretは、どのくらいの期間アクセス可能ですか? + +```javascript +sessionStorage.setItem("cool_secret", 123); +``` + +- A: 永遠に、データが失われることはありません。 +- B: ユーザーがタブを閉じる時 +- C: ユーザーがタブだけでなくブラウザ全体を閉じる時。 +- D: ユーザーが自分のコンピュータをシャットダウンした時。 + +
答え +

+ +#### 答え: B + +`sessionStorage`に格納されたデータは、タブを閉じた後に削除されます。 + +`localStorage`を使用した場合は、`localStorage.clear()`などが呼び出されない限り、データは永久に存在しているでしょう。 + +

+
+ +--- + +###### 23. 何が出力されるでしょうか? + +```javascript +var num = 8; +var num = 10; + +console.log(num); +``` + +- A: `8` +- B: `10` +- C: `SyntaxError` +- D: `ReferenceError` + +
答え +

+ +#### 答え: B + +`var`キーワードを使うと、同じ名前で複数の変数を宣言できます。変数は最新の値を保持します。 + +ブロックスコープの`let`や`const`では、できません。 + +

+
+ +--- + +###### 24. 何が出力されるでしょうか? + +```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` + +
答え +

+ +#### 答え: C + +すべてのオブジェクトキー(Symbolsを除く)は、文字列として自分で入力しなくても、内部では文字列です。これが、`obj.hasOwnProperty('1')`も​​trueを返す理由です。 + +setではそうはいきません。上記のsetには`'1'` はありません: `set.has('1')`は、`false`を返します。数値型`1`の`set.has(1)`は、`true`を返します。 + +

+
+ +--- + +###### 25. 何が出力されるでしょうか? + +```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` + +
答え +

+ +#### 答え: C + +同じ名前のキーが2つある場合、最初の位置にあるキーは置き換えられ、最後に指定された値になります。 + +

+
+ +--- + +###### 26. JavaScriptのglobal execution contextは、2つを作成します。: それはグローバルオブジェクトと "this"キーワードです。 + +- A: true +- B: false +- C: 場合によりけり + +
答え +

+ +#### 答え: A + +基本的なexecution contextは、グローバルな実行コンテキストです。それはあなたのコードの至る所でアクセス可能なものです。 + +

+
+ +--- + +###### 27. 何が出力されるでしょうか? + +```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` + +
答え +

+ +#### 答え: C + +`continue`ステートメントは、ある条件が`true`を返すと、繰り返し処理をスキップします。 + +

+
+ +--- + +###### 28. 何が出力されるでしょうか? + +```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` + +
答え +

+ +#### 答え: A + +`String`はプロパティを追加することができる組み込みコンストラクタです。プロトタイプにメソッドを追加しました。 + +プリミティブ文字列は、文字列プロトタイプ関数によって生成された文字列オブジェクトに自動的に変換されます。 + +つまり、すべての文字列(文字列オブジェクト)がそのメソッドにアクセスできます。 + +

+
+ +--- + +###### 29. 何が出力されるでしょうか? + +```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` + +
答え +

+ +#### 答え: B + +オブジェクトキーは自動的に文字列に変換されます。オブジェクトaのキーとして、値123で設定しようとしています。 + +しかし、オブジェクトを文字列化すると、それは`"[Object object]"`​​になってしまいます。なので、ここで行っているのは、 `a["Object object"] = 123`です。 + +その後、同じことをもう一度試みています。`c`は暗黙のうちに文字列化している別のオブジェクトです。そのため、`a["Object object"] = 456`となります。 + +その後、`a[b]`でログ出力。実際には`a["Object object"]`です。これを `456`に設定しただけなので、`456`を返します。 + +

+
+ +--- + +###### 30. 何が出力されるでしょうか? + +```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` + +
答え +

+ +#### 答え: B + +`setTimeout`関数があり、それを最初に呼び出したのですが、それは最後にログ出力されました。 + +これは、ブラウザにはランタイムエンジンがあるだけでなく、`WebAPI`と呼ばれるものもあるからです。`WebAPI`は最初に`setTimeout`関数を与えてくれます。例えばDOMです。 + +callbackがWebAPIにプッシュされた後、`setTimeout`関数自体(コールバックではありません!)がスタックからポップされます。 + + + +今、`foo`が呼び出され、`"First"`が、ログ出力されています。 + + + +`foo`がスタックからポップされ、`baz`が呼び出されます。`"Third"`が、ログ出力されます。 + + + +WebAPIは、準備が整ったときにスタックに、なにかを追加することはできません。代わりに、コールバック関数を`queue`と呼ばれるものにプッシュします。 + + + +event loopが機能し始めるところです。 **event loop**はスタックとタスクキューを調べます。スタックが空の場合は、キューの最初のものを取り出し、それをスタックにプッシュします。 + + + +`bar`が呼び出され、`"Second"`がログ出力され、スタックからポップされます。 + +

+
+ +--- + +###### 31.ボタンをクリックしたときのevent.targetは何ですか? + +```html +
+
+ +
+
+``` + +- A: 外側 `div` +- B: 内側 `div` +- C: `button` +- D: ネストしたすべての要素の配列 + +
答え +

+ +#### 答え: C + +イベントを引き起こした最も深くネストした要素がイベントのターゲットとなります。`event.stopPropagation`でバブリングを止めることができます + +

+
+ +--- + + +###### 32. p要素をクリックすると、ログ出力はどうなりますか。 + +```html +
+

+ Click here! +

+
+``` + +- A: `p` `div` +- B: `div` `p` +- C: `p` +- D: `div` + +
答え +

+ +#### 答え: A + +`p`をクリックすると、`p`と`div`の2つのログが表示されます。イベント伝播中は、キャプチャ、ターゲット、バブリングの3つのフェーズがあります。 + +デフォルトでは、イベントハンドラはバブリング段階で実行されます(`useCapture`を`true`に設定しない限り)。最も深くネストした要素から外側に向かって進みます。 + +

+
+ +--- + +###### 33. 何が出力されるでしょうか? + +```javascript +const person = { name: "Lydia" }; + +function sayHi(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` + +
答え +

+ +#### 答え: D + +両方とも、`this`キーワードが参照したいオブジェクトを渡すことができます。しかし、`.call`もすぐに実行されます。 + +`.bind.`は関数のコピーを返しますが、コンテキストは束縛されています。すぐには実行されません。 + +

+
+ +--- + +###### 34. 何が出力されるでしょうか? + +```javascript +function sayHi() { + return (() => 0)(); +} + +typeof sayHi(); +``` + +- A: `"object"` +- B: `"number"` +- C: `"function"` +- D: `"undefined"` + +
答え +

+ +#### 答え: B + +`sayHi`関数は、即時呼び出し関数式(IIFE)の戻り値を返します。この関数は`0`を返しました。それは`"number"`型です。 + +参考:7つの組み込み型しかありません: `null`, `undefined`, `boolean`, `number`, `string`, `object`, そして`symbol`。関数はオブジェクトなので、`"function"`型ではなく`"object"`型です。 + +

+
+ +--- + +###### 35. これらの値のどれが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: これらすべてfalsy + +
答え +

+ +#### 答え: A + +falsyの値は6つだけです。 + +- `undefined` +- `null` +- `NaN` +- `0` +- `''` (empty string) +- `false` + +`new Number`や、`new Boolean`のような関数コンストラクタはtruthyです。 + +

+
+ +--- + +###### 36. 何が出力されるでしょうか? + +```javascript +console.log(typeof typeof 1); +``` + +- A: `"number"` +- B: `"string"` +- C: `"object"` +- D: `"undefined"` + +
答え +

+ +#### 答え: B + +`typeof 1`は、`"number"`を返します。 + +`typeof "number"`は、`"string"`を返します。 + +

+
+ +--- + +###### 37. 何が出力されるでしょうか? + +```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` + +
答え +

+ +#### 答え: C + +配列の長さを超える値を配列内の要素に設定すると、JavaScriptでは、"empty slots"と呼ばれるものを作成します。これらは実際には、`undefined`の値を持ちますが、あなたは以下のようなものを見るでしょう + +`[1, 2, 3, 7 x empty, 11]` + +実行場所によって異なります(browser、nodeなどによって異なります)。 + +

+
+ +--- + +###### 38. 何が出力されるでしょうか? + +```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` + +
答え +

+ +#### 答え: A + +`catch`ブロックは引数`x`を受け取ります。これは引数を渡すときの変数と同じ`x`ではありません。この変数`x`はブロックスコープです。 + +後に、このブロックスコープ変数を`1`に設定し、変数`y`の値を設定します。ここで、ブロックスコープ変数`x`をログ出力します。これは`1`となります。 + +`catch`ブロック以外では、`x`は未定義、`y`は2です。 `catch`ブロックの外側で`console.log(x)`した場合は、`undefined`を返し、`y`は`2`を返します。 + +

+
+ +--- + +###### 39. JavaScriptのすべてはどちらかです... + +- A: primitive か object +- B: function か object +- C: ひっかけ問題! objectsのみ +- D: number か object + +
答え +

+ +#### 答え: A + +JavaScriptにはプリミティブ型とオブジェクトしかありません。 + +プリミティブ型は、`boolean`, `null`, `undefined`, `bigint`, `number`, `string`, そして`symbol`です。 + +プリミティブとオブジェクトを区別するのは、プリミティブにはプロパティもメソッドもないということです。 + +ただし、`'foo'.toUpperCase()`は`'FOO'`と評価され、`TypeError`にはなりません。これは、文字列のようなプリミティブのプロパティやメソッドにアクセスしようとすると、JavaScriptがラッパークラスの1つ、すなわち`String`を使ってオブジェクトを暗黙的にラップし、式が評価された後ラッパーを直ちに破棄するためです。 + +`null`と`undefined`を除くすべてのプリミティブはこの振る舞いをします。 + +

+
+ +--- + +###### 40. 何が出力されるでしょうか? + +```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]` + +
答え +

+ +#### 答え: C + +`[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]`を得ます + +

+
+ +--- + +###### 41. 何が出力されるでしょうか? + +```javascript +!!null; +!!""; +!!1; +``` + +- A: `false` `true` `false` +- B: `false` `false` `true` +- C: `false` `true` `true` +- D: `true` `true` `false` + +
答え +

+ +#### 答え: B + +`null`はfalsyです。`!null`は`true`を返します。`!true`は`false`を返します。 + +`""`はfalsyです。`!""`は`true`を返します。`!true`は`false`を返します。 + +`1`はtruthyです。`!1`は`false`を返します。`!false`は`true`を返します。 + +

+
+ +--- + + +###### 42. `setInterval`メソッドはブラウザに何を返しますか? + +```javascript +setInterval(() => console.log("Hi"), 1000); +``` + +- A: ユニークid +- B: 指定されたミリ秒数 +- C: 渡された関数 +- D: `undefined` + +
答え +

+ +#### 答え: A + +一意のIDを返します。このIDは `clearInterval()`関数で、その間隔をクリアするために使うことができます。 + +

+
+ +--- + +###### 43. これは何を返しますか? + +```javascript +[..."Lydia"]; +``` + +- A: `["L", "y", "d", "i", "a"]` +- B: `["Lydia"]` +- C: `[[], "Lydia"]` +- D: `[["L", "y", "d", "i", "a"]]` + +
答え +

+ +#### 答え: A + +文字列はイテラブルです。スプレッド演算子は、イテラブルのすべての文字を1つの要素にマッピングします。 + +

+
From 3f3bc2fb05cb57eb620dfd4b9bc8bb035bebe78b Mon Sep 17 00:00:00 2001 From: Guilherme Nogara Date: Thu, 20 Jun 2019 16:00:30 -0300 Subject: [PATCH 062/915] Questions 16-43 done --- README_pt_BR.md | 327 ++++++++++++++++++++++++------------------------ 1 file changed, 164 insertions(+), 163 deletions(-) diff --git a/README_pt_BR.md b/README_pt_BR.md index 0c5ab777..5be1c3c5 100644 --- a/README_pt_BR.md +++ b/README_pt_BR.md @@ -427,6 +427,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. @@ -452,7 +453,7 @@ Todos objetos tem protótipos, exceto pelo **base object**. O base object tem ac --- -###### 15. What's the output? +###### 15. Qual é a saída? ```javascript function sum(a, b) { @@ -467,21 +468,21 @@ sum(1, "2"); - C: `"12"` - D: `3` -
Answer +
Resposta

-#### Answer: C +#### Resposta: 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. +JavaScript é uma **linguagem dinamicamente tipada**: Não especificamos quais tipos nossas variáveis são. Valores pode ser automaticamente convertidos em outro tipo sem você saber, o que é chamado de coerção implicita de tipo. **Coerção** é converter de um tipo em outro. -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"`. +Nesse exemplo, JavaScript converte o número `1` em uma string, para que a função faça sentido e retorne um valor. Durante a adição de um tipo numérico (`1`) e uma string (`'2'`), o número é tratado como uma string. Podemos concatenar strings como `"Hello" + "World"`, então o que está acontecendo aqui é `"1" + "2"` que retorna `"12"`.

--- -###### 16. What's the output? +###### 16. Qual é a saída? ```javascript let number = 0; @@ -495,29 +496,29 @@ console.log(number); - C: `0` `2` `2` - D: `0` `1` `2` -
Answer +
Resposta

-#### Answer: C +#### Resposta: C -The **postfix** unary operator `++`: +O operador unário no **sufixo** `++`: -1. Returns the value (this returns `0`) -2. Increments the value (number is now `1`) +1. Retorna o valor (retorna o valor `0`) +2. Incrementa o valor (numero agora é `1`) -The **prefix** unary operator `++`: +O operador unário **prefixo** `++`: -1. Increments the value (number is now `2`) -2. Returns the value (this returns `2`) +1. Incrementa o valor (numero agora é `2`) +2. Retorna o valor (Retorna o valor `2`) -This returns `0 2 2`. +Isso retorna `0 2 2`.

--- -###### 17. What's the output? +###### 17. Qual é a saída? ```javascript function getPersonInfo(one, two, three) { @@ -536,19 +537,19 @@ getPersonInfo`${person} is ${age} years old`; - B: `["", " is ", " years old"]` `"Lydia"` `21` - C: `"Lydia"` `["", " is ", " years old"]` `21` -
Answer +
Resposta

-#### Answer: B +#### Resposta: 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! +Se usamos template literals marcadas, ou tagged template literals, o valor do primeiro argumento é sempre um array com a string, separada pelos tagged template liberals. Os argumentos restantes recebem os valores das expressões passadas!

--- -###### 18. What's the output? +###### 18. Qual é a saída? ```javascript function checkAge(data) { @@ -568,23 +569,23 @@ checkAge({ age: 18 }); - B: `You are still an adult.` - C: `Hmm.. You don't have an age I guess` -
Answer +
Resposta

-#### Answer: C +#### Resposta: 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. +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. -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. +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. -This is why both `{ age: 18 } === { age: 18 }` and `{ age: 18 } == { age: 18 }` return `false`. +É por isso que ambos `{ age: 18 } === { age: 18 }` E `{ age: 18 } == { age: 18 }` retornam `false`.

--- -###### 19. What's the output? +###### 19. Qual é a saída? ```javascript function getAge(...args) { @@ -599,19 +600,19 @@ getAge(21); - C: `"object"` - D: `"NaN"` -
Answer +
Resposta

-#### Answer: C +#### Resposta: C -The spread operator (`...args`.) returns an array with arguments. An array is an object, so `typeof args` returns `"object"` +O operador _spread_ (`...args`.) retorna um array com os argumentos. Um array é um objeto, então `typeof args` retorna `"object"`

--- -###### 20. What's the output? +###### 20. Qual é a saída? ```javascript function getAge() { @@ -628,19 +629,19 @@ getAge(); - C: `ReferenceError` - D: `TypeError` -
Answer +
Resposta

-#### Answer: C +#### Resposta: 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. +Com `"use strict"`, você pode ter certeza que não declarou variáveis globais. Nunca declaramos a variável `age`, e já que usamos `"use strict"`, ira gerar um erro de referência. Se não tivéssemos usado `"use strict"`, teria funcionado, uma vez que a propriedade `age` teria sido adicionada ao objeto global.

--- -###### 21. What's value of `sum`? +###### 21. Qual o valor de `sum`? ```javascript const sum = eval("10*10+5"); @@ -651,44 +652,44 @@ const sum = eval("10*10+5"); - C: `TypeError` - D: `"10*10+5"` -
Answer +
Resposta

-#### Answer: A +#### Resposta: 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` executa o código mesmo se passado como string. Se é uma expressão, como nesse caso, ele cálcula a expressão. A expressão é `10 * 10 + 5`. Isso retorna o número `105`.

--- -###### 22. How long is cool_secret accessible? +###### 22. Por quanto tempo cool_secret é acessível? ```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. +- A: Sempre, o dado não é perdido. +- B: Quando o usuário fechar a guia. +- C: Quando o usuário fechar o navegador inteiro. +- D: Quando o usuário desligar o computador. -
Answer +
Resposta

-#### Answer: B +#### Resposta: B -The data stored in `sessionStorage` is removed after closing the _tab_. +Dados guardados em `sessionStorage` são removidos depois de fechar a _guia_. -If you used `localStorage`, the data would've been there forever, unless for example `localStorage.clear()` is invoked. +Se usássemos `localStorage`, o dado seria guardado para sempre, exceto se `localStorage.clear()` fosse chamado.

--- -###### 23. What's the output? +###### 23. Qual é a saída? ```javascript var num = 8; @@ -702,21 +703,21 @@ console.log(num); - C: `SyntaxError` - D: `ReferenceError` -
Answer +
Resposta

-#### Answer: B +#### Resposta: B -With the `var` keyword, you can declare multiple variables with the same name. The variable will then hold the latest value. +Coma a palavra-chave `var`, você pode declarar várias variáveis com o mesmo nome. A variável vai guardar o último valor. -You cannot do this with `let` or `const` since they're block-scoped. +Você não pode fazer isso com `let` ou `const` uma vez que eles conferem o bloco de escopo em que estão inseridos.

--- -###### 24. What's the output? +###### 24. Qual é a saída? ```javascript const obj = { 1: "a", 2: "b", 3: "c" }; @@ -733,21 +734,21 @@ set.has(1); - C: `true` `true` `false` `true` - D: `true` `true` `true` `true` -
Answer +
Resposta

-#### Answer: C +#### Resposta: 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. +Todas as chaves de objetos (exceto símbolos) são strings debaixo do capô, mesmo que você não digite como uma string. É por isso que `obj.hasOwnProperty('1')` também retorna `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`. +Não funciona assim para `Set`. Não tem um `'1'` no nosso set: `set.has('1')` retorna `false`. Temos o tipo número `1`, então `set.has(1)` retorna `true`.

--- -###### 25. What's the output? +###### 25. Qual é a saída? ```javascript const obj = { a: "one", b: "two", a: "three" }; @@ -759,37 +760,37 @@ console.log(obj); - C: `{ a: "three", b: "two" }` - D: `SyntaxError` -
Answer +
Resposta

-#### Answer: C +#### Resposta: 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. +Se temos duas chaves com o mesmo nome, a última irá substituir a primeira. Ainda vai estar na primeira posição, mas com o último valor específicado.

--- -###### 26. The JavaScript global execution context creates two things for you: the global object, and the "this" keyword. +###### 26. O contexto glogal de execução do JavaScrit cria duas coisas para você: O objeto glogal, e a palavra-chave `this`. -- A: true -- B: false -- C: it depends +- A: Verdadeiro +- B: Falso +- C: Depende -
Answer +
Resposta

-#### Answer: A +#### Resposta: A -The base execution context is the global execution context: it's what's accessible everywhere in your code. +O contexto base de execução é o contexto glogal: É aquilo que está acessível em qualquer lugar do código.

--- -###### 27. What's the output? +###### 27. Qual é a saída? ```javascript for (let i = 1; i < 5; i++) { @@ -803,19 +804,19 @@ for (let i = 1; i < 5; i++) { - C: `1` `2` `4` - D: `1` `3` `4` -
Answer +
Resposta

-#### Answer: C +#### Resposta: C -The `continue` statement skips an iteration if a certain condition returns `true`. +A palavra-chave `continue` pula uma iteração se a condição retorna `true`.

--- -###### 28. What's the output? +###### 28. Qual é a saída? ```javascript String.prototype.giveLydiaPizza = () => { @@ -832,19 +833,19 @@ name.giveLydiaPizza(); - C: `SyntaxError` - D: `undefined` -
Answer +
Resposta

-#### Answer: A +#### Resposta: 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` é um construtor embutido, no qual podemos adicionar propriedades. Nesse caso adicionamos um método ao seu protótipo. Tipos primitivos `string` são automaticamente convertidos em um objeto string, gerado pelo construtor `String`. Assim, todas as strings (que são objetos string) tem acesso ao método.

--- -###### 29. What's the output? +###### 29. Qual é a saída? ```javascript const a = {}; @@ -862,23 +863,23 @@ console.log(a[b]); - C: `undefined` - D: `ReferenceError` -
Answer +
Resposta

-#### Answer: B +#### Resposta: 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`. +Chaves de objeto são automaticamente convertidas em strings. Estamos tentando usar um objeto como chave do objeto `a`, com o valor de `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`. +Contudo, quando transformamos um objeto em string, ele vira um `"[Object object]"`. Então, o que estamos afirmando é `a["Object object"] = 123`. Após, tentamos a mesma coisa. `c` é outro objeto que (implicitamente) convertemos para string. Então, temos `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`. +Então, fazemos o log de `a[b]`, o que na verdade é `a["Object object"]`. Acabmos de definir esse valor, como `456`, e é isso que ele retorna.

--- -###### 30. What's the output? +###### 30. Qual é a saída? ```javascript const foo = () => console.log("First"); @@ -895,43 +896,43 @@ baz(); - C: `Second` `First` `Third` - D: `Second` `Third` `First` -
Answer +
Resposta

-#### Answer: B +#### Resposta: B -We have a `setTimeout` function and invoked it first. Yet, it was logged last. +Temos a função `setTimeout` e a invocamos por primeiro. Ainda assim, apareceu no log por último. -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. +Isso acontece pois nos navegadores, não temos apenas o nosso mecanismo de execução (runtime engine), temos também algo chamado `WebAPI`. A `WebAPI` nos da coisas como a `setTimeout` e o DOM. -After the _callback_ is pushed to the WebAPI, the `setTimeout` function itself (but not the callback!) is popped off the stack. +Depois que a função de retorno (callback) é enviada para a `WebAPI`, a função `setTimeout` (mas não seu retorno ou callback) são enviadas para fora do stack. -Now, `foo` gets invoked, and `"First"` is being logged. +Agora, `foo` é chamada, e `"First"` é adicionado ao log. -`foo` is popped off the stack, and `baz` gets invoked. `"Third"` gets logged. +`foo` é evniada para fora do stack, e `baz` é chamada. `"Third"` é adicionado ao log. -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_. +A `WebAPI` não pode simplesmente adicionar coisas ao stack sempre que ficam prontas. Ao invés, disso, todo retorno que fica pronto é enviado para algo chamado _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. +É aqui que um laço de evento começa a ocorrer. Um **laço de evento** confere o stack e o _queue_. Se o stack está livre, pega a primeira coisa que estiver na queue e coloca no stack. -`bar` gets invoked, `"Second"` gets logged, and it's popped off the stack. +`bar` é chamada, `"Second"` é adicionado ao log, e é enviado para fora do stack.

--- -###### 31. What is the event.target when clicking the button? +###### 31. qual é o event.target quando clicamos no botão? ```html
@@ -943,24 +944,24 @@ This is where an event loop starts to work. An **event loop** looks at the stack
``` -- A: Outer `div` -- B: Inner `div` +- A: A `div` mais externa +- B: A `div` mais interna - C: `button` -- D: An array of all nested elements. +- D: Um array dos elementos aninhandos. -
Answer +
Resposta

-#### Answer: C +#### Resposta: C -The deepest nested element that caused the event is the target of the event. You can stop bubbling by `event.stopPropagation` +O elemento mais interno no aninhamento que causou o evento é o alvo do evento. Você pode parar o _bubbling_ com `event.stopPropagation`.

--- -###### 32. When you click the paragraph, what's the logged output? +###### 32. Quando você clica no parágrafo, O que é adicionado ao log? ```html
@@ -975,19 +976,19 @@ The deepest nested element that caused the event is the target of the event. You - C: `p` - D: `div` -
Answer +
Resposta

-#### Answer: A +#### Resposta: 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. +Se clicarmos em `p`, veremos dois itens adicionaos ao log: `p` e `div`. Durante a propagação de eventos, existem 3 fases: capturar, adquirir o _target_, e o bubbling. Por padrão, manipuladores de eventos são executados junto a fase de bubbling (a não ser que você marque `useCapture` como `true`). Percorre do elemento aninhando mais interno, propagando para fora.

--- -###### 33. What's the output? +###### 33. Qual é a saída? ```javascript const person = { name: "Lydia" }; @@ -1005,21 +1006,21 @@ sayHi.bind(person, 21); - C: `Lydia is 21` `Lydia is 21` - D: `Lydia is 21` `function` -
Answer +
Resposta

-#### Answer: D +#### Resposta: D -With both, we can pass the object to which we want the `this` keyword to refer to. However, `.call` is also _executed immediately_! +Com ambos, podemos passar o objeto que queremos que o `this`faça referência. Contudo, `.call` é _executado imediatamente_! -`.bind.` returns a _copy_ of the function, but with a bound context! It is not executed immediately. +`.bind.` retorna uma _cópia_ da função, mas com seu contexto vinculado à cópia. E não é executado imediatamente.

--- -###### 34. What's the output? +###### 34. Qual é a saída? ```javascript function sayHi() { @@ -1034,21 +1035,21 @@ typeof sayHi(); - C: `"function"` - D: `"undefined"` -
Answer +
Resposta

-#### Answer: B +#### Resposta: B -The `sayHi` function returns the returned value of the immediately invoked function (IIFE). This function returned `0`, which is type `"number"`. +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"`. -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"`. +Para saber mais: Só existem 7 tipos já definidos: `null`, `undefined`, `boolean`, `number`, `string`, `object`, e `symbol`. `"function"` não é um tipo, uma vez que funções são objetos, elas são do tipo `"object"`.

--- -###### 35. Which of these values are falsy? +###### 35. Qual desses tem valor falsy? ```javascript 0; @@ -1062,30 +1063,30 @@ 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: Todos são falsy -
Answer +
Resposta

-#### Answer: A +#### Resposta: A -There are only six falsy values: +Existem somente seis valores falsy: - `undefined` - `null` - `NaN` - `0` -- `''` (empty string) +- `''` (string vazia) - `false` -Function constructors, like `new Number` and `new Boolean` are truthy. +Funções construtoras, como `new Number` e `new Boolean` são truthy.

--- -###### 36. What's the output? +###### 36. Qual é a sáida? ```javascript console.log(typeof typeof 1); @@ -1096,20 +1097,20 @@ console.log(typeof typeof 1); - C: `"object"` - D: `"undefined"` -
Answer +
Resposta

-#### Answer: B +#### Resposta: B -`typeof 1` returns `"number"`. -`typeof "number"` returns `"string"` +`typeof 1` retorna `"number"`. +`typeof "number"` retorna `"string"`

--- -###### 37. What's the output? +###### 37. Qual é a saída? ```javascript const numbers = [1, 2, 3]; @@ -1159,46 +1160,46 @@ depending on where you run it (it's different for every browser, node, etc.) - C: `1` `1` `2` - D: `1` `undefined` `undefined` -
Answer +
Resposta

-#### Answer: A +#### Resposta: 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. +O bloco do `catch` recebe o argumento `x`. Esse não é o mesmo `x` da variável de quando estamos passando os argumentos. A variável `x` é de escopo do seu bloco. -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`. +Depois, definimos essa variável, dentro do seu bloco, para valor `1`, e definimos o valor de `y`, que pertence a um bloco maior. Agora, nos adicionamos ao log o valor de `x`, que dentro desse bloco tem valor `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`. +Fora do bloco do `catch`. `x` ainda é `undefined`, e `y` ainda é `2`. Quando tentamos usar `console.log(x)` fora do bloco do `catch`, isso retorna `undefined`, e `y` retorna `2`.

--- -###### 39. Everything in JavaScript is either a... +###### 39. Tudo em JavaScript ou é um... -- A: primitive or object -- B: function or object -- C: trick question! only objects -- D: number or object +- A: primitivo ou um objeto +- B: função ou um object +- C: Pegadinha! Somente objetos +- D: número ou um objeto -
Answer +
Resposta

-#### Answer: A +#### Resposta: A -JavaScript only has primitive types and objects. +JavaScript tem somente tipos primitivos e objetos. -Primitive types are `boolean`, `null`, `undefined`, `bigint`, `number`, `string`, and `symbol`. +Tipos primitivos são `boolean`, `null`, `undefined`, `bigint`, `number`, `string`, e `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 implicity wrap the object 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. +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.

--- -###### 40. What's the output? +###### 40. Qual é a saída? ```javascript [[0, 1], [2, 3]].reduce( @@ -1214,21 +1215,21 @@ What differentiates a primitive from an object is that primitives do not have an - C: `[1, 2, 0, 1, 2, 3]` - D: `[1, 2, 6]` -
Answer +
Resposta

-#### Answer: C +#### Resposta: 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]`. +`[1, 2]` é nosso valor inicial. É o valor que começamos, e portanto o valor do primeiro `acc`. Durante a primeira iteração, `acc` é `[1,2]`, e `cur` é `[0, 1]`. Nós concatemos ambos, o que resulta em `[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]` +Então, `[1, 2, 0, 1]` é `acc` e `[2, 3]` é o `cur`. Concatenamos novamente, e chegamos em `[1, 2, 0, 1, 2, 3]`.

--- -###### 41. What's the output? +###### 41. Qual é a saída? ```javascript !!null; @@ -1241,46 +1242,46 @@ Then, `[1, 2, 0, 1]` is `acc` and `[2, 3]` is `cur`. We concatenate them, and ge - C: `false` `true` `true` - D: `true` `true` `false` -
Answer +
Resposta

-#### Answer: B +#### Resposta: B -`null` is falsy. `!null` returns `true`. `!true` returns `false`. +`null` é falsy. `!null` retorna `true`. `!true` retorna `false`. -`""` is falsy. `!""` returns `true`. `!true` returns `false`. +`""` é falsy. `!""` retorna `true`. `!true` retorna `false`. -`1` is truthy. `!1` returns `false`. `!false` returns `true`. +`1` é truthy. `!1` retorna `false`. `!false` retorna `true`.

--- -###### 42. What does the `setInterval` method return in the browser? +###### 42. O que o método `setInterval` retorna no navegador? ```javascript setInterval(() => console.log("Hi"), 1000); ``` -- A: a unique id -- B: the amount of milliseconds specified -- C: the passed function +- A: um id único +- B: a quantidade de millisegundos especificada +- C: a função passada - D: `undefined` -
Answer +
Resposta

-#### Answer: A +#### Resposta: A -It returns a unique id. This id can be used to clear that interval with the `clearInterval()` function. +Retorna um id único. Esse id pode ser usado para limpar o intervalo com a função `clearInterval()`.

--- -###### 43. What does this return? +###### 43. Qual é o retorno? ```javascript [..."Lydia"]; @@ -1291,12 +1292,12 @@ It returns a unique id. This id can be used to clear that interval with the `cle - C: `[[], "Lydia"]` - D: `[["L", "y", "d", "i", "a"]]` -
Answer +
Resposta

-#### Answer: A +#### Resposta: A -A string is an iterable. The spread operator maps every character of an iterable to one element. +Strings são iteráveis. O operador do spread `...` mapeia todo caractére de um iterável para um elemento.

From 78a9a84925deb542d95e37873916cef9bb309303 Mon Sep 17 00:00:00 2001 From: Guilherme Nogara Date: Thu, 20 Jun 2019 16:08:07 -0300 Subject: [PATCH 063/915] Small typo correction --- README_pt_BR.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README_pt_BR.md b/README_pt_BR.md index 5be1c3c5..64bd9504 100644 --- a/README_pt_BR.md +++ b/README_pt_BR.md @@ -178,7 +178,7 @@ Por outro lado, com a notação de ponto `.`, isso não acontece. `mouse` não t --- -###### 6. Quais são as saídas? +###### 6. Qual é a saída? ```javascript let c = { greeting: "Hey!" }; @@ -1139,7 +1139,7 @@ depending on where you run it (it's different for every browser, node, etc.) --- -###### 38. What's the output? +###### 38. Qual é a saída? ```javascript (() => { From f7a2bf540b1d0f26c51a9d7c1d1df60bce254fc5 Mon Sep 17 00:00:00 2001 From: Tanguy Coppin Date: Thu, 20 Jun 2019 22:26:24 +0200 Subject: [PATCH 064/915] Start to translate answers in French and rename french README --- README-fr.md => README_fr-FR.md | 46 ++++++++++++++++----------------- 1 file changed, 23 insertions(+), 23 deletions(-) rename README-fr.md => README_fr-FR.md (84%) diff --git a/README-fr.md b/README_fr-FR.md similarity index 84% rename from README-fr.md rename to README_fr-FR.md index 07406dfd..68a988a5 100644 --- a/README-fr.md +++ b/README_fr-FR.md @@ -36,9 +36,9 @@ sayHi(); #### Réponse: D -Within the function, we first declare the `name` variable with the `var` keyword. This means that the variable gets hoisted (memory space is set up during the creation phase) with the default value of `undefined`, until we actually get to the line where we define the variable. We haven't defined the variable yet on the line where we try to log the `name` variable, so it still holds the value of `undefined`. +Dans la fonction, nous déclarons en premier la variable `name` grâce au mot clé `var`. Cela signifie que la variable est "levée" _(hoisted)_ (l'espace mémoire est définie à la phase de création) avec pour valeur par défaut `undefined`, jusqu'à ce que le script atteigne la ligne de définition de la variable. Nous n'avons pas encore défini la variable lorsque nous essayons d'afficher la variable `name`, donc elle a toujours la valeur `undefined`. -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`. +Les variables avec le mot clé `let` (et `const`) sont "levées" _(hoisted)_, mais contrairement à `var`, elle n'est pas initialisée. Elles ne sont pas accessible avant la ligne qui les declare (initialise). C'est appelé la "zone morte temporaire". Lorsque nous essayons d'accéder aux variables avant leur déclaration, JavaScript renvoit une `ReferenceError`.

@@ -66,9 +66,9 @@ for (let i = 0; i < 3; i++) { #### Réponse: C -Because of the event queue in JavaScript, the `setTimeout` callback function is called _after_ the loop has been executed. Since the variable `i` in the first loop was declared using the `var` keyword, this value was global. During the loop, we incremented the value of `i` by `1` each time, using the unary operator `++`. By the time the `setTimeout` callback function was invoked, `i` was equal to `3` in the first example. +À cause du système de queue dans JavaScript, la fonction de rappel _(callback)_ du `setTimeout` est appellée _après_ que la boucle soit exécutée. Comme la variable `i` dans la première boucle est déclarée avec le mot clé `var`, c'est une variable global. Pendant la boucle, nous incrémentons la valeur de `i` par `1` à chaque fois, en utilisant l'opérateur arithmétique `++`. Lorsque la fonction de rappel _(callback)_ du `setTimeout` est invoquée, `i` est égal à `3` dans le premier exemple. -In the second loop, the variable `i` was declared using the `let` keyword: variables declared with the `let` (and `const`) keyword are block-scoped (a block is anything between `{ }`). During each iteration, `i` will have a new value, and each value is scoped inside the loop. +Dans la seconde boucle, la variable `i` est déclarée avec le mot clé `let` : les variables déclarées avec `let` (et `const`) ont une portée de bloc (tout ce qui est entre `{ }` est considéré comme un bloc). Pendant chaque itération, `i` aura une nouvelle valeur, et chaque valeur sera définie dans la boucle.

@@ -100,11 +100,11 @@ shape.perimeter(); #### Réponse: B -Note that the value of `diameter` is a regular function, whereas the value of `perimeter` is an arrow function. +Notez que le valeur de `diameter` est une fonction régulière, alors que `perimeter` est une fonction fléchée. -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). +Avec les fonctions fléchée, le mot clé `this` réfère à son périmètre actuel, contrairement au fonctions régulières ! Cela signifie que lorsque nous appelons `perimeter`, elle ne réfère pas à l'objet shape, mais à son périmètre actuel (`window` par exemple). -There is no value `radius` on that object, which returns `undefined`. +Il n'y a pas de valeur `radius` dans cet objet, qui retournera `undefined`.

@@ -127,16 +127,16 @@ There is no value `radius` on that object, which returns `undefined`. #### Réponse: A -The unary plus tries to convert an operand to a number. `true` is `1`, and `false` is `0`. +L'opérateur arithmétique `+` essait de convertir un opérande en une valeur numérique. `true` devient `1`, et `false` devient `0`. -The string `'Lydia'` is a truthy value. What we're actually asking, is "is this truthy value falsy?". This returns `false`. +La chaine de caractère `'Lydia'` est une value considérée comme vraie _(truthy)_. Ce que nous sommes actuellement entrain de demander, c'est "est-ce que cette valeur vraie est fausse ?". Ce qui retournera `false`.

--- -###### 5. Which one is true? +###### 5. Laquelle est vraie ? ```javascript const bird = { @@ -159,13 +159,13 @@ const mouse = { #### Réponse: A -In JavaScript, all object keys are strings (unless it's a Symbol). Even though we might not _type_ them as strings, they are always converted into strings under the hood. +En JavaScript, toutes les clé d'objet sont des chaines de caractères (sauf si c'est un Symbol). Bien que nous ne puission pas les _typer_ comme des chaines de caractères, elles sont converties en chaines de caractères sous le capot. -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. +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. -`mouse[bird.size]`: First it evaluates `bird.size`, which is `"small"`. `mouse["small"]` returns `true` +`mouse[bird.size]` : Premièrement, il évalue `bird.size`, qui est `"small"`. `mouse["small"]` retourne `true`. -However, with dot notation, this doesn't happen. `mouse` does not have a key called `bird`, which means that `mouse.bird` is `undefined`. Then, we ask for the `size` using dot notation: `mouse.bird.size`. Since `mouse.bird` is `undefined`, we're actually asking `undefined.size`. This isn't valid, and will throw an error similar to `Cannot read property "size" of undefined`. +Cependant, avec la notation par points, cela n'arrive pas. `mouse` n'a pas de clé appelée `bird`, ce qui signifie que `mouse.bird` est `undefined`. Puis, on demande `size` en utilisant la notation par point : `mouse.bird.size`. Comme `mouse.bird` est `undefined`, on demande `undefined.size`. Cela n'est pas valide, et nous aurons une erreur similaire à `Impossible de lire la propriété "size" de undefined`.

@@ -196,13 +196,13 @@ console.log(d.greeting); #### Réponse: A -In JavaScript, all objects interact by _reference_ when setting them equal to each other. +En JavaScript, tous les object intéragisent par _référence_ en plaçant égaux les uns aux autres. -First, variable `c` holds a value to an object. Later, we assign `d` with the same reference that `c` has to the object. +Premièrement, la variable `c` contaient une valeur d'objet. Plus tard, nous assignons `d` avec la même réference que `c` à l'objet. -When you change one object, you change all of them. +Quand on modifie un objet, on les modifie donc tous.

@@ -231,11 +231,11 @@ console.log(b === c); #### Réponse: 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. +`new Number()` est une fonction globale. Bien qu'il ressamble à un nombre, ce n'en est pas vraiment un : il a une poignée de fonctionnalités supplémentaire and est un objet. -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`. +Quand nous utilisons l'opérateur `==`, il vérifie seulement qu'il s'agisse de la même _valeur_. Les deux ont pour valeur `3`, donc il retourne `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.` +Cependant, quand on utilise l'opérateur `===`, les 2 valeurs _et_ type doivent être les même. `new Number()` n'est pas un nombre, c'est un **objet**, il retourne `false`.

@@ -270,7 +270,7 @@ freddie.colorChange("orange"); #### Réponse: 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. +La fonction `colorChange` est statique. Les méthodes statiques sont désignée pour vivre seulement dans le constructeur qui les a créer et ne peuvent pas être transférer aux enfants. Comme `freddie` est un enfant, la fonction n'est pas transférée et non disponible dans l'instance de `freddie` : une erreur `TypeError` est renvoyée.

@@ -407,7 +407,7 @@ We said that `this.firstName` equals `"Sarah"` and `this.lastName` equals `"Smit --- -###### 13. What are the three phases of event propagation? +###### 13. Quelle sont les trois phases de propagation des événements ? - A: Target > Capturing > Bubbling - B: Bubbling > Target > Capturing @@ -419,7 +419,7 @@ We said that `this.firstName` equals `"Sarah"` and `this.lastName` equals `"Smit #### Réponse: 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. +Durant la phase de **capture** _(capturing)_, l'événement passe par les événements parent jusqu'à l'élément ciblé. Il attient ensuite l'élément **ciblé** _(target)_, et commence à **bouillonner** _(bubbling)_. From b232c2170c31c3c5e65880a6c75031c95fe32b39 Mon Sep 17 00:00:00 2001 From: KL13NT Date: Fri, 21 Jun 2019 01:06:19 +0200 Subject: [PATCH 065/915] Started Translation into Arabic --- README_ar-EG.md | 1289 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 1289 insertions(+) create mode 100644 README_ar-EG.md diff --git a/README_ar-EG.md b/README_ar-EG.md new file mode 100644 index 00000000..d41261ad --- /dev/null +++ b/README_ar-EG.md @@ -0,0 +1,1289 @@ +# قائمة اسئلة جافاسكربت متقدمة +أنا بنشر أسئلة اختر جافاسكربت كل يوم على [انستجرام](https://www.instagram.com/theavocoder) واللي بدوري هنشرهم هنا + +من البسيط للمتطور: اختبر نفسك في الجافاسكربت, افتكر حاجات كنت ناسيها, او جهز نفسك لمقابلة عمل جايه! :muscle: :rocket: + +الاجابات في الجزء المخفي تحت, ببساطة دوس على السؤال عشان تفتح تفاصيله. اتمنالكم حظ سعيد :heart: + +--- + +###### 1. ايه اللي هيتطبع؟ + +```javascript +function sayHi() { + console.log(name); + console.log(age); + var name = "Lydia"; + let age = 21; +} + +sayHi(); +``` + +- أ: `Lydia` و `undefined` +- ب: `Lydia` و `ReferenceError` +- ج: `ReferenceError` و `21` +- د: `undefined` و `ReferenceError` + +
Answer +

+ +#### الاجابة الصحيحة: د + +جوا الدالة احنا الاول عملنا متغير `name` بالكلمة الدالة `var`. ده معناه ان المتغير ده هيكون موجود في الذاكرة في مرحلة التكوين بالقيمة `undefined` قبل ما الكود يشتغل لحد ما نوصل تحديداً للسطر اللي فيه بنحط قيمة للمتغير ده. احنا بقى لحد السطر اللي بنبطع فيه المتغير ده مكانش لسه اتعمل وبالتالي كان لسه فيه قيمة `undefined`. + +المتغيرات اللي بتتعمل بكلمة `let` و `const` بيعملوا نفس الموضوع, بس الفرق ان مبنقدرش ناخد قيم منهم الا لحد ما نضيفلهم قيم من الأساس. دي اسمها `temporal dead zone` او بالعربي "منطقة الموت المؤقتة". لما بنحاول ناخد قيمة متغير قبل ما نعمله جافاسكربت بترجع خطأ من نوع `ReferenceError` + +

+
+ +--- + +###### 2. What's the 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` and `0 1 2` +- B: `0 1 2` and `3 3 3` +- C: `3 3 3` and `0 1 2` + +
Answer +

+ +#### Answer: C + +Because of the event queue in JavaScript, the `setTimeout` callback function is called _after_ the loop has been executed. Since the variable `i` in the first loop was declared using the `var` keyword, this value was global. During the loop, we incremented the value of `i` by `1` each time, using the unary operator `++`. By the time the `setTimeout` callback function was invoked, `i` was equal to `3` in the first example. + +In the second loop, the variable `i` was declared using the `let` keyword: variables declared with the `let` (and `const`) keyword are block-scoped (a block is anything between `{ }`). During each iteration, `i` will have a new value, and each value is scoped inside the loop. + +

+
+ +--- + +###### 3. What's the output? + +```javascript +const shape = { + radius: 10, + diameter() { + return this.radius * 2; + }, + perimeter: () => 2 * Math.PI * this.radius +}; + +shape.diameter(); +shape.perimeter(); +``` + +- A: `20` and `62.83185307179586` +- B: `20` and `NaN` +- C: `20` and `63` +- D: `NaN` and `63` + +
Answer +

+ +#### Answer: B + +Note that the value of `diameter` is a regular function, whereas the value of `perimeter` is an arrow function. + +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 `undefined`. + +

+
+ +--- + +###### 4. What's the output? + +```javascript ++true; +!"Lydia"; +``` + +- A: `1` and `false` +- B: `false` and `NaN` +- C: `false` and `false` + +
Answer +

+ +#### Answer: A + +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`. + +

+
+ +--- + +###### 5. Which one is true? + +```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 + +
Answer +

+ +#### Answer: A + +In JavaScript, all object keys are strings (unless it's a Symbol). Even though we might not _type_ them as strings, they are always converted into strings under the hood. + +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. + +`mouse[bird.size]`: First it evaluates `bird.size`, which is `"small"`. `mouse["small"]` returns `true` + +However, with dot notation, this doesn't happen. `mouse` does not have a key called `bird`, which means that `mouse.bird` is `undefined`. Then, we ask for the `size` using dot notation: `mouse.bird.size`. Since `mouse.bird` is `undefined`, we're actually asking `undefined.size`. This isn't valid, and will throw an error similar to `Cannot read property "size" of undefined`. + +

+
+ +--- + +--- + +###### 6. What's the 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` + +
Answer +

+ +#### Answer: A + +In JavaScript, all objects interact by _reference_ when setting them equal to each other. + +First, variable `c` holds a value to an object. Later, we assign `d` with the same reference that `c` has to the object. + + + +When you change one object, you change all of them. + +

+
+ +--- + +###### 7. What's the 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` + +
Answer +

+ +#### Answer: 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`. + +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.` + +

+
+ +--- + +###### 8. What's the 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" }); +freddie.colorChange("orange"); +``` + +- A: `orange` +- B: `purple` +- C: `green` +- D: `TypeError` + +
Answer +

+ +#### 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. + +

+
+ +--- + +###### 9. What's the output? + +```javascript +let greeting; +greetign = {}; // Typo! +console.log(greetign); +``` + +- A: `{}` +- B: `ReferenceError: greetign is not defined` +- C: `undefined` + +
Answer +

+ +#### 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). + +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. + +

+
+ +--- + +###### 10. What happens when we do this? + +```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: `undefined` +- D: `ReferenceError` + +
Answer +

+ +#### Answer: A + +This is possible in JavaScript, because functions are objects! (Everything besides primitive types are objects) + +A function is a special type of object. The code you write yourself isn't the actual function. The function is an object with properties. This property is invocable. + +

+
+ +--- + +###### 11. What's the 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` + +
Answer +

+ +#### Answer: A + +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() { + return `${this.firstName} ${this.lastName}`; +}; +``` + +would have made `member.getFullName()` work. Why is this beneficial? Say that we added this method to the constructor itself. Maybe not every `Person` instance needed this method. This would waste a lot of memory space, since they would still have that property, which takes of memory space for each instance. Instead, if we only add it to the prototype, we just have it at one spot in memory, yet they all have access to it! + +

+
+ +--- + +###### 12. What's the 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` + +
Answer +

+ +#### Answer: A + +For `sarah`, we didn't use the `new` keyword. When using `new`, it refers to the new empty object we create. However, if you don't add `new` it 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`. + +

+
+ +--- + +###### 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 + +
Answer +

+ +#### Answer: 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 + +
Answer +

+ +#### Answer: B + +All objects have prototypes, except for the **base object**. 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. What's the output? + +```javascript +function sum(a, b) { + return a + b; +} + +sum(1, "2"); +``` + +- A: `NaN` +- B: `TypeError` +- C: `"12"` +- D: `3` + +
Answer +

+ +#### Answer: 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. What's the 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` + +
Answer +

+ +#### Answer: 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. What's the 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` + +
Answer +

+ +#### Answer: 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. What's the 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` + +
Answer +

+ +#### Answer: 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. What's the output? + +```javascript +function getAge(...args) { + console.log(typeof args); +} + +getAge(21); +``` + +- A: `"number"` +- B: `"array"` +- C: `"object"` +- D: `"NaN"` + +
Answer +

+ +#### Answer: C + +The spread operator (`...args`.) returns an array with arguments. An array is an object, so `typeof args` returns `"object"` + +

+
+ +--- + +###### 20. What's the output? + +```javascript +function getAge() { + "use strict"; + age = 21; + console.log(age); +} + +getAge(); +``` + +- A: `21` +- B: `undefined` +- C: `ReferenceError` +- D: `TypeError` + +
Answer +

+ +#### Answer: 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 value of `sum`? + +```javascript +const sum = eval("10*10+5"); +``` + +- A: `105` +- B: `"105"` +- C: `TypeError` +- D: `"10*10+5"` + +
Answer +

+ +#### 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`. + +

+
+ +--- + +###### 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. + +
Answer +

+ +#### Answer: 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. What's the output? + +```javascript +var num = 8; +var num = 10; + +console.log(num); +``` + +- A: `8` +- B: `10` +- C: `SyntaxError` +- D: `ReferenceError` + +
Answer +

+ +#### Answer: 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. What's the 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` + +
Answer +

+ +#### Answer: 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. What's the 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` + +
Answer +

+ +#### Answer: 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 + +
Answer +

+ +#### Answer: A + +The base execution context is the global execution context: it's what's accessible everywhere in your code. + +

+
+ +--- + +###### 27. What's the 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` + +
Answer +

+ +#### Answer: C + +The `continue` statement skips an iteration if a certain condition returns `true`. + +

+
+ +--- + +###### 28. What's the 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` + +
Answer +

+ +#### 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! + +

+
+ +--- + +###### 29. What's the 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` + +
Answer +

+ +#### Answer: 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. What's the 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` + +
Answer +

+ +#### Answer: 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. + +
Answer +

+ +#### Answer: 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` + +
Answer +

+ +#### 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. + +

+
+ +--- + +###### 33. What's the output? + +```javascript +const person = { name: "Lydia" }; + +function sayHi(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` + +
Answer +

+ +#### Answer: 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. What's the output? + +```javascript +function sayHi() { + return (() => 0)(); +} + +typeof sayHi(); +``` + +- A: `"object"` +- B: `"number"` +- C: `"function"` +- D: `"undefined"` + +
Answer +

+ +#### Answer: B + +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`, and `symbol`. `"function"` is not a type, since functions are objects, it's of type `"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 + +
Answer +

+ +#### Answer: A + +There are only six falsy values: + +- `undefined` +- `null` +- `NaN` +- `0` +- `''` (empty string) +- `false` + +Function constructors, like `new Number` and `new Boolean` are truthy. + +

+
+ +--- + +###### 36. What's the output? + +```javascript +console.log(typeof typeof 1); +``` + +- A: `"number"` +- B: `"string"` +- C: `"object"` +- D: `"undefined"` + +
Answer +

+ +#### Answer: B + +`typeof 1` returns `"number"`. +`typeof "number"` returns `"string"` + +

+
+ +--- + +###### 37. What's the 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` + +
Answer +

+ +#### Answer: 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, 7 x empty, 11]` + +depending on where you run it (it's different for every browser, node, etc.) + +

+
+ +--- + +###### 38. What's the 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` + +
Answer +

+ +#### Answer: 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 + +
Answer +

+ +#### Answer: 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 implicity wrap the object 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. What's the 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]` + +
Answer +

+ +#### Answer: 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. What's the output? + +```javascript +!!null; +!!""; +!!1; +``` + +- A: `false` `true` `false` +- B: `false` `false` `true` +- C: `false` `true` `true` +- D: `true` `true` `false` + +
Answer +

+ +#### Answer: 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` + +
Answer +

+ +#### Answer: 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"]]` + +
Answer +

+ +#### Answer: A + +A string is an iterable. The spread operator maps every character of an iterable to one element. + +

+
From 3746909e740b01ead952e21e70501abcd1020016 Mon Sep 17 00:00:00 2001 From: KL13NT Date: Fri, 21 Jun 2019 01:24:16 +0200 Subject: [PATCH 066/915] Started Translation into Arabic --- README_ar-EG.md | 39 +++++++++++++++++++-------------------- 1 file changed, 19 insertions(+), 20 deletions(-) diff --git a/README_ar-EG.md b/README_ar-EG.md index d41261ad..2446fd5c 100644 --- a/README_ar-EG.md +++ b/README_ar-EG.md @@ -1,4 +1,4 @@ -# قائمة اسئلة جافاسكربت متقدمة +# قائمة اسئلة جافاسكربت متقدمة أنا بنشر أسئلة اختر جافاسكربت كل يوم على [انستجرام](https://www.instagram.com/theavocoder) واللي بدوري هنشرهم هنا من البسيط للمتطور: اختبر نفسك في الجافاسكربت, افتكر حاجات كنت ناسيها, او جهز نفسك لمقابلة عمل جايه! :muscle: :rocket: @@ -39,7 +39,7 @@ sayHi(); --- -###### 2. What's the output? +###### 2. ايه اللي هيتطبع؟ ```javascript for (var i = 0; i < 3; i++) { @@ -51,25 +51,25 @@ for (let i = 0; i < 3; i++) { } ``` -- A: `0 1 2` and `0 1 2` -- B: `0 1 2` and `3 3 3` -- C: `3 3 3` and `0 1 2` +أ- `0 1 2` و `0 1 2` +ب- `0 1 2` و `3 3 3` +ج- `3 3 3` و `0 1 2` -
Answer +
الاجابة

-#### Answer: C +#### الاجابة: ج -Because of the event queue in JavaScript, the `setTimeout` callback function is called _after_ the loop has been executed. Since the variable `i` in the first loop was declared using the `var` keyword, this value was global. During the loop, we incremented the value of `i` by `1` each time, using the unary operator `++`. By the time the `setTimeout` callback function was invoked, `i` was equal to `3` in the first example. +الفنكشن اللي`setTimeout` بتشغلها بيتم تشغليها _بعد_ ما اللووب تخلص بسبب قائمة الاحداث `event queue` في جافاسكربت. بما ان اول لووب اتعملت كان المتغير بتاعها معمول بكلمة `var` اذا كان `global` وبالتالي في اللوب احنا كل شوية كنا بنزود `i` لحد ما وصل ل 3 و _بعد_ كده قامت الفنكشن اللي جوا `setTimeout` اشتغلت. ده كده اول لووب. -In the second loop, the variable `i` was declared using the `let` keyword: variables declared with the `let` (and `const`) keyword are block-scoped (a block is anything between `{ }`). During each iteration, `i` will have a new value, and each value is scoped inside the loop. +اما بقى في تاني لووب المتغير `i` كان معمول بكلمة `let` و بالتالي المنظور بتاعه `scope` محدد بالاقواس المحيطة بيه `block` وبالتالي في كل مره اللوب هتزيد هيكون في قيمة جديدة تماماً للمتغير `i` و كل قيمة من دول موجوده جوا ال`block scope` اللي هي حصلت فيه, و بالتالي هيبقى كأن البرنامج شايف 3 قيم للمتغير `i` في 3 اماكن مختلفه!

--- -###### 3. What's the output? +###### 3. ايه اللي هيتطبع؟ ```javascript const shape = { @@ -84,22 +84,21 @@ shape.diameter(); shape.perimeter(); ``` -- A: `20` and `62.83185307179586` -- B: `20` and `NaN` -- C: `20` and `63` -- D: `NaN` and `63` +أ- `20` و `62.83185307179586` +ب- `20` و `NaN` +ج- `20` و `63` +د- `NaN` و `63` -
Answer +
الاجابة

-#### Answer: B - -Note that the value of `diameter` is a regular function, whereas the value of `perimeter` is an arrow function. +#### الاجابة: ب -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). +خلي بالك من نوعية الفنكشن `diameter` و هي `regular`و نوعية الفنكشن `perimeter` واللي هي `arrow function`. -There is no value `radius` on that object, which returns `undefined`. +في النوع الاخير, الكلمة الدالة `this` بتشاور الى المحيط بالدالة دي. وده معناه اننا لما بنشغل `perimeter` احنا مش بنشاور ب`this` على `shape` بل بنشاور على المحيط و هو `window` مثلاً! +وبالتالي مفيش قيمة `radius` في النطاق ده, و بالتالي البرنامج بيدينا `undefined`.

From f73cc4ff423e7250b3eacd1b0b69af1e9aaa5716 Mon Sep 17 00:00:00 2001 From: KL13NT Date: Fri, 21 Jun 2019 01:25:55 +0200 Subject: [PATCH 067/915] Finished q.3 --- README_ar-EG.md | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/README_ar-EG.md b/README_ar-EG.md index 2446fd5c..979309ab 100644 --- a/README_ar-EG.md +++ b/README_ar-EG.md @@ -51,9 +51,9 @@ for (let i = 0; i < 3; i++) { } ``` -أ- `0 1 2` و `0 1 2` -ب- `0 1 2` و `3 3 3` -ج- `3 3 3` و `0 1 2` +أ - `0 1 2` و `0 1 2` +ب - `0 1 2` و `3 3 3` +ج - `3 3 3` و `0 1 2`
الاجابة

@@ -84,10 +84,10 @@ shape.diameter(); shape.perimeter(); ``` -أ- `20` و `62.83185307179586` -ب- `20` و `NaN` -ج- `20` و `63` -د- `NaN` و `63` +أ - `20` و `62.83185307179586` +ب - `20` و `NaN` +ج - `20` و `63` +د - `NaN` و `63`

الاجابة

From d3ad3f4da7c4e5b1d4158e9a4c7e89d69dc13c8b Mon Sep 17 00:00:00 2001 From: KL13NT Date: Fri, 21 Jun 2019 01:28:10 +0200 Subject: [PATCH 068/915] Finished q.3 --- README_ar-EG.md | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/README_ar-EG.md b/README_ar-EG.md index 979309ab..d935b106 100644 --- a/README_ar-EG.md +++ b/README_ar-EG.md @@ -51,9 +51,9 @@ for (let i = 0; i < 3; i++) { } ``` -أ - `0 1 2` و `0 1 2` -ب - `0 1 2` و `3 3 3` -ج - `3 3 3` و `0 1 2` +- أ: `0 1 2` و `0 1 2` +- ب: `0 1 2` و `3 3 3` +- ج: `3 3 3` و `0 1 2`

الاجابة

@@ -84,10 +84,10 @@ shape.diameter(); shape.perimeter(); ``` -أ - `20` و `62.83185307179586` -ب - `20` و `NaN` -ج - `20` و `63` -د - `NaN` و `63` +- أ: `20` و `62.83185307179586` +- ب: `20` و `NaN` +- ج: `20` و `63` +- د: `NaN` و `63`

الاجابة

From 90164f7e3199614c1810a00c16ad28351ee892c4 Mon Sep 17 00:00:00 2001 From: Nabil Tharwat Date: Fri, 21 Jun 2019 01:39:47 +0200 Subject: [PATCH 069/915] Update README_ar-EG.md --- README_ar-EG.md | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/README_ar-EG.md b/README_ar-EG.md index d935b106..6f8b6fdb 100644 --- a/README_ar-EG.md +++ b/README_ar-EG.md @@ -1,4 +1,5 @@ -# قائمة اسئلة جافاسكربت متقدمة +

+# قائمة اسئلة جافاسكربت متقدمة أنا بنشر أسئلة اختر جافاسكربت كل يوم على [انستجرام](https://www.instagram.com/theavocoder) واللي بدوري هنشرهم هنا من البسيط للمتطور: اختبر نفسك في الجافاسكربت, افتكر حاجات كنت ناسيها, او جهز نفسك لمقابلة عمل جايه! :muscle: :rocket: @@ -1286,3 +1287,4 @@ A string is an iterable. The spread operator maps every character of an iterable

+
From 8ad8f98536c4b5e8f3e35a9d844e1c558c8ac7a6 Mon Sep 17 00:00:00 2001 From: Nabil Tharwat Date: Fri, 21 Jun 2019 01:40:41 +0200 Subject: [PATCH 070/915] Update README_ar-EG.md --- README_ar-EG.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README_ar-EG.md b/README_ar-EG.md index 6f8b6fdb..a99688d3 100644 --- a/README_ar-EG.md +++ b/README_ar-EG.md @@ -1,4 +1,5 @@
+ # قائمة اسئلة جافاسكربت متقدمة أنا بنشر أسئلة اختر جافاسكربت كل يوم على [انستجرام](https://www.instagram.com/theavocoder) واللي بدوري هنشرهم هنا From 2afd42531b25818b9aae826bb9cac0af7b189b06 Mon Sep 17 00:00:00 2001 From: Nabil Tharwat Date: Fri, 21 Jun 2019 01:41:38 +0200 Subject: [PATCH 071/915] Update README_ar-EG.md --- README_ar-EG.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/README_ar-EG.md b/README_ar-EG.md index a99688d3..b1a61513 100644 --- a/README_ar-EG.md +++ b/README_ar-EG.md @@ -11,6 +11,8 @@ ###### 1. ايه اللي هيتطبع؟ +
+ ```javascript function sayHi() { console.log(name); @@ -21,6 +23,7 @@ function sayHi() { sayHi(); ``` +
- أ: `Lydia` و `undefined` - ب: `Lydia` و `ReferenceError` From d503913c407301929656090f2423599f5d645dab Mon Sep 17 00:00:00 2001 From: Nabil Tharwat Date: Fri, 21 Jun 2019 01:42:30 +0200 Subject: [PATCH 072/915] Update README_ar-EG.md --- README_ar-EG.md | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/README_ar-EG.md b/README_ar-EG.md index b1a61513..ae7814e5 100644 --- a/README_ar-EG.md +++ b/README_ar-EG.md @@ -45,7 +45,8 @@ sayHi(); --- ###### 2. ايه اللي هيتطبع؟ - +
+ ```javascript for (var i = 0; i < 3; i++) { setTimeout(() => console.log(i), 1); @@ -55,6 +56,7 @@ for (let i = 0; i < 3; i++) { setTimeout(() => console.log(i), 1); } ``` +
- أ: `0 1 2` و `0 1 2` - ب: `0 1 2` و `3 3 3` @@ -75,7 +77,8 @@ for (let i = 0; i < 3; i++) { --- ###### 3. ايه اللي هيتطبع؟ - +
+ ```javascript const shape = { radius: 10, @@ -88,6 +91,7 @@ const shape = { shape.diameter(); shape.perimeter(); ``` +
- أ: `20` و `62.83185307179586` - ب: `20` و `NaN` From e0e96047e8b02d54110045fe8a0179c65e28361c Mon Sep 17 00:00:00 2001 From: Nabil Tharwat Date: Fri, 21 Jun 2019 01:44:03 +0200 Subject: [PATCH 073/915] Update README_ar-EG.md --- README_ar-EG.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README_ar-EG.md b/README_ar-EG.md index ae7814e5..54c0f44f 100644 --- a/README_ar-EG.md +++ b/README_ar-EG.md @@ -67,7 +67,7 @@ for (let i = 0; i < 3; i++) { #### الاجابة: ج -الفنكشن اللي`setTimeout` بتشغلها بيتم تشغليها _بعد_ ما اللووب تخلص بسبب قائمة الاحداث `event queue` في جافاسكربت. بما ان اول لووب اتعملت كان المتغير بتاعها معمول بكلمة `var` اذا كان `global` وبالتالي في اللوب احنا كل شوية كنا بنزود `i` لحد ما وصل ل 3 و _بعد_ كده قامت الفنكشن اللي جوا `setTimeout` اشتغلت. ده كده اول لووب. +الفنكشن اللي`setTimeout` بتشغلها بيتم تشغليها _بعد_ ما اللووب تخلص بسبب قائمة الاحداث `event queue` في جافاسكربت. بما ان اول لووب اتعملت كان المتغير بتاعها معمول بكلمة `var` اذاً كان `global` وبالتالي في اللوب احنا كل شوية كنا بنزود `i` لحد ما وصل ل 3 و _بعد_ كده قامت الفنكشن اللي جوا `setTimeout` اشتغلت. ده كده اول لووب. اما بقى في تاني لووب المتغير `i` كان معمول بكلمة `let` و بالتالي المنظور بتاعه `scope` محدد بالاقواس المحيطة بيه `block` وبالتالي في كل مره اللوب هتزيد هيكون في قيمة جديدة تماماً للمتغير `i` و كل قيمة من دول موجوده جوا ال`block scope` اللي هي حصلت فيه, و بالتالي هيبقى كأن البرنامج شايف 3 قيم للمتغير `i` في 3 اماكن مختلفه! From 856af98f4ffc988f963b71168a7bd7bb7d9b22f8 Mon Sep 17 00:00:00 2001 From: synccheng Date: Fri, 21 Jun 2019 11:31:37 +0800 Subject: [PATCH 074/915] :memo: Translate & Typo --- README-zh_CN.md | 32 ++++++++++++++++---------------- 1 file changed, 16 insertions(+), 16 deletions(-) diff --git a/README-zh_CN.md b/README-zh_CN.md index bc21b456..91bc8fdf 100644 --- a/README-zh_CN.md +++ b/README-zh_CN.md @@ -308,8 +308,8 @@ function bark() { bark.animal = 'dog' ``` -- A: Nothing, this is totally fine! -- B: `SyntaxError`. You cannot add properties to a function this way. +- A: 正常运行! +- B: `SyntaxError`. 你不能通过这种方式给函数增加属性。 - C: `undefined` - D: `ReferenceError` @@ -657,10 +657,10 @@ const sum = eval('10*10+5') 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. +- A: 永远,数据不会丢失。 +- B: 当用户关掉标签页时。 +- C: 当用户关掉整个浏览器,而不只是关掉标签页。 +- D: 当用户关闭电脑时。
答案

@@ -857,9 +857,9 @@ console.log(a[b]) 对象的键被自动转换为字符串。我们试图将一个对象 `b` 设置为对象 `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`。

@@ -934,7 +934,7 @@ WebAPI 不能随时向栈内添加内容。相反,它将回调函数推到名 - A: Outer `div` - B: Inner `div` - C: `button` -- D: An array of all nested elements. +- D: 一个包含所有嵌套元素的数组。
答案

@@ -1167,10 +1167,10 @@ console.log(numbers) ###### 39. JavaScript 中的一切都是? -- A: primitive or object -- B: function or object -- C: trick question! only objects -- D: number or object +- A: 基本类型与对象 +- B: 函数与对象 +- C: 只有对象 +- D: 数字与对象 -

答案

@@ -1250,9 +1250,9 @@ JavaScript 只有基本类型和对象。 setInterval(() => console.log('Hi'), 1000) ``` -- A: a unique id -- B: the amount of milliseconds specified -- C: the passed function +- A: 一个唯一的id +- B: 该方法指定的毫秒数 +- C: 传递的函数 - D: `undefined`

答案 From d9d846c13028eb84f65e6c884d9942cac734d361 Mon Sep 17 00:00:00 2001 From: re4388 Date: Fri, 21 Jun 2019 14:22:19 +0800 Subject: [PATCH 075/915] delete extra separate line in README.md --- README.md | 1 - 1 file changed, 1 deletion(-) diff --git a/README.md b/README.md index 916fa133..3d058815 100644 --- a/README.md +++ b/README.md @@ -174,7 +174,6 @@ However, with dot notation, this doesn't happen. `mouse` does not have a key cal --- ---- ###### 6. What's the output? From 0a702c130a45083d5391f87a0dc774d0749d763b Mon Sep 17 00:00:00 2001 From: re4388 Date: Fri, 21 Jun 2019 14:32:42 +0800 Subject: [PATCH 076/915] Remove extra separate line in README-zh_CN.md --- README-zh_CN.md | 1 - 1 file changed, 1 deletion(-) diff --git a/README-zh_CN.md b/README-zh_CN.md index bc21b456..06f8f9e2 100644 --- a/README-zh_CN.md +++ b/README-zh_CN.md @@ -168,7 +168,6 @@ const mouse = { --- ---- ###### 6. 输出是什么? From 1a4aeb46b82e023d11d272c5793bb4eaceef1298 Mon Sep 17 00:00:00 2001 From: re4388 Date: Fri, 21 Jun 2019 14:36:46 +0800 Subject: [PATCH 077/915] Remove extra separate line --- README-bs_BS.md | 1 - 1 file changed, 1 deletion(-) diff --git a/README-bs_BS.md b/README-bs_BS.md index 75e47080..57306554 100644 --- a/README-bs_BS.md +++ b/README-bs_BS.md @@ -215,7 +215,6 @@ To nije valjano, a bit će u pitanju pogreška slična onoj * * * * * -* * * * * ###### 6. Što je izlaz? From f0ede076b75c32fc0f7daed8d0fa0f23bb3e38e5 Mon Sep 17 00:00:00 2001 From: re4388 Date: Fri, 21 Jun 2019 14:37:15 +0800 Subject: [PATCH 078/915] Remove extra separate line --- README-de_DE.md | 1 - 1 file changed, 1 deletion(-) diff --git a/README-de_DE.md b/README-de_DE.md index cefffd01..47d99e8d 100644 --- a/README-de_DE.md +++ b/README-de_DE.md @@ -172,7 +172,6 @@ Mit der Dot Notation ist das nicht der Fall. `mouse` hat keinen Key namens `bird --- ---- ###### 6. Was ist der Output? From f8d8614b803a19a63fbb856aa7363187a4d7a7eb Mon Sep 17 00:00:00 2001 From: re4388 Date: Fri, 21 Jun 2019 14:37:40 +0800 Subject: [PATCH 079/915] Remove extra separate line --- README-vi.md | 1 - 1 file changed, 1 deletion(-) diff --git a/README-vi.md b/README-vi.md index b9b7c3be..0fcd67cd 100644 --- a/README-vi.md +++ b/README-vi.md @@ -169,7 +169,6 @@ Tuy nhiên, khi chúng ta sử dụng dấu chấm `.`, điều trên không cò --- ---- ###### 6. Ouput là gì? From bbe4cab0fb870b2a53dc6c0fa938d48f8026156e Mon Sep 17 00:00:00 2001 From: re4388 Date: Fri, 21 Jun 2019 14:38:12 +0800 Subject: [PATCH 080/915] Remove extra separate line --- README_ru-RU.md | 1 - 1 file changed, 1 deletion(-) diff --git a/README_ru-RU.md b/README_ru-RU.md index b8e918df..38cd0efb 100644 --- a/README_ru-RU.md +++ b/README_ru-RU.md @@ -174,7 +174,6 @@ JavaScript интерпретирует (или распаковывает) оп --- ---- ###### 6. Что будет в консоли? From e43b5adf9f0f472304949e95ca1d3870656f0cdd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Adri=C3=A1n?= <22575055+aguadotzn@users.noreply.github.com> Date: Fri, 21 Jun 2019 10:52:14 +0200 Subject: [PATCH 081/915] Questions 30-42 --- README-ES.md | 147 ++++++++++++++++++++++++++------------------------- 1 file changed, 74 insertions(+), 73 deletions(-) diff --git a/README-ES.md b/README-ES.md index 96b2c57c..9f28798d 100644 --- a/README-ES.md +++ b/README-ES.md @@ -915,14 +915,14 @@ Aquí es donde un bucle de eventos comienza a funcionar. Un **lazo de evento** m -Se invoca el `bar`, se registra el ``"Second"`` y se quita de la pila. +Se invoca el `bar`, se registra el `"Second"` y se quita de la pila.

--- -###### 31. What is the event.target when clicking the button? +###### 31. ¿Cuál es la referencia al objeto que lanza el evento cuando se hace click en el botón? ```html
@@ -939,19 +939,19 @@ Se invoca el `bar`, se registra el ``"Second"`` y se quita de la pila. - C: `button` - D: An array of all nested elements. -
Answer +
Solución

-#### Answer: C +#### Respuesta correcta: C -The deepest nested element that caused the event is the target of the event. You can stop bubbling by `event.stopPropagation` +El elemento anidado más profundo que causa el evento es el destino de ese evento.

--- -###### 32. When you click the paragraph, what's the logged output? +###### 32. Al hacer click en el párrafo, ¿qué se muestra por pantalla? ```html
@@ -966,19 +966,19 @@ The deepest nested element that caused the event is the target of the event. You - C: `p` - D: `div` -
Answer +
Solución

-#### Answer: A +#### Respuesta correcta: 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. +Si hacemos clic en `p`, vemos dos _outputs_: `p` y `div`. Durante la propagación del evento, hay 3 [fases](https://www.sitepoint.com/event-bubbling-javascript/): _capturing_, _target_ y _bubbling_. De forma predeterminada, los controladores de eventos se ejecutan en la fase uno (a menos que se establezca `useCapture` en `true`). Va desde el elemento anidado más profundo hacia el exterior.

--- -###### 33. What's the output? +###### 33. ¿Qué devuelve la siguiente función? ```javascript const person = { name: "Lydia" }; @@ -996,21 +996,21 @@ sayHi.bind(person, 21); - C: `Lydia is 21` `Lydia is 21` - D: `Lydia is 21` `function` -
Answer +
Solución

-#### Answer: D +#### Respuesta correcta: D -With both, we can pass the object to which we want the `this` keyword to refer to. However, `.call` is also _executed immediately_! +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.` returns a _copy_ of the function, but with a bound context! It is not executed immediately. +`.bind` devuelve una copia de la función, pero con un contexto enlazado. Es decir, no se ejecuta de inmediato.

--- -###### 34. What's the output? +###### 34. ¿Qué devuelve la siguiente función? ```javascript function sayHi() { @@ -1025,21 +1025,21 @@ typeof sayHi(); - C: `"function"` - D: `"undefined"` -
Answer +
Solución

-#### Answer: B +#### Respuesta correcta: B -The `sayHi` function returns the returned value of the immediately invoked function (IIFE). This function returned `0`, which is type `"number"`. +La función `sayHi` devuelve el valor devuelto de la función invocada inmediatamente ([IIFE](https://developer.mozilla.org/es/docs/Glossary/IIFE)). Esta función devuelve `0`, que es el tipo `"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"`. +En JS solo hay 7 tipos incorporados (En inglés se llaman _built-in types_, y pueden identificarse con el operador `typeof`. Más información [aquí](https://www.oreilly.com/library/view/you-dont-know/9781491905159/ch01.html)): `null`,` undefined`, `boolean`,` number`, `string`,` object` y `symbol`. `"function"` no es un tipo, ya que las funciones son objetos, es de tipo `"object"`.

--- -###### 35. Which of these values are falsy? +###### 35. ¿Cuáles de estos valores son falsos? ```javascript 0; @@ -1055,28 +1055,29 @@ undefined; - C: `0`, `''`, `new Boolean(false)`, `undefined` - D: All of them are falsy -
Answer +
Solución

-#### Answer: A +#### Respuesta correcta: A -There are only six falsy values: +Solo hay seis valores falsos: - `undefined` - `null` - `NaN` - `0` -- `''` (empty string) +- `''` (cadena vacía) - `false` -Function constructors, like `new Number` and `new Boolean` are truthy. + +Los constructores de funciones, como `new Number` y `new Boolean` son correctos.

--- -###### 36. What's the output? +###### 36. ¿Qué devuelve la siguiente función? ```javascript console.log(typeof typeof 1); @@ -1087,20 +1088,20 @@ console.log(typeof typeof 1); - C: `"object"` - D: `"undefined"` -
Answer +
Solución

-#### Answer: B +#### Respuesta correcta: B -`typeof 1` returns `"number"`. -`typeof "number"` returns `"string"` +`typeof 1` devuelve `"number" `. +`typeof "number"` devuelve `"string"`

--- -###### 37. What's the output? +###### 37. ¿Qué devuelve la siguiente función? ```javascript const numbers = [1, 2, 3]; @@ -1113,23 +1114,23 @@ console.log(numbers); - C: `[1, 2, 3, 7 x empty, 11]` - D: `SyntaxError` -
Answer +
Solución

-#### Answer: C +#### Respuesta correcta: 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: +Cuando se establece un valor en un elemento de una matriz que excede la longitud de la matriz, JS crea algo llamado "ranuras vacías". Estos realmente tienen el valor de `undefined`, pero se podrá ver algo como: `[1, 2, 3, 7 x empty, 11]` -depending on where you run it (it's different for every browser, node, etc.) +dependiendo de dónde lo ejecute (es diferente para cada navegador, nodo, etc.)

--- -###### 38. What's the output? +###### 38. ¿Qué devuelve la siguiente función? ```javascript (() => { @@ -1150,46 +1151,46 @@ depending on where you run it (it's different for every browser, node, etc.) - C: `1` `1` `2` - D: `1` `undefined` `undefined` -
Answer +
Solución

-#### Answer: A +#### Respuesta correcta: 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. +El bloque `catch` recibe el argumento` x`. Este no es el mismo `x` que la variable cuando pasamos los argumentos. Esta variable `x` tiene un ámbito de bloque. -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`. +Más adelante, establecemos esta variable de ámbito de bloque igual a `1`, y establecemos el valor de la variable `y`. Ahora, registramos la variable de ámbito de bloque `x`, que es igual a `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`. +Fuera del bloque `catch`,` x` sigue siendo `undefined`, e `y` es `2`. Cuando queremos `console.log (x)` fuera del bloque `catch`, devuelve `undefined`, y `y` devuelve` 2`.

--- -###### 39. Everything in JavaScript is either a... +###### 39. Todo en Javascript es o bien un(a).. -- A: primitive or object -- B: function or object -- C: trick question! only objects -- D: number or object +- A: tipo primitivo o un objeto +- B: función u objeto +- C: ¡pregunta trampa! solo objetos +- D: número u objeto -
Answer +
Solución

-#### Answer: A +#### Respuesta correcta: A -JavaScript only has primitive types and objects. +JavaScript solo tiene tipos y objetos primitivos. -Primitive types are `boolean`, `null`, `undefined`, `bigint`, `number`, `string`, and `symbol`. +Los tipos primitivos son `boolean`, `null`, `undefined`, `bigint`, `number`, `string` y `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 implicity wrap the object 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. +Lo que diferencia a una tipo primitivo de un objeto es que los primeros no tienen propiedades o métodos; sin embargo, se puede ver que `'foo'.toUpperCase ()` se evalúa como `' FOO'` y no da como resultado un` TypeError`. Esto se debe a que cuando se intenta acceder a una propiedad o método en un tipo primitivo, como una cadena, JavaScript envolverá implícitamente el objeto utilizando una de las clases de envoltura, por ejemplo `string`, y luego descartará la envoltura inmediatamente después de evaluar la expresión. Todas los tipos primitivos excepto `null` y `undefined` poseen este comportamiento.

--- -###### 40. What's the output? +###### 40. ¿Qué devuelve la siguiente función? ```javascript [[0, 1], [2, 3]].reduce( @@ -1205,21 +1206,21 @@ What differentiates a primitive from an object is that primitives do not have an - C: `[1, 2, 0, 1, 2, 3]` - D: `[1, 2, 6]` -
Answer +
Solución

-#### Answer: C +#### Respuesta correcta: 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]`. +`[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]`. -Then, `[1, 2, 0, 1]` is `acc` and `[2, 3]` is `cur`. We concatenate them, and get `[1, 2, 0, 1, 2, 3]` +Entonces, `[1, 2, 0, 1]` es `acc` y` [2, 3]` es `cur`. Los concatenamos, y obtenemos `[1, 2, 0, 1, 2, 3]`

--- -###### 41. What's the output? +###### 41. ¿Qué devuelve la siguiente función? ```javascript !!null; @@ -1232,46 +1233,46 @@ Then, `[1, 2, 0, 1]` is `acc` and `[2, 3]` is `cur`. We concatenate them, and ge - C: `false` `true` `true` - D: `true` `true` `false` -
Answer +
Solución

-#### Answer: B +#### Respuesta correcta: B -`null` is falsy. `!null` returns `true`. `!true` returns `false`. +`null` es falso. `! null` devuelve `true`. `! true` devuelve `false`. -`""` is falsy. `!""` returns `true`. `!true` returns `false`. +`" "` es falso. `!" "` devuelve `true`. `! true` devuelve `false`. -`1` is truthy. `!1` returns `false`. `!false` returns `true`. +'1' es verdadero. `! 1` devuelve `false`. `! false` devuelve `true`.

--- -###### 42. What does the `setInterval` method return? +###### 42. ¿Qué devuelveel método `setInterval`? ```javascript setInterval(() => console.log("Hi"), 1000); ``` -- A: a unique id -- B: the amount of milliseconds specified -- C: the passed function +- A: una id único +- B: la cantidad de milisegundos especificada +- C: la función pasada - D: `undefined` -
Answer +
Solución

-#### Answer: A +#### Respuesta correcta: A -It returns a unique id. This id can be used to clear that interval with the `clearInterval()` function. +Devuelve una identificación única, un id único. Este id se puede usar para borrar ese intervalo con la función `clearInterval ()`.

--- -###### 43. What does this return? +###### 43. ¿Qué devuelve la siguiente función? ```javascript [..."Lydia"]; @@ -1282,12 +1283,12 @@ It returns a unique id. This id can be used to clear that interval with the `cle - C: `[[], "Lydia"]` - D: `[["L", "y", "d", "i", "a"]]` -
Answer +
Solución

-#### Answer: A +#### Respuesta correcta: A -A string is an iterable. The spread operator maps every character of an iterable to one element. +Una cadena es un iterable. El [operador de propagación](https://developer.mozilla.org/es/docs/Web/JavaScript/Referencia/Operadores/Spread_operator) asigna todos los caracteres de un iterable a un elemento.

From ed56508b73b935971509fee8cfa57fcd22c60f60 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Adri=C3=A1n?= <22575055+aguadotzn@users.noreply.github.com> Date: Fri, 21 Jun 2019 11:00:57 +0200 Subject: [PATCH 082/915] Correct some typos --- README-ES.md | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/README-ES.md b/README-ES.md index 9f28798d..358e3c92 100644 --- a/README-ES.md +++ b/README-ES.md @@ -164,9 +164,9 @@ 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 `No se puede leer la propiedad" tamaño "de undefined` +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`

@@ -194,7 +194,7 @@ console.log(d.greeting); #### Respuesta correcta: A -En JavaScript, TODOS los objetos interactúan por referencia, de modo que cuando se establecen iguales o pasan a una función, todos apuntan a la misma ubicación, de modo que cuando cambia un objeto, los cambia a todos. +En JavaScript, TODOS los objetos interactúan por referencia, de modo que cuando se establecen iguales o pasan a una función, todos apuntan a la misma ubicación. De esta manera cuando cambia un objeto, los cambia a todos. Primero, la variable `c` tiene un valor para un objeto. Más tarde, asignamos `d` con la misma referencia que` c` tiene al objeto. @@ -233,7 +233,7 @@ console.log(b === c); Cuando usamos el operador `==`, solo verifica si tiene el mismo _valor_. Ambos tienen el valor de `3`, por lo que devuelve` true`. -Sin embargo, cuando usamos el operador `===`, tanto el valor _ como el tipo deben ser iguales. No es: `new Number ()` no es un número, es un ** objeto **. Ambos devuelven "falso". +Sin embargo, cuando usamos el operador `===`, tanto el **valor** como el **tipo** deben ser iguales. Entonces: `new Number ()` no es un número, es un **objeto**. Ambos devuelven "false".

@@ -268,7 +268,7 @@ freddie.colorChange("orange"); #### Respuesta correcta: D -La función `colorChange` es estática. Los métodos estáticos están diseñados para _vivir_ solo en el constructor en el que se crean y no se pueden transmitir a ningún elemento secundario. Como `freddie` es un niño, la función no se transmite y no está disponible en la instancia de` freddie`: por lo tanto se lanza un `TypeError`. +La función `colorChange` es estática. Los métodos estáticos están diseñados para _vivir_ solo en el constructor en el que se crean y no se pueden transmitir a ningún elemento secundario. Como `freddie` es un niño, la función no se transmite y no está disponible en la instancia de `freddie`: por lo tanto se lanza un `TypeError`.

@@ -292,7 +292,7 @@ console.log(greetign); #### Respuesta correcta: A -Lo que hace JS aquí es registrar el objeto debido a que acabamos de crear un objeto vacío en el objeto global. Cuando escribimos erróneamente `greeting` como` greetign`, el intérprete de JS ve esto como `global.greetign = {}` (o `window.greetign = {}` en un navegador). +Lo que hace JS aquí es registrar el objeto debido a que acabamos de crear un objeto vacío en el objeto global. Cuando escribimos erróneamente `greeting` como `greetign`, el intérprete de JS ve esto como `global.greetign = {}` (o `window.greetign = {}` en un navegador). Para evitar esto, podemos usar el ["uso estricto"](https://developer.mozilla.org/es/docs/Web/JavaScript/Referencia/Modo_estricto). Esto asegura que se haya declarado una variable antes de establecerla igual a cualquier cosa. @@ -321,7 +321,7 @@ bark.animal = "dog"; #### Respuesta correcta: A -Esto es perfectamente posible en JavaScript, porque las funciones son objetos (Recuerda: Todo aparte de los tipos primitivos son objetos en JS) +Esto es perfectamente posible en JavaScript, porque las funciones son objetos (Recuerda: **todo** aparte de los tipos primitivos son objetos en JS) Una función es un tipo especial de objeto. El código que escribes tú mismo no es la función real. La función es un objeto con propiedades. Esta propiedad es invocable. @@ -1183,7 +1183,7 @@ JavaScript solo tiene tipos y objetos primitivos. Los tipos primitivos son `boolean`, `null`, `undefined`, `bigint`, `number`, `string` y `symbol`. -Lo que diferencia a una tipo primitivo de un objeto es que los primeros no tienen propiedades o métodos; sin embargo, se puede ver que `'foo'.toUpperCase ()` se evalúa como `' FOO'` y no da como resultado un` TypeError`. Esto se debe a que cuando se intenta acceder a una propiedad o método en un tipo primitivo, como una cadena, JavaScript envolverá implícitamente el objeto utilizando una de las clases de envoltura, por ejemplo `string`, y luego descartará la envoltura inmediatamente después de evaluar la expresión. Todas los tipos primitivos excepto `null` y `undefined` poseen este comportamiento. +Lo que diferencia a un tipo primitivo de un objeto es que los primeros no tienen propiedades o métodos; sin embargo, se puede ver que `'foo'.toUpperCase ()` se evalúa como `'FOO'` y no da como resultado un `TypeError`. Esto se debe a que cuando se intenta acceder a una propiedad o método en un tipo primitivo, como una cadena, JavaScript envolverá implícitamente el objeto utilizando una de las clases de envoltura, por ejemplo `string`, y luego descartará la envoltura inmediatamente después de evaluar la expresión. Todas los tipos primitivos excepto `null` y `undefined` poseen este comportamiento.

From fe2c5bfd1552923f96c7697e52b683603ad9bbc2 Mon Sep 17 00:00:00 2001 From: KL13NT Date: Fri, 21 Jun 2019 14:39:38 +0200 Subject: [PATCH 083/915] Finished Q.13 --- README_ar-EG.md | 336 ++++++++++++++++++++++++++++++++++-------------- 1 file changed, 240 insertions(+), 96 deletions(-) diff --git a/README_ar-EG.md b/README_ar-EG.md index d935b106..247e318b 100644 --- a/README_ar-EG.md +++ b/README_ar-EG.md @@ -1,4 +1,6 @@ -# قائمة اسئلة جافاسكربت متقدمة +
+ +# قائمة اسئلة جافاسكربت متقدمة أنا بنشر أسئلة اختر جافاسكربت كل يوم على [انستجرام](https://www.instagram.com/theavocoder) واللي بدوري هنشرهم هنا من البسيط للمتطور: اختبر نفسك في الجافاسكربت, افتكر حاجات كنت ناسيها, او جهز نفسك لمقابلة عمل جايه! :muscle: :rocket: @@ -8,6 +10,7 @@ --- ###### 1. ايه اللي هيتطبع؟ +
```javascript function sayHi() { @@ -19,6 +22,7 @@ function sayHi() { sayHi(); ``` +
- أ: `Lydia` و `undefined` - ب: `Lydia` و `ReferenceError` @@ -40,6 +44,7 @@ sayHi(); --- ###### 2. ايه اللي هيتطبع؟ +
```javascript for (var i = 0; i < 3; i++) { @@ -50,6 +55,7 @@ for (let i = 0; i < 3; i++) { setTimeout(() => console.log(i), 1); } ``` +
- أ: `0 1 2` و `0 1 2` - ب: `0 1 2` و `3 3 3` @@ -70,6 +76,7 @@ for (let i = 0; i < 3; i++) { --- ###### 3. ايه اللي هيتطبع؟ +
```javascript const shape = { @@ -83,6 +90,7 @@ const shape = { shape.diameter(); shape.perimeter(); ``` +
- أ: `20` و `62.83185307179586` - ب: `20` و `NaN` @@ -104,32 +112,36 @@ shape.perimeter(); --- -###### 4. What's the output? +###### 4. ايه اللي هيتطبع؟ +
```javascript +true; !"Lydia"; ``` +
-- A: `1` and `false` -- B: `false` and `NaN` -- C: `false` and `false` +- أ: `1` و `false` +- ب: `NaN` و `false` +- ج: `false` و `false` -
Answer +
الاجابة

-#### Answer: A +#### الاجابة الصحيحة: أ +علامة الجمع تحاول دائما ان تغير قيم من قيم مدخلاتها الى رقم باعتبار ان اي قيمة حقيقية ايجابية `true` يتم تحويلها لرقم `1` و القيم السالبية `false` تتحول الى `0`. 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`. +و في الحالة دي القيمة الكتابية `'Lydia'` تعتبر ايجابية. هنا بقى السؤال: "هل القيمه الايجابيه دي سالبيه؟ و بالتالي الاجابة لا اللي هي `false`.

--- -###### 5. Which one is true? +###### 5. اختر الاجابة الصحيحة +
```javascript const bird = { @@ -141,24 +153,35 @@ const mouse = { 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 +- أ: `mouse.bird.size` متنفعش +- ب: `mouse[bird.size]` متنفعش +- ج: mouse[bird["size"]]` متنفعش +- د: كلهم ينفعوا -
Answer +
الاجابة

-#### Answer: A +#### الاجابة الصحيحة: أ -In JavaScript, all object keys are strings (unless it's a Symbol). Even though we might not _type_ them as strings, they are always converted into strings under the hood. +في جافاسكربت كل مفاتيح العناصر `object keys` من النوع `string` الا في حالة الـ `symbol`. وعلى الرغم من اننا ممكن منكتبهمش في شكل `string` فهما دايماً بيتحولوا ل`string` +بص المثال: +

-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. +```javascriptlet obj = { + size: 'big' +} +``` +
+ +في المثال ده احنا عملنا عنصر و كان ليه مفتاح اسمه size. شكل size احنا عاملينه من غير علامة التنصيص `""` ولكن لما البرنامج بيشتغل بيتم تحويلها الى سترنج و بالتالي بتكون في شكل `"size"` -`mouse[bird.size]`: First it evaluates `bird.size`, which is `"small"`. `mouse["small"]` returns `true` +غير بقى ان جافاسكربت بتفك كل جمله لوحدها. ده معناه انها لما بنستعمل علامات ال `[]` واسمها `bracket notation` هتفضل تمشي من اول `[` لحد ما توصل للي يقفله اللي هو `]`. و بعد كده هتقوم مشغله الجمله بعد ما تعرف ان الجمله دي مفيهاش اخطاء. -However, with dot notation, this doesn't happen. `mouse` does not have a key called `bird`, which means that `mouse.bird` is `undefined`. Then, we ask for the `size` using dot notation: `mouse.bird.size`. Since `mouse.bird` is `undefined`, we're actually asking `undefined.size`. This isn't valid, and will throw an error similar to `Cannot read property "size" of undefined`. +فا عشان كده عندنا `mouse[bird.size]` الاول هتجيب `bird.size` اللي قيمته `"small"` وبالتالي تبقى الجمله `mouse["small"]` هترجع `true` + +ولكن لما بنستعمل ال `dot notation` مبيحصلش كده. `mouse` ملوش مفتاح اسمه `bird` و بالتالي احنا بنطلب قيمه موجوده جوا حاجه مش موجودة اصلاً و بالتالي بيرجعلنا خطأ `cannot read property of undefined`.

@@ -167,7 +190,8 @@ However, with dot notation, this doesn't happen. `mouse` does not have a key cal --- -###### 6. What's the output? +###### 6. ايه اللي هيتطبع؟ +
```javascript let c = { greeting: "Hey!" }; @@ -177,32 +201,35 @@ d = c; c.greeting = "Hello"; console.log(d.greeting); ``` +
-- A: `Hello` -- B: `Hey` -- C: `undefined` -- D: `ReferenceError` -- E: `TypeError` +- أ: `Hello` +- ب: `Hey` +- ج: `undefined` +- د: `ReferenceError` +- هـ: `TypeError` -
Answer +
الاجابة

-#### Answer: A +#### الاجابة الصحيحة: أ -In JavaScript, all objects interact by _reference_ when setting them equal to each other. +في جافاسكربت كل العناصر `objects` بيتعاملوا بالـ`reference` لما بنساويهم ببعض. ده معناه ان الاوبجكت مش بيتعمل منه نسخه جديدة و انما بيتم الاشارة اليه بأسم جديد مش اكتر. -First, variable `c` holds a value to an object. Later, we assign `d` with the same reference that `c` has to the object. +في الاول المتغير `c` جواه قيمة اوبجكت و بعد كده بنقوم عاملين اشارة للاوبجكت ده عن طريق المتغير `d` +. -When you change one object, you change all of them. +وبالتالي لما بتغير متغير واحد منهم انت بتغير الاتنين لان الاتنين بيشيروا لنفس العنصر في الميموري.

--- -###### 7. What's the output? +###### 7. ايه اللي هيتطبع؟ +
```javascript let a = 3; @@ -213,29 +240,31 @@ 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` +- أ: `true` `false` `true` +- ب: `false` `false` `true` +- ج: `true` `false` `false` +- د: `false` `true` `true` -
Answer +
الاجابة

-#### Answer: 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. +`new Number()` ده `constructor` مبني في اللغه و على الرغم من ان شكل القيمه اللي هتطلع منه مجرد رقم `primitive` لكن الحقيقه ان القيمة اللي هتيجي `object` وهيكون فيه زيادات زي ال`methods` وهكذا. -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`. +لما بنستعمل علامة المساواه `==` احنا بنشوف بس لو القيمتين اللي بنقارنهم ليهم نفس **القيمة** فقط ولا لا. الاتنين ليهم قيمة `3` وبالتالي هترجع `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.` +اما بقى لما بنستعمل المساواة `===` احنا بنشوف **القيمة** و **النوع** و بالتالي بما ان الاتنين `object` بس موجودين في اماكن مختلفه في الميموري اذاً احنا مش عاملين اشارة لنفس العنصر و بالتالي هترجع `false`.

--- -###### 8. What's the output? +###### 8. ايه اللي هيتطبع؟ +
```javascript class Chameleon { @@ -252,51 +281,55 @@ class Chameleon { const freddie = new Chameleon({ newColor: "purple" }); freddie.colorChange("orange"); ``` +
-- A: `orange` -- B: `purple` -- C: `green` -- D: `TypeError` +- أ: `orange` +- ب: `purple` +- ج: `green` +- د: `TypeError` -
Answer +
الاجابة

-#### 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. +الدالة `colorChange` من نوع `static` و بالتالي هي مموجوده فقط في ال`constructor` اللي بتتعمل فيه و مش بتروح لأي عنصر بيتعمل من ال`class` ده و بما ان `freddie` ده عنصر معمول من الكلاس ده فا الدالة `colorChange` مش بتروحله و بالتالي مش موجوده معاه و عشان كده هتدينا `TypeError`.

--- -###### 9. What's the output? +###### 9. ايه اللي هيتطبع؟ +
```javascript let greeting; greetign = {}; // Typo! console.log(greetign); ``` +
-- A: `{}` -- B: `ReferenceError: greetign is not defined` -- C: `undefined` +- أ: `{}` +- ب: `ReferenceError: greetign is not defined` +- ج: `undefined` -
Answer +
الاجابة

-#### 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). +بتطبع العنصر الفاضي لأننا عملنا الاوبجكت ده من نوع `global` لما كتبنا `greetign` بدل `greeting` و بالتالي البرنامج شاف `greetign` على انها `window.greetign={}` لو في المتصفح. -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. +عشان نبعد عن المشكلة دي نقدر نستعمل `"use strict"` و اللي بدورها بتتأكد ان انت عملت المتغير قبل ما تحاول تتعامل معاه.

--- -###### 10. What happens when we do this? +###### 10. ايه اللي هيحصل لما نعمل كده؟ +
```javascript function bark() { @@ -305,27 +338,28 @@ function bark() { bark.animal = "dog"; ``` +
-- A: Nothing, this is totally fine! -- B: `SyntaxError`. You cannot add properties to a function this way. -- C: `undefined` -- D: `ReferenceError` +- أ: مش هيحصل اي حاجه غلط, الكود ده صحيح تماماً! +- ب: `SyntaxError` +- ج: `undefined` +- د: `ReferenceError` -
Answer -

-#### Answer: A +

الاجابة +

-This is possible in JavaScript, because functions are objects! (Everything besides primitive types are objects) +#### الاجابة الصحيحة: أ -A function is a special type of object. The code you write yourself isn't the actual function. The function is an object with properties. This property is invocable. +كل حاجه في جافاسكربت عبارة عن `object` حتى الدوال و بالتالي نقدر بكل سهولة اننا نعمل اللي احنا عملناه في الكود و نضيف مفاتيح و قيم للداله على انها عنصر اوبجكت عادي جداً.

--- -###### 11. What's the output? +###### 11. ايه اللي هيتطبع؟ +
```javascript function Person(firstName, lastName) { @@ -340,33 +374,40 @@ Person.getFullName = function() { console.log(member.getFullName()); ``` +
-- A: `TypeError` -- B: `SyntaxError` -- C: `Lydia Hallie` -- D: `undefined` `undefined` +- أ: `TypeError` +- ب: `SyntaxError` +- ج: `Lydia Hallie` +- د: `undefined` `undefined` -
Answer +
الاجابة

-#### Answer: A +#### الاجابة الصحيحة: أ + +مينفعش تضيف قيم لـ `constructor`بالشكل ده. لو عايز تضيف قيمة لكل الاوبجكتس اللي معمولين من الـ`constructor` ده لازم تستعمل الـ `prototype` -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() { return `${this.firstName} ${this.lastName}`; }; ``` +
+ +في المثال ده هنقدر نضيف القيمه لكل العناصر اللي معموله من الـ`constructor` ده. ايه الفايده من ده بقى؟ تخيل معايا ان احنا عملنا كوبي من دالة دي جوا كل عنصر لوحدة --مع التغاضي عن اعتبار ان بعضهم ممكن ميكونوش محتاجينها اصلاً-- احنا كده بنستخدم ميموري كتير جداً على الفاضي بينما عن طريق الـ`prototype` بنقدر اننا نعملها مره واحدة فقط و بتكون موجوده لكل العناصر اللي معموله منها! -would have made `member.getFullName()` work. Why is this beneficial? Say that we added this method to the constructor itself. Maybe not every `Person` instance needed this method. This would waste a lot of memory space, since they would still have that property, which takes of memory space for each instance. Instead, if we only add it to the prototype, we just have it at one spot in memory, yet they all have access to it!

--- -###### 12. What's the output? +###### 12. ايه اللي هيتطبع؟ +
```javascript function Person(firstName, lastName) { @@ -380,39 +421,39 @@ 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` +- أ: `Person {firstName: "Lydia", lastName: "Hallie"}` و `undefined` +- ب: `Person {firstName: "Lydia", lastName: "Hallie"}` و `Person {firstName: "Sarah", lastName: "Smith"}` +- ج: `Person {firstName: "Lydia", lastName: "Hallie"}` و `{}` +- د: `Person {firstName: "Lydia", lastName: "Hallie"}` و `ReferenceError` -
Answer +
الاجابة

-#### Answer: A - -For `sarah`, we didn't use the `new` keyword. When using `new`, it refers to the new empty object we create. However, if you don't add `new` it 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`. +كلمة `new` بتشير الى الاوبجكت الفاضي الجديد اللي احنا بنعمله قبل ما يتم اضافة اي قيم ليه. لكن لما مش بتستعمل `new` بيتم الاشارة الى الـ`global` او `window` على حسب انت بتشغل الكود فين و بالتالي لما عملنا `this.firstName = "Sarah"` احنا كده كأننا قولنا `window.firstName = "Sarah"` وبالتالي الاوبجكت `sarah نفسه فضل `undefined`

--- -###### 13. What are the three phases of event propagation? +###### 13. ايه الـ3 مراحل بتوع الـ `event propagation`؟ -- A: Target > Capturing > Bubbling -- B: Bubbling > Target > Capturing -- C: Target > Bubbling > Capturing -- D: Capturing > Target > Bubbling +- أ: Target > Capturing > Bubbling +- ب: Bubbling > Target > Capturing +- ج: Target > Bubbling > Capturing +- د: Capturing > Target > Bubbling -
Answer +
الاجابة

-#### Answer: D +#### الاجابة الصحيحة: د + +في مرحلة الـ`capturing` الحدث بيمر الاول خلال العناصر الكبيره المحتوية على العنصر اللي حصلت فيه الحدث اصلاً لحد ما توصل للعنصر ده. بعد كده بتوصل لـ `target` واللي هو العنصر اللي عمل الحدث و بعد كده بترد تاني لفوق في مرحلة الـ`bubbling` -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. @@ -421,10 +462,10 @@ During the **capturing** phase, the event goes through the ancestor elements dow --- -###### 14. All object have prototypes. +###### 14. كل العناصر `objects` ليهم `prototype`. هذه العبارة: -- A: true -- B: false +- أ: صحيحة +- ب: خطأ

Answer

@@ -439,6 +480,7 @@ All objects have prototypes, except for the **base object**. The base object has --- ###### 15. What's the output? +

```javascript function sum(a, b) { @@ -447,6 +489,7 @@ function sum(a, b) { sum(1, "2"); ``` +
- A: `NaN` - B: `TypeError` @@ -469,12 +512,15 @@ In this example, JavaScript converts the number `1` into a string, in order for ###### 16. What's the output? +
+ ```javascript let number = 0; console.log(number++); console.log(++number); console.log(number); ``` +
- A: `1` `1` `2` - B: `1` `2` `2` @@ -505,6 +551,8 @@ This returns `0 2 2`. ###### 17. What's the output? +
+ ```javascript function getPersonInfo(one, two, three) { console.log(one); @@ -517,6 +565,8 @@ const age = 21; getPersonInfo`${person} is ${age} years old`; ``` +
+ - A: `"Lydia"` `21` `["", " is ", " years old"]` - B: `["", " is ", " years old"]` `"Lydia"` `21` @@ -536,6 +586,8 @@ If you use tagged template literals, the value of the first argument is always a ###### 18. What's the output? +
+ ```javascript function checkAge(data) { if (data === { age: 18 }) { @@ -549,6 +601,8 @@ function checkAge(data) { checkAge({ age: 18 }); ``` +
+ - A: `You are an adult!` - B: `You are still an adult.` @@ -572,6 +626,8 @@ This is why both `{ age: 18 } === { age: 18 }` and `{ age: 18 } == { age: 18 }` ###### 19. What's the output? +
+ ```javascript function getAge(...args) { console.log(typeof args); @@ -579,6 +635,8 @@ function getAge(...args) { getAge(21); ``` +
+ - A: `"number"` - B: `"array"` @@ -599,6 +657,8 @@ The spread operator (`...args`.) returns an array with arguments. An array is an ###### 20. What's the output? +
+ ```javascript function getAge() { "use strict"; @@ -608,6 +668,8 @@ function getAge() { getAge(); ``` +
+ - A: `21` - B: `undefined` @@ -628,9 +690,13 @@ With `"use strict"`, you can make sure that you don't accidentally declare globa ###### 21. What's value of `sum`? +
+ ```javascript const sum = eval("10*10+5"); ``` +
+ - A: `105` - B: `"105"` @@ -651,9 +717,13 @@ const sum = eval("10*10+5"); ###### 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. @@ -676,12 +746,16 @@ If you used `localStorage`, the data would've been there forever, unless for exa ###### 23. What's the output? +
+ ```javascript var num = 8; var num = 10; console.log(num); ``` +
+ - A: `8` - B: `10` @@ -704,6 +778,8 @@ 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 set = new Set([1, 2, 3, 4, 5]); @@ -713,6 +789,8 @@ obj.hasOwnProperty(1); set.has("1"); set.has(1); ``` +
+ - A: `false` `true` `false` `true` - B: `false` `true` `true` `true` @@ -735,10 +813,14 @@ 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" }; console.log(obj); ``` +
+ - A: `{ a: "one", b: "two" }` - B: `{ b: "two", a: "three" }` @@ -777,12 +859,16 @@ The base execution context is the global execution context: it's what's accessib ###### 27. What's the output? +
+ ```javascript for (let i = 1; i < 5; i++) { if (i === 3) continue; console.log(i); } ``` +
+ - A: `1` `2` - B: `1` `2` `3` @@ -803,6 +889,8 @@ The `continue` statement skips an iteration if a certain condition returns `true ###### 28. What's the output? +
+ ```javascript String.prototype.giveLydiaPizza = () => { return "Just give Lydia pizza already!"; @@ -812,6 +900,8 @@ const name = "Lydia"; name.giveLydiaPizza(); ``` +
+ - A: `"Just give Lydia pizza already!"` - B: `TypeError: not a function` @@ -832,6 +922,8 @@ name.giveLydiaPizza(); ###### 29. What's the output? +
+ ```javascript const a = {}; const b = { key: "b" }; @@ -842,6 +934,8 @@ a[c] = 456; console.log(a[b]); ``` +
+ - A: `123` - B: `456` @@ -866,6 +960,8 @@ Then, we log `a[b]`, which is actually `a["Object object"]`. We just set that to ###### 30. What's the output? +
+ ```javascript const foo = () => console.log("First"); const bar = () => setTimeout(() => console.log("Second")); @@ -875,6 +971,8 @@ bar(); foo(); baz(); ``` +
+ - A: `First` `Second` `Third` - B: `First` `Third` `Second` @@ -918,6 +1016,7 @@ This is where an event loop starts to work. An **event loop** looks at the stack --- ###### 31. What is the event.target when clicking the button? +
```html
@@ -928,6 +1027,8 @@ This is where an event loop starts to work. An **event loop** looks at the stack
``` +
+ - A: Outer `div` - B: Inner `div` @@ -947,6 +1048,7 @@ The deepest nested element that caused the event is the target of the event. You --- ###### 32. When you click the paragraph, what's the logged output? +
```html
@@ -955,6 +1057,7 @@ The deepest nested element that caused the event is the target of the event. You

``` +
- A: `p` `div` - B: `div` `p` @@ -975,6 +1078,8 @@ 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" }; @@ -985,6 +1090,8 @@ function sayHi(age) { sayHi.call(person, 21); sayHi.bind(person, 21); ``` +
+ - A: `undefined is 21` `Lydia is 21` - B: `function` `function` @@ -1007,6 +1114,8 @@ With both, we can pass the object to which we want the `this` keyword to refer t ###### 34. What's the output? +
+ ```javascript function sayHi() { return (() => 0)(); @@ -1014,6 +1123,8 @@ function sayHi() { typeof sayHi(); ``` +
+ - A: `"object"` - B: `"number"` @@ -1036,6 +1147,8 @@ FYI: there are only 7 built-in types: `null`, `undefined`, `boolean`, `number`, ###### 35. Which of these values are falsy? +
+ ```javascript 0; new Number(0); @@ -1044,6 +1157,8 @@ new Number(0); new Boolean(false); undefined; ``` +
+ - A: `0`, `''`, `undefined` - B: `0`, `new Number(0)`, `''`, `new Boolean(false)`, `undefined` @@ -1073,9 +1188,13 @@ Function constructors, like `new Number` and `new Boolean` are truthy. ###### 36. What's the output? +
+ ```javascript console.log(typeof typeof 1); ``` +
+ - A: `"number"` - B: `"string"` @@ -1097,11 +1216,15 @@ console.log(typeof typeof 1); ###### 37. What's the 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]` @@ -1126,6 +1249,8 @@ depending on where you run it (it's different for every browser, node, etc.) ###### 38. What's the output? +
+ ```javascript (() => { let x, y; @@ -1139,6 +1264,8 @@ depending on where you run it (it's different for every browser, node, etc.) console.log(y); })(); ``` +
+ - A: `1` `undefined` `2` - B: `undefined` `undefined` `undefined` @@ -1186,6 +1313,8 @@ 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( (acc, cur) => { @@ -1194,6 +1323,8 @@ What differentiates a primitive from an object is that primitives do not have an [1, 2] ); ``` +
+ - A: `[0, 1, 2, 3, 1, 2]` - B: `[6, 1, 2]` @@ -1216,11 +1347,15 @@ Then, `[1, 2, 0, 1]` is `acc` and `[2, 3]` is `cur`. We concatenate them, and ge ###### 41. What's the output? +
+ ```javascript !!null; !!""; !!1; ``` +
+ - A: `false` `true` `false` - B: `false` `false` `true` @@ -1245,9 +1380,13 @@ 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); ``` +
+ - A: a unique id - B: the amount of milliseconds specified @@ -1268,9 +1407,13 @@ It returns a unique id. This id can be used to clear that interval with the `cle ###### 43. What does this return? +
+ ```javascript [..."Lydia"]; ``` +
+ - A: `["L", "y", "d", "i", "a"]` - B: `["Lydia"]` @@ -1286,3 +1429,4 @@ A string is an iterable. The spread operator maps every character of an iterable

+
\ No newline at end of file From cf7ce10142235e101320e2e15527a8b1ffda9f63 Mon Sep 17 00:00:00 2001 From: Sara Ahmed Date: Fri, 21 Jun 2019 15:15:34 +0200 Subject: [PATCH 084/915] Create README_AR.md Add an Arabic translation for the Repository. In this commit, translation is done until the third question. --- README_AR.md | 127 +++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 127 insertions(+) create mode 100644 README_AR.md diff --git a/README_AR.md b/README_AR.md new file mode 100644 index 00000000..43351549 --- /dev/null +++ b/README_AR.md @@ -0,0 +1,127 @@ + + +
+ +# قائــمة أسئلة جافا سكريبت (مستوى متقدم) +أقوم بنشر عدة أسئلة جافاسكريبت بصورة يومية على حسابي في [انستغرام](https://www.instagram.com/theavocoder/). + +تتدرج الأسئلة إبتداءا من المستوى الأساسي أو البسيط الى المستوى المتقدم لإختبار مدى معرفتك بلغة الجافا سكريبت, قم بمراجعة و إنعاش معرفتك باللغة قليلا, أو قم بالتجهيز لمقابلة عمل لوظيفة مبرمج عن طريق هذه الأسئلة! + +أقوم بتحديث هذا المستودع أسبوعيا بإضافة المزيد من الأسئلة. :muscle: :rocket: + +الأجوبة توجد في الجزء المطوي بالأسفل أدناه تحت كل سؤال على حدة, فقط قم بالضغط على كلمة الإجابة لكي تحصل على الإجابة, حظا موفقا :heart: + +[English](https://github.com/SaraAli26/javascript-questions/blob/master/README.md) + +[中文版本](https://github.com/SaraAli26/javascript-questions/blob/master/README-zh_CN.md) + +[Русский](https://github.com/SaraAli26/javascript-questions/blob/master/README_ru-RU.md) + +[Western Balkan](https://github.com/SaraAli26/javascript-questions/blob/master/README-bs_BS.md) + +[Deutsch](https://github.com/SaraAli26/javascript-questions/blob/master/README-de_DE.md) + +[Tiếng Việt](https://github.com/SaraAli26/javascript-questions/blob/master/README-vi.md) +
+____________ + +###### 1. ماهو الناتج ؟ + +```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` + +
الإجابة +

+ +

+الإجابة هي الخيار الرابع : D + +في داخل الدالة, قمنا أولا بتعريف المتغير `name` مع الكلمة المفتاحية `var`. و هذا يعني ان المتغير قد حصلت له عملية hoisting والتي تعني انه قد تم حجز مساحة لهذا المتغير في هذه اللحظة مع قيمة مبدئية و التي هي `undefined` إلى ان نقوم فعليا بتعريف قيمة له لاحقا. +لم نقم بتعريف المتغير `name` بعد عندما قمنا بطباعته في السطر الاول من الدالة, لهذا لايزال يحمل القيمة `undefined`. +المتغيرات التي تم تعريفها بجانب الكلمات المفتاحية `let` و `const` يتم عمل عملية hoisting لها أيضا, ولكن على عكس المتغيرات التي يتم تعريفها بجانب الكلمة المفتاحية `var`, لا يتم تعريفها او الوصول اليها مالم نقم بإضافة قيمة لها فعليا. و يسمى هذا بال"temporal dead zone".عندما نحاول الوصول الى المتغيرات من النوع `var`قبل ان يتم تعريفها, نتحصل على الخطأ التالي `ReferenceError`. + +

+
+
+ +--- + +2. ماهو الناتج? + +```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` + +
الإجابة +

+ +

+الإجابة هي الخيار الثالث: C + +بسبب ترتيب تسلسل الأحداث في الجافا سكريبت, دالة `setTimeout` والتي هي دالة من نوع callbackقد تم استدعائها بعد ان تم تنفيذ ال loop. بماأن المتغير `i` في الloop الاولى قد تم تعريفه عن طريق الكلمة المفتاحية `var` فإن هذه القيمة هي glopal. أثناء تنفيذ هذه ال loop قد تم إضافة 1 الى المتغير `var` في كل دورة باستخدام العملية `++`. بنهاية الدورة و عندما تم استدعاء الدالة `setTimeout` كانت قيمة المتغير `i` قد أصبحت تساوي `3` في المثال الأول. +في الloop الثانية ,تم تعريف المتغير `i` باستخدام الكلمة المفتاحية `let` المتغيرات التي يتم تعريفها باستخدام الكلمات المفتاحية `let` و `const` هي متغيرات تنتمي فقط للBlock الذي تم تعريفها بداخله, والذي هو بين القوسين, أثناءتنفيذ الloop, سنقوم بالتحصل على قيمة جديدة للمتغير `i` في نهاية كل دورة , وأي قيمة تكون منتمية للScope بداخل الloop. + +

+
+
+ +--- + +3. ماهو الناتج? + +```javascript +const shape = { + radius: 10, + diameter() { + return this.radius * 2; + }, + perimeter: () => 2 * Math.PI * this.radius +}; + +shape.diameter(); +shape.perimeter(); +``` + +- A: `20` and `62.83185307179586` +- B: `20` and `NaN` +- C: `20` and `63` +- D: `NaN` and `63` + +
الإجابة +

+

+الجواب هو الخيار الثاني: B + +يرجى ملاحظة أن قيمة`diameter` هي دالة Regular و في المقابل قيمة `perimeter` هي دالة من النوع arrow. +في حال استخدام دوال ال arrow, الكلمة المفتاحية `this` ترجع و تدل على المحيط الحالي الذي توجد به الكلمة المفتاحية, على عكس وجود الكلمة المفتاحية `this` في الدالة العادية حيث أنها تعني اننا نقوم بمناداة `perimeter` و هي لا تعني اننا نقصد الshape object بل نقصد الscope الذي يحاوطه, على سبيل المثال : Window. + +لا توجد قيمة `radius` في ذلك ال object لهذا يقوم بإرجاع القيمة `undefined`. + + +

+
+
+--- From 98591f65ed51d55b8266e3cea01696750e823eb3 Mon Sep 17 00:00:00 2001 From: Guilherme Nogara Date: Fri, 21 Jun 2019 10:21:30 -0300 Subject: [PATCH 085/915] Linha 5 refresce -> refresque --- README_pt_BR.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README_pt_BR.md b/README_pt_BR.md index 64bd9504..6970c2ec 100644 --- a/README_pt_BR.md +++ b/README_pt_BR.md @@ -2,7 +2,7 @@ Posto questões de múltipla escolha sobre JavaScript no meu [Instagram](https://www.instagram.com/theavocoder), as quais também posto aqui! -Do básico ao avançado: Teste quão bem você conhece o JavaScript, refresce um pouco do seu conhecimento, ou se prepare para uma entrevista! :muscle: :rocket: Eu atualizo esse repositório semanalmente com novas questões. +Do básico ao avançado: Teste quão bem você conhece o JavaScript, refresque um pouco do seu conhecimento, ou se prepare para uma entrevista! :muscle: :rocket: Eu atualizo esse repositório semanalmente com novas questões. As respostas estão em seções recolhidas abaixo das questões, basta clicar nelas para expandir. Boa sorte :heart: From 03220b5f450b5e16932ed0610814903db6812c7a Mon Sep 17 00:00:00 2001 From: Guilherme Nogara Date: Fri, 21 Jun 2019 10:21:30 -0300 Subject: [PATCH 086/915] Linha 5 refresce -> refresque MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Também removi um separador duplicado, conforme https://github.com/lydiahallie/javascript-questions/pull/74 --- README_pt_BR.md | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/README_pt_BR.md b/README_pt_BR.md index 64bd9504..425653ca 100644 --- a/README_pt_BR.md +++ b/README_pt_BR.md @@ -2,7 +2,7 @@ Posto questões de múltipla escolha sobre JavaScript no meu [Instagram](https://www.instagram.com/theavocoder), as quais também posto aqui! -Do básico ao avançado: Teste quão bem você conhece o JavaScript, refresce um pouco do seu conhecimento, ou se prepare para uma entrevista! :muscle: :rocket: Eu atualizo esse repositório semanalmente com novas questões. +Do básico ao avançado: Teste quão bem você conhece o JavaScript, refresque um pouco do seu conhecimento, ou se prepare para uma entrevista! :muscle: :rocket: Eu atualizo esse repositório semanalmente com novas questões. As respostas estão em seções recolhidas abaixo das questões, basta clicar nelas para expandir. Boa sorte :heart: @@ -176,8 +176,6 @@ Por outro lado, com a notação de ponto `.`, isso não acontece. `mouse` não t --- ---- - ###### 6. Qual é a saída? ```javascript From e1f777bdd116bfdf15ee9d89a3b4968ce7d343b3 Mon Sep 17 00:00:00 2001 From: Guilherme Nogara Date: Fri, 21 Jun 2019 11:12:12 -0300 Subject: [PATCH 087/915] Linha 136 falsey -> falsy MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Mais alguns casos que termos usando `` não eram seguidos por espaço quando no meio da sentença. --- README_pt_BR.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/README_pt_BR.md b/README_pt_BR.md index 425653ca..b90a88d8 100644 --- a/README_pt_BR.md +++ b/README_pt_BR.md @@ -133,7 +133,7 @@ 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 é falsey, que são valores que podem ser convertidos em um booleano `false`. Para fins de consistência, mantenho os termos originais. +###### *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.

@@ -237,7 +237,7 @@ console.log(b === c); 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 é: `new Number()` não é um número, é um **objeto**. Ambos retornam `false`. +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`.

@@ -371,7 +371,7 @@ Person.prototype.getFullName = function() { }; ``` -faria `member.getFullName()` funcionar. Por quê isso é beneficial? Digamos que tivéssemos esse método ao próprio construtor. Talvez nem toda instância de `Person` precisasse desse método. Isso gastaria muita memória, uma vez que cada instância teria esse propriedade e teria seu espaço alocado. Ao invés disso, se adicionarmos somente ao protótipo, alocamos somente um único espaço na memória, e todas instâncias de `Person`ainda tem acesso ao método. +faria `member.getFullName()` funcionar. Por quê isso é beneficial? Digamos que tivéssemos esse método no próprio construtor. Talvez nem toda instância de `Person` precisasse desse método. Isso gastaria muita memória, uma vez que cada instância teria esse propriedade e teria seu espaço alocado. Ao invés disso, se adicionarmos somente ao protótipo, alocamos somente um único espaço na memória, e todas instâncias de `Person` ainda tem acesso ao método.

From 2107ac27374ba8dcdde03afd74de3db092168854 Mon Sep 17 00:00:00 2001 From: Lydia Date: Fri, 21 Jun 2019 17:08:22 +0200 Subject: [PATCH 088/915] Add questions 44 to 54 --- README.md | 358 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 358 insertions(+) diff --git a/README.md b/README.md index 916fa133..ee0c29a3 100644 --- a/README.md +++ b/README.md @@ -1295,3 +1295,361 @@ A string is an iterable. The spread operator maps every character of an iterable

+ +--- + +###### 44. What's the 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` + +
Answer +

+ +#### Answer: 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"` + +
Answer +

+ +#### Answer: B + +When we pass multiple promises to the `Promice.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. What's the output? + +```javascript +let person = { name: "Lydia" }; +const members = [person]; +person = null; + +console.log(members); +``` + +- A: `null` +- B: `[null]` +- C: `[{}]` +- D: `[{ name: "Lydia" }]` + +
Answer +

+ +#### Answer: 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. What's the 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]` + +
Answer +

+ +#### Answer: 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. What's the output? + +```javascript +console.log(3 + 4 + "5"); +``` + +- A: `"345"` +- B: `"75"` +- C: `12` +- D: `"12"` + +
Answer +

+ +#### Answer: 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` + +
Answer +

+ +#### 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. + +`*` is not a valid number. It only parses `"7"` into the decimal `7`. `num` now holds the value of `7`. + +

+
+ +--- + +###### 50. What's the 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 ]` + +
Answer +

+ +#### Answer: 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. What's the 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"` + +
Answer +

+ +#### Answer: 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. What's the 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!` + +
Answer +

+ +#### Answer: 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. What's the 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` + +
Answer +

+ +#### 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"`. + +

+
+ +--- + +###### 54. What's the 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"` + +
Answer +

+ +#### Answer: 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 (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"`. + +

+
From a464c5d14bb7d9647debe64e67ad4d641d358fa8 Mon Sep 17 00:00:00 2001 From: Lydia Hallie Date: Fri, 21 Jun 2019 17:10:48 +0200 Subject: [PATCH 089/915] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index b8983ce6..92badcf8 100644 --- a/README.md +++ b/README.md @@ -2,7 +2,7 @@ I post daily multiple choice JavaScript questions on my [Instagram](https://www.instagram.com/theavocoder), which I'll also post 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 weekly with new questions. +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 weekly with new questions. Last update: June 21st The answers are in the collapsed sections below the questions, simply click on them to expand it. Good luck :heart: From 2e3995416ced1ad9c32934f35417fca7dff30df7 Mon Sep 17 00:00:00 2001 From: panicdragon Date: Sat, 22 Jun 2019 00:45:05 +0900 Subject: [PATCH 090/915] add README.md to ja link --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 916fa133..c8aa7747 100644 --- a/README.md +++ b/README.md @@ -11,7 +11,7 @@ The answers are in the collapsed sections below the questions, simply click on t [Western Balkan](./README-bs_BS.md) [Deutsch](./README-de_DE.md) [Tiếng Việt](./README-vi.md) - +[日本語](./README-ja_JA.md) --- From dbd9b91a5a8d16ae9abb6d90be0b3c0fad15367f Mon Sep 17 00:00:00 2001 From: Jacob Herper Date: Fri, 21 Jun 2019 20:07:19 +0100 Subject: [PATCH 091/915] German updated with new questions + Links to all new languages added --- README-de_DE.md | 645 +++++++++++++++++++++++++++++++++++++----------- 1 file changed, 502 insertions(+), 143 deletions(-) diff --git a/README-de_DE.md b/README-de_DE.md index ae3f4ded..190371a2 100644 --- a/README-de_DE.md +++ b/README-de_DE.md @@ -2,15 +2,17 @@ Täglich poste ich mehrere Multiple-Choice-Fragen über JavaScript auf meinem [Instagram](https://www.instagram.com/theavocoder), die ich nun auch hier veröffentlichen werde. -Von einfach bis fortgeschritten: teste wie gut du JavaScript kennst, frische dein Wissen auf oder bereite dich auf ein Vorstellungsgespräch vor! :muscle: :rocket: Ich werde dieses Repo wöchentlich mit neuen Fragen aktualisieren. +Von einfach bis fortgeschritten: teste wie gut du JavaScript kennst, frische dein Wissen auf oder bereite dich auf ein Vorstellungsgespräch vor! :muscle: :rocket: Ich werde dieses Repo wöchentlich mit neuen Fragen erweitern. -Die Antworten sind unterhalb der Fragen versteckt. Du kannst einfach auf den Pfeil klicken um die Antworten zu sehen. Viel Glück :heart: +Die Antworten sind unterhalb der Fragen versteckt. Du kannst einfach darauf klicken um die Antworten anzuzeigen. Viel Glück :heart: [English](./README.md) -[中文版本](./README-zh_CN.md) +[Bosanski Jezik](./README-bs_BS.md) +[日本語](./README-ja_JA.md) [Русский](./README_ru-RU.md) -[Western Balkan](./README-bs.md) -[Українська мова](./README-ua_UA.md) +[Українська мова](./README-ua_UA.md) +[Tiếng Việt](./README-vi.md) +[中文版本](./README-zh_CN.md) --- @@ -18,13 +20,13 @@ Die Antworten sind unterhalb der Fragen versteckt. Du kannst einfach auf den Pfe ```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` und `undefined` @@ -37,9 +39,9 @@ sayHi() #### Antwort: D -Innerhalb der Funktion wird zuerst der `name` mit dem `var` Keyword gesetzt. Das bedeutet, dass die Variable mit dem Standardwert `undefined` gehoisted wird (Speicherplatz wird während der Erstellung bereitgestellt), bis zu der Zeile, wo wir die Variable definieren. Da wir die Variable auf der Zeile, wo wir den `name` loggen noch nicht gesetzt haben, ist dieser noch `undefined`. +Innerhalb der Funktion wird zuerst der `name` mit dem `var` Keyword gesetzt. Das bedeuted, dass die Variable mit dem Standardwert `undefined` gehoisted wird (Speicher wird während der Erstellung bereitgestellt), bis zu der Zeile, wo wir die Variable definieren. Da wir die Variable auf der Zeile, wo wir den `name` loggen noch nicht gesetzt haben, ist dieser noch `undefined`. -Variablen mit dem `let` (oder `const`) Keyword werden ebenfalls gehoisted, aber im Gegensatz zu `var` werden diese nicht initialisiert. Auf sie können wir daher nicht zugreifen, bevor sie definiert worden sind. JavaScript wirft einen `ReferenceError`. +Variablen mit dem `let` (oder `const`) Keyword werden ebenfalls gehoisted, aber im Gegensatz zu `var` werden diese nicht initialisiert. Auf sie können wir daher nicht zugreifen, bevor sie definiert wurden. JavaScript wirft einen `ReferenceError` aus.

@@ -50,11 +52,11 @@ 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); } ``` @@ -82,13 +84,13 @@ In der zweiten Schleife wurde die Variable `i` mit dem `let` Keyword definiert: const shape = { radius: 10, diameter() { - return this.radius * 2 + return this.radius * 2; }, perimeter: () => 2 * Math.PI * this.radius, -} +}; -shape.diameter() -shape.perimeter() +shape.diameter(); +shape.perimeter(); ``` - A: `20` und `62.83185307179586` @@ -115,8 +117,8 @@ Es gibt keinen Wert `radius` in dem Object, daher wird `undefined` zurückgegebe ###### 4. Was ist der Output? ```javascript -;+true -!"Lydia" ++true; +!"Lydia"; ``` - A: `1` und `false` @@ -142,12 +144,12 @@ Der String `'Lydia'` ist truthy. Was wir eigentlich fragen ist: "ist dieser trut ```javascript const bird = { size: "small", -} +}; const mouse = { name: "Mickey", small: true, -} +}; ``` - A: `mouse.bird.size` ist nicht korrekt @@ -173,16 +175,15 @@ Mit der Dot Notation ist das nicht der Fall. `mouse` hat keinen Key namens `bird --- - ###### 6. Was ist der Output? ```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` @@ -212,13 +213,13 @@ Wenn ein Object geändert wird, werden alle Referenzen zu diesem Object ebenfall ###### 7. Was ist der Output? ```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` @@ -247,17 +248,17 @@ 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 + this.newColor = newColor; + return this.newColor; } constructor({ newColor = "green" } = {}) { - this.newColor = newColor + this.newColor = newColor; } } -const freddie = new Chameleon({ newColor: "purple" }) -freddie.colorChange("orange") +const freddie = new Chameleon({ newColor: "purple" }); +freddie.colorChange("orange"); ``` - A: `orange` @@ -280,9 +281,9 @@ Die `colorChange` Funktion ist statisch (`static`). Statische Methoden existiere ###### 9. Was ist der Output? ```javascript -let greeting -greetign = {} // Typo! -console.log(greetign) +let greeting; +greetign = {}; // Typo! +console.log(greetign); ``` - A: `{}` @@ -307,10 +308,10 @@ 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" +bark.animal = "dog"; ``` - A: Nichts, das ist absolut in Ordnung. @@ -336,16 +337,16 @@ 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") +const member = new Person("Lydia", "Hallie"); Person.getFullName = function() { - return `${this.firstName} ${this.lastName}` -} + return `${this.firstName} ${this.lastName}`; +}; -console.log(member.getFullName()) +console.log(member.getFullName()); ``` - A: `TypeError` @@ -362,8 +363,8 @@ Man kann keine Properties einem Constructor zuweisen, wie es bei normalen Object ```js Person.prototype.getFullName = function() { - return `${this.firstName} ${this.lastName}` -} + return `${this.firstName} ${this.lastName}`; +}; ``` So hätte `member.getFullName()` funktioniert. Warum ist das von Vorteil? Sagen wir, wir hätten diese Methode dem Constructor selbst zugewiesen, aber vielleicht benötigt nicht jede Instanz von `Person` diese Methode. So hätte das eine Menge Arbeitsspeicher verschwendet, weil jede Instanz die Property zugewiesen bekommt, auch wenn sie diese gar nicht benötigt. @@ -378,15 +379,15 @@ 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") -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"}` und `undefined` @@ -450,10 +451,10 @@ 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") +sum(1, "2"); ``` - A: `NaN` @@ -478,10 +479,10 @@ In diesem Beispiel wandelt JavaScript die Nummer `1` in einem String um, sodass ###### 16. Was ist der Output? ```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` @@ -515,15 +516,15 @@ 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" -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"]` @@ -547,15 +548,15 @@ 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!") + 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!` @@ -582,10 +583,10 @@ 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) +getAge(21); ``` - A: `"number"` @@ -609,12 +610,12 @@ 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() +getAge(); ``` - A: `21` @@ -637,7 +638,7 @@ Durch `"use strict"` kann man sicher stellen, dass man nicht versehentlich globa ###### 21. Was ist der Wert von `sum`? ```javascript -const sum = eval("10*10+5") +const sum = eval("10*10+5"); ``` - A: `105` @@ -660,7 +661,7 @@ const sum = eval("10*10+5") ###### 22. Wie lange ist cool_secret verfügbar? ```javascript -sessionStorage.setItem("cool_secret", 123) +sessionStorage.setItem("cool_secret", 123); ``` - A: Für immer, der Wert geht nicht verloren. @@ -685,10 +686,10 @@ Wenn man stattdessen `localStorage` verwendet, bleibt der Wert für immer besteh ###### 23. Was ist der Output? ```javascript -var num = 8 -var num = 10 +var num = 8; +var num = 10; -console.log(num) +console.log(num); ``` - A: `8` @@ -713,13 +714,13 @@ Das ist nicht möglich mit `let` oder `const`, da diese dem Block Scope unterlie ###### 24. Was ist der Output? ```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` @@ -744,8 +745,8 @@ Das funktioniert nicht für Set. Da wir keine `'1'` in unserem Set haben wirft ` ###### 25. Was ist der Output? ```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" }` @@ -787,8 +788,8 @@ 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); } ``` @@ -813,12 +814,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!"` @@ -841,14 +842,14 @@ name.giveLydiaPizza() ###### 29. Was ist der Output? ```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` @@ -875,13 +876,13 @@ Dann loggen wir `a[b]`, was eigentlich `a["Object object"]` ist und gerade von u ###### 30. Was ist der 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() -baz() +bar(); +foo(); +baz(); ``` - A: `First` `Second` `Third` @@ -984,14 +985,14 @@ Wenn wir auf den Paragraph klicken, sehen wir zwei logs: `p` und `div`. Während ###### 33. Was ist der Output? ```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` @@ -1017,10 +1018,10 @@ 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() +typeof sayHi(); ``` - A: `"object"` @@ -1045,12 +1046,12 @@ Es gibt nur 7 eingebaute Typen in JavaScript: `null`, `undefined`, `boolean`, `n ###### 35. Welcher dieser Werte ist falsy? ```javascript -0 -new Number(0) -;("") -;(" ") -new Boolean(false) -undefined +0; +new Number(0); +(""); +(" "); +new Boolean(false); +undefined; ``` - A: `0`, `''`, `undefined` @@ -1082,7 +1083,7 @@ Funktions-Constructor, wie `new Number` und `new Boolean` sind truthy. ###### 36. Was ist der Output? ```javascript -console.log(typeof typeof 1) +console.log(typeof typeof 1); ``` - A: `"number"` @@ -1106,9 +1107,9 @@ console.log(typeof typeof 1) ###### 37. Was ist der Output? ```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]` @@ -1135,17 +1136,17 @@ abhängig davon wo das Array ausgeführt wird (die Ausgabe ist unterschiedlich f ###### 38. Was ist der Output? ```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` @@ -1195,12 +1196,12 @@ Was einen primitiven Typ von einem Objekt unterscheidet ist, dass Primitive kein ###### 40. Was ist der Output? ```javascript -;[[0, 1], [2, 3]].reduce( +[[0, 1], [2, 3]].reduce( (acc, cur) => { - return acc.concat(cur) + return acc.concat(cur); }, [1, 2], -) +); ``` - A: `[0, 1, 2, 3, 1, 2]` @@ -1225,9 +1226,9 @@ Dann entspricht `acc` gleich `[1, 2, 0, 1]` und `cur` ist gleich `[2, 3]`. Wir v ###### 41. Was ist der Output? ```javascript -!!null -!!"" -!!1 +!!null; +!!""; +!!1; ``` - A: `false` `true` `false` @@ -1254,7 +1255,7 @@ Dann entspricht `acc` gleich `[1, 2, 0, 1]` und `cur` ist gleich `[2, 3]`. Wir v ###### 42. Was gibt die `setInterval` Method zurück? ```javascript -setInterval(() => console.log("Hi"), 1000) +setInterval(() => console.log("Hi"), 1000); ``` - A: Eine unique id @@ -1277,7 +1278,7 @@ Es gibt eine unique id zurück. Diese id kann zum Beispiel verwendet werden um d ###### 43. Was wird hier ausgegeben? ```javascript -;[..."Lydia"] +[..."Lydia"]; ``` - A: `["L", "y", "d", "i", "a"]` @@ -1294,3 +1295,361 @@ Ein String ist ein Iterable. Der Spread Operator mappt jedes Zeichen eines Itera

+ +--- + +###### 44. Was ist der 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` + +
Antwort +

+ +#### Antwort: C + +Reguläre Funktionen können nicht angehalten werden, wenn sie bereits aufgerufen wurden. Eine Generator Funktion kann dagegen auch angehalten werden, nachdem sie aufgerufen wurde und später fortgesetzt werden, wo sie angehalten wurde. Jedes Mal, wenn eine Generator Funktion ein `yield` Keyword findet, wirft die Funktion den danach ermittelten Wert aus. Wichtig: _yield_ ist nichtdas selbe wie _return_. + +Zuerst initialisieren wir die Generator Funktion mit `i` gleich `10`. Wir rufen die Generator Funktion mit der `next()` Methode auf. Beim ersten Aufruf der Generator Funktion is `i` gleich `10`. Wenn wir bei `yield` ankommen wird der Wert von `i` ausgegeben. Der Generator wird angehalten und `10` wird geloggt. + +Dann wird die Funktion erneut mit der `next()` Methode aufgerufen und beginnt von dort, wo sie zuletzt angehalten wurde, nach wie vor mit `i` gleich `10`. Jetzt erreichen wir das nächste `yield` Keyword bei `i * 2`. `i` ist gleich `10`, sodass das Ergebnis von `10 * 2` ausgegeben wird, was `20` ist. Das Ergebnis ist `10, 20`. + +

+
+ +--- + +###### 45. Was wird hier ausgegeben? + +```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"` + +
Antwort +

+ +#### Antwort: B + +Wenn wir mehrere Promises in die `Promice.race` Methode eingegeben, wird das Promise, welches _zuerst_ gelöst/abgelehnt wird auch hier gelöst/abgelehnt. Die `setTimeout` Methode bekommt einen Timer von 500ms für das erste Promise (`firstPromise`) übergeben, und 100ms für das zweite Promise (`secondPromise`). Das bedeutet, dass `secondPromise` mit dem Wert `'two'` zuerst gelöst wird und an `res` übergeben wird. Der Wert wird geloggt. + +

+
+ +--- + +###### 46. Was ist der Output? + +```javascript +let person = { name: "Lydia" }; +const members = [person]; +person = null; + +console.log(members); +``` + +- A: `null` +- B: `[null]` +- C: `[{}]` +- D: `[{ name: "Lydia" }]` + +
Antwort +

+ +#### Antwort: D + +Zuerst definieren wir die Variable `person` mit dem Wert eines Objekts, welches eine `name` Property hat. + + + +Dann definieren wir eine Variable namens `members`. Wir setzen das erste Element des Arrays gleich dem Wert der `person` Variable. Objekte interagieren durch eine _Referenz_, wenn diese gleichgesetzt werden. Wenn eine Referenz von einer Variable zur anderen gleichgesetzt wird, so wird eine _Kopie_ der Referenz erstellt (Wichtig: nicht die _selbe_ Referenz!) + + + +Dann setzen wir die Variable `person` gleich `null`. + + + +Wir ändern nur den Wert der Variable `person` und nicht das erste Element im Array, da das Element eine andere Referenz als das Objekt hat (Kopie). Das erste Element in `members` beinhaltet immernoch die Referenz zum original Objekt. Wenn wir das `members` Array loggen ist dieses immernoch der Wert des Objekts, welches dann geloggt wird. + +

+
+ +--- + +###### 47. Was ist der 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]` + +
Antwort +

+ +#### Antwort: B + +Mit einer `for-in` Schleife können wir über Objekt Keys iterieren - in diesem Fall `name` und `age`. Im Endeffekt sind Objekt Keys Strings (oder Symbols). Bei jedem Durchlauf setzen wir den Wert von `item` gleich zum aktuellen Key. Zuerst ist `item` gleich `name` und wird geloggt. Dann wird `item` gleich `age` gesetzt und wird geloggt. + +

+
+ +--- + +###### 48. Was ist der Output? + +```javascript +console.log(3 + 4 + "5"); +``` + +- A: `"345"` +- B: `"75"` +- C: `12` +- D: `"12"` + +
Antwort +

+ +#### Antwort: B + +Operator Assoziativität ist die Reihenfolge, in der der Compiler die Expression evaluiert, entweder links-nach-rechts oder rechts-nach-links. Das funktioniert nur, wenn alle Operatoren die _gleiche_ Priorität haben. Hier haben wir nur einen Operator: `+`. Für Addition ist die Assoziativität links-nach-rechts. + +`3 + 4` wird zuerst errechnet, das Ergebnis ist `7`. + +`7 + '5'` ergibt `"75"` (aufgrund von Coercion). JavaScript wandelt `7` in einen String um (Siehe Frage 15). Zwei Strings werden durch den `+` Operator zusammengesetzt.`"7" + "5"` ergibt `"75"`. + +

+
+ +--- + +###### 49. Was ist der Wert von `num`? + +```javascript +const num = parseInt("7*6", 10); +``` + +- A: `42` +- B: `"42"` +- C: `7` +- D: `NaN` + +
Antwort +

+ +#### Antwort: C + +Nur die erste Zahl im String wird ausgegeben. Aufgrund des _radix_ (das zweite Argument definiert, welchen Typ einer Zahl wir parsen wollen: Basis 10, hexadezimal, Octal, Binary, etc.) prüft `parseInt` ob die Zeichen im String gültig sind. Wenn ein Zeichen erkannt wird, welches nicht gültig ist, wird der Parse Vorgang beendet und die nachfolgenden Zeichen werden ignoriert. + +`*` ist keine gültige Nummer, sodass nur `"7"` als Dezimal geparsed wird: `7`. `num` ist jetzt gleich `7`. + +

+
+ +--- + +###### 50. Was ist der 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 ]` + +
Antwort +

+ +#### Antwort: C + +Wenn man über das Array mappt, ist `num` gleich dem Element, welches gerade durchlaufen wird. In diesem Fall sind die Elemente Nummern, sodass die Kondition der If-Schleife `typeof num === "number"` erfüllt ist und `true` zurück gibt. Die map Funktion erstellt ein neues Array und beinhaltet die Werte der Funktion. + +Allerdings geben wir keinen Wert aus. Wenn unsere Funktion keinen Wert ausgibt, ist der Standard "return" `undefined`. Für jedes Element im Array wird die Funktion aufgerufen, sodass für jedes Element `undefined` ausgegeben wird. + +

+
+ +--- + +###### 51. Was ist der 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"` + +
Antwort +

+ +#### Antwort: A + +Argumente werden als _Wert_ übergeben, es sei denn ihr Wert ist ein Objekt, dann werden sie als _Referenz_ übergeben. `birthYear` wird als Wert übergeben, da es ein String ist und kein Objekt. Wenn Argumente als Wert übergeben werden, wird eine _Kopie_ des Wertes erstellt (Siehe Frage 46). + +Die Variable `birthYear` beinhaltet eine Referenz zum Wert `"1997"`. Das Argument `year` beinhaltet ebenso eine Referenz zum Wert `"1997"`, aber die Werte sind nicht identisch! Wenn wir den Wert von `year` ändern, indem wir ihn gleich `"1998"` setzen, ändern wir nur den Wert von `year`. `birthYear` ist immernoch `"1997"`. + +Der Wert von `person` ist ein Objekt, sodass das Argument `member` eine Kopie der Referenz des _gleichen_ Objekts hat. Wenn wir also eine Property dessen Objekt `member` eine Referenz enthält, wird der Wert von `person` ebenso geändert, da beide die gleiche Referenz zum selben Objekt beinhalten. Die Property `name` von `person` ist jetzt gleich `"Lydia"`. + +

+
+ +--- + +###### 52. Was ist der 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!` + +
Antwort +

+ +#### Antwort: D + +Mit dem `throw` Statement können wir individuelle Fehlermeldungen erstellen und Exceptions erstellen. Eine Exception kann ein String, eine Nummer, ein Boolean oder ein Objekt sein. In diesem Fall ist unsere Exception der String `'Hello world'`. + +Mit dem `catch` Statement können wir definieren, was passiert, wenn die Exception im `try` Block eintritt. Wenn die Exception eintritt wird der String `'Hello world'` ausgegeben. Nun loggen wir `e`, was gleich dem String ist. Das Ergebnis ist `'Oh an error: Hello world'`. + +

+
+ +--- + +###### 53. Was ist der 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` + +
Antwort +

+ +#### Antwort: B + +Wenn man eine Property ausgibt ist der Wert der Property gleich dem ausgegeben Wert und nicht dem Wert, der im Constructor definiert wurde. Wir geben den String `"Maserati"` aus, sodass `myCar.make` gleich `"Maserati"` ist. + +

+
+ +--- + +###### 54. Was ist der 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"` + +
Antwort +

+ +#### Antwort: A + +`let x = y = 10;` ist kurz für: + +```javascript +y = 10; +let x = y; +``` + +Wenn wir `y` gleich `10` setzen, erstellen wir eigentlich eine Property `y` im globalen Objekt (`window` im Browser oder `global` in Node). Im Browser ist jetzt `window.y` gleich `10`. + +Dann erstellen wir eine Variable `x` mit dem Wert von `y` (`10`). Variablen, die mit `let` erstellt werden sind _Block-Scoped_, was bedeutet, dass sie nur in dem Block existieren, wo sie erstellt wurden – der hier erstellte Funktion (IIFE) in diesem Fall. Wenn wir den `typeof` Operator nutzen ist `x` nicht definiert. Wir versuchen auf `x` außerhalb des Scopes zuzugreifen, was bedeutet, dass `x` `"undefined"` ist. `console.log(typeof x)` gibt daher `"undefined"` aus. + +Da wir die Variable `y` aber global erstellt haben ist ihr Wert `10` auch hier verfügbar und überall in userem Code aufrufbar. `y` ist definiert und beinhaltet einen Wert vom Typ `"number"`. `console.log(typeof y)` gibt daher `"number"` aus. + +

+
From 33b3232d4952c4fb147f8adbc1755ae1ca791626 Mon Sep 17 00:00:00 2001 From: Lydia Hallie Date: Fri, 21 Jun 2019 21:32:18 +0200 Subject: [PATCH 092/915] Create LICENSE --- LICENSE | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 LICENSE diff --git a/LICENSE b/LICENSE new file mode 100644 index 00000000..d63d90e5 --- /dev/null +++ b/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2019 Lydia Hallie + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. From 9fd151e2101157aa4e5621eaa37353a74274bafb Mon Sep 17 00:00:00 2001 From: Ihor Sychevskyi <26163841+Arhell@users.noreply.github.com> Date: Sat, 22 Jun 2019 04:00:44 +0300 Subject: [PATCH 093/915] delete unnecessary link & add new, RU --- README_ru-RU.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/README_ru-RU.md b/README_ru-RU.md index b1963664..d0dbeda4 100644 --- a/README_ru-RU.md +++ b/README_ru-RU.md @@ -6,11 +6,11 @@ Ответы находятся в свернутой секции ниже вопросов. Просто нажми на "Ответ", чтобы развернуть. Удачи! :heart: -[中文版本](./README-zh_CN.md) -[Русский](./README_ru-RU.md) -[Western Balkan](./README-bs.md) +[中文版本](./README-zh_CN.md) +[Western Balkan](./README-bs_BS.md) [Deutsch](./README-de_DE.md) [Tiếng Việt](./README-vi.md) +[日本語](./README-ja_JA.md) [Українська мова](./README-ua_UA.md) From 1626a96ca2db39b965492c1ca6c23c19ac9bbe21 Mon Sep 17 00:00:00 2001 From: Tanguy Coppin Date: Sat, 22 Jun 2019 12:06:46 +0200 Subject: [PATCH 094/915] Finish translation of the first 43 questions + answer for the 14 firsts questions in FR --- README_fr-FR.md | 60 ++++++++++++++++++++++++------------------------- 1 file changed, 30 insertions(+), 30 deletions(-) diff --git a/README_fr-FR.md b/README_fr-FR.md index 68a988a5..0eb2fb44 100644 --- a/README_fr-FR.md +++ b/README_fr-FR.md @@ -104,7 +104,7 @@ Notez que le valeur de `diameter` est une fonction régulière, alors que `perim Avec les fonctions fléchée, le mot clé `this` réfère à son périmètre actuel, contrairement au fonctions régulières ! Cela signifie que lorsque nous appelons `perimeter`, elle ne réfère pas à l'objet shape, mais à son périmètre actuel (`window` par exemple). -Il n'y a pas de valeur `radius` dans cet objet, qui retournera `undefined`. +Il n'y a pas de valeur `radius` dans cet objet, on retournera `undefined`.

@@ -231,7 +231,7 @@ console.log(b === c); #### Réponse: C -`new Number()` est une fonction globale. Bien qu'il ressamble à un nombre, ce n'en est pas vraiment un : il a une poignée de fonctionnalités supplémentaire and est un objet. +`new Number()` est une fonction globale. Bien qu'il ressemble à un nombre, ce n'en est pas vraiment un : il a une poignée de fonctionnalités supplémentaire and est un objet. Quand nous utilisons l'opérateur `==`, il vérifie seulement qu'il s'agisse de la même _valeur_. Les deux ont pour valeur `3`, donc il retourne `true`. @@ -294,9 +294,9 @@ console.log(greetign); #### Réponse: 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). +Il affiche l'objet, car on a juste créé un objet vide dnas l'objet global ! Quand on écrit mal `greeting` en `greetign`, JaveScript l'interprète comme il le voit `global.greetign = {}` (ou `window.greetign = {}` dans le navigateur). -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. +Pour éviter cela, on peut utiliser `"use strict"`. Cela nous assure de devoir déclarer la variable avant de lui assigné une valeur.

@@ -323,9 +323,9 @@ bark.animal = "dog"; #### Réponse: A -This is possible in JavaScript, because functions are objects! (Everything besides primitive types are objects) +C'est possible en JavaScript, car les fonctions sont des objets ! (Tout ce qui n'est pas de type primitif est un objet) -A function is a special type of object. The code you write yourself isn't the actual function. The function is an object with properties. This property is invocable. +Une fonction est un type special d'objet. Le code que vous écrivez vous-même n'est pas la fonction. La fonction est un objet avec des propriétées. Cette propriétée est invocable.

@@ -358,7 +358,7 @@ console.log(member.getFullName()); #### Réponse: A -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, +Vous ne pouvez pas ajouter de propriétés à un constructeur comme pour des objets normaux. Si vous voulez ajouter une fonctionnalité pour tout les objets en une fois, vous devez utiliser le prototype. Donc dans ce cas, ```js Person.prototype.getFullName = function() { @@ -366,7 +366,7 @@ Person.prototype.getFullName = function() { }; ``` -would have made `member.getFullName()` work. Why is this beneficial? Say that we added this method to the constructor itself. Maybe not every `Person` instance needed this method. This would waste a lot of memory space, since they would still have that property, which takes of memory space for each instance. Instead, if we only add it to the prototype, we just have it at one spot in memory, yet they all have access to it! +rendra fonctionnel `member.getFullName`. Pourquoi est-ce benifique ? Disons que nous ajoutons cette méthode au constructeur directement. Peut-être que toutes les instances de `Person` n'ont pas besoin de cette méthode. Cela fera perdre de l'espace mémoire, car elles auront tous cette propriété, ce qui prendra de l'espace mémoire pour chaque instance. Alors que, si nous ajoutons la méthode au prototype uniquement, nous n'utilisons qu'un seul slot mémoire, et ils y auront tous accès !

@@ -398,9 +398,9 @@ console.log(sarah); #### Réponse: A -For `sarah`, we didn't use the `new` keyword. When using `new`, it refers to the new empty object we create. However, if you don't add `new` it refers to the **global object**! +Pour `sarah`, nous n'avons pas utilisé le mot clé `new`. Quand nous utilisons `new`, il fait référence à un nouvel objet vide que nous créons. Cependant so nous n'ajoutons pas `new` il réfère à **l'objet global** ! -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`. +Nous disons que `this.firstName` est égal à `"Sarah"` et que `this.lastName` est égal à `Smith`. Ce que nous faisons c'est définir `global.firstName = 'Sarah'` et `global.lastName = 'Smith'`. La variable `sarah` elle-même reste à `undefined`.

@@ -430,15 +430,15 @@ Durant la phase de **capture** _(capturing)_, l'événement passe par les évén ###### 14. Tous les objects ont des prototypes. -- A: true -- B: false +- A: vrai +- B: faux
Réponse

#### Réponse: B -All objects have prototypes, except for the **base object**. 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. +Tous les objets ont des prototypes, excepté pour les **objets standards**. Les objets standards ont accès à certaines méthodes et propriétés, comme `.toString`. C'est pour cette raison que vous pouvez utiliser les méthodes natives de JavaScript ! Toutes ces méthodes sont disponibles dans le prototype. Bien que JavaScript ne trouve pas la fonction dans l'objet, il parcours le prototype et la méthode afin de la rendre accessible.

@@ -764,7 +764,7 @@ If you have two keys with the same name, the key will be replaced. It will still --- -###### 26. The JavaScript global execution context creates two things for you: the global object, and the "this" keyword. +###### 26. Le contexte global d'exécution de JavaScript créait 2 choses pour vous : l'objet global and le mot clé `this`. - A: Vrai - B: Faux @@ -924,7 +924,7 @@ This is where an event loop starts to work. An **event loop** looks at the stack --- -###### 31. What is the event.target when clicking the button? +###### 31. Quel est l'élément ciblé _(event.target)_ au click sur le bouton _(button)_ ? ```html
@@ -936,10 +936,10 @@ This is where an event loop starts to work. An **event loop** looks at the stack
``` -- A: Outer `div` -- B: Inner `div` +- A: La `div` extérieure +- B: La `div` intérieure - C: `button` -- D: An array of all nested elements. +- D: Un tableau de tous les éléments imbriqués.
Réponse

@@ -953,7 +953,7 @@ The deepest nested element that caused the event is the target of the event. You --- -###### 32. When you click the paragraph, what's the logged output? +###### 32. Quand vous cliquez sur le paragraphe, quelle est la sortie ? ```html

@@ -1041,7 +1041,7 @@ FYI: there are only 7 built-in types: `null`, `undefined`, `boolean`, `number`, --- -###### 35. Which of these values are falsy? +###### 35. Lesquelles de ces valeurs sont fausses ? ```javascript 0; @@ -1168,12 +1168,12 @@ Outside of the `catch` block, `x` is still `undefined`, and `y` is `2`. When we --- -###### 39. Everything in JavaScript is either a... +###### 39. Tout en JavaScript est... -- A: primitive or object -- B: function or object -- C: trick question! only objects -- D: number or object +- A: primitif ou objet +- B: fonction ou objet +- C: question délicate ! Seulement des objets +- D: nombre ou objet
Réponse

@@ -1250,15 +1250,15 @@ Then, `[1, 2, 0, 1]` is `acc` and `[2, 3]` is `cur`. We concatenate them, and ge --- -###### 42. What does the `setInterval` method return? +###### 42. Que retourne la méthode `setInterval` ? ```javascript setInterval(() => console.log("Hi"), 1000); ``` -- A: a unique id -- B: the amount of milliseconds specified -- C: the passed function +- A: un identifiant unique +- B: le temps de millisecondes spécifié +- C: la fonction passée en paramètre - D: `undefined`

Réponse @@ -1273,7 +1273,7 @@ It returns a unique id. This id can be used to clear that interval with the `cle --- -###### 43. What does this return? +###### 43. Que retourne ceci ? ```javascript [..."Lydia"]; From 575d253d5b5f7635357c48cc0111c2222767b7ad Mon Sep 17 00:00:00 2001 From: Jacob Herper Date: Sat, 22 Jun 2019 12:05:47 +0100 Subject: [PATCH 095/915] Corrected missing line breaks after some languages --- README-de_DE.md | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/README-de_DE.md b/README-de_DE.md index 190371a2..706654cb 100644 --- a/README-de_DE.md +++ b/README-de_DE.md @@ -6,13 +6,13 @@ Von einfach bis fortgeschritten: teste wie gut du JavaScript kennst, frische dei Die Antworten sind unterhalb der Fragen versteckt. Du kannst einfach darauf klicken um die Antworten anzuzeigen. Viel Glück :heart: -[English](./README.md) -[Bosanski Jezik](./README-bs_BS.md) -[日本語](./README-ja_JA.md) -[Русский](./README_ru-RU.md) -[Українська мова](./README-ua_UA.md) -[Tiếng Việt](./README-vi.md) -[中文版本](./README-zh_CN.md) +[English](./README.md)
+[Bosanski Jezik](./README-bs_BS.md)
+[日本語](./README-ja_JA.md)
+[Русский](./README_ru-RU.md)
+[Українська мова](./README-ua_UA.md)
+[Tiếng Việt](./README-vi.md)
+[中文版本](./README-zh_CN.md)
--- From 4858b8b3d124dc33ab599f81b3ac946ff90d850d Mon Sep 17 00:00:00 2001 From: Gabriel Sroka Date: Sat, 22 Jun 2019 10:12:53 -0700 Subject: [PATCH 096/915] Update README.md fixed a few minor typos/errors. i'm not positive about the parens on Q. 54 --- README.md | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/README.md b/README.md index 3eb7e7e7..ddd3318a 100644 --- a/README.md +++ b/README.md @@ -2,7 +2,7 @@ I post daily multiple choice JavaScript questions on my [Instagram](https://www.instagram.com/theavocoder), which I'll also post 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 weekly with new questions. Last update: June 21st +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 weekly with new questions. Last update: [June 21st](#20190621) The answers are in the collapsed sections below the questions, simply click on them to expand it. Good luck :heart: @@ -1298,7 +1298,7 @@ A string is an iterable. The spread operator maps every character of an iterable --- -###### 44. What's the output? +###### 44. What's the output? ```javascript function* generator(i) { @@ -1485,7 +1485,7 @@ Only the first numbers in the string is returned. Based on the _radix_ (the seco --- -###### 50. What's the output`? +###### 50. What's the output? ```javascript [1, 2, 3].map(num => { @@ -1572,16 +1572,16 @@ 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!` +- D: `"Oh no an error! Hello world!`
Answer

#### Answer: 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 `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'`. +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!'`.

@@ -1638,7 +1638,7 @@ console.log(typeof y); #### Answer: A -`let x = y = 10;` is actually shorthand for: +`let x = (y = 10);` is actually shorthand for: ```javascript y = 10; From 879aadb69627f08fcb5e1e72f268e244ccdab003 Mon Sep 17 00:00:00 2001 From: kimdanah Date: Sun, 23 Jun 2019 03:53:53 +0900 Subject: [PATCH 097/915] Translate the questions 1-10 to Korean --- README-ko_KR.md | 1658 +++++++++++++++++++++++++++++++++++++++++++++++ README.md | 2 +- 2 files changed, 1659 insertions(+), 1 deletion(-) create mode 100644 README-ko_KR.md diff --git a/README-ko_KR.md b/README-ko_KR.md new file mode 100644 index 00000000..c50e3288 --- /dev/null +++ b/README-ko_KR.md @@ -0,0 +1,1658 @@ +# (고급) JavaScript 질문 목록 + +JavaScript 에 관한 객관식 문제를 [Instagram](https://www.instagram.com/theavocoder)에 매일 게시하고 있어요, 물론 여기에도 게시할 거예요! + +초급부터 고급까지: JavaScript를 얼마나 잘 알고 있는지 테스트하거나, 지식을 조금 깊게 하거나, 코딩 면접을 준비하세요! :muscle: :rocket: 이 기록을 매주 새로운 질문으로 업데이트해요. 마지막 업데이트: 6월 21일 + +정답은 질문 아래 접힌 부분에 있어요, 그냥 클릭하면 펼칠 수 있어요. 행운을 빌어요 :heart: + +[中文版本](./README-zh_CN.md) +[Русский](./README_ru-RU.md) +[Western Balkan](./README-bs_BS.md) +[Deutsch](./README-de_DE.md) +[Tiếng Việt](./README-vi.md) +[日本語](./README-ja_JA.md) +[Українська мова](./README-ua_UA.md) +[한국어](./README-ko_KR.md) + +--- + +###### 1. 무엇이 출력 될까요? + +```javascript +function sayHi() { + console.log(name); + console.log(age); + var name = "Lydia"; + let age = 21; +} + +sayHi(); +``` + +- A: `Lydia` 와 `undefined` +- B: `Lydia` 와 `ReferenceError` +- C: `ReferenceError` 와 `21` +- D: `undefined` 와 `ReferenceError` + +
정답 +

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

+
+ +--- + +###### 2. 무엇이 출력 될까요? + +```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` 와 `0 1 2` +- B: `0 1 2` 와 `3 3 3` +- C: `3 3 3` 와 `0 1 2` + +
정답 +

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

+
+ +--- + +###### 3. 무엇이 출력 될까요? + +```javascript +const shape = { + radius: 10, + diameter() { + return this.radius * 2; + }, + perimeter: () => 2 * Math.PI * this.radius +}; + +shape.diameter(); +shape.perimeter(); +``` + +- A: `20` 과 `62.83185307179586` +- B: `20` 과 `NaN` +- C: `20` 과 `63` +- D: `NaN` 과 `63` + +
정답 +

+ +#### 정답: B + +`diameter`의 값은 정규 함수인 반면, `perimeter`의 값은 화살표 함수라는 점에 유의해요. + +화살표 함수에서는, 통상적인 함수와는 달리, `this`키워드는 현재 주위의 범위를 참조해요! 이것은 `perimeter`를 부르면, shape 객체가 아닌, 그 주위의 범위(예를 들면 window)를 참조하는 것을 의미해요. + +그 객체에는 `radius`라는 값은 없고, `undefined`를 리턴해요. + +

+
+ +--- + +###### 4. 무엇이 출력 될까요? + +```javascript ++true; +!"Lydia"; +``` + +- A: `1` 과 `false` +- B: `false` 와 `NaN` +- C: `false` 와 `false` + +
정답 +

+ +#### 정답: A + +단항 더하기는 피연산자를 숫자로 변환하려 해요. `true`는 `1`, `false`은 `0`. + +문자열 `'Lydia'`는 참 같은 값이에요. 실제로 묻고 있는 것은, "이 참 같은 값이 거짓 같은 값인가?"에요. 이것은 `false`을 리턴해요. + +

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

+ +#### 정답: A + +JavaScript에서, 모든 객체 키는 문자열이에요 (Symbol이 아닌 한). 비록 그것을 문자열 _타입_ 으로 입력하지 않아도, 항상 밑바닥에서 문자열로 변환되요. + +JavaScript는 문장을 해석(또는 박스해제)해요. 대괄호 표기를 사용하면, 첫 번째 좌대괄호 `[`를 보고 오른쪽 대괄호 `]`를 찾을 때까지 진행해요. 그때, 그 문장을 평가할거에요. + +`mouse[bird.size]`: 먼저 `bird.size`를 평가해요, 이것은 `"small"`이에요. `mouse["small"]` 은 `true`를 리턴해요. + +그러나, 닷 표기에서는, 이것은 발생하지 않아요, `mouse`는 `bird`라고 불리는 키를 가지고 있지 않아요 즉, `mouse.bird`는 `undefined`를 의미해요. + +또, 닷 표기를 사용해 `size`를 물어봐요. `mouse.bird.size`. `mouse.bird`는 `undefined`로, 실제로는 `undefined.size`를 물어보고 있어요. 이것은 유효하지 않기 때문에, `Cannot read property "size" of undefined`와 비슷한 에러를 던질거에요. + +

+
+ +--- + +###### 6. 무엇이 출력 될까요? + +```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` + +
정답 +

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

+
+ +--- + +###### 7. 무엇이 출력 될까요? + +```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` + +
정답 +

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

+
+ +--- + +###### 8. 무엇이 출력 될까요? + +```javascript +class Chameleon { + 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` + +
정답 +

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

+
+ +--- + +###### 9. 무엇이 출력 될까요? + +```javascript +let greeting; +greetign = {}; // Typo! +console.log(greetign); +``` + +- A: `{}` +- B: `ReferenceError: greetign is not defined` +- C: `undefined` + +
정답 +

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

+
+ +--- + +###### 10. 이것을 하면 어떻게 될까요? + +```javascript +function bark() { + console.log("Woof!"); +} + +bark.animal = "dog"; +``` + +- A: 아무 일도 일어나지 않아요, 이건 완전히 괜찮아요! +- B: `SyntaxError` 이 방법으로 함수에 속성을 추가할 수 없어요. +- C: `undefined` +- D: `ReferenceError` + +
정답 +

+ +#### 정답: A + +JavaScript에서는 가능해요, 함수는 객체이기 때문이에요! +(프리미티브형 이외는 모두 객체에요) + +함수는 특별한 종류의 객체에요. 자신이 쓴 코드는 실제 함수가 아니에요. 함수는 속성을 가진 객체에요. 이 속성은 호출이 가능해요. + +

+
+ +--- + +###### 11. 무엇이 출력 될까요? + +```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` + +
정답 +

+ +#### 정답: A + +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() { + return `${this.firstName} ${this.lastName}`; +}; +``` + +would have made `member.getFullName()` work. Why is this beneficial? Say that we added this method to the constructor itself. Maybe not every `Person` instance needed this method. This would waste a lot of memory space, since they would still have that property, which takes of memory space for each instance. Instead, if we only add it to the prototype, we just have it at one spot in memory, yet they all have access to it! + +

+
+ +--- + +###### 12. 무엇이 출력 될까요? + +```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` + +
정답 +

+ +#### 정답: A + +For `sarah`, we didn't use the `new` keyword. When using `new`, it refers to the new empty object we create. However, if you don't add `new` it 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`. + +

+
+ +--- + +###### 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 + +
정답 +

+ +#### 정답: 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 + +
정답 +

+ +#### 정답: B + +All objects have prototypes, except for the **base object**. 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. 무엇이 출력 될까요? + +```javascript +function sum(a, b) { + return a + b; +} + +sum(1, "2"); +``` + +- A: `NaN` +- B: `TypeError` +- C: `"12"` +- D: `3` + +
정답 +

+ +#### 정답: 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. 무엇이 출력 될까요? + +```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` + +
정답 +

+ +#### 정답: 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. 무엇이 출력 될까요? + +```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` + +
정답 +

+ +#### 정답: 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. 무엇이 출력 될까요? + +```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` + +
정답 +

+ +#### 정답: 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. 무엇이 출력 될까요? + +```javascript +function getAge(...args) { + console.log(typeof args); +} + +getAge(21); +``` + +- A: `"number"` +- B: `"array"` +- C: `"object"` +- D: `"NaN"` + +
정답 +

+ +#### 정답: C + +The spread operator (`...args`.) returns an array with arguments. An array is an object, so `typeof args` returns `"object"` + +

+
+ +--- + +###### 20. 무엇이 출력 될까요? + +```javascript +function getAge() { + "use strict"; + age = 21; + console.log(age); +} + +getAge(); +``` + +- A: `21` +- B: `undefined` +- C: `ReferenceError` +- D: `TypeError` + +
정답 +

+ +#### 정답: 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 value of `sum`? + +```javascript +const sum = eval("10*10+5"); +``` + +- A: `105` +- B: `"105"` +- C: `TypeError` +- D: `"10*10+5"` + +
정답 +

+ +#### 정답: 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. + +
정답 +

+ +#### 정답: 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. 무엇이 출력 될까요? + +```javascript +var num = 8; +var num = 10; + +console.log(num); +``` + +- A: `8` +- B: `10` +- C: `SyntaxError` +- D: `ReferenceError` + +
정답 +

+ +#### 정답: 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. 무엇이 출력 될까요? + +```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` + +
정답 +

+ +#### 정답: 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. 무엇이 출력 될까요? + +```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` + +
정답 +

+ +#### 정답: 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 + +
정답 +

+ +#### 정답: A + +The base execution context is the global execution context: it's what's accessible everywhere in your code. + +

+
+ +--- + +###### 27. 무엇이 출력 될까요? + +```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` + +
정답 +

+ +#### 정답: C + +The `continue` statement skips an iteration if a certain condition returns `true`. + +

+
+ +--- + +###### 28. 무엇이 출력 될까요? + +```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` + +
정답 +

+ +#### 정답: 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. 무엇이 출력 될까요? + +```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` + +
정답 +

+ +#### 정답: 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. 무엇이 출력 될까요? + +```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` + +
정답 +

+ +#### 정답: 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. + +
정답 +

+ +#### 정답: 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` + +
정답 +

+ +#### 정답: 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. 무엇이 출력 될까요? + +```javascript +const person = { name: "Lydia" }; + +function sayHi(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` + +
정답 +

+ +#### 정답: 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. 무엇이 출력 될까요? + +```javascript +function sayHi() { + return (() => 0)(); +} + +typeof sayHi(); +``` + +- A: `"object"` +- B: `"number"` +- C: `"function"` +- D: `"undefined"` + +
정답 +

+ +#### 정답: B + +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`, and `symbol`. `"function"` is not a type, since functions are objects, it's of type `"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 + +
정답 +

+ +#### 정답: A + +There are only six falsy values: + +- `undefined` +- `null` +- `NaN` +- `0` +- `''` (empty string) +- `false` + +Function constructors, like `new Number` and `new Boolean` are truthy. + +

+
+ +--- + +###### 36. 무엇이 출력 될까요? + +```javascript +console.log(typeof typeof 1); +``` + +- A: `"number"` +- B: `"string"` +- C: `"object"` +- D: `"undefined"` + +
정답 +

+ +#### 정답: B + +`typeof 1` returns `"number"`. +`typeof "number"` returns `"string"` + +

+
+ +--- + +###### 37. 무엇이 출력 될까요? + +```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` + +
정답 +

+ +#### 정답: 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, 7 x empty, 11]` + +depending on where you run it (it's different for every browser, node, etc.) + +

+
+ +--- + +###### 38. 무엇이 출력 될까요? + +```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` + +
정답 +

+ +#### 정답: 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 + +
정답 +

+ +#### 정답: 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 implicity wrap the object 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. 무엇이 출력 될까요? + +```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]` + +
정답 +

+ +#### 정답: 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. 무엇이 출력 될까요? + +```javascript +!!null; +!!""; +!!1; +``` + +- A: `false` `true` `false` +- B: `false` `false` `true` +- C: `false` `true` `true` +- D: `true` `true` `false` + +
정답 +

+ +#### 정답: 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` + +
정답 +

+ +#### 정답: 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"]]` + +
정답 +

+ +#### 정답: A + +A string is an iterable. The spread operator maps every character of an iterable to one element. + +

+
+ +--- + +###### 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` + +
정답 +

+ +#### 정답: 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"` + +
정답 +

+ +#### 정답: B + +When we pass multiple promises to the `Promice.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. 무엇이 출력 될까요? + +```javascript +let person = { name: "Lydia" }; +const members = [person]; +person = null; + +console.log(members); +``` + +- A: `null` +- B: `[null]` +- C: `[{}]` +- D: `[{ name: "Lydia" }]` + +
정답 +

+ +#### 정답: 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. 무엇이 출력 될까요? + +```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]` + +
정답 +

+ +#### 정답: 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. 무엇이 출력 될까요? + +```javascript +console.log(3 + 4 + "5"); +``` + +- A: `"345"` +- B: `"75"` +- C: `12` +- D: `"12"` + +
정답 +

+ +#### 정답: 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` + +
정답 +

+ +#### 정답: 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. What's the 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 ]` + +
정답 +

+ +#### 정답: 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. 무엇이 출력 될까요? + +```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"` + +
정답 +

+ +#### 정답: 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. 무엇이 출력 될까요? + +```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!` + +
정답 +

+ +#### 정답: 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. 무엇이 출력 될까요? + +```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` + +
정답 +

+ +#### 정답: 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. 무엇이 출력 될까요? + +```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"` + +
정답 +

+ +#### 정답: 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 (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"`. + +

+
diff --git a/README.md b/README.md index 3eb7e7e7..217ce423 100644 --- a/README.md +++ b/README.md @@ -13,6 +13,7 @@ The answers are in the collapsed sections below the questions, simply click on t [Tiếng Việt](./README-vi.md) [日本語](./README-ja_JA.md) [Українська мова](./README-ua_UA.md) +[한국어](./README-ko_KR.md) --- @@ -175,7 +176,6 @@ However, with dot notation, this doesn't happen. `mouse` does not have a key cal --- - ###### 6. What's the output? ```javascript From cdaa7d675f67fa5b37cc452026a978b8a1deb736 Mon Sep 17 00:00:00 2001 From: KL13NT Date: Sat, 22 Jun 2019 21:30:09 +0200 Subject: [PATCH 098/915] Finished 47 questions --- README_ar-EG.md | 554 +++++++++++++++++++++++------------------------- 1 file changed, 264 insertions(+), 290 deletions(-) diff --git a/README_ar-EG.md b/README_ar-EG.md index 247e318b..5e3dd9f5 100644 --- a/README_ar-EG.md +++ b/README_ar-EG.md @@ -7,6 +7,8 @@ الاجابات في الجزء المخفي تحت, ببساطة دوس على السؤال عشان تفتح تفاصيله. اتمنالكم حظ سعيد :heart: +ملحوظة المترجم: الترجمه دي معموله بمزيج من اللغه الانجليزية و اللغه العامية العربية المستخدمه في مصر. انا مشيت في اتجاه اني استخدم اللغه الانجليزية في جزئيات معينه لأن مينفعش تتكتب بالعربي بطريقة او بأخرى من غير ما تفقد المعنى او يبقى البحث عنها بعد كده صعب. لو عندك اقتراح للترجمه اعمل منشن وانت بتعمل `issue` على الموقع هنا. + --- ###### 1. ايه اللي هيتطبع؟ @@ -29,7 +31,7 @@ sayHi(); - ج: `ReferenceError` و `21` - د: `undefined` و `ReferenceError` -
Answer +
الاجابة

#### الاجابة الصحيحة: د @@ -467,19 +469,20 @@ console.log(sarah); - أ: صحيحة - ب: خطأ -

Answer +
الاجابة

-#### Answer: B +#### الاجابة الصحيحة: ب + +كل العناصر في جافاسكربت ليها `prototype` ما عدا الـ**base object** و اللي كل العناصر بتاخد منه الدوال بتاعته. ده السبب اللي بيخليك تقدر تستعمل الدوال دي في اي عنصر تعمله. -All objects have prototypes, except for the **base object**. 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. What's the output? +###### 15. ايه اللي هيتطبع؟
```javascript @@ -491,26 +494,26 @@ sum(1, "2"); ```
-- A: `NaN` -- B: `TypeError` -- C: `"12"` -- D: `3` +- أ: `NaN` +- ب: `TypeError` +- ج: `12` +- د: `3` -
Answer +
الاجابة

-#### Answer: 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. +جافاسكربت `dynamic` و بالتالي احنا مش بنحدد نوع المتغير لما بنعمله و المتغير نوعه بيتغير عادي جداً و ممكن ده يحصل من غير ما تعرف حتى و ده اسمه `implicit coercion`. -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"`. +في المثال ده بقى جافاسكربت هتحول رقم `1` الى `string` عشان الدالة تقدر تتعامل معاه و ترجع قيمة. و في عملية الجمع مابين القيمة العددية `1` و السترنج `"2"` الرقم هيتحول الى سترنج و بعد كده هيقوم متضاف الى السترنج التانية عشان يعمل سترنج `"12"`.

--- -###### 16. What's the output? +###### 16. ايه اللي هيتطبع؟
@@ -522,34 +525,26 @@ console.log(number); ```
-- A: `1` `1` `2` -- B: `1` `2` `2` -- C: `0` `2` `2` -- D: `0` `1` `2` +- أ: `1` `1` `2` +- ب: `1` `2` `2` +- ج: `0` `2` `2` +- د: `0` `1` `2` -
Answer +
الاجابة

-#### Answer: 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`) +العامل البعدي `x++` بيرجع القيمة الاصلية الاول بعد كده يزود واحد على المتغير -This returns `0 2 2`. +اما العامل القبلي `++x` بيعدل القيمة الاول و يرجع القيمة المعدلة

--- -###### 17. What's the output? +###### 17. ايه اللي هيتطبع؟ (جرب تشغل السؤال ده عشان تفهمه كويس)
@@ -567,24 +562,24 @@ getPersonInfo`${person} is ${age} years old`; ```
+- أ: `"Lydia"` `21` `["", " is ", " years old"]` +- ب: `["", " is ", " years old"]` `"Lydia"` `21` +- ج: `"Lydia"` `["", " is ", " years old"]` `21` -- A: `"Lydia"` `21` `["", " is ", " years old"]` -- B: `["", " is ", " years old"]` `"Lydia"` `21` -- C: `"Lydia"` `["", " is ", " years old"]` `21` - -
Answer +
الاجابة

-#### Answer: 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! +لو بتستعمل `tagged template literals` اول قيمة داخله للدالة دايماً هتكون `array` مليانه بالسترنج اللي داخله فقط من غير اي متغيرات و الباقي هياخدوا القيم اللي داخله بالترتيب.

--- -###### 18. What's the output? +###### 18. ايه اللي هيتطبع؟
@@ -603,28 +598,26 @@ checkAge({ age: 18 }); ```
+- أ: `You are an adult!` +- ب: `You are still an adult.` +- ج: `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` - -
Answer +
الاجابة

-#### Answer: 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. +لما بنقارن في جافاسكربت, القيم الـ`primitive` زي الارقام و السترنج البسيطة بيتم مقارنة قيمتها فقط بينما الاوبجكتس بيتم مقارنة الاشارة ليهم `reference`. يعني لما بنقارن اوبجكتس ببعض جافاسكربت بتشوف هل الاتنين بيشاوروا لنفس المكان في الرام ولا لا. -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. What's the output? +###### 19. ايه اللي هيتطبع؟
@@ -638,24 +631,25 @@ getAge(21);
-- A: `"number"` -- B: `"array"` -- C: `"object"` -- D: `"NaN"` +- أ: `"number"` +- ب: `"array"` +- ج: `"object"` +- د: `"NaN"` + -
Answer +
الاجابة

-#### Answer: C +#### الاجابة الصحيحة: ج -The spread operator (`...args`.) returns an array with arguments. An array is an object, so `typeof args` returns `"object"` +معامل التفكيك `spread operator ...args` بيرجع `array` فيها الـقيم اللي داخله للدالة. و بما ان كل حاجه في جافاسكربت عبارة عن اوبجكت بما فيها الـ`array` يبقى القيمه اللي هترجع `"object"`

--- -###### 20. What's the output? +###### 20. ايه اللي هيتطبع؟
@@ -671,24 +665,25 @@ getAge();
-- A: `21` -- B: `undefined` -- C: `ReferenceError` -- D: `TypeError` +- أ: `21` +- ب: `undefined` +- ج: `ReferenceError` +- د: `TypeError` -
Answer +
الاجابة

-#### Answer: C +#### الاجابة الصحيحة: ج + +لما بنستعمل `"use strict"` تقدر تتأكد ان انت مش بتعمل متغيرات `global` عن طريق الخطأ. احنا هنا عمرنا ما عملنا `declare` للمتغير `age` اصلاً و بما اننا بنستعمل `"use strict"` البرنامج هيدينا خطأ من نوع `ReferenceError`. -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 value of `sum`? +###### 21. ايه قيمة `sum`?
@@ -697,25 +692,25 @@ const sum = eval("10*10+5"); ```
+- أ: `105` +- ب: `"105"` +- ج: `TypeError` +- د: `"10*10+5"` -- A: `105` -- B: `"105"` -- C: `TypeError` -- D: `"10*10+5"` - -
Answer +
الاجابة

-#### Answer: A +#### الاجابة الصحيحة: أ + +الدالة `eval` بتشغل الكود اللي داخلها على هيئة `string`. لو السترنج دي بتعبر عن عملية حسابية مثلاً هتقوم مشغله العملية دي و بالتالي `10 * 10 + 5` هيرجع القيمة العددية `105`. -`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? +###### 22. cool_secret هتفضل موجوده قد ايه؟
@@ -724,27 +719,26 @@ 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. - -
Answer +
الاجابة

-#### Answer: B +#### الاجابة الصحيحة: ب -The data stored in `sessionStorage` is removed after closing the _tab_. +اي معلومات بيتم تخزينها في الـ`sessionStorage` بتتمسح مجرد ما المستخدم يقفل التبويب. -If you used `localStorage`, the data would've been there forever, unless for example `localStorage.clear()` is invoked. +لو استخدمت `localStorage` المعلومات هتفضل موجوده للأبد او لحد ما تمسحها انت بنفسك في الكود.

--- -###### 23. What's the output? +###### 23. ايه اللي هيتطبع؟
@@ -756,27 +750,25 @@ console.log(num); ```
+- أ: `8` +- ب: `10` +- ج: `SyntaxError` +- د: `ReferenceError` -- A: `8` -- B: `10` -- C: `SyntaxError` -- D: `ReferenceError` -
Answer +
الاجابة

-#### Answer: 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. +مع كلمة `var` احنا بنعمل المتغير من اول و جديد بنفس الاسم و بقيم مختلفه و بالتالي اخر قيمه بس هي اللي هتكون موجودة. مش بيحصل كده مع `let` و `const`.

--- -###### 24. What's the output? +###### 24. ايه اللي هيتطبع؟
@@ -791,27 +783,26 @@ set.has(1); ```
+- أ: `false` `true` `false` `true` +- ب: `false` `true` `true` `true` +- ج: `true` `true` `false` `true` +- د: `true` `true` `true` `true` -- A: `false` `true` `false` `true` -- B: `false` `true` `true` `true` -- C: `true` `true` `false` `true` -- D: `true` `true` `true` `true` - -
Answer +
الاجابة

-#### Answer: 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. +كل مفاتيح العناصر `object keys` ما عدا اللي من نوع `Symbol` عبارة عن قيم `string` حتى لو انت مش كاتبها كسترنج. و ده السبب ان `obj.hasOwnProperty('1')` برضه بترجع `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`. +اما بالنسبه لنوع `set` فا اللي معانا حالياً جواها قيم عددية فقط و بالتالي الـ`string` `'1'` مش موجوده.

--- -###### 25. What's the output? +###### 25. ايه اللي هيتطبع؟
@@ -822,42 +813,44 @@ console.log(obj);
-- A: `{ a: "one", b: "two" }` -- B: `{ b: "two", a: "three" }` -- C: `{ a: "three", b: "two" }` -- D: `SyntaxError` +- أ: `{ a: "one", b: "two" }` +- ب: `{ b: "two", a: "three" }` +- ج: `{ a: "three", b: "two" }` +- د: `SyntaxError` -
Answer +
الاجابة

-#### Answer: C +#### الاجابة الصحيحة: ج + +لو عندك في العنصر اكتر من قيمة `object key` بنفس الاسم, هيتم استبدال القيم اللي موجوده بآخر قيمة تم تسجيلها. -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. +###### 26. في جافاسكربت, بنلاقي حاجتين موجودين دايماً وهما الـ `global` و كلمة ال `this` المفتاحية. العبارة دي: -- A: true -- B: false -- C: it depends +- أ: صحيحة +- ب: خاطئة +- ج: تعتمد -
Answer +
الاجابة

-#### Answer: A +#### الاجابة الصحيحة: أ + +و دي حاجه اسمها `global execution context` واللي يمكن اعتباره عن محيط او البيئة اللي الكوود بيشتغل فيه و بيكون فيه المتغيرات الـ`global` كلها. -The base execution context is the global execution context: it's what's accessible everywhere in your code.

--- -###### 27. What's the output? +###### 27. ايه اللي هيتطبع؟
@@ -869,25 +862,25 @@ for (let i = 1; i < 5; i++) { ```
+- أ: `1` `2` +- ب: `1` `2` `3` +- ج: `1` `2` `4` +- د: `1` `3` `4` -- A: `1` `2` -- B: `1` `2` `3` -- C: `1` `2` `4` -- D: `1` `3` `4` -
Answer +
الاجابة

-#### Answer: C +#### الاجابة الصحيحة: ج -The `continue` statement skips an iteration if a certain condition returns `true`. +كلمة `continue` بتخلي اللووب تكمل لو الشرط اللي هي جواه اتحقق.

--- -###### 28. What's the output? +###### 28. ايه اللي هيتطبع؟
@@ -903,24 +896,25 @@ name.giveLydiaPizza();
-- A: `"Just give Lydia pizza already!"` -- B: `TypeError: not a function` -- C: `SyntaxError` -- D: `undefined` -
Answer +- أ: `"Just give Lydia pizza already!"` +- ب: `TypeError: not a function` +- ج: `SyntaxError` +- د: `undefined` + +
الاجابة

-#### 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` هو فنكشن `constructor` واللي بنقدر نضيف خواص و قيم ليه. انا هنا ضيفت دالة للـ`prototype` بتاعه. المتغيرات البدائية `primitive` بيتم تحويلها بطريقة تلقائياً الى عنصر `object` وبالتالي بيكون ليها القدره انها تشغل الدوال الخاصه بالنوع ده.

--- -###### 29. What's the output? +###### 29. ايه اللي هيتطبع؟
@@ -936,29 +930,25 @@ console.log(a[b]); ```
+- أ: `123` +- ب: `456` +- ج: `undefined` +- د: `ReferenceError` -- A: `123` -- B: `456` -- C: `undefined` -- D: `ReferenceError` - -
Answer +
الاجابة

-#### Answer: 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`. +مفاتيح العناصر `Object keys` بيتم تحويلهم تلقائياً الى string. احنا هنا بنحاول نحط اوبجكت على انه مفتاح لأوبجكت تاني. بس المشكلة ان لما نعمل كده مش بيترجم لأسمه او لمحتوياته بل بيتحول الى `[Object object] و بالتالي احنا كنا كأننا بالظبط عاملين `a["Object object"]=123` و بنكرر كده مع `c` و بعد كده بنقوم طابعين `a[b]` اللي احنا لسه مخليين مفتاحها من شوية `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. What's the output? +###### 30. ايه اللي هيتطبع؟
@@ -973,49 +963,38 @@ baz(); ```
+- أ: `First` `Second` `Third` +- ب: `First` `Third` `Second` +- ج: `Second` `First` `Third` +- د: `Second` `Third` `First` -- A: `First` `Second` `Third` -- B: `First` `Third` `Second` -- C: `Second` `First` `Third` -- D: `Second` `Third` `First` - -
Answer +
الاجابة

-#### Answer: B +#### الاجابة الصحيحة: ب -We have a `setTimeout` function and invoked it first. Yet, it was logged last. +عندنا دالة `setTimeout` و المفروض تشتغل الاول و لكن اللي جواها اتشغل اخر حاجه. ايه اللي حصل؟ -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. +في المتصفحات محرك الجافاسكربت مش لوحده اللي موجود, بل موجود كمان معاه حاجه اسمها `Web Application APIs` واختصارها `WebAPIs` ودي بتديلك شوية دوال و حاجات زيادة عن اللغه الاساسية زي `setTimeout` اللي مش في اللغه اصلاً. -After the _callback_ is pushed to the WebAPI, the `setTimeout` function itself (but not the callback!) is popped off the stack. +اللي بيحصل بقى ان الدالة اللي جوا `setTimeout` اللي هي الـ `callback` بتتجهز عشان تشتغل, و `setTimeout` نفسها بتخلص, و بعد كده البرنامج بينط على طول على الدالة اللي بعدها و بتشغلها و اللي بعدها و بتشغلها لحد ما ميتبقاش حاجه شاغله المتصفح بعد كده يقوم البرنامج مشغل الـ`callback` اللي كانت متجهزه. -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? +###### 31. ايه قيمة `event.target` لما تدوس على الزرار؟
```html @@ -1029,25 +1008,26 @@ This is where an event loop starts to work. An **event loop** looks at the stack ```
+- أ: Outer `div` +- ب: Inner `div` +- ج: `button` +- د: اراي جواها كل العناصر اللي جوا الزرار -- A: Outer `div` -- B: Inner `div` -- C: `button` -- D: An array of all nested elements. -
Answer +
الاجابة

-#### Answer: C +#### الاجابة الصحيحة: ج -The deepest nested element that caused the event is the target of the event. You can stop bubbling by `event.stopPropagation` +هدف الحدث بيكون اخر عنصر في سلسلة الابناء و تقدر تمنع ده عن طريق `event.stopPropagation`.

--- -###### 32. When you click the paragraph, what's the logged output? +###### 32. لما تدوس على البرجراف ايه اللي هيتطبع؟ +
```html @@ -1059,24 +1039,24 @@ The deepest nested element that caused the event is the target of the event. You ```
-- A: `p` `div` -- B: `div` `p` -- C: `p` -- D: `div` +- أ: `p` `div` +- ب: `div` `p` +- ج: `p` +- د: `div` -
Answer +
الاجابة

-#### 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. +لما تدوس على البرجراف هتلاقي حاجتين ظهروا: `p` و `div`. و اثناء ما الحدث بيتم التعامل معاه بيحصل 3 مراحل زي ما قولنا في سؤال قبل كده. الاساسي ان الدوال اللي انت بتحددها عشان تتعامل مع الاحداث بتشتغل في اخر مرحله و هي الـ`Bubbling` و بالتالي هيتشغل من اعمق عنصر الى اكبر عنصر.

--- -###### 33. What's the output? +###### 33. ايه اللي هيتطبع؟
@@ -1092,27 +1072,25 @@ sayHi.bind(person, 21); ```
+- أ: `undefined is 21` `Lydia is 21` +- ب: `function` `function` +- ج: `Lydia is 21` `Lydia is 21` +- د: `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` - -
Answer +
الاجابة

-#### Answer: D +#### الاجابة الصحيحة: د -With both, we can pass the object to which we want the `this` keyword to refer to. However, `.call` is also _executed immediately_! +في الحالتين بنقدر نحدد احنا عايزين كلمة `this` تشير لأيه بالظبط. بس الفرق ان `call` بتشتغل على طول اما `bind` بترجع نسخة جديدة من الدالة اللي دخلتلها قيمة `this` بتاعتها اللي احنا محددينها بس مش بتشتغل على طول. -`.bind.` returns a _copy_ of the function, but with a bound context! It is not executed immediately.

--- -###### 34. What's the output? +###### 34. ايه اللي هيتطبع؟
@@ -1125,27 +1103,26 @@ typeof sayHi(); ```
+- أ: `"object"` +- ب: `"number"` +- ج: `"function"` +- د: `"undefined"` -- A: `"object"` -- B: `"number"` -- C: `"function"` -- D: `"undefined"` - -
Answer +
الاجابة

-#### Answer: B +#### الاجابة الصحيحة: ب -The `sayHi` function returns the returned value of the immediately invoked function (IIFE). This function returned `0`, which is type `"number"`. +الدالة `sayHi` بترجع القيمة اللي بتيجي من الدالة ذاتية التشغيل (IIFE) و اللي بدورها بترجع قيمة نوعها `"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"`. +ولمعلومات القارئ: في 3 انواع فقط في الجافاسكربت: `null`, `undefined`, `boolean`, `number`, `string`, `object` و `symbol`. الدوال ليست نوع و انما هما عناصر من نوع `object`.

--- -###### 35. Which of these values are falsy? +###### 35. انهي قيمة من دول سالبية `false`؟
@@ -1159,18 +1136,17 @@ undefined; ```
+- أ: `0`, `''`, `undefined` +- ب: `0`, `new Number(0)`, `''`, `new Boolean(false)`, `undefined` +- ج: `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 - -
Answer +
الاجابة

-#### Answer: A +#### الاجابة الصحيحة: أ -There are only six falsy values: +موجود في اللغه 6 قيم سالبية `false` فقط: - `undefined` - `null` @@ -1179,14 +1155,14 @@ There are only six falsy values: - `''` (empty string) - `false` -Function constructors, like `new Number` and `new Boolean` are truthy. +اي `constructor` بيكون ايجابي `truthy` علشان بيرجع قيمة مش واحدة من اللي 6 دول.

--- -###### 36. What's the output? +###### 36. ايه اللي هيتطبع؟
@@ -1195,26 +1171,24 @@ console.log(typeof typeof 1); ```
+- أ: `"number"` +- ب: `"string"` +- ج: `"object"` +- د: `"undefined"` -- A: `"number"` -- B: `"string"` -- C: `"object"` -- D: `"undefined"` - -
Answer +
الاجابة

-#### Answer: B +#### الاجابة الصحيحة: ب -`typeof 1` returns `"number"`. -`typeof "number"` returns `"string"` +`typeof 1` هترجع `"number"` و لاحظ ان دي مابين `""` يعني سترنج و بالتالي لما تدخل في الـ `typeof "number"` هترجع `"string"`

--- -###### 37. What's the output? +###### 37. ايه اللي هيتطبع؟
@@ -1225,29 +1199,29 @@ console.log(numbers); ```
+- أ: `[1, 2, 3, 7 x null, 11]` +- ب: `[1, 2, 3, 11]` +- ج: `[1, 2, 3, 7 x empty, 11]` +- د: `SyntaxError` -- A: `[1, 2, 3, 7 x null, 11]` -- B: `[1, 2, 3, 11]` -- C: `[1, 2, 3, 7 x empty, 11]` -- D: `SyntaxError` - -
Answer +
الاجابة

-#### Answer: 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: +لما بتحط قيمة في مكان في `array` و المكان ده بيتعدى عدد المساحات الموجوده في الاراي (طولها) بتقوم جافاسكربت بعمل حاجه اسمها "مساحات فارغه" "empty slots" واللي بيكونوا قيمهم `undefined` ولكن لما تبص في الكونسول بتاعت المتصفح مثلاً هتلاقي الشكل طالعلك كده: `[1, 2, 3, 7 x empty, 11]` -depending on where you run it (it's different for every browser, node, etc.) +و الشكل بيعتمد على حسب انت بتشغل الكود فين. كل متصفح بيطلعها بشكل مختلف, و تقدر تجربها بنفسك. +

--- -###### 38. What's the output? +###### 38. ايه اللي هيتطبع؟
@@ -1266,52 +1240,49 @@ depending on where you run it (it's different for every browser, node, etc.) ```
+- أ: `1` `undefined` `2` +- ب: `undefined` `undefined` `undefined` +- ج: `1` `1` `2` +- د: `1` `undefined` `undefined` -- A: `1` `undefined` `2` -- B: `undefined` `undefined` `undefined` -- C: `1` `1` `2` -- D: `1` `undefined` `undefined` -
Answer +
الاجابة

-#### Answer: 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`. +جزء الـ`catch` بيستلم متغير `x` بس الفرق ان الاكس في الحاله دي مش بتاعت الداله و انما ده متغير موجود فقط لجزء الـ `catch`. بعد كده احنا قومنا مغيرين القيمة بتاعته الى `1` و غيرنا قيمة المتغير `y` الى `2`. بعد كده قومنا طابعين القيم اللي موجودة جوا جزء الـ`catch` فقط. -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`. +برا الجزء بتاع الـ`catch` اكس هيفضل برضه `undefined` و `y` بما ان مفيش الا واحدة بس و هي بتاعت الدالة الاساسية واحنا غيرنا قيمتها بالتالي هتفضل على القيمة المتغيره اللي هي `2`.

--- -###### 39. Everything in JavaScript is either a... +###### 39. كل حاجه في جافاسكربت ... -- A: primitive or object -- B: function or object -- C: trick question! only objects -- D: number or object +- أ: primitive او عنصر `object` +- ب: function او عنصر `object` +- ج: عناصر `object` بس! +- د: رقم او عنصر `object` -
Answer -

-#### Answer: A +

الاجابة +

-JavaScript only has primitive types and objects. +#### الاجابة الصحيحة: أ -Primitive types are `boolean`, `null`, `undefined`, `bigint`, `number`, `string`, and `symbol`. +جافاسكربت فيها انواع بدائية\بسيطة `primitives` و عناصر `object` فقط. الانواع البسيطة هما: `boolean`, `null`, `undefined`, `bigint`, `number`, `string`, و `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 implicity wrap the object 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. +الفرق بين البسيطة و العناصر ان البسيطة مفيهاش اي دوال `methods` ولكن بنلاحظ ان لما مثلاُ بنحاول نشغل دالة على نوع بسيط زي `'foo'.toUpperCase()` الداله بتشتغل عادي جداً من غير ما تدينا خطأ `TypeError` و ده لأن زي ما قولنا في اجابة سابقه ان لما بنحاول نستغل الدوال دول جافاسكربت بتقوم تلقائياً بتحويل القيم البدائية اللي بنحاول نشغل عليها الدوال دي الى قيم من نوع `object` عشان تقدر تشغل الدوال دول و بعد كده ترجعها زي ما كانت. كل الانواع البسيطة بينطبق عليها الكلام ده ما عدا `undefined` و `null`.

--- -###### 40. What's the output? +###### 40. ايه اللي هيتطبع؟
@@ -1325,27 +1296,26 @@ What differentiates a primitive from an object is that primitives do not have an ```
+- أ: `[0, 1, 2, 3, 1, 2]` +- ب: `[6, 1, 2]` +- ج: `[1, 2, 0, 1, 2, 3]` +- د: `[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]` -
Answer +
الاجابة

-#### Answer: 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]`. +الاراي `[1,2]` هي القيمه الاساسية اللي معانا و اللي هنبدأ بيها و هي برضه اول قيمة للمتغير `acc`. في الدورة الاولى المتغير `acc` قيمته `[1,2]` و المتغير `cur` قيمته `[0,1]` و لما نجمعهم سوا بيكون الناتج `[1,2,0,1]` و بعد كده المتغير `acc` بياخد القيمة دي و يقوم دامجها مع `[2,3]` اللي هي قيمة `cur` في الدورة التانية و اللي بدوره بيدي الناتج النهائي `[1, 2, 0, 1, 2, 3]`. -Then, `[1, 2, 0, 1]` is `acc` and `[2, 3]` is `cur`. We concatenate them, and get `[1, 2, 0, 1, 2, 3]`

--- -###### 41. What's the output? +###### 41. ايه اللي هيتطبع؟
@@ -1357,28 +1327,30 @@ Then, `[1, 2, 0, 1]` is `acc` and `[2, 3]` is `cur`. We concatenate them, and ge
-- A: `false` `true` `false` -- B: `false` `false` `true` -- C: `false` `true` `true` -- D: `true` `true` `false` +- أ: `false` `true` `false` +- ب: `false` `false` `true` +- ج: `false` `true` `true` +- د: `true` `true` `false` + -
Answer +
الاجابة

-#### Answer: B +#### الاجابة الصحيحة: ب + +`null` قيمة سالبية `falsy` و بالتالي `!null` هترجع قيمة ايجابية `true` و بعد كده بتخش `!true` فا تتحول `false` -`null` is falsy. `!null` returns `true`. `!true` returns `false`. +وزي ما قولنا `""` دي قيمة سالبية لما نجيب عكسها هتتحول هي لـ`false` و بعد كده السالب بتاعها هيكون `true` و بعد كده تدخل في سالب تاني فتبقى `false` -`""` is falsy. `!""` returns `true`. `!true` returns `false`. +بعد كده عندنا رقم `1` اللي هو قيمة ايجابية و بدوره بيتحول مره يبقى سالبية و بعد كده يبقى ايجابية `true`. -`1` is truthy. `!1` returns `false`. `!false` returns `true`.

--- -###### 42. What does the `setInterval` method return in the browser? +###### 42. دالة `setInterval` بترجع ايه في المتصفح؟
@@ -1388,24 +1360,25 @@ setInterval(() => console.log("Hi"), 1000);
-- A: a unique id -- B: the amount of milliseconds specified -- C: the passed function -- D: `undefined` +- أ: اسم تعريفي فريد من نوعه `unique id` +- ب: الوقت المحدد +- ج: الداله المدخله معاها +- د: `undefined` -
Answer +
الاجابة

-#### Answer: A +#### الاجابة الصحيحة: أ + +دالة `setInterval` بترجع اسم تعريفي فريد تقدر تستعمله في `clearInterval` عشان توقف بيه التكرار. -It returns a unique id. This id can be used to clear that interval with the `clearInterval()` function.

--- -###### 43. What does this return? +###### 43. ايه القيمة اللي هتطلع هنا؟
@@ -1415,17 +1388,18 @@ It returns a unique id. This id can be used to clear that interval with the `cle
-- A: `["L", "y", "d", "i", "a"]` -- B: `["Lydia"]` -- C: `[[], "Lydia"]` -- D: `[["L", "y", "d", "i", "a"]]` +- أ: `["L", "y", "d", "i", "a"]` +- ب: `["Lydia"]` +- ج: `[[], "Lydia"]` +- د: `[["L", "y", "d", "i", "a"]]` -
Answer +
الاجابة

-#### Answer: A +#### الاجابة الصحيحة: أ + +القيم اللي من نوع `string` بنقدر نعدي عليها عادي و بالتالي بنقدر نستعمل الـ Spread operator `...x` عشان نحول كل حرف الى عنصر في اراي. -A string is an iterable. The spread operator maps every character of an iterable to one element.

From d6db33e526717aa3737eb9300f382cc6fd032d3f Mon Sep 17 00:00:00 2001 From: Nabil Tharwat Date: Sat, 22 Jun 2019 21:32:25 +0200 Subject: [PATCH 099/915] Added Egyptian Arabic file link --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 916fa133..96fd23b2 100644 --- a/README.md +++ b/README.md @@ -11,7 +11,7 @@ The answers are in the collapsed sections below the questions, simply click on t [Western Balkan](./README-bs_BS.md) [Deutsch](./README-de_DE.md) [Tiếng Việt](./README-vi.md) - +[اللغة العامية - Egyptian Arabic](./README_ar-EG.md) --- From 30172b48b64c405d81d1f3cd8f84c1547fff3be4 Mon Sep 17 00:00:00 2001 From: Ihor Sychevskyi <26163841+Arhell@users.noreply.github.com> Date: Sun, 23 Jun 2019 00:58:47 +0300 Subject: [PATCH 100/915] Upd links & fix typo --- README-ua_UA.md | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/README-ua_UA.md b/README-ua_UA.md index 18f2d4af..0a1a935e 100644 --- a/README-ua_UA.md +++ b/README-ua_UA.md @@ -8,9 +8,10 @@ [中文版本](./README-zh_CN.md) [Русский](./README_ru-RU.md) -[Western Balkan](./README-bs.md) +[Western Balkan](./README-bs_BS.md) [Deutsch](./README-de_DE.md) [Tiếng Việt](./README-vi.md) +[日本語](./README-ja_JA.md) --- @@ -37,7 +38,7 @@ sayHi(); #### Відповідь: D -Усередині функції ми спершу визначаємо змінну `name` за допомогою ключового слова `var`. Це означає, що змінна буде знайдена (область пам'яті під змінну буде виділена під час створення) зі значенням `undefined` за замовчуванням, до тих пора поки виконання коду не дійде до рядка, де визначається змінна. Ми ще не визначили значення name, коли намагаємося вивести її в консоль, тому в консолі буде `undefined`. +Усередині функції ми спершу визначаємо змінну `name` за допомогою ключового слова `var`. Це означає, що змінна буде знайдена (область пам'яті під змінну буде виділена під час створення) зі значенням `undefined` за замовчуванням, до тих пір поки виконання коду не дійде до рядка, де визначається змінна. Ми ще не визначили значення name, коли намагаємося вивести її в консоль, тому в консолі буде `undefined`. Змінні, визначені за допомогою `let` (і `const`), також знаходяться, але на відміну від `var`, не створюються. Доступ до них неможливий до тих пір, поки не виконається рядок їх визначення (ініціалізації). Це називається "тимчасова мертва зона". Коли ми намагаємося звернутися до змінних до того моменту як вони визначені, JavaScript видає `ReferenceError`. From 06fb9abe1c7a7c0cec5e9da6f73d865ebc72a30f Mon Sep 17 00:00:00 2001 From: kimdanah Date: Mon, 24 Jun 2019 00:18:33 +0900 Subject: [PATCH 101/915] Translate the questions 11-20 to Korean --- README-ko_KR.md | 92 ++++++++++++++++++++++++------------------------- 1 file changed, 46 insertions(+), 46 deletions(-) diff --git a/README-ko_KR.md b/README-ko_KR.md index c50e3288..13154c27 100644 --- a/README-ko_KR.md +++ b/README-ko_KR.md @@ -30,10 +30,10 @@ function sayHi() { sayHi(); ``` -- A: `Lydia` 와 `undefined` -- B: `Lydia` 와 `ReferenceError` -- C: `ReferenceError` 와 `21` -- D: `undefined` 와 `ReferenceError` +- A: `Lydia` 그리고 `undefined` +- B: `Lydia` 그리고 `ReferenceError` +- C: `ReferenceError` 그리고 `21` +- D: `undefined` 그리고 `ReferenceError`
정답

@@ -61,9 +61,9 @@ for (let i = 0; i < 3; i++) { } ``` -- A: `0 1 2` 와 `0 1 2` -- B: `0 1 2` 와 `3 3 3` -- C: `3 3 3` 와 `0 1 2` +- A: `0 1 2` 그리고 `0 1 2` +- B: `0 1 2` 그리고 `3 3 3` +- C: `3 3 3` 그리고 `0 1 2`

정답

@@ -94,10 +94,10 @@ shape.diameter(); shape.perimeter(); ``` -- A: `20` 과 `62.83185307179586` -- B: `20` 과 `NaN` -- C: `20` 과 `63` -- D: `NaN` 과 `63` +- A: `20` 그리고 `62.83185307179586` +- B: `20` 그리고 `NaN` +- C: `20` 그리고 `63` +- D: `NaN` 그리고 `63`

정답

@@ -122,9 +122,9 @@ shape.perimeter(); !"Lydia"; ``` -- A: `1` 과 `false` -- B: `false` 와 `NaN` -- C: `false` 와 `false` +- A: `1` 그리고 `false` +- B: `false` 그리고 `NaN` +- C: `false` 그리고 `false`

정답

@@ -190,7 +190,7 @@ console.log(d.greeting); ``` - A: `Hello` -- B: `Hey` +- B: `Hey!` - C: `undefined` - D: `ReferenceError` - E: `TypeError` @@ -235,7 +235,7 @@ console.log(b === c); #### 정답: C -`new Number()`는, 내장 함수 생성자에요. 숫자처럼 보이지만, 실제로는 숫자가 아니에요: 많은 추가 특징이 있고 그것은 객체에요. +`new Number()`는, 내장 함수 생성자에요. 숫자처럼 보이지만, 실제로는 숫자가 아니에요: 많은 추가 특성이 있고 그것은 객체에요. `==`연산자를 사용할 때, 그건 같은 _값_ 을 가지고 있는지 여부만 확인해요. 그것들은 모두`3`의 값을 가지고 있으므로, `true`를 리턴해요. @@ -328,9 +328,9 @@ bark.animal = "dog"; #### 정답: A JavaScript에서는 가능해요, 함수는 객체이기 때문이에요! -(프리미티브형 이외는 모두 객체에요) +(프리미티브형 이외는 모두 객체) -함수는 특별한 종류의 객체에요. 자신이 쓴 코드는 실제 함수가 아니에요. 함수는 속성을 가진 객체에요. 이 속성은 호출이 가능해요. +함수는 특별한 종류의 객체에요. 당신이 쓴 코드는 실제 함수가 아니에요. 함수는 속성을 가진 객체에요. 이 속성은 호출이 가능해요.

@@ -363,7 +363,7 @@ console.log(member.getFullName()); #### 정답: A -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() { @@ -371,7 +371,7 @@ Person.prototype.getFullName = function() { }; ``` -would have made `member.getFullName()` work. Why is this beneficial? Say that we added this method to the constructor itself. Maybe not every `Person` instance needed this method. This would waste a lot of memory space, since they would still have that property, which takes of memory space for each instance. Instead, if we only add it to the prototype, we just have it at one spot in memory, yet they all have access to it! +`member.getFullName()`은 작동되요. 이것은 왜 유익할까요? 이 메소드를 생성자 자체에 추가했다고 할게요. 아마도 모든 `Person` 인스턴스는 이 메소드를 필요로 하지 않을 수도 있어요. 그 경우 그들은 아직 속성을 갖고, 각각의 인스턴스를 위해 메모리 공간을 소비하기 때문에, 많은 메모리 공간을 낭비하게 되요. 대신에, 프로토타입을 추가하는 것만으로, 메모리의 한 지점을 가지지만, 모든 것들은 그것에 접근 할 수 있어요.

@@ -393,26 +393,26 @@ 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` +- A: `Person {firstName: "Lydia", lastName: "Hallie"}` 그리고 `undefined` +- B: `Person {firstName: "Lydia", lastName: "Hallie"}` 그리고 `Person {firstName: "Sarah", lastName: "Smith"}` +- C: `Person {firstName: "Lydia", lastName: "Hallie"}` 그리고 `{}` +- D:`Person {firstName: "Lydia", lastName: "Hallie"}` 그리고 `ReferenceError`
정답

#### 정답: A -For `sarah`, we didn't use the `new` keyword. When using `new`, it refers to the new empty object we create. However, if you don't add `new` it refers to the **global object**! +`sarah`를 위해, `new`키워드를 사용하지 않았어요. `new`를 사용한 경우, 이것은 우리가 만든 새로운 빈 객체를 참조해요. 그러나, `new`를 추가하지 않으면 **전역변수**를 참조하게 되요! -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`. +`this.firstName`에 `"Sarah"`을 대입하고, `this.lastName`에 `"Smith"`을 대입 했다고 말했었어요. (그렇지만) 우리는 실제로, `global.firstName = 'Sarah'` 그리고 `global.lastName = 'Smith'`를 정의한거에요. `sarah` 자체는 `undefined`로 남아있어요.

--- -###### 13. What are the three phases of event propagation? +###### 13. 이벤트 전달의 3단계는 무엇일까요? - A: Target > Capturing > Bubbling - B: Bubbling > Target > Capturing @@ -424,7 +424,7 @@ We said that `this.firstName` equals `"Sarah"` and `this.lastName` equals `"Smit #### 정답: 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. +**capturing** 단계 동안에, 이벤트는 조상요소를 거쳐 목표 요소까지 내려가요. 그런 다음 **target** 요소에 도달하고, **bubbling**이 시작되요. @@ -433,7 +433,7 @@ During the **capturing** phase, the event goes through the ancestor elements dow --- -###### 14. All object have prototypes. +###### 14. 모든 객체는 프로토 타입을 가져요. - A: true - B: false @@ -443,7 +443,7 @@ During the **capturing** phase, the event goes through the ancestor elements dow #### 정답: B -All objects have prototypes, except for the **base object**. 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. +**기본객체**를 제외한, 모든 객체는 프로포타입을 가져요. 기본객체는 `.toString`와 같은 몇개의 메소드와 속성에 접근할 수 있어요. 이것이 내장 JavaScript 메소드를 사용할 수 있는 이유죠! 이러한 모든 메소드는 프로토 타입에서 이용 할 수 있어요. JavaScript가 당신의 객체를 직접 찾을 수 없더라도, 당신이 접근 할 수 있도록, 프로토타입 체인으로 내려가서 찾을거에요.

@@ -470,9 +470,9 @@ sum(1, "2"); #### 정답: 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. +JavaScript는 **동적으로 만들어진 언어**에요: 특정변수가 어떤 타입인지 지정하지 않아요. 변수는 당신이 모르는 사이에 자동으로 다른 타입으로 변환 될 수 있는데, 이걸 _암묵적 타입 변환_ 이라고 불러요. **Coercion**은 하나의 타입을 다른 타입으로 변환하는 거에요. -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"`. +이 예제에서, 함수가 이해하고 값을 리턴하도록, JavaScript는 숫자 `1`을 문자열로 변환해요. 수형 (`1`)와 문자열형 (`'2'`)의 추가 중에는, 숫자는 문자열로 취급되요. `"Hello" + "World"`처럼 문자열을 연결할 수 있어요, 따라서 여기 `"1" + "2"`는 `"12"`을 리턴하는 일이 발생해요.

@@ -498,17 +498,17 @@ console.log(number); #### 정답: C -The **postfix** unary operator `++`: +**접미사** 단항연산자 `++`: -1. Returns the value (this returns `0`) -2. Increments the value (number is now `1`) +1. 값 리턴 (이것은 `0`을 리턴해요) +2. 값 증가 (number는 지금 `1`이에요) -The **prefix** unary operator `++`: +**접두사** 단항연산자 `++`: -1. Increments the value (number is now `2`) -2. Returns the value (this returns `2`) +1. 값 증가 (number는 지금 `2`이에요) +2. 값 리턴 (이것은 `2`을 리턴해요) -This returns `0 2 2`. +이건 `0 2 2`을 리턴해요.

@@ -539,7 +539,7 @@ getPersonInfo`${person} is ${age} years old`; #### 정답: 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! +태그드 템플릿 리터럴을 사용하는 경우, 첫번재 인수의 값은 항상 문자열 값의 배열이에요. 나머지 인수는 식을 통과한 값을 얻게 되요.

@@ -571,11 +571,11 @@ checkAge({ age: 18 }); #### 정답: 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. +동등성을 테스트할 때, 프리미티브는 그 _값_ 에 따라 비교되며, 객체는 그들의 _참조_ 에 따라 비교되요. JavaScript 객체가 메모리내의 같은 장소를 참조하고 있는지 여부를 확인해요. -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`. +이것이 `{ age: 18 } === { age: 18 }` 그리고 `{ age: 18 } == { age: 18 }` 두개 다 `false`를 리턴하는 이유죠.

@@ -602,7 +602,7 @@ getAge(21); #### 정답: C -The spread operator (`...args`.) returns an array with arguments. An array is an object, so `typeof args` returns `"object"` +스프레드 연산자 (`...args`.)는 인수를 가진 배열을 리턴해요. 배열은 객체이므로, `typeof args`는 `"object"`를 리턴해요.

@@ -631,14 +631,14 @@ getAge(); #### 정답: 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. +`"use strict"`을 사용하면, 실수로 전역 변수를 선언하지 않게 할 수 있어요. `age`이라는 변수를 선언한적이 전혀없고, `"use strict"`을 사용하고 있으므로, 참조 에러를 던지게 될거에요. 만약 `"use strict"`을 사용하지 않았다면, 이건 작동할거에요, `age` 속성이 전역 객체에 추가된 것이기 때문이죠.

--- -###### 21. What's value of `sum`? +###### 21. `sum`의 값은 무엇일까요? ```javascript const sum = eval("10*10+5"); From 590cdc939ac97c68ab4f0dd5b201af8904c2d52b Mon Sep 17 00:00:00 2001 From: panicdragon Date: Mon, 24 Jun 2019 02:18:19 +0900 Subject: [PATCH 102/915] fix typo Promice to Promise --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 3eb7e7e7..b24516df 100644 --- a/README.md +++ b/README.md @@ -1357,7 +1357,7 @@ Promise.race([firstPromise, secondPromise]).then(res => console.log(res)); #### Answer: B -When we pass multiple promises to the `Promice.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. +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.

From 3cf91a7b5d22fa69d997e7be9623d49cfc6e6e14 Mon Sep 17 00:00:00 2001 From: Lydia Date: Sun, 23 Jun 2019 23:39:55 +0200 Subject: [PATCH 103/915] Fix question 34 --- README.md | 1 - 1 file changed, 1 deletion(-) diff --git a/README.md b/README.md index 51d89179..3b43f55e 100644 --- a/README.md +++ b/README.md @@ -1042,7 +1042,6 @@ 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`, and `symbol`. `"function"` is not a type, since functions are objects, it's of type `"object"`. -

From 026438386c1c7af2bd78cb82223312c67f128036 Mon Sep 17 00:00:00 2001 From: Lydia Date: Sun, 23 Jun 2019 23:50:57 +0200 Subject: [PATCH 104/915] Clarify question 14 --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 3b43f55e..287aec6f 100644 --- a/README.md +++ b/README.md @@ -445,7 +445,7 @@ During the **capturing** phase, the event goes through the ancestor elements dow #### Answer: B -All objects have prototypes, except for the **base object**. 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. +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.

From 77bb0aefadb7e425ed4ff7cbea808fc0f5c06c29 Mon Sep 17 00:00:00 2001 From: Ihor Sychevskyi <26163841+Arhell@users.noreply.github.com> Date: Mon, 24 Jun 2019 01:41:56 +0300 Subject: [PATCH 105/915] Remove double delimiter, UA --- README-ua_UA.md | 2 -- 1 file changed, 2 deletions(-) diff --git a/README-ua_UA.md b/README-ua_UA.md index 0a1a935e..c14d922e 100644 --- a/README-ua_UA.md +++ b/README-ua_UA.md @@ -174,8 +174,6 @@ JavaScript інтерпретує (або розпаковує) оператор --- ---- - ###### 6. Що буде в консолі? ```javascript From 45bc4b6aa02f926975b05aab9077f6548f012985 Mon Sep 17 00:00:00 2001 From: Guilherme Nogara Date: Sun, 23 Jun 2019 21:35:36 -0300 Subject: [PATCH 106/915] Link original README.md MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit E mais um caso de termo usando `` e não era seguido por espaço quando no meio da sentença. --- README.md | 1 + README_pt_BR.md | 2 +- 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index f1d14d90..fc9f42c7 100644 --- a/README.md +++ b/README.md @@ -11,6 +11,7 @@ The answers are in the collapsed sections below the questions, simply click on t [Western Balkan](./README-bs.md) [Deutsch](./README-de_DE.md) [Tiếng Việt](./README-vi.md) +[Português Brasil](./README_pt_BR.md) --- diff --git a/README_pt_BR.md b/README_pt_BR.md index b90a88d8..9b9d5c25 100644 --- a/README_pt_BR.md +++ b/README_pt_BR.md @@ -1009,7 +1009,7 @@ sayHi.bind(person, 21); #### Resposta: D -Com ambos, podemos passar o objeto que queremos que o `this`faça referência. Contudo, `.call` é _executado imediatamente_! +Com ambos, podemos passar o objeto que queremos que o `this` faça referência. Contudo, `.call` é _executado imediatamente_! `.bind.` retorna uma _cópia_ da função, mas com seu contexto vinculado à cópia. E não é executado imediatamente. From ca8df9197c84e141431773e7192810244a2ca4d6 Mon Sep 17 00:00:00 2001 From: Shyam Chen Date: Mon, 24 Jun 2019 09:43:47 +0800 Subject: [PATCH 107/915] fix: duplicate link --- README.md | 1 - 1 file changed, 1 deletion(-) diff --git a/README.md b/README.md index 287aec6f..91d1abbb 100644 --- a/README.md +++ b/README.md @@ -11,7 +11,6 @@ The answers are in the collapsed sections below the questions, simply click on t List of available languages: * [中文版本](./README-zh_CN.md) * [Versión en español](./README-ES.md) -* [中文版本](./README-zh_CN.md) * [日本語](./README-ja_JA.md) * [Русский](./README_ru-RU.md) * [Western Balkan](./README-bs_BS.md) From 1272dcbad19da871dcb4afa5eb1b25cebd0f584d Mon Sep 17 00:00:00 2001 From: Azarias Boutin Date: Mon, 24 Jun 2019 06:17:14 +0200 Subject: [PATCH 108/915] Remove console.log for giveLydiaPizza --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 5b742ac1..0411ce54 100644 --- a/README.md +++ b/README.md @@ -804,7 +804,7 @@ String.prototype.giveLydiaPizza = () => { const name = "Lydia"; -console.log(name.giveLydiaPizza()); +name.giveLydiaPizza(); ``` - A: `"Just give Lydia pizza already!"` From 6118d053b79a5b94ea01a7d5e212550d52911139 Mon Sep 17 00:00:00 2001 From: Dima Yavorskiy <33015386+yavorskiydima@users.noreply.github.com> Date: Mon, 24 Jun 2019 10:23:02 +0500 Subject: [PATCH 109/915] ru translate 44-50 question --- README_ru-RU.md | 360 ++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 360 insertions(+) diff --git a/README_ru-RU.md b/README_ru-RU.md index d0dbeda4..233f3f9b 100644 --- a/README_ru-RU.md +++ b/README_ru-RU.md @@ -1295,3 +1295,363 @@ 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` + +
Ответ +

+ +#### Ответ: 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, "один"); +}); + +const secondPromise = new Promise((res, rej) => { + setTimeout(res, 100, "два"); +}); + +Promise.race([firstPromise, secondPromise]).then(res => console.log(res)); +``` + +- A: `"один"` +- B: `"два"` +- C: `"два" "один"` +- D: `"один" "два"` + +
Ответ +

+ +#### Ответ: B + +Когда мы передаем несколько промисов методу `Promise.race`, он разрешает/отклоняет _первый_ промис, который разрешает/отклоняет. В метод `setTimeout` мы передаем таймер: 500 мс для первого промиса (`firstPromise`) и 100 мс для второго промиса (`secondPromise`). Это означает, что `secondPromise` разрешается первым со значением `'два'`. `res` теперь содержит значение`'два'`, которое выводиться в консоль. + +

+
+ +--- + +###### 46. Каким будет результат? + +```javascript +let person = { name: "Lydia" }; +const members = [person]; +person = null; + +console.log(members); +``` + +- A: `null` +- B: `[null]` +- C: `[{}]` +- D: `[{ name: "Lydia" }]` + +
Ответ +

+ +#### Ответ: D + +Сначала мы объявляем переменную `person` со значением объекта, у которого есть свойство` name`. + + + +Затем мы объявляем переменную с именем `members`. Мы устанавливаем первый элемент этого массива равным значению переменной `person`. Объекты взаимодействуют посредством _ссылок_ при установке их равными друг другу. Когда вы назначаете ссылку из одной переменной в другую, вы создаете _копию_ этой ссылки. (обратите внимание, что у них _не одинаковые_ ссылки!) + + + +Затем мы присваеваем переменной `person` значение `null`. + + + +Мы изменили только значение переменной `person`, а не первый элемент в массиве, поскольку этот элемент имеет другую (скопированную) ссылку на объект. Первый элемент в `members` по-прежнему содержит ссылку на исходный объект. Когда мы выводим в консоль массив `members`, первый элемент по-прежнему содержит значение объекта, который выводится в консоль. + +

+
+ +--- + +###### 47. Каким будет результат? + +```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]` + +
Ответ +

+ +#### Ответ: B + +С помощью цикла `for-in` мы можем перебирать ключи объекта, в данном случае `name` и `age`. Под капотом ключи объекта являются строками (если они не являются Symbol). В каждом цикле мы устанавливаем значение `item` равным текущему ключу, по которому он перебирается. Сначала, `item` равен `name`, и выводится в консоль. Затем `item` равен `age`, который выводится в консоль. + +

+
+ +--- + +###### 48. Каким будет результат? + +```javascript +console.log(3 + 4 + "5"); +``` + +- A: `"345"` +- B: `"75"` +- C: `12` +- D: `"12"` + +
Ответ +

+ +#### Ответ: 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` оценивается первым. Это приводит к числу `7`. + +`7 + '5'` приводит к `"75"` из-за принуждения. JavaScript преобразует число `7` в строку, см. вопрос 15. Мы можем объединить две строки, используя оператор `+`. `"7" + "5"` приводит к `"75"`. + +

+
+ +--- + +###### 49. Какое значение `num`? + +```javascript +const num = parseInt("7*6", 10); +``` + +- A: `42` +- B: `"42"` +- C: `7` +- D: `NaN` + +
Ответ +

+ +#### Ответ: C + +Только первые числа в строке возвращаются. На основе _системы счисления_ (второй аргумент, чтобы указать, к какому типу чисел мы хотим его анализировать: основание 10, шестнадцатеричное, восьмеричное, двоичное и т.д.), `ParseInt` проверяет, являются ли символы в строке допустимыми. Как только он встречает символ, который не является допустимым числом в основании, он прекращает синтаксический анализ и игнорирует следующие символы. + +`*` не является допустимым числом. Он только разбирает `"7"` в десятичную `7`. `num` теперь содержит значение` 7`. + +

+
+ +--- + +###### 50. Каким будет результат? + +```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 ]` + +
Ответ +

+ +#### Ответ: C + +При использовании метода map, значение `num` равно элементу, над которым он в данный момент зацикливается. В этом случае элементы являются числами, поэтому условие оператора if `typeof num === "number"` возвращает `true`. Функция map создает новый массив и вставляет значения, возвращаемые функцией. + +Однако мы не возвращаем значение. Когда мы не возвращаем значение из функции, функция возвращает значение `undefined`. Для каждого элемента в массиве вызывается функциональный блок, поэтому для каждого элемента мы возвращаем "undefined". + +

+
+ +--- + +###### 51. What's the 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"` + +
Answer +

+ +#### Answer: 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. What's the 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!` + +
Answer +

+ +#### Answer: 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. What's the 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` + +
Answer +

+ +#### 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"`. + +

+
+ +--- + +###### 54. What's the 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"` + +
Answer +

+ +#### Answer: 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 (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"`. + +

+
\ No newline at end of file From 5f6887f0c8a87e7d89919ba08fe96c54e8ae9ed7 Mon Sep 17 00:00:00 2001 From: Dima Yavorskiy <33015386+yavorskiydima@users.noreply.github.com> Date: Mon, 24 Jun 2019 10:42:24 +0500 Subject: [PATCH 110/915] ru translate 50-54 --- README_ru-RU.md | 44 ++++++++++++++++++++++---------------------- 1 file changed, 22 insertions(+), 22 deletions(-) diff --git a/README_ru-RU.md b/README_ru-RU.md index 233f3f9b..f4ee0126 100644 --- a/README_ru-RU.md +++ b/README_ru-RU.md @@ -1515,7 +1515,7 @@ const num = parseInt("7*6", 10); --- -###### 51. What's the output? +###### 51. Каким будет результат? ```javascript function getInfo(member, year) { @@ -1536,23 +1536,23 @@ console.log(person, birthYear); - C: `{ name: "Lydia" }, "1998"` - D: `{ name: "Sarah" }, "1997"` -
Answer +
Ответ

-#### Answer: A +#### Ответ: 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). +Аргументы передаются _значением_, если их значение не является объектом, то они передаются _ссылкой_. `birthYear` передается по значению, поскольку это строка, а не объект. Когда мы передаем аргументы по значению, создается _копия_ этого значения (см. вопрос 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"`. +Переменная `birthYear` имеет ссылку на значение `"1997"`. Аргумент `year` также имеет ссылку на значение` "1997" `, но это не то же самое значение, на которое имеется ссылка для `birthYear`. Когда мы обновляем значение `year`, устанавливая `year` равным `"1998"`, мы обновляем только значение `year`. `birthYear` по-прежнему равно `"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"` +Значение `person` является объектом. Аргумент `member` имеет (скопированную) ссылку на _тот же_ объект. Когда мы изменяем свойство объекта, на который `member` ссылается, значение `person` также будет изменено, поскольку они оба имеют ссылку на один и тот же объект. Свойство `name` объекта `person` теперь равно значению `"Lydia"`.

--- -###### 52. What's the output? +###### 52. Каким будет результат? ```javascript function greeting() { @@ -1576,21 +1576,21 @@ sayHi(); - C: `SyntaxError: can only throw Error objects` - D: `"Oh no an error: Hello world!` -
Answer +
Ответ

-#### Answer: D +#### Ответ: 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'`. +С помощью оператора `throw` мы можем создавать собственные ошибки. С этим оператором вы можете генерировать исключения. Исключением может быть строка, число, логическое значение или объект. В этом случае нашим исключением является строка `'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'`. +С помощью оператора `catch` мы можем указать, что делать, если в блоке` try` выдается исключение. Исключение: строка `'Hello world'`. `e` теперь равно той строке, которую мы записываем. Это приводит к `'Oh error: Hello world'`.

--- -###### 53. What's the output? +###### 53. Каким будет результат? ```javascript function Car() { @@ -1607,19 +1607,19 @@ console.log(myCar.make); - C: `ReferenceError` - D: `TypeError` -
Answer +
Ответ

-#### Answer: B +#### Ответ: 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"`. +Когда вы возвращаете свойство, значение свойства равно _возвращаемому_ значению, а не значению, установленному в функции конструктора. Мы возвращаем строку `"Maserati"`, поэтому `myCar.make` равно `"Maserati"`.

--- -###### 54. What's the output? +###### 54. Каким будет результат? ```javascript (() => { @@ -1635,23 +1635,23 @@ console.log(typeof y); - C: `"object", "number"` - D: `"number", "undefined"` -
Answer +
Ответ

-#### Answer: A +#### Ответ: A -`let x = y = 10;` is actually shorthand for: +`let x = y = 10;` на самом деле является сокращением для: ```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`. +Когда мы устанавливаем `y` равным` 10`, мы фактически добавляем свойство `y` к глобальному объекту (`window` в браузере, `global` в Node). В браузере `window.y` теперь равен` 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 (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"`. +Затем мы объявляем переменную `x` со значением` y`, которое равно `10`. Переменные, объявленные с ключевым словом `let`, имею _блочную видимость_, они определены только в блоке, в котором они объявлены; немедленно вызванная функция (IIFE) в этом случае. Когда мы используем оператор `typeof`, операнд` x` не определен: мы пытаемся получить доступ к `x` вне блока, в котором он объявлен. Это означает, что` x` не определен. Значения, которым не присвоено или не объявлено значение, имеют тип `"undefined"`. `console.log(typeof x)` возвращает `"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"`. +Однако мы создали глобальную переменную `y`, установив `y` равным `10`. Это значение доступно в любом месте нашего кода. `y` определен и содержит значение типа `"number"`. `console.log(typeof y)` возвращает `"number"`.

\ No newline at end of file From b82ac5b5865b859ac880417993f65847b851d04e Mon Sep 17 00:00:00 2001 From: Dima Yavorskiy <33015386+yavorskiydima@users.noreply.github.com> Date: Mon, 24 Jun 2019 10:46:14 +0500 Subject: [PATCH 111/915] fix typo --- README_ru-RU.md | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-) diff --git a/README_ru-RU.md b/README_ru-RU.md index f4ee0126..f0ab0df3 100644 --- a/README_ru-RU.md +++ b/README_ru-RU.md @@ -1357,7 +1357,7 @@ Promise.race([firstPromise, secondPromise]).then(res => console.log(res)); #### Ответ: B -Когда мы передаем несколько промисов методу `Promise.race`, он разрешает/отклоняет _первый_ промис, который разрешает/отклоняет. В метод `setTimeout` мы передаем таймер: 500 мс для первого промиса (`firstPromise`) и 100 мс для второго промиса (`secondPromise`). Это означает, что `secondPromise` разрешается первым со значением `'два'`. `res` теперь содержит значение`'два'`, которое выводиться в консоль. +Когда мы передаем несколько промисов методу `Promise.race`, он разрешает/отклоняет _первый_ промис, который разрешает/отклоняет. В метод `setTimeout` мы передаем таймер: 500 мс для первого промиса (`firstPromise`) и 100 мс для второго промиса (`secondPromise`). Это означает, что `secondPromise` разрешается первым со значением `'два'`. `res` теперь содержит значение `'два'`, которое выводиться в консоль.

@@ -1392,7 +1392,7 @@ console.log(members); -Затем мы присваеваем переменной `person` значение `null`. +Затем мы присваиваем переменной `person` значение `null`. @@ -1449,8 +1449,6 @@ console.log(3 + 4 + "5"); #### Ответ: 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` оценивается первым. Это приводит к числу `7`. @@ -1508,7 +1506,7 @@ const num = parseInt("7*6", 10); При использовании метода map, значение `num` равно элементу, над которым он в данный момент зацикливается. В этом случае элементы являются числами, поэтому условие оператора if `typeof num === "number"` возвращает `true`. Функция map создает новый массив и вставляет значения, возвращаемые функцией. -Однако мы не возвращаем значение. Когда мы не возвращаем значение из функции, функция возвращает значение `undefined`. Для каждого элемента в массиве вызывается функциональный блок, поэтому для каждого элемента мы возвращаем "undefined". +Однако мы не возвращаем значение. Когда мы не возвращаем значение из функции, функция возвращает значение `undefined`. Для каждого элемента в массиве вызывается функциональный блок, поэтому для каждого элемента мы возвращаем `undefined`.

From 6507fdac902c12abe2e50d8df004c0d91569a343 Mon Sep 17 00:00:00 2001 From: TuanTV Date: Mon, 24 Jun 2019 15:13:51 +0700 Subject: [PATCH 112/915] translate and change content vietnamese --- README-vi.md | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/README-vi.md b/README-vi.md index 5550ec41..55e61bad 100644 --- a/README-vi.md +++ b/README-vi.md @@ -1,6 +1,6 @@ # Những câu hỏi JavaScript trình độ Advanced -Hàng ngày tôi sẽ post các câu hỏi multichoice lên [Instagram](https://www.instagram.com/theavocoder) của tôi và tại đây nữa! +Hàng ngày tôi sẽ đăng các câu hỏi multichoice lên [Instagram](https://www.instagram.com/theavocoder) của tôi và tại đây nữa! Các câu hỏi sẽ từ cơ bản đến nâng cao: kiểm tra trình độ JavaScript của bạn, làm mới một chút về kiến thức, hay chuẩn bị cho cuộc phỏng vấn lập trình! :muscle: :rocket: Tôi sẽ cập nhật các câu hỏi mới hàng tuần. @@ -157,7 +157,7 @@ const mouse = { #### Đáp án: A -Trong JavaScript thì tất cả keys của các object đều là string (ngoại trừ khi nó là một Symbol). Dù chúng ta không viết chúng như một string, về cơ bản chúng sẽ luôn được convert sang dạng string. +Trong JavaScript thì tất cả keys của các object đều là string (ngoại trừ khi nó là một Symbol). Dù chúng ta không viết chúng như một string, về cơ bản chúng sẽ luôn được chuyển sang dạng string. JavaScript thông dịch (hay unboxes) từng câu lệnh. Khi chúng ta sử dụng cặp dấu ngoặc `[]`, nó sẽ tìm kiếm dấu mở ngoặc đầu tiên `[`, và sẽ tiếp tục tìm kiếm cho tới khi gặp dấu đóng ngoặc `]`. Chỉ khi đó thì câu lệnh mới được thực thi. @@ -463,7 +463,7 @@ sum(1, "2"); #### Đáp án: C -JavaScript là một ngôn ngữ **dynamically typed**: chúng ta không khai báo kiểu dữ liệu khi khai báo biến. Giá trị có thể bị tự động convert sang một kiểu dữ liệu khác mà ta không hề hay biết, điều này được gọi là __implicit type coercion_. **Coercion** có nghĩa là convert từ kiểu này sang kiểu khác. +JavaScript là một ngôn ngữ **dynamically typed**: chúng ta không khai báo kiểu dữ liệu khi khai báo biến. Giá trị có thể bị tự động convert sang một kiểu dữ liệu khác mà ta không hề hay biết, điều này được gọi là _implicit type coercion_. **Coercion** có nghĩa là convert từ kiểu này sang kiểu khác. Trong ví dụ này, JavaScript sẽ convert số `1` sang dạng string. Mỗi khi ta cộng một số (`1`) với một string (`'2'`), số sẽ luôn được xem như là một string. Kết quả sẽ là một phép nối chuỗi giống như `"Hello" + "World"`, vậy nên `"1" + "2"` sẽ trả về là `"12"`. @@ -631,7 +631,7 @@ Với `"use strict"`, chúng ta sẽ đảm bảo được rằng ta sẽ không --- -###### 21. What's value of `sum`? +###### 21. Giá trị của `sum` là gì? ```javascript const sum = eval("10*10+5"); @@ -922,7 +922,7 @@ WebAPI không thể thêm thứ gì đó vào stack cho tới khi nó được s --- -###### 31. What is the event.target when clicking the button? +###### 31. Giá trị của event.target là gì khi click button? ```html
@@ -951,7 +951,7 @@ Phần tử sâu nhất trong các phần tử lồng nhau sẽ là target của --- -###### 32. Khi bạn click vào đoạn văn, cái gì sẽ được ghi ra output? +###### 32. Khi bạn click vào đoạn văn, giá trị của output sẽ là gì? ```html
From 3114326d0b5bc72ea3d8f95fb7754fd02a7d353b Mon Sep 17 00:00:00 2001 From: panicdragon Date: Mon, 24 Jun 2019 02:06:12 +0900 Subject: [PATCH 113/915] add new questions no.44 ~ no.54 & translate to japanese --- README-ja_JA.md | 378 ++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 378 insertions(+) diff --git a/README-ja_JA.md b/README-ja_JA.md index 9ffde70a..155e8969 100644 --- a/README-ja_JA.md +++ b/README-ja_JA.md @@ -1333,3 +1333,381 @@ 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` + +
答え +

+ +#### 答え: C + +通常の関数は、呼び出し後に途中で停止することはできません。ただし、ジェネレータ関数は途中で"停止"し、後で停止した場所から続行することができます。 + +ジェネレータ関数が`yield`キーワードを見つけるたびに、その関数はその後に指定された値を返します。その場合のジェネレータ関数は、値を"返す"わけではないことに注意してください。値を生み出しています。 + +まず、`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"` + +
答え +

+ +#### 答え: B + +複数のプロミスを`Promise.race`メソッドに渡した時、"resolves/rejects"は、"最初"のプロミスの"resolves/rejects"を行います。 + +`setTimeout`メソッドには、タイマーを渡します: 最初のプロミスには500ms(`firstPromise`)、2番目のプロミスには100ms(`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" }]` + +
答え +

+ +#### 答え: D + +まず、`name`プロパティを持つオブジェクトの値を使って、変数`person`を宣言します。 + + + +それから、`members`という変数を宣言します。その配列の最初の要素に、変数`person`の値を代入します。オブジェクトは、互いをイコールで設定すると、「参照」によって相互作用します。 + +ある変数から別の変数への"参照"を代入すると、その参照の"コピー"が作成されます。 (それらは、"同じ参照"を持っていないことに注意してください!) + + + +そして、変数`person`を`null`に設定します。 + + + +その要素はオブジェクトへの異なる(コピーされた)参照を持っているので、`person`変数の値を変更するだけで配列の最初の要素は変更されません。 `members`の最初の要素はまだ元のオブジェクトへの参照を保持しています。 + +`members`配列をログ出力したとき、最初の要素はまだオブジェクトの値を保持しているので、それがログ出力されます。 + +

+
+ +--- + +###### 47. 何が出力されるでしょうか? + +```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]` + +
答え +

+ +#### 答え: B + +この場合、`for-in`ループを使うと、オブジェクトキーである`name`と`age`の繰り返し処理できます。内部的には、オブジェクトキーは文字列です(シンボルではない場合)。 + +すべてのループで、`item`の値は反復している現在のキーに設定されます。まず、`item`は`name`が代入され、ログに出力されます。その後、`item`は`age`が代入され、ログに出力されます。 + +

+
+ +--- + +###### 48. 何が出力されるでしょうか? + +```javascript +console.log(3 + 4 + "5"); +``` + +- A: `"345"` +- B: `"75"` +- C: `12` +- D: `"12"` + +
答え +

+ +#### 答え: B + +演算子結合性は、コンパイラーが式を評価する順序(左から右または右から左)となります。これは、すべての演算子が同じ優先順位を持つ場合にのみ発生します。演算子の種類は1つだけです: `+`。さらに、結合性は左から右です。 + +`3 + 4`が最初に評価されます。これは数字の`7`になります。 + +`7 + '5'`は、強制的に`"75"`になります。 JavaScriptでは、数字の`7`を文字列に変換します。質問15を参照してください。2つの文字列を演算子の`+`を使って連結することができます。よって、`"7" + "5"`は、`"75"`になります。 + +

+
+ +--- + +###### 49. numの値は何ですか? + +```javascript +const num = parseInt("7*6", 10); +``` + +- A: `42` +- B: `"42"` +- C: `7` +- D: `NaN` + +
答え +

+ +#### 答え: C + +文字列の最初の数字だけが返されます。"基数"(解析する数値の種類を指定するための2番目の引数: 基数10, 16進数, 8進数, 2進数など)に基づいて、`parseInt`は文字列内の文字が有効かどうかをチェックします。基数の中で有効な数字ではない文字に出会うと、構文解析を停止して次の文字を無視します。 + +`*`は、有効な数字ではありません。`"7"`を、10進数の`7`に解析するだけです。そのままnumは`7`の値を保持します。 + +

+
+ +--- + +###### 50. 何が出力されるでしょうか? + +```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 ]` + +
答え +

+ +#### 答え: C + +配列をマッピングするとき、`num`の値に代入されるのは、ループで渡ってくる要素となります。この場合、要素は数値なので、ifステートメント `typeof num === "number"`の条件は`true`を返します。 map関数は新しい配列を作成して関数から返された値を挿入します。 + +ただし、値は返されません。関数から値を返さないと、関数は`undefined`を返します。配列内のすべての要素に対して関数ブロックが呼び出されるので、各要素に対して`undefined`を返します。 + +

+
+ +--- + +###### 51. 何が出力されるでしょうか? + +```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"` + +
答え +

+ +#### 答え: A + +値がオブジェクトでない限り、引数は"値"によって渡され、その後、"参照"によって渡されます。 `birthYear`はオブジェクトではなく文字列なので、値で渡されます。引数を値で渡すと、その値の"コピー"が作成されます(質問46を参照)。 + +変数`birthYear`は、値`"1997"`への参照を持ちます。引数`year`は、値`"1997"`も参照していますが、それは`birthYear`が参照しているのと同じ値ではありません。`year`に`"1998"`を代入することによって`year`の値を更新したとしても、`year`の値を更新するだけです。`birthYear`はまだ`"1997"`となります。 + +`person`の値はオブジェクトです。引数`member`は"同じ"オブジェクトへの(コピーされた)参照を持ちます。 + +`member`が参照を持つオブジェクトのプロパティを変更すると、`person`の値も変更されます。これらは両方とも同じオブジェクトへの参照を持つからです。`person`の`name`プロパティは、値の`"Lydia"`となりました。 + +

+
+ +--- + +###### 52. 何が出力されるでしょうか? + +```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!` + +
答え +

+ +#### 答え: D + +`throw`ステートメントを使って、カスタムエラーを作ることができます。このステートメントで、あなたは例外を投げることができます。例外は、string, number, boolean, objectのいずれかとなります。上記の場合だと、例外は文字列`'Hello world'`となります。 + +`catch`ステートメントを使って、`try`ブロックで例外が投げられた場合にどうするかを指定できます。例外がスローされます: 文字列`'Hello world'`は、`e`に代入されます。その結果`'Oh an error: Hello world'`となります。 + +

+
+ +--- + +###### 53. 何が出力されるでしょうか? + +```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` + +
答え +

+ +#### 答え: B + +プロパティを返すと、そのプロパティの値は、コンストラクタ関数で設定された値ではなく、"戻り値"となります。 `"Maserati"`という文字列を返すので、`myCar.make`は `"Maserati"`となります。 + +

+
+ +--- + +###### 54. 何が出力されるでしょうか? + +```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"` + +
答え +

+ +#### 答え: A + +`let x = y = 10;` is actually shorthand for: + +```javascript +y = 10; +let x = y; +``` + +`y`に`10`を代入すると、実際にはグローバルオブジェクトにプロパティ`y`が追加されます(ブラウザでは`window`、nodeでは`global`)。ブラウザでは、`window.y`は`10`となりました。 + +それから、変数`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"`を返します。 + +

+
From 161a4ab207c119e52c5fa75f8baedbb62799b31b Mon Sep 17 00:00:00 2001 From: Tanguy Coppin Date: Mon, 24 Jun 2019 18:43:34 +0200 Subject: [PATCH 114/915] Translate in french answer 16 to 23 --- README_fr-FR.md | 40 ++++++++++++++++++++-------------------- 1 file changed, 20 insertions(+), 20 deletions(-) diff --git a/README_fr-FR.md b/README_fr-FR.md index 0eb2fb44..d6d2a595 100644 --- a/README_fr-FR.md +++ b/README_fr-FR.md @@ -465,9 +465,9 @@ sum(1, "2"); #### Réponse: 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. +JavaScript est un **langage à types dynamiques** : nous n'avons pas besoin de spécifier le types des variables. Les valeurs peuvent être automatiquement convertir vers les autres types sans que vous le sachiez, c'est ce que l'on appelle _la conversion de types implicites_ _(implicit type coercion)_. -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"`. +Dans cette exemple, JavaScript convertit le nombre `1` en un chaine de caractère, afin que la fonction est du sens et puisse renvoyer un valeur. Durant l'addition d'un type numérique (`1`) et d'un type chaine de caractère (`'2'`), le nombre est traité comme une chaine de caractère. Nous pouvons concaténer les chaines de caractères comme `"Hello" + "World"`, c'est donc ce qui arrive ici avec `"1" + "2"` qui retourne `"12"`.

@@ -493,17 +493,17 @@ console.log(number); #### Réponse: C -The **postfix** unary operator `++`: +L'opérateur arithmétique **postfix** `++` : -1. Returns the value (this returns `0`) -2. Increments the value (number is now `1`) +1. Retourne la valeur (ici il retourne `0`) +2. Incrémente la valeur (le nombre est maintenant égal à `1`) -The **prefix** unary operator `++`: +L'opérateur arithmétique **préfix** `++` : -1. Increments the value (number is now `2`) -2. Returns the value (this returns `2`) +1. Incrémente la valeur (le nombre est maintenant égal à `2`) +2. Retourne la valeur (ici il retourne `2`) -This returns `0 2 2`. +Cela retourne donc `0 2 2`.

@@ -534,7 +534,7 @@ getPersonInfo`${person} is ${age} years old`; #### Réponse: 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! +Si vous utilisez les template de chaine de caractère, la valeur du premier argument sera toujours un tableau de valeurs des chaines de caractère. Le reste des arguments seront les valeurs des expressions utilisées !

@@ -566,11 +566,11 @@ checkAge({ age: 18 }); #### Réponse: 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. +Lorsque l'on teste une égalité, les primitifs sont comparés par leur valeur, alors que les objet sont comparés par leur _référence_. JavaScript vérifie si les objets ont une référence à la même zone de la mémoire.= -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. +Les 2 objets que nous comparons n'ont pas ça : l'objet passé en paramètre fait référence à une zone mémoire différente que l'objet que nous utilisons pour faire la comparaison. -This is why both `{ age: 18 } === { age: 18 }` and `{ age: 18 } == { age: 18 }` return `false`. +C'est pourquoi l;es 2 conditions `{ ag: 18 } === { age: 18 }` et `{ age: 18 } == { age: 18 }` retournent `false`.

@@ -597,7 +597,7 @@ getAge(21); #### Réponse: C -The spread operator (`...args`.) returns an array with arguments. An array is an object, so `typeof args` returns `"object"` +L'opérateur de destructuration _(spread operator)_ (`...args`) retourne un tableau avec les arguments. Un tableau est un objet, donc `typeof args` retournera `"object"`.

@@ -626,7 +626,7 @@ getAge(); #### Réponse: 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. +Avec `"use strict"`, vous pouvez êtes sûr de ne pas déclarer accidentellement des variables gloables. Nous ne déclarerons jamais la variable `age`, et temps que nous utiliserons `"use strict"`, cela créera une erreur de référence. Si nous n'utilisons pas `"use strict"`, cela fonctionnera et la variable `age` sont attribué à l'objet global.

@@ -649,7 +649,7 @@ const sum = eval("10*10+5"); #### Réponse: 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` évalue les codes que nous passons en paramétre de type chaine de caractères. Si c'est une expression, comme dans notre cas, il évaluera l'expression. L'expression est `10 * 10 + 5`, ce qui retourne le nombre `105`.

@@ -672,9 +672,9 @@ sessionStorage.setItem("cool_secret", 123); #### Réponse: B -The data stored in `sessionStorage` is removed after closing the _tab_. +La donnée stocké dans le `sessionStorage` est supprimée après la fermeture de l'onglet. -If you used `localStorage`, the data would've been there forever, unless for example `localStorage.clear()` is invoked. +Si vous utilisez le `localStorage`, la donnée sera là pour toujours, jusqu'à ce que, par exemple, `localStorage.clear()` soit invoquée.

@@ -700,9 +700,9 @@ console.log(num); #### Réponse: B -With the `var` keyword, you can declare multiple variables with the same name. The variable will then hold the latest value. +Avec le mot clé `var`, vous pouvez déclarer plusieurs variables avec le même nom. La variable aura pour valeur la dernière assignée. -You cannot do this with `let` or `const` since they're block-scoped. +Vous ne pouvez par faire cela avec `let` ou `const` puisqu'ils ont une portée de bloc.

From 9b31ffe2a636acfa690557a0324d291a7d344b6b Mon Sep 17 00:00:00 2001 From: Tanguy Coppin Date: Mon, 24 Jun 2019 20:38:29 +0200 Subject: [PATCH 115/915] Translate in FR answers 24 to 43 --- README_fr-FR.md | 86 ++++++++++++++++++++++++------------------------- 1 file changed, 43 insertions(+), 43 deletions(-) diff --git a/README_fr-FR.md b/README_fr-FR.md index d6d2a595..a8dfb5c1 100644 --- a/README_fr-FR.md +++ b/README_fr-FR.md @@ -731,9 +731,9 @@ set.has(1); #### Réponse: 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. +Toutes les clés d'objet (à l'exception des symboles) sont des chaînes de caratères sous le capot, même si vous ne les tapez pas vous-même en tant que chaîne. C'est pourquoi `obj.hasOwnProperty('1')` renvoie également la valeur `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`. +Ça ne marche pas comme ça pour un set. Il n'y a pas de `'1'` dans notre ensemble : `set.has('1')` renvoie `false`. Il a le type numérique `1`, `set.has(1)` renvoie `true`.

@@ -757,7 +757,7 @@ console.log(obj); #### Réponse: 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. +Si vous avez deux clés portant le même nom, la clé sera remplacée. Elle sera toujours dans sa première position, mais avec la dernière valeur spécifiée.

@@ -775,7 +775,7 @@ If you have two keys with the same name, the key will be replaced. It will still #### Réponse: A -The base execution context is the global execution context: it's what's accessible everywhere in your code. +Le contexte d'exécution de base est le contexte d'exécution global: c'est ce qui est accessible partout dans votre code.

@@ -801,7 +801,7 @@ for (let i = 1; i < 5; i++) { #### Réponse: C -The `continue` statement skips an iteration if a certain condition returns `true`. +L'instruction `continue` ignore une itération si une condition donnée renvoie `true`.

@@ -830,7 +830,7 @@ name.giveLydiaPizza(); #### Réponse: 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` est un constructeur intégré, auquel nous pouvons ajouter des propriétés. Je viens d'ajouter une méthode à son prototype. Les chaînes de caratère primitives sont automatiquement converties en un objet chaîne, généré par la fonction prototype de chaîne. Ainsi, toutes les chaînes (objets de chaîne) ont accès à cette méthode !

@@ -860,11 +860,11 @@ console.log(a[b]); #### Réponse: 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`. +Les clés d'objet sont automatiquement converties en chaînes de caractère. Nous essayons de définir un objet en tant que clé de l'objet `a`, avec la valeur `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`. +Cependant, lorsque nous transformons un objet en chaine de caractère, il devient `"[Objet objet]"`. Donc, ce que nous disons ici, c'est que un `a["Objet objet"] = 123`. Ensuite, nous pouvons essayer de refaire la même chose. `c` est un autre objet que nous sommes implicitement en train de transformer en chaine de carctère. Donc, `a["Objet objet"] = 456`. -Then, we log `a[b]`, which is actually `a["Object object"]`. We just set that to `456`, so it returns `456`. +Ensuite, nous affichons `a[b]`, qui est en fait `a["Objet objet"]`. Que nous venons de définir à `456`, nous renvoyons donc `456`.

@@ -893,31 +893,31 @@ baz(); #### Réponse: B -We have a `setTimeout` function and invoked it first. Yet, it was logged last. +Nous avons une fonction `setTimeout` et nous l'avons d'abord appelée. Pourtant, il a été affiché en dernier. -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. +En effet, dans les navigateurs, nous n’avons pas seulement le moteur d’exécution, nous avons aussi quelque chose appelé `WebAPI`. `WebAPI` nous donne la fonction` setTimeout` pour commencer, et par exemple le DOM. -After the _callback_ is pushed to the WebAPI, the `setTimeout` function itself (but not the callback!) is popped off the stack. +Une fois que la fonction de rappel _(callback)_ est poussée via la WebAPI, la fonction `setTimeout` elle-même (mais pas la fonction de rappel !) est extraite de la pile. -Now, `foo` gets invoked, and `"First"` is being logged. +Maintenant, `foo` est invoqué et `"Premier"` est affiché. -`foo` is popped off the stack, and `baz` gets invoked. `"Third"` gets logged. +`foo` est extrait de la pile et `baz` est invoqué. `"Troisième"` est affiché. -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_. +WebAPI ne peut simplement pas ajouter des éléments à la pile dès qu’elle est prête. Au lieu de cela, elle pousse la fonction de rappel vers quelque chose appelé la _file d'attente_. -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. +C'est ici qu'une boucle d'événement commence à fonctionner. La **boucle d'événement** examine la pile et la file d'attente des tâches. Si la pile est vide, il prend la première chose dans la file d'attente et la pousse sur la pile. -`bar` gets invoked, `"Second"` gets logged, and it's popped off the stack. +`bar` est invoqué, `"Second"` est affiché et il est sorti de la pile.

@@ -946,7 +946,7 @@ This is where an event loop starts to work. An **event loop** looks at the stack #### Réponse: C -The deepest nested element that caused the event is the target of the event. You can stop bubbling by `event.stopPropagation` +L'élément imbriqué le plus profond qui a provoqué l'événement est la cible de l'événement. Vous pouvez arrêter le bouillonnement _(bubbling)_ en utilisant `event.stopPropagation`.

@@ -973,7 +973,7 @@ The deepest nested element that caused the event is the target of the event. You #### Réponse: 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. +Si nous cliquons sur `p`, nous verrons deux lignes : `p` et `div`. Lors de la propagation d'un événement, il y a 3 phases: capture, cible et bouillonnement _(bubbling)_. Par défaut, les gestionnaires d'événements sont exécutés dans la phase de bouillonnement (sauf si vous définissez `useCapture` sur` true`). Il va de l'élément imbriqué le plus profond vers l'extérieur.

@@ -1003,9 +1003,9 @@ sayHi.bind(person, 21); #### Réponse: D -With both, we can pass the object to which we want the `this` keyword to refer to. However, `.call` is also _executed immediately_! +Avec les deux, nous pouvons transmettre l'objet auquel nous voulons que le mot clé `this` fasse référence. Cependant, `.call` est aussi _exécuté immédiatement_ ! -`.bind.` returns a _copy_ of the function, but with a bound context! It is not executed immediately. +`.bind.` renvoie une copie de la fonction, mais avec un contexte lié ! Elle n'est pas exécuté immédiatement.

@@ -1032,9 +1032,9 @@ typeof sayHi(); #### Réponse: B -The `sayHi` function returns the returned value of the immediately invoked function (IIFE). This function returned `0`, which is type `"number"`. +La fonction `sayHi` renvoie la valeur renvoyée par la fonction immédiatement appelée (IIFE). Cette fonction a renvoyé `0`, qui est du type `"nombre"`. -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"`. +Pour info : il n'y a que 7 types natifs : `null`, `undefined`, `boolean`, `number`, `string`, `object` et `symbol`. `"function"` n'est pas un type, puisque les fonctions sont des objets, il est de type `"object"`.

@@ -1062,16 +1062,16 @@ undefined; #### Réponse: A -There are only six falsy values: +Il n'y a que six valeurs de fausses : - `undefined` - `null` - `NaN` - `0` -- `''` (empty string) +- `''` (chaine de caractère vide) - `false` -Function constructors, like `new Number` and `new Boolean` are truthy. +Les constructeurs de fonctions, comme `new Number` et `new Boolean` sont la vraies.

@@ -1094,8 +1094,8 @@ console.log(typeof typeof 1); #### Réponse: B -`typeof 1` returns `"number"`. -`typeof "number"` returns `"string"` +`typeof 1` retourne `"number"`. +`typeof "number"` retourne `"string"`

@@ -1120,11 +1120,11 @@ console.log(numbers); #### Réponse: 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: +Lorsque vous définissez une valeur sur un élément d'un tableau qui dépasse la longueur du tableau, JavaScript crée un quelque chose appelé "emplacements vides". Ceux-ci ont en fait la valeur `undefined`, mais vous verrez quelque chose comme : `[1, 2, 3, 7 x empty, 11]` -depending on where you run it (it's different for every browser, node, etc.) +en fonction de l'endroit où vous l'exécutez (différent pour chaque navigateur, nœud, etc.).

@@ -1157,11 +1157,11 @@ depending on where you run it (it's different for every browser, node, etc.) #### Réponse: 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. +Le bloc `catch` reçoit l'argument `x`. Ce n'est pas le même `x` que la variable que nous passons en arguments. Cette variable `x` a une portée de bloc. -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`. +Plus tard, nous définissons cette variable de bloc égale à `1` et définissons la valeur de la variable `y`. Maintenant, nous affichons la variable `x` de portée de bloc, dont la valeur est égale à `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`. +En dehors du bloc `catch`, `x` est toujours `undefined` et `y` est égal à `2`. Lorsque nous voulons `console.log(x)` en dehors du bloc `catch`, il renvoie `undefined`, et `y` renvoie `2`.

@@ -1180,11 +1180,11 @@ Outside of the `catch` block, `x` is still `undefined`, and `y` is `2`. When we #### Réponse: A -JavaScript only has primitive types and objects. +JavaScript n'a que des types et des objets primitifs. -Primitive types are `boolean`, `null`, `undefined`, `bigint`, `number`, `string`, and `symbol`. +Les types primitifs sont `boolean`, `null`, `undefined`, `bigint`, `number`, `string` et `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 implicity wrap the object 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. +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'encapsuleur, à savoir `String`, puis supprime immédiatement l'encapsuleur après l'évaluation de l'expression. Toutes les primitives à l'exception de `null` et` undefined` présentent ce comportement.

@@ -1212,9 +1212,9 @@ What differentiates a primitive from an object is that primitives do not have an #### Réponse: 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]`. +`[1, 2]` est notre valeur initiale. C'est la valeur avec laquelle nous commençons et la valeur du tout premier `acc`. Au premier tour, `acc` est `[1,2]` et `cur` est `[0, 1]`. Nous les concaténons, ce qui donne `[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]` +Ensuite, `acc` est `[1, 2, 0, 1]` et `cur` est `[2, 3]`. Nous les concaténons et obtenons `[1, 2, 0, 1, 2, 3]`

@@ -1239,11 +1239,11 @@ Then, `[1, 2, 0, 1]` is `acc` and `[2, 3]` is `cur`. We concatenate them, and ge #### Réponse: B -`null` is falsy. `!null` returns `true`. `!true` returns `false`. +`null` est faux. `!null` retourne `true`. `!true` retourne `false`. -`""` is falsy. `!""` returns `true`. `!true` returns `false`. +`""` est faux. `!""` retourne `true`. `!true` retourne `false`. -`1` is truthy. `!1` returns `false`. `!false` returns `true`. +`1` est vrai. `!1` retourne `false`. `!false` retourne `true`.

@@ -1266,7 +1266,7 @@ setInterval(() => console.log("Hi"), 1000); #### Réponse: A -It returns a unique id. This id can be used to clear that interval with the `clearInterval()` function. +Il retourne un identifiant unique. Cet identifiant peut être utilisé pour effacer cet interval avec la fonction `clearInterval()`.

@@ -1289,7 +1289,7 @@ It returns a unique id. This id can be used to clear that interval with the `cle #### Réponse: A -A string is an iterable. The spread operator maps every character of an iterable to one element. +Une chaîne de caractère est itérable. L'opérateur de desconstruction transforme chaque caractère d'un itérable en un élément.

From 1cacef1569f5fc7bbc3c025f96189b759df65c64 Mon Sep 17 00:00:00 2001 From: Sara Ahmed Date: Mon, 24 Jun 2019 21:44:52 +0200 Subject: [PATCH 116/915] 4 - 7 Arabic translation Added Translation for question 4 - 5 - 6 - 7. --- README_AR.md | 128 +++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 128 insertions(+) diff --git a/README_AR.md b/README_AR.md index 43351549..7ee5f70b 100644 --- a/README_AR.md +++ b/README_AR.md @@ -121,6 +121,134 @@ shape.perimeter(); لا توجد قيمة `radius` في ذلك ال object لهذا يقوم بإرجاع القيمة `undefined`. +

+
+ +--- + +4. ماهو الناتج؟ + +```javascript ++true; +!"Lydia"; +``` + +- A: `1` and `false` +- B: `false` and `NaN` +- C: `false` and `false` + +
الإجابة +

+

+الجواب هو الخيار الأول : A + +عملية الزيادة الأحادية هنا وجدت لكي تقوم بتحويل المعامل الى رقم, `true` هي `1` , و `false` هي `0`. + المتغير من نوع string `'Lydia'` هو قيمة صدقية أو حقيقية, بمعنى أنها تساوي `true` . السؤال الذي نقوم بطرحه هنا, هو هل هذه القيمة الصدقية هي قيمة غير صدقية؟ اي تساوي `false`؟ لهذا نتحصل على الجواب `false`. +

+
+ +--- + +5. أي الإجابات هو إجابة صحيحة؟ + +```javascript +const bird = { + size: "small" +}; + +const mouse = { + name: "Mickey", + small: true +}; +``` + +- A: `mouse.bird.size` غير صحيحة +- B: `mouse[bird.size]` غير صحيحة +- C: `mouse[bird["size"]]` غير صحيحة +- D: كل الإجابات صحيحة + +
الإجابة +

+

+الجواب هو الخيار الأول: A + +في لغة الجافا سكريبت, جميع مفاتيح الobjects هي من النوع string. الا اذا كانت عبارة عن symbol. حتى ولو أننا في بعض المرات لانقوم بوضع نوعها على انها string بصورة صريحة, ولكنها دائما يتم تحويلها الى نوع string وراء الكواليس. + +لغة الجافاسكريبت تقوم بترجمةال 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`. +

+
+ +--- + +6. ماهو الناتج؟ + +```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` + +
الإجابة +

+

+الجواب هو الخيار الأول : A + +في لغة الجافاسكريبت, جميع ال objectsيتم التفاعل معها عن طريق _reference_ و ذلك عندما نقوم بمساواتهم ببعضهم البعض بعلامة ال=. + +أولا, المتغير `c` يحمل قيمة ل object. لاحقا قمنا بإضافة `d` لنفس الrefence الذي لدى المتغير `c` لل object. + + + +لذا, عندما تقوم بتغيير object واحد , انت فعليا تقوم بتغيير جميع الobjects. + +

+
+ +--- + +7. ماهو الناتج؟ + +```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` + +
الإجابة +

+

+الجواب هو الخيار الثالث: C + +`new Number()` هي دالة من نوع built-in function constructer. على الرغم من أنها تبدو كرقم, ولكنها في الحقيقة ليس رقم, هي عبارة عن object ولديها العديد العديد من المميزات. + +عندما نقوم بإستخدام العلامة او العامل `==`, هي تقوم فقط بالتحقق من إذا ماكان لديها same _value_.كلا الطرفين قيمتهم تساوي `3` لهذا تقوم بإرجاع `true`. + +و لكن على الرغم من هذا, عندما نقوم بإستخدام العملية أو المعامل `===`, كلا القيمة _and_ النوع يجب ان يكونا نفس الشيء. + +هي ليست `new Number()` هي ليست عبارة عن رقم, هي عبارة عن **object** , وكلاهما سيقومان بإرجاع `false.` +

From 2f6139a85efbf960068ac55844c13a660ef9203a Mon Sep 17 00:00:00 2001 From: Ihor Sychevskyi <26163841+Arhell@users.noreply.github.com> Date: Tue, 25 Jun 2019 01:02:43 +0300 Subject: [PATCH 117/915] Updated syntax highlighting in first response. UA --- README-ua_UA.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README-ua_UA.md b/README-ua_UA.md index c14d922e..54eb1f99 100644 --- a/README-ua_UA.md +++ b/README-ua_UA.md @@ -38,7 +38,7 @@ sayHi(); #### Відповідь: D -Усередині функції ми спершу визначаємо змінну `name` за допомогою ключового слова `var`. Це означає, що змінна буде знайдена (область пам'яті під змінну буде виділена під час створення) зі значенням `undefined` за замовчуванням, до тих пір поки виконання коду не дійде до рядка, де визначається змінна. Ми ще не визначили значення name, коли намагаємося вивести її в консоль, тому в консолі буде `undefined`. +Усередині функції ми спершу визначаємо змінну `name` за допомогою ключового слова `var`. Це означає, що змінна буде знайдена (область пам'яті під змінну буде виділена під час створення) зі значенням `undefined` за замовчуванням, до тих пір поки виконання коду не дійде до рядка, де визначається змінна. Ми ще не визначили значення `name`, коли намагаємося вивести її в консоль, тому в консолі буде `undefined`. Змінні, визначені за допомогою `let` (і `const`), також знаходяться, але на відміну від `var`, не створюються. Доступ до них неможливий до тих пір, поки не виконається рядок їх визначення (ініціалізації). Це називається "тимчасова мертва зона". Коли ми намагаємося звернутися до змінних до того моменту як вони визначені, JavaScript видає `ReferenceError`. From eeefec8909889aed31a7488676320a00160acb40 Mon Sep 17 00:00:00 2001 From: Josselin Buils Date: Tue, 25 Jun 2019 11:54:28 +0200 Subject: [PATCH 118/915] Fixes answer of question 52 and adds missing quotes --- README-de_DE.md | 4 ++-- README.md | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/README-de_DE.md b/README-de_DE.md index 706654cb..51456884 100644 --- a/README-de_DE.md +++ b/README-de_DE.md @@ -1570,9 +1570,9 @@ sayHi(); ``` - A: `"It worked! Hello world!"` -- B: `"Oh no an error: undefined` +- B: `"Oh no an error: undefined"` - C: `SyntaxError: can only throw Error objects` -- D: `"Oh no an error: Hello world!` +- D: `"Oh no an error! Hello world!"`
Antwort

diff --git a/README.md b/README.md index 52c948f6..5c9fb4b9 100644 --- a/README.md +++ b/README.md @@ -1572,9 +1572,9 @@ sayHi(); ``` - A: `"It worked! Hello world!"` -- B: `"Oh no an error: undefined` +- B: `"Oh no an error: undefined"` - C: `SyntaxError: can only throw Error objects` -- D: `"Oh no an error: Hello world!` +- D: `"Oh no an error! Hello world!"`

Answer

From ecbc6a7009de3daf7597f385e3b238954cb0836c Mon Sep 17 00:00:00 2001 From: kimdanah Date: Wed, 26 Jun 2019 00:54:08 +0900 Subject: [PATCH 119/915] Translate the questions 21-30 to Korean --- README-ko_KR.md | 65 ++++++++++++++++++++++++++----------------------- 1 file changed, 34 insertions(+), 31 deletions(-) diff --git a/README-ko_KR.md b/README-ko_KR.md index 13154c27..5df54822 100644 --- a/README-ko_KR.md +++ b/README-ko_KR.md @@ -163,7 +163,7 @@ const mouse = { #### 정답: A -JavaScript에서, 모든 객체 키는 문자열이에요 (Symbol이 아닌 한). 비록 그것을 문자열 _타입_ 으로 입력하지 않아도, 항상 밑바닥에서 문자열로 변환되요. +JavaScript에서, 모든 객체 키는 문자열이에요 (Symbol이 아닌 한). 비록 그것을 문자열 _타입_ 으로 입력하지 않아도, 항상 내부적으로 문자열로 변환되요. JavaScript는 문장을 해석(또는 박스해제)해요. 대괄호 표기를 사용하면, 첫 번째 좌대괄호 `[`를 보고 오른쪽 대괄호 `]`를 찾을 때까지 진행해요. 그때, 그 문장을 평가할거에요. @@ -298,7 +298,7 @@ console.log(greetign); #### 정답: A -객체는 출력되요, 전역객체에 빈 객체를 방금 만들었기 때문이에요. `greeting`을 `greettign`으로 잘못 입력했을 경우, JS 터프리터는 실제로 이것을 `global.greettign = {}` (또는 브라우저의 `window.greetign = {}`) 라고 간주해요. +객체는 출력되요, 전역객체에 빈 객체를 방금 만들었기 때문이에요. `greeting`을 `greettign`으로 잘못 입력했을 경우, JS 인터프리터는 실제로 이것을 `global.greettign = {}` (또는 브라우저의 `window.greetign = {}`) 라고 간주해요. 이것을 피하기 위해서, `"use strict"`를 사용할 수 있어요. 이렇게 하면 변수를 어떤 것과 동일하게 설정하기 전에 변수를 선언했는지 확인할 수 있어요. @@ -328,7 +328,7 @@ bark.animal = "dog"; #### 정답: A JavaScript에서는 가능해요, 함수는 객체이기 때문이에요! -(프리미티브형 이외는 모두 객체) +(윈시형 이외는 모두 객체) 함수는 특별한 종류의 객체에요. 당신이 쓴 코드는 실제 함수가 아니에요. 함수는 속성을 가진 객체에요. 이 속성은 호출이 가능해요. @@ -571,7 +571,7 @@ checkAge({ age: 18 }); #### 정답: C -동등성을 테스트할 때, 프리미티브는 그 _값_ 에 따라 비교되며, 객체는 그들의 _참조_ 에 따라 비교되요. JavaScript 객체가 메모리내의 같은 장소를 참조하고 있는지 여부를 확인해요. +동등성을 테스트할 때, 원시형은 그 _값_ 에 따라 비교되며, 객체는 그들의 _참조_ 에 따라 비교되요. JavaScript 객체가 메모리내의 같은 장소를 참조하고 있는지 여부를 확인해요. 비교하고 있는 두개의 객체는 그것이 없어요: 파라미터로 전달된 객체와 동등성을 확인하기 위해 사용한 객체는 메모리 내의 다른 장소를 참조해요. @@ -654,32 +654,32 @@ const sum = eval("10*10+5"); #### 정답: 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` 문자열로서 통과된 코드를 평가해요. 이 경우와 같이 만약 그것이 표현식이라면, 표현식을 평가해요. 표현식은 `10 * 10 + 5` 이에요. 이것은 숫자 `105`를 리턴해요.

--- -###### 22. How long is cool_secret accessible? +###### 22. cool_secret에 몇시간 접근이 가능 할까요 ? ```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. +- A: 영원히, 데이터는 사라지지 않아요. +- B: 사용자가 탭을 닫을 때. +- C: 사용자가 탭 뿐만 아니라, 브라우저 전체를 닫을 때. +- D: 사용자가 자신의 컴퓨터를 종료시켰을때.
정답

#### 정답: B -The data stored in `sessionStorage` is removed after closing the _tab_. +`sessionStorage`에 저장된 데이터는 _탭_ 을 닫은 후에 삭제되요. -If you used `localStorage`, the data would've been there forever, unless for example `localStorage.clear()` is invoked. +만약 `localStorage`를 사용했다면, 예를들어 `localStorage.clear()`를 호출 하지 않는 한, 데이터는 영원할거에요.

@@ -705,9 +705,9 @@ console.log(num); #### 정답: B -With the `var` keyword, you can declare multiple variables with the same name. The variable will then hold the latest value. +`var`키워드를 사용하면, 같은 이름으로 복수의 변수를 선언 할 수 있어요. 변수는 최신의 값을 유지해요. -You cannot do this with `let` or `const` since they're block-scoped. +블록 스코프의 `let` 또는 `const`에서는 할 수 없어요.

@@ -736,9 +736,10 @@ set.has(1); #### 정답: 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. +모든 객체 키(Symbols 제외) +모든 객체 키는(Symbol 제외) 문자열로 직접 입력하지 않아도, 내부적으로는 문자열이에요. 이것이 `obj.hasOwnProperty('1')` 또한 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`. +set에서는 작동하지 않아요. set에는 `'1'`이 없어요: `set.has('1')`는 `false`를 리턴해요. 그것은 수형인 `1`을 가지고 있어, `set.has(1)`은 `true`를 리턴해요.

@@ -762,14 +763,14 @@ console.log(obj); #### 정답: 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. +###### 26. JavaScript의 global execution context는 두개를 작성해요. : 전역객체와 "this" 키워드에요. - A: true - B: false @@ -780,7 +781,7 @@ If you have two keys with the same name, the key will be replaced. It will still #### 정답: A -The base execution context is the global execution context: it's what's accessible everywhere in your code. +기본적인 execution context는 전역 실행 문장이에요: 당신의 코드 모든 곳에서 접근 할 수 있어요.

@@ -806,7 +807,7 @@ for (let i = 1; i < 5; i++) { #### 정답: C -The `continue` statement skips an iteration if a certain condition returns `true`. +`continue` 표현식은 특정 조건이 `true`를 리턴하면 반복처리를 건너뛰어요.

@@ -835,7 +836,7 @@ name.giveLydiaPizza(); #### 정답: 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`은 내장 생성자로 속성을 추가 할 수 있어요. 단지 프로토타입이라는 메소드를 추가했어요. 원시형 문자열은 문자열 프로토타입 함수에 의해 생성된 문자열 객체로 자동 변환되요. 그래서, 모든 문자열(문자열 객체)는 그 메소드에 접근 할 수 있어요!

@@ -865,11 +866,11 @@ console.log(a[b]); #### 정답: 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`. +객체 키는 자동으로 문자열로 변환되요. 객체 `a`의 키 값으로 `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`. +그러나, 객체를 문자열화 하면 `"[Object object]"`가 되요. 그래서 여기서 밀하고자 하는 건 `a["Object object"] = 123` 이라는 거에요. 그후, 같은 일을 다시 시도해요. `c`는 암묵적으로 문자열화 한 다른객체에요. 그래서 `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`. +그후, `a[b]`는 출력하면 실제로는 `a["Object object"]`에요. 단지 `456`를 설정 했기때문에, `456`를 리턴해요.

@@ -898,31 +899,33 @@ baz(); #### 정답: B -We have a `setTimeout` function and invoked it first. Yet, it was logged last. +`setTimeout`함수를 처음으로 호출 했어요. 그러나 그것은 마지막에 출력되요. -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. +브라우저에는 런타임 엔진 뿐만 아니라 `WebAPI`라고 불리는 것도 있기 때문이에요. `WebAPI`는 `setTimeout`함수를 최초에 부여하는데, DOM을 예로 들 수 있어요. After the _callback_ is pushed to the WebAPI, the `setTimeout` function itself (but not the callback!) is popped off the stack. +_callback_ 이 WebAPI에 푸시된 후, `setTimeout`함수 자체(callback이 아니에요!)는 stack에 사라졌어요. + -Now, `foo` gets invoked, and `"First"` is being logged. +지금, `foo` 는 호출 되었고, `"First"`는 출력 되었어요. -`foo` is popped off the stack, and `baz` gets invoked. `"Third"` gets logged. +`foo`는 stack에 사라지고, `baz`가 호출 되었어요. `"Third"`가 출력 되었어요. -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_. +WebAPI는 준비가 될때 마다 stack에 항목을 추가 할 수 없어요. 대신에, _queue_ 라고 불리는 것에 callback함수를 푸시해요. -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. +여기서 event loop가 작동하기 시작해요. **event loop**는 stack과 task queue를 봐요. stack이 비어있다면, queue에 첫번째것을 가져다가 stack 위로 푸시해요. -`bar` gets invoked, `"Second"` gets logged, and it's popped off the stack. +`bar`가 호출되었고, `"Second"`가 출력 되었으며, stack에서 사라졌어요.

From 7a252c180da3d68889ec2cc4fcc059d509b1ac5b Mon Sep 17 00:00:00 2001 From: Sara Ahmed Date: Wed, 26 Jun 2019 00:04:47 +0200 Subject: [PATCH 120/915] Questions 8 to 20 added (Arabic Translation) --- README_AR.md | 403 +++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 403 insertions(+) diff --git a/README_AR.md b/README_AR.md index 7ee5f70b..8499b16e 100644 --- a/README_AR.md +++ b/README_AR.md @@ -11,6 +11,8 @@ الأجوبة توجد في الجزء المطوي بالأسفل أدناه تحت كل سؤال على حدة, فقط قم بالضغط على كلمة الإجابة لكي تحصل على الإجابة, حظا موفقا :heart: +اللغات المتوفرة: + [English](https://github.com/SaraAli26/javascript-questions/blob/master/README.md) [中文版本](https://github.com/SaraAli26/javascript-questions/blob/master/README-zh_CN.md) @@ -124,6 +126,7 @@ shape.perimeter();

+ --- 4. ماهو الناتج؟ @@ -147,6 +150,7 @@ shape.perimeter();

+ --- 5. أي الإجابات هو إجابة صحيحة؟ @@ -182,6 +186,7 @@ const mouse = {

+ --- 6. ماهو الناتج؟ @@ -217,6 +222,7 @@ console.log(d.greeting);

+ --- 7. ماهو الناتج؟ @@ -252,4 +258,401 @@ console.log(b === c);

+ +--- + +8. ماهو الناتج؟ + +```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` + +
الإجابة +

+

+الجواب هو الخيار الرابع: D + +الدالة `colorChange` هي دالة static, و الدوال التي هي من نوع static هي دوال صممت لكي يتم استخدامها فقط في الconstructor الذي تم تعريفها به, و ليس من الممكن ان يتم تمريرها او استخدامها من قبل اي مكون children. بما أن `freddie` هي متغير children فإن الدالة لم يتم تمريرها اليه و هي غير متوفرة في ال instant من `freddie` لذا نتحصل على الخطأ `TypeError` . +

+
+ + +--- + +9. ماهو الناتج؟ + +```javascript +let greeting; +greetign = {}; // Typo! +console.log(greetign); +``` + +- A: `{}` +- B: `ReferenceError: greetign is not defined` +- C: `undefined` + +
الإجابة +

+

+الجواب هو الخيار الأول : A + +تقوم بعمل log على الconsole ل object. و لأننا قمنا بإنشاء object فارغ في glopal object! عندما قمنا بالخطأ بطباعة `greetign` بدل ان نقوم بطباعتها بصورة صحيحة هكذا `greeting`, هنا قام مترجم الجافاسكريبت بترجمة الآتي `global.greetign = {}` أو `window.greetign = {}` في المتصفح. + +لكي نتجنب حدوث مثل هذه الحالة, بإمكاننا إستخدام `"use strict"`. بفعل هذه الخطوة ستتأكد من أنك قد عرفت المتغير قبل ان تساويه بأي شي آخر. +

+
+ + +--- + + 10. ما الذي يحدث عندما نقوم بعمل الآتي؟ + +```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: `undefined` +- D: `ReferenceError` + +
الإجابة +

+

+الجواب هو الخيار الأول: A + +هذا ممكن في لغة الجافاسكريبت, لأن الدوال هي عبارة عن objects, (كل شيء بداخل الأنواع التي هي primitive هو عبارة عن object) + +الدالة هي عبارة عن نوع خاص من الobjects, الكود الذي تقوم بكتابته بنفسك هو ليس بالدالة الفعلية, الدالة هي object لديه خصائص. و هذه الخاصية قابلة للمناداة +

+
+ + +--- + +11. ماهو الناتج؟ + +```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` + +
الإجابة +

+

+الجواب هو الخيار الأول: A + +ليس بإمكانك اضافة الخصائص ل constructor كما تقوم بإضافة الخصائص للobjects. إذا أردت أن تضيف مميزات لكل الobjects مرة واحدة, سيجب عليك أن تقوم بإستخدام الprototype. لذا في هذه الحالة, +
+ +```js +Person.prototype.getFullName = function() { + return `${this.firstName} ${this.lastName}`; +}; +``` + +
+اذا استطعنا جعل `member.getFullName()` تعمل. لماذا ستكون ذات فائدة؟ فلنفترض أننا أضفنا هذه الmethod للconstructor نفسها. ربما ليس أي instance من `Person` تحتاج الى هذه ال method. بهذه الطريقة سنقوم بإستهلاك مساحة كبيرة من الذاكرة, بما أنهم سيظلون يحتفظون ب هذه الخاصية, و التي بدورها ستقوم بحجز مساحة في الذاكرة لأي instance. لذا من الأفضل أن نقوم بإضافتهاالى الprototype, بهذه الطريقة ستقوم بحجز مكان واحد فقط في الذاكرة, و لكنها متاحة للكل للوصول إليها. +

+
+
+ +--- + +12. ماهو الناتج؟ + +```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` + +
الإجابة +

+

+الجواب هو الخيار الأول: A + +للمتغير `sarah` لم نقم بإستخدام الكلمة المفتاحية `new`, عندإستخدام الكلمة المفتاحية `new` ف هي تشير الى ال object الخالي او الفارغ الذي قمنا بإنشاءه, و لكن اذا لم تقم بإضافة`new` ف هي ستشير الى ال **global object**!. + +نحن نقول بأن `this.firstName` تساوي `"Sarah"` و `this.lastName` تساوي `"Smith"`. ماقمنا بفعله حقا هنا, هو أنه قمنا بتعريف `global.firstName = 'Sarah'` و `global.lastName = 'Smith'`. المتغير `sarah` لا يظل `undefined`. +

+
+
+ +--- + +13. ماهي الثلاث مراحل التي تمر بها الevent propagation? + +- A: Target > Capturing > Bubbling +- B: Bubbling > Target > Capturing +- C: Target > Bubbling > Capturing +- D: Capturing > Target > Bubbling + +
الإجابة +

+

+الجواب هو الخيار الرابع: D + +أثناء مرحلة ال**capturing**, الevent تمر عبر العناصر العليا, أي العناصر الآباء إلى أن تصل الى العنصر المقصود أو المراد, حينها تتمكن من الوصول الى العنصر **target** , و حينها تبدأ عملية ال **bubbling**. + + + +

+
+ + +--- + +14. جميع الobjects لديها prototypes? + +- A: true +- B: false + +
الإجابة +

+

+الجواب هو الخيار الثاني: B + +جميع الobjects لديها prototypes, عدا ال objects من نوع **base object**. الobject من نوع base object هو عبارة عن object تم إنشاءه من قبل المستخدم, أو تم إنشاءه عن طريق إستخدام الكلمة المفتاحية `new`. الbase object لديه حق الوصول الى بعض ال methods و الخصائص. مثال: `.toString`. هذا هو السبب الذي يمكنك من إستخدام built-in JavaScript methods, مثل هذه ال methods جميعها متاحة في ال ptototype, على الرغم من أن لغة الجافا سكريبت ليس بإمكانها أن تجدها بصورة مباشرة من الobject الذي قمت أنت بإنشاءه, و لكنها تذهب الى سلسلة الprototype حيث بإمكانها ان تجده هناك, مما يجعله قابل للوصول من قبلك, أي بإمكانك أن تصل إليه. +

+
+ + +--- + +15. ماهو الناتج؟ + +```javascript +function sum(a, b) { + return a + b; +} + +sum(1, "2"); +``` + +- A: `NaN` +- B: `TypeError` +- C: `"12"` +- D: `3` + +
الإجابة +

+

+الجواب هو الخيار الثالث: C + +لغة الجافاسكريبت هي لغة **dynamically typed language** بمعنى أننا لا نقوم بتعريف نوع معين للمتغيرات, المتغيرات بصورة أوتوماتيكية يتم تحويلها الى أنواع أخرى بدون أن تعرف أنت ذلك, وهذا يسمى ب _implicit type coercion_. **Coercion** تعني بأنك تقوم بالتحويل من نوع الى آخر. + +في هذا المثال, لغة الجافاسكريبت تقوم بتحويل الرقم `1` الى string, لكي تستطيع الدالةأن تقوم بعملها و تتمكن من إرجاع قيمة. أثناء قيام عملية إضافةالمتغير من النوع number و الذي هو (`1`) و المتغير من النوع string والذي هو (`'2'`), الرقم تم التعامل معه ك string, بهذه الطريقة سنتمكن من عمل عملية concatenate للمتغيرين من نوع string ك مثال `"Hello" + "World"`, لهذا مايحدث هنا هو عبارة عن `"1" + "2"` و الذي بدوره يقوم بإرجاع `"12"`. +

+
+ + +--- + +16. ماهو الناتج؟ + +```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` + +
الإجابة +

+

+الجواب هو الخيار الثالث: C + +ال **postfix** العامل الأحادي `++`: + +1. تقوم بإرجاع القيمة (هذه ترجع `0`) +2. تقوم بزيادةالقيمة (number الآن تساوي `1`) + +ال **prefix** العامل الأحادي `++`: + +1. تقوم بزيادة القيمة(number الآن تساوي `2`) +2. تقوم بإٍرجاع القيمة (هذه ترجع `2`) + +هذايقوم بإرجاع `0 2 2`. + +

+
+ + +--- + +17.ماهو الناتج؟ + +```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` + +
الإجابة +

+

+الجواب هو الخيار الثاني: B + +اذا قمت بإستخدام tagged template literals, فإن قيمة ال argument الأول هي دائما عبارة عن array والذي نوع قيمها عبارة عن string, ماتبقى من الarguments تتحصل على القيم من الpassed expressions. +

+
+ + +--- + +18. ماهو الناتج؟ + +```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` + +
الإجابة +

+

+الجواب هو الخيار الثالث: C + +عندما نقوم بإختبار المساواة أو التساوي بين طرفين, ال primitives يتم مقارنتها عن طريق قيمها, بينما ال objects يتم مقارنتها عن طريق الreference الذي يتبع لها, لغة الجافاسكريبت تتحقق عن إذا ماكان الrefrence الذي يتبع لobject يشير الى نفس الموقع في الذاكرة. + +لدينا هنا اثنان من ال objects والتي نقوم بعمل مقارنة بينهما, واللذان بدورهما ليس لديهما ذلك, الobject الذي قمنا بتمريره ك parameter يشير الى موقع مختلف في الذاكرة من الموقع الذي يشير اليه الobject الثاني و الذي تم استخدامه للتحق من شرط المساواة. + +لهذا كلا من `{ age: 18 } === { age: 18 }` و `{ age: 18 } == { age: 18 }` يرجعان `false`. + +

+
+ + +--- + +19. ماهو الناتج؟ + +```javascript +function getAge(...args) { + console.log(typeof args); +} + +getAge(21); +``` + +- A: `"number"` +- B: `"array"` +- C: `"object"` +- D: `"NaN"` + +
الإجابة +

+

+الجواب هو الخيار الثالث: C + +العامل spread `...args` يقوم بإرجاع array مع arguments. الarray هي object, لذا فإن `typeof args` تقوم بإرجاع `"object"`. +

+
+ + +--- + +20. ماهو الناتج؟ + +```javascript +function getAge() { + "use strict"; + age = 21; + console.log(age); +} + +getAge(); +``` + +- A: `21` +- B: `undefined` +- C: `ReferenceError` +- D: `TypeError` + +
الإجابة +

+

+الجواب هو الخيار الثالث: C + +بإستخدام `"use strict"`, يمكنك التأكد بأنك لن تقوم عن طريق الخطأ بتعريف glopal variables. نحن لم نقم قط بتعريف المتغير `age`, و بما أننا قمنا بإستخدام `"use strict"` ستقوم بإرجاع reference error. اذا لم نقم بإستخدام `"use strict"` لكانت قد أدت المطلوب, بما أن الخاصية `age` تم إضافتها لل glopal object. +

+
+ + --- From a677fa7119b3db154dd669229995092d397d6cbd Mon Sep 17 00:00:00 2001 From: Sara Ahmed Date: Wed, 26 Jun 2019 00:12:48 +0200 Subject: [PATCH 121/915] Right Alignment for Q13-14 --- README_AR.md | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/README_AR.md b/README_AR.md index 8499b16e..c2bdef3f 100644 --- a/README_AR.md +++ b/README_AR.md @@ -27,7 +27,7 @@ ____________ -###### 1. ماهو الناتج ؟ +1. ماهو الناتج ؟ ```javascript function sayHi() { @@ -428,7 +428,9 @@ console.log(sarah); --- -13. ماهي الثلاث مراحل التي تمر بها الevent propagation? +
+13. ماهي الثلاث مراحل التي تمر بها الevent propagation? +
- A: Target > Capturing > Bubbling - B: Bubbling > Target > Capturing @@ -450,7 +452,9 @@ console.log(sarah); --- +
14. جميع الobjects لديها prototypes? +
- A: true - B: false From 9d2b3464d96f8e7886d1e00d0e8620b36c931def Mon Sep 17 00:00:00 2001 From: Sara Ahmed Date: Wed, 26 Jun 2019 00:13:58 +0200 Subject: [PATCH 122/915] Update README_AR.md --- README_AR.md | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/README_AR.md b/README_AR.md index c2bdef3f..eb702eae 100644 --- a/README_AR.md +++ b/README_AR.md @@ -454,14 +454,13 @@ console.log(sarah);
14. جميع الobjects لديها prototypes? -
- A: true - B: false
الإجابة

-

+ الجواب هو الخيار الثاني: B جميع الobjects لديها prototypes, عدا ال objects من نوع **base object**. الobject من نوع base object هو عبارة عن object تم إنشاءه من قبل المستخدم, أو تم إنشاءه عن طريق إستخدام الكلمة المفتاحية `new`. الbase object لديه حق الوصول الى بعض ال methods و الخصائص. مثال: `.toString`. هذا هو السبب الذي يمكنك من إستخدام built-in JavaScript methods, مثل هذه ال methods جميعها متاحة في ال ptototype, على الرغم من أن لغة الجافا سكريبت ليس بإمكانها أن تجدها بصورة مباشرة من الobject الذي قمت أنت بإنشاءه, و لكنها تذهب الى سلسلة الprototype حيث بإمكانها ان تجده هناك, مما يجعله قابل للوصول من قبلك, أي بإمكانك أن تصل إليه. From da34d13b0c23143f5bb02a18328f0e0b9391301c Mon Sep 17 00:00:00 2001 From: Sara Ahmed Date: Wed, 26 Jun 2019 00:20:20 +0200 Subject: [PATCH 123/915] Update README_AR.md --- README_AR.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/README_AR.md b/README_AR.md index eb702eae..c2bdef3f 100644 --- a/README_AR.md +++ b/README_AR.md @@ -454,13 +454,14 @@ console.log(sarah);
14. جميع الobjects لديها prototypes? +
- A: true - B: false
الإجابة

- +

الجواب هو الخيار الثاني: B جميع الobjects لديها prototypes, عدا ال objects من نوع **base object**. الobject من نوع base object هو عبارة عن object تم إنشاءه من قبل المستخدم, أو تم إنشاءه عن طريق إستخدام الكلمة المفتاحية `new`. الbase object لديه حق الوصول الى بعض ال methods و الخصائص. مثال: `.toString`. هذا هو السبب الذي يمكنك من إستخدام built-in JavaScript methods, مثل هذه ال methods جميعها متاحة في ال ptototype, على الرغم من أن لغة الجافا سكريبت ليس بإمكانها أن تجدها بصورة مباشرة من الobject الذي قمت أنت بإنشاءه, و لكنها تذهب الى سلسلة الprototype حيث بإمكانها ان تجده هناك, مما يجعله قابل للوصول من قبلك, أي بإمكانك أن تصل إليه. From 03c14eac71e507239d0899f36f7b806e03a23e5b Mon Sep 17 00:00:00 2001 From: kimdanah Date: Wed, 26 Jun 2019 21:40:05 +0900 Subject: [PATCH 124/915] Translate the questions 31-40 to Korean --- README-ko_KR.md | 73 +++++++++++++++++++++++++------------------------ 1 file changed, 37 insertions(+), 36 deletions(-) diff --git a/README-ko_KR.md b/README-ko_KR.md index 5df54822..fc0f0834 100644 --- a/README-ko_KR.md +++ b/README-ko_KR.md @@ -163,7 +163,7 @@ const mouse = { #### 정답: A -JavaScript에서, 모든 객체 키는 문자열이에요 (Symbol이 아닌 한). 비록 그것을 문자열 _타입_ 으로 입력하지 않아도, 항상 내부적으로 문자열로 변환되요. +JavaScript에서, 모든 객체 키는 문자열이에요 (Symbol이 아닌 한). 비록 그것을 문자열 _형_ 으로 입력하지 않아도, 항상 내부적으로 문자열로 변환되요. JavaScript는 문장을 해석(또는 박스해제)해요. 대괄호 표기를 사용하면, 첫 번째 좌대괄호 `[`를 보고 오른쪽 대괄호 `]`를 찾을 때까지 진행해요. 그때, 그 문장을 평가할거에요. @@ -239,7 +239,7 @@ console.log(b === c); `==`연산자를 사용할 때, 그건 같은 _값_ 을 가지고 있는지 여부만 확인해요. 그것들은 모두`3`의 값을 가지고 있으므로, `true`를 리턴해요. -그러나, `===`연산자를 사용할 때, 값 _과_ 타입 둘다 같아야 해요. 이건 아니에요: `new Number()`는 숫자가 아니에요. **객체**에요. 그래서 둘다 `false`를 리턴해요. +그러나, `===`연산자를 사용할 때, 값 _과_ 형 둘다 같아야 해요. 이건 아니에요: `new Number()`는 숫자가 아니에요. **객체**에요. 그래서 둘다 `false`를 리턴해요.

@@ -363,7 +363,7 @@ console.log(member.getFullName()); #### 정답: A -보통의 객체처럼 생성자에는 속성을 추가할 수 없어요. 한 번에 모든 객체에 기능을 추가하고 싶다면, 프로토 타입을 사용해야 해요. 그래서 이 경우에, +보통의 객체처럼 생성자에는 속성을 추가할 수 없어요. 한 번에 모든 객체에 기능을 추가하고 싶다면, 프로토타입을 사용해야 해요. 그래서 이 경우에, ```js Person.prototype.getFullName = function() { @@ -470,7 +470,7 @@ sum(1, "2"); #### 정답: C -JavaScript는 **동적으로 만들어진 언어**에요: 특정변수가 어떤 타입인지 지정하지 않아요. 변수는 당신이 모르는 사이에 자동으로 다른 타입으로 변환 될 수 있는데, 이걸 _암묵적 타입 변환_ 이라고 불러요. **Coercion**은 하나의 타입을 다른 타입으로 변환하는 거에요. +JavaScript는 **동적으로 만들어진 언어**에요: 특정변수가 어떤 형인지 지정하지 않아요. 변수는 당신이 모르는 사이에 자동으로 다른 형으로 변환 될 수 있는데, 이걸 _암묵적 형 변환_ 이라고 불러요. **Coercion**은 하나의 형을 다른 형으로 변환하는 거에요. 이 예제에서, 함수가 이해하고 값을 리턴하도록, JavaScript는 숫자 `1`을 문자열로 변환해요. 수형 (`1`)와 문자열형 (`'2'`)의 추가 중에는, 숫자는 문자열로 취급되요. `"Hello" + "World"`처럼 문자열을 연결할 수 있어요, 따라서 여기 `"1" + "2"`는 `"12"`을 리턴하는 일이 발생해요. @@ -932,7 +932,7 @@ WebAPI는 준비가 될때 마다 stack에 항목을 추가 할 수 없어요. --- -###### 31. What is the event.target when clicking the button? +###### 31. 버튼을 클릭했을때 event.target은 무엇일까요? ```html
@@ -944,24 +944,24 @@ WebAPI는 준비가 될때 마다 stack에 항목을 추가 할 수 없어요.
``` -- A: Outer `div` -- B: Inner `div` +- A: 외부의 `div` +- B: 내부의 `div` - C: `button` -- D: An array of all nested elements. +- D: 중첩된 모든 요소의 배열
정답

#### 정답: C -The deepest nested element that caused the event is the target of the event. You can stop bubbling by `event.stopPropagation` +가장 깊이 중첩된 요소가 이벤트를 발생시킬 이벤트 대상이에요. `event.stopPropagation`을 통해서 버블링을 중단 할 수 있어요.

--- -###### 32. When you click the paragraph, what's the logged output? +###### 32. p태그를 클릭하면 로그의 출력은 무엇일까요 ? ```html
@@ -981,7 +981,7 @@ The deepest nested element that caused the event is the target of the event. You #### 정답: 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. +`p`를 클릭하면, 2개의 로그를 볼 수 있어요: `p` 그리고 `div`. 이벤트의 전파 중에는 3 단계가 있어요: 캡처링, 타켓, 버블링. 기본적으로, 이벤트 핸들러는 버블링단계에서 시작되요. (`useCapture`를 `true`로 설정하지 않는 한). 가장 깊게 중첩된 요소로 부터 바깥쪽으로 나가요.

@@ -1011,9 +1011,9 @@ sayHi.bind(person, 21); #### 정답: D -With both, we can pass the object to which we want the `this` keyword to refer to. However, `.call` is also _executed immediately_! +두개 모두, `this`키워드를 참조하고자하는 객체로 보낼 수 있어요. 그러나, `.call`은 _즉시 실행되요_! -`.bind.` returns a _copy_ of the function, but with a bound context! It is not executed immediately. +`.bind.`는 함수의 _복사본_ 을 리턴하지만, 바인딩 컨텍스트에요! 이건 즉시 실행되지 않아요.

@@ -1040,16 +1040,16 @@ typeof sayHi(); #### 정답: B -The `sayHi` function returns the returned value of the immediately invoked function (IIFE). This function returned `0`, which is type `"number"`. +`sayHi`함수는 즉시 호출 함수(IIFE)로서 리턴된 값을 리턴해요. 이 함수는 `0`을 리턴하고, 형은 `"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"`. +참고: 단 7개의 내장형이 있어요: `null`, `undefined`, `boolean`, `number`, `string`, `object` 그리고 `symbol`. `"function"`은 객체이기 때문에 형이아니라 `"object"` 형이에요.

--- -###### 35. Which of these values are falsy? +###### 35. 이 값들 중 어느 것이 거짓 같은 값 일까요? ```javascript 0; @@ -1063,23 +1063,23 @@ 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: 모든 값은 거짓
정답

#### 정답: A -There are only six falsy values: +단 6개의 거짓 값이 있어요: - `undefined` - `null` - `NaN` - `0` -- `''` (empty string) +- `''` (빈 문자열) - `false` -Function constructors, like `new Number` and `new Boolean` are truthy. +`new Number` 그리고 `new Boolean`와 같은 생성자 함수는 참같은 값이에요.

@@ -1102,8 +1102,8 @@ console.log(typeof typeof 1); #### 정답: B -`typeof 1` returns `"number"`. -`typeof "number"` returns `"string"` +`typeof 1` 은 `"number"`을 리턴해요. +`typeof "number"`은 `"string"`을 리턴해요.

@@ -1128,11 +1128,12 @@ console.log(numbers); #### 정답: 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: +배열의 길이를 초과한 값을 배열의 요소로 설정하고자 할때, 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 등마다 달라요.)

@@ -1165,34 +1166,34 @@ depending on where you run it (it's different for every browser, node, etc.) #### 정답: 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. +`catch`블록은 `x`의 인자를 받아요. 이것은 인수를 전달할때 변수로서의 `x`와는 달라요. 이 `x` 변수는 블록-스코프에요. -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`. +후에, 블록-스코프 변수는 `1`로 설정하고, 변수 `y`의 값을 설정해요. 여기서, 블록-스코프의 변수 `x`를 출력하는데, 이것은 `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`. +`catch` 블록 밖에서, `x`는 여전히 `undefined`이고 `y`는 `2`이에요. `catch` 블록 밖에서 `console.log(x)`를 출력하면, `undefined`을 리턴하고. 그리고 `y`는 `2`를 리턴해요.

--- -###### 39. Everything in JavaScript is either a... +###### 39. JavaScript의 모든 것은... -- A: primitive or object -- B: function or object -- C: trick question! only objects -- D: number or object +- A: primitive 또는 object +- B: function 또는 object +- C: 함정 문제! objects만 +- D: number 또는 object
정답

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

@@ -1220,9 +1221,9 @@ What differentiates a primitive from an object is that primitives do not have an #### 정답: 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]`. +`[1, 2]`은 초기값이에요. 이것이 최초의 값으로, 제일 처음의 `acc`의 값이에요. 처음 라운드 동안에 `acc`은 `[1,2]`이며, `cur`은 `[0, 1]`이에요. 그것들을 연결하면 결과적으로 `[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]` +그리고나서, `[1, 2, 0, 1]`은 `acc`이고, `[2, 3]`은 `cur`이 에요. 그것들을 연결하면 `[1, 2, 0, 1, 2, 3]`을 얻게되요.

From a6a847962c9c1383faed951af6f6e54d7d512eea Mon Sep 17 00:00:00 2001 From: kimdanah Date: Wed, 26 Jun 2019 21:58:28 +0900 Subject: [PATCH 125/915] Corrects for spelling --- README-ko_KR.md | 15 +++++++-------- 1 file changed, 7 insertions(+), 8 deletions(-) diff --git a/README-ko_KR.md b/README-ko_KR.md index fc0f0834..0b3ac688 100644 --- a/README-ko_KR.md +++ b/README-ko_KR.md @@ -40,7 +40,7 @@ sayHi(); #### 정답: D -함수내에서, 우선 `var`키워드를 사용해 `name`변수를 선언해요. 이것은 변수가 정의되어 있는 행에 실제로 도달할 때까지, 변수는 `undefined`을 기본값으로 호이스팅 된(생성단계에 메모리 공간이 설정됨)는 것을 의미해요. `name`변수를 출력 하려는 줄에서 아직 변수를 정의하고 있지 않았기 때문에, `undefined`값을 유지하고 있어요. +함수내에서, 우선 `var`키워드를 사용해 `name`변수를 선언해요. 이것은 변수가 정의되어 있는 행에 실제로 도달할 때까지, 변수는 `undefined`을 기본값으로 호이스팅 되(생성단계에 메모리 공간이 설정됨)는 것을 의미해요. `name` 변수를 출력 하려는 줄에서 아직 변수를 정의하고 있지 않기 때문에, `undefined`값을 유지하고 있어요. `let`키워드(그리고 `const`)를 가지는 변수들은, `var`와는 달리, 호이스팅되지만 초기화되지 않아요. 그것들을 선언(초기화)하는 줄 전에는 접근 할 수 없어요. 이것은 "일시적 사각지대"라고 불려요. 선언되기 전에 변수에 접근하려고 하면, JavaScript는 `ReferenceError`를 던져요. @@ -736,8 +736,7 @@ set.has(1); #### 정답: C -모든 객체 키(Symbols 제외) -모든 객체 키는(Symbol 제외) 문자열로 직접 입력하지 않아도, 내부적으로는 문자열이에요. 이것이 `obj.hasOwnProperty('1')` 또한 true를 리턴하는 이유에요. +모든 객체 키는(Symbol 제외) 문자열로 직접 입력하지 않아도, 내부적으로는 문자열이에요. 이것이 `obj.hasOwnProperty('1')` 또한 true를 리턴하는 이유에요. set에서는 작동하지 않아요. set에는 `'1'`이 없어요: `set.has('1')`는 `false`를 리턴해요. 그것은 수형인 `1`을 가지고 있어, `set.has(1)`은 `true`를 리턴해요. @@ -1128,12 +1127,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 등마다 달라요.) +실행 위치에 따라 달라요 (브라우저, node 등 마다 달라요.)

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

From 85cf3c14257f67fee8f25afe7818c1b197dda429 Mon Sep 17 00:00:00 2001 From: kimdanah Date: Thu, 27 Jun 2019 20:23:24 +0900 Subject: [PATCH 126/915] Reset README.md from original & Translate the questions 41-43 to Korean --- README-ko_KR.md | 30 ++++++++++++++++-------------- README.md | 25 ++++++++++++------------- 2 files changed, 28 insertions(+), 27 deletions(-) diff --git a/README-ko_KR.md b/README-ko_KR.md index 0b3ac688..909e7f48 100644 --- a/README-ko_KR.md +++ b/README-ko_KR.md @@ -7,13 +7,15 @@ JavaScript 에 관한 객관식 문제를 [Instagram](https://www.instagram.com/ 정답은 질문 아래 접힌 부분에 있어요, 그냥 클릭하면 펼칠 수 있어요. 행운을 빌어요 :heart: [中文版本](./README-zh_CN.md) +[Versión en español](./README-ES.md) +[日本語](./README-ja_JA.md) +[한국어](./README-ko_KR.md) [Русский](./README_ru-RU.md) [Western Balkan](./README-bs_BS.md) [Deutsch](./README-de_DE.md) [Tiếng Việt](./README-vi.md) -[日本語](./README-ja_JA.md) [Українська мова](./README-ua_UA.md) -[한국어](./README-ko_KR.md) +[Português Brasil](./README_pt_BR.md) --- @@ -1247,26 +1249,26 @@ JavaScript는 원시형과 객체만 가지고 있어요. #### 정답: B -`null` is falsy. `!null` returns `true`. `!true` returns `false`. +`null`은 거짓 같은 값이에요. `!null`은 `true`를 리턴해요. `!true`은 `false`를 리턴해요. -`""` is falsy. `!""` returns `true`. `!true` returns `false`. +`""` 은 거짓 같은 값이에요. `!""`은 `true`를 리턴해요. `!true`은 `false`를 리턴해요. -`1` is truthy. `!1` returns `false`. `!false` returns `true`. +`1`은 참 같은 값이에요. `!1`은 `false`를 리턴해요. `!false`는`true`를 리턴해요.

--- -###### 42. What does the `setInterval` method return in the browser? +###### 42. `setInterval` 메소드는 브라우저에게 무엇을 리턴 할까요? ```javascript setInterval(() => console.log("Hi"), 1000); ``` -- A: a unique id -- B: the amount of milliseconds specified -- C: the passed function +- A: 유니크한 id +- B: 지정된 밀리초 +- C: 통과된 함수 - D: `undefined`
정답 @@ -1274,14 +1276,14 @@ setInterval(() => console.log("Hi"), 1000); #### 정답: A -It returns a unique id. This id can be used to clear that interval with the `clearInterval()` function. +이것은 유니크한 id를 리턴해요. 이 id는 `clearInterval()` 함수로 간격을 없애기 위해 사용 될 수 있어요.

--- -###### 43. What does this return? +###### 43. 이것은 무엇을 리턴할까요? ```javascript [..."Lydia"]; @@ -1297,7 +1299,7 @@ It returns a unique id. This id can be used to clear that interval with the `cle #### 정답: A -A string is an iterable. The spread operator maps every character of an iterable to one element. +문자열은 반복 가능한 객체에요. 스프레드 연산자는 반복 가능한 객체의 모든 문자를 1개의 요소로 매핑해요.

@@ -1339,7 +1341,7 @@ Then, we invoke the function again with the `next()` method. It starts to contin --- -###### 45. What does this return? +###### 45. 이것은 무엇을 리턴할까요? ```javascript const firstPromise = new Promise((res, rej) => { @@ -1363,7 +1365,7 @@ Promise.race([firstPromise, secondPromise]).then(res => console.log(res)); #### 정답: B -When we pass multiple promises to the `Promice.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. +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.

diff --git a/README.md b/README.md index 840b9b7c..e58fa2ac 100644 --- a/README.md +++ b/README.md @@ -7,17 +7,16 @@ From basic to advanced: test how well you know JavaScript, refresh your knowledg The answers are in the collapsed sections below the questions, simply click on them to expand it. Good luck :heart: List of available languages: - -- [中文版本](./README-zh_CN.md) -- [Versión en español](./README-ES.md) -- [日本語](./README-ja_JA.md) -- [한국어](./README-ko_KR.md) -- [Русский](./README_ru-RU.md) -- [Western Balkan](./README-bs_BS.md) -- [Deutsch](./README-de_DE.md) -- [Tiếng Việt](./README-vi.md) -- [Українська мова](./README-ua_UA.md) -- [Português Brasil](./README_pt_BR.md) +* [中文版本](./README-zh_CN.md) +* [Versión en español](./README-ES.md) +* [日本語](./README-ja_JA.md) +* [한국어](./README-ko_KR.md) +* [Русский](./README_ru-RU.md) +* [Western Balkan](./README-bs_BS.md) +* [Deutsch](./README-de_DE.md) +* [Tiếng Việt](./README-vi.md) +* [Українська мова](./README-ua_UA.md) +* [Português Brasil](./README_pt_BR.md) --- @@ -180,6 +179,7 @@ However, with dot notation, this doesn't happen. `mouse` does not have a key cal --- + ###### 6. What's the output? ```javascript @@ -1041,7 +1041,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`, and `symbol`. `"function"` is not a type, since functions are objects, it's of type `"object"`. -

@@ -1656,4 +1655,4 @@ Then, we declare a variable `x` with the value of `y`, which is `10`. Variables 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"`.

-
+
\ No newline at end of file From 3235c42a3f3943a2f96e0d15f832a5a47fbaf582 Mon Sep 17 00:00:00 2001 From: kimdanah Date: Thu, 27 Jun 2019 20:46:40 +0900 Subject: [PATCH 127/915] =?UTF-8?q?Remove=20=ED=95=9C=EA=B5=AD=EC=96=B4,?= =?UTF-8?q?=20Add=20English=20and=20fix=20typo=20from=20original?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README-ko_KR.md | 26 +++++++++++++------------- 1 file changed, 13 insertions(+), 13 deletions(-) diff --git a/README-ko_KR.md b/README-ko_KR.md index 909e7f48..a30ea659 100644 --- a/README-ko_KR.md +++ b/README-ko_KR.md @@ -6,16 +6,16 @@ JavaScript 에 관한 객관식 문제를 [Instagram](https://www.instagram.com/ 정답은 질문 아래 접힌 부분에 있어요, 그냥 클릭하면 펼칠 수 있어요. 행운을 빌어요 :heart: -[中文版本](./README-zh_CN.md) -[Versión en español](./README-ES.md) -[日本語](./README-ja_JA.md) -[한국어](./README-ko_KR.md) -[Русский](./README_ru-RU.md) -[Western Balkan](./README-bs_BS.md) -[Deutsch](./README-de_DE.md) -[Tiếng Việt](./README-vi.md) -[Українська мова](./README-ua_UA.md) -[Português Brasil](./README_pt_BR.md) +- [English](./README.md) +- [中文版本](./README-zh_CN.md) +- [Versión en español](./README-ES.md) +- [日本語](./README-ja_JA.md) +- [Русский](./README_ru-RU.md) +- [Western Balkan](./README-bs_BS.md) +- [Deutsch](./README-de_DE.md) +- [Tiếng Việt](./README-vi.md) +- [Українська мова](./README-ua_UA.md) +- [Português Brasil](./README_pt_BR.md) --- @@ -263,7 +263,7 @@ class Chameleon { } const freddie = new Chameleon({ newColor: "purple" }); -freddie.colorChange("orange"); +console.log(freddie.colorChange("orange")); ``` - A: `orange` @@ -445,7 +445,7 @@ console.log(sarah); #### 정답: B -**기본객체**를 제외한, 모든 객체는 프로포타입을 가져요. 기본객체는 `.toString`와 같은 몇개의 메소드와 속성에 접근할 수 있어요. 이것이 내장 JavaScript 메소드를 사용할 수 있는 이유죠! 이러한 모든 메소드는 프로토 타입에서 이용 할 수 있어요. JavaScript가 당신의 객체를 직접 찾을 수 없더라도, 당신이 접근 할 수 있도록, 프로토타입 체인으로 내려가서 찾을거에요. +**기본객체**를 제외한, 모든 객체는 프로포타입을 가져요. 기본객체는 사용자에 의해 만들어지거나 `new`키워드를 사용하여 만들어져요. 기본객체는 `.toString`와 같은 몇개의 메소드와 속성에 접근할 수 있어요. 이것이 내장 JavaScript 메소드를 사용할 수 있는 이유죠! 이러한 모든 메소드는 프로토 타입에서 이용 할 수 있어요. JavaScript가 당신의 객체를 직접 찾을 수 없더라도, 당신이 접근 할 수 있도록, 프로토타입 체인으로 내려가서 찾을거에요.

@@ -1028,7 +1028,7 @@ function sayHi() { return (() => 0)(); } -typeof sayHi(); +console.log(typeof sayHi()); ``` - A: `"object"` From 95d196bae1c750c418ddb08735942d9ed0ca554b Mon Sep 17 00:00:00 2001 From: Sara Ahmed Date: Thu, 27 Jun 2019 14:51:45 +0200 Subject: [PATCH 128/915] Questions 21 - 30 Translated to Arabic --- README_AR.md | 596 +++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 596 insertions(+) diff --git a/README_AR.md b/README_AR.md index c2bdef3f..a1946e7e 100644 --- a/README_AR.md +++ b/README_AR.md @@ -660,3 +660,599 @@ getAge(); --- + +
+21. ماهي القيمة التي تحملها `sum`؟ +
+ +```javascript +const sum = eval("10*10+5"); +``` + +- A: `105` +- B: `"105"` +- C: `TypeError` +- D: `"10*10+5"` + +
الأجابة +

+

+الجواب هو الخيار الأول : A + +`eval` تقوم بتقييم الكود الذي تم تمريره ك string. إذا كان عبارة عن expression كما في هذه الحالة, فإنها تقوم بتقييم ال expression. ال expression هو `10 * 10 + 5`. و هذا بدوره يقوم بإرجاع الرقم `105`. +

+
+ + +--- + +
+22. الى كم من المدة الزمنية ستكون "cool_secret" قابلة للوصول إليها؟ +
+ +```javascript +sessionStorage.setItem("cool_secret", 123); +``` +
+A - الى الأبد, فالبيانات لايمكن أن تفقد. +B - عندما يقوم المستخدم بقفل ال tab. +C - عندما يقوم المستخدم بقفل نافذه المتصفح , ليس فقط الtab. +D - عندما يقوم المستخدم بقفل جهاز الكمبيوتر. +
+ +
الإجابة +

+

+الجواب هو الخيار الثاني: B + +البيانات التي يتم تخزينها في `sessionStorage` يتم فقدها بعد قفل ال tab. + +إذا قمت بإستخدام `localStorage`, البيانات ستكون مخزنة هناك الى الأبد, و لكن اذا قمت بإستثناء ان تقوم بمناداة الدالة Clear كما في التالي `localStorage.clear()` عندها ستفقد هذه البيانات.: +

+
+ + +--- + +23. ماهو الناتج؟ + +```javascript +var num = 8; +var num = 10; + +console.log(num); +``` + +- A: `8` +- B: `10` +- C: `SyntaxError` +- D: `ReferenceError` + +
الإجابة +

+

+الجواب هو الخيار الثاني: B + +مع الكلمة المفتاحية `var` بإمكانك تريف عدد من المتغيرات تحمل نفس الإسم, و المتغير سيقوم بأخذ آخر قيمة تمت إضافتها اليه. + +ليس بإمكانك أن تفعل هذا مع `let` أو `const` بما أن الكلمتان المفتاحيتان عبارة عن block-scoped, بمعنى أن القيمة ستكون متاحة في نطاق الBlock الذي تم تعريفها به. +

+
+ + +--- + +24. ماهو الناتج؟ + +```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` + +
الإجابة +

+

+الجواب هو الخيار الثالث: C + +كل مفاتيح ال object (عدا الSymbols)هي عبارة عن strings وراء الكواليس, حتى لو لم تقم بكتابة ذلك صراحة بنفسك ك string, لهذا دائما `obj.hasOwnProperty('1')` تقوم بإرجاع القيمة true. + +ولكنها لا تعمل بهذا الشكل مع set, ليس هنالك `'1'` من ضمن set, لهذا `set.has('1')` تقوم بإرجاع `false`, لديها القيمة الرقمية `1` أي من النوع number, `set.has(1)` تقوم بإرجاع `true`. +

+
+ + +--- + +25. ماهو الناتج؟ + +```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` + +
الإجابة +

+

+الجواب هو الخيار الثالث: C + +إذا كان لديك مفتاحان يحملان نفس الاسم, فإن المفتاح سيتم تبديله, سيكون المفتاح في نفس مكانه, ولكنه سيحمل فقط القيمة الأخيرة +

+
+ + +--- + +
+26. في سياق تنفيذ glopal في لغة الجافاسكريبت, فإن الجافاسكريبت تقوم بإنشاء شيئين لك: الglopal object و الكلمة المفتاحية "this". +
+ +- A: true +- B: false +- C: تعتمد على + +
الإجابة +

+

+الجواب هو الخيارالأول: A + +سياق التنفيذ الأساسي هو سياق تنفيذ الglopal, وهي الشيء الذي يمكن الوصول إليه من أي مكان في الكود الذي ببرنامجك. +

+
+ + +--- + +27. ماهو الناتج؟ + +```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` + +
الإجابة +

+

+الجواب هو الخيار الثالث: C + +العبارة `continue` تقوم بتخطي دورة التكرار إذا وجد شرط معين يقوم بإرجاع `true`. +

+
+ + +--- + +28. ماهو الناتج؟ + +```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` + +
الإجابة +

+

+الجواب هو الخيار الأول : A + +`String` هي built-in constructor, و لهذا سنتمكن من إضافة خصائص لها. لقد قمت بإضافة method للprototype الخاص ب `String`. Primitive strings يتمتحويلهم بصورة اوتوماتيكية الى objects من نوع string, و التي بدورها تم انشائها عن طريق دالة ال string prototype, لهذا جميع الstrings و التي هي string objects لديها حق الوصول الى الmethod. +

+
+ + +--- + +29. ماهو الناتج؟ + +```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` + +
الإجابة +

+

+الجواب هو الخيار الثاني : B + +مفاتيح ال 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`. +

+
+ + +--- + +30. ماهو الناتج؟ + +```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` + +
الإجابة +

+

+الجوا ب هو الخيار الثاني: B + +لدينا الدالة `setTimeout` والتي تم استدعائها أولا, و لكن تم الخروج منها آخراً. + +هذا لأن في المتصفح, ليس لدينا محرَك من نوع runtime, أيضا لدينا مايعرف ب `WebAPI`. هذا ال`WebAPI` يقوم بإعطائنا الدالة `setTimeout` لكي نبدأ بها, على سبيل المثال: DOM. + +بعد ان يتم ارسال و البدء بتنفيذ ال _callback_ الى الWebAPI, الدالة `setTimeout` نفسها (ليس ال callback!) يتم اخراجها من الstack. + + + +الآن, `foo` يتم إدخالها و البدء بتنفيذها, بينما `"First"` يتم تسجيل دخولها. + + + +`foo` يتم إخراجها من ال stack, بينما `baz` يتم إدخالها و البدأ بتنفيذها. `"Third"` يتم تسجيل دخولها. + + + +ال WebAPI ليس بإمكانها إضافة أشياء الى ال stack عندما تكون جاهزة. في المقابل, هي تقوم بإدخال دالة الcallback الى شيء يسمى بال _queue_. + + + +هنا تحديدا المكان الذي تبدأ فيه الloop بالعمل. +ال **event loop** تنظر الى الstack و ال task queue, إذا كانت الstack خاوية, فهي تقوم بأخذ أول شيء في الqueue. و تقوم بإدخاله الى stack. + + + +`bar` يتم إدخالها و البدأ بتنفيذها, `"Second"` يتم تسجيل دخولها, و من ثم إخراجها من ال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. + +
Answer +

+ +#### Answer: 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` + +
Answer +

+ +#### 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. + +

+
+ +--- + +###### 33. What's the output? + +```javascript +const person = { name: "Lydia" }; + +function sayHi(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` + +
Answer +

+ +#### Answer: 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. What's the output? + +```javascript +function sayHi() { + return (() => 0)(); +} + +console.log(typeof sayHi()); +``` + +- A: `"object"` +- B: `"number"` +- C: `"function"` +- D: `"undefined"` + +
Answer +

+ +#### Answer: B + +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`, and `symbol`. `"function"` is not a type, since functions are objects, it's of type `"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 + +
Answer +

+ +#### Answer: A + +There are only six falsy values: + +- `undefined` +- `null` +- `NaN` +- `0` +- `''` (empty string) +- `false` + +Function constructors, like `new Number` and `new Boolean` are truthy. + +

+
+ +--- + +###### 36. What's the output? + +```javascript +console.log(typeof typeof 1); +``` + +- A: `"number"` +- B: `"string"` +- C: `"object"` +- D: `"undefined"` + +
Answer +

+ +#### Answer: B + +`typeof 1` returns `"number"`. +`typeof "number"` returns `"string"` + +

+
+ +--- + +###### 37. What's the 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` + +
Answer +

+ +#### Answer: 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, 7 x empty, 11]` + +depending on where you run it (it's different for every browser, node, etc.) + +

+
+ +--- + +###### 38. What's the 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` + +
Answer +

+ +#### Answer: 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 + +
Answer +

+ +#### Answer: 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 implicity wrap the object 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. What's the 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]` + +
Answer +

+ +#### Answer: 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]` + +

+
+ +--- From 8897f31467f41775df06ae9697c73b099f68ef2f Mon Sep 17 00:00:00 2001 From: Sara Ahmed Date: Thu, 27 Jun 2019 14:54:33 +0200 Subject: [PATCH 129/915] Question 22 edited --- README_AR.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/README_AR.md b/README_AR.md index a1946e7e..cc12142b 100644 --- a/README_AR.md +++ b/README_AR.md @@ -694,9 +694,13 @@ const sum = eval("10*10+5"); sessionStorage.setItem("cool_secret", 123); ```
+ A - الى الأبد, فالبيانات لايمكن أن تفقد. + B - عندما يقوم المستخدم بقفل ال tab. + C - عندما يقوم المستخدم بقفل نافذه المتصفح , ليس فقط الtab. + D - عندما يقوم المستخدم بقفل جهاز الكمبيوتر.
From 6ab2f074914f71ee47e3cd939774dbb676bd9daf Mon Sep 17 00:00:00 2001 From: Sara Ahmed Date: Thu, 27 Jun 2019 16:14:00 +0200 Subject: [PATCH 130/915] Questions 31 - 40 translated. --- README_AR.md | 161 +++++++++++++++++++++++++++------------------------ 1 file changed, 86 insertions(+), 75 deletions(-) diff --git a/README_AR.md b/README_AR.md index cc12142b..98fa0b52 100644 --- a/README_AR.md +++ b/README_AR.md @@ -964,8 +964,9 @@ baz(); --- - -###### 31. What is the event.target when clicking the button? +
+31. ماهو ال event.target عندما نقوم بالضغط على الزر +
```html
@@ -977,24 +978,31 @@ baz();
``` -- A: Outer `div` -- B: Inner `div` -- C: `button` -- D: An array of all nested elements. +
+- A: الخارجي `div` -
Answer -

+- B: الداخلي `div` -#### Answer: C +- C: `button` -The deepest nested element that caused the event is the target of the event. You can stop bubbling by `event.stopPropagation` +- D: array تحتوي على جميع العناصرالمتداخلة. +

+
الإجابة +

+

+الجواب هو الخيار الثالث: C + +العنصر المتداخل الأعمق الذي تسبب بتنفيذ الevent هو العنصر الذي يستهدفه هذا الevent, بإمكانك إيقاف ال bubbling عن طريق `event.stopPropagation`.

+ --- -###### 32. When you click the paragraph, what's the logged output? +
+32. عندما تقوم بالضغط على الفقرة (P), ماهو الناتج الذي ستتحصل عليه؟ +
```html
@@ -1009,19 +1017,19 @@ The deepest nested element that caused the event is the target of the event. You - C: `p` - D: `div` -
Answer +
الإجابة

+

+الجواب هو الخيار الأول: A -#### 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. - +إذا قمنا بالضغط على `p` سنرى إثنان من الlogs, ألا و هما `p` و `div`, أثناء عملية event propagation, هنالك ثلاث مراحل: الا وهي capturing, target و bubbling. بصورة افتراضية, الevent handlers يتم تنفيذهم في مرحلة الbubbling (إلا في حال أنك قمت بضبط قيمة `useCapture` ل `true` ). هي تتسلسل ابتداءا من أعمق عنصر متداخل تصاعدا الى الأقل عمقاً.

+
--- -###### 33. What's the output? +33. ماهو الناتج؟ ```javascript const person = { name: "Lydia" }; @@ -1039,21 +1047,21 @@ sayHi.bind(person, 21); - C: `Lydia is 21` `Lydia is 21` - D: `Lydia is 21` `function` -
Answer +
الإجابة

+

+الجواب هو الخيار الرابع: D -#### Answer: 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. +في الحالتين, بإمكاننا تمرير ال object الذي نود أن تشير اليه الكلمة المفتاحية `this`, ولكن, `.call` هي أيضا تم تنفيذها حالا. +`.bind.` تقوم بإرجاع نسخة من الدالة, ولكن مع سياق محدد, لذا هي لا يتم تنفيذها حالاً.

+ --- -###### 34. What's the output? +34. ماهو الناتج؟ ```javascript function sayHi() { @@ -1068,20 +1076,21 @@ console.log(typeof sayHi()); - C: `"function"` - D: `"undefined"` -
Answer +
الإجابة

+

+الجواب هو الخيار الثاني: B -#### Answer: B - -The `sayHi` function returns the returned value of the immediately invoked function (IIFE). This function returned `0`, which is type `"number"`. +دالة `sayHi` تقوم بإرجاع القيمة المرجعة من الدالة المناداة في اللحظة (IIFE). هذه الدالة تقوم بإرجاع `0`, و الذي نوعه عبارة عن `"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"`. +لمعلوماتك: لدينا فقط سبعة أنواع من ال built-in و هي : `null`, `undefined`, `boolean`, `number`, `string`, `object`, و `symbol`.`"function"` هي ليست نوع, وبما أن الدوال عبارة عن objects, ف هي ليست من النوع `"object"`.

+ --- -###### 35. Which of these values are falsy? +35. أي هذه القيم هي قيم قابلة للخطأ؟ ```javascript 0; @@ -1095,14 +1104,14 @@ 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: جميعها -
Answer +
الإجابة

+

+الجواب هو الخيار الأول : A -#### Answer: A - -There are only six falsy values: +لدينا فقط ستة قيم قابلة للخطأ: - `undefined` - `null` @@ -1111,14 +1120,15 @@ There are only six falsy values: - `''` (empty string) - `false` -Function constructors, like `new Number` and `new Boolean` are truthy. +Function constructors, مثل `new Number` و `new Boolean` هي قيم قابلة للصواب.

+ --- -###### 36. What's the output? +36. ماهو الناتج؟ ```javascript console.log(typeof typeof 1); @@ -1129,20 +1139,21 @@ console.log(typeof typeof 1); - C: `"object"` - D: `"undefined"` -
Answer +
الإجابة

+

+الجواب هو الخيار الثاني: B -#### Answer: B - -`typeof 1` returns `"number"`. -`typeof "number"` returns `"string"` +`typeof 1` تقوم بإرجاع `"number"`. +`typeof "number"` تقوم بإرجاع `"string"`

+ --- -###### 37. What's the output? +37. ماهو الناتج؟ ```javascript const numbers = [1, 2, 3]; @@ -1155,23 +1166,23 @@ console.log(numbers); - C: `[1, 2, 3, 7 x empty, 11]` - D: `SyntaxError` -
Answer +
الإجابة

+

+الجواب هو الخيار الثالث: C -#### Answer: 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: +عندما تقوم بضبط قيمة ما لعنصر في الarray , و بعد إضافة هذا العنصر انت تكون قد تجاوزت طول الarray, لغة الجافاسكريبت تنشيء شيئا يسمى ب "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, ...الخ)

+ --- -###### 38. What's the output? +38. ماهو الناتج؟ ```javascript (() => { @@ -1192,46 +1203,46 @@ depending on where you run it (it's different for every browser, node, etc.) - C: `1` `1` `2` - D: `1` `undefined` `undefined` -
Answer +
الإجابة

+

+الجواب هو الخيار الأول : A -#### Answer: 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`. +النطاق أو الblock `catch`يستقبل ال arguemnt الذي يساوي `x`, هذا ليس نفس القيمة `x` هندما قمنا بتمرير الarguments, هذا المتغير `x` هو متغير block-scoped, أي يتم التعامل معه أو مناداته فقط بداخل الblock الذي تم تعريفه به. -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`. +لاحقا, قمنا بضبط القيمة `1` لهذا المتغير من نوع block-scoped, وقمنا أيضا بضبط قيمة للمتغير `y`. الآن نحن نقوم بطباعة قيمة المتغير الذي من نوع block-scoped و الذي هو `x` عن طريق الlog, و الذي هو يساوي `1`. +بخارج نطاق ال`catch` block, `x` هي لاتزال `undefined`, و قيمة ال `y` تساوي `2`. عندما نريد طباعة قيمة ال x عن طريق الlog خارج نطاق ال `catch` block, فهي تقوم بإرجاع `undefined`, و ال `y` تقوم بإرجاع `2`.

+ --- -###### 39. Everything in JavaScript is either a... +39. كل شيء في الجافاسكريبت هو عبارة عن ... -- A: primitive or object -- B: function or object -- C: trick question! only objects +- A: primitive أو object +- B: function أو object +- C: فقط objects , سؤال مخادع - D: number or object -
Answer +
الإجابة

+

+الجواب هو الخيار الأول: A -#### Answer: A - -JavaScript only has primitive types and objects. - -Primitive types are `boolean`, `null`, `undefined`, `bigint`, `number`, `string`, and `symbol`. +لغة الجافاسكريبت لديها فقط primitive types و objects. -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 implicity wrap the object 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. +نقصد بال 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. What's the output? +40. ماهو الناتج؟ ```javascript [[0, 1], [2, 3]].reduce( @@ -1247,16 +1258,16 @@ What differentiates a primitive from an object is that primitives do not have an - C: `[1, 2, 0, 1, 2, 3]` - D: `[1, 2, 6]` -
Answer +
الإجابة

+

+الجواب هو الخيارالثالث: C -#### Answer: 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]` +`[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]`.

+ --- From 5f7e35baab94c2151faf23d3c8ecb8984e573803 Mon Sep 17 00:00:00 2001 From: Sara Ahmed Date: Thu, 27 Jun 2019 16:17:28 +0200 Subject: [PATCH 131/915] Update README_AR.md --- README_AR.md | 5 ----- 1 file changed, 5 deletions(-) diff --git a/README_AR.md b/README_AR.md index 98fa0b52..b4b9e260 100644 --- a/README_AR.md +++ b/README_AR.md @@ -978,15 +978,10 @@ baz(); ``` -
- A: الخارجي `div` - - B: الداخلي `div` - - C: `button` - - D: array تحتوي على جميع العناصرالمتداخلة. -
الإجابة

From 3d98f9f1e82c83572a5adc95afbd882ff7a51daf Mon Sep 17 00:00:00 2001 From: kimdanah Date: Fri, 28 Jun 2019 06:53:13 +0900 Subject: [PATCH 132/915] Translate the questions 44-52 to Korean. Done. --- README-ko_KR.md | 188 ++++++++++++++++++++++++------------------------ 1 file changed, 93 insertions(+), 95 deletions(-) diff --git a/README-ko_KR.md b/README-ko_KR.md index a30ea659..7719f3c2 100644 --- a/README-ko_KR.md +++ b/README-ko_KR.md @@ -42,9 +42,9 @@ sayHi(); #### 정답: D -함수내에서, 우선 `var`키워드를 사용해 `name`변수를 선언해요. 이것은 변수가 정의되어 있는 행에 실제로 도달할 때까지, 변수는 `undefined`을 기본값으로 호이스팅 되(생성단계에 메모리 공간이 설정됨)는 것을 의미해요. `name` 변수를 출력 하려는 줄에서 아직 변수를 정의하고 있지 않기 때문에, `undefined`값을 유지하고 있어요. +함수 내에서, 우선 `var`키워드를 사용해 `name`변수를 선언해요. 이것은 변수가 정의되어 있는 행에 실제로 도달할 때까지, 변수는 `undefined`의 기본값으로 호이스팅 되(생성단계에 메모리 공간이 설정됨)는 것을 의미해요. `name` 변수를 출력하려는 줄에서 아직 변수를 정의하고 있지 않기 때문에, `undefined`값을 유지하고 있어요. -`let`키워드(그리고 `const`)를 가지는 변수들은, `var`와는 달리, 호이스팅되지만 초기화되지 않아요. 그것들을 선언(초기화)하는 줄 전에는 접근 할 수 없어요. 이것은 "일시적 사각지대"라고 불려요. 선언되기 전에 변수에 접근하려고 하면, JavaScript는 `ReferenceError`를 던져요. +`let`키워드(그리고 `const`)를 가지는 변수들은, `var`와는 달리, 호이스팅되지만 초기화되지 않아요. 그것들을 선언(초기화)하는 줄 전에는 접근할 수 없어요. 이것은 "일시적 사각지대"라고 불려요. 선언되기 전에 변수에 접근하려고 하면, JavaScript는 `ReferenceError`를 던져요.

@@ -72,9 +72,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`는 새로운 값을 가지고, 각각의 값은 루프 안쪽 범위에 있어요.

@@ -106,11 +106,11 @@ shape.perimeter(); #### 정답: B -`diameter`의 값은 정규 함수인 반면, `perimeter`의 값은 화살표 함수라는 점에 유의해요. +`diameter`의 값은 정규 함수인 반면, `perimeter`의 값은 화살표 함수라는 점을 유의하세요. 화살표 함수에서는, 통상적인 함수와는 달리, `this`키워드는 현재 주위의 범위를 참조해요! 이것은 `perimeter`를 부르면, shape 객체가 아닌, 그 주위의 범위(예를 들면 window)를 참조하는 것을 의미해요. -그 객체에는 `radius`라는 값은 없고, `undefined`를 리턴해요. +그 객체에는 `radius`라는 값은 없어, `undefined`를 리턴해요.

@@ -135,7 +135,7 @@ shape.perimeter(); 단항 더하기는 피연산자를 숫자로 변환하려 해요. `true`는 `1`, `false`은 `0`. -문자열 `'Lydia'`는 참 같은 값이에요. 실제로 묻고 있는 것은, "이 참 같은 값이 거짓 같은 값인가?"에요. 이것은 `false`을 리턴해요. +문자열 `'Lydia'`는 참 같은 값이에요. 실제로 물어보는 것은, "이 참 같은 값이 거짓 같은 값인가?"에요. 이것은 `false`을 리턴해요.

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

@@ -208,7 +208,7 @@ JavaScript에서, 모든 객체는 서로 동일하게 설정하면 _참조_ 에 -한개의 객체를 변경하면, 그것들 모두 변경해요. +한 개의 객체를 변경하면, 그것들 모두 변경해요.

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

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

@@ -300,7 +300,7 @@ console.log(greetign); #### 정답: A -객체는 출력되요, 전역객체에 빈 객체를 방금 만들었기 때문이에요. `greeting`을 `greettign`으로 잘못 입력했을 경우, JS 인터프리터는 실제로 이것을 `global.greettign = {}` (또는 브라우저의 `window.greetign = {}`) 라고 간주해요. +객체는 출력돼요, 전역 객체에 빈 객체를 방금 만들었기 때문이에요. `greeting`을 `greettign`으로 잘못 입력했을 경우, JS 인터프리터는 실제로 이것을 `global.greettign = {}` (또는 브라우저의 `window.greetign = {}`) 라고 간주해요. 이것을 피하기 위해서, `"use strict"`를 사용할 수 있어요. 이렇게 하면 변수를 어떤 것과 동일하게 설정하기 전에 변수를 선언했는지 확인할 수 있어요. @@ -332,7 +332,7 @@ bark.animal = "dog"; JavaScript에서는 가능해요, 함수는 객체이기 때문이에요! (윈시형 이외는 모두 객체) -함수는 특별한 종류의 객체에요. 당신이 쓴 코드는 실제 함수가 아니에요. 함수는 속성을 가진 객체에요. 이 속성은 호출이 가능해요. +함수는 특별한 종류의 객체예요. 당신이 쓴 코드는 실제 함수가 아니에요. 함수는 속성을 가진 객체예요. 이 속성은 호출이 가능해요.

@@ -373,7 +373,7 @@ Person.prototype.getFullName = function() { }; ``` -`member.getFullName()`은 작동되요. 이것은 왜 유익할까요? 이 메소드를 생성자 자체에 추가했다고 할게요. 아마도 모든 `Person` 인스턴스는 이 메소드를 필요로 하지 않을 수도 있어요. 그 경우 그들은 아직 속성을 갖고, 각각의 인스턴스를 위해 메모리 공간을 소비하기 때문에, 많은 메모리 공간을 낭비하게 되요. 대신에, 프로토타입을 추가하는 것만으로, 메모리의 한 지점을 가지지만, 모든 것들은 그것에 접근 할 수 있어요. +`member.getFullName()`은 작동해요. 이것은 왜 유익할까요? 이 메소드를 생성자 자체에 추가했다고 할게요. 아마도 모든 `Person` 인스턴스는 이 메소드를 필요로 하지 않을 수도 있어요. 그 경우 그들은 아직 속성을 갖고, 각각의 인스턴스를 위해 메모리 공간을 소비하기 때문에, 많은 메모리 공간을 낭비해요. 대신에, 프로토타입을 추가하는 것만으로, 메모리의 한 지점을 가지지만, 모든 것들은 그것에 접근 할 수 있어요.

@@ -405,9 +405,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`로 남아있어요. +`this.firstName`에 `"Sarah"`을 대입하고, `this.lastName`에 `"Smith"`을 대입했다고 말했었어요. (그렇지만) 우리는 실제로, `global.firstName = 'Sarah'` 그리고 `global.lastName = 'Smith'`를 정의해요. `sarah` 자체는 `undefined`로 남아있어요.

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

@@ -472,9 +472,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"`을 리턴하는 일이 발생해요.

@@ -500,12 +500,12 @@ console.log(number); #### 정답: C -**접미사** 단항연산자 `++`: +**접미사** 단항 연산자 `++`: 1. 값 리턴 (이것은 `0`을 리턴해요) 2. 값 증가 (number는 지금 `1`이에요) -**접두사** 단항연산자 `++`: +**접두사** 단항 연산자 `++`: 1. 값 증가 (number는 지금 `2`이에요) 2. 값 리턴 (이것은 `2`을 리턴해요) @@ -541,7 +541,7 @@ getPersonInfo`${person} is ${age} years old`; #### 정답: B -태그드 템플릿 리터럴을 사용하는 경우, 첫번재 인수의 값은 항상 문자열 값의 배열이에요. 나머지 인수는 식을 통과한 값을 얻게 되요. +태그드 템플릿 리터럴을 사용하는 경우, 첫 번재 인수의 값은 항상 문자열 값의 배열이에요. 나머지 인수는 식을 통과한 값을 얻어요.

@@ -573,11 +573,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`를 리턴하는 이유죠.

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

@@ -656,7 +656,7 @@ const sum = eval("10*10+5"); #### 정답: A -`eval` 문자열로서 통과된 코드를 평가해요. 이 경우와 같이 만약 그것이 표현식이라면, 표현식을 평가해요. 표현식은 `10 * 10 + 5` 이에요. 이것은 숫자 `105`를 리턴해요. +`eval` 문자열로서 통과된 코드를 평가해요. 이 경우와 같이 만약 그것이 표현식이라면, 표현식을 평가해요. 표현식은 `10 * 10 + 5`이에요. 이것은 숫자 `105`를 리턴해요.

@@ -679,9 +679,9 @@ sessionStorage.setItem("cool_secret", 123); #### 정답: B -`sessionStorage`에 저장된 데이터는 _탭_ 을 닫은 후에 삭제되요. +`sessionStorage`에 저장된 데이터는 _탭_ 을 닫은 후에 삭제돼요. -만약 `localStorage`를 사용했다면, 예를들어 `localStorage.clear()`를 호출 하지 않는 한, 데이터는 영원할거에요. +만약 `localStorage`를 사용했다면, 예를 들어 `localStorage.clear()`를 호출하지 않는 한, 데이터는 영원할 거에요.

@@ -707,7 +707,7 @@ console.log(num); #### 정답: B -`var`키워드를 사용하면, 같은 이름으로 복수의 변수를 선언 할 수 있어요. 변수는 최신의 값을 유지해요. +`var`키워드를 사용하면, 같은 이름으로 복수의 변수를 선언할 수 있어요. 변수는 최신의 값을 유지해요. 블록 스코프의 `let` 또는 `const`에서는 할 수 없어요. @@ -738,7 +738,7 @@ set.has(1); #### 정답: C -모든 객체 키는(Symbol 제외) 문자열로 직접 입력하지 않아도, 내부적으로는 문자열이에요. 이것이 `obj.hasOwnProperty('1')` 또한 true를 리턴하는 이유에요. +모든 객체 키는(심볼 제외) 문자열로 직접 입력하지 않아도, 내부적으로는 문자열이에요. 이것이 `obj.hasOwnProperty('1')` 또한 true를 리턴하는 이유죠. set에서는 작동하지 않아요. set에는 `'1'`이 없어요: `set.has('1')`는 `false`를 리턴해요. 그것은 수형인 `1`을 가지고 있어, `set.has(1)`은 `true`를 리턴해요. @@ -764,7 +764,7 @@ console.log(obj); #### 정답: C -같은 이름의 키를 두개 가지고 있다면, 첫번째 위치에서, 마지막에 지정된 값으로 대체 될 거에요. +같은 이름의 키를 두 개 가지고 있다면, 첫 번째 위치에서, 마지막에 지정된 값으로 대체될 거예요.

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

@@ -808,7 +808,7 @@ for (let i = 1; i < 5; i++) { #### 정답: C -`continue` 표현식은 특정 조건이 `true`를 리턴하면 반복처리를 건너뛰어요. +`continue` 표현식은 특정 조건이 `true`를 리턴하면 반복 처리를 건너뛰어요.

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

@@ -867,11 +867,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`를 리턴해요.

@@ -900,33 +900,31 @@ baz(); #### 정답: B -`setTimeout`함수를 처음으로 호출 했어요. 그러나 그것은 마지막에 출력되요. +처음에 `setTimeout`함수를 호출했어요. 그러나 그것은 마지막에 출력돼요. -브라우저에는 런타임 엔진 뿐만 아니라 `WebAPI`라고 불리는 것도 있기 때문이에요. `WebAPI`는 `setTimeout`함수를 최초에 부여하는데, DOM을 예로 들 수 있어요. - -After the _callback_ is pushed to the WebAPI, the `setTimeout` function itself (but not the callback!) is popped off the stack. +브라우저에는 런타임 엔진뿐만 아니라 `WebAPI`라고 불리는 것도 있기 때문이에요. `WebAPI`는 `setTimeout`함수를 최초에 부여하는데, DOM을 예로 들 수 있어요. _callback_ 이 WebAPI에 푸시된 후, `setTimeout`함수 자체(callback이 아니에요!)는 stack에 사라졌어요. -지금, `foo` 는 호출 되었고, `"First"`는 출력 되었어요. +지금, `foo` 는 호출되었고, `"First"`는 출력되었어요. -`foo`는 stack에 사라지고, `baz`가 호출 되었어요. `"Third"`가 출력 되었어요. +`foo`는 stack에 사라지고, `baz`가 호출되었어요. `"Third"`가 출력되었어요. -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 위로 푸시해요. -`bar`가 호출되었고, `"Second"`가 출력 되었으며, stack에서 사라졌어요. +`bar`가 호출되었고, `"Second"`가 출력되었으며, stack에서 사라졌어요.

@@ -955,7 +953,7 @@ WebAPI는 준비가 될때 마다 stack에 항목을 추가 할 수 없어요. #### 정답: C -가장 깊이 중첩된 요소가 이벤트를 발생시킬 이벤트 대상이에요. `event.stopPropagation`을 통해서 버블링을 중단 할 수 있어요. +가장 깊이 중첩된 요소가 이벤트를 발생시킬 이벤트 대상이에요. `event.stopPropagation`을 통해서 버블링을 중단할 수 있어요.

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

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

@@ -1043,7 +1041,7 @@ console.log(typeof sayHi()); `sayHi`함수는 즉시 호출 함수(IIFE)로서 리턴된 값을 리턴해요. 이 함수는 `0`을 리턴하고, 형은 `"number"`이에요. -참고: 단 7개의 내장형이 있어요: `null`, `undefined`, `boolean`, `number`, `string`, `object` 그리고 `symbol`. `"function"`은 객체이기 때문에 형이아니라 `"object"` 형이에요. +참고: 단 7개의 내장형이 있어요: `null`, `undefined`, `boolean`, `number`, `string`, `object` 그리고 `symbol`. `"function"`은 객체이기 때문에 형이 아니라 `"object"` 형이에요.

@@ -1071,7 +1069,7 @@ undefined; #### 정답: A -단 6개의 거짓 값이 있어요: +단 6개의 거짓 같은 값이 있어요: - `undefined` - `null` @@ -1080,7 +1078,7 @@ undefined; - `''` (빈 문자열) - `false` -`new Number` 그리고 `new Boolean`와 같은 생성자 함수는 참같은 값이에요. +`new Number` 그리고 `new Boolean`와 같은 생성자 함수는 참 같은 값이에요.

@@ -1129,12 +1127,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 등 마다 달라요.) +실행 위치에 따라 달라요 (브라우저, node 등마다 달라요.)

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

@@ -1222,9 +1220,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]`을 얻게 돼요.

@@ -1276,7 +1274,7 @@ setInterval(() => console.log("Hi"), 1000); #### 정답: A -이것은 유니크한 id를 리턴해요. 이 id는 `clearInterval()` 함수로 간격을 없애기 위해 사용 될 수 있어요. +이것은 유니크한 id를 리턴해요. 이 id는 `clearInterval()` 함수로 간격을 없애기 위해 사용될 수 있어요.

@@ -1299,7 +1297,7 @@ setInterval(() => console.log("Hi"), 1000); #### 정답: A -문자열은 반복 가능한 객체에요. 스프레드 연산자는 반복 가능한 객체의 모든 문자를 1개의 요소로 매핑해요. +문자열은 반복 가능한 객체예요. 스프레드 연산자는 반복 가능한 객체의 모든 문자를 1개의 요소로 매핑해요.

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

@@ -1365,7 +1363,7 @@ Promise.race([firstPromise, secondPromise]).then(res => console.log(res)); #### 정답: 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. +복수의 프로미스를 `Promise.race` 메소드에 넘겨주면, _최초_ 의 프로미스를 해결/거부 해요. `setTimeout` 메소드에 타이머를 전달해요: 첫번째 프로미스(`firstPromise`)에는 500ms, 두번째 프로미스(`secondPromise`)에는 100ms. 이것은 `'two'`의 값을 가진 `secondPromise`가 최초로 해결한다는 것을 의미해요. 이제 `res`는 `'two'`의 값을 유지하고 출력되요.

@@ -1392,19 +1390,19 @@ console.log(members); #### 정답: D -First, we declare a variable `person` with the value of an object that has a `name` property. +우선, 변수 `person`의 값을 `name`속성을 가진 객체로 선언해요. -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!) +그 후, `members`라는 변수를 선언해요. 배열의 첫 번째 요소에 `person`변수의 값을 대입해요. 서로를 같게 설정하면 _참조_ 에 의해 상호작용해요. 어떤 변수에서 다른 변수로 참조를 할당하면, 그 참조의 _복사본_ 을 만들어요. (그들은 _같은_ 참조를 가지고 있지 않다는 것을 유의하세요!) -Then, we set the variable `person` equal to `null`. +그리고, 변수 `person`를 `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. +배열의 첫 번째 요소는 객체에 대한 다른 (복사된) 참조를 가지고 있기 때문에, `person` 변수의 값만 변경하고, 배열의 첫번째 요소는 변경할 수 없어요. `members`의 첫 번째 요소는 여전히 원본 객체에 대한 참조를 유지하고 있어요. `members` 배열을 출력할 때, 첫 번째 요소는 여전히 객체의 값을 유지하고 있어 로그가 출력돼요.

@@ -1434,7 +1432,7 @@ for (const item in person) { #### 정답: 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. +`for-in` 루프를 사용하면, 객체 키를 통해서 반복할 수 있는데, 이경우에서는 `name` 그리고 `age`에요. 내부적으로, 객체 키는 문자열이에요 (심볼이 아니라면 말이죠). 모든 루프에서, `item`의 값은 반복되어 있는 현재의 키 값으로 설정해요. 우선, `item`은 `name`가 대입되어, 로그로 출력돼요. 그 후, `item`은 `age`가 대입되어, 로그로 출력돼요.

@@ -1457,18 +1455,18 @@ console.log(3 + 4 + "5"); #### 정답: 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`. +처음으로 `3 + 4`가 평가되요. 결과는 숫자 `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"`. +`7 + '5'`의 결과는 강제성 때문에 `"75"`가 돼요. JavaScript는 숫자 `7`을 문자열로 변환하고, (자세한 내용은)질문 15를 보세요. `+` 연산자를 사용해서 두 개의 문자열을 연결할 수 있어요. `"7" + "5"`의 결과는 `"75"`이에요.

--- -###### 49. What's the value of `num`? +###### 49. `num`의 값은 무엇일까요? ```javascript const num = parseInt("7*6", 10); @@ -1484,16 +1482,16 @@ const num = parseInt("7*6", 10); #### 정답: 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. +문자열의 첫 번째 숫자만 리턴돼요. _진법_ 에 근거하여 (파싱 하고자 하는 숫자의 기준을 명시하기 위한 두 번째 인수: 기본적인 10진수, 6진수, 8진수, 2진수 등), `parseInt`는 문자열 내의 문자가 타당한지 여부를 확인해요. 진수에 유효한 숫자가 아닌 문자를 만나면, 파싱을 멈추고, 다음 문자를 무시해요. -`*` is not a valid number. It only parses `"7"` into the decimal `7`. `num` now holds the value of `7`. +`*`은 유요한 숫자가 아니에요. `"7"`만 십진수의 `7`으로 파싱 돼요. 이제 `num`은 `7`의 값을 유지해요.

--- -###### 50. What's the output`? +###### 50. 무엇이 출력 될까요? ```javascript [1, 2, 3].map(num => { @@ -1512,9 +1510,9 @@ Only the first numbers in the string is returned. Based on the _radix_ (the seco #### 정답: 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. +배열을 매핑할 때, `num`의 값은 헌재 순환하고 있는 요소예요. 이 경우, 요소는 숫자이기 때문에, if문의 조건 `typeof num === "number"`는 `true`를 리턴해요. map 합수는 새로운 배열을 만들고 함수에서 리턴된 값을 삽입해요. -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`. +그러나, 값을 리턴하지 않아요. 함수는 값을 리턴하지 않을 때, `undefined`을 리턴해요. 배열에서의 모든 요소에 대해 블록 함수가 호출되기 때문에, 각 요소에 대해 `undefined`을 리턴해요.

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

@@ -1578,18 +1576,18 @@ sayHi(); ``` - A: `"It worked! Hello world!"` -- B: `"Oh no an error: undefined` +- B: `"Oh no an error! undefined"` - C: `SyntaxError: can only throw Error objects` -- D: `"Oh no an error: Hello world!` +- D: `"Oh no an error! Hello world!"`
정답

#### 정답: 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'`. +`throw`문을 사용해, 커스텀 에러를 만들 수 있어요. 이 표현식을 사용해, 예외를 던질 수 있어요. 예외는 string, a number, a boolean or an object이 될 수 있어요. 이 경우, 예외는 `'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'`. +`catch` 문을 사용해, `try` 블록에서 예외가 던져졌을 경우에 어떻게 할지 명시할 수 있어요. 예외가 던져졌어요: 문자열 `'Hello world'`. `e`는 이제 문자열이고, 그것을 출력해요. 결과는 `'Oh an error: Hello world'`이에요.

@@ -1618,7 +1616,7 @@ console.log(myCar.make); #### 정답: 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"`. +속성을 리턴할 때, 속성 값은 생성자에 설정한 값이 아닌, _리턴된_ 값과 같아요. `"Maserati"` 문자열을 리턴하기 때문에, `myCar.make`는 `"Maserati"`에요.

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

From 6564cf1489c7c9ade6b4ad5d1d2647d4823bf800 Mon Sep 17 00:00:00 2001 From: Sara Ahmed Date: Fri, 28 Jun 2019 14:06:09 +0200 Subject: [PATCH 133/915] Questions 41-43 translated into Arabic --- README_AR.md | 85 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 85 insertions(+) diff --git a/README_AR.md b/README_AR.md index b4b9e260..0fd44e7e 100644 --- a/README_AR.md +++ b/README_AR.md @@ -1266,3 +1266,88 @@ console.log(numbers); --- + +41. ماهو الناتج؟ + +```javascript +!!null; +!!""; +!!1; +``` + +- A: `false` `true` `false` +- B: `false` `false` `true` +- C: `false` `true` `true` +- D: `true` `true` `false` + +
الإجابة +

+

+الجواب هو الخيارالثاني: B + +`null` هي قيمة خطئية. `!null` تقوم بإرجاع `true`. `!true` تقوم بإرجاع `false`. + +`""` هي قيمة خطئية. `!""` تقوم بإرجاع `true`. `!true` تقوم بإرجاع `false`. + +`1` هي قيمة صحيحية. `!1` تقوم بإرجاع `false`. `!false` تقوم بإرجاع `true`. + +

+
+ + +--- + +
+42. ماهو الذي تقوم الدالة `setInterval` بإرجاع في المتصفح؟ +
+ +```javascript +setInterval(() => console.log("Hi"), 1000); +``` + +
+- A: فريد id + +- B: قيمة ال milliseconds محددة. + +- C: الدالة التي تم تمريرها + +- D: `undefined` + +
+ +
الإجابة +

+

+الجواب هو الخيار الأول: A + +تقوم بإرجاع ال id الفريد, هذا الid يمكن استخدامه لكي يقوم بتصفير عداد الفترات المفصلة عن طريق استخدام الدالة `clearInterval()` +

+
+ + +--- + +43. مالذي يتم ارجاعه بعد تنفيذ الكود أدناه؟ + +```javascript +[..."Lydia"]; +``` + +- A: `["L", "y", "d", "i", "a"]` +- B: `["Lydia"]` +- C: `[[], "Lydia"]` +- D: `[["L", "y", "d", "i", "a"]]` + +
الإجابة +

+

+الجواب هو الخيار الأول: A + +الstring هي تكرارية, و عملية الspread (...) تقوم بتحويل اي حرف ينتمي الى فئة تكرارية الى عنصر منفرد واحد. +

+
+ + +--- + From 811f3637bccf8c6fd086b486daebafcd872cebad Mon Sep 17 00:00:00 2001 From: Sara Ahmed Date: Fri, 28 Jun 2019 14:13:59 +0200 Subject: [PATCH 134/915] Update README_AR.md --- README_AR.md | 374 +++++++++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 365 insertions(+), 9 deletions(-) diff --git a/README_AR.md b/README_AR.md index 0fd44e7e..fa8b5802 100644 --- a/README_AR.md +++ b/README_AR.md @@ -1285,11 +1285,12 @@ console.log(numbers);
الجواب هو الخيارالثاني: B -`null` هي قيمة خطئية. `!null` تقوم بإرجاع `true`. `!true` تقوم بإرجاع `false`. - -`""` هي قيمة خطئية. `!""` تقوم بإرجاع `true`. `!true` تقوم بإرجاع `false`. - -`1` هي قيمة صحيحية. `!1` تقوم بإرجاع `false`. `!false` تقوم بإرجاع `true`. +`null` is falsy. `!null` returns `true`. `!true` returns `false`. +`null` هي قيمة خطئية, `!null` تقوم بإرجاع `true`. `!true` تقوم بإرجاع `false`. +`""` is falsy. `!""` returns `true`. `!true` returns `false`. +`""` هي قيمة خطئية, `!""` تقوم بإرجاع `true` . `!true` تقوم بإرجاع `false`. +`1` is truthy. `!1` returns `false`. `!false` returns `true`. +`1` هي قيمة صحيحية. `!1` تقوم بإرجاع `false`. `!false` تقوم بإرجاع `true`.

@@ -1306,13 +1307,13 @@ setInterval(() => console.log("Hi"), 1000); ```
-- A: فريد id +- A: فريد id -- B: قيمة ال milliseconds محددة. +- B: قيمة ال milliseconds محددة. -- C: الدالة التي تم تمريرها +- C: الدالة التي تم تمريرها -- D: `undefined` +- D: `undefined`
@@ -1351,3 +1352,358 @@ setInterval(() => console.log("Hi"), 1000); --- +###### 44. What's the 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` + +
Answer +

+ +#### Answer: 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"` + +
Answer +

+ +#### Answer: 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. What's the output? + +```javascript +let person = { name: "Lydia" }; +const members = [person]; +person = null; + +console.log(members); +``` + +- A: `null` +- B: `[null]` +- C: `[{}]` +- D: `[{ name: "Lydia" }]` + +
Answer +

+ +#### Answer: 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. What's the 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]` + +
Answer +

+ +#### Answer: 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. What's the output? + +```javascript +console.log(3 + 4 + "5"); +``` + +- A: `"345"` +- B: `"75"` +- C: `12` +- D: `"12"` + +
Answer +

+ +#### Answer: 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` + +
Answer +

+ +#### 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. + +`*` is not a valid number. It only parses `"7"` into the decimal `7`. `num` now holds the value of `7`. + +

+
+ +--- + +###### 50. What's the 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 ]` + +
Answer +

+ +#### Answer: 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. What's the 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"` + +
Answer +

+ +#### Answer: 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. What's the 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!` + +
Answer +

+ +#### Answer: 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. What's the 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` + +
Answer +

+ +#### 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"`. + +

+
+ +--- + +###### 54. What's the 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"` + +
Answer +

+ +#### Answer: 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 (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"`. + +

+
From 69c1e1dcc1b594451a1ac69212c10e33c23c8811 Mon Sep 17 00:00:00 2001 From: Sara Ahmed Date: Fri, 28 Jun 2019 15:45:55 +0200 Subject: [PATCH 135/915] =?UTF-8?q?=D9=8EQuestions=2044=20-=2050=20transla?= =?UTF-8?q?ted=20into=20Arabic?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README_AR.md | 163 +++++++++++++++++++++++++++++---------------------- 1 file changed, 92 insertions(+), 71 deletions(-) diff --git a/README_AR.md b/README_AR.md index fa8b5802..8c816a9e 100644 --- a/README_AR.md +++ b/README_AR.md @@ -1285,12 +1285,25 @@ console.log(numbers);
الجواب هو الخيارالثاني: B -`null` is falsy. `!null` returns `true`. `!true` returns `false`. -`null` هي قيمة خطئية, `!null` تقوم بإرجاع `true`. `!true` تقوم بإرجاع `false`. -`""` is falsy. `!""` returns `true`. `!true` returns `false`. -`""` هي قيمة خطئية, `!""` تقوم بإرجاع `true` . `!true` تقوم بإرجاع `false`. -`1` is truthy. `!1` returns `false`. `!false` returns `true`. -`1` هي قيمة صحيحية. `!1` تقوم بإرجاع `false`. `!false` تقوم بإرجاع `true`. +`null` قيمة خطئية. + +`!null` تقوم بإرجاع `true`. + +`!true` تقوم بإرجاع `false`. +********* + +`""` قيمة خطئية. + +`!""`تقوم بإرجاع `true`. + +`!true` تقوم بإرجاع `false`. +********* + +`1` قيمة صحيحية. + +`!1` تقوم بإرجاع `false`. + +`!false` تقوم بإرجاع `true`.

@@ -1352,7 +1365,7 @@ setInterval(() => console.log("Hi"), 1000); --- -###### 44. What's the output? +44. ماهو الناتج؟ ```javascript function* generator(i) { @@ -1371,23 +1384,23 @@ console.log(gen.next().value); - C: `10, 20` - D: `0, 10 and 10, 20` -
Answer +
الإجابة

+

+الجواب هو الخيار الثالث: C -#### Answer: 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. +الدوال العادية ليس بإمكانها ان تتوقف في وسط التنفيذ بعد أن يتم مناداتها, و لكن الدوال من نوع generator من الممكن أن يتم ايقافها وسط التنفيذ, و لاحقا يتم مواصلة تنفيذها من حيث المكان الذي توقفت به. في كل مرة تواجه فيها الدالة من نوع generator الكلمة المفتاحية `yield`, فإن الدالة تخضع أو تستسلم للقيمة المحددة بعدها. مع ملاحظة أن الدالة من نوع generator في هذه الحالة, لاتقوم بإرجاع القيمة, يل تخضع لتلك القيمة. -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`. +أولا, نقوم بإنشاء الدالة من نوع 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`.

+ --- -###### 45. What does this return? +45. ما الذي يتم ارجاعه عند تنفيذ الكود؟ ```javascript const firstPromise = new Promise((res, rej) => { @@ -1406,19 +1419,19 @@ Promise.race([firstPromise, secondPromise]).then(res => console.log(res)); - C: `"two" "one"` - D: `"one" "two"` -
Answer +
الإجابة

+

+الجواب هو الخيار الثاني: B -#### Answer: 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. - +عندما نقوم بتمرير عدد من الpromises للدالة `Promise.race`. فهي تقوم برفض أو فصل الpromise الاولى. للدالة `setTimeout` نحن نقوم بتمرير timer: 500ms لل promise الأولى و التي هي (`firstPromise`), و 100ms اي 100ملي ثانية للpromise الثانية والتي هي (`secondPromise`) هذا يعني ان ال `secondPromise` يتم فصلها اولاً مع القيمة `'two'`. `res` الآن تحمل قيمة `'two'`, وهي التي تم طباعتها عن طريق الlog.

+ --- -###### 46. What's the output? +46. ماهو الناتج؟ ```javascript let person = { name: "Lydia" }; @@ -1433,31 +1446,32 @@ console.log(members); - C: `[{}]` - D: `[{ name: "Lydia" }]` -
Answer +
الإجابة

+

+الجواب هو الخيار الرابع: D -#### Answer: D - -First, we declare a variable `person` with the value of an object that has a `name` property. +أولا, نقوم بتعريف المتغير `person` مع قيمة عبارة عن object لديه الخاصية `name`. -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!) +ثم ,نقوم بتعريف المتغير الذي يسمى ب `members`. نقوم بضيط قيمة أول عنصر في ال array بالقيمة التي يحملها المتغير `person`. +الobjects تتفاعل عن طريق الrefrence عندما نقوم بضبطها مساويةً لبعضها البعض, عندما تقوم بتعريف أو إنشاء refrence معين من متغير الى متغير آخر, أنت فعليا تقوم بعمل نسخة من ذلك الrefrence. (مع ملاحظة أنهم ليس لديهم نفس الrefrence) -Then, we set the variable `person` equal to `null`. +ثم , نقوم بضبط قمية المتغير `person` بقيمة تساوي `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. - +نحن فقط نقوم بتعديل قيمة المتغير `person`, وليس أول عنصر في ال array, بما أن ذلك العنصر لديه refrence منسوخ من ال object. أول عنصر في `members` لا يزال لديه refrence للobject الأصلي. و عندما نقوم بطباع الarray `members` عن طريق الlog, فإن العنصر الأول لايزال يحمل قيمة الobject, و التي سيتم طباعتها عن طريق log.

+ --- -###### 47. What's the output? +47. ماهو الناتج؟ ```javascript const person = { @@ -1475,19 +1489,19 @@ for (const item in person) { - C: `"Lydia", 21` - D: `["name", "Lydia"], ["age", 21]` -
Answer +
الإجابة

- +

#### Answer: 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. - +بإستخدام `for-in` التكرارية, بامكاننا أن نصل الى جميع المفاتيح التي تخص object معين. في هذه الحالة `name` و `age`. ماوراء الكواليس, مفاتيح ال objects هي عبارة عن strings (إذا لم تكن هذه المفاتيح عبارة عن symbol), في أي حلقة من الحلقات التكرارية, نقوم بضبط القيمة `item`مساوية للمفتاح الحالي الذي هي تتكرر فيه اوعنده. أولا `item` تساوي `name`, و يتم طباعتها عن طريق الlog, ثم `item` تساوي `age` و التي ايضا تم طباعتها عن طريق الlog.

+ --- -###### 48. What's the output? +48. ماهو الناتج؟ ```javascript console.log(3 + 4 + "5"); @@ -1498,23 +1512,26 @@ console.log(3 + 4 + "5"); - C: `12` - D: `"12"` -
Answer +
الإجابة

+

+الجواب هو الخيار الثاني: B -#### Answer: 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. +Operator associativity او ترابطية العامل هي الترتيب أو التسلسل الذي يقيم به الcompiler ال expressions, ف هو إما أن يكون من اليسار الى اليمين أو من اليمين الى اليسار. هذا يحدث فقط إذا كان جميع الoperators لديها نفس الأسبقية. لدينا فقط نوع واحد من الoperator ألا و هو `+`. بالإضافة الى التالي, الترابطية هي من اليسار الى اليمين. `3 + 4` gets evaluated first. This results in the number `7`. +`3 + 4` يتم تقييمها أولا. هذا مايعطينا الناتج الذي هو عبارة عن الرقم `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"`. - +`7 + '5'` تقوم بإرجاع الناتج `"75"` بسبب عملية ال coercion وهي العمليةالتي تقوم بالتحويل من نوع الى آخر, لغة الجافاسكريبت تقوم بتحويل الرقم `7` الى النوع string, أنظرالى السؤال رقم 15 في الأعلى. بإمكاننا عمل concatenate لمتغيرين من النوع string بإستخدام العملية `+`. `"7" + "5"` سترجع الناتج `"75"`.

+ --- -###### 49. What's the value of `num`? +
+49. ماهي قيمة `num`؟ +
```javascript const num = parseInt("7*6", 10); @@ -1525,21 +1542,21 @@ const num = parseInt("7*6", 10); - C: `7` - D: `NaN` -
Answer +
الإجابة

+

+الجواب هو الخيار الثالث: C -#### 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. - -`*` is not a valid number. It only parses `"7"` into the decimal `7`. `num` now holds the value of `7`. +فقط الأرقام الأولى في الstring يتم إرجاعها. بناءاً على _radix_ (الargument الثاني لكي يتم تحديدنوعية الرقم الذي نود أن نقوم بعمل parse له الى: base 10, hexadecimal, octal, binary, الخ. ). تقوم `parseInt` بالتحقق عن إذا ماكانت الحروف في الstring صالحة. و بمجرد أن تجد حرف غير صالح في ال radix, ف هي تقوم بإيقاف عملية الparsing مباشرة و تتجاهل الحروف التي تليه. +`*` ليست رقم صالح. هي فقط تقوم بعمل parse ل `"7"` الى عدد عشري `7`. `num` الآن تحمل القيمة `7`.

+ --- -###### 50. What's the output`? +50. ماهو الناتج؟ ```javascript [1, 2, 3].map(num => { @@ -1553,21 +1570,21 @@ Only the first numbers in the string is returned. Based on the _radix_ (the seco - C: `[undefined, undefined, undefined]` - D: `[ 3 x empty ]` -
Answer +
الإجابة

+

+الجواب هو الخيار الثالث: C -#### Answer: 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`. +عندما يتم عمل mapping لل array, فإن قيمة `num` ستساوي قيمة العنصر الذي يتم حاليا المرور به, فكما نعرف أن الmapping يدور على جميع عناصر الarray. في هذه الحالة, العناصر عبارة عن أرقام, لهذا فإن شرط ال if statement `typeof num === "number"` يقوم بإرجاع `true`. دالة map تقوم بإنشاء array جديدة, و إدخال القيم المرجعة من الدالة في هذه الarray. +ولكن, لا نقوم بإرجاع قيمة. عندما لا نقوم بإرجاع قيمة من الدالة, فإن الدالة تقوم بإرجاع `undefined`. لكل عنصرٍ في الarray, فإن نطاق الدالة يتم مناداته, لهذا لأي عنصر نقوم بإرجاع `undefined`.

+ --- -###### 51. What's the output? +51. ماهو الناتج؟ ```javascript function getInfo(member, year) { @@ -1588,10 +1605,10 @@ console.log(person, birthYear); - C: `{ name: "Lydia" }, "1998"` - D: `{ name: "Sarah" }, "1997"` -
Answer +
الإجابة

- -#### Answer: A +

+الجواب هو الخيار الأول: 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). @@ -1601,10 +1618,11 @@ The value of `person` is an object. The argument `member` has a (copied) referen

+ --- -###### 52. What's the output? +52. ماهو الناتج؟ ```javascript function greeting() { @@ -1628,10 +1646,10 @@ sayHi(); - C: `SyntaxError: can only throw Error objects` - D: `"Oh no an error: Hello world!` -
Answer +
الإجابة

- -#### Answer: D +

+الجواب هو الخيار الرابع: 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'`. @@ -1639,10 +1657,11 @@ With the `catch` statement, we can specify what to do if an exception is thrown

+ --- -###### 53. What's the output? +53. ماهو الناتج؟ ```javascript function Car() { @@ -1659,19 +1678,20 @@ console.log(myCar.make); - C: `ReferenceError` - D: `TypeError` -
Answer +
الإجابةAnswer

- -#### Answer: B +

+الجواب هو الخيار الثاني: 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. What's the output? +54. ماهو الناتج؟ ```javascript (() => { @@ -1687,10 +1707,10 @@ console.log(typeof y); - C: `"object", "number"` - D: `"number", "undefined"` -
Answer +
الإجابة

- -#### Answer: A +

+الجواب هو الخيار الأول : A `let x = y = 10;` is actually shorthand for: @@ -1707,3 +1727,4 @@ However, we created a global variable `y` when setting `y` equal to `10`. This v

+ From 0a594d85266e7367e59aa8952b3fc0a80061e68a Mon Sep 17 00:00:00 2001 From: Sara Ahmed Date: Fri, 28 Jun 2019 16:43:11 +0200 Subject: [PATCH 136/915] Questions 51 - 54 translated into Arabic --- README_AR.md | 26 ++++++++++++-------------- 1 file changed, 12 insertions(+), 14 deletions(-) diff --git a/README_AR.md b/README_AR.md index 8c816a9e..95f93aec 100644 --- a/README_AR.md +++ b/README_AR.md @@ -1610,12 +1610,11 @@ console.log(person, birthYear);
الجواب هو الخيار الأول: 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). +الArguments يتم تمريرها عن طريق قيمها, إلا في حالة كان قيمتها عبارة عن object, ففي هذه الحالة يتم تمريرها عن طريق الrefrence. `birthYear` تم تمريرها عن طريق القيمة, و بما أنها من النوع string وليس object. عندما نقوم بتمرير الarguments عن طريق القيمة, فإن نسخة من هذه القيمة يتم إنشاءها (أنظر للسؤال رقم 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"` +المتغير `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"`.

@@ -1651,10 +1650,9 @@ sayHi();
الجواب هو الخيار الرابع: 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'`. +مع عبارة `throw` , بإمكاننا إنشاء errors حسب الطلب, أي ليست كا الإخطاء العامة في اللغة, بإستخدام هذه العبارة بإمكانك أن تضع exception, الexception يمكن أن يكون : string, a number, a boolean or an object. في هذه الحالة, الexcption لدينا هو ال string `'Hello world'`. +مع عبارة `catch`, بإمكاننا ان نحدد ما الذي يتوجب فعله عندما يتم وضع أو إلقاء الexception في نطاق ال `try`. تم إلقاء أو وضع exception: الstring `'Hello world'`. `e` الآن تساوي تلك تلك الstring,و هي التي نقوم بطباعتها عن طريق الlgo. هذا سيعطينا النتيجة `'Oh an error: Hello world'`.

@@ -1683,8 +1681,7 @@ console.log(myCar.make);
الجواب هو الخيار الثاني: 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"`. - +عندما تقوم بإرجاع خاصية, فإن قيمة هذه الخاصية هي تساوي القيمة المرجعة, ليس القيمة التي تم ضبطها في دالة الconstructor. نقوم بإرجاع الstring `"Maserati"`, لذا فإن `myCar.make` تساوي `"Maserati"`.

@@ -1712,19 +1709,20 @@ console.log(typeof y);
الجواب هو الخيار الأول : A -`let x = y = 10;` is actually shorthand for: +`let x = y = 10;` هي في الحقيقة إختصار ل: +
```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 (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"`. +
+عندما نقوم بضبط قيمة `y` لكي تساوي `10`, فنحن فعليا نقوم بإضافة الخاصية `y` للglopal object. (`window` في المتصفح, `global` في Node). في المتصفح, `window.y` الآن تساوي `10`. -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"`. +ثم, عندما نقوم بتعريف المتغير `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"`.

From 6b03e0c5192178ea887338d54a9465933ae1fa2b Mon Sep 17 00:00:00 2001 From: Sara Ahmed Date: Fri, 28 Jun 2019 17:12:10 +0200 Subject: [PATCH 137/915] Update the Introduction --- README_AR.md | 24 +++++++++++++----------- 1 file changed, 13 insertions(+), 11 deletions(-) diff --git a/README_AR.md b/README_AR.md index 95f93aec..57753fd2 100644 --- a/README_AR.md +++ b/README_AR.md @@ -9,21 +9,23 @@ أقوم بتحديث هذا المستودع أسبوعيا بإضافة المزيد من الأسئلة. :muscle: :rocket: -الأجوبة توجد في الجزء المطوي بالأسفل أدناه تحت كل سؤال على حدة, فقط قم بالضغط على كلمة الإجابة لكي تحصل على الإجابة, حظا موفقا :heart: - -اللغات المتوفرة: - -[English](https://github.com/SaraAli26/javascript-questions/blob/master/README.md) +آخر تحديث: 21 يونيو -[中文版本](https://github.com/SaraAli26/javascript-questions/blob/master/README-zh_CN.md) -[Русский](https://github.com/SaraAli26/javascript-questions/blob/master/README_ru-RU.md) - -[Western Balkan](https://github.com/SaraAli26/javascript-questions/blob/master/README-bs_BS.md) +الأجوبة توجد في الجزء المطوي بالأسفل أدناه تحت كل سؤال على حدة, فقط قم بالضغط على كلمة الإجابة لكي تحصل على الإجابة, حظا موفقا :heart: -[Deutsch](https://github.com/SaraAli26/javascript-questions/blob/master/README-de_DE.md) +اللغات المتوفرة: -[Tiếng Việt](https://github.com/SaraAli26/javascript-questions/blob/master/README-vi.md) +* [English](./README.md) +* [中文版本](./README-zh_CN.md) +* [Versión en español](./README-ES.md) +* [日本語](./README-ja_JA.md) +* [Русский](./README_ru-RU.md) +* [Western Balkan](./README-bs_BS.md) +* [Deutsch](./README-de_DE.md) +* [Tiếng Việt](./README-vi.md) +* [Українська мова](./README-ua_UA.md) +* [Português Brasil](./README_pt_BR.md) ____________ From 90c6718ce75c1ec8da94e0b60c134e0749183ca1 Mon Sep 17 00:00:00 2001 From: Sara Ahmed Date: Fri, 28 Jun 2019 17:12:55 +0200 Subject: [PATCH 138/915] Update README_AR.md --- README_AR.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/README_AR.md b/README_AR.md index 57753fd2..3a65247f 100644 --- a/README_AR.md +++ b/README_AR.md @@ -27,8 +27,10 @@ * [Українська мова](./README-ua_UA.md) * [Português Brasil](./README_pt_BR.md) + ____________ + 1. ماهو الناتج ؟ ```javascript From 2da26a0cec170e24f9d859c76c57ec964616194d Mon Sep 17 00:00:00 2001 From: Sara Ahmed Date: Fri, 28 Jun 2019 17:43:23 +0200 Subject: [PATCH 139/915] Update README_AR.md --- README_AR.md | 36 ++++++++++++++++++------------------ 1 file changed, 18 insertions(+), 18 deletions(-) diff --git a/README_AR.md b/README_AR.md index 3a65247f..7df33b9c 100644 --- a/README_AR.md +++ b/README_AR.md @@ -1207,7 +1207,7 @@ console.log(numbers);
الجواب هو الخيار الأول : A -النطاق أو الblock `catch`يستقبل ال arguemnt الذي يساوي `x`, هذا ليس نفس القيمة `x` هندما قمنا بتمرير الarguments, هذا المتغير `x` هو متغير block-scoped, أي يتم التعامل معه أو مناداته فقط بداخل الblock الذي تم تعريفه به. +النطاق أو الblock `catch`يستقبل ال arguemnt الذي يساوي `x`, هذا ليس نفس القيمة `x` عندما قمنا بتمرير الarguments, هذا المتغير `x` هو متغير block-scoped, أي يتم التعامل معه أو مناداته فقط بداخل الblock الذي تم تعريفه به. لاحقا, قمنا بضبط القيمة `1` لهذا المتغير من نوع block-scoped, وقمنا أيضا بضبط قيمة للمتغير `y`. الآن نحن نقوم بطباعة قيمة المتغير الذي من نوع block-scoped و الذي هو `x` عن طريق الlog, و الذي هو يساوي `1`. @@ -1264,7 +1264,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]`.

@@ -1316,7 +1316,7 @@ console.log(numbers); ---
-42. ماهو الذي تقوم الدالة `setInterval` بإرجاع في المتصفح؟ +42. ماهو الذي تقوم الدالة `setInterval` بإرجاعه في المتصفح؟
```javascript @@ -1324,13 +1324,13 @@ setInterval(() => console.log("Hi"), 1000); ```
-- A: فريد id +فريد id - A -- B: قيمة ال milliseconds محددة. +قيمة ال milliseconds محددة. - B -- C: الدالة التي تم تمريرها + C - الدالة التي تم تمريرها -- D: `undefined` +`undefined` - D
@@ -1339,7 +1339,7 @@ setInterval(() => console.log("Hi"), 1000);
الجواب هو الخيار الأول: A -تقوم بإرجاع ال id الفريد, هذا الid يمكن استخدامه لكي يقوم بتصفير عداد الفترات المفصلة عن طريق استخدام الدالة `clearInterval()` +تقوم بإرجاع ال id الفريد, هذا الid يمكن استخدامه لكي يقوم بتصفير عداد الفترات المفصلة أي الinterval عن طريق استخدام الدالة `clearInterval()`

@@ -1362,7 +1362,7 @@ setInterval(() => console.log("Hi"), 1000);
الجواب هو الخيار الأول: A -الstring هي تكرارية, و عملية الspread (...) تقوم بتحويل اي حرف ينتمي الى فئة تكرارية الى عنصر منفرد واحد. +الstring هي تكرارية, و عملية الspread (...) تقوم بتحويل اي حرف تم فيه تنفيذ فئة تكرارية الى عنصر منفرد واحد.

@@ -1393,7 +1393,7 @@ 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. @@ -1496,7 +1496,7 @@ for (const item in person) {
الإجابة

-#### Answer: B +الجواب هو الخيار الثاني: B بإستخدام `for-in` التكرارية, بامكاننا أن نصل الى جميع المفاتيح التي تخص object معين. في هذه الحالة `name` و `age`. ماوراء الكواليس, مفاتيح ال objects هي عبارة عن strings (إذا لم تكن هذه المفاتيح عبارة عن symbol), في أي حلقة من الحلقات التكرارية, نقوم بضبط القيمة `item`مساوية للمفتاح الحالي الذي هي تتكرر فيه اوعنده. أولا `item` تساوي `name`, و يتم طباعتها عن طريق الlog, ثم `item` تساوي `age` و التي ايضا تم طباعتها عن طريق الlog.

@@ -1523,7 +1523,6 @@ console.log(3 + 4 + "5"); Operator associativity او ترابطية العامل هي الترتيب أو التسلسل الذي يقيم به الcompiler ال expressions, ف هو إما أن يكون من اليسار الى اليمين أو من اليمين الى اليسار. هذا يحدث فقط إذا كان جميع الoperators لديها نفس الأسبقية. لدينا فقط نوع واحد من الoperator ألا و هو `+`. بالإضافة الى التالي, الترابطية هي من اليسار الى اليمين. -`3 + 4` gets evaluated first. This results in the number `7`. `3 + 4` يتم تقييمها أولا. هذا مايعطينا الناتج الذي هو عبارة عن الرقم `7`. `7 + '5'` تقوم بإرجاع الناتج `"75"` بسبب عملية ال coercion وهي العمليةالتي تقوم بالتحويل من نوع الى آخر, لغة الجافاسكريبت تقوم بتحويل الرقم `7` الى النوع string, أنظرالى السؤال رقم 15 في الأعلى. بإمكاننا عمل concatenate لمتغيرين من النوع string بإستخدام العملية `+`. `"7" + "5"` سترجع الناتج `"75"`. @@ -1581,7 +1580,7 @@ const num = parseInt("7*6", 10); عندما يتم عمل mapping لل array, فإن قيمة `num` ستساوي قيمة العنصر الذي يتم حاليا المرور به, فكما نعرف أن الmapping يدور على جميع عناصر الarray. في هذه الحالة, العناصر عبارة عن أرقام, لهذا فإن شرط ال if statement `typeof num === "number"` يقوم بإرجاع `true`. دالة map تقوم بإنشاء array جديدة, و إدخال القيم المرجعة من الدالة في هذه الarray. -ولكن, لا نقوم بإرجاع قيمة. عندما لا نقوم بإرجاع قيمة من الدالة, فإن الدالة تقوم بإرجاع `undefined`. لكل عنصرٍ في الarray, فإن نطاق الدالة يتم مناداته, لهذا لأي عنصر نقوم بإرجاع `undefined`. +ولكن, لا نقوم بإرجاع قيمة. عندما لا نقوم بإرجاع قيمة من الدالة, فإن الدالة تقوم بإرجاع `undefined`. لكل عنصرٍ في الarray, فإن نطاق الدالة او نعني الfunction block يتم مناداته, لهذا لأي عنصر نقوم بإرجاع `undefined`.

@@ -1654,9 +1653,9 @@ sayHi();
الجواب هو الخيار الرابع: D -مع عبارة `throw` , بإمكاننا إنشاء errors حسب الطلب, أي ليست كا الإخطاء العامة في اللغة, بإستخدام هذه العبارة بإمكانك أن تضع exception, الexception يمكن أن يكون : string, a number, a boolean or an 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,و هي التي نقوم بطباعتها عن طريق الlgo. هذا سيعطينا النتيجة `'Oh an error: Hello world'`. +مع عبارة `catch`, بإمكاننا ان نحدد ما الذي يتوجب فعله عندما يتم وضع أو إلقاء الexception في نطاق ال `try`. تم إلقاء أو وضع exception: الstring `'Hello world'`. `e` الآن تساوي تلك الstring,log. هذا سيعطينا النتيجة `'Oh an error: Hello world'`.

@@ -1680,12 +1679,12 @@ console.log(myCar.make); - C: `ReferenceError` - D: `TypeError` -
الإجابةAnswer +
الإجابة

الجواب هو الخيار الثاني: B -عندما تقوم بإرجاع خاصية, فإن قيمة هذه الخاصية هي تساوي القيمة المرجعة, ليس القيمة التي تم ضبطها في دالة الconstructor. نقوم بإرجاع الstring `"Maserati"`, لذا فإن `myCar.make` تساوي `"Maserati"`. +عندما تقوم بإرجاع خاصية, فإن قيمة هذه الخاصية هي تساوي القيمة المرجعة, ليس القيمة التي تم ضبطها في دالة الconstructor. نقوم بإرجاع ال string `"Maserati"`, لذا فإن `myCar.make` تساوي `"Maserati"`.

@@ -1722,7 +1721,8 @@ let x = y; ```
-عندما نقوم بضبط قيمة `y` لكي تساوي `10`, فنحن فعليا نقوم بإضافة الخاصية `y` للglopal object. (`window` في المتصفح, `global` في Node). في المتصفح, `window.y` الآن تساوي `10`. + +عندما نقوم بضبط قيمة`y` لكي تساوي `10`, فنحن فعليا نقوم بإضافة الخاصية `y` للglopal 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"`. From e22f060a508c4365f6d333217926c54f6abe4650 Mon Sep 17 00:00:00 2001 From: Sara Ahmed Date: Fri, 28 Jun 2019 17:48:29 +0200 Subject: [PATCH 140/915] Update README_AR.md --- README_AR.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/README_AR.md b/README_AR.md index 7df33b9c..07650141 100644 --- a/README_AR.md +++ b/README_AR.md @@ -1089,7 +1089,7 @@ console.log(typeof sayHi()); --- -35. أي هذه القيم هي قيم قابلة للخطأ؟ +35. أي هذه القيم هي قيم خطئية؟ ```javascript 0; @@ -1110,7 +1110,7 @@ undefined;
الجواب هو الخيار الأول : A -لدينا فقط ستة قيم قابلة للخطأ: +لدينا فقط ستة قيم خطئية: - `undefined` - `null` @@ -1119,7 +1119,7 @@ undefined; - `''` (empty string) - `false` -Function constructors, مثل `new Number` و `new Boolean` هي قيم قابلة للصواب. +Function constructors, مثل `new Number` و `new Boolean` هي قيم صحيحية.

From 6606eafb5bd5188c929229024859b4bc1cf6e413 Mon Sep 17 00:00:00 2001 From: Sara Ahmed Date: Fri, 28 Jun 2019 17:53:05 +0200 Subject: [PATCH 141/915] Update README_AR.md --- README_AR.md | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/README_AR.md b/README_AR.md index 07650141..82c5c8d6 100644 --- a/README_AR.md +++ b/README_AR.md @@ -1316,6 +1316,7 @@ console.log(numbers); ---
+ 42. ماهو الذي تقوم الدالة `setInterval` بإرجاعه في المتصفح؟
@@ -1324,9 +1325,11 @@ setInterval(() => console.log("Hi"), 1000); ```
-فريد id - A - -قيمة ال milliseconds محددة. - B + + A- id فريد + + + B - قيمة محددة لل milliseconds C - الدالة التي تم تمريرها From a89c46a7e75b920221b9756328bee7fde018a185 Mon Sep 17 00:00:00 2001 From: Sara Ahmed Date: Fri, 28 Jun 2019 17:54:51 +0200 Subject: [PATCH 142/915] Update README_AR.md --- README_AR.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README_AR.md b/README_AR.md index 82c5c8d6..9a2140c7 100644 --- a/README_AR.md +++ b/README_AR.md @@ -1326,7 +1326,7 @@ setInterval(() => console.log("Hi"), 1000);
- A- id فريد +A - id فريد B - قيمة محددة لل milliseconds From 37dce1098d76675b9993171f2462ebb922033262 Mon Sep 17 00:00:00 2001 From: Sara Ahmed Date: Fri, 28 Jun 2019 17:56:26 +0200 Subject: [PATCH 143/915] Update README_AR.md --- README_AR.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README_AR.md b/README_AR.md index 9a2140c7..183efb8f 100644 --- a/README_AR.md +++ b/README_AR.md @@ -1326,7 +1326,7 @@ setInterval(() => console.log("Hi"), 1000);
-A - id فريد +A - فريد id B - قيمة محددة لل milliseconds From a462a17e3edcc598c2c43d102fa45d8eaef80515 Mon Sep 17 00:00:00 2001 From: Sara Ahmed Date: Fri, 28 Jun 2019 17:59:06 +0200 Subject: [PATCH 144/915] Update README_AR.md --- README_AR.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README_AR.md b/README_AR.md index 183efb8f..8c4f822a 100644 --- a/README_AR.md +++ b/README_AR.md @@ -1326,7 +1326,7 @@ setInterval(() => console.log("Hi"), 1000);
-A - فريد id +A - رقم فريد أو متفرد id B - قيمة محددة لل milliseconds From dd41301522b0a0c22dbcff2b38befac04aba735a Mon Sep 17 00:00:00 2001 From: Sara Ahmed Date: Fri, 28 Jun 2019 18:03:10 +0200 Subject: [PATCH 145/915] Update README_AR.md --- README_AR.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/README_AR.md b/README_AR.md index 8c4f822a..f8e48560 100644 --- a/README_AR.md +++ b/README_AR.md @@ -391,6 +391,7 @@ Person.prototype.getFullName = function() { ```
+ اذا استطعنا جعل `member.getFullName()` تعمل. لماذا ستكون ذات فائدة؟ فلنفترض أننا أضفنا هذه الmethod للconstructor نفسها. ربما ليس أي instance من `Person` تحتاج الى هذه ال method. بهذه الطريقة سنقوم بإستهلاك مساحة كبيرة من الذاكرة, بما أنهم سيظلون يحتفظون ب هذه الخاصية, و التي بدورها ستقوم بحجز مساحة في الذاكرة لأي instance. لذا من الأفضل أن نقوم بإضافتهاالى الprototype, بهذه الطريقة ستقوم بحجز مكان واحد فقط في الذاكرة, و لكنها متاحة للكل للوصول إليها.

@@ -533,7 +534,7 @@ console.log(number); 1. تقوم بزيادة القيمة(number الآن تساوي `2`) 2. تقوم بإٍرجاع القيمة (هذه ترجع `2`) -هذايقوم بإرجاع `0 2 2`. +هذا يقوم بإرجاع `0 2 2`.

From f1bf6d419380ee098ef48c5c1f4a826ae333da97 Mon Sep 17 00:00:00 2001 From: Lydia Date: Sat, 29 Jun 2019 13:58:59 +0200 Subject: [PATCH 146/915] Add questions 55 to 63 --- README.md | 299 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 299 insertions(+) diff --git a/README.md b/README.md index 52c948f6..b886f849 100644 --- a/README.md +++ b/README.md @@ -1655,3 +1655,302 @@ However, we created a global variable `y` when setting `y` equal to `10`. This v

+ +--- + +###### 55. What's the 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` + +
Answer +

+ +#### Answer: 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. What's the 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}` + +
Answer +

+ +#### Answer: 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. What's the 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` + +
Answer +

+ +#### Answer: 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. What's the 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` + +
Answer +

+ +#### Answer: A + +The `delete` operator returns a boolena 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. What's the output? + +```javascript +const numbers = [1, 2, 3, 4, 5]; +const [y] = numberes; + +console.log(y); +``` + +- A: `[[1, 2, 3, 4, 5]]` +- B: `[1, 2, 3, 4, 5]` +- C: `1` +- D: `[1]` + +
Answer +

+ +#### Answer: C + +We can unpack values from arrays or properties from objects through destructing. 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. What's the 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 }` + +
Answer +

+ +#### Answer: 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. What's the 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"]` + +
Answer +

+ +#### Answer: 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. What's the 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}"` + +
Answer +

+ +#### Answer: 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 properties which names are included in the array will be added to the JSON string. In this case, only the properies 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. What's the 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` + +
Answer +

+ +#### 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. + +`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 b9e7651e13f07c5a8a3b2cb1b9d490fc635b43e6 Mon Sep 17 00:00:00 2001 From: Lydia Date: Sat, 29 Jun 2019 14:15:32 +0200 Subject: [PATCH 147/915] Fix question 51 --- README.md | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index f68f5f09..1bb924fc 100644 --- a/README.md +++ b/README.md @@ -10,7 +10,6 @@ List of available languages: * [中文版本](./README-zh_CN.md) * [Versión en español](./README-ES.md) * [日本語](./README-ja_JA.md) -* [한국어](./README-ko_KR.md) * [Русский](./README_ru-RU.md) * [Western Balkan](./README-bs_BS.md) * [Deutsch](./README-de_DE.md) @@ -1521,7 +1520,7 @@ 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; + year = "1998"; } const person = { name: "Sarah" }; @@ -1573,9 +1572,9 @@ sayHi(); ``` - A: `"It worked! Hello world!"` -- B: `"Oh no an error: undefined"` +- B: `"Oh no an error: undefined` - C: `SyntaxError: can only throw Error objects` -- D: `"Oh no an error! Hello world!"` +- D: `"Oh no an error: Hello world!`
Answer

From 3004132b96e84335c9fe68bcaecc0cc157b838ad Mon Sep 17 00:00:00 2001 From: Lydia Date: Sat, 29 Jun 2019 14:20:01 +0200 Subject: [PATCH 148/915] Fix question 10 --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 1bb924fc..e6005514 100644 --- a/README.md +++ b/README.md @@ -320,7 +320,7 @@ bark.animal = "dog"; - A: Nothing, this is totally fine! - B: `SyntaxError`. You cannot add properties to a function this way. -- C: `undefined` +- C: `"Woof"` gets logged. - D: `ReferenceError`

Answer From c9a015243500cb6400dbebe3aef5522e0fbb6ab8 Mon Sep 17 00:00:00 2001 From: Lydia Date: Sat, 29 Jun 2019 14:23:22 +0200 Subject: [PATCH 149/915] Fix question 3 --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index e6005514..d684f98f 100644 --- a/README.md +++ b/README.md @@ -92,8 +92,8 @@ const shape = { perimeter: () => 2 * Math.PI * this.radius }; -shape.diameter(); -shape.perimeter(); +console.log(shape.diameter()); +console.log(shape.perimeter()); ``` - A: `20` and `62.83185307179586` From 319e3f2375269e8b504f9efe323f6d6e16e5cea3 Mon Sep 17 00:00:00 2001 From: Lydia Hallie Date: Sat, 29 Jun 2019 15:15:35 +0200 Subject: [PATCH 150/915] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index d684f98f..af9784d3 100644 --- a/README.md +++ b/README.md @@ -2,7 +2,7 @@ I post daily multiple choice JavaScript questions on my [Instagram](https://www.instagram.com/theavocoder), which I'll also post 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 weekly with new questions. Last update: June 21st +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 weekly with new questions. Last update: June 29th The answers are in the collapsed sections below the questions, simply click on them to expand it. Good luck :heart: From 3ac8f92809b2c3b2d0121b3ad29d8811627d1de3 Mon Sep 17 00:00:00 2001 From: Sara Ahmed Date: Sat, 29 Jun 2019 15:35:10 +0200 Subject: [PATCH 151/915] Update README.md --- README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/README.md b/README.md index 916fa133..16379695 100644 --- a/README.md +++ b/README.md @@ -6,6 +6,8 @@ From basic to advanced: test how well you know JavaScript, refresh your knowledg The answers are in the collapsed sections below the questions, simply click on them to expand it. Good luck :heart: + +[العربية](https://github.com/SaraAli26/javascript-questions/blob/master/README_AR.md) [中文版本](./README-zh_CN.md) [Русский](./README_ru-RU.md) [Western Balkan](./README-bs_BS.md) From 5d8e349e56900eb8cf7f97c9326ec61dcbcd1acf Mon Sep 17 00:00:00 2001 From: Sara Ahmed Date: Sat, 29 Jun 2019 15:38:01 +0200 Subject: [PATCH 152/915] link to Arabic added to introduction --- README.md | 19 ++++++++++++------- 1 file changed, 12 insertions(+), 7 deletions(-) diff --git a/README.md b/README.md index 16379695..91a7e32f 100644 --- a/README.md +++ b/README.md @@ -6,13 +6,18 @@ From basic to advanced: test how well you know JavaScript, refresh your knowledg The answers are in the collapsed sections below the questions, simply click on them to expand it. Good luck :heart: - -[العربية](https://github.com/SaraAli26/javascript-questions/blob/master/README_AR.md) -[中文版本](./README-zh_CN.md) -[Русский](./README_ru-RU.md) -[Western Balkan](./README-bs_BS.md) -[Deutsch](./README-de_DE.md) -[Tiếng Việt](./README-vi.md) + +* [English](./README.md) +* [中文版本](./README-zh_CN.md) +* [Versión en español](./README-ES.md) +* [日本語](./README-ja_JA.md) +* [Русский](./README_ru-RU.md) +* [Western Balkan](./README-bs_BS.md) +* [Deutsch](./README-de_DE.md) +* [Tiếng Việt](./README-vi.md) +* [Українська мова](./README-ua_UA.md) +* [Português Brasil](./README_pt_BR.md) +* [العربية](https://github.com/SaraAli26/javascript-questions/blob/master/README_AR.md) --- From 67405aaf884922def99e7384982c4fa537309260 Mon Sep 17 00:00:00 2001 From: Lydia Hallie Date: Sat, 29 Jun 2019 15:41:48 +0200 Subject: [PATCH 153/915] Update README.md --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index af9784d3..d4fffadb 100644 --- a/README.md +++ b/README.md @@ -10,6 +10,7 @@ List of available languages: * [中文版本](./README-zh_CN.md) * [Versión en español](./README-ES.md) * [日本語](./README-ja_JA.md) +* [한국어](./README-ko_KR.md) * [Русский](./README_ru-RU.md) * [Western Balkan](./README-bs_BS.md) * [Deutsch](./README-de_DE.md) From e12b10b0790c66a616e688ae32ff0e02d0ae4e04 Mon Sep 17 00:00:00 2001 From: Sara Ahmed Date: Sat, 29 Jun 2019 15:54:37 +0200 Subject: [PATCH 154/915] Update README.md --- README.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index d1ebb7d0..f30cc8f6 100644 --- a/README.md +++ b/README.md @@ -18,7 +18,8 @@ List of available languages: * [Tiếng Việt](./README-vi.md) * [Українська мова](./README-ua_UA.md) * [Português Brasil](./README_pt_BR.md) -* [العربية](https://github.com/SaraAli26/javascript-questions/blob/master/README_AR.md) +* [العربية](./README_AR.md) + --- From 73f516977aee349402945d79274736fff6f01e0b Mon Sep 17 00:00:00 2001 From: Sara Ahmed Date: Sat, 29 Jun 2019 16:08:42 +0200 Subject: [PATCH 155/915] Update README_AR.md --- README_AR.md | 2 -- 1 file changed, 2 deletions(-) diff --git a/README_AR.md b/README_AR.md index f8e48560..05d51b95 100644 --- a/README_AR.md +++ b/README_AR.md @@ -9,8 +9,6 @@ أقوم بتحديث هذا المستودع أسبوعيا بإضافة المزيد من الأسئلة. :muscle: :rocket: -آخر تحديث: 21 يونيو - الأجوبة توجد في الجزء المطوي بالأسفل أدناه تحت كل سؤال على حدة, فقط قم بالضغط على كلمة الإجابة لكي تحصل على الإجابة, حظا موفقا :heart: From d6a5a2e2314c71d52071278dfe8aa7676d91a381 Mon Sep 17 00:00:00 2001 From: kimdanah Date: Sun, 30 Jun 2019 02:28:22 +0900 Subject: [PATCH 156/915] Improve accuracy of the translation. --- README-ko_KR.md | 97 ++++++++++++++++++++++++------------------------- 1 file changed, 47 insertions(+), 50 deletions(-) diff --git a/README-ko_KR.md b/README-ko_KR.md index 7719f3c2..0b926df0 100644 --- a/README-ko_KR.md +++ b/README-ko_KR.md @@ -2,7 +2,7 @@ JavaScript 에 관한 객관식 문제를 [Instagram](https://www.instagram.com/theavocoder)에 매일 게시하고 있어요, 물론 여기에도 게시할 거예요! -초급부터 고급까지: JavaScript를 얼마나 잘 알고 있는지 테스트하거나, 지식을 조금 깊게 하거나, 코딩 면접을 준비하세요! :muscle: :rocket: 이 기록을 매주 새로운 질문으로 업데이트해요. 마지막 업데이트: 6월 21일 +초급부터 고급까지: JavaScript를 얼마나 잘 알고 있는지 테스트하거나, 지식을 조금 더 새롭게 하거나, 코딩 면접을 준비하세요! :muscle: :rocket: 이 기록을 매주 새로운 질문으로 업데이트해요. 마지막 업데이트: 6월 29일 정답은 질문 아래 접힌 부분에 있어요, 그냥 클릭하면 펼칠 수 있어요. 행운을 빌어요 :heart: @@ -42,9 +42,9 @@ sayHi(); #### 정답: D -함수 내에서, 우선 `var`키워드를 사용해 `name`변수를 선언해요. 이것은 변수가 정의되어 있는 행에 실제로 도달할 때까지, 변수는 `undefined`의 기본값으로 호이스팅 되(생성단계에 메모리 공간이 설정됨)는 것을 의미해요. `name` 변수를 출력하려는 줄에서 아직 변수를 정의하고 있지 않기 때문에, `undefined`값을 유지하고 있어요. +함수 내에서, 우선 `var`키워드를 사용해 `name`변수를 선언해요. 이것은 변수가 정의되어 있는 행에 실제로 도달할 때까지, `undefined`의 기본값으로 호이스팅 되(생성단계에 메모리 공간이 설정)는 것을 의미해요. `name` 변수를 출력하려는 줄에서 아직 변수를 정의하고 있지 않기 때문에, `undefined`값을 유지하고 있어요. -`let`키워드(그리고 `const`)를 가지는 변수들은, `var`와는 달리, 호이스팅되지만 초기화되지 않아요. 그것들을 선언(초기화)하는 줄 전에는 접근할 수 없어요. 이것은 "일시적 사각지대"라고 불려요. 선언되기 전에 변수에 접근하려고 하면, JavaScript는 `ReferenceError`를 던져요. +`let`키워드(그리고 `const`)를 가지는 변수들은, `var`와는 달리, 호이스팅되지만 초기화되지 않아요. 그것들을 선언(초기화)하는 줄 전에는 접근할 수 없어요. 이것은 "일시적 사각지대"라고 불려요. 선언되기 전 변수에 접근하려고 하면, JavaScript는 `ReferenceError`를 던져요.

@@ -72,7 +72,7 @@ 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`는 새로운 값을 가지고, 각각의 값은 루프 안쪽 범위에 있어요. @@ -92,8 +92,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` @@ -108,9 +108,9 @@ shape.perimeter(); `diameter`의 값은 정규 함수인 반면, `perimeter`의 값은 화살표 함수라는 점을 유의하세요. -화살표 함수에서는, 통상적인 함수와는 달리, `this`키워드는 현재 주위의 범위를 참조해요! 이것은 `perimeter`를 부르면, shape 객체가 아닌, 그 주위의 범위(예를 들면 window)를 참조하는 것을 의미해요. +화살표 함수에서, `this`키워드는 통상적인 함수와는 다르게 현재 주위의 범위를 참조해요! 이것은 `perimeter`를 부르면, shape 객체가 아닌 그 주위의 범위(예를 들면 window)를 참조하는 것을 의미해요. -그 객체에는 `radius`라는 값은 없어, `undefined`를 리턴해요. +그 객체에는 `radius`라는 값은 없기 때문에 `undefined`를 리턴해요.

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

@@ -165,15 +165,13 @@ const mouse = { #### 정답: A -JavaScript에서, 모든 객체 키는 문자열이에요 (심볼이 아닌 한). 비록 그것을 문자열 _형_ 으로 입력하지 않아도, 항상 내부적으로 문자열로 변환되어요. +JavaScript에서, 모든 객체 키는 문자열이에요 (심볼이 아닌 한). 비록 그것을 문자열 _형_ 으로 입력하지 않아도, 항상 내부적으로 문자열로 변환돼요. -JavaScript는 문장을 해석(또는 박스 해제)해요. 대괄호 표기를 사용하면, 첫 번째 왼쪽 대괄호 `[`를 보고 오른쪽 대괄호 `]`를 찾을 때까지 진행해요. 그때, 그 문장을 평가할 거에요. +JavaScript는 문장을 해석(또는 박스 해제)해요. 대괄호 표기를 사용하면, 첫 번째 열린 대괄호 `[`를 보고 닫힌 대괄호 `]`를 찾을 때까지 진행해요. 그때에 만, 그 문장을 평가할 거예요. -`mouse[bird.size]`: 먼저 `bird.size`를 평가해요, 이것은 `"small"`이에요. `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`와 비슷한 에러를 던질 거예요.

@@ -286,8 +284,8 @@ console.log(freddie.colorChange("orange")); ###### 9. 무엇이 출력 될까요? ```javascript -let greeting; -greetign = {}; // Typo! +let greeting; // Typo! +greetign = {}; console.log(greetign); ``` @@ -300,7 +298,7 @@ console.log(greetign); #### 정답: A -객체는 출력돼요, 전역 객체에 빈 객체를 방금 만들었기 때문이에요. `greeting`을 `greettign`으로 잘못 입력했을 경우, JS 인터프리터는 실제로 이것을 `global.greettign = {}` (또는 브라우저의 `window.greetign = {}`) 라고 간주해요. +역 객체에 빈 객체를 방금 만들었기 때문에, 객체는 출력되요. `greeting`을 `greettign`으로 잘못 입력했을 경우, JS 인터프리터는 실제로 이것을 `global.greettign = {}` (또는 브라우저의 `window.greetign = {}`) 라고 간주해요. 이것을 피하기 위해서, `"use strict"`를 사용할 수 있어요. 이렇게 하면 변수를 어떤 것과 동일하게 설정하기 전에 변수를 선언했는지 확인할 수 있어요. @@ -309,7 +307,7 @@ console.log(greetign); --- -###### 10. 이것을 하면 어떻게 될까요? +###### 10. 이렇게 하면 무슨 일이 생길까요? ```javascript function bark() { @@ -319,9 +317,9 @@ function bark() { bark.animal = "dog"; ``` -- A: 아무 일도 일어나지 않아요, 이건 완전히 괜찮아요! +- A: 별일 없어요, 이건 완전히 괜찮아요! - B: `SyntaxError` 이 방법으로 함수에 속성을 추가할 수 없어요. -- C: `undefined` +- C: `"Woof"`이 출력돼요. - D: `ReferenceError`
정답 @@ -329,8 +327,7 @@ bark.animal = "dog"; #### 정답: A -JavaScript에서는 가능해요, 함수는 객체이기 때문이에요! -(윈시형 이외는 모두 객체) +함수는 객체이기 때문에, 이건 JavaScript에서는 가능해요! (윈시형 이외는 모두 객체) 함수는 특별한 종류의 객체예요. 당신이 쓴 코드는 실제 함수가 아니에요. 함수는 속성을 가진 객체예요. 이 속성은 호출이 가능해요. @@ -365,7 +362,7 @@ console.log(member.getFullName()); #### 정답: A -보통의 객체처럼 생성자에는 속성을 추가할 수 없어요. 한 번에 모든 객체에 기능을 추가하고 싶다면, 프로토타입을 사용해야 해요. 그래서 이 경우에, +생성자에는 보통의 객체처럼 속성을 추가할 수 없어요. 한 번에 모든 객체에 기능을 추가하고 싶다면, 프로토타입을 사용해야 해요. 그래서 이 경우에, ```js Person.prototype.getFullName = function() { @@ -373,7 +370,7 @@ Person.prototype.getFullName = function() { }; ``` -`member.getFullName()`은 작동해요. 이것은 왜 유익할까요? 이 메소드를 생성자 자체에 추가했다고 할게요. 아마도 모든 `Person` 인스턴스는 이 메소드를 필요로 하지 않을 수도 있어요. 그 경우 그들은 아직 속성을 갖고, 각각의 인스턴스를 위해 메모리 공간을 소비하기 때문에, 많은 메모리 공간을 낭비해요. 대신에, 프로토타입을 추가하는 것만으로, 메모리의 한 지점을 가지지만, 모든 것들은 그것에 접근 할 수 있어요. +`member.getFullName()`은 작동해요. 이것은 왜 유익할까요? 이 메소드를 생성자 자체에 추가했다고 할게요. 아마도 모든 `Person` 인스턴스는 이 메소드를 필요로 하지 않을 수도 있어요. 그 경우 그들은 계속해서 속성을 갖고 있기 때문에, 각각의 인스턴스를 위한 메모리 공간을 소비하게 되어, 많은 메모리 공간을 낭비하게 될 거예요. 대신에, 프로토타입을 추가하는 것만으로, 메모리의 한 지점을 가지지만, 모든 것들은 그것에 접근 할 수 있어요.

@@ -405,9 +402,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`로 남아있어요. +`this.firstName`은 `"Sarah"`이고, `this.lastName`은 `"Smith"`이리고 말했었어요. (그렇지만) 우리는 실제로 한 일은 `global.firstName = 'Sarah'` 그리고 `global.lastName = 'Smith'`를 정의하는 것이에요. `sarah` 자체는 `undefined`로 남아있어요.

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

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

@@ -738,7 +735,7 @@ set.has(1); #### 정답: C -모든 객체 키는(심볼 제외) 문자열로 직접 입력하지 않아도, 내부적으로는 문자열이에요. 이것이 `obj.hasOwnProperty('1')` 또한 true를 리턴하는 이유죠. +모든 객체 키는(심볼 제외) 문자열로 직접 입력하지 않아도, 내부적으로는 문자열이에요. 이것이 `obj.hasOwnProperty('1')`도 true를 리턴하는 이유죠. set에서는 작동하지 않아요. set에는 `'1'`이 없어요: `set.has('1')`는 `false`를 리턴해요. 그것은 수형인 `1`을 가지고 있어, `set.has(1)`은 `true`를 리턴해요. @@ -764,7 +761,7 @@ console.log(obj); #### 정답: C -같은 이름의 키를 두 개 가지고 있다면, 첫 번째 위치에서, 마지막에 지정된 값으로 대체될 거예요. +같은 이름의 키를 두 개 가지고 있다면, 여전히 첫 번째 위치에 있지만, 마지막에 지정된 값으로 대체될 거예요.

@@ -775,14 +772,14 @@ console.log(obj); - A: true - B: false -- C: it depends +- C: 경우에 따라 달라요
정답

#### 정답: A -기본적인 execution context는 전역 실행 문장이에요: 당신의 코드 모든 곳에서 접근할 수 있어요. +기본적인 실행 콘텍스트는 전역 실행 문장이에요: 당신의 코드 모든 곳에서 접근할 수 있어요.

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

@@ -1012,7 +1009,7 @@ sayHi.bind(person, 21); 두 개 모두, `this`키워드를 참조하고자 하는 객체로 보낼 수 있어요. 그러나, `.call`은 _즉시 실행돼요_! -`.bind.`는 함수의 _복사본_ 을 리턴하지만, 바인딩 콘텍스트죠! 이건 즉시 실행되지 않아요. +`.bind.`는 함수의 _복사본_ 을 리턴하지만, 바인딩 콘텍스트죠! 이건 즉시 실행되지 않아요.

@@ -1041,7 +1038,7 @@ console.log(typeof sayHi()); `sayHi`함수는 즉시 호출 함수(IIFE)로서 리턴된 값을 리턴해요. 이 함수는 `0`을 리턴하고, 형은 `"number"`이에요. -참고: 단 7개의 내장형이 있어요: `null`, `undefined`, `boolean`, `number`, `string`, `object` 그리고 `symbol`. `"function"`은 객체이기 때문에 형이 아니라 `"object"` 형이에요. +참고: 단 7개의 내장형이 있어요: `null`, `undefined`, `boolean`, `number`, `string`, `object` 그리고 `symbol`. `"function"`은 객체이기 때문에 형이 아니라 `"object"`형이에요.

@@ -1332,7 +1329,7 @@ console.log(gen.next().value); 우선, 제너레이터 함수에서 `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`이에요.

@@ -1363,7 +1360,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'`의 값을 유지하고 출력되요.

@@ -1402,7 +1399,7 @@ console.log(members); -배열의 첫 번째 요소는 객체에 대한 다른 (복사된) 참조를 가지고 있기 때문에, `person` 변수의 값만 변경하고, 배열의 첫번째 요소는 변경할 수 없어요. `members`의 첫 번째 요소는 여전히 원본 객체에 대한 참조를 유지하고 있어요. `members` 배열을 출력할 때, 첫 번째 요소는 여전히 객체의 값을 유지하고 있어 로그가 출력돼요. +배열의 첫 번째 요소는 객체에 대한 다른 (복사된) 참조를 가지고 있기 때문에, `person` 변수의 값만 변경하고, 배열의 첫번째 요소는 변경할 수 없어요. `members`의 첫 번째 요소는 여전히 원본 객체에 대한 참조를 유지하고 있어요. `members` 배열을 출력할 때, 첫 번째 요소는 여전히 객체의 값을 유지하고 있어 로그가 출력돼요.

@@ -1432,7 +1429,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`로 출력돼요.

@@ -1459,7 +1456,7 @@ 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"`이에요.

@@ -1482,7 +1479,7 @@ const num = parseInt("7*6", 10); #### 정답: C -문자열의 첫 번째 숫자만 리턴돼요. _진법_ 에 근거하여 (파싱 하고자 하는 숫자의 기준을 명시하기 위한 두 번째 인수: 기본적인 10진수, 6진수, 8진수, 2진수 등), `parseInt`는 문자열 내의 문자가 타당한지 여부를 확인해요. 진수에 유효한 숫자가 아닌 문자를 만나면, 파싱을 멈추고, 다음 문자를 무시해요. +문자열의 첫 번째 숫자만 리턴돼요. _진법_ 에 근거하여 (파싱 하고자 하는 숫자의 기준을 명시하기 위한 두 번째 인수: 기본적인 10진수, 6진수, 8진수, 2진수 등), `parseInt`는 문자열 내의 문자가 타당한지 여부를 확인해요. 진수에 유효한 숫자가 아닌 문자를 만나면, 파싱을 멈추고, 다음 문자를 무시해요. `*`은 유요한 숫자가 아니에요. `"7"`만 십진수의 `7`으로 파싱 돼요. 이제 `num`은 `7`의 값을 유지해요. @@ -1524,7 +1521,7 @@ const num = parseInt("7*6", 10); ```javascript function getInfo(member, year) { member.name = "Lydia"; - year = 1998; + year = "1998"; } const person = { name: "Sarah" }; @@ -1545,11 +1542,11 @@ console.log(person, birthYear); #### 정답: A -인수들의 값이 객체가 아닌 한 _값_ 에 의해 전달되요. 그 후 _참조_ 에 의해 전달되요. `birthYear`는 객체가 아니라 문자열이기 때문에 값에 의해 전달되요. 값으로 전달하면 값의 _복사본_ 이 만들어 져요(질문 46을 보세요). +인수들의 값이 객체가 아닌 한 _값_ 에 의해 전달되요. 그 후 _참조_ 에 의해 전달되요. `birthYear`는 객체가 아니라 문자열이기 때문에 값에 의해 전달되요. 값으로 전달하면 값의 _복사본_ 이 만들어 져요(질문 46을 보세요). -변수 `birthYear`는 `"1997"`값에 대한 참조를 가져요. 인수 `year` 또한 `"1997"`에 대한 참조를 가지지만, `birthYear`가 가진 참조값과는 달라요. `year`에 `"1997"`을 대입하여 `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"`에요.

@@ -1587,7 +1584,7 @@ sayHi(); `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'`예요.

From 475d42a86b31bf704531b6c9b6b145d7f1f665f5 Mon Sep 17 00:00:00 2001 From: sweetmilkys Date: Sun, 30 Jun 2019 03:24:50 +0900 Subject: [PATCH 157/915] Add Translate the questions 55-63 to Korean. --- README-ko_KR.md | 299 ++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 299 insertions(+) diff --git a/README-ko_KR.md b/README-ko_KR.md index 0b926df0..7efc2bf9 100644 --- a/README-ko_KR.md +++ b/README-ko_KR.md @@ -1656,3 +1656,302 @@ let x = y;

+ +--- + +###### 55. 무엇이 출력 될까요? + +```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` + +
Answer +

+ +#### Answer: A + +프로토타입에서도 `delete`키워드를 사용해, 객체로부터 속성을 삭제할 수 있어요. 프로토타입에서 속성을 삭제하면, 프로토타입 체인에서 더 이상 사용할 수 없게 돼요. 이경우, `bark`함수는 `delete Dog.prototype.bark` 후에 프로토타입에서 더 이상 사용할 수 없게 되지만, 그래도 여전히 그것에 접근하려고 해요. + +함수가 아닌 것을 호출하려고 할 때, `TypeError`가 던져져요. 이경우 `pet.bark`은 `undefined`이기 때문에, `TypeError: pet.bark is not a function`예요. + +

+
+ +--- + +###### 56. 무엇이 출력 될까요? + +```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}` + +
Answer +

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

+
+ +--- + +###### 57. 무엇이 출력 될까요? + +```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` + +
Answer +

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

+
+ +--- + +###### 58. 무엇이 출력 될까요? + +```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` + +
Answer +

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

+
+ +--- + +###### 59. 무엇이 출력 될까요? + +```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]` + +
Answer +

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

+
+ +--- + +###### 60. 무엇이 출력 될까요? + +```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 }` + +
Answer +

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

+
+ +--- + +###### 61. 무엇이 출력 될까요? + +```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"]` + +
Answer +

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

+
+ +--- + +###### 62. 무엇이 출력 될까요? + +```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}"` + +
Answer +

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

+
+ +--- + +###### 63. 무엇이 출력 될까요? + +```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` + +
Answer +

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

+
From 88d6a3f7017beb1abfb1527203742aa487b99cdf Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Adrian=20Go=C5=82awski?= Date: Sat, 29 Jun 2019 20:27:04 +0200 Subject: [PATCH 158/915] Fixing typo in the main document numebers => numbers --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index d4fffadb..3be1c1f8 100644 --- a/README.md +++ b/README.md @@ -1796,7 +1796,7 @@ The `name` variable was declared with a `const` keyword, so its deletion is not ```javascript const numbers = [1, 2, 3, 4, 5]; -const [y] = numberes; +const [y] = numbers; console.log(y); ``` From a624dbf9e4701e9160009b0b05f2ebba617afe80 Mon Sep 17 00:00:00 2001 From: Sara Ahmed Date: Sun, 30 Jun 2019 12:14:41 +0200 Subject: [PATCH 159/915] Questions from 55 to 63 translated into arabic --- README_AR.md | 302 +++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 302 insertions(+) diff --git a/README_AR.md b/README_AR.md index 05d51b95..806ef11f 100644 --- a/README_AR.md +++ b/README_AR.md @@ -1732,3 +1732,305 @@ let x = y;

+ +--- + +55. ماهو الناتج؟ + +```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` + +
الإجابة +

+

+الجواب هو الخيار الأول: A + +بإمكاننا مسح خصائص object معين عن طريق استخدام الكلمة المفتاحية `delete`, أيضا يمكن فعل هذا في ال prototype. بمسح خاصية معينة من الprototype, فهي سيتم مسحها وبالتالي لن تكون موجودة في سلسلة الprototype. في هذه الحالة فإن الدالة `bark` لن تكون موجودة بعد الآن في الprototype بعد `delete Dog.prototype.bark`, ولكن بالرغم من هذا فنحن نحاول الوصول إليها. + +عندما نحاول أن ننادي شيئا ما في دالة و هو ليس موجود في هذه الدالة, فإننا سنتحصل على الخطأ `TypeError`, و في هذه الحالة `TypeError: pet.bark is not a function` بما أن `pet.bark` هي `undefined`. +

+
+ + +--- + +56. ماهو الناتج؟ + +```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}` + +
الإجابة +

+

+الجواب هو الخيار الرابع: D + +ال object `Set` هو مجموعة من القيم الفريدة, أي القيمة بإمكانها أن تتواجد مرة واحدة فقط في المجموعة. + +نقوم بتمرير التكراري أي نعني الiterable `[1, 1, 2, 3, 4]` بوجود قيمة مكررة ألا وهي `1` . بما أننا لا يمكن أن نضع قيمة واحدة مرتين في مجموعة, فإن واحدة من القيم المكررة سيتم إزالتها, و سيكون الناتج: `{1, 2, 3, 4}`. +

+
+ + +--- + +57. ماهو الناتج؟ + +```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` + +
الإجابة +

+

+الجواب هو الخيار الثالث: C + +هنا يوجد لدينا module مستورد وهو قابل للقراءة فقط, ليس بإمكانك تعديل او تحديث الmodule المستورد, أي imported module. فقط الmodule الذي قام بتصديره هو القادر على تغيير قيمته. + +عندما نحاول أن نزيد قيمة المتغير `myCounter`, سنتحصل على الخطأ `myCounter` هو قابل للقراءة فقط و ليس من الممكن تعديله. +

+
+ + +--- + +58. ماهو الناتج؟ + +```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` + +
الإجابة +

+

+الجواب هو الخيار الأول: A + +العامل `delete` تقوم بإرجاع قيمة boolen و هي `true` عندما تتم عملية المسح بنجاح, خلاف ذلك ستقوم بإرجاع `false`, ولكن المتغيرات المعرفة بالكلمات المفتاحية `var`, `const` أو `let` ليس بالإمكان مسحها بإستخدام العامل `delete`. + +المتغير `name` تم تعريفه باستخدام الكلمة المفتاحية `const`, لهذا فإن عملية مسحه لم تتم بنجاح, وتم إرجاع القيمة `false`, عندما نقوم بضبط المتغير `age` ليساوي القيمة `21` فإننا فعليا نقوم بإضافة خاصية تسمى `age` للglopal object. بإمكانك أن تمسح خصائص من الobjects بنجاح بإستخدام هذه الطريقة , أيضا الglopal objects, لذا فإن `delete age` تقوم بإرجاع `true`. +

+
+ +--- + +59. ماهو الناتج؟ + +```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]` + +
الإجابة +

+

+الجواب هو الخيار الثالث: C + +بإمكاننا إستخراج أو استخلاص القيم من arrays أو من objects عن طريق إستخدام الdestructing, على سبيل المثال: +
+ +```javascript +[a, b] = [1, 2]; +``` + +
+ + +قيمة `a` الآن تساوي `1`, و قيمة `b` الآن تساوي `2`. ماقمنا بفعله حقاً في هذا السؤال هو: +
+ +```javascript +[y] = [1, 2, 3, 4, 5]; +``` + +
+ + +هذا يعني أن قيمة `y` هي مساوية للقيمة الأولى في الarray, والتي هي عبارة عن نوع رقم يساوي `1`, عندما نقوم بطباعة `y` عن طريق الlog, فإن القيمة `1` هي التي يتم إرجاعها. +

+
+ + +--- + +60. ماهو الناتج؟ + +```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 }` + +
الإجابة +

+

+الجواب هو الخيار الثاني: B + +من الممكن دمج الobjects بإستخدام العامل spread `...`. هي تمكنك من إنشاء نسخ من أزواج ال key/value أي أزواج المفاتيح و القيم التي تنتمي الى object معين, و إضافتهم الى object آخر. في هذه الحالة, نحن نقوم بعمل نسخ من الobject `user`, و من ثم إضافتهم الى ال obejct `admin`. ال object `admin` الآن يتضمن نسخ عبارة عن أزواج مفاتيح و قيم, و هذا ما سبب في إعطاء النتيجة `{ admin: true, name: "Lydia", age: 21 }`. +

+
+ + +--- + +61. ماهو الناتج؟ + +```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"]` + +
الإجابة +

+

+الجواب هو الخيار الثاني: B + +مع إستخدام `defineProperty` method, بإمكاننا إضافة خصائص جديدة لobject معين,أو تعديل خصائصه الحالية,. عندما نقوم بإضافة خاصية لobject بإستخدام `defineProperty` method, ف هي بطبيعة الحال ليست enumerable. ال `Object.keys` method تقوم بإرجاع جميع أسامي الخصائص من object معين و التي هي جميعها enumerable, في هذه الحالة `"name"` فقط. + +الخصائص التي تم إضافتها بإستخدام `defineProperty` method هي بطبيعة الحال غير قابلة للتغيير أو التعديل. بإمكانك عمل override بإستخدام الخصائص `writable`, `configurable` و `enumerable`. بهذه الطريقة, ال `defineProperty` method ستعطيك تحكم أكثر بكثير على الخصائص التي قمت بإضافتها الى object معين. +

+
+ + +--- + +62. ماهو الناتج؟ + +```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}"` + +
الإجابة +

+

+الجواب هو الخيار الأول : A + +ال 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. +

+
+ + +--- + +63. ماهو الناتج؟ + +```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` + +
الإجابة +

+

+الجواب هو الخيار الأول : A + +العامل الأحادي `++` يقوم أولا بإرجاع قيمة المعامل, ثم يقوم بزيادة قيمة هذا المعامل. قيمة `num1` تساوي `10`, و بما أن دالة `increaseNumber` أولا تقوم بإرجاع قيمة `num` و التي هي تساوي `10`, و تقوم بزيادة قيمة `num` لاحقاً فقط. + +`num2` تساوي`10`, وبما أننا نقوم بتمرير `num1` ل `increasePassedNumber`. فإن `number` تساوي `10` والتي هي قيمة`num1`. مجدداً, العامل الأحادي `++`, أولاً يقوم بإرجاع قيمة المعامل, و من ثم زيادة قيمة المعامل. قيمة `number` تساوي`10`, إذاً `num2` تساوي `10`. +

+
+ From c3e178e6309e4fbb2b4b7c84eaf45e1809412295 Mon Sep 17 00:00:00 2001 From: Jacob Herper Date: Sun, 30 Jun 2019 11:19:14 +0100 Subject: [PATCH 160/915] Added questions 55-63 and added new languages --- README-de_DE.md | 303 ++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 303 insertions(+) diff --git a/README-de_DE.md b/README-de_DE.md index 51456884..4ff1bf12 100644 --- a/README-de_DE.md +++ b/README-de_DE.md @@ -6,9 +6,12 @@ Von einfach bis fortgeschritten: teste wie gut du JavaScript kennst, frische dei Die Antworten sind unterhalb der Fragen versteckt. Du kannst einfach darauf klicken um die Antworten anzuzeigen. Viel Glück :heart: +### Andere verfügbare Sprachen [English](./README.md)
[Bosanski Jezik](./README-bs_BS.md)
[日本語](./README-ja_JA.md)
+[한국어](./README-ko_KR.md)
+[Português Brasil](./README_pt_BR.md)
[Русский](./README_ru-RU.md)
[Українська мова](./README-ua_UA.md)
[Tiếng Việt](./README-vi.md)
@@ -1653,3 +1656,303 @@ Da wir die Variable `y` aber global erstellt haben ist ihr Wert `10` auch hier v

+ + +--- + +###### 55. Was ist der 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` + +
Antwort +

+ +#### Antwort: A + +Properties von Objekten können mit dem `delete` Keyword entfernt werden, selbst am Prototype. Beim entfernen von Properties am Prototype ist zu beachten, dass diese dann aus der Prototypen-Kette verschwinden. In unserem Fall existiert die `bark` Funktion nicht mehr am Prototype nachdem `delete Dog.prototype.bark` ausgeführt wurde. + +Wenn wir versuchen etwas auszuführen, was keine Funktion ist, wird ein `TypeError` ausgeworfen. In diesem Fall `TypeError: pet.bark is not a function`, da `pet.bark` `undefined` ist. + +

+
+ +--- + +###### 56. Was ist der 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}` + +
Antwort +

+ +#### Antwort: D + +Das `Set` Objekt ist eine Sammlung von _eindeutigen_ Werten: jeder Wert kann nur ein Mal in einem Set vorkommen. + +Wir übergeben `[1, 1, 2, 3, 4]` mit einer doppelten `1`. Da wir keine doppelten Werte in einem Set haben können wird eine `1` entfernt. Das Ergebnis ist `{1, 2, 3, 4}`. + +

+
+ +--- + +###### 57. Was ist der 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` + +
Antwort +

+ +#### Antwort: C + +Ein importiertes Modul ist _read-only_, was bedeutet, dass importierte Module nicht geändert werden können. Nur das Modul, welches diese exportiert kann deren Wert ändern. + +Wenn wir also den Wert von `myCounter` erhöhen bekommen wir den Fehler `myCounter is read-only and cannot be modified`. + +

+
+ +--- + +###### 58. Was ist der 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` + +
Antwort +

+ +#### 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 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. + +

+
+ +--- + +###### 59. Was ist der 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]` + +
Antwort +

+ +#### Antwort: C + +Wir können durch Destructuring Werte aus Arrays oder Properties aus Objekten entpacken. Zum Beispiel: + +```javascript +[a, b] = [1, 2]; +``` + + + +Der Wert von `a` ist jetzt `1` und der Wert von `b` ist jetzt `2`. Was wir in der Frage eigentlich getan haben ist: + +```javascript +[y] = [1, 2, 3, 4, 5]; +``` + + + +Das bedeutet, dass der Wert von `y` gleich des ersten Wertes im Array ist, sprich der Zahl `1` entspricht. Wenn wir `y` loggen bekommen wir `1` ausgegeben. + +

+
+ +--- + +###### 60. Was ist der 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 }` + +
Antwort +

+ +#### Antwort: B + +Es ist möglich Objekte mit dem Spread Operator `...` zu verbinden. Dieser erstellt Kopien der Key/Value Paare eines Objektes und fügt diese dem anderen Objekt hinzu. In diesem Fall wird eine Kopie des `user` Objekts erstellt und dem `admin` Objekt zugewiesen. Das `admin` Objekt beinhaltet nun die kopierten Key/Value Paare, sodass das Ergebnis `{ admin: true, name: "Lydia", age: 21 }` ist. + +

+
+ +--- + +###### 61. Was ist der 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"]` + +
Antwort +

+ +#### Antwort: B + +Mit der `defineProperty` Methode können wir neue Properties zu einem Objekt hinzufügen oder bestehende modifizieren. Wenn wir mit der `defineProperty` Methode Properties einem Objekt hinzufügen, sind diese standardmäßig _nicht zählbar_. Die `Object.keys` Methode gibt alle _zählbaren_ Property Namen eines Objektes zurück, in diesem Fall nur `"name"`. + +Properties, die mit `defineProperty` erstellt wurden sind standardmäßig unveränderbar. Man kann dieses Verhalten mit den `writable`, `configurable` und `enumerable` Properties verändern. Auf diese Art gibt die `defineProperty` Methode mehr Kontrolle über die Properties, die einem Objekt hinzugefügt werden. + +

+
+ +--- + +###### 62. Was ist der 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}"` + +
Antwort +

+ +#### Antwort: A + +Das zweite Argument von `JSON.stringify` ist ein _Replacer_. Der Replacer kann entweder eine Funktion oder ein Array sein und gibt uns Kontrolle darüber, wie die Werte in Strings umgewandelt werden sollen. + +Wenn der Replacer ein _Array_ ist, werden nur die Properties dem JSON String hinzugefügt, die in dem Array aufgeführt sind. In diesem Fall sind das nur `"level"` und `"health"`. `"username"` ist ausgeschlossen. `data` ist jetzt gleich `"{"level":19, "health":90}"`. + +Wenn der Replacer eine _Funktion_ ist, so wird diese Funktion für jede Property im Objekt aufgerufen, die in Strings umgewandelt wird. Der Wert, den die Funktion zurückgibt, ist der Wert der Property, die dem JSON String hinzugefügt wird. Ist der Wert `undefined`, so wird die Property ausgeschlossen. + +

+
+ +--- + +###### 63. Was ist der 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` + +
Antwort +

+ +#### Antwort: A + +Der unäre Operator `++` _gibt zuerst_ den Wert des Operanden aus und _erhöht danach_ den Wert des Operanden. Der Wert `num1` ist `10`, da `increaseNumber` zuerst den Wert von `num1` (`10`) ausgibt und ihn danach erhöht. + +`num2` ist gleich `10`, da wir `num1` `increasePassedNumber` zugewiesen haben. `number` ist gleich `10` (der Wert von `num1`). Der unäre Operator `++` gibt erneut _zuerst_ den Wert des Operanden aus und _erhöht danach_ den Wert. Der Wert von `number` ist `10`, sodass `num2` ebenfalls `10` ist. + +

+
From cf0968aad3ec9ceb67fd1eebec82c17f1d61f8ab Mon Sep 17 00:00:00 2001 From: Lydia Date: Sun, 30 Jun 2019 13:06:48 +0200 Subject: [PATCH 161/915] Rephrase question 19 --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index d684f98f..e64496b7 100644 --- a/README.md +++ b/README.md @@ -602,7 +602,7 @@ getAge(21); #### Answer: C -The spread operator (`...args`.) returns an array with arguments. An array is an object, so `typeof args` returns `"object"` +The rest parameter (`...args`.) lets us "collect" all remaining arguments into an array. An array is an object, so `typeof args` returns `"object"`

From a4294c2835c76f44f7ba51e4c7dedb78a765a092 Mon Sep 17 00:00:00 2001 From: Gabriel Sroka Date: Sun, 30 Jun 2019 07:31:44 -0700 Subject: [PATCH 162/915] Update README.md fixed typo and added link from "June 29th" to question 55 --- README.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 3be1c1f8..3af8e328 100644 --- a/README.md +++ b/README.md @@ -2,7 +2,7 @@ I post daily multiple choice JavaScript questions on my [Instagram](https://www.instagram.com/theavocoder), which I'll also post 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 weekly with new questions. Last update: June 29th +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 weekly with new questions. Last update: June 29th The answers are in the collapsed sections below the questions, simply click on them to expand it. Good luck :heart: @@ -1659,7 +1659,7 @@ However, we created a global variable `y` when setting `y` equal to `10`. This v --- -###### 55. What's the output? +###### 55. What's the output? ```javascript class Dog { @@ -1783,7 +1783,7 @@ console.log(delete age); #### Answer: A -The `delete` operator returns a boolena 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` 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`. From 59771501f77cd7759e8e8c7fdd06d148fd8f74ec Mon Sep 17 00:00:00 2001 From: Gabriel Sroka Date: Sun, 30 Jun 2019 07:34:13 -0700 Subject: [PATCH 163/915] Update README.md 1 more typo --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 3af8e328..9b680d87 100644 --- a/README.md +++ b/README.md @@ -1811,7 +1811,7 @@ console.log(y); #### Answer: C -We can unpack values from arrays or properties from objects through destructing. For example: +We can unpack values from arrays or properties from objects through destructuring. For example: ```javascript [a, b] = [1, 2]; From e933fcbf05359a356a640f93ddc0ce627ea60fc2 Mon Sep 17 00:00:00 2001 From: Sara Ahmed Date: Sun, 30 Jun 2019 18:10:07 +0200 Subject: [PATCH 164/915] Updated the introduction --- README_AR.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/README_AR.md b/README_AR.md index 806ef11f..09078392 100644 --- a/README_AR.md +++ b/README_AR.md @@ -18,12 +18,13 @@ * [中文版本](./README-zh_CN.md) * [Versión en español](./README-ES.md) * [日本語](./README-ja_JA.md) +* [한국어](./README-ko_KR.md) * [Русский](./README_ru-RU.md) * [Western Balkan](./README-bs_BS.md) * [Deutsch](./README-de_DE.md) * [Tiếng Việt](./README-vi.md) * [Українська мова](./README-ua_UA.md) -* [Português Brasil](./README_pt_BR.md) +* [Português Brasil](./README_pt_BR.md) ____________ From 5afff59df695cb91a8c385135404cccfa27350da Mon Sep 17 00:00:00 2001 From: Yoon Seonggwon Date: Mon, 1 Jul 2019 15:10:11 +0900 Subject: [PATCH 165/915] Fix typos Signed-off-by: Yoon Seonggwon --- README-ko_KR.md | 188 ++++++++++++++++++++++++------------------------ 1 file changed, 94 insertions(+), 94 deletions(-) diff --git a/README-ko_KR.md b/README-ko_KR.md index 7efc2bf9..6214a0d7 100644 --- a/README-ko_KR.md +++ b/README-ko_KR.md @@ -42,9 +42,9 @@ sayHi(); #### 정답: D -함수 내에서, 우선 `var`키워드를 사용해 `name`변수를 선언해요. 이것은 변수가 정의되어 있는 행에 실제로 도달할 때까지, `undefined`의 기본값으로 호이스팅 되(생성단계에 메모리 공간이 설정)는 것을 의미해요. `name` 변수를 출력하려는 줄에서 아직 변수를 정의하고 있지 않기 때문에, `undefined`값을 유지하고 있어요. +함수 내에서, 우선 `var` 키워드를 사용해 `name` 변수를 선언해요. 이것은 변수가 정의된 행에 실제로 도달할 때까지, `undefined`의 기본값으로 호이스팅 되(생성단계에 메모리 공간이 설정)는 것을 의미해요. `name` 변수를 출력하려는 줄에서 아직 변수를 정의하고 있지 않기 때문에, `undefined` 값을 유지하고 있어요. -`let`키워드(그리고 `const`)를 가지는 변수들은, `var`와는 달리, 호이스팅되지만 초기화되지 않아요. 그것들을 선언(초기화)하는 줄 전에는 접근할 수 없어요. 이것은 "일시적 사각지대"라고 불려요. 선언되기 전 변수에 접근하려고 하면, JavaScript는 `ReferenceError`를 던져요. +`let` 키워드(그리고 `const`)를 가지는 변수들은, `var`와는 달리, 호이스팅 되지만 초기화 되지 않아요. 그것들을 선언(초기화)하는 줄 전에는 접근할 수 없어요. 이것은 "일시적 사각지대"라고 불려요. 선언되기 전 변수에 접근하려고 하면, JavaScript는 `ReferenceError`를 던져요.

@@ -72,9 +72,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`는 새로운 값을 가지고, 각각의 값은 루프 안쪽 범위에 있어요.

@@ -106,9 +106,9 @@ console.log(shape.perimeter()); #### 정답: B -`diameter`의 값은 정규 함수인 반면, `perimeter`의 값은 화살표 함수라는 점을 유의하세요. +`diameter`의 값은 정규 함수지만, `perimeter`의 값은 화살표 함수라는 점을 유의하세요. -화살표 함수에서, `this`키워드는 통상적인 함수와는 다르게 현재 주위의 범위를 참조해요! 이것은 `perimeter`를 부르면, shape 객체가 아닌 그 주위의 범위(예를 들면 window)를 참조하는 것을 의미해요. +화살표 함수에서, `this` 키워드는 통상적인 함수와는 다르게 현재 주위의 범위를 참조해요! 이것은 `perimeter`를 부르면, shape 객체가 아닌 그 주위의 범위(예를 들면 window)를 참조하는 것을 의미해요. 그 객체에는 `radius`라는 값은 없기 때문에 `undefined`를 리턴해요. @@ -133,9 +133,9 @@ console.log(shape.perimeter()); #### 정답: A -단항 더하기는 피연산자를 숫자로 변환하려 시도 해요. `true`는 `1`이고, `false`은 `0`이에요. +단항 더하기는 피연산자를 숫자로 변환하려 시도해요. `true`는 `1`이고, `false`는 `0`이에요. -문자열 `'Lydia'`는 참 같은 값이에요. 실제로는, "이 참 같은 값이 거짓 같은 값인가?"를 물어보고 있어요. 이것은 `false`을 리턴해요. +문자열 `'Lydia'`는 참 같은 값이에요. 실제로는, "이 참 같은 값이 거짓 같은 값인가?"를 물어보고 있어요. 이것은 `false`를 리턴해요.

@@ -155,9 +155,9 @@ const mouse = { }; ``` -- A: `mouse.bird.size` 은 유효하지 않아요 -- B: `mouse[bird.size]` 은 유효하지 않아요 -- C: `mouse[bird["size"]]` 은 유효하지 않아요 +- A: `mouse.bird.size` 는 유효하지 않아요 +- B: `mouse[bird.size]` 는 유효하지 않아요 +- C: `mouse[bird["size"]]` 는 유효하지 않아요 - D: 이 모든 것들은 유효해요.
정답 @@ -167,7 +167,7 @@ const mouse = { JavaScript에서, 모든 객체 키는 문자열이에요 (심볼이 아닌 한). 비록 그것을 문자열 _형_ 으로 입력하지 않아도, 항상 내부적으로 문자열로 변환돼요. -JavaScript는 문장을 해석(또는 박스 해제)해요. 대괄호 표기를 사용하면, 첫 번째 열린 대괄호 `[`를 보고 닫힌 대괄호 `]`를 찾을 때까지 진행해요. 그때에 만, 그 문장을 평가할 거예요. +JavaScript는 문장을 해석(또는 박스 해제)해요. 대괄호 표기를 사용하면, 첫 번째 열린 대괄호 `[`를 보고 닫힌 대괄호 `]`를 찾을 때까지 진행해요. 그때에만, 그 문장을 평가할 거예요. `mouse[bird.size]`: 먼저 `"small"`인 `bird.size`를 평가해요. `mouse["small"]` 은 `true`를 리턴해요. @@ -200,7 +200,7 @@ console.log(d.greeting); #### 정답: A -JavaScript에서, 모든 객체는 서로 동일하게 설정하면 _참조_ 에 따라 상호작용 해요. +JavaScript에서, 모든 객체는 서로 동일하게 설정하면 _참조_ 에 따라 상호작용해요. 우선 변수 `c`는 객체에 대한 값을 유지해요. 그 후, `c`와 동일한 객체 참조를 `d`에 할당해요. @@ -237,7 +237,7 @@ console.log(b === c); `new Number()`는, 내장 함수 생성자예요. 숫자처럼 보이지만, 실제로는 숫자가 아니에요: 많은 추가 특성이 있고 그것은 객체예요. -`==`연산자를 사용할 때, 그건 같은 _값_ 을 가지고 있는지 여부만 확인해요. 그것들은 모두`3`의 값을 가지고 있으므로, `true`를 리턴해요. +`==`연산자를 사용할 때, 그건 같은 _값_ 을 가졌는지 여부만 확인해요. 그것들은 모두`3`의 값을 가지고 있으므로, `true`를 리턴해요. 그러나, `===`연산자를 사용할 때, 값 _과_ 형 둘 다 같아야 해요. 이건 아니에요: `new Number()`는 숫자가 아니에요. **객체**에요. 그래서 둘 다 `false`를 리턴해요. @@ -298,7 +298,7 @@ console.log(greetign); #### 정답: A -역 객체에 빈 객체를 방금 만들었기 때문에, 객체는 출력되요. `greeting`을 `greettign`으로 잘못 입력했을 경우, JS 인터프리터는 실제로 이것을 `global.greettign = {}` (또는 브라우저의 `window.greetign = {}`) 라고 간주해요. +역 객체에 빈 객체를 방금 만들었기 때문에, 객체는 출력돼요. `greeting`을 `greettign`으로 잘못 입력했을 경우, JS 인터프리터는 실제로 이것을 `global.greettign = {}` (또는 브라우저의 `window.greetign = {}`) 라고 간주해요. 이것을 피하기 위해서, `"use strict"`를 사용할 수 있어요. 이렇게 하면 변수를 어떤 것과 동일하게 설정하기 전에 변수를 선언했는지 확인할 수 있어요. @@ -370,7 +370,7 @@ Person.prototype.getFullName = function() { }; ``` -`member.getFullName()`은 작동해요. 이것은 왜 유익할까요? 이 메소드를 생성자 자체에 추가했다고 할게요. 아마도 모든 `Person` 인스턴스는 이 메소드를 필요로 하지 않을 수도 있어요. 그 경우 그들은 계속해서 속성을 갖고 있기 때문에, 각각의 인스턴스를 위한 메모리 공간을 소비하게 되어, 많은 메모리 공간을 낭비하게 될 거예요. 대신에, 프로토타입을 추가하는 것만으로, 메모리의 한 지점을 가지지만, 모든 것들은 그것에 접근 할 수 있어요. +`member.getFullName()`은 작동해요. 이것은 왜 유익할까요? 이 메소드를 생성자 자체에 추가했다고 할게요. 아마도 모든 `Person` 인스턴스는 이 메소드가 필요하지 않을 수도 있어요. 그 경우 그들은 계속해서 속성을 갖고 있기 때문에, 각각의 인스턴스를 위한 메모리 공간을 소비하게 되어, 많은 메모리 공간을 낭비하게 될 거예요. 대신에, 프로토타입을 추가하는 것만으로, 메모리의 한 지점을 가지지만, 모든 것들은 그것에 접근할 수 있어요.

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

@@ -507,7 +507,7 @@ console.log(number); 1. 값 증가 (number는 지금 `2`이에요) 2. 값 리턴 (이것은 `2`을 리턴해요) -이건 `0 2 2`을 리턴해요. +이건 `0 2 2`를 리턴해요.

@@ -538,7 +538,7 @@ getPersonInfo`${person} is ${age} years old`; #### 정답: B -태그드 템플릿 리터럴을 사용하는 경우, 첫 번재 인수의 값은 항상 문자열 값의 배열이에요. 나머지 인수는 식을 통과한 값을 얻어요. +태그드 템플릿 리터럴을 사용하는 경우, 첫 번째 인수의 값은 항상 문자열 값의 배열이에요. 나머지 인수는 식을 통과한 값을 얻어요.

@@ -570,9 +570,9 @@ checkAge({ age: 18 }); #### 정답: C -동등성을 테스트할 때, 원시형은 그 _값_ 에 따라 비교되며, 객체는 그들의 _참조_ 에 따라 비교돼요. JavaScript 객체가 메모리 내의 같은 장소를 참조하고 있는지 여부를 확인해요. +동등성을 테스트할 때, 원시형은 그 _값_ 에 따라 비교되며, 객체는 그들의 _참조_ 에 따라 비교돼요. JavaScript 객체가 메모리 내의 같은 장소를 참조하고 있는지를 확인해요. -비교하고 있는 두개의 객체는 그것이 없어요: 파라미터로 전달된 객체와 동등성을 확인하기 위해 사용한 객체는 메모리 내의 다른 장소를 참조해요. +비교하고 있는 두 개의 객체는 그것이 없어요: 파라미터로 전달된 객체와 동등성을 확인하기 위해 사용한 객체는 메모리 내의 다른 장소를 참조해요. 이것이 `{ age: 18 } === { age: 18 }` 그리고 `{ age: 18 } == { age: 18 }` 두 개 다 `false`를 리턴하는 이유죠. @@ -630,7 +630,7 @@ getAge(); #### 정답: C -`"use strict"`을 사용하면, 실수로 전역 변수를 선언하지 않게 할 수 있어요. `age`이라는 변수를 선언한 적이 전혀 없고, `"use strict"`을 사용하고 있으므로, 참조 에러를 던지게 될 거에요. 만약 `"use strict"`을 사용하지 않았다면, 이건 작동할 거에요, `age` 속성이 전역 객체에 추가된 것이기 때문이죠. +`"use strict"`을 사용하면, 실수로 전역 변수를 선언하지 않게 할 수 있어요. `age`라는 변수를 선언한 적이 전혀 없고, `"use strict"`을 사용하고 있으므로, 참조 에러를 던지게 될 거예요. 만약 `"use strict"`을 사용하지 않았다면, 이건 작동할 거예요, `age` 속성이 전역 객체에 추가된 것이기 때문이죠.

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

@@ -668,7 +668,7 @@ sessionStorage.setItem("cool_secret", 123); - A: 영원히, 데이터는 사라지지 않아요. - B: 사용자가 탭을 닫을 때. -- C: 사용자가 탭 뿐만 아니라, 브라우저 전체를 닫을 때. +- C: 사용자가 탭뿐만 아니라, 브라우저 전체를 닫을 때. - D: 사용자가 자신의 컴퓨터를 종료시켰을 때.
정답 @@ -678,7 +678,7 @@ sessionStorage.setItem("cool_secret", 123); `sessionStorage`에 저장된 데이터는 _탭_ 을 닫은 후에 삭제돼요. -만약 `localStorage`를 사용했다면, 예를 들어 `localStorage.clear()`를 호출하지 않는 한, 데이터는 영원할 거에요. +만약 `localStorage`를 사용했다면, 예를 들어 `localStorage.clear()`를 호출하지 않는 한, 데이터는 영원할 거예요.

@@ -704,7 +704,7 @@ console.log(num); #### 정답: B -`var`키워드를 사용하면, 같은 이름으로 복수의 변수를 선언할 수 있어요. 변수는 최신의 값을 유지해요. +`var` 키워드를 사용하면, 같은 이름으로 복수의 변수를 선언할 수 있어요. 변수는 최신의 값을 유지해요. 블록 스코프의 `let` 또는 `const`에서는 할 수 없어요. @@ -737,7 +737,7 @@ set.has(1); 모든 객체 키는(심볼 제외) 문자열로 직접 입력하지 않아도, 내부적으로는 문자열이에요. 이것이 `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`를 리턴해요.

@@ -805,7 +805,7 @@ for (let i = 1; i < 5; i++) { #### 정답: C -`continue` 표현식은 특정 조건이 `true`를 리턴하면 반복 처리를 건너뛰어요. +`continue` 표현 식은 특정 조건이 `true`를 리턴하면 반복 처리를 건너뛰어요.

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

@@ -864,11 +864,11 @@ console.log(a[b]); #### 정답: B -객체 키는 자동으로 문자열로 변환돼요. 객체 `a`의 키 값으로 `123`를 세팅하려고 해요. +객체 키는 자동으로 문자열로 변환돼요. 객체 `a`의 키 값으로 `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`을 리턴해요.

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

@@ -1007,7 +1007,7 @@ sayHi.bind(person, 21); #### 정답: D -두 개 모두, `this`키워드를 참조하고자 하는 객체로 보낼 수 있어요. 그러나, `.call`은 _즉시 실행돼요_! +두 개 모두, `this` 키워드를 참조하고자 하는 객체로 보낼 수 있어요. 그러나, `.call`은 _즉시 실행돼요_! `.bind.`는 함수의 _복사본_ 을 리턴하지만, 바인딩 콘텍스트죠! 이건 즉시 실행되지 않아요. @@ -1075,7 +1075,7 @@ undefined; - `''` (빈 문자열) - `false` -`new Number` 그리고 `new Boolean`와 같은 생성자 함수는 참 같은 값이에요. +`new Number` 그리고 `new Boolean`과 같은 생성자 함수는 참 같은 값이에요.

@@ -1098,7 +1098,7 @@ console.log(typeof typeof 1); #### 정답: B -`typeof 1` 은 `"number"`을 리턴해요. +`typeof 1` 은 `"number"`를 리턴해요. `typeof "number"`은 `"string"`을 리턴해요.

@@ -1124,7 +1124,7 @@ console.log(numbers); #### 정답: C -배열의 길이를 초과한 값을 배열의 요소로 설정하고자 할 때, JavaScript는 "empty slots"이라고 불리는 것을 생성해요. 이것은 실제로 `undefined`의 값을 가지고 있지만, 다음과 같은 것을 보게 될 거에요: +배열의 길이를 초과한 값을 배열의 요소로 설정하고자 할 때, JavaScript는 "empty slots"라고 불리는 것을 생성해요. 이것은 실제로 `undefined`의 값을 가지고 있지만, 다음과 같은 것을 보게 될 거예요: `[1, 2, 3, 7 x empty, 11]` @@ -1166,7 +1166,7 @@ depending on where you run it (it's different for every browser, node, etc.) 후에, 블록-스코프 변수는 `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`를 리턴해요.

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

@@ -1217,7 +1217,7 @@ 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]`을 얻게 돼요. @@ -1244,9 +1244,9 @@ JavaScript는 원시형과 객체만 가지고 있어요. #### 정답: B -`null`은 거짓 같은 값이에요. `!null`은 `true`를 리턴해요. `!true`은 `false`를 리턴해요. +`null`은 거짓 같은 값이에요. `!null`은 `true`를 리턴해요. `!true`는 `false`를 리턴해요. -`""` 은 거짓 같은 값이에요. `!""`은 `true`를 리턴해요. `!true`은 `false`를 리턴해요. +`""` 은 거짓 같은 값이에요. `!""`은 `true`를 리턴해요. `!true`는 `false`를 리턴해요. `1`은 참 같은 값이에요. `!1`은 `false`를 리턴해요. `!false`는`true`를 리턴해요. @@ -1327,7 +1327,7 @@ console.log(gen.next().value); 보통의 함수는 호출 후에 중단할 수 없어요. 하지만, 제너레이터 함수는 중간에 "멈췄다가", 나중에 중단된 부분부터 계속할 수 있어요. 제너레이터 함수는 `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`이에요. @@ -1360,7 +1360,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'`의 값을 유지하고 출력돼요.

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

@@ -1429,7 +1429,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`로 출력돼요.

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

@@ -1479,9 +1479,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`의 값을 유지해요.

@@ -1507,9 +1507,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`를 리턴해요.

@@ -1542,11 +1542,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"`에요.

@@ -1582,7 +1582,7 @@ 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'`예요. @@ -1613,7 +1613,7 @@ console.log(myCar.make); #### 정답: B -속성을 리턴할 때, 속성 값은 생성자에 설정한 값이 아닌, _리턴된_ 값과 같아요. `"Maserati"` 문자열을 리턴하기 때문에, `myCar.make`는 `"Maserati"`에요. +속성을 리턴할 때, 속성값은 생성자에 설정한 값이 아닌, _리턴된_ 값과 같아요. `"Maserati"` 문자열을 리턴하기 때문에, `myCar.make`는 `"Maserati"`에요.

@@ -1650,7 +1650,7 @@ let x = y; `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"`을 리턴해요. @@ -1686,14 +1686,14 @@ pet.bark(); - C: `"Woof I am Mara"`, `undefined` - D: `TypeError`, `TypeError` -
Answer +
정답

-#### Answer: 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`예요. +함수가 아닌 것을 호출하려고 할 때, `TypeError`가 던져져요. 이 경우 `pet.bark`는 `undefined`이기 때문에, `TypeError: pet.bark is not a function`예요.

@@ -1713,12 +1713,12 @@ console.log(set); - C: `{1, 1, 2, 3, 4}` - D: `{1, 2, 3, 4}` -
Answer +
정답

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

Answer +
정답

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

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

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

@@ -1806,10 +1806,10 @@ console.log(y); - C: `1` - D: `[1]` -
Answer +
정답

-#### Answer: C +#### 정답: C 구조 분해 할당을 통해 객체의 배열 또는 속성들로부터 변수를 해체할 수 있어요. 예를 들어: @@ -1827,7 +1827,7 @@ console.log(y); -이것은 `y`의 값은 숫자 `1`인 배열의 첫번째 값과 같다는 것을 의미하죠. `y`를 출력하면 `1`이 리턴돼요. +이것은 `y`의 값은 숫자 `1`인 배열의 첫 번째 값과 같다는 것을 의미하죠. `y`를 출력하면 `1`이 리턴돼요.

@@ -1848,12 +1848,12 @@ console.log(admin); - C: `{ admin: true, user: ["Lydia", 21] }` - D: `{ admin: true }` -
Answer +
정답

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

@@ -1876,14 +1876,14 @@ console.log(Object.keys(person)); - C: `{ name: "Lydia"}`, `["name", "age"]` - D: `{ name: "Lydia"}`, `["age"]` -
Answer +
정답

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

@@ -1908,16 +1908,16 @@ console.log(data); - C: `"["level", "health"]"` - D: `"{"username": "lydiahallie", "level":19, "health":90}"` -
Answer +
정답

-#### Answer: A +#### 정답: 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 문자열로부터 제외돼요.

@@ -1944,12 +1944,12 @@ console.log(num2); - C: `11`, `11` - D: `11`, `12` -
Answer +
정답

-#### Answer: 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`이죠. From b0255d8af25c1af8ad182e9154b277180353f1ef Mon Sep 17 00:00:00 2001 From: shooterRao Date: Mon, 1 Jul 2019 23:10:34 +0800 Subject: [PATCH 166/915] Fix question 14 in README-zh_CN.md --- README-zh_CN.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README-zh_CN.md b/README-zh_CN.md index cb26343d..21740dc3 100644 --- a/README-zh_CN.md +++ b/README-zh_CN.md @@ -432,7 +432,7 @@ console.log(sarah) #### 答案: B -除了**基本对象**(base object),所有对象都有原型。基本对象可以访问一些方法和属性,比如 `.tostring`。这就是为什么你可以使用内置的 JavaScript 方法!所有这些方法在原型上都是可用的。虽然 JavaScript 不能直接在对象上找到这些方法,但 JavaScript 会沿着原型链找到它们,以便于你使用。 +除了**基本对象**(base object),所有对象都有原型。基本对象可以访问一些方法和属性,比如 `.toString`。这就是为什么你可以使用内置的 JavaScript 方法!所有这些方法在原型上都是可用的。虽然 JavaScript 不能直接在对象上找到这些方法,但 JavaScript 会沿着原型链找到它们,以便于你使用。

From d55f9f4b6cc822842585a67b70a866db17477e27 Mon Sep 17 00:00:00 2001 From: Jacob Herper Date: Tue, 2 Jul 2019 15:44:23 +0100 Subject: [PATCH 167/915] Languages ordered This is a proposal to bring the languages into alphabetical order and to standardise their format (all in their own language). --- README.md | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/README.md b/README.md index 500208b2..585fbae3 100644 --- a/README.md +++ b/README.md @@ -9,18 +9,18 @@ The answers are in the collapsed sections below the questions, simply click on t List of available languages: * [English](./README.md) -* [中文版本](./README-zh_CN.md) -* [Versión en español](./README-ES.md) +* [العربية](./README_AR.md) +* [اللغة العامية - Egyptian Arabic](./README_ar-EG.md) +* [Bosanski](./README-bs_BS.md) +* [Deutsch](./README-de_DE.md) +* [Español](./README-ES.md) * [日本語](./README-ja_JA.md) * [한국어](./README-ko_KR.md) +* [Português Brasil](./README_pt_BR.md) * [Русский](./README_ru-RU.md) -* [Western Balkan](./README-bs_BS.md) -* [Deutsch](./README-de_DE.md) -* [Tiếng Việt](./README-vi.md) * [Українська мова](./README-ua_UA.md) -* [Português Brasil](./README_pt_BR.md) -* [العربية](./README_AR.md) -* [اللغة العامية - Egyptian Arabic](./README_ar-EG.md) +* [Tiếng Việt](./README-vi.md) +* [中文版本](./README-zh_CN.md) --- From 7fee122eb695b8511fcfb82cc893ebd159dce4ac Mon Sep 17 00:00:00 2001 From: Alexander Ivanov Date: Wed, 3 Jul 2019 20:46:11 +0300 Subject: [PATCH 168/915] Russian. Updates 06/19 --- README_ru-RU.md | 323 ++++++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 315 insertions(+), 8 deletions(-) diff --git a/README_ru-RU.md b/README_ru-RU.md index f0ab0df3..b8f8ab31 100644 --- a/README_ru-RU.md +++ b/README_ru-RU.md @@ -6,12 +6,21 @@ Ответы находятся в свернутой секции ниже вопросов. Просто нажми на "Ответ", чтобы развернуть. Удачи! :heart: -[中文版本](./README-zh_CN.md) -[Western Balkan](./README-bs_BS.md) -[Deutsch](./README-de_DE.md) -[Tiếng Việt](./README-vi.md) -[日本語](./README-ja_JA.md) -[Українська мова](./README-ua_UA.md) + +List of available languages: +* [English](./README.md) +* [中文版本](./README-zh_CN.md) +* [Versión en español](./README-ES.md) +* [日本語](./README-ja_JA.md) +* [한국어](./README-ko_KR.md) +* [Русский](./README_ru-RU.md) +* [Western Balkan](./README-bs_BS.md) +* [Deutsch](./README-de_DE.md) +* [Tiếng Việt](./README-vi.md) +* [Українська мова](./README-ua_UA.md) +* [Português Brasil](./README_pt_BR.md) +* [العربية](./README_AR.md) +* [اللغة العامية - Egyptian Arabic](./README_ar-EG.md --- @@ -1037,7 +1046,6 @@ typeof sayHi(); Функция `sayHi` возвращает значение, возвращаемое из немедленно вызываемого функционального выражения (IIFE). Результатом является `0` типа `"number"`. Для информации: в JS 7 встроенных типов: `null`, `undefined`, `boolean`, `number`, `string`, `object`, и `symbol`. `"function"` не является отдельным типом, т.к. функции являются объектами типа `"object"`. -

@@ -1652,4 +1660,303 @@ let x = y; Однако мы создали глобальную переменную `y`, установив `y` равным `10`. Это значение доступно в любом месте нашего кода. `y` определен и содержит значение типа `"number"`. `console.log(typeof y)` возвращает `"number"`.

-
\ No newline at end of file +
+ +--- + +###### 55. Какой будет вывод? + +```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` + +
Ответ +

+ +#### Ответ: A + +Мы можем удалить свойства из объектов, используя ключевое слово `delete`, также в прототипе. Удаляя свойство в прототипе, оно больше не доступно в цепочке прототипов. В этом случае функция `bark` больше не доступна в прототипе после`delete Dog.prototype.bark`, но мы все еще пытаемся получить к ней доступ. + +Когда мы пытаемся вызвать что-то, что не является функцией, выдается `TypeError`. В этом случае `TypeError: pet.bark не является функцией`, поскольку` pet.bark` является `undefined`. + +

+
+ +--- + +###### 56. Какой будет вывод? + +```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}` + +
Ответ +

+ +#### Ответ: D + +Объект `Set` является коллекцией _unique_ значений: значение может появляться только один раз в наборе. + +Мы передали последовательность `[1, 1, 2, 3, 4]` с повторяющимся значением `1`. Поскольку в наборе не может быть двух одинаковых значений, одно из них удаляется. Это приводит к `{1, 2, 3, 4}`. + +

+
+ +--- + +###### 57. Какой будет вывод? + +```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` + +
Ответ +

+ +#### Ответ: C + +Импортированный модуль является _read-only_: вы не можете изменить импортированный модуль. Только модуль, который их экспортирует, может изменить его значение. + +Когда мы пытаемся увеличить значение `myCounter`, выдается ошибка: `myCounter` доступен только для чтения и не может быть изменен. + +

+
+ +--- + +###### 58. Какой будет вывод? + +```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` + +
Ответ +

+ +#### Ответ: A + +Оператор `delete` возвращает логическое значение: `true` при успешном удалении, иначе он вернет `false`. Однако переменные, объявленные с ключевым словом `var`,` const` или `let`, не могут быть удалены с помощью оператора` delete`. + +Переменная `name` была объявлена ​​с ключевым словом `const`, поэтому ее удаление не было успешным: возвращается `false`. Когда мы устанавливаем `age` равным `21`, мы фактически добавляем свойство с именем `age` к глобальному объекту. Вы можете успешно удалить свойства из объектов, в том числе из глобального объекта, поэтому `delete age` возвращает `true`. + +

+
+ +--- + +###### 59. Какой будет вывод? + +```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]` + +
Ответ +

+ +#### Ответ: C + +Мы можем распаковать значения из массивов или свойств из объектов путем деструктуризации. Например: + +```javascript +[a, b] = [1, 2]; +``` + + + +Значение `a` теперь равно `1`, а значение `b` теперь равно `2`. Что мы на самом деле сделали в этом вопросе, так это: + +```javascript +[y] = [1, 2, 3, 4, 5]; +``` + + + +Это означает, что значение `y` равно первому значению в массиве, которое является числом` 1`. Когда мы регистрируем `y`, возвращается `1`. + +

+
+ +--- + +###### 60. Какой будет вывод? + +```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 }` + +
Ответ +

+ +#### Ответ: B + +Можно комбинировать объекты с помощью оператора распространения `...`. Это позволяет создавать копии пар ключ/значение одного объекта и добавлять их в другой объект. В этом случае мы создаем копии объекта `user` и добавляем их в объект `admin`. Объект `admin` теперь содержит скопированные пары ключ/значение, что приводит к `{admin: true, name: "Lydia", age: 21}`. + +

+
+ +--- + +###### 61. Какой будет вывод? + +```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"]` + +
Ответ +

+ +#### Ответ: B + +С помощью метода `defineProperty` мы можем добавлять новые свойства к объекту или изменять существующие. Когда мы добавляем свойство к объекту с помощью метода `defineProperty`, они по умолчанию _не перечисляемые_. Метод `Object.keys` возвращает все имена _enumerable_ свойств объекта, в данном случае только `"name"`. + +Свойства, добавленные с помощью метода `defineProperty`, по умолчанию неизменны. Вы можете переопределить это поведение, используя свойства `writable`, `configurable` и `enumerable`. Таким образом, метод `defineProperty` дает вам гораздо больший контроль над свойствами, которые вы добавляете к объекту. + +

+
+ +--- + +###### 62. Какой будет вывод? + +```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}"` + +
Ответ +

+ +#### Ответ: A + +Второй аргумент `JSON.stringify` - это _replacer_. Заменитель может быть либо функцией, либо массивом, и позволяет вам контролировать, что и как должны быть преобразованы в значения. + +Если заменитель является _array_, только свойства, имена которых включены в массив, будут добавлены в строку JSON. В этом случае включаются только свойства с именами `"level"` и `"health"`, `"username"` исключается. `data` теперь равен `"{"level":19, "health":90}"`. + +Если заменитель является _function_, эта функция вызывается для каждого свойства объекта, который вы преобразуете. Значение, возвращаемое из этой функции, будет значением свойства при добавлении в строку JSON. Если значение равно undefined, это свойство исключается из строки JSON. + +

+
+ +--- + +###### 63. Какой будет вывод? + +```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` + +
Ответ +

+ +#### Ответ: A + +Унарный оператор `++` _first возвращает_ значение операнда, _then приращивает_ значение операнда. Значение `num1` равно `10`, так как функция увеличений вначале возвращает значение `num`, которое равно `10`, и только затем увеличивает значение `num`. + +`num2` - это `10`, так как мы передали `num1` в `incpasePassedNumber`. `number` равно `10` (значение `num1`. Опять же, унарный оператор `++` _first возвращает_ значение операнда, _then увеличивает значение операнда. Значение `number` равно `10`, поэтому `num2` равно `10`. + +

+
From 4cd8bad730ed16681e93d9b1b21488746f8b0c1c Mon Sep 17 00:00:00 2001 From: Alexander Ivanov Date: Wed, 3 Jul 2019 20:49:38 +0300 Subject: [PATCH 169/915] Translate line 10 --- README_ru-RU.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README_ru-RU.md b/README_ru-RU.md index b8f8ab31..9ef823ee 100644 --- a/README_ru-RU.md +++ b/README_ru-RU.md @@ -7,7 +7,7 @@ Ответы находятся в свернутой секции ниже вопросов. Просто нажми на "Ответ", чтобы развернуть. Удачи! :heart: -List of available languages: +Список доступных переводов: * [English](./README.md) * [中文版本](./README-zh_CN.md) * [Versión en español](./README-ES.md) From ff2c9bfb39b1add8865e014586bf8def11c12b23 Mon Sep 17 00:00:00 2001 From: Alexander Ivanov Date: Wed, 3 Jul 2019 20:50:48 +0300 Subject: [PATCH 170/915] Typo --- README_ru-RU.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README_ru-RU.md b/README_ru-RU.md index 9ef823ee..df536c26 100644 --- a/README_ru-RU.md +++ b/README_ru-RU.md @@ -20,7 +20,7 @@ * [Українська мова](./README-ua_UA.md) * [Português Brasil](./README_pt_BR.md) * [العربية](./README_AR.md) -* [اللغة العامية - Egyptian Arabic](./README_ar-EG.md +* [اللغة العامية - Egyptian Arabic](./README_ar-EG.md) --- From 6587fe081f616cc1615596d43dc69c841a39c1b2 Mon Sep 17 00:00:00 2001 From: TuanTV Date: Thu, 4 Jul 2019 18:29:12 +0700 Subject: [PATCH 171/915] add question to vietname and translate title --- README-vi.md | 657 +++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 657 insertions(+) diff --git a/README-vi.md b/README-vi.md index 55e61bad..db91448a 100644 --- a/README-vi.md +++ b/README-vi.md @@ -1291,3 +1291,660 @@ String là một _iterable_. Thế nên _spread operator_ sẽ map toàn bộ c

+ +--- + +###### 44. Ouput là gì? + +```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 và 10, 20` + +
Đáp án +

+ +#### Đáp án: 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. Giá trị trả về là gì? + +```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 án +

+ +#### Đáp án: 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. Ouput là gì? + +```javascript +let person = { name: "Lydia" }; +const members = [person]; +person = null; + +console.log(members); +``` + +- A: `null` +- B: `[null]` +- C: `[{}]` +- D: `[{ name: "Lydia" }]` + +
Đáp án +

+ +#### Đáp án: 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. Ouput là gì? + +```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 án +

+ +#### Đáp án: 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. Ouput là gì? + +```javascript +console.log(3 + 4 + "5"); +``` + +- A: `"345"` +- B: `"75"` +- C: `12` +- D: `"12"` + +
Đáp án +

+ +#### Đáp án: 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` + +
Đáp án +

+ +#### Đáp án: 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. What's the 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 ]` + +
Đáp án +

+ +#### Đáp án: 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. Ouput là gì? + +```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 án +

+ +#### Đáp án: 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. Ouput là gì? + +```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 án +

+ +#### Đáp án: 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. Ouput là gì? + +```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 án +

+ +#### Đáp án: 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. Ouput là gì? + +```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 án +

+ +#### Đáp án: 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 (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. Ouput là gì? + +```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 án +

+ +#### Đáp án: 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. Ouput là gì? + +```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 án +

+ +#### Đáp án: 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. Ouput là gì? + +```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 án +

+ +#### Đáp án: 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. Ouput là gì? + +```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 án +

+ +#### Đáp án: 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. Ouput là gì? + +```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 án +

+ +#### Đáp án: 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. Ouput là gì? + +```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 án +

+ +#### Đáp án: 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. Ouput là gì? + +```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 án +

+ +#### Đáp án: 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. Ouput là gì? + +```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 án +

+ +#### Đáp án: 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 properties which names are included in the array will be added to the JSON string. In this case, only the properies 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. Ouput là gì? + +```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 án +

+ +#### Đáp án: 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`. + +

+
\ No newline at end of file From 8b2bea76c2ded8e0ae25edb9dd5d7f8013c5792b Mon Sep 17 00:00:00 2001 From: TuanTV Date: Thu, 4 Jul 2019 18:32:25 +0700 Subject: [PATCH 172/915] add list language other --- README-vi.md | 16 ++++++++++++++-- 1 file changed, 14 insertions(+), 2 deletions(-) diff --git a/README-vi.md b/README-vi.md index db91448a..bcb536b5 100644 --- a/README-vi.md +++ b/README-vi.md @@ -6,8 +6,20 @@ 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: -[English Version](./README.md) -[Українська мова](./README-ua_UA.md) +Danh sách các ngôn ngữ khác: +* [English](./README.md) +* [中文版本](./README-zh_CN.md) +* [Versión en español](./README-ES.md) +* [日本語](./README-ja_JA.md) +* [한국어](./README-ko_KR.md) +* [Русский](./README_ru-RU.md) +* [Western Balkan](./README-bs_BS.md) +* [Deutsch](./README-de_DE.md) +* [Tiếng Việt](./README-vi.md) +* [Українська мова](./README-ua_UA.md) +* [Português Brasil](./README_pt_BR.md) +* [العربية](./README_AR.md) +* [اللغة العامية - Egyptian Arabic](./README_ar-EG.md) --- From 7265ebaaafee394aa68d1bad3299bd3794476106 Mon Sep 17 00:00:00 2001 From: Alexander Ivanov Date: Thu, 4 Jul 2019 14:45:53 +0300 Subject: [PATCH 173/915] Fix #139 --- README-zh_CN.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README-zh_CN.md b/README-zh_CN.md index 21740dc3..92e68124 100644 --- a/README-zh_CN.md +++ b/README-zh_CN.md @@ -110,7 +110,7 @@ shape.perimeter() ###### 4. 输出是什么? ```javascript -;+true ++true !'Lydia' ``` From 859f7839cc91e0b1ffcf732a7e4ddaac77fde31c Mon Sep 17 00:00:00 2001 From: Alexander Ivanov Date: Thu, 4 Jul 2019 15:03:57 +0300 Subject: [PATCH 174/915] Add as all Signed-off-by: Alexander Ivanov --- README-zh_CN.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README-zh_CN.md b/README-zh_CN.md index 92e68124..23ae293b 100644 --- a/README-zh_CN.md +++ b/README-zh_CN.md @@ -110,8 +110,8 @@ shape.perimeter() ###### 4. 输出是什么? ```javascript -+true -!'Lydia' ++true; +!"Lydia"; ``` - A: `1` and `false` From 986220b745f1cf0fe8177a3875abf8cff4b719c7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E8=B5=B5=E4=B9=8B=E7=90=9B?= Date: Thu, 4 Jul 2019 20:19:20 +0800 Subject: [PATCH 175/915] translate 44-63 to ZH_CN --- README-zh_CN.md | 659 ++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 659 insertions(+) diff --git a/README-zh_CN.md b/README-zh_CN.md index 21740dc3..64d8e03a 100644 --- a/README-zh_CN.md +++ b/README-zh_CN.md @@ -1286,3 +1286,662 @@ string 类型是可迭代的。扩展运算符将迭代的每个字符映射成

+ +--- + +###### 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` + +
答案 +

+ +#### 答案: C + +一般的函数在执行之后是不能中途停下的。但是,生成器函数却可以中途“停下”,之后可以再从停下的地方继续。当生成器遇到`yield`关键字的时候,会生成`yield`后面的值。注意,生成器在这种情况下不 _返回_ (_return_ )值,而是 _生成_ (_yield_)值。 + +首先,我们用`10`作为参数`i`来初始化生成器函数。然后使用`next()`方法一步步执行生成器。第一次执行生成器的时候,`i`的值为`10`,遇到第一个`yield`关键字,它要生成`i`的值。此时,生成器“暂停”,生成了`10`。 + +然后,我们再执行`next()`方法。生成器会从刚才暂停的地方继续,这个时候`i`还是`10`。于是我们走到了第二个`yield`关键字处,这时候需要生成的值是`i*2`,`i`为`10`,那么此时生成的值便是`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"` + +
答案 +

+ +#### 答案: B + +当我们向`Promise.race`方法中传入多个`Promise`时,会进行 _优先_ 解析。在这个例子中,我们用`setTimeout`给`firstPromise`和`secondPromise`分别设定了500ms和100ms的定时器。这意味着`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" }]` + +
答案 +

+ +#### 答案: D + + +首先我们声明了一个拥有`name`属性的对象 `person`。 + + + +然后我们又声明了一个变量`members`. 将首个元素赋值为变量`person`。 当设置两个对象彼此相等时,它们会通过 _引用_ 进行交互。但是当你将引用从一个变量分配至另一个变量时,其实只是执行了一个 _复制_ 操作。(注意一点,他们的引用 _并不相同_!) + + + +接下来我们让`person`等于`null`。 + + + +我们没有修改数组第一个元素的值,而只是修改了变量`person`的值,因为元素(复制而来)的引用与`person`不同。`members`的第一个元素仍然保持着对原始对象的引用。当我们输出`members`数组时,第一个元素会将引用的对象打印出来。 + +

+
+ +--- + +###### 47. 输出是什么? + +```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]` + +
答案 +

+ +#### 答案: B + +在`for-in`循环中,我们可以通过对象的key来进行迭代,也就是这里的`name`和`age`。在底层,对象的key都是字符串(如果他们不是Symbol的话)。在每次循环中,我们将`item`设定为当前遍历到的key.所以一开始,`item`是`name`,之后 `item`输出的则是`age`。 + +

+
+ +--- + +###### 48. 输出是什么? + +```javascript +console.log(3 + 4 + "5"); +``` + +- A: `"345"` +- B: `"75"` +- C: `12` +- D: `"12"` + +
答案 +

+ +#### 答案: B + +当所有运算符的 _优先级_ 相同时,计算表达式需要确定运算符的结合顺序,即从右到左还是从左往右。在这个例子中,我们只有一类运算符`+`,对于加法来说,结合顺序就死从左到右。 + +`3 + 4`首先计算,得到数字`7`. + +由于类型的强制转换,`7 + '5'`的结果是`"75"`. JavaScript将`7`转换成了字符串,可以参考问题15.我们可以用`+`号把两个字符串连接起来。 `"7" + "5"` 就得到了`"75"`. + +

+
+ +--- + +###### 49. `num`的值是什么? + +```javascript +const num = parseInt("7*6", 10); +``` + +- A: `42` +- B: `"42"` +- C: `7` +- D: `NaN` + +
答案 +

+ +#### 答案: C + +只返回了字符串中第一个字母. 设定了 _进制_ 后 (也就是第二个参数,指定需要解析的数字是什么进制: 十进制、十六机制、八进制、二进制等等……),`parseInt` 检查字符串中的字符是否合法. 一旦遇到一个在指定进制中不合法的字符后,立即停止解析并且忽略后面所有的字符。 + +`*`就是不合法的数字字符。所以只解析到`"7"`,并将其解析为十进制的`7`. `num`的值即为`7`. + +

+
+ +--- + +###### 50. 输出是什么? + +```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 ]` + +
答案 +

+ +#### 答案: C + +对数组进行映射的时候,`num`就是当前循环到的元素. 在这个例子中,所有的映射都是number类型,所以if中的判断`typeof num === "number"`结果都是`true`.map函数创建了新数组并且将函数的返回值插入数组。 + +但是,没有任何值返回。当函数没有返回任何值时,即默认返回`undefined`.对数组中的每一个元素来说,函数块都得到了这个返回值,所以结果中每一个元素都是`undefined`. + +

+
+ +--- + +###### 51. 输出的是什么? + +```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"` + +
答案 +

+ +#### 答案: A + +普通参数都是 _值_ 传递的,而对象则不同,是 _引用_ 传递。所以说,`birthYear`是值传递,因为他是个字符串而不是对象。当我们对参数进行值传递时,会创建一份该值的 _复制_ 。(可以参考问题46) + +变量`birthYear`有一个对`"1997"`的引用,而传入的参数也有一个对`"1997"`的引用,但二者的引用并不相同。当我们通过给 `year`赋值`"1998"`来更新`year`的值的时候我们只是更新了`year`(的引用)。此时`birthYear`仍然是`"1997"`. + +而`person`是个对象。参数`member`引用与之 _相同的_ 对象。当我们修改`member`所引用对象的属性时,`person`的相应属性也被修改了,因为他们引用了相同的对象. `person`的 `name`属性也变成了 `"Lydia"`. + +

+
+ +--- + +###### 52. 输出是什么? + +```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!` + +
答案 +

+ +#### 答案: D + +通过`throw`语句,我么可以创建自定义错误。 而通过它,我们可以抛出异常。异常可以是一个字符串, 一个 数字, 一个 布尔类型 或者是一个 对象。在本例中,我们的异常是字符串`'Hello world'`. + +通过 `catch`语句,我们可以设定当`try`语句块中抛出异常后应该做什么处理。在本例中抛出的异常是字符串`'Hello world'`. `e`就是这个字符串,因此被输出。最终结果就是`'Oh an error: Hello world'`. + +

+
+ +--- + +###### 53. 输出是什么? + +```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` + +
答案 +

+ +#### 答案: B + +返回属性的时候,属性的值等于 _返回的_ 值,而不是构造函数中设定的值。我们返回了字符串 `"Maserati"`,所以 `myCar.make`等于`"Maserati"`. + +

+
+ +--- + +###### 54. 输出是什么? + +```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"` + +
答案 +

+ +#### 答案: A + +`let x = y = 10;` 是下面这个表达式的缩写: + +```javascript +y = 10; +let x = y; +``` + +我们设定`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"`. + +

+
+ +--- + +###### 55. 输出是什么? + +```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` + +
答案 +

+ +#### 答案: A + +我们可以用`delete`关键字删除对象的属性,对原型也是适用的。删除了原型的属性后,该属性在原型链上就不可用了。在本例中,函数`bark`在执行了`delete Dog.prototype.bark`后不可用, 然而后面的代码还在调用它。 + +当我们尝试调用一个不存在的函数时`TypeError`异常会被抛出。在本例中就是 `TypeError: pet.bark is not a function`,因为`pet.bark`是`undefined`. + +

+
+ +--- + +###### 56. 输出是什么? + +```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}` + +
答案 +

+ +#### 答案: D + +`Set`对象手机 _独一无二_ 的值:也就是说同一个值在其中仅出现一次。 + +我们传入了数组`[1, 1, 2, 3, 4]`,他有一个重复值`1`.以为一个集合里不能有两个重复的值,其中一个就被移除了。所以结果是 `{1, 2, 3, 4}`. + +

+
+ +--- + +###### 57. 输出是什么? + +```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` + +
答案 +

+ +#### 答案: C + +引入的模块是 _只读_ 的: 你不能修改引入的模块。只有导出他们的模块才能修改其值。 + +当我们给`myCounter`增加一个值的时候会抛出一个异常: `myCounter`是只读的,不能被修改。 + +

+
+ +--- + +###### 58. 输出是什么? + +```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` + +
答案 +

+ +#### 答案: A + +`delete`操作符返回一个布尔值: `true`指删除成功,否则返回`false`. 但是通过 `var`, `const` 或 `let` 关键字声明的变量无法用 `delete` 操作符来删除。 + +`name`变量由`const`关键字声明,所以删除不成功:返回 `false`. 而我们设定`age`等于`21`时,我们实际上添加了一个名为`age`的属性给全局对象。对象中的属性是可以删除的,全局对象也是如此,所以`delete age`返回`true`. + +

+
+ +--- + +###### 59. 输出是什么? + +```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]` + +
答案 +

+ +#### 答案: C + +我们可以通过解构赋值来解析来自对象的数组或属性的值,比如说: + +```javascript +[a, b] = [1, 2]; +``` + + + +`a`的值现在是`1`,`b`的值现在是`2`.而在题目中,我们是这么做的: + +```javascript +[y] = [1, 2, 3, 4, 5]; +``` + + + +也就是说,`y`等于数组的第一个值就是数字`1`.我们输出`y`, 返回`1`. + +

+
+ +--- + +###### 60. 输出是什么? + +```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 }` + +
答案 +

+ +#### 答案: B + +扩展运算符`...`为对象的组合提供了可能。你可以复制对象中的键值对,然后把它们加到另一个对象里去。在本例中,我们复制了`user`对象键值对,然后把它们加入到`admin`对象中。`admin`对象就拥有了这些键值对,所以结果为`{ admin: true, name: "Lydia", age: 21 }`. + +

+
+ +--- + +###### 61. 输出是什么? + +```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"]` + +
答案 +

+ +#### 答案: B + +通过`defineProperty`方法,我们可以给对象添加一个新属性,或者修改已经存在的属性。而我们使用`defineProperty`方法给对象添加了一个属性之后,属性默认为 _不可枚举(not enumerable)_. `Object.keys`方法仅返回对象中 _可枚举(enumerable)_ 的属性,因此只剩下了`"name"`. + +用`defineProperty`方法添加的属性默认不可变。你可以通过`writable`, `configurable` 和 `enumerable`属性来改变这一行为。这样的话, 相比于自己添加的属性,`defineProperty`方法添加的属性有了更多的控制权。 + +

+
+ +--- + +###### 62. 输出是什么? + +```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}"` + +
答案 +

+ +#### 答案: A + +`JSON.stringify`的第二个参数是 _替代者(replacer)_. 替代者(replacer)可以是个函数或数组,用以控制哪些值如何被转换为字符串。 + +如果替代者(replacer)是个 _数组_ ,那么就只有包含在数组中的属性将会被转化为字符串。在本例中,只有名为`"level"` 和 `"health"` 的属性被包括进来, `"username"`则被排除在外。 `data` 就等于 `"{"level":19, "health":90}"`. + +而如果替代者(replacer)是个 _函数_,这个函数将被对象的每个属性都调用一遍。 +函数返回的值会成为这个属性的值,最终体现在转化后的JSON字符串中(译者注:Chrome下,经过实验,如果所有属性均返回同一个值的时候有异常,会直接将返回值作为结果输出而不会输出JSON字符串),而如果返回值为`undefined`,则该属性会被排除在外。 + +

+
+ +--- + +###### 63. 输出是什么? + +```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` + +
答案 +

+ +#### 答案: A + +一元操作符 `++` _先返回_ 操作值, _再累加_ 操作值。`num1`的值是`10`, 因为`increaseNumber`函数首先返回`num`的值,也就是`10`,随后再进行 `num`的累加。 + +`num2`是`10`因为我们将 `num1`传入`increasePassedNumber`. `number`等于`10`(`num1`的值。同样道理,`++` _先返回_ 操作值, _再累加_ 操作值。) `number`是`10`,所以`num2`也是`10`. + +

+
From 51c56ec1ed64e0b3d01820a484bd326fe73c76d6 Mon Sep 17 00:00:00 2001 From: Reg Date: Thu, 4 Jul 2019 23:35:21 +0800 Subject: [PATCH 176/915] fix: Remove the extra symbols On question 35, 38, 40. --- README-zh_CN.md | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/README-zh_CN.md b/README-zh_CN.md index 08aa81ea..d1db96f4 100644 --- a/README-zh_CN.md +++ b/README-zh_CN.md @@ -1040,8 +1040,8 @@ typeof sayHi() ```javascript 0 new Number(0) -;('') -;(' ') +('') +(' ') new Boolean(false) undefined ``` @@ -1130,12 +1130,12 @@ console.log(numbers) ###### 38. 输出是什么? ```javascript -;(() => { +(() => { let x, y try { throw new Error() } catch (x) { - ;(x = 1), (y = 2) + (x = 1), (y = 2) console.log(x) } console.log(x) @@ -1188,7 +1188,7 @@ JavaScript 只有基本类型和对象。 ###### 40. 输出是什么? ```javascript -;[[0, 1], [2, 3]].reduce( +[[0, 1], [2, 3]].reduce( (acc, cur) => { return acc.concat(cur) }, From d89414e0611d6baafadf582e82b052e64c472cdc Mon Sep 17 00:00:00 2001 From: Tanguy Coppin Date: Thu, 4 Jul 2019 21:28:43 +0200 Subject: [PATCH 177/915] Update README_fr-FR.md Co-Authored-By: Nathanael CHERRIER --- README_fr-FR.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README_fr-FR.md b/README_fr-FR.md index a8dfb5c1..a4e35ba6 100644 --- a/README_fr-FR.md +++ b/README_fr-FR.md @@ -66,7 +66,7 @@ for (let i = 0; i < 3; i++) { #### Réponse: C -À cause du système de queue dans JavaScript, la fonction de rappel _(callback)_ du `setTimeout` est appellée _après_ que la boucle soit exécutée. Comme la variable `i` dans la première boucle est déclarée avec le mot clé `var`, c'est une variable global. Pendant la boucle, nous incrémentons la valeur de `i` par `1` à chaque fois, en utilisant l'opérateur arithmétique `++`. Lorsque la fonction de rappel _(callback)_ du `setTimeout` est invoquée, `i` est égal à `3` dans le premier exemple. +À cause du système de queue dans JavaScript, la fonction de rappel _(callback)_ du `setTimeout` est appelée _après_ que la boucle soit exécutée. Comme la variable `i` dans la première boucle est déclarée avec le mot-clé `var`, c'est une variable globale. Pendant la boucle, nous incrémentons la valeur de `i` de `1` à chaque fois, en utilisant l'opérateur arithmétique `++`. Lorsque la fonction de rappel _(callback)_ du `setTimeout` est invoquée, `i` est égal à `3` dans le premier exemple. Dans la seconde boucle, la variable `i` est déclarée avec le mot clé `let` : les variables déclarées avec `let` (et `const`) ont une portée de bloc (tout ce qui est entre `{ }` est considéré comme un bloc). Pendant chaque itération, `i` aura une nouvelle valeur, et chaque valeur sera définie dans la boucle. From aad533d236665fa553cb5997987d4b6bf8ed28ea Mon Sep 17 00:00:00 2001 From: Tanguy Coppin Date: Thu, 4 Jul 2019 21:29:04 +0200 Subject: [PATCH 178/915] Update README_fr-FR.md Co-Authored-By: Nathanael CHERRIER --- README_fr-FR.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README_fr-FR.md b/README_fr-FR.md index a4e35ba6..26ecbe25 100644 --- a/README_fr-FR.md +++ b/README_fr-FR.md @@ -100,7 +100,7 @@ shape.perimeter(); #### Réponse: B -Notez que le valeur de `diameter` est une fonction régulière, alors que `perimeter` est une fonction fléchée. +Notez que la valeur de `diameter` est une fonction régulière, alors que celle de `perimeter` est une fonction fléchée. Avec les fonctions fléchée, le mot clé `this` réfère à son périmètre actuel, contrairement au fonctions régulières ! Cela signifie que lorsque nous appelons `perimeter`, elle ne réfère pas à l'objet shape, mais à son périmètre actuel (`window` par exemple). From cfe69467ae6d3c0f60511fc2342aef578ca54fde Mon Sep 17 00:00:00 2001 From: Tanguy Coppin Date: Thu, 4 Jul 2019 21:29:55 +0200 Subject: [PATCH 179/915] Update README_fr-FR.md Co-Authored-By: Nathanael CHERRIER --- README_fr-FR.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README_fr-FR.md b/README_fr-FR.md index 26ecbe25..69c1cc39 100644 --- a/README_fr-FR.md +++ b/README_fr-FR.md @@ -129,7 +129,7 @@ Il n'y a pas de valeur `radius` dans cet objet, on retournera `undefined`. L'opérateur arithmétique `+` essait de convertir un opérande en une valeur numérique. `true` devient `1`, et `false` devient `0`. -La chaine de caractère `'Lydia'` est une value considérée comme vraie _(truthy)_. Ce que nous sommes actuellement entrain de demander, c'est "est-ce que cette valeur vraie est fausse ?". Ce qui retournera `false`. +La chaine de caractère `'Lydia'` est une valeur considérée comme vraie _(truthy)_. Ce que nous sommes actuellement en train de demander, c'est "est-ce que cette valeur considérée comme vraie est fausse ?". Ce qui retournera `false`.

From 6247050d14f2f6410b9ab7042fe666fa5e621743 Mon Sep 17 00:00:00 2001 From: Tanguy Coppin Date: Thu, 4 Jul 2019 21:30:14 +0200 Subject: [PATCH 180/915] Update README_fr-FR.md Co-Authored-By: Nathanael CHERRIER --- README_fr-FR.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README_fr-FR.md b/README_fr-FR.md index 69c1cc39..f4ba3960 100644 --- a/README_fr-FR.md +++ b/README_fr-FR.md @@ -159,7 +159,7 @@ const mouse = { #### Réponse: A -En JavaScript, toutes les clé d'objet sont des chaines de caractères (sauf si c'est un Symbol). Bien que nous ne puission pas les _typer_ comme des chaines de caractères, elles sont converties en chaines de caractères sous le capot. +En JavaScript, toutes les clés d'objet sont des chaines de caractères (sauf si c'est un Symbol). Bien que nous ne puissions pas les _typer_ comme des chaines de caractères, elles sont converties en chaines 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. From 8e155e32f43c3c9a5b83bc35091c190ea76dc2e1 Mon Sep 17 00:00:00 2001 From: Tanguy Coppin Date: Thu, 4 Jul 2019 21:30:37 +0200 Subject: [PATCH 181/915] Update README_fr-FR.md Co-Authored-By: Nathanael CHERRIER --- README_fr-FR.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README_fr-FR.md b/README_fr-FR.md index f4ba3960..9edbd53a 100644 --- a/README_fr-FR.md +++ b/README_fr-FR.md @@ -196,7 +196,7 @@ console.log(d.greeting); #### Réponse: A -En JavaScript, tous les object intéragisent par _référence_ en plaçant égaux les uns aux autres. +En JavaScript, tous les objets interagissent par _référence_ lorsqu'on les définit égaux les uns aux autres. Premièrement, la variable `c` contaient une valeur d'objet. Plus tard, nous assignons `d` avec la même réference que `c` à l'objet. From 94fd29d1f1f610cce08c7c4a1f5a3c09424b4aaa Mon Sep 17 00:00:00 2001 From: Tanguy Coppin Date: Thu, 4 Jul 2019 21:30:50 +0200 Subject: [PATCH 182/915] Update README_fr-FR.md Co-Authored-By: Nathanael CHERRIER --- README_fr-FR.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README_fr-FR.md b/README_fr-FR.md index 9edbd53a..29b0fb4d 100644 --- a/README_fr-FR.md +++ b/README_fr-FR.md @@ -570,7 +570,7 @@ Lorsque l'on teste une égalité, les primitifs sont comparés par leur valeur, Les 2 objets que nous comparons n'ont pas ça : l'objet passé en paramètre fait référence à une zone mémoire différente que l'objet que nous utilisons pour faire la comparaison. -C'est pourquoi l;es 2 conditions `{ ag: 18 } === { age: 18 }` et `{ age: 18 } == { age: 18 }` retournent `false`. +C'est pourquoi les 2 conditions `{ age: 18 } === { age: 18 }` et `{ age: 18 } == { age: 18 }` retournent `false`.

From ec0eb68b2095f501330392b2aa68d331153ffb2a Mon Sep 17 00:00:00 2001 From: Tanguy Coppin Date: Thu, 4 Jul 2019 21:31:05 +0200 Subject: [PATCH 183/915] Update README_fr-FR.md Co-Authored-By: Nathanael CHERRIER --- README_fr-FR.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README_fr-FR.md b/README_fr-FR.md index 29b0fb4d..137e5a91 100644 --- a/README_fr-FR.md +++ b/README_fr-FR.md @@ -626,7 +626,7 @@ getAge(); #### Réponse: C -Avec `"use strict"`, vous pouvez êtes sûr de ne pas déclarer accidentellement des variables gloables. Nous ne déclarerons jamais la variable `age`, et temps que nous utiliserons `"use strict"`, cela créera une erreur de référence. Si nous n'utilisons pas `"use strict"`, cela fonctionnera et la variable `age` sont attribué à l'objet global. +Avec `"use strict"`, vous pouvez êtes sûr de ne pas déclarer accidentellement des variables gloables. Nous ne déclarerons jamais la variable `age`, et temps que nous utiliserons `"use strict"`, cela créera une erreur de référence. Si nous n'utilisons pas `"use strict"`, cela fonctionnera et la variable `age` sera attribué à l'objet global.

From b7f9a72fec44e33e37969cc100acf9dd17f839e9 Mon Sep 17 00:00:00 2001 From: Tanguy Coppin Date: Thu, 4 Jul 2019 21:31:25 +0200 Subject: [PATCH 184/915] Update README_fr-FR.md Co-Authored-By: Nathanael CHERRIER --- README_fr-FR.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README_fr-FR.md b/README_fr-FR.md index 137e5a91..90c1f35d 100644 --- a/README_fr-FR.md +++ b/README_fr-FR.md @@ -731,7 +731,7 @@ set.has(1); #### Réponse: C -Toutes les clés d'objet (à l'exception des symboles) sont des chaînes de caratères sous le capot, même si vous ne les tapez pas vous-même en tant que chaîne. C'est pourquoi `obj.hasOwnProperty('1')` renvoie également la valeur `true`. +Toutes les clés d'objet (à l'exception des symboles) sont des chaînes de caractères sous le capot, même si vous ne les tapez pas vous-même en tant que chaîne. C'est pourquoi `obj.hasOwnProperty("1")` renvoie également la valeur `true`. Ça ne marche pas comme ça pour un set. Il n'y a pas de `'1'` dans notre ensemble : `set.has('1')` renvoie `false`. Il a le type numérique `1`, `set.has(1)` renvoie `true`. From 6019dbd15115df850b622aab77cbaadb4e96a9e9 Mon Sep 17 00:00:00 2001 From: Tanguy Coppin Date: Thu, 4 Jul 2019 21:31:36 +0200 Subject: [PATCH 185/915] Update README_fr-FR.md Co-Authored-By: Nathanael CHERRIER --- README_fr-FR.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README_fr-FR.md b/README_fr-FR.md index 90c1f35d..5f5c1c52 100644 --- a/README_fr-FR.md +++ b/README_fr-FR.md @@ -764,7 +764,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éait 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 and le mot-clé `this`. - A: Vrai - B: Faux From aac9d3266154fcca2c267af12d178b65511fc449 Mon Sep 17 00:00:00 2001 From: Tanguy Coppin Date: Thu, 4 Jul 2019 21:31:58 +0200 Subject: [PATCH 186/915] Update README_fr-FR.md Co-Authored-By: Nathanael CHERRIER --- README_fr-FR.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README_fr-FR.md b/README_fr-FR.md index 5f5c1c52..ef45a77f 100644 --- a/README_fr-FR.md +++ b/README_fr-FR.md @@ -860,7 +860,7 @@ console.log(a[b]); #### Réponse: B -Les clés d'objet sont automatiquement converties en chaînes de caractère. Nous essayons de définir un objet en tant que clé de l'objet `a`, avec la valeur `123`. +Les clés d'objet sont automatiquement converties en chaînes de caractères. Nous essayons de définir un objet en tant que clé de l'objet `a`, avec la valeur `123`. Cependant, lorsque nous transformons un objet en chaine de caractère, il devient `"[Objet objet]"`. Donc, ce que nous disons ici, c'est que un `a["Objet objet"] = 123`. Ensuite, nous pouvons essayer de refaire la même chose. `c` est un autre objet que nous sommes implicitement en train de transformer en chaine de carctère. Donc, `a["Objet objet"] = 456`. From f20b9ea38aff580f198d72916ee49ee95825ce09 Mon Sep 17 00:00:00 2001 From: Tanguy Coppin Date: Thu, 4 Jul 2019 21:32:24 +0200 Subject: [PATCH 187/915] Update README_fr-FR.md Co-Authored-By: Quentin Tomasicchio --- README_fr-FR.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README_fr-FR.md b/README_fr-FR.md index ef45a77f..412a3534 100644 --- a/README_fr-FR.md +++ b/README_fr-FR.md @@ -2,7 +2,7 @@ Je poste quotidiennement des questions à choix multiple sur mon [Instagram](https://www.instagram.com/theavocoder), que je posterai aussi ici ! -Des basiques au avancée: testez vos connaissances en JavaScript, rafraichissez vos connaissances, ou préparez vous pour un entretien de code ! :muscle: :rocket: Je mets à jour ce dépôt chaque semaine avec des nouvelles questions. +Des basiques au avancée : testez votre compréhension de JavaScript, rafraîchissez vos connaissances, ou préparez-vous pour un entretien technique ! :muscle: :rocket: Je mets à jour ce dépôt chaque semaine avec des nouvelles questions. Dernière mise à jour : 29 juin Les réponses se trouvent dans les sections fermées en dessous des questions, cliquez simplement dessus pour les faire apparaitre. Bonne chance :heart: From 149dba305a5e5edd8bd655ed7aefc6342f60128a Mon Sep 17 00:00:00 2001 From: Tanguy Coppin Date: Thu, 4 Jul 2019 21:34:07 +0200 Subject: [PATCH 188/915] Update frnech introduction --- README_fr-FR.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README_fr-FR.md b/README_fr-FR.md index 412a3534..e236427b 100644 --- a/README_fr-FR.md +++ b/README_fr-FR.md @@ -2,7 +2,7 @@ Je poste quotidiennement des questions à choix multiple sur mon [Instagram](https://www.instagram.com/theavocoder), que je posterai aussi ici ! -Des basiques au avancée : testez votre compréhension de JavaScript, rafraîchissez vos connaissances, ou préparez-vous pour un entretien technique ! :muscle: :rocket: Je mets à jour ce dépôt chaque semaine avec des nouvelles questions. Dernière mise à jour : 29 juin +De la base aux subtilités du langage : testez votre compréhension de JavaScript, rafraîchissez vos connaissances, ou préparez-vous pour un entretien technique ! :muscle: :rocket: Je mets à jour ce dépôt chaque semaine avec des nouvelles questions. Dernière mise à jour : [**29 juin**](#20190629) Les réponses se trouvent dans les sections fermées en dessous des questions, cliquez simplement dessus pour les faire apparaitre. Bonne chance :heart: From 8744ebff0ce2209881325cdc8ada7c5de005a683 Mon Sep 17 00:00:00 2001 From: Tanguy Coppin Date: Thu, 4 Jul 2019 21:34:52 +0200 Subject: [PATCH 189/915] Update README_fr-FR.md Co-Authored-By: Quentin Tomasicchio --- README_fr-FR.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README_fr-FR.md b/README_fr-FR.md index 412a3534..51d5bf57 100644 --- a/README_fr-FR.md +++ b/README_fr-FR.md @@ -38,7 +38,7 @@ sayHi(); Dans la fonction, nous déclarons en premier la variable `name` grâce au mot clé `var`. Cela signifie que la variable est "levée" _(hoisted)_ (l'espace mémoire est définie à la phase de création) avec pour valeur par défaut `undefined`, jusqu'à ce que le script atteigne la ligne de définition de la variable. Nous n'avons pas encore défini la variable lorsque nous essayons d'afficher la variable `name`, donc elle a toujours la valeur `undefined`. -Les variables avec le mot clé `let` (et `const`) sont "levées" _(hoisted)_, mais contrairement à `var`, elle n'est pas initialisée. Elles ne sont pas accessible avant la ligne qui les declare (initialise). C'est appelé la "zone morte temporaire". Lorsque nous essayons d'accéder aux variables avant leur déclaration, JavaScript renvoit une `ReferenceError`. +Les variables avec le mot clé `let` (et `const`) sont "levées" _(hoisted)_, mais contrairement à `var`, elle n'est pas initialisée. Elles ne sont pas accessible avant la ligne qui les déclare (initialise). C'est appelé la "zone morte temporaire". Lorsque nous essayons d'accéder aux variables avant leur déclaration, JavaScript renvoie une `ReferenceError`.

From c7c1cd6672ac05a5b1a4a25a8edf8b277bd7abea Mon Sep 17 00:00:00 2001 From: Tanguy Coppin Date: Thu, 4 Jul 2019 21:35:12 +0200 Subject: [PATCH 190/915] Update README_fr-FR.md Co-Authored-By: Quentin Tomasicchio --- README_fr-FR.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README_fr-FR.md b/README_fr-FR.md index 51d5bf57..12633bb4 100644 --- a/README_fr-FR.md +++ b/README_fr-FR.md @@ -102,7 +102,7 @@ shape.perimeter(); Notez que la valeur de `diameter` est une fonction régulière, alors que celle de `perimeter` est une fonction fléchée. -Avec les fonctions fléchée, le mot clé `this` réfère à son périmètre actuel, contrairement au fonctions régulières ! Cela signifie que lorsque nous appelons `perimeter`, elle ne réfère pas à l'objet shape, mais à son périmètre actuel (`window` par exemple). +Avec les fonctions fléchée, le mot clé `this` réfère à son périmètre actuel, contrairement aux fonctions régulières ! Cela signifie que lorsque nous appelons `perimeter`, elle ne réfère pas à l'objet `shape`, mais à son périmètre actuel (`window` par exemple). Il n'y a pas de valeur `radius` dans cet objet, on retournera `undefined`. From 23d67024138466d65affebbd5d524c71e675d657 Mon Sep 17 00:00:00 2001 From: Tanguy Coppin Date: Thu, 4 Jul 2019 21:35:19 +0200 Subject: [PATCH 191/915] Update README_fr-FR.md Co-Authored-By: Quentin Tomasicchio --- README_fr-FR.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README_fr-FR.md b/README_fr-FR.md index 12633bb4..74f35a55 100644 --- a/README_fr-FR.md +++ b/README_fr-FR.md @@ -303,7 +303,7 @@ Pour éviter cela, on peut utiliser `"use strict"`. Cela nous assure de devoir d --- -###### 10. Que ce passe-t-il lorsque nous faisons ça ? +###### 10. Que se passe-t-il lorsque nous faisons ça ? ```javascript function bark() { From 721989e4717179ceed4b410683d5cdab2fc524d6 Mon Sep 17 00:00:00 2001 From: Tanguy Coppin Date: Thu, 4 Jul 2019 21:35:34 +0200 Subject: [PATCH 192/915] Update README_fr-FR.md Co-Authored-By: Quentin Tomasicchio --- README_fr-FR.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README_fr-FR.md b/README_fr-FR.md index 74f35a55..ac73533b 100644 --- a/README_fr-FR.md +++ b/README_fr-FR.md @@ -358,7 +358,7 @@ console.log(member.getFullName()); #### Réponse: A -Vous ne pouvez pas ajouter de propriétés à un constructeur comme pour des objets normaux. Si vous voulez ajouter une fonctionnalité pour tout les objets en une fois, vous devez utiliser le prototype. Donc dans ce cas, +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() { From 971ec71c31ee0b05c27e27bed275804ac2294eb0 Mon Sep 17 00:00:00 2001 From: Tanguy Coppin Date: Thu, 4 Jul 2019 21:35:40 +0200 Subject: [PATCH 193/915] Update README_fr-FR.md Co-Authored-By: Quentin Tomasicchio --- README_fr-FR.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README_fr-FR.md b/README_fr-FR.md index ac73533b..cc7becda 100644 --- a/README_fr-FR.md +++ b/README_fr-FR.md @@ -428,7 +428,7 @@ Durant la phase de **capture** _(capturing)_, l'événement passe par les évén --- -###### 14. Tous les objects ont des prototypes. +###### 14. Tous les objets ont des prototypes. - A: vrai - B: faux From 48aa14e4383c135a5fcb4d336de972463c4d5248 Mon Sep 17 00:00:00 2001 From: Tanguy Coppin Date: Thu, 4 Jul 2019 21:35:52 +0200 Subject: [PATCH 194/915] Update README_fr-FR.md Co-Authored-By: Quentin Tomasicchio --- README_fr-FR.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README_fr-FR.md b/README_fr-FR.md index cc7becda..5278162b 100644 --- a/README_fr-FR.md +++ b/README_fr-FR.md @@ -438,7 +438,7 @@ Durant la phase de **capture** _(capturing)_, l'événement passe par les évén #### Réponse: B -Tous les objets ont des prototypes, excepté pour les **objets standards**. Les objets standards ont accès à certaines méthodes et propriétés, comme `.toString`. C'est pour cette raison que vous pouvez utiliser les méthodes natives de JavaScript ! Toutes ces méthodes sont disponibles dans le prototype. Bien que JavaScript ne trouve pas la fonction dans l'objet, il parcours le prototype et la méthode afin de la rendre accessible. +Tous les objets ont des prototypes, excepté pour les **objets standards**. Les objets standards ont accès à certaines méthodes et propriétés, comme `.toString`. C'est pour cette raison que vous pouvez utiliser les méthodes natives de JavaScript ! Toutes ces méthodes sont disponibles dans le prototype. Bien que JavaScript ne trouve pas la fonction dans l'objet, il parcourt le prototype et la méthode afin de la rendre accessible.

From 1d47081c4ddfbeb2f3532049d06bde2e69d6248f Mon Sep 17 00:00:00 2001 From: Tanguy Coppin Date: Thu, 4 Jul 2019 21:36:06 +0200 Subject: [PATCH 195/915] Update README_fr-FR.md Co-Authored-By: Quentin Tomasicchio --- README_fr-FR.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README_fr-FR.md b/README_fr-FR.md index 5278162b..81f93b65 100644 --- a/README_fr-FR.md +++ b/README_fr-FR.md @@ -534,7 +534,7 @@ getPersonInfo`${person} is ${age} years old`; #### Réponse: B -Si vous utilisez les template de chaine de caractère, la valeur du premier argument sera toujours un tableau de valeurs des chaines de caractère. Le reste des arguments seront les valeurs des expressions utilisées ! +Si vous utilisez les littéraux de gabarits, la valeur du premier argument sera toujours un tableau de valeurs des chaines de caractère. Le reste des arguments seront les valeurs des expressions utilisées !

From bc1011407c2d7e5c2f719e7e0b6141b69b7a39f3 Mon Sep 17 00:00:00 2001 From: Tanguy Coppin Date: Thu, 4 Jul 2019 21:36:21 +0200 Subject: [PATCH 196/915] Update README_fr-FR.md Co-Authored-By: Quentin Tomasicchio --- README_fr-FR.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README_fr-FR.md b/README_fr-FR.md index 81f93b65..e1ff905c 100644 --- a/README_fr-FR.md +++ b/README_fr-FR.md @@ -566,7 +566,7 @@ checkAge({ age: 18 }); #### Réponse: C -Lorsque l'on teste une égalité, les primitifs sont comparés par leur valeur, alors que les objet sont comparés par leur _référence_. JavaScript vérifie si les objets ont une référence à la même zone de la mémoire.= +Lorsque l'on teste une égalité, les primitifs sont comparés par leur valeur, alors que les objets sont comparés par leur _référence_. JavaScript vérifie si les objets ont une référence à la même zone de la mémoire.= Les 2 objets que nous comparons n'ont pas ça : l'objet passé en paramètre fait référence à une zone mémoire différente que l'objet que nous utilisons pour faire la comparaison. From 79517b0119922f8f170254aaec08c1642d15560d Mon Sep 17 00:00:00 2001 From: Tanguy Coppin Date: Thu, 4 Jul 2019 21:37:00 +0200 Subject: [PATCH 197/915] Update README_fr-FR.md Co-Authored-By: Quentin Tomasicchio --- README_fr-FR.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README_fr-FR.md b/README_fr-FR.md index e1ff905c..71cdeabe 100644 --- a/README_fr-FR.md +++ b/README_fr-FR.md @@ -830,7 +830,7 @@ name.giveLydiaPizza(); #### Réponse: A -`String` est un constructeur intégré, auquel nous pouvons ajouter des propriétés. Je viens d'ajouter une méthode à son prototype. Les chaînes de caratère primitives sont automatiquement converties en un objet chaîne, généré par la fonction prototype de chaîne. Ainsi, toutes les chaînes (objets de chaîne) ont accès à cette méthode ! +`String` est un constructeur intégré, auquel nous pouvons ajouter des propriétés. Je viens d'ajouter une méthode à son prototype. Les chaînes de caractère primitives sont automatiquement converties en un objet chaîne, généré par la fonction prototype de chaîne. Ainsi, toutes les chaînes (objets de chaîne) ont accès à cette méthode !

From a2fce6a87a032d0d8aab7b23030600935e4d0ae4 Mon Sep 17 00:00:00 2001 From: Tanguy Coppin Date: Thu, 4 Jul 2019 21:37:17 +0200 Subject: [PATCH 198/915] Update README_fr-FR.md Co-Authored-By: Quentin Tomasicchio --- README_fr-FR.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README_fr-FR.md b/README_fr-FR.md index 71cdeabe..b5117d31 100644 --- a/README_fr-FR.md +++ b/README_fr-FR.md @@ -924,7 +924,7 @@ C'est ici qu'une boucle d'événement commence à fonctionner. La **boucle d'év --- -###### 31. Quel est l'élément ciblé _(event.target)_ au click sur le bouton _(button)_ ? +###### 31. Quel est l'élément ciblé _(event.target)_ au clic sur le bouton _(button)_ ? ```html
From c29fc7fb50f18f84bb5bcff838f7df63c5b031bd Mon Sep 17 00:00:00 2001 From: Tanguy Coppin Date: Thu, 4 Jul 2019 21:37:28 +0200 Subject: [PATCH 199/915] Update README_fr-FR.md Co-Authored-By: Quentin Tomasicchio --- README_fr-FR.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README_fr-FR.md b/README_fr-FR.md index b5117d31..9557e0f0 100644 --- a/README_fr-FR.md +++ b/README_fr-FR.md @@ -1005,7 +1005,7 @@ sayHi.bind(person, 21); Avec les deux, nous pouvons transmettre l'objet auquel nous voulons que le mot clé `this` fasse référence. Cependant, `.call` est aussi _exécuté immédiatement_ ! -`.bind.` renvoie une copie de la fonction, mais avec un contexte lié ! Elle n'est pas exécuté immédiatement. +`.bind.` renvoie une copie de la fonction, mais avec un contexte lié ! Elle n'est pas exécutée immédiatement.

From f6f8988983bc229a921e34420c9c9b5f6c122d70 Mon Sep 17 00:00:00 2001 From: Tanguy Coppin Date: Thu, 4 Jul 2019 21:38:04 +0200 Subject: [PATCH 200/915] Update README_fr-FR.md Co-Authored-By: Quentin Tomasicchio --- README_fr-FR.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README_fr-FR.md b/README_fr-FR.md index 9557e0f0..bab04970 100644 --- a/README_fr-FR.md +++ b/README_fr-FR.md @@ -1184,7 +1184,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'encapsuleur, à savoir `String`, puis supprime immédiatement l'encapsuleur 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.

From 7ffd89070530781bd8057d86d0e12bf3c1e7a756 Mon Sep 17 00:00:00 2001 From: Tanguy Coppin Date: Thu, 4 Jul 2019 21:38:14 +0200 Subject: [PATCH 201/915] Update README_fr-FR.md Co-Authored-By: Quentin Tomasicchio --- README_fr-FR.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README_fr-FR.md b/README_fr-FR.md index bab04970..91590973 100644 --- a/README_fr-FR.md +++ b/README_fr-FR.md @@ -1289,7 +1289,7 @@ Il retourne un identifiant unique. Cet identifiant peut être utilisé pour effa #### Réponse: A -Une chaîne de caractère est itérable. L'opérateur de desconstruction transforme chaque caractère d'un itérable en un élément. +Une chaîne de caractère est itérable. L'opérateur de déconstruction transforme chaque caractère d'un itérable en un élément.

From d4dce83098b2603c60b5af10fe9228be7b0d854e Mon Sep 17 00:00:00 2001 From: Tanguy Coppin Date: Thu, 4 Jul 2019 21:38:27 +0200 Subject: [PATCH 202/915] Update README_fr-FR.md Co-Authored-By: Quentin Tomasicchio --- README_fr-FR.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README_fr-FR.md b/README_fr-FR.md index 91590973..ade4973f 100644 --- a/README_fr-FR.md +++ b/README_fr-FR.md @@ -597,7 +597,7 @@ getAge(21); #### Réponse: C -L'opérateur de destructuration _(spread operator)_ (`...args`) retourne un tableau avec les arguments. Un tableau est un objet, donc `typeof args` retournera `"object"`. +L'opérateur de déstructuration _(spread operator)_ (`...args`) retourne un tableau avec les arguments. Un tableau est un objet, donc `typeof args` retournera `"object"`.

From cdaca3fceedb6d6ef5d82633fad8a85332e40363 Mon Sep 17 00:00:00 2001 From: Tanguy Coppin Date: Thu, 4 Jul 2019 21:39:54 +0200 Subject: [PATCH 203/915] Update README_fr-FR.md Co-Authored-By: Quentin Tomasicchio --- README_fr-FR.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README_fr-FR.md b/README_fr-FR.md index ade4973f..3c7d86be 100644 --- a/README_fr-FR.md +++ b/README_fr-FR.md @@ -649,7 +649,7 @@ const sum = eval("10*10+5"); #### Réponse: A -`eval` évalue les codes que nous passons en paramétre de type chaine de caractères. Si c'est une expression, comme dans notre cas, il évaluera l'expression. L'expression est `10 * 10 + 5`, ce qui retourne le nombre `105`. +`eval` évalue les codes que nous passons en paramètre de type chaîne de caractères. Si c'est une expression, comme dans notre cas, il évaluera l'expression. L'expression est `10 * 10 + 5`, ce qui retourne le nombre `105`.

From ad09fb44d3ca560878604ec1d575529ea4e25310 Mon Sep 17 00:00:00 2001 From: Tanguy Coppin Date: Thu, 4 Jul 2019 21:40:10 +0200 Subject: [PATCH 204/915] Update README_fr-FR.md Co-Authored-By: Nathanael CHERRIER --- README_fr-FR.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README_fr-FR.md b/README_fr-FR.md index 3c7d86be..92768437 100644 --- a/README_fr-FR.md +++ b/README_fr-FR.md @@ -231,7 +231,7 @@ console.log(b === c); #### Réponse: C -`new Number()` est une fonction globale. Bien qu'il ressemble à un nombre, ce n'en est pas vraiment un : il a une poignée de fonctionnalités supplémentaire and est un objet. +`new Number()` est une fonction globale. Bien qu'il ressemble à un nombre, ce n'en est pas vraiment un : il a une poignée de fonctionnalités supplémentaire et est un objet. Quand nous utilisons l'opérateur `==`, il vérifie seulement qu'il s'agisse de la même _valeur_. Les deux ont pour valeur `3`, donc il retourne `true`. From 70dc00e6a338abc3daa80f47775b0077b957b672 Mon Sep 17 00:00:00 2001 From: Tanguy Coppin Date: Thu, 4 Jul 2019 21:40:36 +0200 Subject: [PATCH 205/915] Update README_fr-FR.md Co-Authored-By: Quentin Tomasicchio --- README_fr-FR.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README_fr-FR.md b/README_fr-FR.md index 92768437..231a7c4f 100644 --- a/README_fr-FR.md +++ b/README_fr-FR.md @@ -4,7 +4,7 @@ Je poste quotidiennement des questions à choix multiple sur mon [Instagram](htt Des basiques au avancée : testez votre compréhension de JavaScript, rafraîchissez vos connaissances, ou préparez-vous pour un entretien technique ! :muscle: :rocket: Je mets à jour ce dépôt chaque semaine avec des nouvelles questions. Dernière mise à jour : 29 juin -Les réponses se trouvent dans les sections fermées en dessous des questions, cliquez simplement dessus pour les faire apparaitre. Bonne chance :heart: +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: [English](./README.md) [中文版本](./README-zh_CN.md) From 365bae5590177b62f5b6414895bc7cf05641c2e5 Mon Sep 17 00:00:00 2001 From: Tanguy Coppin Date: Thu, 4 Jul 2019 21:40:56 +0200 Subject: [PATCH 206/915] Update README_fr-FR.md Co-Authored-By: Quentin Tomasicchio --- README_fr-FR.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README_fr-FR.md b/README_fr-FR.md index 231a7c4f..a7430f9a 100644 --- a/README_fr-FR.md +++ b/README_fr-FR.md @@ -656,7 +656,7 @@ const sum = eval("10*10+5"); --- -###### 22. Pendant combien de temps `cool_secret` sera-t'il accessible ? +###### 22. Pendant combien de temps `cool_secret` sera-t-il accessible ? ```javascript sessionStorage.setItem("cool_secret", 123); From 0ae3d290213d7aef751200d1d4f11b3b4f8f910c Mon Sep 17 00:00:00 2001 From: Tanguy Coppin Date: Thu, 4 Jul 2019 21:41:10 +0200 Subject: [PATCH 207/915] Update README_fr-FR.md Co-Authored-By: Quentin Tomasicchio --- README_fr-FR.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README_fr-FR.md b/README_fr-FR.md index a7430f9a..cf159372 100644 --- a/README_fr-FR.md +++ b/README_fr-FR.md @@ -702,7 +702,7 @@ console.log(num); Avec le mot clé `var`, vous pouvez déclarer plusieurs variables avec le même nom. La variable aura pour valeur la dernière assignée. -Vous ne pouvez par faire cela avec `let` ou `const` puisqu'ils ont une portée de bloc. +Vous ne pouvez pas faire cela avec `let` ou `const` puisqu'ils ont une portée de bloc.

From d7e6f5b518b707a079de9f463af9b6b8861ea655 Mon Sep 17 00:00:00 2001 From: Tanguy Coppin Date: Thu, 4 Jul 2019 21:41:24 +0200 Subject: [PATCH 208/915] Update README_fr-FR.md Co-Authored-By: Quentin Tomasicchio --- README_fr-FR.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README_fr-FR.md b/README_fr-FR.md index cf159372..f90f179d 100644 --- a/README_fr-FR.md +++ b/README_fr-FR.md @@ -775,7 +775,7 @@ Si vous avez deux clés portant le même nom, la clé sera remplacée. Elle sera #### Réponse: A -Le contexte d'exécution de base est le contexte d'exécution global: c'est ce qui est accessible partout dans votre code. +Le contexte d'exécution de base est le contexte d'exécution global : c'est ce qui est accessible partout dans votre code.

From dc3a806703c4a407baa36a30f31f1895fccab190 Mon Sep 17 00:00:00 2001 From: Tanguy Coppin Date: Thu, 4 Jul 2019 21:41:35 +0200 Subject: [PATCH 209/915] Update README_fr-FR.md Co-Authored-By: Quentin Tomasicchio --- README_fr-FR.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README_fr-FR.md b/README_fr-FR.md index f90f179d..ff868b4f 100644 --- a/README_fr-FR.md +++ b/README_fr-FR.md @@ -768,7 +768,7 @@ Si vous avez deux clés portant le même nom, la clé sera remplacée. Elle sera - A: Vrai - B: Faux -- C: Ça dépends +- C: Ça dépend
Réponse

From fb8cd698df92436fab9f9da3d0d4f964ac81f5e7 Mon Sep 17 00:00:00 2001 From: Tanguy Coppin Date: Thu, 4 Jul 2019 21:41:59 +0200 Subject: [PATCH 210/915] Update README_fr-FR.md Co-Authored-By: Nathanael CHERRIER --- README_fr-FR.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README_fr-FR.md b/README_fr-FR.md index ff868b4f..5e0a8857 100644 --- a/README_fr-FR.md +++ b/README_fr-FR.md @@ -235,7 +235,7 @@ console.log(b === c); Quand nous utilisons l'opérateur `==`, il vérifie seulement qu'il s'agisse de la même _valeur_. Les deux ont pour valeur `3`, donc il retourne `true`. -Cependant, quand on utilise l'opérateur `===`, les 2 valeurs _et_ type doivent être les même. `new Number()` n'est pas un nombre, c'est un **objet**, il retourne `false`. +Cependant, quand on utilise l'opérateur `===`, les 2 valeurs _et_ types doivent être les mêmes. `new Number()` n'est pas un nombre, c'est un **objet**, il retourne `false`.

From ae3e57b0bb06e10612a9b95361d0555f39511d3d Mon Sep 17 00:00:00 2001 From: Tanguy Coppin Date: Thu, 4 Jul 2019 21:42:24 +0200 Subject: [PATCH 211/915] Update README_fr-FR.md Co-Authored-By: Nathanael CHERRIER --- README_fr-FR.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README_fr-FR.md b/README_fr-FR.md index 5e0a8857..24128677 100644 --- a/README_fr-FR.md +++ b/README_fr-FR.md @@ -270,7 +270,7 @@ freddie.colorChange("orange"); #### Réponse: D -La fonction `colorChange` est statique. Les méthodes statiques sont désignée pour vivre seulement dans le constructeur qui les a créer et ne peuvent pas être transférer aux enfants. Comme `freddie` est un enfant, la fonction n'est pas transférée et non disponible dans l'instance de `freddie` : une erreur `TypeError` est renvoyée. +La fonction `colorChange` est statique. Les méthodes statiques sont désignées pour vivre seulement dans le constructeur qui les a créé et ne peuvent pas être transférer aux enfants. Comme `freddie` est un enfant, la fonction n'est pas transférée et n'est pas disponible dans l'instance de `freddie` : une erreur `TypeError` est renvoyée.

From d341173368448b7921b784f38baf9d46820f73b8 Mon Sep 17 00:00:00 2001 From: Tanguy Coppin Date: Thu, 4 Jul 2019 21:42:41 +0200 Subject: [PATCH 212/915] Update README_fr-FR.md Co-Authored-By: Nathanael CHERRIER --- README_fr-FR.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README_fr-FR.md b/README_fr-FR.md index 24128677..80012ae7 100644 --- a/README_fr-FR.md +++ b/README_fr-FR.md @@ -294,7 +294,7 @@ console.log(greetign); #### Réponse: A -Il affiche l'objet, car on a juste créé un objet vide dnas l'objet global ! Quand on écrit mal `greeting` en `greetign`, JaveScript l'interprète comme il le voit `global.greetign = {}` (ou `window.greetign = {}` dans le navigateur). +Il affiche l'objet, car on a juste créé un objet vide dans l'objet global ! Quand on écrit mal `greeting` en `greetign`, JavaScript l'interprète comme il le voit `global.greetign = {}` (ou `window.greetign = {}` dans le navigateur). Pour éviter cela, on peut utiliser `"use strict"`. Cela nous assure de devoir déclarer la variable avant de lui assigné une valeur. From 40dff9f36bffc99d3f7dc3809c118301bde80e92 Mon Sep 17 00:00:00 2001 From: Tanguy Coppin Date: Thu, 4 Jul 2019 21:42:55 +0200 Subject: [PATCH 213/915] Update README_fr-FR.md Co-Authored-By: Nathanael CHERRIER --- README_fr-FR.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README_fr-FR.md b/README_fr-FR.md index 80012ae7..872a71eb 100644 --- a/README_fr-FR.md +++ b/README_fr-FR.md @@ -296,7 +296,7 @@ console.log(greetign); Il affiche l'objet, car on a juste créé un objet vide dans l'objet global ! Quand on écrit mal `greeting` en `greetign`, JavaScript l'interprète comme il le voit `global.greetign = {}` (ou `window.greetign = {}` dans le navigateur). -Pour éviter cela, on peut utiliser `"use strict"`. Cela nous assure de devoir déclarer la variable avant de lui assigné une valeur. +Pour éviter cela, on peut utiliser `"use strict"`. Cela nous assure de devoir déclarer la variable avant de lui assigner une valeur.

From bce2b12b982e56ad788eea6804f840b03f494295 Mon Sep 17 00:00:00 2001 From: Tanguy Coppin Date: Thu, 4 Jul 2019 21:43:12 +0200 Subject: [PATCH 214/915] Update README_fr-FR.md Co-Authored-By: Nathanael CHERRIER --- README_fr-FR.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README_fr-FR.md b/README_fr-FR.md index 872a71eb..688b805a 100644 --- a/README_fr-FR.md +++ b/README_fr-FR.md @@ -325,7 +325,7 @@ bark.animal = "dog"; C'est possible en JavaScript, car les fonctions sont des objets ! (Tout ce qui n'est pas de type primitif est un objet) -Une fonction est un type special d'objet. Le code que vous écrivez vous-même n'est pas la fonction. La fonction est un objet avec des propriétées. Cette propriétée est invocable. +Une fonction est un type spécial d'objet. Le code que vous écrivez vous-même n'est pas la fonction. La fonction est un objet avec des propriétés. Cette propriété est invocable.

From cf7f1f49b347939aeef719131b8536250afe0003 Mon Sep 17 00:00:00 2001 From: Tanguy Coppin Date: Thu, 4 Jul 2019 21:43:37 +0200 Subject: [PATCH 215/915] Update README_fr-FR.md Co-Authored-By: Nathanael CHERRIER --- README_fr-FR.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README_fr-FR.md b/README_fr-FR.md index 688b805a..4a762115 100644 --- a/README_fr-FR.md +++ b/README_fr-FR.md @@ -467,7 +467,7 @@ sum(1, "2"); JavaScript est un **langage à types dynamiques** : nous n'avons pas besoin de spécifier le types des variables. Les valeurs peuvent être automatiquement convertir vers les autres types sans que vous le sachiez, c'est ce que l'on appelle _la conversion de types implicites_ _(implicit type coercion)_. -Dans cette exemple, JavaScript convertit le nombre `1` en un chaine de caractère, afin que la fonction est du sens et puisse renvoyer un valeur. Durant l'addition d'un type numérique (`1`) et d'un type chaine de caractère (`'2'`), le nombre est traité comme une chaine de caractère. Nous pouvons concaténer les chaines de caractères comme `"Hello" + "World"`, c'est donc ce qui arrive ici avec `"1" + "2"` qui retourne `"12"`. +Dans cette exemple, JavaScript convertit le nombre `1` en un chaine de caractère, afin que la fonction ait du sens et puisse renvoyer une valeur. Durant l'addition d'un type numérique (`1`) et d'un type chaine de caractère (`'2'`), le nombre est traité comme une chaine de caractère. Nous pouvons concaténer les chaines de caractères comme `"Hello" + "World"`, c'est donc ce qui arrive ici avec `"1" + "2"` qui retourne `"12"`.

From 3da6cdb3a8f6c3fc8bc2b3654efa2e17bb2d2ddd Mon Sep 17 00:00:00 2001 From: Tanguy Coppin Date: Thu, 4 Jul 2019 21:43:59 +0200 Subject: [PATCH 216/915] Update README_fr-FR.md Co-Authored-By: Nathanael CHERRIER --- README_fr-FR.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README_fr-FR.md b/README_fr-FR.md index 4a762115..5f875098 100644 --- a/README_fr-FR.md +++ b/README_fr-FR.md @@ -366,7 +366,7 @@ Person.prototype.getFullName = function() { }; ``` -rendra fonctionnel `member.getFullName`. Pourquoi est-ce benifique ? Disons que nous ajoutons cette méthode au constructeur directement. Peut-être que toutes les instances de `Person` n'ont pas besoin de cette méthode. Cela fera perdre de l'espace mémoire, car elles auront tous cette propriété, ce qui prendra de l'espace mémoire pour chaque instance. Alors que, si nous ajoutons la méthode au prototype uniquement, nous n'utilisons qu'un seul slot mémoire, et ils y auront tous accès ! +rendra fonctionnel `member.getFullName`. Pourquoi est-ce bénéfique ? Disons que nous ajoutons cette méthode au constructeur directement. Peut-être que toutes les instances de `Person` n'ont pas besoin de cette méthode. Cela fera perdre de l'espace mémoire, car elles auront tous cette propriété, ce qui prendra de l'espace mémoire pour chaque instance. Alors que, si nous ajoutons la méthode au prototype uniquement, nous n'utilisons qu'un seul slot mémoire, et ils y auront tous accès !

From 3468e7816f8ba9a253c7546c043923aba1ed235b Mon Sep 17 00:00:00 2001 From: Tanguy Coppin Date: Thu, 4 Jul 2019 21:44:19 +0200 Subject: [PATCH 217/915] Update README_fr-FR.md Co-Authored-By: Nathanael CHERRIER --- README_fr-FR.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README_fr-FR.md b/README_fr-FR.md index 5f875098..a8b27659 100644 --- a/README_fr-FR.md +++ b/README_fr-FR.md @@ -398,7 +398,7 @@ console.log(sarah); #### Réponse: A -Pour `sarah`, nous n'avons pas utilisé le mot clé `new`. Quand nous utilisons `new`, il fait référence à un nouvel objet vide que nous créons. Cependant so nous n'ajoutons pas `new` il réfère à **l'objet global** ! +Pour `sarah`, nous n'avons pas utilisé le mot clé `new`. Quand nous utilisons `new`, il fait référence à un nouvel objet vide que nous créons. Cependant, nous n'ajoutons pas `new`. Il réfère à **l'objet global** ! Nous disons que `this.firstName` est égal à `"Sarah"` et que `this.lastName` est égal à `Smith`. Ce que nous faisons c'est définir `global.firstName = 'Sarah'` et `global.lastName = 'Smith'`. La variable `sarah` elle-même reste à `undefined`. From e21d743c8d109b86f5d330fc69df471cdd239651 Mon Sep 17 00:00:00 2001 From: Tanguy Coppin Date: Thu, 4 Jul 2019 21:44:35 +0200 Subject: [PATCH 218/915] Update README_fr-FR.md Co-Authored-By: Nathanael CHERRIER --- README_fr-FR.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README_fr-FR.md b/README_fr-FR.md index a8b27659..349c540b 100644 --- a/README_fr-FR.md +++ b/README_fr-FR.md @@ -419,7 +419,7 @@ Nous disons que `this.firstName` est égal à `"Sarah"` et que `this.lastName` e #### Réponse: D -Durant la phase de **capture** _(capturing)_, l'événement passe par les événements parent jusqu'à l'élément ciblé. Il attient ensuite l'élément **ciblé** _(target)_, et commence à **bouillonner** _(bubbling)_. +Durant la phase de **capture** _(capturing)_, l'événement passe par les éléments parents jusqu'à l'élément ciblé. Il atteint ensuite l'élément **ciblé** _(target)_, et commence à **bouillonner** _(bubbling)_. From a7f5c3cfa1d7ba6867729893c7869c51dc13b615 Mon Sep 17 00:00:00 2001 From: Tanguy Coppin Date: Thu, 4 Jul 2019 21:44:54 +0200 Subject: [PATCH 219/915] Update README_fr-FR.md Co-Authored-By: Nathanael CHERRIER --- README_fr-FR.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README_fr-FR.md b/README_fr-FR.md index 349c540b..7a7aded1 100644 --- a/README_fr-FR.md +++ b/README_fr-FR.md @@ -465,7 +465,7 @@ sum(1, "2"); #### Réponse: C -JavaScript est un **langage à types dynamiques** : nous n'avons pas besoin de spécifier le types des variables. Les valeurs peuvent être automatiquement convertir vers les autres types sans que vous le sachiez, c'est ce que l'on appelle _la conversion de types implicites_ _(implicit type coercion)_. +JavaScript est un **langage à types dynamiques** : nous n'avons pas besoin de spécifier le types des variables. Les valeurs peuvent être automatiquement converties vers les autres types sans que vous le sachiez, c'est ce que l'on appelle _la conversion de types implicites_ _(implicit type coercion)_. Dans cette exemple, JavaScript convertit le nombre `1` en un chaine de caractère, afin que la fonction ait du sens et puisse renvoyer une valeur. Durant l'addition d'un type numérique (`1`) et d'un type chaine de caractère (`'2'`), le nombre est traité comme une chaine de caractère. Nous pouvons concaténer les chaines de caractères comme `"Hello" + "World"`, c'est donc ce qui arrive ici avec `"1" + "2"` qui retourne `"12"`. From 7b027c51b8e5c31111a8a3b63e7ef3c301718567 Mon Sep 17 00:00:00 2001 From: Tanguy Coppin Date: Thu, 4 Jul 2019 22:11:58 +0200 Subject: [PATCH 220/915] FR : Translate the first 63 questions --- README.md | 1 + README_fr-FR.md | 760 +++++++++++++++++++++++++++++++++++++++++++++--- 2 files changed, 713 insertions(+), 48 deletions(-) diff --git a/README.md b/README.md index d4fffadb..687b0c24 100644 --- a/README.md +++ b/README.md @@ -17,6 +17,7 @@ List of available languages: * [Tiếng Việt](./README-vi.md) * [Українська мова](./README-ua_UA.md) * [Português Brasil](./README_pt_BR.md) +* [Français](./README_fr-FR.md) --- diff --git a/README_fr-FR.md b/README_fr-FR.md index 5c5c234f..9dc016b9 100644 --- a/README_fr-FR.md +++ b/README_fr-FR.md @@ -6,10 +6,17 @@ 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: -[English](./README.md) -[中文版本](./README-zh_CN.md) -[Русский](./README_ru-RU.md) -[Western Balkan](./README-bs.md) +* [English](./README.md) +* [中文版本](./README-zh_CN.md) +* [Versión en español](./README-ES.md) +* [日本語](./README-ja_JA.md) +* [한국어](./README-ko_KR.md) +* [Русский](./README_ru-RU.md) +* [Western Balkan](./README-bs_BS.md) +* [Deutsch](./README-de_DE.md) +* [Tiếng Việt](./README-vi.md) +* [Українська мова](./README-ua_UA.md) +* [Português Brasil](./README_pt_BR.md) --- @@ -34,7 +41,7 @@ sayHi();
Réponse

-#### Réponse: D +#### Réponse : D Dans la fonction, nous déclarons en premier la variable `name` grâce au mot clé `var`. Cela signifie que la variable est "levée" _(hoisted)_ (l'espace mémoire est définie à la phase de création) avec pour valeur par défaut `undefined`, jusqu'à ce que le script atteigne la ligne de définition de la variable. Nous n'avons pas encore défini la variable lorsque nous essayons d'afficher la variable `name`, donc elle a toujours la valeur `undefined`. @@ -64,7 +71,7 @@ for (let i = 0; i < 3; i++) {

Réponse

-#### Réponse: C +#### Réponse : C À cause du système de queue dans JavaScript, la fonction de rappel _(callback)_ du `setTimeout` est appelée _après_ que la boucle soit exécutée. Comme la variable `i` dans la première boucle est déclarée avec le mot-clé `var`, c'est une variable globale. Pendant la boucle, nous incrémentons la valeur de `i` de `1` à chaque fois, en utilisant l'opérateur arithmétique `++`. Lorsque la fonction de rappel _(callback)_ du `setTimeout` est invoquée, `i` est égal à `3` dans le premier exemple. @@ -98,7 +105,7 @@ shape.perimeter();

Réponse

-#### Réponse: B +#### Réponse : B Notez que la valeur de `diameter` est une fonction régulière, alors que celle de `perimeter` est une fonction fléchée. @@ -125,7 +132,7 @@ Il n'y a pas de valeur `radius` dans cet objet, on retournera `undefined`.

Réponse

-#### Réponse: A +#### Réponse : A L'opérateur arithmétique `+` essait de convertir un opérande en une valeur numérique. `true` devient `1`, et `false` devient `0`. @@ -157,7 +164,7 @@ const mouse = {

Réponse

-#### Réponse: A +#### Réponse : A En JavaScript, toutes les clés d'objet sont des chaines de caractères (sauf si c'est un Symbol). Bien que nous ne puissions pas les _typer_ comme des chaines de caractères, elles sont converties en chaines de caractères sous le capot. @@ -194,7 +201,7 @@ console.log(d.greeting);

Réponse

-#### Réponse: A +#### Réponse : A En JavaScript, tous les objets interagissent par _référence_ lorsqu'on les définit égaux les uns aux autres. @@ -229,7 +236,7 @@ console.log(b === c);

Réponse

-#### Réponse: C +#### Réponse : C `new Number()` est une fonction globale. Bien qu'il ressemble à un nombre, ce n'en est pas vraiment un : il a une poignée de fonctionnalités supplémentaire et est un objet. @@ -268,7 +275,7 @@ freddie.colorChange("orange");

Réponse

-#### Réponse: D +#### Réponse : D La fonction `colorChange` est statique. Les méthodes statiques sont désignées pour vivre seulement dans le constructeur qui les a créé et ne peuvent pas être transférer aux enfants. Comme `freddie` est un enfant, la fonction n'est pas transférée et n'est pas disponible dans l'instance de `freddie` : une erreur `TypeError` est renvoyée. @@ -292,7 +299,7 @@ console.log(greetign);

Réponse

-#### Réponse: A +#### Réponse : A Il affiche l'objet, car on a juste créé un objet vide dans l'objet global ! Quand on écrit mal `greeting` en `greetign`, JavaScript l'interprète comme il le voit `global.greetign = {}` (ou `window.greetign = {}` dans le navigateur). @@ -321,7 +328,7 @@ bark.animal = "dog";

Réponse

-#### Réponse: A +#### Réponse : A C'est possible en JavaScript, car les fonctions sont des objets ! (Tout ce qui n'est pas de type primitif est un objet) @@ -356,7 +363,7 @@ console.log(member.getFullName());

Réponse

-#### Réponse: A +#### Réponse : A 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, @@ -396,7 +403,7 @@ console.log(sarah);

Réponse

-#### Réponse: A +#### Réponse : A Pour `sarah`, nous n'avons pas utilisé le mot clé `new`. Quand nous utilisons `new`, il fait référence à un nouvel objet vide que nous créons. Cependant, nous n'ajoutons pas `new`. Il réfère à **l'objet global** ! @@ -417,7 +424,7 @@ Nous disons que `this.firstName` est égal à `"Sarah"` et que `this.lastName` e

Réponse

-#### Réponse: D +#### Réponse : D Durant la phase de **capture** _(capturing)_, l'événement passe par les éléments parents jusqu'à l'élément ciblé. Il atteint ensuite l'élément **ciblé** _(target)_, et commence à **bouillonner** _(bubbling)_. @@ -436,7 +443,7 @@ Durant la phase de **capture** _(capturing)_, l'événement passe par les élém

Réponse

-#### Réponse: B +#### Réponse : B Tous les objets ont des prototypes, excepté pour les **objets standards**. Les objets standards ont accès à certaines méthodes et propriétés, comme `.toString`. C'est pour cette raison que vous pouvez utiliser les méthodes natives de JavaScript ! Toutes ces méthodes sont disponibles dans le prototype. Bien que JavaScript ne trouve pas la fonction dans l'objet, il parcourt le prototype et la méthode afin de la rendre accessible. @@ -463,7 +470,7 @@ sum(1, "2");

Réponse

-#### Réponse: C +#### Réponse : C JavaScript est un **langage à types dynamiques** : nous n'avons pas besoin de spécifier le types des variables. Les valeurs peuvent être automatiquement converties vers les autres types sans que vous le sachiez, c'est ce que l'on appelle _la conversion de types implicites_ _(implicit type coercion)_. @@ -491,7 +498,7 @@ console.log(number);

Réponse

-#### Réponse: C +#### Réponse : C L'opérateur arithmétique **postfix** `++` : @@ -532,7 +539,7 @@ getPersonInfo`${person} is ${age} years old`;

Réponse

-#### Réponse: B +#### Réponse : B Si vous utilisez les littéraux de gabarits, la valeur du premier argument sera toujours un tableau de valeurs des chaines de caractère. Le reste des arguments seront les valeurs des expressions utilisées ! @@ -564,7 +571,7 @@ checkAge({ age: 18 });

Réponse

-#### Réponse: C +#### Réponse : C Lorsque l'on teste une égalité, les primitifs sont comparés par leur valeur, alors que les objets sont comparés par leur _référence_. JavaScript vérifie si les objets ont une référence à la même zone de la mémoire.= @@ -595,9 +602,9 @@ getAge(21);

Réponse

-#### Réponse: C +#### Réponse : C -L'opérateur de déstructuration _(spread operator)_ (`...args`) retourne un tableau avec les arguments. Un tableau est un objet, donc `typeof args` retournera `"object"`. +La syntaxe des paramètres du reste _(rest parameters)_ (`...args`) retourne un tableau avec les arguments. Un tableau est un objet, donc `typeof args` retournera `"object"`.

@@ -624,7 +631,7 @@ getAge();
Réponse

-#### Réponse: C +#### Réponse : C Avec `"use strict"`, vous pouvez êtes sûr de ne pas déclarer accidentellement des variables gloables. Nous ne déclarerons jamais la variable `age`, et temps que nous utiliserons `"use strict"`, cela créera une erreur de référence. Si nous n'utilisons pas `"use strict"`, cela fonctionnera et la variable `age` sera attribué à l'objet global. @@ -647,7 +654,7 @@ const sum = eval("10*10+5");

Réponse

-#### Réponse: A +#### Réponse : A `eval` évalue les codes que nous passons en paramètre de type chaîne de caractères. Si c'est une expression, comme dans notre cas, il évaluera l'expression. L'expression est `10 * 10 + 5`, ce qui retourne le nombre `105`. @@ -670,7 +677,7 @@ sessionStorage.setItem("cool_secret", 123);

Réponse

-#### Réponse: B +#### Réponse : B La donnée stocké dans le `sessionStorage` est supprimée après la fermeture de l'onglet. @@ -698,7 +705,7 @@ console.log(num);

Réponse

-#### Réponse: B +#### Réponse : B Avec le mot clé `var`, vous pouvez déclarer plusieurs variables avec le même nom. La variable aura pour valeur la dernière assignée. @@ -729,7 +736,7 @@ set.has(1);

Réponse

-#### Réponse: C +#### Réponse : C Toutes les clés d'objet (à l'exception des symboles) sont des chaînes de caractères sous le capot, même si vous ne les tapez pas vous-même en tant que chaîne. C'est pourquoi `obj.hasOwnProperty("1")` renvoie également la valeur `true`. @@ -755,7 +762,7 @@ console.log(obj);

Réponse

-#### Réponse: C +#### Réponse : C Si vous avez deux clés portant le même nom, la clé sera remplacée. Elle sera toujours dans sa première position, mais avec la dernière valeur spécifiée. @@ -773,7 +780,7 @@ Si vous avez deux clés portant le même nom, la clé sera remplacée. Elle sera

Réponse

-#### Réponse: A +#### Réponse : A Le contexte d'exécution de base est le contexte d'exécution global : c'est ce qui est accessible partout dans votre code. @@ -799,7 +806,7 @@ for (let i = 1; i < 5; i++) {

Réponse

-#### Réponse: C +#### Réponse : C L'instruction `continue` ignore une itération si une condition donnée renvoie `true`. @@ -828,7 +835,7 @@ name.giveLydiaPizza();

Réponse

-#### Réponse: A +#### Réponse : A `String` est un constructeur intégré, auquel nous pouvons ajouter des propriétés. Je viens d'ajouter une méthode à son prototype. Les chaînes de caractère primitives sont automatiquement converties en un objet chaîne, généré par la fonction prototype de chaîne. Ainsi, toutes les chaînes (objets de chaîne) ont accès à cette méthode ! @@ -858,7 +865,7 @@ console.log(a[b]);

Réponse

-#### Réponse: B +#### Réponse : B Les clés d'objet sont automatiquement converties en chaînes de caractères. Nous essayons de définir un objet en tant que clé de l'objet `a`, avec la valeur `123`. @@ -891,7 +898,7 @@ baz();

Réponse

-#### Réponse: B +#### Réponse : B Nous avons une fonction `setTimeout` et nous l'avons d'abord appelée. Pourtant, il a été affiché en dernier. @@ -944,7 +951,7 @@ C'est ici qu'une boucle d'événement commence à fonctionner. La **boucle d'év

Réponse

-#### Réponse: C +#### Réponse : C L'élément imbriqué le plus profond qui a provoqué l'événement est la cible de l'événement. Vous pouvez arrêter le bouillonnement _(bubbling)_ en utilisant `event.stopPropagation`. @@ -971,7 +978,7 @@ L'élément imbriqué le plus profond qui a provoqué l'événement est la cible

Réponse

-#### Réponse: A +#### Réponse : A Si nous cliquons sur `p`, nous verrons deux lignes : `p` et `div`. Lors de la propagation d'un événement, il y a 3 phases: capture, cible et bouillonnement _(bubbling)_. Par défaut, les gestionnaires d'événements sont exécutés dans la phase de bouillonnement (sauf si vous définissez `useCapture` sur` true`). Il va de l'élément imbriqué le plus profond vers l'extérieur. @@ -1001,7 +1008,7 @@ sayHi.bind(person, 21);

Réponse

-#### Réponse: D +#### Réponse : D Avec les deux, nous pouvons transmettre l'objet auquel nous voulons que le mot clé `this` fasse référence. Cependant, `.call` est aussi _exécuté immédiatement_ ! @@ -1030,7 +1037,7 @@ typeof sayHi();

Réponse

-#### Réponse: B +#### Réponse : B La fonction `sayHi` renvoie la valeur renvoyée par la fonction immédiatement appelée (IIFE). Cette fonction a renvoyé `0`, qui est du type `"nombre"`. @@ -1060,7 +1067,7 @@ undefined;

Réponse

-#### Réponse: A +#### Réponse : A Il n'y a que six valeurs de fausses : @@ -1092,7 +1099,7 @@ console.log(typeof typeof 1);

Réponse

-#### Réponse: B +#### Réponse : B `typeof 1` retourne `"number"`. `typeof "number"` retourne `"string"` @@ -1118,7 +1125,7 @@ console.log(numbers);

Réponse

-#### Réponse: C +#### Réponse : C Lorsque vous définissez une valeur sur un élément d'un tableau qui dépasse la longueur du tableau, JavaScript crée un quelque chose appelé "emplacements vides". Ceux-ci ont en fait la valeur `undefined`, mais vous verrez quelque chose comme : @@ -1155,7 +1162,7 @@ en fonction de l'endroit où vous l'exécutez (différent pour chaque navigateur

Réponse

-#### Réponse: A +#### Réponse : A Le bloc `catch` reçoit l'argument `x`. Ce n'est pas le même `x` que la variable que nous passons en arguments. Cette variable `x` a une portée de bloc. @@ -1178,7 +1185,7 @@ En dehors du bloc `catch`, `x` est toujours `undefined` et `y` est égal à `2`.

Réponse

-#### Réponse: A +#### Réponse : A JavaScript n'a que des types et des objets primitifs. @@ -1210,7 +1217,7 @@ Ce qui différencie une primitive d'un objet, c'est que les primitives n'ont auc

Réponse

-#### Réponse: C +#### Réponse : C `[1, 2]` est notre valeur initiale. C'est la valeur avec laquelle nous commençons et la valeur du tout premier `acc`. Au premier tour, `acc` est `[1,2]` et `cur` est `[0, 1]`. Nous les concaténons, ce qui donne `[1, 2, 0, 1]`. @@ -1237,7 +1244,7 @@ Ensuite, `acc` est `[1, 2, 0, 1]` et `cur` est `[2, 3]`. Nous les concaténons e

Réponse

-#### Réponse: B +#### Réponse : B `null` est faux. `!null` retourne `true`. `!true` retourne `false`. @@ -1264,7 +1271,7 @@ setInterval(() => console.log("Hi"), 1000);

Réponse

-#### Réponse: A +#### Réponse : A Il retourne un identifiant unique. Cet identifiant peut être utilisé pour effacer cet interval avec la fonction `clearInterval()`. @@ -1287,9 +1294,666 @@ Il retourne un identifiant unique. Cet identifiant peut être utilisé pour effa

Réponse

-#### Réponse: A +#### Réponse : A Une chaîne de caractère est itérable. L'opérateur de déconstruction transforme chaque caractère d'un itérable en un élément.

+ +--- + +###### 44. Quelle est la sortie ? + +```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éponse +

+ +#### Réponse : C + +Les fonctions régulières ne peuvent pas être arrêtées à mi-parcours après l'invocation. Cependant, une fonction de générateur peut être "arrêtée" à mi-chemin et continuer plus tard à partir de son point d'arrêt. Chaque fois qu'une fonction génératrice rencontre un mot-clé `yield`, elle renvoie la valeur spécifiée après celui-ci. Notez que la fonction du générateur dans ce cas ne _return_ pas la valeur, il _yields_ la valeur. + +Premièrement, nous initialisons la fonction du générateur avec `i` égal à` 10`. Nous appelons la fonction génératrice en utilisant la méthode `next()`. La première fois que nous appelons la fonction de générateur, `i` est égal à `10`. Il rencontre le premier mot-clé `yield` : il donne la valeur de `i`. Le générateur est maintenant "en pause" et `10` est affiché. + +Ensuite, nous appelons à nouveau la fonction avec la méthode `next()`. Il commence à continuer là où il s’était arrêté précédemment, toujours avec `i` égal à `10`. Maintenant, il rencontre le prochain mot-clé `yield` et donne `i * 2`. `i` est égal à `10`, donc il renvoie `10 * 2`, ce qui correspond à `20`. Cela donne `10, 20`. + +

+
+ +--- + +###### 45. Qu'est-ce que cela retourne ? + +```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éponse +

+ +#### Réponse : B + +Lorsque nous passons plusieurs promesses à la méthode `Promise.race`, elle résout/rejette la promesse _first_ qui résout/rejette. Nous passons, à la méthode `setTimeout`, un timer: 500 ms pour la première promesse (`firstPromise`), et 100 ms pour la deuxième promesse (`secondPromise`). Cela signifie que le `secondPromise` se résout en premier avec la valeur de `'two'`. `res` contient maintenant la valeur de `'deux'`, qui est affiché. + +

+
+ +--- + +###### 46. Quelle est la sortie ? + +```javascript +let person = { name: "Lydia" }; +const members = [person]; +person = null; + +console.log(members); +``` + +- A: `null` +- B: `[null]` +- C: `[{}]` +- D: `[{ name: "Lydia" }]` + +
Réponse +

+ +#### Réponse : D + +Tout d'abord, nous déclarons une variable `person` avec la valeur d'un objet possédant une propriété `name`. + + + +Ensuite, nous déclarons une variable appelée `membres`. Nous définissons le premier élément de ce tableau égal à la valeur de la variable `person`. Les objets interagissent par référence quand ils sont égaux. Lorsque vous affectez une référence d'une variable à une autre, vous créez une copie de cette référence. (notez qu'ils n'ont pas la même référence !) + + + +Ensuite, nous définissons la variable `person` égale à `null`. + + + +Nous modifions seulement la valeur de la variable `person`, et non le premier élément du tableau, car cet élément a une référence (copiée) différente de l'objet. Le premier élément de `members` conserve sa référence à l'objet d'origine. Lorsque nous affichons le tableau `members`, le premier élément contient toujours la valeur de l'objet, qui est affiché. + +

+
+ +--- + +###### 47. Quelle est la sortie ? + +```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éponse +

+ +#### Réponse : B + +Avec une boucle `for-in`, nous pouvons parcourir les clés d'objet, dans ce cas `name` et `age`. Sous le capot, les clés d'objet sont des chaînes (si elles ne sont pas un symbole). A chaque boucle, nous définissons la valeur de `item` égal à la clé courante sur laquelle elle est entrain d'itéré. Premièrement, `item` est égal à `name` et est affiché. Ensuite, `item` est égal à `age`, qui est affiché. + +

+
+ +--- + +###### 48. Quelle est la sortie ? + +```javascript +console.log(3 + 4 + "5"); +``` + +- A: `"345"` +- B: `"75"` +- C: `12` +- D: `"12"` + +
Réponse +

+ +#### Réponse : B + +L'associativité des opérateurs correspond à l'ordre dans lequel le compilateur évalue les expressions, de gauche à droite ou de droite à gauche. Cela se produit uniquement si tous les opérateurs ont la même priorité. Nous n'avons qu'un type d'opérateur : `+`. De plus, l'associativité est de gauche à droite. + +`3 + 4` est évalué en premier. Cela donne le nombre `7`. + +`7 + '5'` donne `'75'` à cause de la conversion. JavaScript convertit le nombre `7` en une chaîne, voir question 15. Nous pouvons concaténer deux chaînes en utilisant l'opérateur `+`. `"7" + "5"` a pour résultat `"75"`. + +

+
+ +--- + +###### 49. Quelle est la valeur de `num` ? + +```javascript +const num = parseInt("7*6", 10); +``` + +- A: `42` +- B: `"42"` +- C: `7` +- D: `NaN` + +
Réponse +

+ +#### Réponse : C + +Seuls les premiers nombres de la chaîne sont renvoyés. Basé sur la base dix (le deuxième argument permettant de spécifier le type de nombre que nous voulons analyser: base 10, hexadécimal, octal, binaire, etc.), `parseInt` vérifie si les caractères de la chaîne sont valides. Une fois qu'il rencontre un caractère qui n'est pas un nombre valide dans la base, il arrête l'analyse et ignore les caractères suivants. + +`*` n'est pas un nombre valide. Il analyse seulement `7` dans la décimale `7`. `num` contient maintenant la valeur de` 7`. + +

+
+ +--- + +###### 50. Quelle est la sortie ? + +```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éponse +

+ +#### Réponse : C + +Lors du l'utilisation de `map` sur le tableau, la valeur de `num` est égale à l’élément sur lequel elle est en train de boucler. Dans ce cas, les éléments sont des nombres. La condition de l'instruction si `typeof num === "numéro"` renvoie `true`. La fonction map crée un nouveau tableau et insère les valeurs renvoyées par la fonction. + +Cependant, nous ne renvoyons pas de valeur. Lorsque nous ne renvoyons pas de valeur à partir de la fonction, la fonction renvoie `undefined`. Le bloc de fonction est appelé pour chaque élément du tableau. Ainsi, pour chaque élément, nous renvoyons `undefined`. + +

+
+ +--- + +###### 51. Quelle est la sortie ? + +```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éponse +

+ +#### Réponse : A + +Les arguments sont passés par _valeur_, à moins que leur valeur ne soit un objet, ils sont passés par _réfèrence_. `birthYear` est passée par valeur, car c'est une chaîne, pas un objet. Lorsque nous passons des arguments par valeur, une copie de cette valeur est créée (voir question 46). + +La variable `birthYear` a une référence à la valeur `"1997"`. L'argument `year` fait également référence à la valeur `"1997"`, mais il ne s'agit pas de la même valeur que celle de `birthYear`. Lorsque nous mettons à jour la valeur de `year` en plaçant `year` égal à `"1998"`, nous ne mettons à jour que la valeur de `year`. `birthYear` est toujours égal à `"1997"`. + +La valeur de `person` est un objet. L'argument `membre` a une référence (copiée) au même objet. Lorsque nous modifions une propriété de l'objet, `membre` a une référence à la valeur de` person` sera également modifiée, puisqu'elles ont toutes les deux une référence au même objet. La propriété `name` de `person` est maintenant égale à la valeur `"Lydia"`. + +

+
+ +--- + +###### 52. Quelle est la sortie ? + +```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éponse +

+ +#### Réponse : D + +Avec l'instruction `throw`, nous pouvons créer des erreurs personnalisées. Avec cette déclaration, vous pouvez lancer des exceptions. Une exception peut être une chaîne, un numéro, un booléen ou un objet. Dans ce cas, notre exception est la chaîne `'Hello world'`. + +Avec l'instruction `catch`, nous pouvons spécifier quoi faire si une exception est levée dans le bloc `try`. Une exception est levée : la chaîne `'Hello world'`. `e` est maintenant égal à cette chaîne, que nous affichons. Il en résulte `'Oh an error: Hello world'`. + +

+
+ +--- + +###### 53. Quelle est la sortie ? + +```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éponse +

+ +#### Réponse : B + +Lorsque vous retournez une propriété, la valeur de la propriété est égale à la valeur _retournée_ et non à la valeur définie dans la fonction constructeur. Nous renvoyons la chaîne `"Maserati"`, donc `myCar.make` est égal à `"Maserati"`. + +

+
+ +--- + +###### 54. Quelle est la sortie ? + +```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éponse +

+ +#### Réponse : A + +`let x = y = 10;` est en réalité un raccourci pour : + +```javascript +y = 10; +let x = y; +``` + +Lorsque nous définissons `y` égal à `10`, nous ajoutons en fait une propriété `y` à l'objet global (`window` dans le navigateur,` global` dans NodeJS). Dans un navigateur, `window.y` est égal à `10`. + +Ensuite, nous déclarons une variable `x` avec la valeur de `y`, qui est `10`. Les variables déclarées avec le mot-clé `let` ont une portée de bloc, elles ne sont définies que dans le bloc dans lequel elles sont déclarées; la fonction immédiatement invoquée (IIFE) dans ce cas. Lorsque nous utilisons l'opérateur `typeof`, l'opérande `x` n'est pas défini: nous essayons d'accéder à `x` en dehors du bloc dans lequel il est déclaré. Cela signifie que `x` n'est pas défini. Les valeurs auxquelles aucune valeur n'a été attribuée ni déclarée sont du type `"undefined"`. `console.log (typeof x)` renvoie `"undefined"`. + +Cependant, nous avons créé une variable globale `y` lorsque `y` est égal à `10`. Cette valeur est accessible n'importe où dans notre code. `y` est défini et contient une valeur de type `"number"`. `console.log (typeof y)` renvoie `"number"`. + +

+
+ +--- + +###### 55. Quelle est la sortie ? + +```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éponse +

+ +#### Réponse : A + +Nous pouvons supprimer des propriétés d'objets en utilisant le mot-clé `delete`, également dans le prototype. En supprimant une propriété dans le prototype, elle n’est plus disponible dans la chaîne de prototypes. Dans ce cas, la fonction `bark` n'est plus disponible dans le prototype après `delete Dog.prototype.bark`, mais nous essayons toujours d'y accéder. + +Lorsque nous essayons d'appeler quelque chose qui n'est pas une fonction, un `TypeError` est levé. Dans ce cas, `TypeError: pet.bark n'est pas une fonction`, puisque` pet.bark` est `undefined`. + +

+
+ +--- + +###### 56. Quelle est la sortie ? + +```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éponse +

+ +#### Réponse : D + +L'objet `Set` est une collection de valeurs _uniques_ : une valeur ne peut apparaître qu'une seule fois dans un ensemble. + +Nous avons passé l'itérable `[1, 1, 2, 3, 4]` avec une valeur dupliquée `1`. Puisque nous ne pouvons pas avoir deux valeurs identiques dans un ensemble, l'une d'entre elles est supprimée. Cela donne `{1, 2, 3, 4}`. + +

+
+ +--- + +###### 57. Quelle est la sortie ? + +```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éponse +

+ +#### Réponse : C + +Un module importé est _en lecture seule_ : vous ne pouvez pas modifier le module importé. Seul le module qui les exporte peut en changer la valeur. + +Lorsque nous essayons d'incrémenter la valeur de `myCounter`, une erreur est générée : `myCounter` est en lecture seule et ne peut pas être modifié. + +

+
+ +--- + +###### 58. Quelle est la sortie ? + +```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éponse +

+ +#### Réponse : A + +L'opérateur `delete` renvoie une valeur booléenne : `true` en cas de suppression réussie, sinon il renvoie `false`. Toutefois, les variables déclarées avec les mots clés `var`,` const` ou `let` ne peuvent pas être supprimées à l'aide de l'opérateur` delete`. + +La variable `name` a été déclarée avec un mot-clé `const`. Par conséquent, sa suppression a échoué : `false` est renvoyé. Lorsque nous définissons `age` égal à `21`, nous avons en fait ajouté une propriété appelée `age` à l'objet global. De cette façon, vous pouvez supprimer des propriétés d’objets, ainsi que de l’objet global, pour que `delete age` renvoie` true`. + +

+
+ +--- + +###### 59. Quelle est la sortie ? + +```javascript +const numbers = [1, 2, 3, 4, 5]; +const [y] = numberes; + +console.log(y); +``` + +- A: `[[1, 2, 3, 4, 5]]` +- B: `[1, 2, 3, 4, 5]` +- C: `1` +- D: `[1]` + +
Réponse +

+ +#### Réponse : C + +Nous pouvons décompresser les valeurs des tableaux ou les propriétés des objets en les détruisant. Par exemple : + +```javascript +[a, b] = [1, 2]; +``` + + + +La valeur de `a` est maintenant `1` et la valeur de `b` est maintenant `2`. Ce que nous avons réellement fait dans la question, c'est : + +```javascript +[y] = [1, 2, 3, 4, 5]; +``` + + + +Cela signifie que la valeur de `y` est égale à la première valeur du tableau, qui correspond au nombre `1`. Lorsque nous affichons `y`,` 1` est renvoyé. + +

+
+ +--- + +###### 60. Quelle est la sortie ? + +```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éponse +

+ +#### Réponse : B + +Il est possible de combiner des objets en utilisant l'opérateur de déconstruction `...`. Il vous permet de créer des copies des paires clé / valeur d'un objet et de les ajouter à un autre objet. Dans ce cas, nous créons des copies de l'objet `user` et nous les ajoutons à l'objet` admin`. L'objet `admin` contient maintenant les paires clé / valeur copiées, ce qui donne `{admin: true, nom: "Lydia", age: 21}`. + +

+
+ +--- + +###### 61. Quelle est la sortie ? + +```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éponse +

+ +#### Réponse : B + +Avec la méthode `defineProperty`, nous pouvons ajouter de nouvelles propriétés à un objet ou modifier celles existantes. Lorsque nous ajoutons une propriété à un objet en utilisant la méthode `defineProperty`, il s’agit par défaut d'une propriété _non énumérable_. La méthode `Object.keys` renvoie tous les noms de propriétés _énumérable_ à partir d'un objet, dans ce cas uniquement `"name"`. + +Les propriétés ajoutées à l'aide de la méthode `defineProperty` sont immuables par défaut. Vous pouvez remplacer ce comportement en utilisant les propriétés `writeable`, `configurable` et `enumerable`. De cette façon, la méthode `defineProperty` vous donne beaucoup plus de contrôle sur les propriétés que vous ajoutez à un objet. + +

+
+ +--- + +###### 62. Quelle est la sortie ? + +```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éponse +

+ +#### Réponse : A + +Le second argument de `JSON.stringify` est le _replaçant_. Le remplaçant peut être une fonction ou un tableau, et vous permet de contrôler quoi et comment les valeurs doivent être stringifiées. + +Si le remplaçant est un _tableau_, seules les propriétés dont les noms sont inclus dans le tableau seront ajoutées à la chaîne JSON. Dans ce cas, seules les propriétés avec les noms `"level"` et `"health"` sont incluses, `"username"` est exclu. `data` est maintenant égal à `"{"level":19, "health":90}"`. + +Si le remplaceur est une _fonction_, cette fonction est appelée sur chaque propriété de l'objet que vous personnalisez. La valeur renvoyée par cette fonction sera la valeur de la propriété lorsqu'elle sera ajoutée à la chaîne JSON. Si la valeur est `undefined`, cette propriété est exclue de la chaîne JSON. + +

+
+ +--- + +###### 63. Quelle est la sortie ? + +```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éponse +

+ +#### Réponse : A + +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`. + +

+
From 764c52e7f7462c59e7cddde5422db3b3e21777ab Mon Sep 17 00:00:00 2001 From: Do Trung Kien Date: Thu, 4 Jul 2019 13:24:51 +0700 Subject: [PATCH 221/915] add new questions --- README-vi.md | 199 ++++++++++++++++++++++++--------------------------- 1 file changed, 94 insertions(+), 105 deletions(-) diff --git a/README-vi.md b/README-vi.md index bcb536b5..a017dd53 100644 --- a/README-vi.md +++ b/README-vi.md @@ -6,24 +6,11 @@ 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: -* [English](./README.md) -* [中文版本](./README-zh_CN.md) -* [Versión en español](./README-ES.md) -* [日本語](./README-ja_JA.md) -* [한국어](./README-ko_KR.md) -* [Русский](./README_ru-RU.md) -* [Western Balkan](./README-bs_BS.md) -* [Deutsch](./README-de_DE.md) -* [Tiếng Việt](./README-vi.md) -* [Українська мова](./README-ua_UA.md) -* [Português Brasil](./README_pt_BR.md) -* [العربية](./README_AR.md) -* [اللغة العامية - Egyptian Arabic](./README_ar-EG.md) +[English Version](./README.md) --- -###### 1. Ouput là gì? +###### 1. Output là gì? ```javascript function sayHi() { @@ -121,7 +108,7 @@ Khi không có giá trị `radius` tại object đó, nó sẽ trả về `undef --- -###### 4. Ouput là gì? +###### 4. Output là gì? ```javascript +true; @@ -183,7 +170,7 @@ Tuy nhiên, khi chúng ta sử dụng dấu chấm `.`, điều trên không cò --- -###### 6. Ouput là gì? +###### 6. Output là gì? ```javascript let c = { greeting: "Hey!" }; @@ -218,7 +205,7 @@ Khi ta thay đổi giá trị của object, tất cả các biến tham chiếu --- -###### 7. Ouput là gì? +###### 7. Output là gì? ```javascript let a = 3; @@ -251,7 +238,7 @@ Tuy nhiên khi sử dụng phép so sánh `===`, cả _giá trị_ và _kiểu_ --- -###### 8. Ouput là gì? +###### 8. Output là gì? ```javascript class Chameleon { @@ -286,7 +273,7 @@ Hàm `colorChange` là một hàm static (hàm tĩnh). Hàm static được thi --- -###### 9. Ouput là gì? +###### 9. Output là gì? ```javascript let greeting; @@ -341,7 +328,7 @@ Function là một object đặc biệt. Phần code mà bạn viết không ph --- -###### 11. Ouput là gì? +###### 11. Output là gì? ```javascript function Person(firstName, lastName) { @@ -382,7 +369,7 @@ khi này `member.getFullName()` sẽ hoạt động. Tại sao nên làm vậy? --- -###### 12. Ouput là gì? +###### 12. Output là gì? ```javascript function Person(firstName, lastName) { @@ -455,7 +442,7 @@ Tất cả các object đều có prototypes, ngoại trừ **base object**. Obj --- -###### 15. Ouput là gì? +###### 15. Output là gì? ```javascript function sum(a, b) { @@ -484,7 +471,7 @@ Trong ví dụ này, JavaScript sẽ convert số `1` sang dạng string. Mỗi --- -###### 16. Ouput là gì? +###### 16. Output là gì? ```javascript let number = 0; @@ -520,7 +507,7 @@ Vậy kết quả là `0 2 2`. --- -###### 17. Ouput là gì? +###### 17. Output là gì? ```javascript function getPersonInfo(one, two, three) { @@ -551,7 +538,7 @@ Nếu bạn dùng _tagged template literals_, giá trị của đối số đầ --- -###### 18. Ouput là gì? +###### 18. Output là gì? ```javascript function checkAge(data) { @@ -587,7 +574,7 @@ Hai object chúng ta đang so sánh không có được điều đó: object đ --- -###### 19. Ouput là gì? +###### 19. Output là gì? ```javascript function getAge(...args) { @@ -614,7 +601,7 @@ _Spread operator_ (`...args`.) sẽ trả về một mảng các đối số. M --- -###### 20. Ouput là gì? +###### 20. Output là gì? ```javascript function getAge() { @@ -691,7 +678,7 @@ Nếu chúng ta dùng `localStorage`, data sẽ được lưu trữ mãi mãi, t --- -###### 23. Ouput là gì? +###### 23. Output là gì? ```javascript var num = 8; @@ -719,7 +706,7 @@ Bạn không thể làm điều tương tự với `let` hay `const` vì chúng --- -###### 24. Ouput là gì? +###### 24. Output là gì? ```javascript const obj = { 1: "a", 2: "b", 3: "c" }; @@ -750,7 +737,7 @@ Tuy nhiên điều đó không đúng với `set`. Không hề có `'1'` trong s --- -###### 25. Ouput là gì? +###### 25. Output là gì? ```javascript const obj = { a: "one", b: "two", a: "three" }; @@ -792,7 +779,7 @@ Ngữ cảnh thực thi cơ bản chính là ngữ cảnh global: nó là thứ --- -###### 27. Ouput là gì? +###### 27. Output là gì? ```javascript for (let i = 1; i < 5; i++) { @@ -818,7 +805,7 @@ Lệnh `continue` sẽ bỏ qua một vòng lặp nếu điều kiện của nó --- -###### 28. Ouput là gì? +###### 28. Output là gì? ```javascript String.prototype.giveLydiaPizza = () => { @@ -847,7 +834,7 @@ name.giveLydiaPizza(); --- -###### 29. Ouput là gì? +###### 29. Output là gì? ```javascript const a = {}; @@ -881,7 +868,7 @@ Cuối cùng khi gọi `a[b]`, thực chất chính là gọi `a["Object object" --- -###### 30. Ouput là gì? +###### 30. Output là gì? ```javascript const foo = () => console.log("First"); @@ -990,7 +977,7 @@ Nếu ta click vào `p`, ta sẽ thấy hai log: `p` và `div`. Trong chuỗi ev --- -###### 33. Ouput là gì? +###### 33. Output là gì? ```javascript const person = { name: "Lydia" }; @@ -1022,7 +1009,7 @@ Với cả hai, chúng ta có thể đưa vào object để sử dụng từ kh --- -###### 34. Ouput là gì? +###### 34. Output là gì? ```javascript function sayHi() { @@ -1088,7 +1075,7 @@ Function constructors như `new Number` và `new Boolean` đều là _truthy_. --- -###### 36. Ouput là gì? +###### 36. Output là gì? ```javascript console.log(typeof typeof 1); @@ -1112,7 +1099,7 @@ console.log(typeof typeof 1); --- -###### 37. Ouput là gì? +###### 37. Output là gì? ```javascript const numbers = [1, 2, 3]; @@ -1141,7 +1128,7 @@ phụ thuộc vào nơi mà chúng ta chạy chúng (có thể khác nhau tùy m --- -###### 38. Ouput là gì? +###### 38. Output là gì? ```javascript (() => { @@ -1201,7 +1188,7 @@ Primitive types là `boolean`, `null`, `undefined`, `bigint`, `number`, `string` --- -###### 40. Ouput là gì? +###### 40. Output là gì? ```javascript [[0, 1], [2, 3]].reduce( @@ -1231,7 +1218,7 @@ Tiếp tục, `[1, 2, 0, 1]` là `acc` và `[2, 3]` là `cur`. Ta nối chúng l --- -###### 41. Ouput là gì? +###### 41. Output là gì? ```javascript !!null; @@ -1306,7 +1293,7 @@ String là một _iterable_. Thế nên _spread operator_ sẽ map toàn bộ c --- -###### 44. Ouput là gì? +###### 44. Output là gì? ```javascript function* generator(i) { @@ -1323,18 +1310,18 @@ console.log(gen.next().value); - A: `[0, 10], [10, 20]` - B: `20, 20` - C: `10, 20` -- D: `0, 10 và 10, 20` +- D: `0, 10 and 10, 20`
Đáp án

#### Đáp án: 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. +Một hàm bình thường không thể bị dừng giữa chừng khi được gọi. Tuy nhiên một _generator_ thì khác, nó có thể "dừng lại" được, và sau đó nó sẽ tiếp tục từ vị trí nó dừng lại. Mỗi khi một _generator_ gặp một từ khóa `yield`, nó sẽ sinh ra giá trị ngay phía sau nó. Chú ý là _generator_ không _trả về_ giá trị, nó _sinh ra_ giá trị. -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. +Đầu tiên, chúng ta khởi tạo generator với giá trị `i` là `10`. Generator được gọi bằng cách sử dụng phương thức `next()`. Khi lần đầu gọi thì `i` vẫn là `10`. Khi nó bắt gặp từ khóa `yield`: nó sẽ sinh ra giá trị `i`. Generator sẽ được "tạm dừng" tại đây, và ghi ra giá trị `10`. -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`. +Sau đó chung ta tiếp tục gọi generator bằng cách sử dụng tiếp phương thức `next()`. Nó sẽ bắt đầu từ vị trí nó tạm dừng lúc trước, khi `i` vẫn đang là `10`. Và khi nó bắt gặp từ khóa `yield`, nó sẽ sinh ra giá trị `i * 2`. `i` là `10`, nên nó sẽ sinh ra `10 * 2`, tức `20`. Vậy kết quả cuối cùng là `10, 20`.

@@ -1365,14 +1352,14 @@ Promise.race([firstPromise, secondPromise]).then(res => console.log(res)); #### Đáp án: 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. +Khi chúng ta đưa các promise vào trong một hàm `Promise.race`, nó sẽ chỉ resolves hay rejects promise _đầu tiên_ được resolves/rejects. Với hàm `setTimeout`, chúng ta đưa vào một khoảng thời gian: 500 mili giây cho promise đầu tiên (`firstPromise`), và 100 mili giây cho promise thứ hai (`secondPromise`). Nó có nghĩa là `secondPromise` sẽ hoàn thành trước và trả về giá trị `'two'`. `res` khi này sẽ nhận giá trị `'two'` và được in ra console.

--- -###### 46. Ouput là gì? +###### 46. Output là gì? ```javascript let person = { name: "Lydia" }; @@ -1392,26 +1379,26 @@ console.log(members); #### Đáp án: D -First, we declare a variable `person` with the value of an object that has a `name` property. +Đầu tiên, chúng ta khai báo một biến `person` là một object có thuộc tính `name`. -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!) +Sau đó chúng ta khai báo một biến `members`. Ta set giá trị đầu tiên của mảng là giá trị của biến `person`. Khi sử dụng gán bằng, object sẽ được _tham chiếu_ tới object mà nó được gán. Khi ta gán tham chiếu từ một biến sang biến khác, ta tạo ra một bản sao của tham chiếu đó. (nên nhớ rằng đó vẫn là 2 tham chiếu hoàn toàn khác nhau!) -Then, we set the variable `person` equal to `null`. +Sau đó ta set giá trị của `person` bằng `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. +Chúng ta chỉ đơn thuần là thay đổi giá trị của biến `person` mà thôi, chứ không phải giá trị của phần tử đầu tiên ở trong mảng, vì chúng ta có một tham chiếu khác đến object đó. Phần tử đầu tiên của mảng `members` vẫn giữ tham chiêu đến object gốc. Do vậy, khi chúng ta in ra mảng `members`, phần tử đầu tiên sẽ vẫn in ra giá trị của objet gốc.

--- -###### 47. Ouput là gì? +###### 47. Output là gì? ```javascript const person = { @@ -1434,14 +1421,14 @@ for (const item in person) { #### Đáp án: 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. +Với vòng lặp `for-in` chúng ta sẽ lặp qua tất cả các `keys` của object, trong trường hợp này là `name` và `age`. Về cơ bản, object keys là string (nếu nó không phải là Symbol). Tại mỗi vòng lặp, giá trị của `item` chính là giá trị của key hiện tại trong vòng lặp. Đầu tiên, `item` là `name`, và được in ra. Vòng lặp sau, `item` là `age`, và được in ra.

--- -###### 48. Ouput là gì? +###### 48. Output là gì? ```javascript console.log(3 + 4 + "5"); @@ -1457,11 +1444,11 @@ console.log(3 + 4 + "5"); #### Đáp án: 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. +Compiler sẽ đánh giá biểu thức dựa trên độ ưu tiên giữa các phép toán trong biểu thức đó, từ đó nó sẽ tính toán hoặc trái-sang-phải hoặc phải-qua-trái. Ở đây chúng ta chỉ có một phép toán mà thôi, phép cộng: `+`. Với phép cộng, tính toán sẽ là từ trái-qua-phải. -`3 + 4` gets evaluated first. This results in the number `7`. +Giá trị `3 + 4` được tính toán trước. Kết quả là `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"`. +`7 + '5'` sẽ ra kết quả là `"75"` bởi xuất hiện ép kiểu tại đây. JavaScript sẽ convert `7` sang dạng string, bạn có thể xem thêm tại câu hỏi 15. Và sau đó 2 string sẽ được nối lại với nhau bởi phép toán cộng `+`. Kết quả `"7" + "5"` sẽ là `"75"`.

@@ -1484,16 +1471,16 @@ const num = parseInt("7*6", 10); #### Đáp án: 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. +Chỉ có số đầu tiên trong chuỗi kí tự được trả về. Hệ cơ số là _hệ thập phân__ (đối số thứ 2 trong hàm chính là cơ số: hệ thập phân, hệ 16, hệ 8, hệ nhị phân, vv.), Hàm `parseInt` sẽ kiểm tra xem các ký tự trong chuỗi có đảm bảo hợp lệ hay không. Một khi chúng tìm ra ký tự không phải là ký tự hợp lệ trong hệ cơ số, nó dừng lại và bỏ qua các ký tự phía sau. -`*` is not a valid number. It only parses `"7"` into the decimal `7`. `num` now holds the value of `7`. +`*` không phải là một số. Vậy nên nó sẽ chỉ convert ký tự `"7"` sang hệ thập phân là `7`. `num` sẽ có giá trị là `7`.

--- -###### 50. What's the output`? +###### 50. Output là gì? ```javascript [1, 2, 3].map(num => { @@ -1512,16 +1499,16 @@ Only the first numbers in the string is returned. Based on the _radix_ (the seco #### Đáp án: 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. +Khi ta tiến hành `map` một mảng, giá trị của `num` sẽ chính là giá trị của phần tử hiện giờ trong vòng lặp. Trong trường hợp này, các phần tử đều là dạng số, tức là `typeof num === "number"` sẽ là `true`. Hàm `map` sẽ tạo ra một mảng mởi từ các giá trị của mảng ban đầu. -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`. +Tuy nhiên chúng ta không hề trả về giá trị nào cả. Khi đó, hàm số sẽ mặc định trả về `undefined`. Do đó qua mỗi vòng lặp, ta lại nhận được thêm một giá trị `undefined` nữa.

--- -###### 51. Ouput là gì? +###### 51. Output là gì? ```javascript function getInfo(member, year) { @@ -1547,18 +1534,19 @@ console.log(person, birthYear); #### Đáp án: 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). +`Đối số` sẽ được đưa vào hàm dạng _tham trị_, trừ phi nó là object, khi đó nó sẽ được đưa vào hàm dạng _tham chiếu_. `birthYear` là dạng giá trị, vì nó là string chứ không phải object. Khi chúng ta đưa vào dạng giá trị, một bản sao của giá trị đó sẽ được tạo ra (xem thêm câu 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"`. +`birthYear` trỏ đến giá trị là `"1997"`. Đối số `year` cũng sẽ rỏ đến giá trị `"1997"`, nhưng giá trị này chỉ là một bản sao của giá trị mà `birthYear` trỏ tới mà thôi, hai giá trị đó hoàn toàn khác nhau. Do đó khi ta thay đổi giá trị `year` bằng `"1998"`, chúng ta chỉ thay đổi giá trị của `year` mà thôi. `birthYear` sẽ vẫn giữ giá trị là `"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"` +`person` là một object. Biến `member` có một tham chiếu tới cùng object mà `person` trỏ tới. Khi chúng ta thay đổi một thuộc tính của object mà `member` trỏ tới, giá trị của `person` cũng sẽ tự động thay đổi theo, vì chúng có chung tham chiếu. `name` của `person` khi này sẽ có giá trị mới là `"Lydia"`.

--- -###### 52. Ouput là gì? +###### 52. Output là gì? ```javascript function greeting() { @@ -1587,16 +1575,16 @@ sayHi(); #### Đáp án: 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'`. +Với lệnh `throw`, chúng ta có thể tạo ra các errors tùy ý. Với câu lệnh đó, chúng ta có thể throw các exception. Một _exeption_ có thể là một chuỗi, một số, một boolean hoặc một object. Trong trường hợp này thì nó là chuỗi `'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'`. +Với lệnh `catch` chúng ta có thể xử lý những exeption được throw ra khi thực hiện `try`. Một exeption đã được throw ra: chuỗi `'Hello world'`. `e` chính là chuỗi đó và chúng ta sẽ in ra. Kết quả là `'Oh an error: Hello world'`.

--- -###### 53. Ouput là gì? +###### 53. Output là gì? ```javascript function Car() { @@ -1618,14 +1606,14 @@ console.log(myCar.make); #### Đáp án: 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"`. +Khi chúng ta trả về một thuộc tính, giá trị của thuộc tính bằng với giá trị đã được trả về bởi lệnh _return_, chứ không phải giá trị được set trong constructor. Chúng ta trả về giá trị là `"Maserati"`, do đó `myCar.make` sẽ là `"Maserati"`.

--- -###### 54. Ouput là gì? +###### 54. Output là gì? ```javascript (() => { @@ -1646,25 +1634,25 @@ console.log(typeof y); #### Đáp án: A -`let x = y = 10;` is actually shorthand for: +`let x = y = 10;` chính là cách viết ngắn gọn của: ```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`. +Khi ta set `y` bằng `10`, thực tế chúng ta đã sử dụng biến global `y` (`window` nếu là trên browser, `global` nếu là môi trường Node).Trên browser, `window.y` sẽ là `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 (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"`. +Sau đó, chúng ta khai báo giá trị của `x` với giá trị của `y`, tức `10`. Tuy nhiên khi ta khai báo với từ khóa `let` biến x sẽ chỉ tồn tại trong _block scoped_; hay trong trường hợp này là `hàm thực hiện ngay lập tức` (immediately-invoked function - IIFE). Khi ta sử dụng phép toán `typeof`, `x` hoàn toàn chưa được định nghĩa: vì `x` lúc này nằm bên ngoài block nó được định nghĩa lúc trước. Nghĩa là `x` là `undefined`. Do đó `console.log(typeof x)` trả về `"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"`. +Tuy nhiên với `y` thì khác, ta đã có giá trị của `y` khi set `y` bằng `10`. Giá trị đó có thể truy cập được từ bất kì đâu bởi chúng là biến global. `y` được định nghĩa với kiểu là `"number"`. Do đó `console.log(typeof y)` trả về `"number"`.

--- -###### 55. Ouput là gì? +###### 55. Output là gì? ```javascript class Dog { @@ -1696,16 +1684,16 @@ pet.bark(); #### Đáp án: 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. +Chúng ta có thể xóa các thuộc tính khỏe object bằng từ khóa `delete`, kể cả với prototype. Khi chúng ta xóa một thuộc tính trên prototype, nó sẽ bị vô hiệu hóa hoàn toàn trong chuỗi prototype. Trong trường hợp này, hàm `bark` sẽ bị vô hiệu hóa ngay sau khi chúng ta thực hiện hàm xóa `delete Dog.prototype.bark`, tất nhiên ta vẫn có thể truy cập vào nó nhưng giá trị sẽ là `undefined`. -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`. +Khi chúng ta chạy một thứ không phải là `hàm`, nó sẽ bắn ra một `TypeError`. Trong trường hợp này là `TypeError: pet.bark is not a function`, vì bản thân thuộc tính `pet.bark` là `undefined`.

--- -###### 56. Ouput là gì? +###### 56. Output là gì? ```javascript const set = new Set([1, 1, 2, 3, 4]); @@ -1723,16 +1711,16 @@ console.log(set); #### Đáp án: D -The `Set` object is a collection of _unique_ values: a value can only occur once in a set. +`Set` là một tập hơp các giá trị _không trùng nhau_. -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}`. +Chúng ta đưa đầu vào là một mảng `[1, 1, 2, 3, 4]` với giá trị `1` bị trùng. Giá trị trùng đó sẽ bị loại bỏ. Kết quả là `{1, 2, 3, 4}`.

--- -###### 57. Ouput là gì? +###### 57. Output là gì? ```javascript // counter.js @@ -1759,16 +1747,16 @@ console.log(myCounter); #### Đáp án: C -An imported module is _read-only_: you cannot modify the imported module. Only the module that exports them can change its value. +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. -When we try to increment the value of `myCounter`, it throws an error: `myCounter` is read-only and cannot be modified. +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.

--- -###### 58. Ouput là gì? +###### 58. Output là gì? ```javascript const name = "Lydia"; @@ -1788,16 +1776,17 @@ console.log(delete age); #### Đáp án: 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. +Phép toán `delete` sẽ trả về một giá trị boolean: `true` nếu xóa thành công, `false` nếu thất bại. Tuy nhiên, nếu biến được khai báo với các từ khóa `var`, `const` hay `let` thì nó sẽ không thể bị xóa bởi phép toán `delete`. 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`. +Biến `name` được khai báo với từ khóa `const`, nên nó sẽ không thể bị xóa và trả về `false`. Khi ta set `age` bằng `21`, thực tế là ta đang sử dụng biến global `age`. Ta có thể xóa sử dụng phép toán `delete`, khi này `delete age` trả về `true`.

--- -###### 59. Ouput là gì? +###### 59. Output là gì? ```javascript const numbers = [1, 2, 3, 4, 5]; @@ -1816,7 +1805,7 @@ console.log(y); #### Đáp án: C -We can unpack values from arrays or properties from objects through destructuring. For example: +Chúng ta có thể unpack các giá trị từ mảng hoặc thuộc tính từ objects bằng phương pháp `destructuring`. Ví dụ: ```javascript [a, b] = [1, 2]; @@ -1824,7 +1813,7 @@ We can unpack values from arrays or properties from objects through destructurin -The value of `a` is now `1`, and the value of `b` is now `2`. What we actually did in the question, is: +Giá trị của `a` sẽ là `1`, `b` sẽ là `2`. Thực tế, câu hỏi của chúng ta đơn giản là: ```javascript [y] = [1, 2, 3, 4, 5]; @@ -1832,14 +1821,14 @@ The value of `a` is now `1`, and the value of `b` is now `2`. What we actually d -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. +Có nghĩa là `y` chính là giá trị đầu tiên trong mảng, tức số `1`. Do đó khi ta in ra `y` thì sẽ là`1`.

--- -###### 60. Ouput là gì? +###### 60. Output là gì? ```javascript const user = { name: "Lydia", age: 21 }; @@ -1858,14 +1847,14 @@ console.log(admin); #### Đáp án: 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 }`. +Ta có thể kết hợp 2 object sử dụng phép toán `spread operator` `...`. Nó cho phép ta tạo ra bản sao của từng cặp key/values trong từng object và nối chúng lại với nhau thành một object mới. Trong trường hợp này chúng ta tạo ra các bản sao của các cặp key/value của object `user` object, và nối chúng vào object `admin`. `admin` object khi này sẽ trở thành `{ admin: true, name: "Lydia", age: 21 }`.

--- -###### 61. Ouput là gì? +###### 61. Output là gì? ```javascript const person = { name: "Lydia" }; @@ -1886,16 +1875,16 @@ console.log(Object.keys(person)); #### Đáp án: 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"`. +Với phương thức `defineProperty`, chúng ta có thể thêm các thuộc tính mới, cũng như sửa các thuộc tính sẵn có của object. Khi chúng ta thêm thuộc tính vào object bằng `defineProperty`, chúng sẽ mặc định là thuộc tính _not enumerable_. Phương thức `Object.keys` sẽ trả về tất cả các thuộc tính _enumerable_ của object, trong trường hợp này thì chỉ có `"name"` mà thôi. -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. +Thêm nữa, các thuộc tính được thêm bởi `defineProperty` là mặc định không thể thay đổi được. Tất nhiên ta có thể override các điều đó bằng các thuộc tính như `writable`, `configurable` và `enumerable`. Tức là `defineProperty` là một cách rất mềm dẻo để tạo ra và điều chỉnh thuộc tính của object.

--- -###### 62. Ouput là gì? +###### 62. Output là gì? ```javascript const settings = { @@ -1918,18 +1907,18 @@ console.log(data); #### Đáp án: 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. +Đối số thứ hai của `JSON.stringify` là _replacer_. Replacer Có thể là một hàm hoặc một mảng, nó sẽ quy định xem giá trị nào sẽ được chuỗi hóa ra sao. -If the replacer is an _array_, only the properties which names are included in the array will be added to the JSON string. In this case, only the properies with the names `"level"` and `"health"` are included, `"username"` is excluded. `data` is now equal to `"{"level":19, "health":90}"`. +Nếu replacer là một _mảng_, chỉ có các thuộc tính có tên trong mảng được convert thành chuỗi JSON. Trong trường hợp này, chỉ có các thuộc tính `"level"` và `"health"` được đưa vào, `"username"` bị loại bỏ. `data` giờ sẽ là `"{"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. +Nếu replacer là _function_, hàm này sẽ được gọi trên từng thuộc tính của object được chuỗi hóa. Giá trị trả về sẽ là giá trị được đưa vào chuỗi JSON. Nếu trả về `undefined`, thuộc tính này sẽ bị loại bỏ khỏi chuỗi.

--- -###### 63. Ouput là gì? +###### 63. Output là gì? ```javascript let num = 10; @@ -1954,9 +1943,9 @@ console.log(num2); #### Đáp án: 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. +Phép toán `++` sẽ _trả về trước_ giá trị của toán hạng, _sau đó tăng_ giá trị của toán hạng lên. Giá trị của `num1` là `10`, vì `increaseNumber` sẽ trả về giá trị của `num`, đang là `10`, và sau đó mới tăng giá trị của `num` lên. -`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` cũng là `10`, vì chúng ta đưa `num1` vào `increasePassedNumber`. `number` bằng `10`(tức giá trị của `num1`). Cũng giống như trên, phép toán `++` sẽ _trả về trước_ giá trị của toán hạng, _sau đó tăng_ giá trị của toán hạng lên. Giá trị của `number` là `10`, do đó `num2` cũng sẽ là `10`.

-
\ No newline at end of file +
From 14b1f50ff32ac96a177310ed0cb2b5335237097c Mon Sep 17 00:00:00 2001 From: Do Trung Kien Date: Fri, 5 Jul 2019 17:42:01 +0700 Subject: [PATCH 222/915] remove remains English part --- README-vi.md | 2 -- 1 file changed, 2 deletions(-) diff --git a/README-vi.md b/README-vi.md index a017dd53..ecec1c9d 100644 --- a/README-vi.md +++ b/README-vi.md @@ -1538,7 +1538,6 @@ console.log(person, birthYear); `birthYear` trỏ đến giá trị là `"1997"`. Đối số `year` cũng sẽ rỏ đến giá trị `"1997"`, nhưng giá trị này chỉ là một bản sao của giá trị mà `birthYear` trỏ tới mà thôi, hai giá trị đó hoàn toàn khác nhau. Do đó khi ta thay đổi giá trị `year` bằng `"1998"`, chúng ta chỉ thay đổi giá trị của `year` mà thôi. `birthYear` sẽ vẫn giữ giá trị là `"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"` `person` là một object. Biến `member` có một tham chiếu tới cùng object mà `person` trỏ tới. Khi chúng ta thay đổi một thuộc tính của object mà `member` trỏ tới, giá trị của `person` cũng sẽ tự động thay đổi theo, vì chúng có chung tham chiếu. `name` của `person` khi này sẽ có giá trị mới là `"Lydia"`.

@@ -1778,7 +1777,6 @@ console.log(delete age); Phép toán `delete` sẽ trả về một giá trị boolean: `true` nếu xóa thành công, `false` nếu thất bại. Tuy nhiên, nếu biến được khai báo với các từ khóa `var`, `const` hay `let` thì nó sẽ không thể bị xóa bởi phép toán `delete`. -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`. Biến `name` được khai báo với từ khóa `const`, nên nó sẽ không thể bị xóa và trả về `false`. Khi ta set `age` bằng `21`, thực tế là ta đang sử dụng biến global `age`. Ta có thể xóa sử dụng phép toán `delete`, khi này `delete age` trả về `true`.

From a172447fc4023e17da91aaafae30f15e32d7af49 Mon Sep 17 00:00:00 2001 From: Do Trung Kien Date: Fri, 5 Jul 2019 17:44:29 +0700 Subject: [PATCH 223/915] add others language into README-vi --- README-vi.md | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) diff --git a/README-vi.md b/README-vi.md index ecec1c9d..3deee970 100644 --- a/README-vi.md +++ b/README-vi.md @@ -6,7 +6,19 @@ 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: -[English Version](./README.md) +Danh sách các ngôn ngữ khác: +* [English](./README.md) +* [中文版本](./README-zh_CN.md) +* [Versión en español](./README-ES.md) +* [日本語](./README-ja_JA.md) +* [한국어](./README-ko_KR.md) +* [Русский](./README_ru-RU.md) +* [Western Balkan](./README-bs_BS.md) +* [Deutsch](./README-de_DE.md) +* [Українська мова](./README-ua_UA.md) +* [Português Brasil](./README_pt_BR.md) +* [العربية](./README_AR.md) +* [اللغة العامية - Egyptian Arabic](./README_ar-EG.md) --- From 9b716b234ddbb188691603edb76510cc729c8030 Mon Sep 17 00:00:00 2001 From: panicdragon Date: Sat, 6 Jul 2019 02:58:59 +0900 Subject: [PATCH 224/915] add new questions no.55 ~ no.63 & translate to japanese --- README-ja_JA.md | 308 +++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 307 insertions(+), 1 deletion(-) diff --git a/README-ja_JA.md b/README-ja_JA.md index 155e8969..69e041f4 100644 --- a/README-ja_JA.md +++ b/README-ja_JA.md @@ -2,7 +2,7 @@ 私は毎日、JavaScriptに関する選択問題を [Instagram](https://www.instagram.com/theavocoder)に投稿していますが、ここにも投稿します。 -初級から上級まで: JavaScriptの知識のテストを行ったり、知識を少し深めたり、コーディング面接の準備をしてください。:muscle: :rocket: 私はこのレポを毎週新しい質問で更新します。 +初級から上級まで: JavaScriptの知識のテストを行ったり、知識を少し深めたり、コーディング面接の準備をしてください。:muscle: :rocket: 私はこのレポを毎週新しい質問で更新します。Last update: June 29th 答えは質問の下の折りたたまれたセクションにあります、クリックすればそれを広げられます。幸運を祈ります。:heart: @@ -1711,3 +1711,309 @@ yに関しては、`y`に`10`を代入するときにグローバル変数`y`を

+ +###### 55. 何が出力されるでしょうか? + +```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` + +
答え +

+ +#### 答え: A + +プロトタイプでも、`delete`キーワードを使ってオブジェクトからプロパティを削除できます。プロトタイプのプロパティを削除すると、プロトタイプチェーンでは使用できなくなります。 + +この場合、`bark`関数は `delete Dog.prototype.bark`の後のプロトタイプでは、もう利用できず、それでもアクセスし、関数ではない何かを呼び出そうとすると、`TypeError`がスローされます。 + +関数ではない何かを呼び出そうとすると、`pet.bark`は`undefined`なので、`TypeError`がスローされ、`TypeError: pet.bark is not a function`となります。 + +

+
+ +--- + +###### 56. 何が出力されるでしょうか? + +```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}` + +
答え +

+ +#### 答え: D + + +`Set`オブジェクトは _unique_ の値の集合です: 値は集合の中で一度だけ現れることができます + +値`1`が重複したイテラブル`[1、1、2、3、4]`を渡しました。セット内に同じ値を2つ持つことはできないので、そのうちの1つが削除され`{1、2、3、4}`となります。 + +

+
+ +--- + +###### 57. 何が出力されるでしょうか? + +```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` + +
答え +

+ +#### 答え: C + +インポートされたモジュールは読み取り専用です。: インポートされたモジュールを変更することはできません。エクスポートするモジュールだけがその値を変更できます。 + +`myCounter`の値を増やそうとすると、error: `myCounter` is read-only and cannot be modified. と、エラーがスローされます。 + +

+
+ +--- + +###### 58. 何が出力されるでしょうか? + +```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` + +
答え +

+ +#### 答え: A + +`delete`演算子は、ブール値を返します: 正常に削除された場合はtrue、それ以外の場合はfalseを返します。`var`, `const`または`let`キーワードで宣言された変数は`delete`演算子を使って削除することはできません。 + +`name`変数は`const`キーワードで宣言されているので、削除は成功しません: `false`が返されます。 + +`age`を`21`に設定すると、実際にはグローバルオブジェクトに`age`というプロパティを追加されました。グローバルオブジェクトからもプロパティを削除することができますので、`delete age`は`true`を返します。 + +

+
+ +--- + +###### 59. 何が出力されるでしょうか? + +```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]` + +
答え +

+ +#### 答え: C + +配列から値を取り出したり、オブジェクトからプロパティを分解して取り出すことができます。 example: + +```javascript +[a, b] = [1, 2]; +``` + + + +`a`の値は`1`となり、`b`の値は`2`となる。実際に問題で行った事は、 + +```javascript +[y] = [1, 2, 3, 4, 5]; +``` + + + +`y`の値が配列の最初の値、つまり`1`に等しいことを意味します。`y`をログ出力すると、`1`が返されます。 + +

+
+ +--- + +###### 60. 何が出力されるでしょうか? + +```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 }` + +
答え +

+ +#### 答え: B + +スプレッド演算子`...`を使ってオブジェクトを結合することができます。あるオブジェクトのキーと値のペアのコピーを作成し、それらを別のオブジェクトに追加することができます。 + +上記の場合だと、`user`オブジェクトのコピーを作成し、それらを`admin`オブジェクトに追加します。`admin`オブジェクトはコピーされたキーと値のペアを含み、その結果`{admin:true、name: "Lydia"、age:21}`となります。 + +

+
+ +--- + +###### 61. 何が出力されるでしょうか? + +```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"]` + +
答え +

+ +#### 答え: B + +`defineProperty`メソッドを使うと、オブジェクトに新しいプロパティを追加したり、既存のプロパティを修正することができます。 `defineProperty`メソッドを使ってオブジェクトにプロパティを追加すると、それらはデフォルトでは _列挙できません_。 + +`Object.keys`メソッドはオブジェクトから全ての _enumerable_ (列挙可能)なプロパティ名を返します。上記の場合は`"name"`だけとなります。 + +`defineProperty`メソッドを使って追加されたプロパティはデフォルトでは不変となります。 この動作は`writable`, `configurable`, `enumerable`プロパティを使って上書きすることができます。このように、`defineProperty`メソッドは、オブジェクトに追加しようとしているプロパティをもっと細かく制御できます。 + +

+
+ +--- + +###### 62. 何が出力されるでしょうか? + +```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}"` + +
答え +

+ +#### 答え: A + +`JSON.stringify`の2番目の引数は _replacer_ です。replacerは、関数または配列のいずれかにすることができ、値を文字列化する対象とその方法を制御できます。 + +replacerが _array_ の場合、名前が配列に含まれるプロパティのみがJSON文字列に追加されます。上記の場合、`"level"`と`"health"`という名前のプロパティだけが含まれ、`"username"`は除外されます。`data`は`"{" level ":19、" health ":90}"`となります。 + +replacerが _function_ の場合、この関数は文字列化しているオブジェクト内のすべてのプロパティに対して呼び出されます。この関数から返される値は、JSON文字列に追加されたときのプロパティの値になり、値が`undefined`の場合、このプロパティはJSON文字列から除外されます。 + +

+
+ +--- + +###### 63. 何が出力されるでしょうか? + +```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` + +
答え +

+ +#### 答え: A + +単項演算子`++`はオペランドの値を _最初に返し_ 、_その後に インクリメント_ します。`num1`の値は`10`となります。 なぜなら`incrementNumber`関数は、最初に`num`の値`10`を返し、その後に`num`の値をインクリメントするだけです。 + +`num1`を`increPassedNumber`に渡したので、`num2`は`10`です。`number`は`10`(`num1`の値です。繰り返しますが、単項演算子`++`は、オペランドの値を _最初に返し_、_その後に インクリメント_ します。したがって、`num2`は`10`となります。 + +

+
From 5dd980b910e9bc75f82498892b924aded2fca3a9 Mon Sep 17 00:00:00 2001 From: Lydia Date: Sun, 7 Jul 2019 18:30:06 +0200 Subject: [PATCH 225/915] Add questions 64-69 --- README.md | 207 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 207 insertions(+) diff --git a/README.md b/README.md index d16ea84e..024c3e59 100644 --- a/README.md +++ b/README.md @@ -1960,3 +1960,210 @@ The unary operator `++` _first returns_ the value of the operand, _then incremen

+ +--- + +###### 64. What's the 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` + +
Answer +

+ +#### Answer: 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 defeault 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 valled `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. What's the 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` + +
Answer +

+ +#### Answer: 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 + +
Answer +

+ +#### Answer: 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 `Dog` class receives two arguments, `name` since it extends `Animal`, and `size` as an extra property on the `Dog` class. They both need to be passed to the constructor function on `Dog`, which is done correctly using constructor 2. +

+
+ +--- + +###### 67. With which constructor can we successfully extend the `Dog` class? + +```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` + +
Answer +

+ +#### 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_. + +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. What's the 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` + +
Answer +

+ +#### Answer: 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. What's the 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"` +- C: `" Lydia Hallie"`, `"Lydia Hallie"` +- D: `"Lydia Hallie"`, `"Lyd"`, + +
Answer +

+ +#### Answer: 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. + +

+
From 8406920a67c78df6ff9225147eae4acdf1707ee9 Mon Sep 17 00:00:00 2001 From: Lydia Date: Sun, 7 Jul 2019 18:39:00 +0200 Subject: [PATCH 226/915] Add description for markdown padding and update date --- README.md | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/README.md b/README.md index 024c3e59..80514ec5 100644 --- a/README.md +++ b/README.md @@ -2,7 +2,7 @@ I post daily multiple choice JavaScript questions on my [Instagram](https://www.instagram.com/theavocoder), which I'll also post 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 weekly with new questions. Last update: June 29th +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 weekly with new questions. Last update: July 7th The answers are in the collapsed sections below the questions, simply click on them to expand it. Good luck :heart: @@ -1664,7 +1664,7 @@ However, we created a global variable `y` when setting `y` equal to `10`. This v --- -###### 55. What's the output? +###### 55. What's the output? ```javascript class Dog { @@ -1963,7 +1963,7 @@ The unary operator `++` _first returns_ the value of the operand, _then incremen --- -###### 64. What's the output? +###### 64. What's the output? ```javascript const value = { number: 10 }; @@ -2152,8 +2152,8 @@ console.log(name.padStart(2)) ``` - A: `"Lydia Hallie"`, `"Lydia Hallie"` -- B: `" Lydia Hallie"`, `" Lydia Hallie"` -- C: `" 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"`,
Answer From 6d8bbaa8e2d568e1e093c5212470dbf7942befce Mon Sep 17 00:00:00 2001 From: Tanguy Coppin Date: Sun, 7 Jul 2019 22:23:14 +0200 Subject: [PATCH 227/915] Update with new language ordering --- README-ja_JA.md | 308 +++++++++++++++++++++++++++++++++++++++++++++++- README-vi.md | 187 +++++++++++++++-------------- README-zh_CN.md | 10 +- README.md | 232 ++++++++++++++++++++++++++++++++++-- 4 files changed, 625 insertions(+), 112 deletions(-) diff --git a/README-ja_JA.md b/README-ja_JA.md index 155e8969..69e041f4 100644 --- a/README-ja_JA.md +++ b/README-ja_JA.md @@ -2,7 +2,7 @@ 私は毎日、JavaScriptに関する選択問題を [Instagram](https://www.instagram.com/theavocoder)に投稿していますが、ここにも投稿します。 -初級から上級まで: JavaScriptの知識のテストを行ったり、知識を少し深めたり、コーディング面接の準備をしてください。:muscle: :rocket: 私はこのレポを毎週新しい質問で更新します。 +初級から上級まで: JavaScriptの知識のテストを行ったり、知識を少し深めたり、コーディング面接の準備をしてください。:muscle: :rocket: 私はこのレポを毎週新しい質問で更新します。Last update: June 29th 答えは質問の下の折りたたまれたセクションにあります、クリックすればそれを広げられます。幸運を祈ります。:heart: @@ -1711,3 +1711,309 @@ yに関しては、`y`に`10`を代入するときにグローバル変数`y`を

+ +###### 55. 何が出力されるでしょうか? + +```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` + +
答え +

+ +#### 答え: A + +プロトタイプでも、`delete`キーワードを使ってオブジェクトからプロパティを削除できます。プロトタイプのプロパティを削除すると、プロトタイプチェーンでは使用できなくなります。 + +この場合、`bark`関数は `delete Dog.prototype.bark`の後のプロトタイプでは、もう利用できず、それでもアクセスし、関数ではない何かを呼び出そうとすると、`TypeError`がスローされます。 + +関数ではない何かを呼び出そうとすると、`pet.bark`は`undefined`なので、`TypeError`がスローされ、`TypeError: pet.bark is not a function`となります。 + +

+
+ +--- + +###### 56. 何が出力されるでしょうか? + +```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}` + +
答え +

+ +#### 答え: D + + +`Set`オブジェクトは _unique_ の値の集合です: 値は集合の中で一度だけ現れることができます + +値`1`が重複したイテラブル`[1、1、2、3、4]`を渡しました。セット内に同じ値を2つ持つことはできないので、そのうちの1つが削除され`{1、2、3、4}`となります。 + +

+
+ +--- + +###### 57. 何が出力されるでしょうか? + +```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` + +
答え +

+ +#### 答え: C + +インポートされたモジュールは読み取り専用です。: インポートされたモジュールを変更することはできません。エクスポートするモジュールだけがその値を変更できます。 + +`myCounter`の値を増やそうとすると、error: `myCounter` is read-only and cannot be modified. と、エラーがスローされます。 + +

+
+ +--- + +###### 58. 何が出力されるでしょうか? + +```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` + +
答え +

+ +#### 答え: A + +`delete`演算子は、ブール値を返します: 正常に削除された場合はtrue、それ以外の場合はfalseを返します。`var`, `const`または`let`キーワードで宣言された変数は`delete`演算子を使って削除することはできません。 + +`name`変数は`const`キーワードで宣言されているので、削除は成功しません: `false`が返されます。 + +`age`を`21`に設定すると、実際にはグローバルオブジェクトに`age`というプロパティを追加されました。グローバルオブジェクトからもプロパティを削除することができますので、`delete age`は`true`を返します。 + +

+
+ +--- + +###### 59. 何が出力されるでしょうか? + +```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]` + +
答え +

+ +#### 答え: C + +配列から値を取り出したり、オブジェクトからプロパティを分解して取り出すことができます。 example: + +```javascript +[a, b] = [1, 2]; +``` + + + +`a`の値は`1`となり、`b`の値は`2`となる。実際に問題で行った事は、 + +```javascript +[y] = [1, 2, 3, 4, 5]; +``` + + + +`y`の値が配列の最初の値、つまり`1`に等しいことを意味します。`y`をログ出力すると、`1`が返されます。 + +

+
+ +--- + +###### 60. 何が出力されるでしょうか? + +```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 }` + +
答え +

+ +#### 答え: B + +スプレッド演算子`...`を使ってオブジェクトを結合することができます。あるオブジェクトのキーと値のペアのコピーを作成し、それらを別のオブジェクトに追加することができます。 + +上記の場合だと、`user`オブジェクトのコピーを作成し、それらを`admin`オブジェクトに追加します。`admin`オブジェクトはコピーされたキーと値のペアを含み、その結果`{admin:true、name: "Lydia"、age:21}`となります。 + +

+
+ +--- + +###### 61. 何が出力されるでしょうか? + +```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"]` + +
答え +

+ +#### 答え: B + +`defineProperty`メソッドを使うと、オブジェクトに新しいプロパティを追加したり、既存のプロパティを修正することができます。 `defineProperty`メソッドを使ってオブジェクトにプロパティを追加すると、それらはデフォルトでは _列挙できません_。 + +`Object.keys`メソッドはオブジェクトから全ての _enumerable_ (列挙可能)なプロパティ名を返します。上記の場合は`"name"`だけとなります。 + +`defineProperty`メソッドを使って追加されたプロパティはデフォルトでは不変となります。 この動作は`writable`, `configurable`, `enumerable`プロパティを使って上書きすることができます。このように、`defineProperty`メソッドは、オブジェクトに追加しようとしているプロパティをもっと細かく制御できます。 + +

+
+ +--- + +###### 62. 何が出力されるでしょうか? + +```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}"` + +
答え +

+ +#### 答え: A + +`JSON.stringify`の2番目の引数は _replacer_ です。replacerは、関数または配列のいずれかにすることができ、値を文字列化する対象とその方法を制御できます。 + +replacerが _array_ の場合、名前が配列に含まれるプロパティのみがJSON文字列に追加されます。上記の場合、`"level"`と`"health"`という名前のプロパティだけが含まれ、`"username"`は除外されます。`data`は`"{" level ":19、" health ":90}"`となります。 + +replacerが _function_ の場合、この関数は文字列化しているオブジェクト内のすべてのプロパティに対して呼び出されます。この関数から返される値は、JSON文字列に追加されたときのプロパティの値になり、値が`undefined`の場合、このプロパティはJSON文字列から除外されます。 + +

+
+ +--- + +###### 63. 何が出力されるでしょうか? + +```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` + +
答え +

+ +#### 答え: A + +単項演算子`++`はオペランドの値を _最初に返し_ 、_その後に インクリメント_ します。`num1`の値は`10`となります。 なぜなら`incrementNumber`関数は、最初に`num`の値`10`を返し、その後に`num`の値をインクリメントするだけです。 + +`num1`を`increPassedNumber`に渡したので、`num2`は`10`です。`number`は`10`(`num1`の値です。繰り返しますが、単項演算子`++`は、オペランドの値を _最初に返し_、_その後に インクリメント_ します。したがって、`num2`は`10`となります。 + +

+
diff --git a/README-vi.md b/README-vi.md index bcb536b5..3deee970 100644 --- a/README-vi.md +++ b/README-vi.md @@ -15,7 +15,6 @@ Danh sách các ngôn ngữ khác: * [Русский](./README_ru-RU.md) * [Western Balkan](./README-bs_BS.md) * [Deutsch](./README-de_DE.md) -* [Tiếng Việt](./README-vi.md) * [Українська мова](./README-ua_UA.md) * [Português Brasil](./README_pt_BR.md) * [العربية](./README_AR.md) @@ -23,7 +22,7 @@ Danh sách các ngôn ngữ khác: --- -###### 1. Ouput là gì? +###### 1. Output là gì? ```javascript function sayHi() { @@ -121,7 +120,7 @@ Khi không có giá trị `radius` tại object đó, nó sẽ trả về `undef --- -###### 4. Ouput là gì? +###### 4. Output là gì? ```javascript +true; @@ -183,7 +182,7 @@ Tuy nhiên, khi chúng ta sử dụng dấu chấm `.`, điều trên không cò --- -###### 6. Ouput là gì? +###### 6. Output là gì? ```javascript let c = { greeting: "Hey!" }; @@ -218,7 +217,7 @@ Khi ta thay đổi giá trị của object, tất cả các biến tham chiếu --- -###### 7. Ouput là gì? +###### 7. Output là gì? ```javascript let a = 3; @@ -251,7 +250,7 @@ Tuy nhiên khi sử dụng phép so sánh `===`, cả _giá trị_ và _kiểu_ --- -###### 8. Ouput là gì? +###### 8. Output là gì? ```javascript class Chameleon { @@ -286,7 +285,7 @@ Hàm `colorChange` là một hàm static (hàm tĩnh). Hàm static được thi --- -###### 9. Ouput là gì? +###### 9. Output là gì? ```javascript let greeting; @@ -341,7 +340,7 @@ Function là một object đặc biệt. Phần code mà bạn viết không ph --- -###### 11. Ouput là gì? +###### 11. Output là gì? ```javascript function Person(firstName, lastName) { @@ -382,7 +381,7 @@ khi này `member.getFullName()` sẽ hoạt động. Tại sao nên làm vậy? --- -###### 12. Ouput là gì? +###### 12. Output là gì? ```javascript function Person(firstName, lastName) { @@ -455,7 +454,7 @@ Tất cả các object đều có prototypes, ngoại trừ **base object**. Obj --- -###### 15. Ouput là gì? +###### 15. Output là gì? ```javascript function sum(a, b) { @@ -484,7 +483,7 @@ Trong ví dụ này, JavaScript sẽ convert số `1` sang dạng string. Mỗi --- -###### 16. Ouput là gì? +###### 16. Output là gì? ```javascript let number = 0; @@ -520,7 +519,7 @@ Vậy kết quả là `0 2 2`. --- -###### 17. Ouput là gì? +###### 17. Output là gì? ```javascript function getPersonInfo(one, two, three) { @@ -551,7 +550,7 @@ Nếu bạn dùng _tagged template literals_, giá trị của đối số đầ --- -###### 18. Ouput là gì? +###### 18. Output là gì? ```javascript function checkAge(data) { @@ -587,7 +586,7 @@ Hai object chúng ta đang so sánh không có được điều đó: object đ --- -###### 19. Ouput là gì? +###### 19. Output là gì? ```javascript function getAge(...args) { @@ -614,7 +613,7 @@ _Spread operator_ (`...args`.) sẽ trả về một mảng các đối số. M --- -###### 20. Ouput là gì? +###### 20. Output là gì? ```javascript function getAge() { @@ -691,7 +690,7 @@ Nếu chúng ta dùng `localStorage`, data sẽ được lưu trữ mãi mãi, t --- -###### 23. Ouput là gì? +###### 23. Output là gì? ```javascript var num = 8; @@ -719,7 +718,7 @@ Bạn không thể làm điều tương tự với `let` hay `const` vì chúng --- -###### 24. Ouput là gì? +###### 24. Output là gì? ```javascript const obj = { 1: "a", 2: "b", 3: "c" }; @@ -750,7 +749,7 @@ Tuy nhiên điều đó không đúng với `set`. Không hề có `'1'` trong s --- -###### 25. Ouput là gì? +###### 25. Output là gì? ```javascript const obj = { a: "one", b: "two", a: "three" }; @@ -792,7 +791,7 @@ Ngữ cảnh thực thi cơ bản chính là ngữ cảnh global: nó là thứ --- -###### 27. Ouput là gì? +###### 27. Output là gì? ```javascript for (let i = 1; i < 5; i++) { @@ -818,7 +817,7 @@ Lệnh `continue` sẽ bỏ qua một vòng lặp nếu điều kiện của nó --- -###### 28. Ouput là gì? +###### 28. Output là gì? ```javascript String.prototype.giveLydiaPizza = () => { @@ -847,7 +846,7 @@ name.giveLydiaPizza(); --- -###### 29. Ouput là gì? +###### 29. Output là gì? ```javascript const a = {}; @@ -881,7 +880,7 @@ Cuối cùng khi gọi `a[b]`, thực chất chính là gọi `a["Object object" --- -###### 30. Ouput là gì? +###### 30. Output là gì? ```javascript const foo = () => console.log("First"); @@ -990,7 +989,7 @@ Nếu ta click vào `p`, ta sẽ thấy hai log: `p` và `div`. Trong chuỗi ev --- -###### 33. Ouput là gì? +###### 33. Output là gì? ```javascript const person = { name: "Lydia" }; @@ -1022,7 +1021,7 @@ Với cả hai, chúng ta có thể đưa vào object để sử dụng từ kh --- -###### 34. Ouput là gì? +###### 34. Output là gì? ```javascript function sayHi() { @@ -1088,7 +1087,7 @@ Function constructors như `new Number` và `new Boolean` đều là _truthy_. --- -###### 36. Ouput là gì? +###### 36. Output là gì? ```javascript console.log(typeof typeof 1); @@ -1112,7 +1111,7 @@ console.log(typeof typeof 1); --- -###### 37. Ouput là gì? +###### 37. Output là gì? ```javascript const numbers = [1, 2, 3]; @@ -1141,7 +1140,7 @@ phụ thuộc vào nơi mà chúng ta chạy chúng (có thể khác nhau tùy m --- -###### 38. Ouput là gì? +###### 38. Output là gì? ```javascript (() => { @@ -1201,7 +1200,7 @@ Primitive types là `boolean`, `null`, `undefined`, `bigint`, `number`, `string` --- -###### 40. Ouput là gì? +###### 40. Output là gì? ```javascript [[0, 1], [2, 3]].reduce( @@ -1231,7 +1230,7 @@ Tiếp tục, `[1, 2, 0, 1]` là `acc` và `[2, 3]` là `cur`. Ta nối chúng l --- -###### 41. Ouput là gì? +###### 41. Output là gì? ```javascript !!null; @@ -1306,7 +1305,7 @@ String là một _iterable_. Thế nên _spread operator_ sẽ map toàn bộ c --- -###### 44. Ouput là gì? +###### 44. Output là gì? ```javascript function* generator(i) { @@ -1323,18 +1322,18 @@ console.log(gen.next().value); - A: `[0, 10], [10, 20]` - B: `20, 20` - C: `10, 20` -- D: `0, 10 và 10, 20` +- D: `0, 10 and 10, 20`
Đáp án

#### Đáp án: 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. +Một hàm bình thường không thể bị dừng giữa chừng khi được gọi. Tuy nhiên một _generator_ thì khác, nó có thể "dừng lại" được, và sau đó nó sẽ tiếp tục từ vị trí nó dừng lại. Mỗi khi một _generator_ gặp một từ khóa `yield`, nó sẽ sinh ra giá trị ngay phía sau nó. Chú ý là _generator_ không _trả về_ giá trị, nó _sinh ra_ giá trị. -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. +Đầu tiên, chúng ta khởi tạo generator với giá trị `i` là `10`. Generator được gọi bằng cách sử dụng phương thức `next()`. Khi lần đầu gọi thì `i` vẫn là `10`. Khi nó bắt gặp từ khóa `yield`: nó sẽ sinh ra giá trị `i`. Generator sẽ được "tạm dừng" tại đây, và ghi ra giá trị `10`. -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`. +Sau đó chung ta tiếp tục gọi generator bằng cách sử dụng tiếp phương thức `next()`. Nó sẽ bắt đầu từ vị trí nó tạm dừng lúc trước, khi `i` vẫn đang là `10`. Và khi nó bắt gặp từ khóa `yield`, nó sẽ sinh ra giá trị `i * 2`. `i` là `10`, nên nó sẽ sinh ra `10 * 2`, tức `20`. Vậy kết quả cuối cùng là `10, 20`.

@@ -1365,14 +1364,14 @@ Promise.race([firstPromise, secondPromise]).then(res => console.log(res)); #### Đáp án: 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. +Khi chúng ta đưa các promise vào trong một hàm `Promise.race`, nó sẽ chỉ resolves hay rejects promise _đầu tiên_ được resolves/rejects. Với hàm `setTimeout`, chúng ta đưa vào một khoảng thời gian: 500 mili giây cho promise đầu tiên (`firstPromise`), và 100 mili giây cho promise thứ hai (`secondPromise`). Nó có nghĩa là `secondPromise` sẽ hoàn thành trước và trả về giá trị `'two'`. `res` khi này sẽ nhận giá trị `'two'` và được in ra console.

--- -###### 46. Ouput là gì? +###### 46. Output là gì? ```javascript let person = { name: "Lydia" }; @@ -1392,26 +1391,26 @@ console.log(members); #### Đáp án: D -First, we declare a variable `person` with the value of an object that has a `name` property. +Đầu tiên, chúng ta khai báo một biến `person` là một object có thuộc tính `name`. -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!) +Sau đó chúng ta khai báo một biến `members`. Ta set giá trị đầu tiên của mảng là giá trị của biến `person`. Khi sử dụng gán bằng, object sẽ được _tham chiếu_ tới object mà nó được gán. Khi ta gán tham chiếu từ một biến sang biến khác, ta tạo ra một bản sao của tham chiếu đó. (nên nhớ rằng đó vẫn là 2 tham chiếu hoàn toàn khác nhau!) -Then, we set the variable `person` equal to `null`. +Sau đó ta set giá trị của `person` bằng `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. +Chúng ta chỉ đơn thuần là thay đổi giá trị của biến `person` mà thôi, chứ không phải giá trị của phần tử đầu tiên ở trong mảng, vì chúng ta có một tham chiếu khác đến object đó. Phần tử đầu tiên của mảng `members` vẫn giữ tham chiêu đến object gốc. Do vậy, khi chúng ta in ra mảng `members`, phần tử đầu tiên sẽ vẫn in ra giá trị của objet gốc.

--- -###### 47. Ouput là gì? +###### 47. Output là gì? ```javascript const person = { @@ -1434,14 +1433,14 @@ for (const item in person) { #### Đáp án: 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. +Với vòng lặp `for-in` chúng ta sẽ lặp qua tất cả các `keys` của object, trong trường hợp này là `name` và `age`. Về cơ bản, object keys là string (nếu nó không phải là Symbol). Tại mỗi vòng lặp, giá trị của `item` chính là giá trị của key hiện tại trong vòng lặp. Đầu tiên, `item` là `name`, và được in ra. Vòng lặp sau, `item` là `age`, và được in ra.

--- -###### 48. Ouput là gì? +###### 48. Output là gì? ```javascript console.log(3 + 4 + "5"); @@ -1457,11 +1456,11 @@ console.log(3 + 4 + "5"); #### Đáp án: 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. +Compiler sẽ đánh giá biểu thức dựa trên độ ưu tiên giữa các phép toán trong biểu thức đó, từ đó nó sẽ tính toán hoặc trái-sang-phải hoặc phải-qua-trái. Ở đây chúng ta chỉ có một phép toán mà thôi, phép cộng: `+`. Với phép cộng, tính toán sẽ là từ trái-qua-phải. -`3 + 4` gets evaluated first. This results in the number `7`. +Giá trị `3 + 4` được tính toán trước. Kết quả là `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"`. +`7 + '5'` sẽ ra kết quả là `"75"` bởi xuất hiện ép kiểu tại đây. JavaScript sẽ convert `7` sang dạng string, bạn có thể xem thêm tại câu hỏi 15. Và sau đó 2 string sẽ được nối lại với nhau bởi phép toán cộng `+`. Kết quả `"7" + "5"` sẽ là `"75"`.

@@ -1484,16 +1483,16 @@ const num = parseInt("7*6", 10); #### Đáp án: 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. +Chỉ có số đầu tiên trong chuỗi kí tự được trả về. Hệ cơ số là _hệ thập phân__ (đối số thứ 2 trong hàm chính là cơ số: hệ thập phân, hệ 16, hệ 8, hệ nhị phân, vv.), Hàm `parseInt` sẽ kiểm tra xem các ký tự trong chuỗi có đảm bảo hợp lệ hay không. Một khi chúng tìm ra ký tự không phải là ký tự hợp lệ trong hệ cơ số, nó dừng lại và bỏ qua các ký tự phía sau. -`*` is not a valid number. It only parses `"7"` into the decimal `7`. `num` now holds the value of `7`. +`*` không phải là một số. Vậy nên nó sẽ chỉ convert ký tự `"7"` sang hệ thập phân là `7`. `num` sẽ có giá trị là `7`.

--- -###### 50. What's the output`? +###### 50. Output là gì? ```javascript [1, 2, 3].map(num => { @@ -1512,16 +1511,16 @@ Only the first numbers in the string is returned. Based on the _radix_ (the seco #### Đáp án: 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. +Khi ta tiến hành `map` một mảng, giá trị của `num` sẽ chính là giá trị của phần tử hiện giờ trong vòng lặp. Trong trường hợp này, các phần tử đều là dạng số, tức là `typeof num === "number"` sẽ là `true`. Hàm `map` sẽ tạo ra một mảng mởi từ các giá trị của mảng ban đầu. -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`. +Tuy nhiên chúng ta không hề trả về giá trị nào cả. Khi đó, hàm số sẽ mặc định trả về `undefined`. Do đó qua mỗi vòng lặp, ta lại nhận được thêm một giá trị `undefined` nữa.

--- -###### 51. Ouput là gì? +###### 51. Output là gì? ```javascript function getInfo(member, year) { @@ -1547,18 +1546,18 @@ console.log(person, birthYear); #### Đáp án: 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). +`Đối số` sẽ được đưa vào hàm dạng _tham trị_, trừ phi nó là object, khi đó nó sẽ được đưa vào hàm dạng _tham chiếu_. `birthYear` là dạng giá trị, vì nó là string chứ không phải object. Khi chúng ta đưa vào dạng giá trị, một bản sao của giá trị đó sẽ được tạo ra (xem thêm câu 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"`. +`birthYear` trỏ đến giá trị là `"1997"`. Đối số `year` cũng sẽ rỏ đến giá trị `"1997"`, nhưng giá trị này chỉ là một bản sao của giá trị mà `birthYear` trỏ tới mà thôi, hai giá trị đó hoàn toàn khác nhau. Do đó khi ta thay đổi giá trị `year` bằng `"1998"`, chúng ta chỉ thay đổi giá trị của `year` mà thôi. `birthYear` sẽ vẫn giữ giá trị là `"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"` +`person` là một object. Biến `member` có một tham chiếu tới cùng object mà `person` trỏ tới. Khi chúng ta thay đổi một thuộc tính của object mà `member` trỏ tới, giá trị của `person` cũng sẽ tự động thay đổi theo, vì chúng có chung tham chiếu. `name` của `person` khi này sẽ có giá trị mới là `"Lydia"`.

--- -###### 52. Ouput là gì? +###### 52. Output là gì? ```javascript function greeting() { @@ -1587,16 +1586,16 @@ sayHi(); #### Đáp án: 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'`. +Với lệnh `throw`, chúng ta có thể tạo ra các errors tùy ý. Với câu lệnh đó, chúng ta có thể throw các exception. Một _exeption_ có thể là một chuỗi, một số, một boolean hoặc một object. Trong trường hợp này thì nó là chuỗi `'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'`. +Với lệnh `catch` chúng ta có thể xử lý những exeption được throw ra khi thực hiện `try`. Một exeption đã được throw ra: chuỗi `'Hello world'`. `e` chính là chuỗi đó và chúng ta sẽ in ra. Kết quả là `'Oh an error: Hello world'`.

--- -###### 53. Ouput là gì? +###### 53. Output là gì? ```javascript function Car() { @@ -1618,14 +1617,14 @@ console.log(myCar.make); #### Đáp án: 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"`. +Khi chúng ta trả về một thuộc tính, giá trị của thuộc tính bằng với giá trị đã được trả về bởi lệnh _return_, chứ không phải giá trị được set trong constructor. Chúng ta trả về giá trị là `"Maserati"`, do đó `myCar.make` sẽ là `"Maserati"`.

--- -###### 54. Ouput là gì? +###### 54. Output là gì? ```javascript (() => { @@ -1646,25 +1645,25 @@ console.log(typeof y); #### Đáp án: A -`let x = y = 10;` is actually shorthand for: +`let x = y = 10;` chính là cách viết ngắn gọn của: ```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`. +Khi ta set `y` bằng `10`, thực tế chúng ta đã sử dụng biến global `y` (`window` nếu là trên browser, `global` nếu là môi trường Node).Trên browser, `window.y` sẽ là `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 (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"`. +Sau đó, chúng ta khai báo giá trị của `x` với giá trị của `y`, tức `10`. Tuy nhiên khi ta khai báo với từ khóa `let` biến x sẽ chỉ tồn tại trong _block scoped_; hay trong trường hợp này là `hàm thực hiện ngay lập tức` (immediately-invoked function - IIFE). Khi ta sử dụng phép toán `typeof`, `x` hoàn toàn chưa được định nghĩa: vì `x` lúc này nằm bên ngoài block nó được định nghĩa lúc trước. Nghĩa là `x` là `undefined`. Do đó `console.log(typeof x)` trả về `"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"`. +Tuy nhiên với `y` thì khác, ta đã có giá trị của `y` khi set `y` bằng `10`. Giá trị đó có thể truy cập được từ bất kì đâu bởi chúng là biến global. `y` được định nghĩa với kiểu là `"number"`. Do đó `console.log(typeof y)` trả về `"number"`.

--- -###### 55. Ouput là gì? +###### 55. Output là gì? ```javascript class Dog { @@ -1696,16 +1695,16 @@ pet.bark(); #### Đáp án: 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. +Chúng ta có thể xóa các thuộc tính khỏe object bằng từ khóa `delete`, kể cả với prototype. Khi chúng ta xóa một thuộc tính trên prototype, nó sẽ bị vô hiệu hóa hoàn toàn trong chuỗi prototype. Trong trường hợp này, hàm `bark` sẽ bị vô hiệu hóa ngay sau khi chúng ta thực hiện hàm xóa `delete Dog.prototype.bark`, tất nhiên ta vẫn có thể truy cập vào nó nhưng giá trị sẽ là `undefined`. -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`. +Khi chúng ta chạy một thứ không phải là `hàm`, nó sẽ bắn ra một `TypeError`. Trong trường hợp này là `TypeError: pet.bark is not a function`, vì bản thân thuộc tính `pet.bark` là `undefined`.

--- -###### 56. Ouput là gì? +###### 56. Output là gì? ```javascript const set = new Set([1, 1, 2, 3, 4]); @@ -1723,16 +1722,16 @@ console.log(set); #### Đáp án: D -The `Set` object is a collection of _unique_ values: a value can only occur once in a set. +`Set` là một tập hơp các giá trị _không trùng nhau_. -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}`. +Chúng ta đưa đầu vào là một mảng `[1, 1, 2, 3, 4]` với giá trị `1` bị trùng. Giá trị trùng đó sẽ bị loại bỏ. Kết quả là `{1, 2, 3, 4}`.

--- -###### 57. Ouput là gì? +###### 57. Output là gì? ```javascript // counter.js @@ -1759,16 +1758,16 @@ console.log(myCounter); #### Đáp án: C -An imported module is _read-only_: you cannot modify the imported module. Only the module that exports them can change its value. +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. -When we try to increment the value of `myCounter`, it throws an error: `myCounter` is read-only and cannot be modified. +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.

--- -###### 58. Ouput là gì? +###### 58. Output là gì? ```javascript const name = "Lydia"; @@ -1788,16 +1787,16 @@ console.log(delete age); #### Đáp án: 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. +Phép toán `delete` sẽ trả về một giá trị boolean: `true` nếu xóa thành công, `false` nếu thất bại. Tuy nhiên, nếu biến được khai báo với các từ khóa `var`, `const` hay `let` thì nó sẽ không thể bị xóa bởi phép toán `delete`. -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`. +Biến `name` được khai báo với từ khóa `const`, nên nó sẽ không thể bị xóa và trả về `false`. Khi ta set `age` bằng `21`, thực tế là ta đang sử dụng biến global `age`. Ta có thể xóa sử dụng phép toán `delete`, khi này `delete age` trả về `true`.

--- -###### 59. Ouput là gì? +###### 59. Output là gì? ```javascript const numbers = [1, 2, 3, 4, 5]; @@ -1816,7 +1815,7 @@ console.log(y); #### Đáp án: C -We can unpack values from arrays or properties from objects through destructuring. For example: +Chúng ta có thể unpack các giá trị từ mảng hoặc thuộc tính từ objects bằng phương pháp `destructuring`. Ví dụ: ```javascript [a, b] = [1, 2]; @@ -1824,7 +1823,7 @@ We can unpack values from arrays or properties from objects through destructurin -The value of `a` is now `1`, and the value of `b` is now `2`. What we actually did in the question, is: +Giá trị của `a` sẽ là `1`, `b` sẽ là `2`. Thực tế, câu hỏi của chúng ta đơn giản là: ```javascript [y] = [1, 2, 3, 4, 5]; @@ -1832,14 +1831,14 @@ The value of `a` is now `1`, and the value of `b` is now `2`. What we actually d -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. +Có nghĩa là `y` chính là giá trị đầu tiên trong mảng, tức số `1`. Do đó khi ta in ra `y` thì sẽ là`1`.

--- -###### 60. Ouput là gì? +###### 60. Output là gì? ```javascript const user = { name: "Lydia", age: 21 }; @@ -1858,14 +1857,14 @@ console.log(admin); #### Đáp án: 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 }`. +Ta có thể kết hợp 2 object sử dụng phép toán `spread operator` `...`. Nó cho phép ta tạo ra bản sao của từng cặp key/values trong từng object và nối chúng lại với nhau thành một object mới. Trong trường hợp này chúng ta tạo ra các bản sao của các cặp key/value của object `user` object, và nối chúng vào object `admin`. `admin` object khi này sẽ trở thành `{ admin: true, name: "Lydia", age: 21 }`.

--- -###### 61. Ouput là gì? +###### 61. Output là gì? ```javascript const person = { name: "Lydia" }; @@ -1886,16 +1885,16 @@ console.log(Object.keys(person)); #### Đáp án: 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"`. +Với phương thức `defineProperty`, chúng ta có thể thêm các thuộc tính mới, cũng như sửa các thuộc tính sẵn có của object. Khi chúng ta thêm thuộc tính vào object bằng `defineProperty`, chúng sẽ mặc định là thuộc tính _not enumerable_. Phương thức `Object.keys` sẽ trả về tất cả các thuộc tính _enumerable_ của object, trong trường hợp này thì chỉ có `"name"` mà thôi. -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. +Thêm nữa, các thuộc tính được thêm bởi `defineProperty` là mặc định không thể thay đổi được. Tất nhiên ta có thể override các điều đó bằng các thuộc tính như `writable`, `configurable` và `enumerable`. Tức là `defineProperty` là một cách rất mềm dẻo để tạo ra và điều chỉnh thuộc tính của object.

--- -###### 62. Ouput là gì? +###### 62. Output là gì? ```javascript const settings = { @@ -1918,18 +1917,18 @@ console.log(data); #### Đáp án: 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. +Đối số thứ hai của `JSON.stringify` là _replacer_. Replacer Có thể là một hàm hoặc một mảng, nó sẽ quy định xem giá trị nào sẽ được chuỗi hóa ra sao. -If the replacer is an _array_, only the properties which names are included in the array will be added to the JSON string. In this case, only the properies with the names `"level"` and `"health"` are included, `"username"` is excluded. `data` is now equal to `"{"level":19, "health":90}"`. +Nếu replacer là một _mảng_, chỉ có các thuộc tính có tên trong mảng được convert thành chuỗi JSON. Trong trường hợp này, chỉ có các thuộc tính `"level"` và `"health"` được đưa vào, `"username"` bị loại bỏ. `data` giờ sẽ là `"{"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. +Nếu replacer là _function_, hàm này sẽ được gọi trên từng thuộc tính của object được chuỗi hóa. Giá trị trả về sẽ là giá trị được đưa vào chuỗi JSON. Nếu trả về `undefined`, thuộc tính này sẽ bị loại bỏ khỏi chuỗi.

--- -###### 63. Ouput là gì? +###### 63. Output là gì? ```javascript let num = 10; @@ -1954,9 +1953,9 @@ console.log(num2); #### Đáp án: 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. +Phép toán `++` sẽ _trả về trước_ giá trị của toán hạng, _sau đó tăng_ giá trị của toán hạng lên. Giá trị của `num1` là `10`, vì `increaseNumber` sẽ trả về giá trị của `num`, đang là `10`, và sau đó mới tăng giá trị của `num` lên. -`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` cũng là `10`, vì chúng ta đưa `num1` vào `increasePassedNumber`. `number` bằng `10`(tức giá trị của `num1`). Cũng giống như trên, phép toán `++` sẽ _trả về trước_ giá trị của toán hạng, _sau đó tăng_ giá trị của toán hạng lên. Giá trị của `number` là `10`, do đó `num2` cũng sẽ là `10`.

-
\ No newline at end of file +
diff --git a/README-zh_CN.md b/README-zh_CN.md index 08aa81ea..d1db96f4 100644 --- a/README-zh_CN.md +++ b/README-zh_CN.md @@ -1040,8 +1040,8 @@ typeof sayHi() ```javascript 0 new Number(0) -;('') -;(' ') +('') +(' ') new Boolean(false) undefined ``` @@ -1130,12 +1130,12 @@ console.log(numbers) ###### 38. 输出是什么? ```javascript -;(() => { +(() => { let x, y try { throw new Error() } catch (x) { - ;(x = 1), (y = 2) + (x = 1), (y = 2) console.log(x) } console.log(x) @@ -1188,7 +1188,7 @@ JavaScript 只有基本类型和对象。 ###### 40. 输出是什么? ```javascript -;[[0, 1], [2, 3]].reduce( +[[0, 1], [2, 3]].reduce( (acc, cur) => { return acc.concat(cur) }, diff --git a/README.md b/README.md index 51f23862..5ca61dc1 100644 --- a/README.md +++ b/README.md @@ -2,26 +2,27 @@ I post daily multiple choice JavaScript questions on my [Instagram](https://www.instagram.com/theavocoder), which I'll also post 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 weekly with new questions. Last update: June 29th +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 weekly with new questions. Last update: July 7th The answers are in the collapsed sections below the questions, simply click on them to expand it. Good luck :heart: List of available languages: * [English](./README.md) -* [中文版本](./README-zh_CN.md) -* [Versión en español](./README-ES.md) +* [العربية](./README_AR.md) +* [اللغة العامية - Egyptian Arabic](./README_ar-EG.md) +* [Bosanski](./README-bs_BS.md) +* [Deutsch](./README-de_DE.md) +* [Español](./README-ES.md) +* [Français](./README_fr-FR.md) * [日本語](./README-ja_JA.md) * [한국어](./README-ko_KR.md) +* [Português Brasil](./README_pt_BR.md) * [Русский](./README_ru-RU.md) -* [Western Balkan](./README-bs_BS.md) -* [Deutsch](./README-de_DE.md) -* [Tiếng Việt](./README-vi.md) * [Українська мова](./README-ua_UA.md) -* [Português Brasil](./README_pt_BR.md) -* [العربية](./README_AR.md) -* [اللغة العامية - Egyptian Arabic](./README_ar-EG.md) -* [Français](./README_fr-FR.md) +* [Tiếng Việt](./README-vi.md) +* [中文版本](./README-zh_CN.md) + --- @@ -608,7 +609,7 @@ getAge(21); #### Answer: C -The spread operator (`...args`.) returns an array with arguments. An array is an object, so `typeof args` returns `"object"` +The rest parameter (`...args`.) lets us "collect" all remaining arguments into an array. An array is an object, so `typeof args` returns `"object"`

@@ -1664,7 +1665,7 @@ However, we created a global variable `y` when setting `y` equal to `10`. This v --- -###### 55. What's the output? +###### 55. What's the output? ```javascript class Dog { @@ -1960,3 +1961,210 @@ The unary operator `++` _first returns_ the value of the operand, _then incremen

+ +--- + +###### 64. What's the 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` + +
Answer +

+ +#### Answer: 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 defeault 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 valled `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. What's the 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` + +
Answer +

+ +#### Answer: 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 + +
Answer +

+ +#### Answer: 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 `Dog` class receives two arguments, `name` since it extends `Animal`, and `size` as an extra property on the `Dog` class. They both need to be passed to the constructor function on `Dog`, which is done correctly using constructor 2. +

+
+ +--- + +###### 67. With which constructor can we successfully extend the `Dog` class? + +```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` + +
Answer +

+ +#### 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_. + +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. What's the 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` + +
Answer +

+ +#### Answer: 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. What's the 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"`, + +
Answer +

+ +#### Answer: 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. + +

+
From a3f094c0f4038841ded731441120bd8b863a5cda Mon Sep 17 00:00:00 2001 From: TuanTV Date: Mon, 8 Jul 2019 09:40:39 +0700 Subject: [PATCH 228/915] :books: translate question 49 to vietnamese --- README-vi.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README-vi.md b/README-vi.md index 3deee970..1f130cd9 100644 --- a/README-vi.md +++ b/README-vi.md @@ -1467,7 +1467,7 @@ Giá trị `3 + 4` được tính toán trước. Kết quả là `7`. --- -###### 49. What's the value of `num`? +###### 49. Giá trị của `num` là gì? ```javascript const num = parseInt("7*6", 10); @@ -1483,7 +1483,7 @@ const num = parseInt("7*6", 10); #### Đáp án: C -Chỉ có số đầu tiên trong chuỗi kí tự được trả về. Hệ cơ số là _hệ thập phân__ (đối số thứ 2 trong hàm chính là cơ số: hệ thập phân, hệ 16, hệ 8, hệ nhị phân, vv.), Hàm `parseInt` sẽ kiểm tra xem các ký tự trong chuỗi có đảm bảo hợp lệ hay không. Một khi chúng tìm ra ký tự không phải là ký tự hợp lệ trong hệ cơ số, nó dừng lại và bỏ qua các ký tự phía sau. +Chỉ có số đầu tiên trong chuỗi kí tự được trả về. Hệ cơ số là _hệ thập phân_ (đối số thứ 2 trong hàm chính là cơ số: hệ thập phân, hệ 16, hệ 8, hệ nhị phân, vv.), Hàm `parseInt` sẽ kiểm tra xem các ký tự trong chuỗi có đảm bảo hợp lệ hay không. Một khi chúng tìm ra ký tự không phải là ký tự hợp lệ trong hệ cơ số, nó dừng lại và bỏ qua các ký tự phía sau. `*` không phải là một số. Vậy nên nó sẽ chỉ convert ký tự `"7"` sang hệ thập phân là `7`. `num` sẽ có giá trị là `7`. From a73cb899710c990baff3cce136e26fc78af6f0f8 Mon Sep 17 00:00:00 2001 From: lazy <310195875@qq.com> Date: Mon, 8 Jul 2019 19:01:14 +0800 Subject: [PATCH 229/915] update zh_CN: add question 64-69 --- README-zh_CN.md | 214 ++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 214 insertions(+) diff --git a/README-zh_CN.md b/README-zh_CN.md index d1db96f4..177f383e 100644 --- a/README-zh_CN.md +++ b/README-zh_CN.md @@ -1945,3 +1945,217 @@ console.log(num2);

+ +--- + +###### 64. 输出什么? + +```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` + +
答案 +

+ +#### 答案: C + +在ES6中,我们可以使用默认值初始化参数。如果没有给函数传参,或者传的参值为 `"undefined"` ,那么参数的值将是默认值。上述例子中,我们将 `value` 对象进行了解构并传到一个新对象中,因此 `x` 的默认值为 `{number:10}` 。 + +默认参数在调用时才会进行计算,每次调用函数时,都会创建一个新的对象。我们前两次调用 `multiply` 函数且不传递值,那么每一次 `x` 的默认值都为 `{number:10}` ,因此打印出该数字的乘积值为`20`。 + +第三次调用 `multiply` 时,我们传递了一个参数,即对象`value`。 `*=`运算符实际上是`x.number = x.number * 2`的简写,我们修改了`x.number`的值,并打印出值`20`。 + +第四次,我们再次传递`value`对象。 `x.number`之前被修改为`20`,所以`x.number * = 2`打印为`40`。 + +

+
+ +--- + +###### 65. 输出什么? + +```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` + +
答案 +

+ +#### 答案: D + +`reducer` 函数接收4个参数: + +1. Accumulator (acc) (累计器) +2. Current Value (cur) (当前值) +3. Current Index (idx) (当前索引) +4. Source Array (src) (源数组) + +`reducer` 函数的返回值将会分配给累计器,该返回值在数组的每个迭代中被记住,并最后成为最终的单个结果值。 + +`reducer` 函数还有一个可选参数`initialValue`, 该参数将作为第一次调用回调函数时的第一个参数的值。 如果没有提供初始值,则将使用数组中的第一个元素。 + +在上述例子,`reduce`方法接收的第一个参数(Accumulator)是`x`, 第二个参数(Current Value)是`y`。 + +在第一次调用时,累加器`x`为`1`,当前值`“y”`为`2`,打印出累加器和当前值:`1`和`2`。 + +例子中我们的回调函数没有返回任何值,只是打印累加器的值和当前值。如果函数没有返回值,则默认返回`undefined`。 在下一次调用时,累加器为`undefined`,当前值为“3”, 因此`undefined`和`3`被打印出。 + +在第四次调用时,回调函数依然没有返回值。 累加器再次为 `undefined` ,当前值为“4”。 `undefined`和`4`被打印出。 +

+
+ +--- + +###### 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 + +
答案 +

+ +#### 答案: B + +在子类中,在调用`super`之前不能访问到`this`关键字。 如果这样做,它将抛出一个`ReferenceError`:1和4将引发一个引用错误。 + +使用`super`关键字,需要用给定的参数来调用父类的构造函数。 父类的构造函数接收`name`参数,因此我们需要将`name`传递给`super`。 + +`Labrador`类接收两个参数,`name`参数是由于它继承了`Dog`,`size`作为`Labrador`类的额外属性,它们都需要传递给`Labrador`的构造函数,因此使用构造函数2正确完成。 +

+
+ +--- + +###### 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`会被依次打印。 + +

+
+ +--- + +###### 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('foo')`,第二个`Symbol('foo')`, 这两个值是唯一的,彼此不相等,因此返回`false`。 + +

+
+ +--- + +###### 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(`13 - 12 = 1`)个空格。 + +如果传递给`padStart`方法的参数小于字符串的长度,则不会添加填充。 + +

+
From c871eaf904c0e1a47b14406916d722ea74a6904a Mon Sep 17 00:00:00 2001 From: Jordan Buckley Date: Mon, 8 Jul 2019 23:00:49 +0000 Subject: [PATCH 230/915] fix typos in question 64 --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index f3fb3a50..54e11e41 100644 --- a/README.md +++ b/README.md @@ -1969,7 +1969,7 @@ The unary operator `++` _first returns_ the value of the operand, _then incremen const value = { number: 10 }; const multiply = (x = { ...value }) => { - console.log((x.number * 2)); + console.log((x.number *= 2)); }; multiply(); @@ -1990,7 +1990,7 @@ multiply(value); 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 defeault 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 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 valled `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`. From e6532b56770064b152836851eb6ea9ff3fc74ee8 Mon Sep 17 00:00:00 2001 From: Jordan Buckley Date: Mon, 8 Jul 2019 23:16:09 +0000 Subject: [PATCH 231/915] fix various minor typos and missing spaces --- README.md | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/README.md b/README.md index 54e11e41..38a85bf6 100644 --- a/README.md +++ b/README.md @@ -1194,7 +1194,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 implicity wrap the object 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 object 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.

@@ -1434,7 +1434,7 @@ for (const item in person) { #### Answer: 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. +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.

@@ -1687,7 +1687,7 @@ pet.bark(); ``` - A: `"Woof I am Mara"`, `TypeError` -- B: `"Woof I am Mara"`,`"Woof I am Mara"` +- B: `"Woof I am Mara"`, `"Woof I am Mara"` - C: `"Woof I am Mara"`, `undefined` - D: `TypeError`, `TypeError` @@ -1920,7 +1920,7 @@ console.log(data); 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 properties which names are included in the array will be added to the JSON string. In this case, only the properies with the names `"level"` and `"health"` are included, `"username"` is excluded. `data` is now equal to `"{"level":19, "health":90}"`. +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. @@ -1992,7 +1992,7 @@ 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 valled `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`. @@ -2136,7 +2136,7 @@ console.log(Symbol('foo') === Symbol('foo')) #### Answer: 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`.

From 9bb2455de9ecd707af6c63b19f7b2d6c417560da Mon Sep 17 00:00:00 2001 From: Jordan Buckley Date: Mon, 8 Jul 2019 23:26:59 +0000 Subject: [PATCH 232/915] fix wrong class names on question 66 --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 38a85bf6..e70336cf 100644 --- a/README.md +++ b/README.md @@ -2080,7 +2080,7 @@ In a derived class, you cannot access the `this` keyword before calling `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 `Dog` class receives two arguments, `name` since it extends `Animal`, and `size` as an extra property on the `Dog` class. They both need to be passed to the constructor function on `Dog`, which is done correctly using constructor 2. +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.

From 658976d93ced14d5facfbf6ca87fb40e7c7d9023 Mon Sep 17 00:00:00 2001 From: Jordan Buckley Date: Mon, 8 Jul 2019 23:29:01 +0000 Subject: [PATCH 233/915] fix duplicated question title for question 67 --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index e70336cf..ffcdfb46 100644 --- a/README.md +++ b/README.md @@ -2086,7 +2086,7 @@ The `Labrador` class receives two arguments, `name` since it extends `Dog`, and --- -###### 67. With which constructor can we successfully extend the `Dog` class? +###### 67. What's the output? ```javascript // index.js From 7e2078537ea1b3e9ad1b4414a2d97ad7f281c71b Mon Sep 17 00:00:00 2001 From: lazy <310195875@qq.com> Date: Tue, 9 Jul 2019 17:47:08 +0800 Subject: [PATCH 234/915] update: zh_CN --- README-zh_CN.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README-zh_CN.md b/README-zh_CN.md index 177f383e..7d1a38d4 100644 --- a/README-zh_CN.md +++ b/README-zh_CN.md @@ -2011,7 +2011,7 @@ multiply(value); `reducer` 函数的返回值将会分配给累计器,该返回值在数组的每个迭代中被记住,并最后成为最终的单个结果值。 -`reducer` 函数还有一个可选参数`initialValue`, 该参数将作为第一次调用回调函数时的第一个参数的值。 如果没有提供初始值,则将使用数组中的第一个元素。 +`reducer` 函数还有一个可选参数`initialValue`, 该参数将作为第一次调用回调函数时的第一个参数的值。如果没有提供`initialValue`,则将使用数组中的第一个元素。 在上述例子,`reduce`方法接收的第一个参数(Accumulator)是`x`, 第二个参数(Current Value)是`y`。 @@ -2082,7 +2082,7 @@ class Labrador extends Dog { ```javascript // index.js -console.log('running index.js); +console.log('running index.js'); import { sum } from './sum.js'; console.log(sum(1, 2)); From 227f44926ff86b2ced1841a3d827ac55643ba304 Mon Sep 17 00:00:00 2001 From: sweetmilkys Date: Tue, 9 Jul 2019 20:40:12 +0900 Subject: [PATCH 235/915] Fix typos in questions 67 --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index f3fb3a50..5b2e6265 100644 --- a/README.md +++ b/README.md @@ -2086,11 +2086,11 @@ The `Dog` class receives two arguments, `name` since it extends `Animal`, and `s --- -###### 67. With which constructor can we successfully extend the `Dog` class? +###### 67. What's the output? ```javascript // index.js -console.log('running index.js); +console.log('running index.js'); import { sum } from './sum.js'; console.log(sum(1, 2)); From c87c6b942988d6a28b5a3e5af1f72c142711a21d Mon Sep 17 00:00:00 2001 From: Matheus Vessaro Date: Tue, 9 Jul 2019 10:52:36 -0300 Subject: [PATCH 236/915] fix(pt-BR): corrected the word glogal for global --- README_pt_BR.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README_pt_BR.md b/README_pt_BR.md index 9b9d5c25..ae5f387d 100644 --- a/README_pt_BR.md +++ b/README_pt_BR.md @@ -770,7 +770,7 @@ Se temos duas chaves com o mesmo nome, a última irá substituir a primeira. Ain --- -###### 26. O contexto glogal de execução do JavaScrit cria duas coisas para você: O objeto glogal, e a palavra-chave `this`. +###### 26. O contexto global de execução do JavaScrit cria duas coisas para você: O objeto global, e a palavra-chave `this`. - A: Verdadeiro - B: Falso @@ -781,7 +781,7 @@ Se temos duas chaves com o mesmo nome, a última irá substituir a primeira. Ain #### Resposta: A -O contexto base de execução é o contexto glogal: É aquilo que está acessível em qualquer lugar do código. +O contexto base de execução é o contexto global: É aquilo que está acessível em qualquer lugar do código.

From ed3a3005047140f3b956039d28684b2de83f804c Mon Sep 17 00:00:00 2001 From: sweetmilkys Date: Tue, 9 Jul 2019 23:19:41 +0900 Subject: [PATCH 237/915] Add Translate the questions 64-69 to Korean. --- README-ko_KR.md | 211 +++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 210 insertions(+), 1 deletion(-) diff --git a/README-ko_KR.md b/README-ko_KR.md index 6214a0d7..814c35a3 100644 --- a/README-ko_KR.md +++ b/README-ko_KR.md @@ -2,7 +2,7 @@ JavaScript 에 관한 객관식 문제를 [Instagram](https://www.instagram.com/theavocoder)에 매일 게시하고 있어요, 물론 여기에도 게시할 거예요! -초급부터 고급까지: JavaScript를 얼마나 잘 알고 있는지 테스트하거나, 지식을 조금 더 새롭게 하거나, 코딩 면접을 준비하세요! :muscle: :rocket: 이 기록을 매주 새로운 질문으로 업데이트해요. 마지막 업데이트: 6월 29일 +초급부터 고급까지: JavaScript를 얼마나 잘 알고 있는지 테스트하거나, 지식을 조금 더 새롭게 하거나, 코딩 면접을 준비하세요! :muscle: :rocket: 이 기록을 매주 새로운 질문으로 업데이트해요. 마지막 업데이트: 7월 7일 정답은 질문 아래 접힌 부분에 있어요, 그냥 클릭하면 펼칠 수 있어요. 행운을 빌어요 :heart: @@ -1955,3 +1955,212 @@ console.log(num2);

+ +--- + +###### 64. 무엇이 출력 될까요? + +```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` + +
정답 +

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

+
+ +--- + +###### 65. 무엇이 출력 될까요? + +```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` + +
정답 +

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

+
+ +--- + +###### 66. `Dog` 클래스를 성공적으로 확장할 수 있는 생성자는 어느 것일까요? + +```javascript +class Animal { + constructor(name) { + this.name = name; + } +}; + +class Dog extends Animal { + // 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 + +
정답 +

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

+
+ +--- + +###### 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` 키워드를 사용하면, 모든 import된 modules은 _우선-파싱_ 되어요. import된 모듈은 _처음에_ 실행되는 것을 의미하고, import한 파일 안에 있는 코드는 _나중에_ 실행돼요. + +이것은 CommonJSd의 `require()`와 `import`의 차이예요! `require()`을 사용하면, 런타임 중 코드에서 필요한 시점에 의존성 모듈을 로드 할 수 있어요. 만약 `import` 대신에 `require`을 사용하면, `running index.js`, `running sum.js`, `3`으로 콘솔에 출력될 거에요. + +

+
+ +--- + +###### 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('foo')`와 두번째 `Symbol('foo')`. 이 두개의 값들은 유니크하며, 서로 같지 않아요, `Symbol('foo') === Symbol('foo')`는 `false`를 리턴해요. + +

+
+ +--- + +###### 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` 메소드에 전달된 인수가 배열의 길이보다 작다면, 패딩은 추가되지 않을 거예요. + +

+
From caffe51a40927daa5ed6964ae38184224fef6c53 Mon Sep 17 00:00:00 2001 From: Jordan Buckley Date: Wed, 10 Jul 2019 09:50:43 +1200 Subject: [PATCH 238/915] add missing closing single-quote in question 67 --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index ffcdfb46..c35f8d7e 100644 --- a/README.md +++ b/README.md @@ -2090,7 +2090,7 @@ The `Labrador` class receives two arguments, `name` since it extends `Dog`, and ```javascript // index.js -console.log('running index.js); +console.log('running index.js'); import { sum } from './sum.js'; console.log(sum(1, 2)); From e6df01a4f205c4e51e791c4487616b70d0f367b7 Mon Sep 17 00:00:00 2001 From: Alberto Fragoso Date: Tue, 9 Jul 2019 22:03:41 -0500 Subject: [PATCH 239/915] Fixing question # 67. That question doesn't correspond to its answers. --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index f3fb3a50..8b0fb25f 100644 --- a/README.md +++ b/README.md @@ -2086,7 +2086,7 @@ The `Dog` class receives two arguments, `name` since it extends `Animal`, and `s --- -###### 67. With which constructor can we successfully extend the `Dog` class? +###### 67. What's the output of the following code? ```javascript // index.js From 4f024152a9538f641ae7541688980680084c722b Mon Sep 17 00:00:00 2001 From: JesterPrince <45131249+JesterPrince@users.noreply.github.com> Date: Wed, 10 Jul 2019 11:09:55 +0200 Subject: [PATCH 240/915] Fix syntax error Adds a missing single quote thus fixing a syntax error. --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index f3fb3a50..f464b89a 100644 --- a/README.md +++ b/README.md @@ -2090,7 +2090,7 @@ The `Dog` class receives two arguments, `name` since it extends `Animal`, and `s ```javascript // index.js -console.log('running index.js); +console.log('running index.js'); import { sum } from './sum.js'; console.log(sum(1, 2)); From a0e41b8eaa3c97146a9f0fb747fe450f4236b2df Mon Sep 17 00:00:00 2001 From: yusufkaracin Date: Sun, 14 Jul 2019 09:49:50 +0300 Subject: [PATCH 241/915] translates to Turkish(1-69) and adds Turkish to README --- README-tr_TR.md | 2162 +++++++++++++++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 2163 insertions(+) create mode 100644 README-tr_TR.md diff --git a/README-tr_TR.md b/README-tr_TR.md new file mode 100644 index 00000000..4cbb1c4b --- /dev/null +++ b/README-tr_TR.md @@ -0,0 +1,2162 @@ +# JavaScript Sorular Listesi (İleri Düzey) + +[Instagram](https://www.instagram.com/theavocoder) hesabımda, günlük olarak çoktan seçmeli Javascript soruları paylaşıyorum, ayrıca burada da paylaşacağım! + +Temelden ileri düzeye: Javascript'i ne kadar iyi bildiğinizi test edin, bilginizi biraz tazeleyin ya da mülakatanıza hazırlanın! :muscle: :rocket: Repoyu haftalık olarak yeni sorularla güncelliyorum. Son güncelleme: Last update: 7 Temmuz + +Cevaplar, soruların altında gizlenmiştir. Görmek için sadece tıklayın. İyi şanşlar :heart: + +Mevcut dillerin listesi: + +* [English](./README.md) +* [العربية](./README_AR.md) +* [اللغة العامية - Egyptian Arabic](./README_ar-EG.md) +* [Bosanski](./README-bs_BS.md) +* [Deutsch](./README-de_DE.md) +* [Español](./README-ES.md) +* [日本語](./README-ja_JA.md) +* [한국어](./README-ko_KR.md) +* [Português Brasil](./README_pt_BR.md) +* [Русский](./README_ru-RU.md) +* [Українська мова](./README-ua_UA.md) +* [Tiếng Việt](./README-vi.md) +* [中文版本](./README-zh_CN.md) +* [Türkçe](./README-tr_TR.md) + +--- + +###### 1. Çıktısı nedir? + +```javascript +function sayHi() { + console.log(name); + console.log(age); + var name = "Lydia"; + let age = 21; +} + +sayHi(); +``` + +- A: `Lydia` ve `undefined` +- B: `Lydia` ve `ReferenceError` +- C: `ReferenceError` ve `21` +- D: `undefined` ve `ReferenceError` + +
Cevap +

+ +#### 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. +

+
+ +--- + +###### 2. Çıktısı Nedir? + +```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` ve `0 1 2` +- B: `0 1 2` ve `3 3 3` +- C: `3 3 3` ve `0 1 2` + +
Cevap +

+ +#### Cevap: C + +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. +

+
+ +--- + +###### 3. Çıktısı Nedir? + +```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` ve `62.83185307179586` +- B: `20` ve `NaN` +- C: `20` ve `63` +- D: `NaN` ve `63` + +
Cevap +

+ +#### Cevap: B + +`diameter` sıradan bir fonksiyonken, `perimeter`'in arrow fonksiyon olduğuna dikkat edin. + +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. + +

+
+ +--- + +###### 4. Çıktısı Nedir? + +```javascript ++true; +!"Lydia"; +``` + +- A: `1` and `false` +- B: `false` and `NaN` +- C: `false` and `false` + +
Cevap +

+ +#### Cevap: A + +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. +

+
+ +--- + +###### 5. Hangisi doğru? + +```javascript +const bird = { + size: "small" +}; + +const mouse = { + name: "Mickey", + small: true +}; +``` + +- A: `mouse.bird.size` geçerli değildir +- B: `mouse[bird.size]` geçerli değildir +- C: `mouse[bird["size"]]` geçerli değildir +- D: Hepsi geçerlidir + +
Cevap +

+ +#### Cevap: A + +Javascript'te, tüm nesne keyleri string'dir (Symbol olmadıkları müddetçe). Keyleri, string olarak _yazmadıysak_ bile, arka planda string'e çevrilirler. + +Javascript, ifadeleri yorumlar (ya da açar ("unboxes")). Köşeli parentez notasyonu kullandığımız zaman, Javascript ilk `[` görür ve `]` bulana kadar devam eder. Ancak ondan sonra ifadeyi hesaplar. + +`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 +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` + +
Cevap +

+ +#### Cevap: A + +Javascript'te tüm nesneler, birbirlerine eşitlendikleri zaman _referansları_ ile etkileşime girerler. + +Önce, `c` değişkeni bir nesnenin değerini tutuyor. Sonra, `d`'ye aynı referansı atadık ki bu referans da `c`'nin sahip olduğu nesnedir. + + +Bir nesneyi değiştirdiğiniz zaman, hepsini değiştirirsiniz. + +

+
+ +--- + +###### 7. Çıktısı Nedir? + +```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` + +
Cevap +

+ +#### Cevap: C + +`new Number()` yerleşik bir yapıcı fonksiyondur ("function constructor"). Sayı ("number") gibi gözükse de gerçekten bir sayı değil: bir kaç ekstra özelliğe sahip ve o bir nesne. + +`==` 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. +

+
+ +--- + +###### 8. Çıktısı Nedir? + +```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` + +
Cevap +

+ +#### 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. +

+
+ +--- + +###### 9. Çıktısı Nedir? + +```javascript +let greeting; +greetign = {}; // Yazım hatası! +console.log(greetign); +``` + +- A: `{}` +- B: `ReferenceError: greetign is not defined` +- C: `undefined` + +
Cevap +

+ +#### Cevap: A + +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. +

+
+ +--- + +###### 10. Bunu yaptığımız zaman ne gerçekleşir? + +```javascript +function bark() { + console.log("Woof!"); +} + +bark.animal = "dog"; +``` + +- A: Hiç bir şey, tamamen iyi! +- B: `SyntaxError`. Fonksiyonlara bu şekilde özellik atayamazsın. +- C: `"Woof"` şeklinde loglanır. +- D: `ReferenceError` + +
Cevap +

+ +#### Cevap: A + +Javascript'te bu mümkün, çünkü fonksiyonlar nesnedir! (Primitive tiplere nazaran her şey nesnedir) + +Fonksiyon özel bir nesne tipidir. Yazdığınız kod asıl fonksiyon değil. Fonksiyon, özelliklere sahip bir nesnedir. Bu özellik çalıştırabilme kapasitesine sahiptir ("invocable"). + +

+
+ +--- + +###### 11. Çıktısı Nedir? + +```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` + +
Cevap +

+ +#### 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() { + return `${this.firstName} ${this.lastName}`; +}; +``` + +`member.getFullName()` çalışmış olacak. Bu neden faydalı? Diyelim ki, yapıcının kendisine bu methodu ekledik. Belki de tüm `Person` instance'leri bu methoda ihtiyaç duymuyor. Bu özelliğe sahip olduklarından dolayı, her bir instance hafızadan yer alır, bu da bir sürü hafıza israfı demek. Bunun yerine, eğer sadece prototype'a eklersek, hafızadan sadece bir tek yer alırız ve yine de tüm instanceler bu özelliğe erişebilir! + +

+
+ +--- + +###### 12. Çıktısı Nedir? + +```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"}` ve `undefined` +- B: `Person {firstName: "Lydia", lastName: "Hallie"}` ve `Person {firstName: "Sarah", lastName: "Smith"}` +- C: `Person {firstName: "Lydia", lastName: "Hallie"}` ve `{}` +- D:`Person {firstName: "Lydia", lastName: "Hallie"}` ve `ReferenceError` + +
Cevap +

+ +#### Cevap: A + +`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. +

+
+ +--- + +###### 13. Olay silsilesinin (event propagation) üç aşaması nedir? + +- A: Target > Capturing > Bubbling +- B: Bubbling > Target > Capturing +- C: Target > Bubbling > Capturing +- D: Capturing > Target > Bubbling + +
Cevap +

+ +#### 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. + + + +

+
+ +--- + +###### 14. Bütün nesneler prototiplere sahiptir. + +- A: doğru +- B: yanlış + +
Cevap +

+ +#### 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. +

+
+ +--- + +###### 15. Çıktısı Nedir? + +```javascript +function sum(a, b) { + return a + b; +} + +sum(1, "2"); +``` + +- A: `NaN` +- B: `TypeError` +- C: `"12"` +- D: `3` + +
Cevap +

+ +#### Cevap: C + +Javascript **dinamik tipli dil**dir: değişkenlerin hangi tip olduğunu belirtmeyiz. Değerler otomatik olarak diğer tipi bilmeden dönüştürebilir, bu _implicit type coercion_, _örtük tip dönüşümü_, olarak adlandırılır. **Coercion** bir tipi diğer bir tipe dönüştürmektir. + +Bu örnekte, JavaScript sayı olan `1`'i string'e dönüştürüyor, fonksiyonun mantıklı olması ve değer döndürmesi için. Sayısal tip (`1`) ve string tip (`2`)'nin toplanması sırasında, sayıya string olarak muamele edilir. Stringleri `"Hello" + "World"` şeklinde birleştirebiliriz, yani burada olan `"1" + "2"` ki bu da `"12"` döndürür. + +

+
+ +--- + +###### 16. Çıktısı Nedir? + +```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` + +
Cevap +

+ +#### Cevap: C + +**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`) + +**ön ek**, **prefix**, `++` unary operatörü: + +1. Değeri arttırır (sayı şimdi `2`) +2. Değeri döndürür (`2` döndürür) + +Burada `0 2 2` döner. + +

+
+ +--- + +###### 17. Çıktısı Nedir? + +```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` + +
Cevap +

+ +#### Cevap: B + +Eğer "tagged template literals" kullanırsanoz, ilk argumanın değeri her zaman string değerler dizisidir. Geriye kalan argumanlar, ifadeye geçilen değerleri alır. + +

+
+ +--- + +###### 18. Çıktısı Nedir? + +```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` + +
Cevap +

+ +#### Cevap: C + +Eşitliği test ederken, nesneler _referanslarına_ göre kıyaslanırken primitifler _değerlerine_ göre kıyaslanır. Javascript, nesnelerin referanslarının hafızada aynı konumda olup olmadığını kontrol eder. + +Kıyasladığımız iki nesne bu şekilde değilse: parametre olarak geçtiğimiz nesne, hafızada eşitliğini kontrol ettiğimiz nesneden farklı bir konumu referans gösterir. + +Bu sebepten, `{ age: 18 } === { age: 18 }` ve `{ age: 18 } == { age: 18 }`, ikisi de `false` döndürür. + +

+
+ +--- + +###### 19. Çıktısı Nedir? + +```javascript +function getAge(...args) { + console.log(typeof args); +} + +getAge(21); +``` + +- A: `"number"` +- B: `"array"` +- C: `"object"` +- D: `"NaN"` + +
Cevap +

+ +#### Cevap: C + +Yayma operatorü, "spread operator", (`...args`) argumanların dahil olduğu bir dizi döndürür. Dizi bir nesnedir, bu yüzden `typeof args` `"object"` döndürür. + +

+
+ +--- + +###### 20. Çıktısı Nedir? + +```javascript +function getAge() { + "use strict"; + age = 21; + console.log(age); +} + +getAge(); +``` + +- A: `21` +- B: `undefined` +- C: `ReferenceError` +- D: `TypeError` + +
Cevap +

+ +#### Cevap: C + +`"use strict"` ile, yanlışlıkla global değişkenler tanımlamadığınızdan emin olabilirsiniz. `age` değişkenini hiç tanımlamadık ve `"use strict"` kullandığımızdan, referans hatası fırlatacaktır. Eğer `"use strict"` kullanmasaydık, `age` özelliği global nesneye eklenmiş olacağından, çalışmış olacaktı. + +

+
+ +--- + +###### 21. `sum`'ın değeri nedir? + +```javascript +const sum = eval("10*10+5"); +``` + +- A: `105` +- B: `"105"` +- C: `TypeError` +- D: `"10*10+5"` + +
Cevap +

+ +#### Cevap: A + +`eval`, string olarak geçilen kodu çalıştırır. Eğer bir ifadeyse, bu durumdaki gibi, ifadeyi çalıştırır. İfade `10 * 10 + 5`. Bu `105` sayısını döndürür. + +

+
+ +--- + +###### 22. cool_secret ne kadar süre boyunca erişebilinir? + +```javascript +sessionStorage.setItem("cool_secret", 123); +``` + +- A: Sonsuza kadar, veri kaybolmaz. +- B: Kullanıcı sekmeyi kapatınca. +- C: Kullanıcı tamamen tarayıcıyı kapattığı zaman, sadece sekmeyi değil. +- D: Kullanıcı bilgisayarını kapattığı zaman. + +
Cevap +

+ +#### Cevap: B + +`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. + +

+
+ +--- + +###### 23. Çıktısı Nedir? + +```javascript +var num = 8; +var num = 10; + +console.log(num); +``` + +- A: `8` +- B: `10` +- C: `SyntaxError` +- D: `ReferenceError` + +
Cevap +

+ +#### Cevap: B + +`var` anahtar kelimesi ile aynı isme sahip birden çok değişken tanımlayabilirsiniz. O halde değişken son değeri tutacak. + +Bunu `let` ya da `const` ile yapamazsınız, "block-scoped" olduklarından dolayı. + +

+
+ +--- + +###### 24. Çıktısı Nedir? + +```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` + +
Cevap +

+ +#### Cevap: C + +Tüm nesne anahtarları (Symbol'ler hariç) arka planda string'dir, kendiniz string olarak yazmasanız bile. Bu sebepten `obj.hasOwnProperty('1')` da `true` döndürür. + +Set için bu şekilde çalışmaz. Setimizde `'1'` yok: `set.has('1')` `false` döndürür. Setimiz sayısal tip `1`'e sahip, `set.has(1)` `true` döndürür. + +

+
+ +--- + +###### 25. Çıktısı Nedir? + +```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` + +
Cevap +

+ +#### Cevap: C + +Eğer aynı ada sahip iki tane anahtarınız, "key", varsa, anahtar değiştirilecektir. Hala ilk konumunda olacaktır ama son belirtilen değerle birlikte. + +

+
+ +--- + +###### 26. JavaScript global yürütme konteksti, "global execution context", sizin için iki şey oluşturur: global nesne, ve "this" anahtar kelimesi. + +- A: doğru +- B: yanlış +- C: değişir + +
Cevap +

+ +#### Cevap: A + +Temel yürütme konteksti, global yürütme kontekstidir: kodunuzda her yerde erişilebilir olan şeydir. + +

+
+ +--- + +###### 27. Çıktısı Nedir? + +```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` + +
Cevap +

+ +#### Cevap: C + +Eğer belirli şart `true` döndürürse, `continue` ifadesi yinelemeyi, "iteration", atlar. + +

+
+ +--- + +###### 28. Çıktısı Nedir? + +```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` + +
Cevap +

+ +#### Cevap: A + +`String`, özellikler de ekleyebileceğimiz tümleşik bir yapıcıdır. Prototipine bir method ekledim sadece. Primitif stringler, string prototip fonksiyonu tarafından üretilen string nesnesine otomatik olarak dönüştürülür. Bu yüzden, tüm stringler (string nesneleri) bu methoda erişebilir! + +

+
+ +--- + +###### 29. Çıktısı Nedir? + +```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` + +
Cevap +

+ +#### Cevap: B + +Nesne keyleri otomatik olarak stringe dönüştürülür. `a` nesnesine değeri `123` olacak şekilde, bir nesneyi key olarak atamaya çalışıyoruz. + +Ancak, bir nesnesi string hale getirince, `"[Object object]"` olur. Dolayısıyla burada söylediğimiz, `a["Object object"] = 123`. Sonra, aynı şeyi tekrar yapmayı deniyoruz. `c`, dolaylı olarak string hale getirdiğimiz başka bir nesne. O halde, `a["Object object"] = 456`. + +Sonra, `a[b]`'yi logluyoruz, ki aslında o da `a["Object object"]`. Onu da `456` olarak atamıştık, o yüzden `456` döndürür. + +

+
+ +--- + +###### 30. Çıktısı Nedir? + +```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` + +
Cevap +

+ +#### Cevap: B + +Bir `setTimeout` fonksiyonumuz var ve ilk onu çalıştırdık. Yine de en son loglandı. + +Bunun nedeni tarayıcılarda, "runtime engine"'a sahip olmamamızdan, `WebAPI` denilen bir şeye sahibiz. `WebAPI`, örneğin DOM ile çalışması için bize, `setTimeout` fonksiyonunu verir. + +_callback_ WebAPI'a eklendikten sonra, `setTimeout` fonksiyonun kendisi (callback hariç!) hafıza bloğundan atılır, "popped off the stack". + + + +Şimdi, `foo` çalıştı ve `"First"` loglandı. + + + +`foo` hafıza bloğundan atıldı ve `baz` çalıştı. `"Third"` loglandı. + + + +WebAPI, her ne zaman bir şeyler hazırsa hafıza bloğuna öylece ekleyemez. Onun yerine callback fonksiyonunu, _queue_ diye adlandıralan bir şeye ekler. + + + +Burası olay döngüsünün çalışmaya başlayacapı yerdir. **olay döngüsü**, **event loop**, hafıza bloğuna ve iş kuyruğuna, "task queue", bakar. Eğer hafıza bloğu boşsa, kuyruktaki ilk şeyi alır ve hafıza bloğuna ekler. + + + +`bar` çalıştı, `"Second"` loglandı ve hafıza bloğundan atıldı. + +

+
+ +--- + +###### 31. Butona tıklandığında, event.target nedir? + +```html +
+
+ +
+
+``` + +- A: Dıştaki `div` +- B: İçteki `div` +- C: `button` +- D: İç içe olan tüm elemanlar listesi. + +
Cevap +

+ +#### Cevap: C + +Olaya sebep olan en derindeki iç eleman, olayın hedefidir ("event.target"). `event.stopPropagation` kullanarak "bubbling"'i durdurabilirsiniz. + +

+
+ +--- + +###### 32. Paragrafa tıkladığınız zaman, çıktı olarak ne loglanır? + +```html +
+

+ Click here! +

+
+``` + +- A: `p` `div` +- B: `div` `p` +- C: `p` +- D: `div` + +
Cevap +

+ +#### Cevap: A + +Eğer `p`'ye tıklarsak, iki log görürüz: `p` ve `div`. Olay silsilesi, "event propagation", sırasında, 3 aşama vardır: "capturing", "target", ve "bubbling". Varsayılan olarak, olay işleyiciler, "event handlers", "bubbling" aşamasında (`useCapture`'ı `true` olarak ayarlanmadığı müddetçe) çalıştırılır. En derin elemandan dışa doğru gider. + +

+
+ +--- + +###### 33. Çıktısı Nedir? + +```javascript +const person = { name: "Lydia" }; + +function sayHi(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` + +
Cevap +

+ +#### Cevap: D + +İkisinde de, `this` anahtar kelimesinin referans olmasını istediğimiz nesneyi geçebiliriz. Ancak, `.call` _anında çalıştırılır_! + +`.bind.` fonksiyonun _kopyasını_ döndürür, ama konteksle bağlı şejilde. Anında çalıştırılmaz. + +

+
+ +--- + +###### 34. Çıktısı Nedir? + +```javascript +function sayHi() { + return (() => 0)(); +} + +console.log(typeof sayHi()); +``` + +- A: `"object"` +- B: `"number"` +- C: `"function"` +- D: `"undefined"` + +
Cevap +

+ +#### Cevap: B + +`sayHi` fonksiyonu, anında çalıştırılan fonksiyonun, "immediately invoked function (IIFE)", döndürdüğü değeri döndürür. Bu fonksiyon `0` döndürdü, k, tipi `"number"`'dır. + +Bilginize; 7 tane tümleşik tip vardır: `null`, `undefined`, `boolean`, `number`, `string`, `object`, ve `symbol`. Fonksiyonlar nesne olduklarından, `"function"` tip değildir. Fonksiyonun tipi `"object"`'dir. + +

+
+ +--- + +###### 35. Bu değerlerden hangileri yanlış-ımsıdır (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 + +
Cevap +

+ +#### Cevap: A + +Sadece 6 tane yanlış-ımsı, "falsy", değer vardır: + +- `undefined` +- `null` +- `NaN` +- `0` +- `''` (empty string) +- `false` + +Fonksiyon yapıcıları, `new Number` ve `new Boolean` gibi, doğrusaldır. + +

+
+ +--- + +###### 36. Çıktısı Nedir? + +```javascript +console.log(typeof typeof 1); +``` + +- A: `"number"` +- B: `"string"` +- C: `"object"` +- D: `"undefined"` + +
Cevap +

+ +#### Cevap: B + +`typeof 1` `"number"` döndürür. +`typeof "number"` `"string"` döndürür. + +

+
+ +--- + +###### 37. Çıktısı Nedir? + +```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` + +
Cevap +

+ +#### Cevap: C + +Dizi içinde, dizinin uzunluğunu aşan bir elemana değer atadığınızda, JavaScript "boş alanlar, "empty slots", denilen bir şey oluşturur. Bunların değeri aslında `undefined` olsa da şöyle bir şey görürsünüz: + +`[1, 2, 3, 7 x empty, 11]` + +nerede çalıştırdığınıza bağlı olarak (her tarayıcı, node, vb... için farklıdır.) + +

+
+ +--- + +###### 38. Çıktısı Nedir? + +```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` + +
Cevap +

+ +#### Cevap: A + +`catch` bloğu `x` argumanını alıyor. Argumanları geçtiğimiz zaman, bu değişken olan `x` ile aynı değildir. Bu `x` değişkeni block-scoped'dur. + +Sonra, bu block-scoped değişkeni `1`'e eşit olarak ayarladık ve `y` değişkeninin değerini ayarladık. Block-scoped `x` değişkenini logladık, ki değeri `1`'e eşitti. + +`catch` bloğunun dışında, `x` hala `undefined`, ve `y` `2`'dir. `catch` bloğunun dışında, `console.log(x)` çalıştırmak istediğimizde `undefined` döndürür ve `y` `2` döndürür. + +

+
+ +--- + +###### 39. JavaScript'teki her şey ya bir... + +- A: primitifdir ya da nesnedir +- B: fonksiyondur or nesnedir +- C: tuzak soru! sadece nesnedir +- D: sayıdır (number) ya da nesnedir + +
Cevap +

+ +#### Cevap: A + +JavaScript sadece primitif ve nesne tiplerine sahiptir. + +Primitif tipler, `boolean`, `null`, `undefined`, `bigint`, `number`, `string`, ve `symbol`. + +Primitif ve nesneyi birbirinden ayıran, primitif tiplerin herhangi bir özelliğie ya da methoda sahip olmamasıdır; ancak, fark edeceğiniz üzere `'foo'.toUpperCase()` `'FOO'` olarak değer döndürür ve `TypeError` ile sonuçlanmaz. Bunun sebebi, string gibi primitif bir tip üzerinde özelliğe ya da methoda erişmeye çalıştığınızda, JavaScript sarıcı sınıflardan, "wrapper classes", birini kullanarak nesneyi dolaylı şekilde sarar, örneğin `String`, ve sonrasında ifade çalıştıktan sonra anında sarıcıyı ayırır. `null` ve `undefined` dışındaki tüm primitifler bu şekilde davranır. + +

+
+ +--- + +###### 40. Çıktısı Nedir? + +```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]` + +
Cevap +

+ +#### Cevap: C + +`[1, 2]` başlangıç değerimizdir. Başladığımız değer budur ve `acc`'nin en ilk değeridir. İlk tur süresince, `acc` `[1,2]`'dir ve `cur` `[0, 1]`'dir. Onları birleştiririz ve `[1, 2, 0, 1]` olarak sonuçlanır. + +Sonra, `acc` `[1, 2, 0, 1]`'dir ve `cur` `[2, 3]`'dür. Onları birleştiririz ve `[1, 2, 0, 1, 2, 3]` elde ederiz. + +

+
+ +--- + +###### 41. Çıktısı Nedir? + +```javascript +!!null; +!!""; +!!1; +``` + +- A: `false` `true` `false` +- B: `false` `false` `true` +- C: `false` `true` `true` +- D: `true` `true` `false` + +
Cevap +

+ +#### Cevap: B + +`null` yanlış-ımsıdır, "falsy". `!null` `true` döndürür. `!true` `false` döndürür. + +`""` yanlış-ımsıdır. `!""` `true` döndürür. `!true` `false` döndürür. + +`1` doğrusaldır. `!1` `false` döndürür. `!false` `true` döndürür. + +

+
+ +--- + +###### 42. `setInterval` methodu tarayıcıda ne döndürür? + +```javascript +setInterval(() => console.log("Hi"), 1000); +``` + +- A: benzersiz bir id +- B: belirtilen milisayine tutarı +- C: gönderilen fonksiyon +- D: `undefined` + +
Cevap +

+ +#### Cevap: A + +Benzersiz bir id döndürür. Bu id, süre aralığını, "interval", `clearInterval()` fonksiyonu ile temizlemek için kullanılabilinir. + +

+
+ +--- + +###### 43. Ne döndürür? + +```javascript +[..."Lydia"]; +``` + +- A: `["L", "y", "d", "i", "a"]` +- B: `["Lydia"]` +- C: `[[], "Lydia"]` +- D: `[["L", "y", "d", "i", "a"]]` + +
Cevap +

+ +#### Cevap: A + +String, yinelenebilirdir, "iterable". Yayma operatörü, yenilenebilirin her bir karakterini bir elemana eşler. + +

+
+ +--- + +###### 44. Çıktısı Nedir? + +```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` + +
Cevap +

+ +#### 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_). + +Önce, generator fonksiyonu `i`'yi `10`'a eşitleyerek başlatıyoruz. `next()` methodunu 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ı. + +Sonra, `next()` methodunu kullanarak fonksiyonu tekrar çalıştırıyoruz. Fonksiyon önceki kaldığı yerden çalışmaya devam ediyor, `i` hala `10`'a eşit. Şimdi, fonksiyon sıraki `yield` anahtar kelimesi ile karşılaşıyor, ve `i * 2`'yi veriyor, yani fonksiyon `10 * 2` veriyor, ki o da `20`'dir. `10, 20` şeklinde sonuçlanıyor. + +

+
+ +--- + +###### 45. Ne döndürür? + +```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"` + +
Cevap +

+ +#### Cevap: B + +`Promise.race` methoduna birçok promise geçtiğimiz zaman, _ilk_ çözümlenen/reddedilen, "resolves/rejects", promise'i çözümler/reddeder . `setTimeout` methoduna, zamanlayıcı, "timer", geçtik: ilk promise (`firstPromise`) için 500ms, ve ikinci promise (`secondPromise`) için 100ms. Bu demektir ki `secondPromise` `'two'` değeriyle birlikte önce çözümlenir. `res` sakladığı `'two'` değeriyle loglanır. + +

+
+ +--- + +###### 46. Çıktısı Nedir? + +```javascript +let person = { name: "Lydia" }; +const members = [person]; +person = null; + +console.log(members); +``` + +- A: `null` +- B: `[null]` +- C: `[{}]` +- D: `[{ name: "Lydia" }]` + +
Cevap +

+ +#### Cevap: D + +Önce, `person` değişkenini, `name` özelliğine sahip bir nesne değeriyle birlikte tanımlarız. + + + +Sonra, `members` olarak adlandırdığımız değişkeni tanımlarız. Bu dizinin ilk elemanını, `person` değişkeninin değerine eşit olarak ayarlarız. Nesneler, birbirlerine eşitlendiklerinde, _referans_ üzerinden etkileşime girer. Bir referansı, bir değişkenden diğerine atadığınız zaman, o referansın _kopyasını_ oluşturursunuz. (değişkenlerin _aynı_ referansa sahip olmadığına dikkat edin!) + + + +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. + +

+
+ +--- + +###### 47. Çıktısı Nedir? + +```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]` + +
Cevap +

+ +#### Cevap: B + +`for-in` döngüsüyle, nesne keyleri boyunca ileryebiliriz, bu durumda `name` ve `age`. Temelde, nesne keyleri stringdir (eğer Symbol değilse). Her döngüde, `item`'in değerini, döngü sırasındaki geçerli key olarak eşitleriz. Önce, `item` `name`'e eşittir, ve loglanır. Sonra loglanan `item`, `age`'e eşittir. + +

+
+ +--- + +###### 48. Çıktısı Nedir? + +```javascript +console.log(3 + 4 + "5"); +``` + +- A: `"345"` +- B: `"75"` +- C: `12` +- D: `"12"` + +
Cevap +

+ +#### Cevap: B + +Operatör birleşme özelliği, "operator associativity, derleyicinin ifadeleri çalıştırdığı sıradır, ya soldan sağa ya da sağdan soladır. Bu sadece, eğer tüm operatörler _aynı_ önceliğe sahipse gerçekleşir. Sadece tek tip operatörümüz var: `+`. Toplama için birleşme özelliği soldan sağadır. + +`3 + 4` önce çalıştırılır. `7` sayısı olarak sonuçlanır. + +Tip baskısından, "coercion", dolayı `7 + '5'`, `"75"` olarak sonuçlanır. JavaScript `7` sayısını string'e çevirir, 15. soruya bakabilirsiniz. İki string'i `+` operatörünü kullanarak birleştirebiliriz. `"7" + "5"` `"75"` olarak sonuçlanır. + +

+
+ +--- + +###### 49. `num` ın değeri nedir? + +```javascript +const num = parseInt("7*6", 10); +``` + +- A: `42` +- B: `"42"` +- C: `7` +- D: `NaN` + +
Cevap +

+ +#### Cevap: C + +Sadece string içindeki ilk sayılar döndürülür. _Sayı tabanına_ (hangi tipte sayıya çözümlemek istediğimizi belirtmek için geçilen ikinci argüman: 10'lu, onaltılı, sekizli, ikili tabanda vb...) bağlı olarak, `parseInt` string içindeki hangi karakterlerin geçerli olduğunu kontrol eder. Sayı tabanında, geçerli olmayan bir karaktere denk geldiğinde, çözümleyi durdurur ve sonraki gelen karakterleri görmezden gelir. + +`*` geçerli bir sayı değil. `parseInt` sadece `"7"`'yi ondalık sistemde `7`'ye çözümler. `num`, `7` değerini saklıyor artık. + +

+
+ +--- + +###### 50. Çıktısı Nedir`? + +```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 ]` + +
Cevap +

+ +#### 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. + +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. + +

+
+ +--- + +###### 51. Çıktısı Nedir? + +```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"` + +
Cevap +

+ +#### Cevap: A + +Argümanlar _değer_ olarak geçilir, değerleri nesne olmadıkları müddetçe, eğer öyleyse _referans_ olarak geçilir. `birthYear` nesne değil string olduğundan değer olarak geçilir. Argümanları değer olarak geçtiğimizde, o değerin bir _kopyası_ oluşturulur (46. soruya göz atın). + +`birthYear` değişkeni `"1997"` değeri için referansa sahip. `year` argümanı da ayrıca `"1997"` değeri için referansa sahip, ama `birthYear`'ın sahip olduğu referansın değeri ile aynı değer değil. `year`'ın değerini `"1998"`'e eşit olarak ayarlayıp güncellediğimizde, sadece `year`'ın değerini güncelleriz. `birthYear` hala `"1997"`'e eşittir. + +`person`'ın değeri bir nesnedir. `member` argümanı _aynı_ nesne için (kopyalanmış) referansa sahip. `member` nesnesinin özelliğini değiştirdiğimizde, `person`'ın değeri de ayrıca değişmiş olacaktır, ikisi de aynı nesne için referansa sahip olduklarından. `person`'ın `name` özelliği şimdi `"Lydia"` değerine eşittir. + +

+
+ +--- + +###### 52. Çıktısı Nedir? + +```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!` + +
Cevap +

+ +#### Cevap: D + +`throw` ifadesi ile, özelleştirilmiş hatalar oluşturabiliriz. Bu ifade ile, hatalar fırlatabilirsiniz. Hata durumu, "exception", bir string, sayı, doğru/yanlış ya da nesne olabilir. Bu durumda, bizim hata durumumuz string olan `'Hello world'`. + +`catch` ifadesi ile, eğer `try` bloğunda bir hata durumu fırlatılmışsa ne yapacağımızı belirtebiliriz. Bir hata durumu fırlatıldı: `'Hello world'` string'i. `e` artık bu string'e eşit, ki onu logluyoruz. `'Oh an error: Hello world'` olarak sonuç veriyor. + +

+
+ +--- + +###### 53. Çıktısı Nedir? + +```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` + +
Cevap +

+ +#### Cevap: B + +Bir özellik döndürdüğünüz zaman, özelliğin değeri _döndürülen_ değere eşittir, yapıcı fonksiyon içinde atanmış değere değil. `"Maserati"` string'ini döndürüyoruz, yani `myCar.make` `"Maserati"`'ye eşittir. + +

+
+ +--- + +###### 54. Çıktısı Nedir? + +```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"` + +
Cevap +

+ +#### Cevap: A + +`let x = y = 10;` aslında şunun için kısa yazımdır: + +```javascript +y = 10; +let x = y; +``` + +`y`'yi `10`'a eşit olarak ayarladığımızda, aslında global nesneye `y` özelliğini ekliyoruz (tarayıcıda `window`, Node içinde `global`). Tarayıcıda, `window.y` artık `10`'a eşit. + +Sonra, `x` değişkenini `y`'nin değeri ile birlkte tanımlıyoruz ki o da `10`. `let` anahtar kelimesi ile tanımlanan değişkenler _block scope_'dur, onlar sadece tanımlandıkları blok içinde sınırlıdır; bu durumda anında çalıştırılan fonksiyon, "immediately-invoked function (IIFE)", ile sınırlı. `typeof` operatörünü kullandığımız zaman, `x` operandı tanımlı değil: `x`'e tanımlandığı bloğun dışından erişmeye çalışıyoruz. Bu, `x` tanımlanmadı demektir. Bir değer ataması yapılmamış ya da tanımlanmamış değerlerin tipi `"undefined"`'dır. `console.log(typeof x)` `"undefined"` döndürür. + +Ancak, `y`'yi `10`'a eşitlerken global değişken `y`'yi oluşturduk. Bu değer kodunuzun herhangi bir yerinden erişilebilinir. `y` tanımlı ve `"number"` tipinde değeri saklıyor. `console.log(typeof y)` `"number"` döndürür. + +

+
+ +--- + +###### 55. Çıktısı Nedir? + +```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` + +
Cevap +

+ +#### Cevap: A + +`delete` anahtar kelimesini kullanarak özellikleri hem nesnelerden hem de prototip üzerinden silebiliriz. Prototip üzerindeki bir özellik silindiğinde, artık prototip zincirinde kullanıma müsait değildir. Bu durumda, `bark` fonksiyonu, `delete Dog.prototype.bark` ardından, prototip üzerinden kullanılabilir değildir fakat yine de erişmeye çalışıyoruz. + +Fonksiyon olmayan bir şeyi çalıştırmayı denediğimiz zaman, `TypeError` fırlatılır. Bu durumda, `pet.bark` `undefined` olduğundan, `TypeError: pet.bark is not a function` fırlatıldı. + +

+
+ +--- + +###### 56. Çıktısı Nedir? + +```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}` + +
Cevap +

+ +#### Cevap: D + +`Set` nesnesi _benzersiz_ değerlerin koleksiyonudur: bir değer, set içinde sadece bir kez bulunabilir. + +Yinelenebilir `[1, 1, 2, 3, 4]`'i çift `1` değeriyle birlikte geçtik. Set içinde aynı değere iki kere sahip olamayacağımızdan, bir tanesi kaldırıldı. Sonuç, `{1, 2, 3, 4}`. + +

+
+ +--- + +###### 57. Çıktısı Nedir? + +```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` + +
Cevap +

+ +#### Cevap: C + +İçe aktarılan, "imported", modul _salt okur_'dur: içe aktarılan modulü değiştiremezsiniz. Sadece, dışa aktarım yapan modul değerini değiştirebilir. + +`myCounter`'ın değerini arttırmaya çalıştığımız zaman, hata fırlatır: `myCounter` salt okurdur ve değiştirilemez. + +

+
+ +--- + +###### 58. Çıktısı Nedir? + +```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` + +
Cevap +

+ +#### Cevap: A + +`delete` operatörü doğru/yanlış, "boolean", değer döndürür: silme başarılıysa `true`, değilse `false` döndürecektir. Ancak, `var`, `const` ya da `let` anahtar kelimeleri ile tanımlanan değişkenler, `delete` kullanılarak silinemez. + +`name` değişkeni `const` anahtar kelimesi ile tanımlandı, yani silinme işlemi başarılı değil: `false` döndü. `age`'i `21`'e eşitlediğimizde, global nesneye `age` diye özellik ekledik aslında. Bu yöntemle, sorunsuz şekilde nesnelerden özellikleri silebilirsiniz, böylelikle `delete age` `true` döndürür. + +

+
+ +--- + +###### 59. Çıktısı Nedir? + +```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]` + +
Cevap +

+ +#### Cevap: C + +Listelerden değerleri ya da nesnelerden özellikleri, yıkım yoluyla, "destructuring", çıkarabiliriz. Örneğin: + +```javascript +[a, b] = [1, 2]; +``` + + + +`a`'nın değeri `1` ve `b`'nin değeri `2`'dir. Bu soruda aslında yaptığımız şuydu: + +```javascript +[y] = [1, 2, 3, 4, 5]; +``` + + + +Bu demektir ki, `y`'nin değeri dizideki ilk değere eşit, o da `1` sayısıdır. `y`'yi logladığımız zaman, `1` döndürülür. + +

+
+ +--- + +###### 60. Çıktısı Nedir? + +```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 }` + +
Cevap +

+ +#### Cevap: B + +Nesneleri `...` yayma operatörü kullanarak birleştirmek, kombine etmek, mümkündür. Bir nesnenin key/değer kopyasını oluşturmanıza olanak sunar, ve key/değerleri diğer nesneye ekler. Bu durumda, `user` nesnesinin kopyasını oluşturuyoruz, ve onları `admin` nesnesine ekliyoruz. `admin` nesnesi şimdi kopyalanan key/değerleri de içeriyor, ki bu da `{ admin: true, name: "Lydia", age: 21 }` olarak sonuç verir. + +

+
+ +--- + +###### 61. Çıktısı Nedir? + +```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"]` + +
Cevap +

+ +#### Cevap: B + +`defineProperty` methodu ile, nesnelere yeni özellikler ekleyebiliriz, ya da var olanları değiştirebiliriz. `defineProperty` methodu kullanarak bir nesneye özellik eklediğimiz zaman, varsayılan olarak _sıralanabilir değildir_, "_not enumerable_". `Object.keys` methodu, bir nesneden tüm _sıralanabilir_ özelliklerin adını döndürür, bu durumda sadece `"name"`. + +`defineProperty` methodu kullanılarak eklenen özellikler, varsayılan olarak değişmezdir. Bu davranışı `writable`, `configurable` ve `enumerable` kullaranak ezebilirsiniz. Bu yöntemle, `defineProperty` methodu nesnelere eklediğiniz özellikler üzerinde size çok daha fazla kontrol verir. + +

+
+ +--- + +###### 62. Çıktısı Nedir? + +```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}"` + +
Cevap +

+ +#### Cevap: A + +`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 _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. + +

+
+ +--- + +###### 63. Çıktısı Nedir? + +```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` + +
Cevap +

+ +#### Cevap: A + +`++` unary operatörü _önce_ operandın değerini döndürür, _sonra_ operandın değerini arttırır. `increaseNumber` fonksiyonu önce değeri `10` olan `num`'ın değerini döndürdüğünden, `num1`'ın değeri `10`'dur, ve `num`'ın değeri ancak bundan sonra artar. + +`increasePassedNumber`'a `num1`'i geçtiğimizden, `num2`'nin değeri `10`'dur. `number` `10`'a eşittir (`num1`'ın değeri. Bir kez daha, `++` operatörü _önce_ operandın değerini döndürür, _sonra_ operandın değerini arttırır. `number`'ın değeri `10`, yani `num2` `10`'a eşittir.) + +

+
+ +--- + +###### 64. Çıktısı Nedir? + +```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` + +
Cevap +

+ +#### Cevap: C + +ES6'da, parametrelere varsayılan değer atayabiliriz. Eğer fonksiyona değer geçilmezse ya da parametrenin değeri `undefined` ise, parametrenin değeri varsayılan değer olacaktır. Bu örnekte, `value` nesnesinin özelliklerini yeni nesneye yaydık, böylece `x` varsayılan değer olarak `{ number: 10}`'a sahip. + +Varsayılan argüman _çağrı sırasında_, "_call time_", çalıştırılır. Fonksiyonu her çağırdığımızda, _yeni_ bir nesne oluşturulur. `multiply` fonksiyonunu ilk iki seferde değer geçmeden çağırdık: `x` varsayılan değeri olan `{ number: 10 }`'a sahip. Sonra, bu sayının çarpılmış değerini logluyoruz, o da `20`. + +Üçüncü kez, `multiply`'ı çağırdığımız zaman, argüman geçiyoruz: `value` isimli nesne. `*=` operatörü aslında `x.number = x.number * 2` için kısa yazımdır: `x.number`'ın değerini değiştiriyoruz ve çarpılmış değer olan `20`'yi logluyoruz. + +Dördüncü kez, `value` nesnesini tekrar geçiyoruz. `x.number` önceden `20`'ye değiştirilmişti, yani `x.number *= 2` `40` loglar. + +

+
+ +--- + +###### 65. Çıktısı Nedir? + +```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` + +
Cevap +

+ +#### Cevap: D + +`reduce` methodunun aldığı ilk argüman _biriktiricidir_, "_accumulator_", bu örnekte `x`. İkinci argüman _o anki değerdir_, `y`. reduce methodu ile, dizideki her eleman üzerinde callback fonksiyonunu çalıştırırız, bu da en sonunda tek bir değer sonuçlanabilir. + +Bu örnekte, geriye bir değer döndürmüyoruz, sadece biriktiricinin değerini ve o anki değeri logluyoruz. + +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. + +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. + +Dördündü çağrıda, tekrar callback fonksiyonundan değer döndürmüyoruz. Biriktirici tekrar `undefined`, ve o anki geçerli değer `4`. `undefined` ve `4` loglanır. + +

+
+ +--- + +###### 66. Hangi yapıcı method (constructor) ile `Dog` sınıfından başarılı şekilde kalıtım yapabiliriz? + +```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 + +
Cevap +

+ +#### Cevap: B + +Türetilmiş bir sınıfta, `super`'i çağırmadan önce `this` anahtar kelimesine erişemezsiniz. Eğer erişmeyi denerseniz, ReferenceError fırlatır: 1 ve 4 referans hatası fırlatır. + +`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. + +

+
+ +--- + +###### 67. Çıktısı Nedir? + +```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` + +
Cevap +

+ +#### Cevap: B + +`import` anahtar kelimesiyle, tüm içe aktarılan modüller _ilk çözümlenir_, "_pre-parsed_". Bu şu demektir, içe aktarılan modüller _önce_ çalışır, içe aktarım yapan dosyadaki kodlar _sonra_ çalıştırılır. + +CommonJS'deki `require()` ve `import` arasındaki fark budur! `require()` ile, bağımlılıkları kod çalışmaya başladığında yükleyebilirsiniz. `import` yerine `require` kullanmış olsaydık, `running index.js`, `running sum.js`, `3` konsolda loglanmış olacaktı. + +

+
+ +--- + +###### 68. Çıktısı Nedir? + +```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` + +
Cevap +

+ +#### Cevap: A + +Her Symbol tamamen benzersizdir. Symbol'e geçilen argümanın amacı, Symbol'e bir açıklama vermektir. Symbol'ün değeri geçilen argümana bağlı değildir. Eşitliği test ederken, tamamen yeni iki symbol oluşturuyoruz: ilki `Symbol('foo')` ve ikincisi `Symbol('foo')`. Bu iki değer benzersiz ve birbirlerine eşit değil, `Symbol('foo') === Symbol('foo')` `false` döndürür. + +

+
+ +--- + +###### 69. Çıktısı Nedir? + +```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"`, + +
Cevap +

+ +#### Cevap: C + +`padStart` methoduyla, bir string'in başlangıcına dolgu yapabiliriz. Bu methoda geçilen değer, dolguyla beraber string'in _toplam_ uzunluğudur. `"Lydia Hallie"`'in uzunluğu `12`, `name.padStart(13)` string'in başlangıcına 1 boşluk eker, çünkü 12 + 1 = 13. + +Eğer `padStart` methoduna geçilen argüman, string'in uzunluğundan daha azsa, dolgu yapılmaz. + +

+
diff --git a/README.md b/README.md index f3fb3a50..b13c0567 100644 --- a/README.md +++ b/README.md @@ -21,6 +21,7 @@ List of available languages: * [Українська мова](./README-ua_UA.md) * [Tiếng Việt](./README-vi.md) * [中文版本](./README-zh_CN.md) +* [Türkçe](./README-tr_TR.md) --- From b5d0a23dc5793cc36dcaa982e90cf8d4e7e97dcf Mon Sep 17 00:00:00 2001 From: Lydia Hallie Date: Sun, 14 Jul 2019 21:05:20 +0200 Subject: [PATCH 242/915] Add questions 70-78 --- README.md | 292 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 292 insertions(+) diff --git a/README.md b/README.md index f3fb3a50..89579358 100644 --- a/README.md +++ b/README.md @@ -2167,3 +2167,295 @@ If the argument passed to the `padStart` method is smaller than the length of th

+ +--- + +###### 70. What's the output? + +```javascript +console.log("🥑" + "💻"); +``` + +- A: `"🥑💻"` +- B: `257548` +- C: A string containing their code points +- D: Error + +
Answer +

+ +#### Answer: 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 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")` + +
Answer +

+ +#### Answer: 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-statemnet returns `false`, and `JavaScript loves you back ❤️` gets logged. + +

+
+ +--- + +###### 72. What's the output? + +```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` 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. What's the 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` + +
Answer +

+ +#### Answer: 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. What's the 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` + +
Answer +

+ +#### Answer: 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. What's the output? + +```javascript +const box = { x: 10, y: 20 }; + +Object.freeze(box); + +const shape = box; +shape.x = 100; +``` + +- A: `{ x: 100, y: 20 }` +- B: `{ x: 10, y: 20 }` +- C: `{ x: 100 }` +- D: `ReferenceError` + +
Answer +

+ +#### Answer: B + +`Object.freeze` makes it impossible to add, remove, or modify properties of an object (unless the property's value os 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. + +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. What's the output? + +```javascript +const { name: myName } = { name: "Lydia" }; + +console.log(name); +``` + +- A: `"Lydia"` +- B: `"myName"` +- C: `undefined` +- D: `ReferenceError` + +
Answer +

+ +#### 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, a ReferenceError gets thrown. + +

+
+ +--- + +###### 77. Is this a pure function? + +```javascript +function sum(a, b) { + return a + b; +} +``` + +- A: Yes +- B: No + +
Answer +

+ +#### Answer: 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) { + console.log(`From cache! ${cache[num]}`); + } else { + const result = num + 10; + console.log(`Calculated! ${result}`); + cache[num] = 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 + +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. + +

+
From b4cf9c28713886c834d42300085c1236633eab09 Mon Sep 17 00:00:00 2001 From: Lydia Hallie Date: Sun, 14 Jul 2019 21:06:54 +0200 Subject: [PATCH 243/915] Update last updated date --- README.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 89579358..92df6f01 100644 --- a/README.md +++ b/README.md @@ -2,7 +2,7 @@ I post daily multiple choice JavaScript questions on my [Instagram](https://www.instagram.com/theavocoder), which I'll also post 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 weekly with new questions. Last update: July 7th +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 weekly with new questions. Last update: July 14th The answers are in the collapsed sections below the questions, simply click on them to expand it. Good luck :heart: @@ -1963,7 +1963,7 @@ The unary operator `++` _first returns_ the value of the operand, _then incremen --- -###### 64. What's the output? +###### 64. What's the output? ```javascript const value = { number: 10 }; @@ -2170,7 +2170,7 @@ If the argument passed to the `padStart` method is smaller than the length of th --- -###### 70. What's the output? +###### 70. What's the output? ```javascript console.log("🥑" + "💻"); From a8e8b583aefea01f28e7e836a349b05108e8978d Mon Sep 17 00:00:00 2001 From: Lydia Hallie Date: Sun, 14 Jul 2019 21:17:31 +0200 Subject: [PATCH 244/915] Use return instead of console.log --- README.md | 27 +++++++++++++-------------- 1 file changed, 13 insertions(+), 14 deletions(-) diff --git a/README.md b/README.md index 34f04272..39fa0d7b 100644 --- a/README.md +++ b/README.md @@ -21,7 +21,6 @@ List of available languages: * [Українська мова](./README-ua_UA.md) * [Tiếng Việt](./README-vi.md) * [中文版本](./README-zh_CN.md) -* [Türkçe](./README-tr_TR.md) --- @@ -1195,7 +1194,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 object 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 implicity wrap the object 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.

@@ -1435,7 +1434,7 @@ for (const item in person) { #### Answer: 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. +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.

@@ -1688,7 +1687,7 @@ pet.bark(); ``` - A: `"Woof I am Mara"`, `TypeError` -- B: `"Woof I am Mara"`, `"Woof I am Mara"` +- B: `"Woof I am Mara"`,`"Woof I am Mara"` - C: `"Woof I am Mara"`, `undefined` - D: `TypeError`, `TypeError` @@ -1921,7 +1920,7 @@ console.log(data); 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 an _array_, only the properties which names are included in the array will be added to the JSON string. In this case, only the properies 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. @@ -1970,7 +1969,7 @@ The unary operator `++` _first returns_ the value of the operand, _then incremen const value = { number: 10 }; const multiply = (x = { ...value }) => { - console.log((x.number *= 2)); + console.log((x.number * 2)); }; multiply(); @@ -1991,9 +1990,9 @@ multiply(value); 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 defeault 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 valled `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`. @@ -2081,17 +2080,17 @@ In a derived class, you cannot access the `this` keyword before calling `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`, 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. +The `Dog` class receives two arguments, `name` since it extends `Animal`, and `size` as an extra property on the `Dog` class. They both need to be passed to the constructor function on `Dog`, which is done correctly using constructor 2.

--- -###### 67. What's the output? +###### 67. With which constructor can we successfully extend the `Dog` class? ```javascript // index.js -console.log('running index.js'); +console.log('running index.js); import { sum } from './sum.js'; console.log(sum(1, 2)); @@ -2137,7 +2136,7 @@ console.log(Symbol('foo') === Symbol('foo')) #### Answer: 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`.

@@ -2423,11 +2422,11 @@ const add = () => { const cache = {}; return num => { if (num in cache) { - console.log(`From cache! ${cache[num]}`); + return `From cache! ${cache[num]}`; } else { const result = num + 10; - console.log(`Calculated! ${result}`); cache[num] = result; + return `Calculated! ${result}`; } }; }; From 3022ceb11a4f5f9d0326d6c550cd1438d26ca42e Mon Sep 17 00:00:00 2001 From: Lydia Hallie Date: Sun, 14 Jul 2019 21:28:21 +0200 Subject: [PATCH 245/915] Fix typos --- README.md | 23 ++++++++++++----------- 1 file changed, 12 insertions(+), 11 deletions(-) diff --git a/README.md b/README.md index 39fa0d7b..e52ef4d7 100644 --- a/README.md +++ b/README.md @@ -21,6 +21,7 @@ List of available languages: * [Українська мова](./README-ua_UA.md) * [Tiếng Việt](./README-vi.md) * [中文版本](./README-zh_CN.md) +* [Türkçe](./README-tr_TR.md) --- @@ -1194,7 +1195,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 implicity wrap the object 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 object 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.

@@ -1434,7 +1435,7 @@ for (const item in person) { #### Answer: 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. +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.

@@ -1687,7 +1688,7 @@ pet.bark(); ``` - A: `"Woof I am Mara"`, `TypeError` -- B: `"Woof I am Mara"`,`"Woof I am Mara"` +- B: `"Woof I am Mara"`, `"Woof I am Mara"` - C: `"Woof I am Mara"`, `undefined` - D: `TypeError`, `TypeError` @@ -1920,7 +1921,7 @@ console.log(data); 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 properties which names are included in the array will be added to the JSON string. In this case, only the properies with the names `"level"` and `"health"` are included, `"username"` is excluded. `data` is now equal to `"{"level":19, "health":90}"`. +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. @@ -1969,7 +1970,7 @@ The unary operator `++` _first returns_ the value of the operand, _then incremen const value = { number: 10 }; const multiply = (x = { ...value }) => { - console.log((x.number * 2)); + console.log((x.number *= 2)); }; multiply(); @@ -1990,9 +1991,9 @@ multiply(value); 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 defeault 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 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 valled `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`. @@ -2080,17 +2081,17 @@ In a derived class, you cannot access the `this` keyword before calling `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 `Dog` class receives two arguments, `name` since it extends `Animal`, and `size` as an extra property on the `Dog` class. They both need to be passed to the constructor function on `Dog`, which is done correctly using constructor 2. +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. With which constructor can we successfully extend the `Dog` class? +###### 67. What's the output? ```javascript // index.js -console.log('running index.js); +console.log('running index.js'); import { sum } from './sum.js'; console.log(sum(1, 2)); @@ -2136,7 +2137,7 @@ console.log(Symbol('foo') === Symbol('foo')) #### Answer: 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`.

From 6a7b94b0f3924c7fd04be241056e6856648f7364 Mon Sep 17 00:00:00 2001 From: Lydia Hallie Date: Sun, 14 Jul 2019 21:36:16 +0200 Subject: [PATCH 246/915] Rephrase question 12 --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index e52ef4d7..ef24bd94 100644 --- a/README.md +++ b/README.md @@ -412,7 +412,7 @@ console.log(sarah); For `sarah`, we didn't use the `new` keyword. When using `new`, it refers to the new empty object we create. However, if you don't add `new` it 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`. +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.

From da8cd30687933cb3bb01c25f3feb0e2f26f5432e Mon Sep 17 00:00:00 2001 From: Alexander Ivanov Date: Mon, 15 Jul 2019 11:16:06 +0300 Subject: [PATCH 247/915] Updates 2019-07 1 --- README_ru-RU.md | 526 ++++++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 513 insertions(+), 13 deletions(-) diff --git a/README_ru-RU.md b/README_ru-RU.md index df536c26..6ad55983 100644 --- a/README_ru-RU.md +++ b/README_ru-RU.md @@ -2,25 +2,26 @@ Я ежедневно публикую вопросы по JavaScript с вариантами ответов в своем [Instagram](https://www.instagram.com/theavocoder), которые дублируются в этом репозитории. -От азов к сложным вопросам: проверь, как хорошо ты знаешь JavaScript, освежи свои знания или приготовься к собеседованию! :muscle: :rocket: Я дополняю этот репозиторий каждую неделю новыми вопросами. +От базового до продвинутого: проверьте, насколько хорошо вы знаете JavaScript, немного освежите свои знания или подготовьтесь к собеседованию! :muscle: :rocket: Я обновляю репозиторий еженедельно новыми вопросами. Последнее обновление: 7 июля Ответы находятся в свернутой секции ниже вопросов. Просто нажми на "Ответ", чтобы развернуть. Удачи! :heart: Список доступных переводов: * [English](./README.md) -* [中文版本](./README-zh_CN.md) -* [Versión en español](./README-ES.md) +* [العربية](./README_AR.md) +* [اللغة العامية - Egyptian Arabic](./README_ar-EG.md) +* [Bosanski](./README-bs_BS.md) +* [Deutsch](./README-de_DE.md) +* [Español](./README-ES.md) * [日本語](./README-ja_JA.md) * [한국어](./README-ko_KR.md) +* [Português Brasil](./README_pt_BR.md) * [Русский](./README_ru-RU.md) -* [Western Balkan](./README-bs_BS.md) -* [Deutsch](./README-de_DE.md) -* [Tiếng Việt](./README-vi.md) * [Українська мова](./README-ua_UA.md) -* [Português Brasil](./README_pt_BR.md) -* [العربية](./README_AR.md) -* [اللغة العامية - Egyptian Arabic](./README_ar-EG.md) +* [Tiếng Việt](./README-vi.md) +* [中文版本](./README-zh_CN.md) +* [Türkçe](./README-tr_TR.md) --- @@ -411,7 +412,7 @@ console.log(sarah); Для `sarah` мы не использовали ключевое слово `new`. Использование `new` приводит к созданию нового объекта. Но без `new` он указывает на **глобальный объект**! -Мы указали, что `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`, поскольку мы не возвращаем значение из функции `Person`.

@@ -1178,7 +1179,7 @@ console.log(numbers); --- -###### 39. Всё в JavaScript это +###### 39. Всё в JavaScript это - A: примитив или объект - B: функция или объект @@ -1687,7 +1688,7 @@ pet.bark(); ``` - A: `"Woof I am Mara"`, `TypeError` -- B: `"Woof I am Mara"`,`"Woof I am Mara"` +- B: `"Woof I am Mara"`, `"Woof I am Mara"` - C: `"Woof I am Mara"`, `undefined` - D: `TypeError`, `TypeError` @@ -1920,7 +1921,7 @@ console.log(data); Второй аргумент `JSON.stringify` - это _replacer_. Заменитель может быть либо функцией, либо массивом, и позволяет вам контролировать, что и как должны быть преобразованы в значения. -Если заменитель является _array_, только свойства, имена которых включены в массив, будут добавлены в строку JSON. В этом случае включаются только свойства с именами `"level"` и `"health"`, `"username"` исключается. `data` теперь равен `"{"level":19, "health":90}"`. +Если заменитель является _массивом_, только свойства, имена которых включены в массив, будут добавлены в строку JSON. В этом случае включаются только свойства с именами `"level"` и `"health"`, `"username"` исключается. `data` теперь равен `"{"level":19, "health":90}"`. Если заменитель является _function_, эта функция вызывается для каждого свойства объекта, который вы преобразуете. Значение, возвращаемое из этой функции, будет значением свойства при добавлении в строку JSON. Если значение равно undefined, это свойство исключается из строки JSON. @@ -1960,3 +1961,502 @@ console.log(num2);

+ +--- + +###### 64. Какой будет вывод? + +```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` + +
Ответ +

+ +#### Ответ: C + +В ES6 мы можем инициализировать параметры значением по умолчанию. Значением параметра будет значение по умолчанию, если никакое другое значение не было передано функции, или если значение параметра равно `"undefined"`. В этом случае мы распространяем свойства объекта `value` на новый объект, поэтому значение` x` по умолчанию равно `{number: 10}`. + +Аргумент по умолчанию реализуется в момент _call time_! Каждый раз, когда мы вызываем функцию, создается _new_ объект. Мы вызываем функцию `multiply` первые два раза, не передавая значение: `x` имеет значение по умолчанию `{number: 10}`. Затем мы записываем умноженное значение этого числа, которое равно `20`. + +В третий раз, когда мы вызываем multiply, мы передаем аргумент: объект с именем `value`. Оператор `*=` на самом деле является сокращением для `x.number = x.number * 2`: мы изменяем значение `x.number` и записываем умноженное значение `20`. + +В четвертый раз мы снова передаем объект `value`. `x.number` ранее был изменен на `20`, поэтому `x.number * = 2` записывает` 40`. + +

+
+ +--- + +###### 65. Какой будет вывод? + +```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` + +
Ответ +

+ +#### Ответ: D + +Первым аргументом, который получает метод `reduce`, является _аккумулятором_, в данном случае `x`. Второй аргумент - это _текущее значение_, `y`. С помощью метода `reduce` мы выполняем функцию обратного вызова для каждого элемента в массиве, что в конечном итоге может привести к единственному значению. + +В этом примере мы не возвращаем никаких значений, мы просто регистрируем значения аккумулятора и текущее значение. + +Значение аккумулятора равно ранее возвращенному значению функции обратного вызова. Если вы не передадите необязательный аргумент `initialValue` методу `reduce`, аккумулятор будет равен первому элементу при первом вызове. + +При первом вызове аккумулятор (`x`) равен `1`, а текущее значение (`y`) равно `2`. Мы не возвращаемся из функции обратного вызова, мы регистрируем аккумулятор и текущее значение: `1` и `2` регистрируются. + +Если вы не возвращаете значение из функции, она возвращает значение `undefined`. При следующем вызове аккумулятор равен `undefined`, а текущее значение равно 3. `undefined` и `3` будут зарегистрированы. + +При четвертом вызове мы снова не возвращаемся из функции обратного вызова. Аккумулятор снова равен `undefined`, а текущее значение равно `4`. `undefined` и` 4` будут зарегистрированы. +

+
+ +--- + +###### 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 + +
Ответ +

+ +#### Ответ: B + +В производном классе вы не можете получить доступ к ключевому слову `this` до вызова `super`. Если вы попытаетесь это сделать, он выдаст ReferenceError: 1 и 4 приведут к ошибке ссылки. + +С ключевым словом `super` мы вызываем конструктор родительского класса с заданными аргументами. Конструктор родителя получает аргумент `name`, поэтому нам нужно передать `name` в `super`. + +Класс `Labrador` получает два аргумента: `name`, поскольку он расширяет `Dog`, и `size` в качестве дополнительного свойства класса `Labrador`. Они оба должны быть переданы в функцию конструктора в `Labrador`, что делается правильно с помощью конструктора 2. +

+
+ +--- + +###### 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` все импортируемые модули являются _pre-parsed_. Это означает, что импортированные модули запускаются _первыми_, код в файле, который импортирует модуль, исполняется _после_. + +В этом разница между `require()` в CommonJS и `import`! С помощью `require()` вы можете загружать зависимости по требованию во время выполнения кода. Если бы мы использовали `require` вместо `import`, в консоль были бы записаны `running index.js`, `running sum.js`, `3`. + +

+
+ +--- + +###### 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`. + +

+
+ +--- + +###### 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`, меньше длины строки, заполнение не будет добавлено. + +

+
+ +--- + +###### 70. Какой будет вывод? + +```javascript +console.log("🥑" + "💻"); +``` + +- A: `"🥑💻"` +- B: `257548` +- C: A string containing their code points +- D: Error + +
Ответ +

+ +#### Ответ: A + +С помощью оператора `+` вы можете объединять строки. В этом случае мы объединяем строку `""` со строкой `"💻"`, что приводит к `"💻"`. + +

+
+ +--- + +###### 71. Как мы можем вывести в лог значения, которые закомментированы после оператора 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")` + +
Ответ +

+ +#### Ответ: C + +Функция генератора "приостанавливает" выполнение, когда видит ключевое слово yield. Во-первых, мы должны позволить функции выдать строку "Do you love JavaScript?", Что можно сделать, вызвав `game.next (). Value`. + +Каждая строка выполняется до тех пор, пока не найдет первое ключевое слово `yield`. В первой строке функции есть ключевое слово `yield` на первом месте: выполнение останавливается с первым выходом! _Это означает, что переменная `answer` еще не определена!_ + +Когда мы вызываем `game.next("Yes").value`, предыдущий `yield` заменяется значением параметров, переданных функции `next()`, в данном случае `"Yes"`. Значение переменной `answer` теперь равно `"Yes"`. Условие if возвращает `false`, а `JavaScript loves you back ❤️`, регистрируется. + +

+
+ +--- + +###### 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`, которая и выводится. + +

+
+ +--- + +###### 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 + +Асинхронная функция всегда возвращает обещание. `await` все еще должен ждать разрешения обещания: ожидаемое обещание возвращается, когда мы вызываем `getData()`, чтобы установить `data` равным ему. + +Если бы мы хотели получить доступ к разрешенному значению `"I made it"`, мы могли бы использовать метод `.then()` для `data`: + +`data.then(res => console.log(res))` + +Тогда это бы вывело `"I made it!"` + +

+
+ +--- + +###### 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()` возвращает _длину_ нового массива! Ранее массив содержал один элемент (строка `"banana"`) и имел длину `1`. После добавления в массив строки `"apple"`, массив содержит два элемента и имеет длину `2`. Это возвращается из функции `addToList`. + +Метод `push` изменяет исходный массив. Если вы хотите вернуть _массив_ из функции, а не _длину массива_, вы должны были вернуть `list` после добавления в нее `item`. + +

+
+ +--- + +###### 75. Какой будет вывод? + +```javascript +const box = { x: 10, y: 20 }; + +Object.freeze(box); + +const shape = box; +shape.x = 100; +``` + +- A: `{ x: 100, y: 20 }` +- B: `{ x: 10, y: 20 }` +- C: `{ x: 100 }` +- D: `ReferenceError` + +
Ответ +

+ +#### Ответ: B + +`Object.freeze` делает невозможным добавление, удаление или изменение свойств объекта (если только значение свойства не является другим объектом). + +Когда мы создаем переменную `shape` и устанавливаем ее равной замороженному объекту `box`, `shape` также ссылается на замороженный объект. Вы можете проверить, заморожен ли объект, используя `Object.isFrozen`. В этом случае `Object.isFrozen(shape)` возвращает true, поскольку переменная `shape` имеет ссылку на замороженный объект. + +Поскольку `shape` заморожен, и поскольку значение `x` не является объектом, мы не можем изменить свойство `x`. `x` по-прежнему равно `10`, и `{x: 10, y: 20}` регистрируется. + +

+
+ +--- + +###### 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. + +

+
+ +--- + +###### 77. Это чистая функция? + +```javascript +function sum(a, b) { + return a + b; +} +``` + +- A: Yes +- B: No + +
Ответ +

+ +#### Ответ: A + +Чистая функция - это функция, которая всегда возвращает тот же результат, если переданы одинаковые аргументы. + +Функция `sum` всегда возвращает один и тот же результат. Если мы передадим `1` и `2`, он всегда вернет `3` без побочных эффектов. Если мы передадим `5` и `10`, он всегда вернет `15` и так далее. Это определение чистой функции. + +

+
+ +--- + +###### 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'` регистрируется. + +

+
From a2258737816199fb76ad5f9f7d5c7db2bf864aed Mon Sep 17 00:00:00 2001 From: Jacob Herper Date: Mon, 15 Jul 2019 09:35:06 +0100 Subject: [PATCH 248/915] Questions 64-69 added --- README-de_DE.md | 234 +++++++++++++++++++++++++++++++++++++++++++++--- 1 file changed, 224 insertions(+), 10 deletions(-) diff --git a/README-de_DE.md b/README-de_DE.md index 4ff1bf12..41e4f35b 100644 --- a/README-de_DE.md +++ b/README-de_DE.md @@ -6,16 +6,21 @@ Von einfach bis fortgeschritten: teste wie gut du JavaScript kennst, frische dei Die Antworten sind unterhalb der Fragen versteckt. Du kannst einfach darauf klicken um die Antworten anzuzeigen. Viel Glück :heart: -### Andere verfügbare Sprachen -[English](./README.md)
-[Bosanski Jezik](./README-bs_BS.md)
-[日本語](./README-ja_JA.md)
-[한국어](./README-ko_KR.md)
-[Português Brasil](./README_pt_BR.md)
-[Русский](./README_ru-RU.md)
-[Українська мова](./README-ua_UA.md)
-[Tiếng Việt](./README-vi.md)
-[中文版本](./README-zh_CN.md)
+### Alle verfügbaren Sprachen +* [English](./README.md) +* [العربية](./README_AR.md) +* [اللغة العامية - Egyptian Arabic](./README_ar-EG.md) +* [Bosanski](./README-bs_BS.md) +* [Deutsch](./README-de_DE.md) +* [Español](./README-ES.md) +* [日本語](./README-ja_JA.md) +* [한국어](./README-ko_KR.md) +* [Português Brasil](./README_pt_BR.md) +* [Русский](./README_ru-RU.md) +* [Türkçe](./README-tr_TR.md) +* [Українська мова](./README-ua_UA.md) +* [Tiếng Việt](./README-vi.md) +* [中文版本](./README-zh_CN.md) --- @@ -1956,3 +1961,212 @@ Der unäre Operator `++` _gibt zuerst_ den Wert des Operanden aus und _erhöht d

+ + + +--- + +###### 64. Was ist der 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` + +
Antwort +

+ +#### Antwort: C + +In ES6 können wir Parameter mit einem Standardwert initialisieren. Der Wert des Parameters wird als Standard gesetzt, wenn kein anderer Wert übergeben wird oder der Wert des Parameters `"undefined"` ist. In diesem Fall verteilen wir die Properties von `value` in einem neuen Objekt, sodass `x` den Standardwert `{ number: 10 }` bekommt. + +Das Standard Argument wird beim _Aufruf_ evaluiert. Jedes Mal, wenn wir die Funktion aufrufen, wird ein _neues_ Objekt erstellt. Wir rufen die `multiply` Funktion die ersten beiden Male auf ohne einen Wert zu übergeben: `x` hat daher den Standardwert `{ number: 10 }`. Wir loggen dann den multiplizierten Wert davon, sodass wir `20` bekommen. + +Beim dritten Mal wird die `multiply` Funktion mit einem Argument für `value` aufgerufen. Der `*=` Operator ist kurz für `x.number = x.number * 2`: wir ändern den Wert von `x.number` und loggen den multiplizierten Wert `20`. + +Beim vierten Mal übergeben wir wieder eine `value`. `x.number` wurde zuvor in `20` geändert, sodass `x.number *= 2` jetzt `40` loggt. + +

+
+ +--- + +###### 65. Was ist der 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` + +
Antwort +

+ +#### Antwort: D + +Das erste Argument, welches die `reduce` Methode erhält ist der _Akkumulator_ `x`. Das zweite Argument ist der _aktuelle Wert_, `y`. Durch die `reduce` Methode führen wir eine Callback Funktion an jedem Element des Arrays aus, was im Endeffekt einen einzelnen Wert ausgibt. + +In diesem Beispiel geben wir nicht irgendwelche Werte aus, sondern loggen einfach nur den Akkumulator und den momentanen Wert. + +Der Wert des Akkumulators ist gleich dem vorhergehenden Wert der Callback Funktion. Wenn wir `initialValue` nicht an die `reduce` Methode übergeben bleibt der Akkumulator gleich dem ersten Element des ersten Calls. + +Beim ersten Call ist der Akkumulator (`x`) gleich `1` und der aktuelle Wert (`y`) ist `2`. Da wir in der Callback Funktion bleiben loggen wir den Akkumulator und den aktuellen Wert: `1` und `2`. + +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. +

+
+ +--- + +###### 66. Mit welchem Constructor können wir die `Dog` Klasse erweitern? + +```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 + +
Antwort +

+ +#### Antwort: B + +In einer abgeleiteten Klasse kann das `this` Keyword nicht aufgerufen werden, bevor `super` aufgerufen wurde. Wenn man das versucht wird ein ReferenceError ausgeworfen: 1 und 4 würden daher einen Referenz-Fehler ausgeben. + +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. +

+
+ +--- + +###### 67. Mit welchem Constructor können wir die `Dog` Klasse erweitern? + +```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` + +
Antwort +

+ +#### Antwort: B + +Mit dem `import` Keyword werden alle importierten Module _vorgeparsed_. Das bedeutet, dass importierte Module _zuerst_ ausgeführt werden, der Code in der eigentlichen Datei wird _danach_ ausgeführt. + +Das ist der große Unterschied zwischen `require()` in CommonJS und `import`. Mit `require()` können Dependencies bei Bedarf geladen werden, während der Code ausgeführt wird. Hätten wir `require()` anstelle von `import` verwendet, wäre `running index.js`, `running sum.js`, `3` in der Konsole geloggt worden. + +

+
+ +--- + +###### 68. Was ist der 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` + +
Antwort +

+ +#### Antwort: A + +Jedes Symbol ist eindeutig. Der Sinn des Argumentes, welches an das Symbol weitergegeben wird, ist dem Symbol eine Beschreibung zu geben. Der Wert des Symbols hängt nicht von diesem Argument ab. Beim vergleichen der Symbole werden zwei komplett neue Symbole erstellt: das erste `Symbol('foo')` und das zweite `Symbol('foo')`. Diese beiden Werte sind eindeutig und nicht identisch, weshalb `Symbol('foo') === Symbol('foo')` `false` ausgibt. + +

+
+ +--- + +###### 69. Was ist der 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"`, + +
Antwort +

+ +#### Antwort: C + +Mit der `padStart` Methode können wir Padding am Anfang des Strings hinzufügen. Der Wert, der an die Methode übergeben wird ist die _absolute_ Länge des Strings mit dem Padding. Der String `"Lydia Hallie"` hat eine Länge von `12`. `name.padStart(13)` fügt ein Leerzeichen am Anfang des Strings ein, weil 12 + 1 = 13 ist. + +Falls der Wert, der an `padStart` übergeben wurde kleiner ist, als die Länge des Arrays, so wird kein Padding hinzugefügt. + +

+
From 0ad91b3063cf7aedf1444222f5ab8c96f4c6146d Mon Sep 17 00:00:00 2001 From: lazy <310195875@qq.com> Date: Mon, 15 Jul 2019 16:41:22 +0800 Subject: [PATCH 249/915] add question 70-78 to zh_CN --- README-zh_CN.md | 300 ++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 300 insertions(+) diff --git a/README-zh_CN.md b/README-zh_CN.md index 7d1a38d4..3c738431 100644 --- a/README-zh_CN.md +++ b/README-zh_CN.md @@ -2159,3 +2159,303 @@ console.log(name.padStart(2))

+ +--- + +###### 70. 输出什么? + +```javascript +console.log("🥑" + "💻"); +``` + +- A: `"🥑💻"` +- B: `257548` +- C: A string containing their code points +- D: Error + +
答案 +

+ +#### 答案: A + +使用`+`运算符,您可以连接字符串。 上述情况,我们将字符串`“🥑”`与字符串`”💻“`连接起来,产生`”🥑💻“`。 + +

+
+ +--- + +###### 71. 如何能打印出`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")` + +
答案 +

+ +#### 答案: C + +`generator`函数在遇到`yield`关键字时会“暂停”其执行。 首先,我们需要让函数产生字符串`Do you love JavaScript?`,这可以通过调用`game.next().value`来完成。上述函数的第一行就有一个`yield`关键字,那么运行立即停止了,`yield`表达式本身没有返回值,或者说总是返回`undefined`, 这意味着此时变量 `answer` 为`undefined` + +`next`方法可以带一个参数,该参数会被当作上一个 `yield` 表达式的返回值。当我们调用`game.next("Yes").value`时,先前的 `yield` 的返回值将被替换为传递给`next()`函数的参数`"Yes"`。此时变量 `answer` 被赋值为 `"Yes"`,`if`语句返回`false`,所以`JavaScript loves you back ❤️`被打印。 + +

+
+ +--- + +###### 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`等)。但反斜杠可能造成问题,因为你可能会遇到下面这种类似情况: + +```javascript +const path = `C:\Documents\Projects\table.html` +String.raw`${path}` +``` + +这将导致: + +`"C:DocumentsProjects able.html"` + +直接使用`String.raw` +```javascript +String.raw`C:\Documents\Projects\table.html` +``` +它会忽略转义字符并打印:`C:\Documents\Projects\table.html` + +上述情况,字符串是`Hello\nworld`被打印出。 + +

+
+ +--- + +###### 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的解决:当我们调用`getData()`并将其赋值给`data`,此时`data`为`getData`方法返回的一个挂起的promise,该promise并没有解决。 + +如果我们想要访问已解决的值`"I made it!"`,可以在`data`上使用`.then()`方法: + +`data.then(res => console.log(res))` + +这样将打印 `"I made it!"` + +

+
+ +--- + +###### 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()`方法返回新数组的长度。一开始,数组包含一个元素(字符串`"banana"`),长度为1。 在数组中添加字符串`"apple"`后,长度变为2,并将从`addToList`函数返回。 + +`push`方法修改原始数组,如果你想从函数返回数组而不是数组长度,那么应该在push `item`之后返回`list`。 + +

+
+ +--- + +###### 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`使得无法添加、删除或修改对象的属性(除非属性的值是另一个对象)。 + +当我们创建变量`shape`并将其设置为等于冻结对象`box`时,`shape`指向的也是冻结对象。你可以使用`Object.isFrozen`检查一个对象是否被冻结,上述情况,`Object.isFrozen(shape)`将返回`true`。 + +由于`shape`被冻结,并且`x`的值不是对象,所以我们不能修改属性`x`。 `x`仍然等于`10`,`{x:10,y:20}`被打印。 + +注意,上述例子我们对属性`x`进行修改,可能会导致抛出TypeError异常(最常见但不仅限于严格模式下时)。 + +

+
+ +--- + +###### 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`。 + +

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

+ +#### 答案: A + +纯函数一种若输入参数相同,则永远会得到相同输出的函数。 + +`sum`函数总是返回相同的结果。 如果我们传递`1`和`2`,它将总是返回`3`而没有副作用。 如果我们传递`5`和`10`,它将总是返回`15`,依此类推,这是纯函数的定义。 + +

+
+ +--- + +###### 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`被打印。 + +

+
From 1b4bc6fdf4186791da79e0426f324793c869f99d Mon Sep 17 00:00:00 2001 From: yusufkaracin Date: Mon, 15 Jul 2019 12:06:37 +0300 Subject: [PATCH 250/915] translates 70-78 to Turkish --- README-tr_TR.md | 294 +++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 293 insertions(+), 1 deletion(-) diff --git a/README-tr_TR.md b/README-tr_TR.md index 4cbb1c4b..a43eac69 100644 --- a/README-tr_TR.md +++ b/README-tr_TR.md @@ -2,7 +2,7 @@ [Instagram](https://www.instagram.com/theavocoder) hesabımda, günlük olarak çoktan seçmeli Javascript soruları paylaşıyorum, ayrıca burada da paylaşacağım! -Temelden ileri düzeye: Javascript'i ne kadar iyi bildiğinizi test edin, bilginizi biraz tazeleyin ya da mülakatanıza hazırlanın! :muscle: :rocket: Repoyu haftalık olarak yeni sorularla güncelliyorum. Son güncelleme: Last update: 7 Temmuz +Temelden ileri düzeye: Javascript'i ne kadar iyi bildiğinizi test edin, bilginizi biraz tazeleyin ya da mülakatanıza hazırlanın! :muscle: :rocket: Repoyu haftalık olarak yeni sorularla güncelliyorum. Son güncelleme: Last update: 14 Temmuz Cevaplar, soruların altında gizlenmiştir. Görmek için sadece tıklayın. İyi şanşlar :heart: @@ -2160,3 +2160,295 @@ Eğer `padStart` methoduna geçilen argüman, string'in uzunluğundan daha azsa,

+ +--- + +###### 70. Çıktısı Nedir? + +```javascript +console.log("🥑" + "💻"); +``` + +- A: `"🥑💻"` +- B: `257548` +- C: A string containing their code points +- D: Error + +
Cevap +

+ +#### Cevap: A + +`+` operatörü ile stringleri birleştirebilirsiniz. Bu örnekte, `"🥑"` ile `"💻"` birleştiriyoruz, `"🥑💻"` olarak sonuçlanıyor. +

+
+ +--- + +###### 71. console.log ifadesinden sonra yorum satırı olarak gelen değerleri nasıl loglayabiliriz? + +```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")` + +
Cevap +

+ +#### Cevap: C + +Generator fonksiyon `yield` anahtar kelimesini gördüğünde çalışmasını "durdurur". Öncelikle, fonksiyonun "Do you love JavaScript?" stringini vermesini sağlamamız gerek ki bu `game.next().value` çağrılarak yapılabilir. + +İlk `yield` anahtar kelimesi bulunana dek her satır çalıştırılır. Fonksiyonun içinde, ilk satırda `yield` anahtar kelimesi var: çalışma ilk yield ile durur. _Bu demektir ki `answer` değişkeni henüz tanımlanmadı!_ + +`game.next("Yes").value` çağırdığımız zaman, önceki `yield` `next()` fonksiyonuna geçilen parametlerin değeri ile değiştirilir, bu durumda `"Yes"`. `answer` değişkeninin değeri artık `"Yes"`'e eşit. if ifadesi `false` döndürür, ve `JavaScript loves you back ❤️` loglanır. + +

+
+ +--- + +###### 72. Çıktısı Nedir? + +```javascript +console.log(String.raw`Hello\nworld`); +``` + +- A: `Hello world!` +- B: `Hello`
     `world` +- C: `Hello\nworld` +- D: `Hello\n`
     `world` + +
Cevap +

+ +#### Cevap: C + +`String.raw` kaçış karakterlerinin (`\n`, `\v`, `\t` vb.) göz ardı edildiği bir string döndürür. Ters bölü işareti şöyle bir şey gibi sonuçlanabileceğinden sorun olabilir: + +`` const path = `C:\Documents\Projects\table.html` `` + +Şöyle sonuçlanır: + +`"C:DocumentsProjects able.html"` + +`String.raw` ile, kaçış karakteri basitçe göz ardı edilir ve yazdırılır: + +`C:\Documents\Projects\table.html` + +Bu örnekte, string `Hello\nworld`, dolayısıyla `Hello\nworld` olarak loglanır. + +

+
+ +--- + +###### 73. Çıktısı Nedir? + +```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` + +
Cevap +

+ +#### Cevap: C + +Asenkron bir fonksiyon her zaman promise döndürür. `await` promise'ı çözmek için beklemeli: `getData()`'yı `data`'ya eşitlemek için çağırdığımız zaman bekleyen promise döndürülür. + +Çözülmüş değer olan `"I made it"`'e erişmek isteseydik, `data` üzerinde `.then()` methodunu kullanabilirdik: + +`data.then(res => console.log(res))` + +Bu `"I made it!"` loglardı. + +

+
+ +--- + +###### 74. Çıktısı Nedir? + +```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` + +
Cevap +

+ +#### Cevap: B + +`push()` methodu yeni dizinin _uzunluğunu_ döndürür. Önceden, dizi bir eleman içeriyordu (`"banana"`) ve uzunluğu 1'di. Diziye `"apple"`'ı ekledikten sonra, dizi iki eleman içerir ve uzunluğu `2`'dir. `addToList` fonksiyonundan döndürülen budur. + +`push` methodu orijinal diziyi değiştirir. Eğer _dizinin uzunluğunu_ değil de _diziyi_ döndürmek isterseniz, `item`'i ekledikten sonra `list`'i döndürmelisiniz. + +

+
+ +--- + +###### 75. Çıktısı Nedir? + +```javascript +const box = { x: 10, y: 20 }; + +Object.freeze(box); + +const shape = box; +shape.x = 100; +``` + +- A: `{ x: 100, y: 20 }` +- B: `{ x: 10, y: 20 }` +- C: `{ x: 100 }` +- D: `ReferenceError` + +
Cevap +

+ +#### Cevap: B + +`Object.freeze` bir nesneye özellik eklemeyi, silmeyi ya da değiştirmeyi olanaksız kılar (özelliğin değeri başka bir nesneye ait olmadıkça) + +`shape` değişkenini oluşturup, donmuş `box` nesnesine eşitlediğimiz zaman, `shape` de ayrıca donmuş nesneyi referans eder. `Object.isFrozen` kullanarak bir nesnenin dondurulmuş olup olmadığını kontrol edebilirsiniz. Bu örnekte, `shape` değişkeni donmuş bir nesneyi referans gösterdiğinden, `Object.isFrozen(shape)` `true` döndürür. + +`shape` donmuş olduğundan, ve `x`'in değeri bir nesne olmadığından, `x` özelliğini değiştiremeyiz. `x` hala `10`'a eşit, ve `{ x: 10, y: 20 }` loglanır. + +

+
+ +--- + +###### 76. Çıktısı Nedir? + +```javascript +const { name: myName } = { name: "Lydia" }; + +console.log(name); +``` + +- A: `"Lydia"` +- B: `"myName"` +- C: `undefined` +- D: `ReferenceError` + +
Cevap +

+ +#### Cevap: D + +Eşitliğin sağ tarafındaki nesneden `name` özelliğini çıkarttığımız zaman, `myName` isimli değişkene, o özelliğin değeri olan `"Lydia"`'yı atıyoruz. + +`{ 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. + +

+
+ +--- + +###### 77. Bu bir saf (pure) fonksiyon mu? + +```javascript +function sum(a, b) { + return a + b; +} +``` + +- A: Yes +- B: No + +
Cevap +

+ +#### Cevap: A + +Saf fonksiyon, aynı argümanlar geçildiği zaman, _her zaman_ aynı sonucu döndüren fonksiyondur. + +`sum` fonksiyonu her zaman aynı sonucu döndürür. Eğer `1` ve `2` geçersek, _her zaman_ `3` döndürecektir. Eğer `5` ve `10` geçersek, _her zaman_ `15` döndürür, bunun gibi devam eder... Saf fonksiyonun tanımlaması budur. + +

+
+ +--- + +###### 78. Çıktısı nedir? + +```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` + +
Cevap +

+ +#### Cevap: C + +`add` fonksiyonu _ezberlenmiş_, "_memoized_", bir fonksiyondur. Ezberleme ile, fonksiyonun sonuçlarını, fonksiyonun daha hızlı çalışması için cache'leyebiliriz. Bu örnekte, önceki dönen değerleri saklayan bir `cache` nesnesi oluşturuyoruz. + +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 }` + +İ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. + +

+
From 4758bce48b530e89feb1e7af0feb5dbda10fbe0f Mon Sep 17 00:00:00 2001 From: sweetmilkys Date: Mon, 15 Jul 2019 18:54:33 +0900 Subject: [PATCH 251/915] Fix typo from main --- README-ko_KR.md | 37 ++++++++++++++++++++----------------- 1 file changed, 20 insertions(+), 17 deletions(-) diff --git a/README-ko_KR.md b/README-ko_KR.md index 814c35a3..89b81173 100644 --- a/README-ko_KR.md +++ b/README-ko_KR.md @@ -2,20 +2,23 @@ JavaScript 에 관한 객관식 문제를 [Instagram](https://www.instagram.com/theavocoder)에 매일 게시하고 있어요, 물론 여기에도 게시할 거예요! -초급부터 고급까지: JavaScript를 얼마나 잘 알고 있는지 테스트하거나, 지식을 조금 더 새롭게 하거나, 코딩 면접을 준비하세요! :muscle: :rocket: 이 기록을 매주 새로운 질문으로 업데이트해요. 마지막 업데이트: 7월 7일 +초급부터 고급까지: JavaScript를 얼마나 잘 알고 있는지 테스트하거나, 지식을 조금 더 새롭게 하거나, 코딩 면접을 준비하세요! :muscle: :rocket: 이 기록을 매주 새로운 질문으로 업데이트해요. 마지막 업데이트: 7월 14일 정답은 질문 아래 접힌 부분에 있어요, 그냥 클릭하면 펼칠 수 있어요. 행운을 빌어요 :heart: -- [English](./README.md) -- [中文版本](./README-zh_CN.md) -- [Versión en español](./README-ES.md) -- [日本語](./README-ja_JA.md) -- [Русский](./README_ru-RU.md) -- [Western Balkan](./README-bs_BS.md) -- [Deutsch](./README-de_DE.md) -- [Tiếng Việt](./README-vi.md) -- [Українська мова](./README-ua_UA.md) -- [Português Brasil](./README_pt_BR.md) +* [English](./README.md) +* [العربية](./README_AR.md) +* [اللغة العامية - Egyptian Arabic](./README_ar-EG.md) +* [Bosanski](./README-bs_BS.md) +* [Deutsch](./README-de_DE.md) +* [Español](./README-ES.md) +* [日本語](./README-ja_JA.md) +* [Português Brasil](./README_pt_BR.md) +* [Русский](./README_ru-RU.md) +* [Українська мова](./README-ua_UA.md) +* [Tiếng Việt](./README-vi.md) +* [中文版本](./README-zh_CN.md) +* [Türkçe](./README-tr_TR.md) --- @@ -404,7 +407,7 @@ console.log(sarah); `sarah`에게 `new` 키워드를 사용하지 않았어요. `new`를 사용한 경우, 이것은 우리가 만든 새로운 빈 객체를 참조해요. 그러나, `new`를 추가하지 않으면 **전역변수**를 참조해요! -`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`로 남아있어요. 따라서 `Person`함수의 값을 리턴하지 않아요.

@@ -1682,7 +1685,7 @@ pet.bark(); ``` - A: `"Woof I am Mara"`, `TypeError` -- B: `"Woof I am Mara"`,`"Woof I am Mara"` +- B: `"Woof I am Mara"`, `"Woof I am Mara"` - C: `"Woof I am Mara"`, `undefined` - D: `TypeError`, `TypeError` @@ -1958,7 +1961,7 @@ console.log(num2); --- -###### 64. 무엇이 출력 될까요? +###### 64. 무엇이 출력 될까요? ```javascript const value = { number: 10 }; @@ -2032,13 +2035,13 @@ ES6에서는, 기본값으로 파라미터를 초기화할 수 있어요. 함수 ###### 66. `Dog` 클래스를 성공적으로 확장할 수 있는 생성자는 어느 것일까요? ```javascript -class Animal { +class Dog { constructor(name) { this.name = name; } }; -class Dog extends Animal { +class Labrador extends Dog { // 1 constructor(name, size) { this.size = size; @@ -2076,7 +2079,7 @@ class Dog extends Animal { `super` 키워드를 가지고, 부모 클래스 생성자에 주어진 인수들을 부를 수 있어요. 부모 생성자는 `name` 인수를 받아요, 그래서 `name`을 `super`로 전달해야 해요. -`Dog` 클래스는 인수를 2개 받는데, `Animal`로 부터 확장된 `name`과 `Dog` 클래스의 추가 속성인 `size`예요. 그 두 개는 `Dog` 생성자 함수에 전달되어야 하는데, 올바르게 사용된 건 2번째 생성자예요. +`Labrador` 클래스는 인수를 2개 받는데, `Dog`로 부터 확장된 `name`과 `Labrador` 클래스의 추가 속성인 `size`예요. 그 두 개는 `Labrador` 생성자 함수에 전달되어야 하는데, 올바르게 사용된 건 2번째 생성자예요.

From 4eeeff157c63f9700db2b165c5b355ec4cf2eae6 Mon Sep 17 00:00:00 2001 From: sweetmilkys Date: Thu, 18 Jul 2019 20:18:25 +0900 Subject: [PATCH 252/915] Add log --- README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/README.md b/README.md index ef24bd94..992d296d 100644 --- a/README.md +++ b/README.md @@ -2339,6 +2339,8 @@ Object.freeze(box); const shape = box; shape.x = 100; + +console.log(shape); ``` - A: `{ x: 100, y: 20 }` From 00aac3e6ae0d9b051714729d69eeecffbfefdd21 Mon Sep 17 00:00:00 2001 From: sweetmilkys Date: Thu, 18 Jul 2019 21:25:40 +0900 Subject: [PATCH 253/915] Add Translate the questions 70-78 to Korean. --- README-ko_KR.md | 294 ++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 294 insertions(+) diff --git a/README-ko_KR.md b/README-ko_KR.md index 89b81173..fbc30e11 100644 --- a/README-ko_KR.md +++ b/README-ko_KR.md @@ -2167,3 +2167,297 @@ console.log(name.padStart(2))

+ +--- + +###### 70. 무엇이 출력 될까요? + +```javascript +console.log("🥑" + "💻"); +``` + +- A: `"🥑💻"` +- B: `257548` +- C: 해당 코드 주소를 포함하는 문자열 +- D: 에러 + +
정답 +

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

+
+ +--- + +###### 71. 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` 그리고 `game.next().value` +- B: `game.next.value("Yes")` 그리고 `game.next.value()` +- C: `game.next().value` 그리고 `game.next("Yes").value` +- D: `game.next.value()` 그리고 `game.next.value("Yes")` + +
정답 +

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

+
+ +--- + +###### 72. 무엇이 출력 될까요? + +```javascript +console.log(String.raw`Hello\nworld`); +``` + +- A: `Hello world!` +- B: `Hello`
     `world` +- C: `Hello\nworld` +- D: `Hello\n`
     `world` + +
정답 +

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

+
+ +--- + +###### 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 + +async 함수는 항상 promise를 리턴해요. `await`는 promise가 resolve 할 때까지 기다려야 해요: pending promise는 `data`를 설정하기 위해 부른 `getData()`가 리턴한 것을 가져요. + +resolve된 값 `"I made it"`에 접근하고 싶다면, `data`에 `.then()` 메소드를 사용해야해요. + +`data.then(res => console.log(res))` + +이건 `"I made it!"`을 출력할 거예요. + +

+
+ +--- + +###### 74. 무엇이 출력 될까요? + +```javascript +function addToList(item, list) { + return list.push(item); +} + +const result = addToList("apple", ["banana"]); +console.log(result); +``` + +- A: `['banana', 'apple']` +- B: `2` +- C: `true` +- D: `undefined` + +
정답 +

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

+
+ +--- + +###### 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`는 객체의 속성들을 추가, 삭제 혹은 수정하는 걸 불가능하게 만들어요(다른 객체로서의 속성들의 값이 아닌 한). + +변수 `shape`을 생성할 때, 동결 객체 `box`와 동일하게 설정했고, `shape` 역시 동결 객체를 참조해요. `Object.isFrozen`을 사용해 객체의 동결 여부를 확인할 수 있어요. 이 경우, `Object.isFrozen(shape)`은 참을 리턴하고, 따라서 변수 `shape`는 동결 객체 참조를 가져요. + +`shape`가 동결 상태이므로, `x`의 값은 객체가 아니며, `x`의 속성을 수정할 수 없어요. `x`는 여전히 `10`이고, `{ x: 10, y: 20 }`가 출력돼요. + +

+
+ +--- + +###### 76. 무엇이 출력 될까요? + +```javascript +const { name: myName } = { name: "Lydia" }; + +console.log(name); +``` + +- A: `"Lydia"` +- B: `"myName"` +- C: `undefined` +- D: `ReferenceError` + +
정답 +

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

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

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

+
+ +--- + +###### 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`함수는 _memoization_ 함수예요. memoization으로, 함수 실행 속도를 높이기 위해 함수의 결과를 캐시에 저장할 수 있어요. 이 경우, 이전에 리턴된 값을 저장한 `cache` 객체를 만들어요. + +같은 인수로 `addFunction` 함수를 다시 부르면, 우선 cache 안에 값을 갖고 있는지 확인해요. 만약 그렇다면, 캐시에 저장된 값이 리턴되어, 실행시간이 절약돼요. 캐시에 저장되지 않았다면, 값을 계산하고 나중에 저장해요. + +같은 값으로 `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'`이 출력돼요. + +세 번째에는, `5 * 2`을 `10`으로 평가하여 함수에 전달해요. `cache` 객체는 `10`을 위해 리턴될 값을 포함하고 있어요. if문의 조건 `num in cache`은 `true`를 리턴하고, `'From cache! 20'`이 출력돼요. + +

+
From 33a24e3a6b60bd400589191f3411fb403f5f889f Mon Sep 17 00:00:00 2001 From: Michael <184316+muescha@users.noreply.github.com> Date: Sat, 20 Jul 2019 00:12:52 +0200 Subject: [PATCH 254/915] fix: typo in Question 64 in DE --- README-de_DE.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README-de_DE.md b/README-de_DE.md index 41e4f35b..1eb56566 100644 --- a/README-de_DE.md +++ b/README-de_DE.md @@ -1972,7 +1972,7 @@ Der unäre Operator `++` _gibt zuerst_ den Wert des Operanden aus und _erhöht d const value = { number: 10 }; const multiply = (x = { ...value }) => { - console.log((x.number * 2)); + console.log((x.number *= 2)); }; multiply(); From e95acdc1f8f656dd2c94cf127c47cf6f7f03fb3b Mon Sep 17 00:00:00 2001 From: Johnny Kwok Date: Thu, 25 Jul 2019 17:36:22 +0800 Subject: [PATCH 255/915] Update README-zh_CN.md typo --- README-zh_CN.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README-zh_CN.md b/README-zh_CN.md index 3c738431..e3dee426 100644 --- a/README-zh_CN.md +++ b/README-zh_CN.md @@ -1441,7 +1441,7 @@ console.log(3 + 4 + "5"); #### 答案: B -当所有运算符的 _优先级_ 相同时,计算表达式需要确定运算符的结合顺序,即从右到左还是从左往右。在这个例子中,我们只有一类运算符`+`,对于加法来说,结合顺序就死从左到右。 +当所有运算符的 _优先级_ 相同时,计算表达式需要确定运算符的结合顺序,即从右到左还是从左往右。在这个例子中,我们只有一类运算符`+`,对于加法来说,结合顺序就是从左到右。 `3 + 4`首先计算,得到数字`7`. From 78c8f32274806854a680e0e12c49d319369a3e43 Mon Sep 17 00:00:00 2001 From: Lydia Hallie Date: Fri, 26 Jul 2019 12:39:28 +0200 Subject: [PATCH 256/915] Add questions 79-88 --- README.md | 321 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 321 insertions(+) diff --git a/README.md b/README.md index ef24bd94..c1f2c0f3 100644 --- a/README.md +++ b/README.md @@ -2460,3 +2460,324 @@ The third time, we pass `5 * 2` to the function which gets evaluated to `10`. Th

+ +--- + +###### 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: "🍫"}` + +
Answer +

+ +#### Answer: 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 propreties. `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]` + +
Answer +

+ +#### Answer: 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 +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 + +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`. + +

+
+ +--- + +###### 82. What is the output? + +```javascript +function sayHi(name) { + return `Hi there, ${name}` +} + +console.log(sayHi()) +``` + +- A: `Hello there, ` +- B: `Hello there, undefined` +- C: `Hello there, null` +- D: `ReferenceError` + +
Answer +

+ +#### Answer: 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` + +

+
+ +--- + +###### 83. 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 `"😎"` + +
Answer +

+ +#### Answer: 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. + + +

+
+ +--- + +###### 84. 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"` + +
Answer +

+ +#### Answer: 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 returend. + +

+
+ +--- + +###### 85. 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"` + +
Answer +

+ +#### Answer: 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 returend. + +

+ +--- + +###### 86. 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` + +
Answer +

+ +#### 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. + +

+ +--- + +###### 87. 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. + +
Answer +

+ +#### Answer: 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. + +

+ +--- + +###### 88. 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` + +
Answer +

+ +#### Answer: A + +With `!!name`, we determine whether the value of `name` is truthy or falsey. 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`. + +

\ No newline at end of file From 0a9547aaaf110e481b69cbf036830de7f1746292 Mon Sep 17 00:00:00 2001 From: Lydia Hallie Date: Fri, 26 Jul 2019 12:43:59 +0200 Subject: [PATCH 257/915] Add email link --- README.md | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index c1f2c0f3..dfbf232b 100644 --- a/README.md +++ b/README.md @@ -6,6 +6,9 @@ From basic to advanced: test how well you know JavaScript, refresh your knowledg The answers are in the collapsed sections below the questions, simply click on them to expand it. Good luck :heart: +Want to get an email whenever I've added more questions?
+✨✉Subscribe to email updates✉✨ + List of available languages: * [English](./README.md) @@ -2695,6 +2698,8 @@ Then, we set `city` equal to the string `"Amsterdam"`. This doesn't change the p When logging the `person` object, the unmodified object gets returend.

+
+ --- @@ -2727,6 +2732,8 @@ console.log(checkAge(21)) 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.

+
+ --- @@ -2751,6 +2758,8 @@ fetch('https://www.website.com/api/user/1') 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.

+
+ --- @@ -2780,4 +2789,5 @@ By setting `hasName` equal to `name`, you set `hasName` equal to whatever value `name.length` returns the length of the passed argument, not whether it's `true`. -

\ No newline at end of file +

+
From e73c102f3448f62af4a441ea7eb1cf1b37f93773 Mon Sep 17 00:00:00 2001 From: Lydia Hallie Date: Fri, 26 Jul 2019 12:45:35 +0200 Subject: [PATCH 258/915] Update update date --- README.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index dfbf232b..957638c0 100644 --- a/README.md +++ b/README.md @@ -2,7 +2,7 @@ I post daily multiple choice JavaScript questions on my [Instagram](https://www.instagram.com/theavocoder), which I'll also post 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 weekly with new questions. Last update: July 14th +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 weekly with new questions. Last update: July 26th The answers are in the collapsed sections below the questions, simply click on them to expand it. Good luck :heart: @@ -2174,7 +2174,7 @@ If the argument passed to the `padStart` method is smaller than the length of th --- -###### 70. What's the output? +###### 70. What's the output? ```javascript console.log("🥑" + "💻"); @@ -2466,7 +2466,7 @@ The third time, we pass `5 * 2` to the function which gets evaluated to `10`. Th --- -###### 79. What is the output? +###### 79. What is the output? ```javascript const myLifeSummedUp = ["☕", "💻", "🍷", "🍫"] From a393748082277157470de9fdfb3c33348aabc4bf Mon Sep 17 00:00:00 2001 From: Jordan Buckley Date: Sat, 27 Jul 2019 00:12:47 +0000 Subject: [PATCH 259/915] fix #181: remove duplicate question 81 and re-number following questions --- README.md | 38 ++++++-------------------------------- 1 file changed, 6 insertions(+), 32 deletions(-) diff --git a/README.md b/README.md index 957638c0..68b5cef1 100644 --- a/README.md +++ b/README.md @@ -2531,32 +2531,6 @@ The element will be equal to the returned value. `1 + 2` returns `3`, `1 * 2` r ###### 81. 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]` - -
Answer -

- -#### Answer: 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`. - -

-
- ---- - -###### 82. What is the output? - ```javascript function sayHi(name) { return `Hi there, ${name}` @@ -2588,7 +2562,7 @@ In this case, if we didn't pass a value or if we passed `undefined`, `name` woul --- -###### 83. What is the output? +###### 82. What is the output? ```javascript var status = "😎" @@ -2628,7 +2602,7 @@ With the `call` method, we can change the object to which the `this` keyword ref --- -###### 84. What is the output? +###### 83. What is the output? ```javascript const person = { @@ -2665,7 +2639,7 @@ When logging the `person` object, the unmodified object gets returend. --- -###### 85. What is the output? +###### 84. What is the output? ```javascript const person = { @@ -2703,7 +2677,7 @@ When logging the `person` object, the unmodified object gets returend. --- -###### 86. What is the output? +###### 85. What is the output? ```javascript function checkAge(age) { @@ -2737,7 +2711,7 @@ Variables with the `const` and `let` keyword are _block-scoped_. A block is anyt --- -###### 87. What kind of information would get logged? +###### 86. What kind of information would get logged? ```javascript fetch('https://www.website.com/api/user/1') @@ -2763,7 +2737,7 @@ The value of `res` in the second `.then` is equal to the returned value of the p --- -###### 88. Which option is a way to set hasName equal to `true`, provided you cannot pass `true` as an argument? +###### 87. Which option is a way to set hasName equal to `true`, provided you cannot pass `true` as an argument? ```javascript function getName(name) { From 53136d90825a21af8bcd6c80f0f266e89efef393 Mon Sep 17 00:00:00 2001 From: Jordan Buckley Date: Sat, 27 Jul 2019 00:51:49 +0000 Subject: [PATCH 260/915] fix typos 2019-07-26 --- README.md | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/README.md b/README.md index 68b5cef1..3ce32187 100644 --- a/README.md +++ b/README.md @@ -2227,7 +2227,7 @@ A generator function "pauses" its execution when it sees the `yield` keyword. Fi 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-statemnet returns `false`, and `JavaScript loves you back ❤️` gets logged. +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.

@@ -2354,7 +2354,7 @@ shape.x = 100; #### Answer: B -`Object.freeze` makes it impossible to add, remove, or modify properties of an object (unless the property's value os another object). +`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. @@ -2494,7 +2494,7 @@ With a _for-in_ loop, we can iterate over **enumerable** properties. In an array `{0: "☕", 1: "💻", 2: "🍷", 3: "🍫"}` -Where the keys are the enumerable propreties. `0` `1` `2` `3` get logged. +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. @@ -2539,9 +2539,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`
Answer @@ -2632,7 +2632,7 @@ Note that we are _not_ referencing the `person` object itself! We simply set the 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 returend. +When logging the `person` object, the unmodified object gets returned.

From e93cb379ceeb34c92386dd870d3337298259ec18 Mon Sep 17 00:00:00 2001 From: Jordan Buckley Date: Sat, 27 Jul 2019 00:52:45 +0000 Subject: [PATCH 261/915] remove duplicate question 85 and re-number following questions --- README.md | 44 ++------------------------------------------ 1 file changed, 2 insertions(+), 42 deletions(-) diff --git a/README.md b/README.md index 3ce32187..20cd2962 100644 --- a/README.md +++ b/README.md @@ -2641,44 +2641,6 @@ When logging the `person` object, the unmodified object gets returned. ###### 84. 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"` - -
Answer -

- -#### Answer: 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 returend. - -

-
- - ---- - -###### 85. What is the output? - ```javascript function checkAge(age) { if (age < 18) { @@ -2708,10 +2670,9 @@ Variables with the `const` and `let` keyword are _block-scoped_. A block is anyt

- --- -###### 86. What kind of information would get logged? +###### 85. What kind of information would get logged? ```javascript fetch('https://www.website.com/api/user/1') @@ -2734,10 +2695,9 @@ The value of `res` in the second `.then` is equal to the returned value of the p

- --- -###### 87. Which option is a way to set hasName equal to `true`, provided you cannot pass `true` as an argument? +###### 86. Which option is a way to set `hasName` equal to `true`, provided you cannot pass `true` as an argument? ```javascript function getName(name) { From 64873e0ce27be85717614d1f88f908ebc1528511 Mon Sep 17 00:00:00 2001 From: Alexander Ivanov Date: Sat, 27 Jul 2019 07:52:36 +0300 Subject: [PATCH 262/915] Russian. Updates 2019/07 2 Signed-off-by: Alexander Ivanov --- README_ru-RU.md | 335 +++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 333 insertions(+), 2 deletions(-) diff --git a/README_ru-RU.md b/README_ru-RU.md index 6ad55983..0191ddd5 100644 --- a/README_ru-RU.md +++ b/README_ru-RU.md @@ -2,10 +2,13 @@ Я ежедневно публикую вопросы по JavaScript с вариантами ответов в своем [Instagram](https://www.instagram.com/theavocoder), которые дублируются в этом репозитории. -От базового до продвинутого: проверьте, насколько хорошо вы знаете JavaScript, немного освежите свои знания или подготовьтесь к собеседованию! :muscle: :rocket: Я обновляю репозиторий еженедельно новыми вопросами. Последнее обновление: 7 июля +От базового до продвинутого: проверьте, насколько хорошо вы знаете JavaScript, немного освежите свои знания или подготовьтесь к собеседованию! :muscle: :rocket: Я обновляю репозиторий еженедельно новыми вопросами. Последнее обновление: 26 июля Ответы находятся в свернутой секции ниже вопросов. Просто нажми на "Ответ", чтобы развернуть. Удачи! :heart: +Хотите получать электронную почту всякий раз, когда я добавляю новые вопросы?
+✨✉Подпишитесь на обновления✉✨ + Список доступных переводов: * [English](./README.md) @@ -2171,7 +2174,7 @@ console.log(name.padStart(2)) --- -###### 70. Какой будет вывод? +###### 70. Какой будет вывод? ```javascript console.log("🥑" + "💻"); @@ -2460,3 +2463,331 @@ console.log(addFunction(5 * 2));

+ +--- + +###### 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` и `"☕"` ` "💻"` `"🍷"` `"🍫"` +- B: `"☕"` ` "💻"` `"🍷"` `"🍫"` и `"☕"` ` "💻"` `"🍷"` `"🍫"` +- C: `"☕"` ` "💻"` `"🍷"` `"🍫"` и `0` `1` `2` `3` +- D: `0` `1` `2` `3` и `{0: "☕", 1: "💻", 2: "🍷", 3: "🍫"}` + +
Ответ +

+ +#### Ответ: A + +С помощью цикла _for-in_ мы можем перебирать **перечисляемые** свойства. В массиве перечисляемые свойства являются "ключами" элементов массива, которые фактически являются их индексами. Вы можете увидеть массив как: + +`{0: "☕", 1: "💻", 2: "🍷", 3: "🍫"}` + +Где ключи - перечисляемые свойства. `0` `1` `2` `3` войти в систему. + +С помощью цикла _for-of_ мы можем выполнять итерацию **итераций**. Массив является итеративным. Когда мы выполняем итерацию по массиву, переменная "item" равна элементу, по которому она итерируется в данный момент, `"☕"` `"💻"` `"🍷"` `"🍫"` выводится в лог. + +

+
+ +--- + +###### 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 + +Элементы массива могут содержать любые значения. Числа, строки, объекты, другие массивы, ноль, логические значения, неопределенные и другие выражения, такие как даты, функции и вычисления. + +Элемент будет равен возвращаемому значению. `1 + 2` вернет `3`, `1 * 2` вернет `2`, а `1 / 2` вернет `0.5`. + +

+
+ +--- + +###### 81. Какой будет вывод? + +```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 + +Элементы массива могут содержать любые значения. Числа, строки, объекты, другие массивы, ноль, логические значения, неопределенные и другие выражения, такие как даты, функции и вычисления. + +Элемент будет равен возвращаемому значению. `1 + 2` вернет `3`, `1 * 2` вернет `2`, а `1 / 2` вернет `0.5`. + +

+
+ +--- + +###### 82. Какой будет вывод? + +```javascript +function sayHi(name) { + return `Hi there, ${name}` +} + +console.log(sayHi()) +``` + +- A: `Hello there, ` +- B: `Hello there, undefined` +- C: `Hello there, null` +- D: `ReferenceError` + +
Ответ +

+ +#### Ответ: B + +По умолчанию аргументы имеют значение `undefined`, если только значение не было передано функции. В этом случае мы не передали значение для аргумента `name`. `name` равно логгируемому `undefined`. + +В ES6 мы можем перезаписать значение по умолчанию `undefined` параметрами по умолчанию. Например: + +`function sayHi(name = "Lydia") { ... }` + +В этом случае, если мы не передали значение или если мы передали `undefined`, `name` всегда будет равно строке `Lydia` + +

+
+ +--- + +###### 83. Какой будет вывод? + +```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: `"🥑"` и `"😍"` +- B: `"🥑"` и `"😎"` +- C: `"😍"` и `"😎"` +- D: `"😎"` и `"😎"` + +
Ответ +

+ +#### Ответ: B + +Значение ключевого слова `this` зависит от того, где вы его используете. В **методе**, как и в методе `getStatus`, ключевое слово `this` ссылается на объект, которому принадлежит метод. Метод принадлежит объекту `data`, поэтому `this` относится к объекту `data`. Когда мы регистрируем `this.status`, регистрируется свойство `status` объекта `data`, которое является `"🥑"`. + +С помощью метода `call` мы можем изменить объект, на который ссылается ключевое слово `this`. В **функциях** ключевое слово `this` относится к _объекту, которому принадлежит функция_. Мы объявили функцию `setTimeout` для объекта _global_, поэтому в функции `setTimeout` ключевое слово `this` ссылается на объект _global_. В глобальном объекте есть переменная с именем _status_ со значением `"😎"`. При регистрации `this.status` выводится `"😎"`. + + +

+
+ +--- + +###### 84. Какой будет вывод? + +```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` равной значению свойства с именем `city` для объекта `person`. У этого объекта нет свойства с именем `city`, поэтому переменная `city` имеет значение `undefined`. + +Обратите внимание, что мы _не_ ссылаемся на сам объект person! Мы просто устанавливаем переменную `city` равной текущему значению свойства `city` объекта `person`. + +Затем мы устанавливаем `city` равным строке `"Amsterdam"`. Это не меняет объект person - нет ссылки на этот объект. + +При регистрации объекта `person` возвращается неизмененный объект. + +

+
+ +--- + +###### 85. Какой будет вывод? + +```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` равной значению свойства с именем `city` для объекта `person`. У этого объекта нет свойства с именем `city`, поэтому переменная `city` имеет значение `undefined`. + +Обратите внимание, что мы _не_ ссылаемся на сам объект person! Мы просто устанавливаем переменную `city` равной текущему значению свойства `city` объекта `person`. + +Затем мы устанавливаем `city` равным строке `"Amsterdam"`. Это не меняет объект person - нет ссылки на этот объект. + +При регистрации объекта `person` возвращается неизмененный объект. + +

+
+ + +--- + +###### 86. Какой будет вывод? + +```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` являются _block-scoped_. Блок - это что-то между фигурными скобками (`{}`). В этом случае в фигурных скобках операторов if/else. Вы не можете ссылаться на переменную за пределами блока, в котором она объявлена, вызывается ReferenceError. + +

+
+ + +--- + +###### 87. Какая информация будетвыведена в лог? + +```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. + +
Ответ +

+ +#### Ответ: C + +Значение `res` во втором `.then` равно возвращенному значению предыдущего `.then`. Вы можете продолжать цепочку `.then` таким образом; значение передается следующему обработчику. + +

+
+ + +--- + +###### 88. Какая опция позволяет установить hasName равным `true`, если вы не можете передать`true` в качестве аргумента? + +```javascript +function getName(name) { + const hasName = // +} +``` + +- A: `!!name` +- B: `name` +- C: `new Boolean(name)` +- D: `name.length` + +
Ответ +

+ +#### Ответ: A + +С помощью `!!name` мы определяем, является ли значение `name` истинным или ложным. Если имя истинное, которое мы хотим проверить, то `!name` возвращает `false`. А `!false` (это то, чем на самом деле является `!! name`) возвращает `true`. + +Устанавливая `hasName` равным `name`, вы устанавливаете `hasName` равным любому значению, которое вы передали функции `getName`, а не логическому значению `true`. + +`new Boolean (true)` возвращает объектную оболочку, а не само логическое значение. + +`name.length` возвращает длину переданного аргумента, независимо от того, является ли он `true`. + +

+
From e3b5ea0947f5974a7332ad7e30ca4730b30f0826 Mon Sep 17 00:00:00 2001 From: Alexander Ivanov Date: Sat, 27 Jul 2019 19:08:54 +0300 Subject: [PATCH 263/915] Update after #182 Signed-off-by: Alexander Ivanov --- README_ru-RU.md | 78 +++++-------------------------------------------- 1 file changed, 7 insertions(+), 71 deletions(-) diff --git a/README_ru-RU.md b/README_ru-RU.md index 0191ddd5..1698bba4 100644 --- a/README_ru-RU.md +++ b/README_ru-RU.md @@ -2342,6 +2342,8 @@ Object.freeze(box); const shape = box; shape.x = 100; + +console.log(shape); ``` - A: `{ x: 100, y: 20 }` @@ -2531,32 +2533,6 @@ console.log(list) ###### 81. Какой будет вывод? -```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 - -Элементы массива могут содержать любые значения. Числа, строки, объекты, другие массивы, ноль, логические значения, неопределенные и другие выражения, такие как даты, функции и вычисления. - -Элемент будет равен возвращаемому значению. `1 + 2` вернет `3`, `1 * 2` вернет `2`, а `1 / 2` вернет `0.5`. - -

-
- ---- - -###### 82. Какой будет вывод? - ```javascript function sayHi(name) { return `Hi there, ${name}` @@ -2588,7 +2564,7 @@ console.log(sayHi()) --- -###### 83. Какой будет вывод? +###### 82. Какой будет вывод? ```javascript var status = "😎" @@ -2628,44 +2604,7 @@ setTimeout(() => { --- -###### 84. Какой будет вывод? - -```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` равной значению свойства с именем `city` для объекта `person`. У этого объекта нет свойства с именем `city`, поэтому переменная `city` имеет значение `undefined`. - -Обратите внимание, что мы _не_ ссылаемся на сам объект person! Мы просто устанавливаем переменную `city` равной текущему значению свойства `city` объекта `person`. - -Затем мы устанавливаем `city` равным строке `"Amsterdam"`. Это не меняет объект person - нет ссылки на этот объект. - -При регистрации объекта `person` возвращается неизмененный объект. - -

-
- ---- - -###### 85. Какой будет вывод? +###### 83. Какой будет вывод? ```javascript const person = { @@ -2700,10 +2639,9 @@ console.log(person)

- --- -###### 86. Какой будет вывод? +###### 84. Какой будет вывод? ```javascript function checkAge(age) { @@ -2734,10 +2672,9 @@ console.log(checkAge(21))

- --- -###### 87. Какая информация будетвыведена в лог? +###### 85. Какая информация будетвыведена в лог? ```javascript fetch('https://www.website.com/api/user/1') @@ -2760,10 +2697,9 @@ fetch('https://www.website.com/api/user/1')

- --- -###### 88. Какая опция позволяет установить hasName равным `true`, если вы не можете передать`true` в качестве аргумента? +###### 86. Какая опция позволяет установить hasName равным `true`, если вы не можете передать`true` в качестве аргумента? ```javascript function getName(name) { From e629605e5428d3a9fd8160410ce3f9644d32cc0c Mon Sep 17 00:00:00 2001 From: yusufkaracin Date: Sun, 28 Jul 2019 11:23:33 +0300 Subject: [PATCH 264/915] updates to 26th July --- README-tr_TR.md | 284 ++++++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 275 insertions(+), 9 deletions(-) diff --git a/README-tr_TR.md b/README-tr_TR.md index a43eac69..16667811 100644 --- a/README-tr_TR.md +++ b/README-tr_TR.md @@ -2,10 +2,14 @@ [Instagram](https://www.instagram.com/theavocoder) hesabımda, günlük olarak çoktan seçmeli Javascript soruları paylaşıyorum, ayrıca burada da paylaşacağım! -Temelden ileri düzeye: Javascript'i ne kadar iyi bildiğinizi test edin, bilginizi biraz tazeleyin ya da mülakatanıza hazırlanın! :muscle: :rocket: Repoyu haftalık olarak yeni sorularla güncelliyorum. Son güncelleme: Last update: 14 Temmuz +Temelden ileri düzeye: Javascript'i ne kadar iyi bildiğinizi test edin, bilginizi biraz tazeleyin ya da mülakatanıza hazırlanın! :muscle: :rocket: Repoyu haftalık olarak yeni sorularla güncelliyorum. Son güncelleme: 26 Temmuz Cevaplar, soruların altında gizlenmiştir. Görmek için sadece tıklayın. İyi şanşlar :heart: +Daha fazla soru eklendikçe eposta almak ister misiniz?
+✨✉Eposta bildirimlerine abone olun✉✨ + + Mevcut dillerin listesi: * [English](./README.md) @@ -2171,8 +2175,8 @@ console.log("🥑" + "💻"); - A: `"🥑💻"` - B: `257548` -- C: A string containing their code points -- D: Error +- C: Emojilerin kod numaralarını gösteren string +- D: Hata
Cevap

@@ -2201,10 +2205,10 @@ 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")` +- A: `game.next("Yes").value` ve `game.next().value` +- B: `game.next.value("Yes")` ve `game.next.value()` +- C: `game.next().value` ve `game.next("Yes").value` +- D: `game.next.value()` ve `game.next.value("Yes")`

Cevap

@@ -2390,8 +2394,8 @@ function sum(a, b) { } ``` -- A: Yes -- B: No +- A: Evet +- B: Hayır

Cevap

@@ -2452,3 +2456,265 @@ Eğer `addFunction` fonksiyonunu aynı argüman ile tekrar çağırırsak, önce

+ +--- + +###### 79. Çıktısı Nedir? + +```javascript +const myLifeSummedUp = ["☕", "💻", "🍷", "🍫"] + +for (let item in myLifeSummedUp) { + console.log(item) +} + +for (let item of myLifeSummedUp) { + 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: "🍫"}` + +
Cevap +

+ +#### Cevap: A + +_for-in_ döngüsü ile, **sayılabilir** (**enumerable**) özellikler üzerinde iterasyon yapabiliriz. Dizilerde, sayılabilir özellikler dizi elemanlarının "keyleridir", ki bu keyler aslında dizinin indeksidir. Diziyi şöyle görebilirsiniz: + +`{0: "☕", 1: "💻", 2: "🍷", 3: "🍫"}` + +Burada keyler, sayılabilir özelliklerdir. `0` `1` `2` `3` loglanır. + +_for-of_ döngüsü ile, **yinelenebilirler** (**iterables**) üzerinde iterasyon yapabiliriz. Dizi, yinelebilirdir. Dizi üzerinde iterasyon yaptığımız zaman, `item` değişkeni o anda iterasyon yapılan elemana eşittir, `"☕"` ` "💻"` `"🍷"` `"🍫"` loglanır. + +

+
+ +--- + +###### 80. Çıktısı Nedir? + +```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]` + +
Cevap +

+ +#### Cevap: C + +Dizi elemanları herhangi bir değeri tutabilir. Sayılar, stringler, nesneler, başka diziler, null, doğru/yanlış değerler, undefined, ve date, fonksiyonlar, hesaplamalar gibi başka ifadeler. + +Eleman dönen değere eşit olacaktır. `1 + 2` `3` döndürür, `1 * 2` `2` döndürür, ve `1 / 2` `0.5` döndürür. + +

+
+ +--- + +###### 81. Çıktısı Nedir? + +```javascript +function sayHi(name) { + return `Hi there, ${name}` +} + +console.log(sayHi()) +``` + +- A: `Hi there, ` +- B: `Hi there, undefined` +- C: `Hi there, null` +- D: `ReferenceError` + +
Cevap +

+ +#### Cevap: B + +Varsayılan olarak, fonksiyona bir değer geçilmedikçe, argümanlar `undefined` değerine sahiptir. Bu örnekte, `name` argümanı için bir değer geçmedik. + +ES6'da, bu varsayılan `undefined` değerini varsayılan parametreler ile ezebiliriz. Örneğin; + +`function sayHi(name = "Lydia") { ... }` + +Bu örnekte, eğer bir değer geçmeseydik ya da `undefined` geçseydik, `name` her zaman `Lydia`'a eşit olacaktı. + +

+
+ +--- + +###### 82. Çıktısı Nedir? + +```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: `"🥑"` ve `"😍"` +- B: `"🥑"` ve `"😎"` +- C: `"😍"` ve `"😎"` +- D: `"😎"` ve `"😎"` + +
Cevap +

+ +#### Cevap: 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. Çıktısı Nedir? + +```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"` + +
Cevap +

+ +#### Cevap: 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. Çıktısı Nedir? + +```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` + +
Cevap +

+ +#### Cevap: 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. + +
Cevap +

+ +#### Cevap: 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` + +
Cevap +

+ +#### Cevap: A + +With `!!name`, we determine whether the value of `name` is truthy or falsey. 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`. + +

+
From 2534ec415fd72b07090045ebbcaa04f1032d55ff Mon Sep 17 00:00:00 2001 From: lazy <310195875@qq.com> Date: Sun, 28 Jul 2019 17:39:23 +0800 Subject: [PATCH 265/915] update zh_CN.md: add question 79-86 --- README-zh_CN.md | 260 ++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 260 insertions(+) diff --git a/README-zh_CN.md b/README-zh_CN.md index e3dee426..fe73979f 100644 --- a/README-zh_CN.md +++ b/README-zh_CN.md @@ -2459,3 +2459,263 @@ console.log(addFunction(5 * 2));

+ +--- + +###### 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`, 因此`“☕”`,`“💻“`,`”🍷”`,`“🍫“`被打印。 + +

+
+ +--- + +###### 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`。 + +

+
+ +--- + +###### 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` + +

+
+ +--- + +###### 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`时,会打印`“😎”`。 +

+
+ +--- + +###### 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`对象时,会返回未修改的对象。 + +

+
+ +--- + +###### 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`。 + +

+
+ +--- + +###### 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`,将值传递给下一个处理程序。 + +

+
+ +--- + +###### 86. 哪个选项是将`hasName`设置为`true`的方法,前提是不能将`true`作为参数传递? + +```javascript +function getName(name) { + const hasName = // +} +``` + +- A: `!!name` +- B: `name` +- C: `new Boolean(name)` +- D: `name.length` + +
答案 +

+ +#### 答案: A + +使用逻辑非运算符`!`,将返回一个布尔值,使用`!! name`,我们可以确定`name`的值是真的还是假的。 如果`name`是真实的,那么`!name`返回`false`。 `!false`返回`true`。 + +通过将`hasName`设置为`name`,可以将`hasName`设置为等于传递给`getName`函数的值,而不是布尔值`true`。 + +`new Boolean(true)`返回一个对象包装器,而不是布尔值本身。 + +`name.length`返回传递的参数的长度,而不是布尔值`true`。 + +

+
From 5d533c046192968a772718d465a11f52c4e8fb70 Mon Sep 17 00:00:00 2001 From: lazy <310195875@qq.com> Date: Sun, 28 Jul 2019 17:44:34 +0800 Subject: [PATCH 266/915] typo --- README-zh_CN.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README-zh_CN.md b/README-zh_CN.md index fe73979f..d5898cc5 100644 --- a/README-zh_CN.md +++ b/README-zh_CN.md @@ -2588,7 +2588,7 @@ setTimeout(() => { #### 答案: 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`时,会打印`“😎”`。

From d10c06858920e32efcee2b57ef75bafe8387a9fa Mon Sep 17 00:00:00 2001 From: yusufkaracin Date: Sun, 28 Jul 2019 13:40:58 +0300 Subject: [PATCH 267/915] translates till 86 --- README-tr_TR.md | 41 ++++++++++++++++++++--------------------- 1 file changed, 20 insertions(+), 21 deletions(-) diff --git a/README-tr_TR.md b/README-tr_TR.md index 16667811..0b8fd6ba 100644 --- a/README-tr_TR.md +++ b/README-tr_TR.md @@ -2585,10 +2585,9 @@ setTimeout(() => { #### Cevap: 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. +`this` anahtar kelimesinin değeri, onu nerede kullandığınıza bağlıdır. **method** içinde, `getStatus` methodu gibi, `this` anahtar kelimesi _methodun bağlı olduğu nesneyi_ referans gösterir. Method `data` nesnesine ait, bu yüzden `this` `data` nesnesini referans gösterir. `this.status`'ü logladığımız zaman, `data` nesnesindeki `status` özelliği loglanır, ki o da `"🥑"`. +`call` methodu ile, `this` anahtar kelimesinin referans gösterdiği nesneyi değiştirebiliriz. **fonksiyon** içinde, `this` anahtar kelimesi _fonksiyonun ait olduğu nesneyi_ referans gösterir. _global nesne_ üzerinde `setTimeout` fonksiyonu tanımladık, yani `setTimeout` fonksiyonu içinde, `this` anahtar kelimesi _global nesneyi_ referans gösterir. Global nesnede, değeri `"😎"` olan _status_ olarak adlandırılmış bir değişken var. `this.status`'ü logladığımız zaman, `"😎"` loglanır.

@@ -2618,14 +2617,14 @@ 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. -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. +`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. -When logging the `person` object, the unmodified object gets returned. +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.

@@ -2658,14 +2657,14 @@ console.log(checkAge(21)) #### Cevap: 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. +`const` ve `let` anahtar kelimesine sahip değişkenler _block-scoped_'dur. Blok süslü parantezler (`{}`) arasındaki herhangi bir şeydir. Bu örnekte, if/else ifadesindeki süslü parantezlerdir. Bir değişkene, tanımlandığı blok dışından erişemezsiniz, ReferenceError fırlatılır.

--- -###### 85. What kind of information would get logged? +###### 85. Loglanacak değer ne tür olur? ```javascript fetch('https://www.website.com/api/user/1') @@ -2673,24 +2672,24 @@ fetch('https://www.website.com/api/user/1') .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. +- 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.
Cevap

#### Cevap: 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. +İkinci `.then` içindeki `res`'in değeri bir önceki `.then`'den dönen değere eşittir. Bunun gibi, değerlerin bir sonraki yöneticiye (handler) geçileceği şekilde, `.then`'leri birbirlerine bağlayabilirsiniz,

--- -###### 86. Which option is a way to set `hasName` equal to `true`, provided you cannot pass `true` as an argument? +###### 86. `true`'yu argüman olarak geçemediğiniz durumda, hangi seçenek `hasName`'i `true`'ya eşitlemenin yoludur? ```javascript function getName(name) { @@ -2708,13 +2707,13 @@ function getName(name) { #### Cevap: A -With `!!name`, we determine whether the value of `name` is truthy or falsey. If name is truthy, which we want to test for, `!name` returns `false`. `!false` (which is what `!!name` practically is) returns `true`. +`!!name` ile, `name`'in değerinin doğrusal ya da yanlış-ımsı olup olmadığını belirleriz. Eğer `name` doğrusalsa, ki test etmek istediğimiz bu, `!name` `false` döndürür. `!false` (bu da `!!name` ne demekse o demektir gerçekte) `true` döndürür. -By setting `hasName` equal to `name`, you set `hasName` equal to whatever value you passed to the `getName` function, not the boolean value `true`. +`hasName`'i `name`'e eşitleyerek, `hasName`'i `getName` fonksiyonuna hangi değeri geçtiyseniz ona eşitlersiniz, `true` değerine değil. -`new Boolean(true)` returns an object wrapper, not the boolean value itself. +`new Boolean(true)` nesne (object wrapper) döndürür, doğru/yanlış (boolean) değerinin kendisini değil. -`name.length` returns the length of the passed argument, not whether it's `true`. +`name.length` geçilen argümanın uzunluğunu döndürür, `true` olup olmadığını değil.

From 99275a1249f63f57612a2f745126d843ebd345ae Mon Sep 17 00:00:00 2001 From: panicdragon Date: Mon, 29 Jul 2019 22:08:27 +0900 Subject: [PATCH 268/915] add new questions no.64~no.86 & translate to japanese --- README-ja_JA.md | 817 +++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 811 insertions(+), 6 deletions(-) diff --git a/README-ja_JA.md b/README-ja_JA.md index 69e041f4..7bbe1641 100644 --- a/README-ja_JA.md +++ b/README-ja_JA.md @@ -7,12 +7,21 @@ 答えは質問の下の折りたたまれたセクションにあります、クリックすればそれを広げられます。幸運を祈ります。:heart: -[中文版本](./README-zh_CN.md) -[Русский](./README_ru-RU.md) -[Western Balkan](./README-bs_BS.md) -[Deutsch](./README-de_DE.md) -[Tiếng Việt](./README-vi.md) -[日本語](./README-ja_JA.md) +利用可能な言語リスト: +* [English](./README.md) +* [العربية](./README_AR.md) +* [اللغة العامية - Egyptian Arabic](./README_ar-EG.md) +* [Bosanski](./README-bs_BS.md) +* [Deutsch](./README-de_DE.md) +* [Español](./README-ES.md) +* [日本語](./README-ja_JA.md) +* [한국어](./README-ko_KR.md) +* [Português Brasil](./README_pt_BR.md) +* [Русский](./README_ru-RU.md) +* [Українська мова](./README-ua_UA.md) +* [Tiếng Việt](./README-vi.md) +* [中文版本](./README-zh_CN.md) +* [Türkçe](./README-tr_TR.md) --- @@ -2017,3 +2026,799 @@ console.log(num2);

+ +--- + +###### 64. 何が出力されるでしょうか? + +```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` + +
答え +

+ +#### 答え: C + + +ES6では、パラメータをデフォルト値で初期化できます。値が関数に渡されていない場合やパラメータの値が `"undefined"`の場合、パラメータの値はデフォルト値になります。上記の場合、`value`オブジェクトのプロパティを新しいオブジェクトに分割代入されるので、`x`のデフォルト値は`{number:10}`になります。 + +デフォルトの引数は、_呼び出し時_ に評価されます。関数を呼び出すたびに、_新しい_ オブジェクトが作成されます。 + +最初に値を渡さずに2回、`multiply`関数を呼び出します: `x`のデフォルト値は `{number:10}`となり、その数の乗算された値、つまり `20`を出力します。 + +3回目のmultiplyを呼び出すとき、引数を渡します: `value`というオブジェクトです。 + +`*=`演算子は`x.number = x.number * 2`の省略形となります: `x.number`の値は乗算した値に修正され、`20`を出力します。 + +4回目は、`value`オブジェクトをもう一度渡します。`x.number`は以前は`20`に修正されているので、`x.number *= 2`は`40`を出力します。 + +

+
+ +--- + +###### 65. 何が出力されるでしょうか? + +```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` + +
答え +

+ +#### 答え: D + + +`reduce`メソッドが受け取る最初の引数は _アキュムレータ_ となります。この場合は`x`です。 2番目の引数は、_現在の値_ `y`です。 reduceメソッドでは、配列内のすべての要素に対してコールバック関数を実行します。これにより、最終的に1つの値が得られます。 + +上記の例では、値を返していません。単にアキュムレータの値と現在の値を記録しています。 + +アキュムレータの値は、以前に返されたコールバック関数の値と同じです。オプションの`initialValue`引数を`reduce`メソッドに渡さないと、アキュムレータは最初の呼び出しの最初の要素に等しくなります。 + +最初の呼び出しでは、アキュムレータ(`x`)は`1`であり、現在値(`y`)は`2`となります。コールバック関数からは戻らないので、アキュムレータと現在の値を出力します: `1`と`2`が出力されます。 + +関数から値を返さなければ、`undefined`を返します。次の呼び出しでは、アキュムレータは`undefined`で、現在の値は`3`です。`undefined`と`3`が出力されます。 + +4回目の呼び出しでも、コールバック関数からは戻りません。アキュムレータもまた`undefined`であり、現在の値は`4`となり、`undefined`と`4`が出力されます。 + +

+
+ +--- + +###### 66. どのコンストラクタを使えば `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 + +
答え +

+ +#### 答え: B + +派生クラスでは、`super`を呼び出す前に、`this`キーワードにアクセスすることはできません。そうしようとすると、ReferenceErrorがスローされます: 1と4は参照エラーをスローします。 + +`super`キーワードを使って、与えられた引数で、その親クラスのコンストラクタを呼び出します。親のコンストラクタは`name`引数を受け取るので、`name`を`super`に渡す必要があります。 + +`Labrador`クラスは2つの引数、`Dog`を拡張するための`name`と、`Labrador`クラスの追加のプロパティとしての`size`を受け取ります。 + +両方とも`Labrador`のコンストラクタ関数に渡す必要があります。これはコンストラクタ2を使って正しく実行されます。 +

+
+ +--- + +###### 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()`を使うと、コードが実行されている間に依存関係をオンデマンドでロードすることができます。 + +`import`の代わりに`require`を使用したとしたら、`running index.js`, `running sum.js`, `3`が出力されているはずです。 + +

+
+ +--- + +###### 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の値は渡された引数に依存しません。 + +等価性をテストしているので、2つのまったく新しいシンボルを作成します: 最初の`Symbol('foo')`と、2番目の`Symbol('foo')`です。これら2つの値は一意であり、互いに等しくはありません、なので`Symbol('foo') === Symbol('foo')`は`false`を返します。 + +

+
+ +--- + +###### 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)`は、12 + 1が13であるため、文字列の先頭に1スペースを挿入されます。 + +`padStart`メソッドに渡された引数が、配列の長さよりも小さい場合、パディングは追加されません。 + +

+
+ +--- + +###### 70. 何が出力されるでしょうか? + +```javascript +console.log("🥑" + "💻"); +``` + +- A: `"🥑💻"` +- B: `257548` +- C: A string containing their code points +- D: Error + +
答え +

+ +#### 答え: A + + +`+`演算子を使うと、文字列を連結することができます。この場合、文字列`"🥑"`を文字列`"💻"`と連結して、結果として`"🥑💻"`となります。 + +

+
+ +--- + +###### 71. 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")` + +
答え +

+ +#### 答え: C + +ジェネレータ関数は、`yield`キーワードを見るとその実行を「一時停止」します。まず、関数に文字列 "Do you love JavaScript?" を返させる必要があります。これは `game.next().value`を呼び出すことによって行うことができます。 + +最初の`yield`キーワードが見つかるまで、すべての行が実行されます。関数内の最初の行に`yield`キーワードがあります: 実行は最初のyieldで停止します! _これは変数 `answer`がまだ定義されていないことを意味します!_ + +`game.next("Yes").value`を呼び出すと、前の`yield`は`next()`関数に渡されたパラメータの値、この場合は`"Yes"`に置き換えられます。変数`answer`の値は現在`"Yes"`となります。 + +if-statemnetの条件は`false`を返し、`JavaScript loves you back ❤️`が、出力されます。 + +

+
+ +--- + +###### 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`と出力されます。 + +

+
+ +--- + +###### 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が解決されるのを待たなければなりません: `getData()`を呼び出すと、`data`は保留中のpromiseが返されます。 + +解決した値`"I made it"`にアクセスしたい場合は、`data`に対して`.then()`メソッドを使用することができます: + +`data.then(res => console.log(res))` + +これは`"I made it!"`と出力するでしょう。 + +

+
+ +--- + +###### 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つの要素(文字列 `" 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を返すべきです。 +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. 何が出力されるでしょうか? + +```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`は、オブジェクトのプロパティを追加、削除、変更することを不可能にします(プロパティの値が他のオブジェクトのものでない限り)。 + +変数`shape`を作成し、フリーズしたオブジェクト`box`に代入すると、`shape`はフリーズしたオブジェクトとなります。オブジェクトがフリーズしているかどうかは `Object.isFrozen`を使って確認できます。 + +この場合、変数`shape`はフリーズしたオブジェクトへの参照を持っているので、`Object.isFrozen(shape)`はtrueを返します。 + +`shape`はフリーズされており、`x`の値はオブジェクトではないので、プロパティ`x`を変更することはできません。 + +`x`は`10`のままとなり、`{ x: 10, y: 20 }`と出力されます。 + +

+
+ +--- + +###### 76. 何が出力されるでしょうか? + +```javascript +const { name: myName } = { name: "Lydia" }; + +console.log(name); +``` + +- A: `"Lydia"` +- B: `"myName"` +- C: `undefined` +- D: `ReferenceError` + +
答え +

+ +#### 答え: D + +右側のオブジェクトからプロパティ`name`をアンパックするとき、その値`"Lydia"`を`myName`という名前の変数に代入します。 + +`{name:myName}`を使って、右側の `name`プロパティの値で`myName`という新しい変数を作りたいことをJavaScriptに伝えます。 + +定義されていない変数`name`を出力しようとしているので、ReferenceErrorが投げられます。 + +

+
+ +--- + +###### 77. これは純粋関数でしょうか? + +```javascript +function sum(a, b) { + return a + b; +} +``` + +- A: Yes +- B: No + +
答え +

+ +#### 答え: A + +純粋な関数は、同じ引数が渡された場合、_常に_ 同じ結果を返す関数です。 + +`sum`関数は常に同じ結果を返します。`1`と`2`を渡すと、副作用なしに _常に_ `3` を返します。`5`と`10`を渡すと、_常に_ `15`が返され、以下同様に続きます。これが純粋関数の定義です。 + +

+
+ +--- + +###### 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`関数は _memoized_ 関数です。メモ化により、実行速度を上げるために関数の結果をキャッシュすることができます。上記の場合、以前に返された値を格納する`cache`オブジェクトを作成します。 + +同じ引数を指定してもう一度`addFunction`関数を呼び出すと、最初にキャッシュ内でその値がすでに取得されているかどうかを調べます。 + +この場合、cachesの値が返され、実行時間が短縮されます。そうでなくキャッシュされていなければ、値を計算した後にそれを格納します。 + +同じ値で3回`addFunction`関数を呼び出します: 最初の呼び出しでは、`num`に`10`を代入した時、関数の値はまだキャッシュされていません。 + +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'`が出力されます。 + +3回目は、`10`に評価される関数に`5 * 2`を渡します。`cache`オブジェクトは`10`に対して返される値を含みます。ifステートメントの`num in cache`の条件は`true`となり、`'From cache! 20'`を返します。 よって`'From cache! 20'`が出力されます。 + +

+
+ +--- + +###### 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_ ループを使うと、**列挙可能な**プロパティを繰り返し処理できます。配列では、列挙可能なプロパティは配列要素の「キー」です。これはそれらのインデックスとなり、配列は次のようになります: + +`{0: "☕", 1: "💻", 2: "🍷", 3: "🍫"}` + +キーが列挙可能なプロパティであるので、`0` `1` `2` `3`が出力されます。 + +_for-of_ ループを使うと、**反復可能オブジェクト**を繰り返し処理できます。 + +配列はイテラブルです。配列を反復処理するとき、変数 "item"は、現在反復処理している要素となるので、`"☕"` ` "💻"` `"🍷"` `"🍫"`が出力されます。 + +

+
+ +--- + +###### 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、ブール値、undefined、および日付、関数、計算などのその他の式。 + +要素は戻り値と等しくなります。`1 + 2`は`3`を返し、`1 * 2`は`2`を返し、`1 / 2`は`0.5`を返します。 + +

+
+ +--- + +###### 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`となります。 + +

+
+ +--- + +###### 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`オブジェクトに属しているので、`this`は `data`オブジェクトを参照します。 `this.status`をログ出力すると、`data`オブジェクトの`status`プロパティの`"🥑"`がログ出力されます。 + +`call`メソッドを使うと、`this`キーワードが参照するオブジェクトを変更することができます。 **関数**では、`this`キーワードは _その関数が属するオブジェクトを参照します_ 。 + +_グローバルオブジェクトで_ `setTimeout`関数を宣言したので、`setTimeout`関数内では、 `this`キーワードは _グローバルオブジェクト_ を参照します。 + +グローバルオブジェクト上には、値`"😎"`を持つ _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`オブジェクト自身を参照して _いない_ ことに注意してください。`person`オブジェクトの`city`プロパティを、変数`city`に代入するだけです。 + +それから、`city`に、文字列`"Amsterdam"`を代入しますこれは personオブジェクトを変更しません: そのオブジェクトへの参照はありません。 + +`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 がスローされます。 + +

+
+ +--- + +###### 85. どのような情報が出力されますか? + +```javascript +fetch('https://www.website.com/api/user/1') + .then(res => res.json()) + .then(res => console.log(res)) +``` + +- A: `fetch`メソッドの結果 +- B: 2回目の `fetch`メソッド呼び出しの結果 +- C: 前の`.then()`でのコールバックの結果 +- D: 常に undefined. + +
答え +

+ +#### 答え: C + +2番目の`.then`の`res`の値は、前の`.then`の戻り値と同じとなります。値が次のハンドラに渡されるように、`.then`を連鎖させることができます。 + +

+
+ +--- + +###### 86. 引数としてtrueを渡すことができない場合、どのオプションが`hasName`を`true`に設定するための方法ですか? + +```javascript +function getName(name) { + const hasName = // +} +``` + +- A: `!!name` +- B: `name` +- C: `new Boolean(name)` +- D: `name.length` + +
答え +

+ +#### 答え: A + +`!!name`を使って、`name`の値が、truthyか falseyかを判断します。nameがtruthyであり、これをテストしたい場合、`!name`は`false`を返します。`!false`(これは実際には`!!name`です)は`true`を返します。 + +`hasName`に`name`を代入することで、`getName`関数に渡されたどんな値も`hasName`に代入されます。ブール値`true`は設定できません。 + +`new Boolean(true)`は、ブール値そのものではなく、オブジェクトラッパーを返します。 + +`name.length`は渡された引数の長さを返します。それが`true`であるかどうかではありません。 + +

+
From 0f6a3b98d32df79839dca7e2ca1cc3860324de5f Mon Sep 17 00:00:00 2001 From: Alexander Ivanov Date: Tue, 30 Jul 2019 12:56:12 +0300 Subject: [PATCH 269/915] =?UTF-8?q?Add=20Fran=C3=A7ais=20to=20TOC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Alexander Ivanov --- README_ru-RU.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README_ru-RU.md b/README_ru-RU.md index 1698bba4..c03d087b 100644 --- a/README_ru-RU.md +++ b/README_ru-RU.md @@ -17,6 +17,7 @@ * [Bosanski](./README-bs_BS.md) * [Deutsch](./README-de_DE.md) * [Español](./README-ES.md) +* [Français](./README_fr-FR.md) * [日本語](./README-ja_JA.md) * [한국어](./README-ko_KR.md) * [Português Brasil](./README_pt_BR.md) From e5260b25e9f3ce75ea16ecbf8c7b253bdcbd39d7 Mon Sep 17 00:00:00 2001 From: sweetmilkys Date: Fri, 2 Aug 2019 00:35:19 +0900 Subject: [PATCH 270/915] Fix typo 2019-07-26 --- README-ko_KR.md | 286 ++++++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 277 insertions(+), 9 deletions(-) diff --git a/README-ko_KR.md b/README-ko_KR.md index fbc30e11..a34ee8e5 100644 --- a/README-ko_KR.md +++ b/README-ko_KR.md @@ -2,20 +2,26 @@ JavaScript 에 관한 객관식 문제를 [Instagram](https://www.instagram.com/theavocoder)에 매일 게시하고 있어요, 물론 여기에도 게시할 거예요! -초급부터 고급까지: JavaScript를 얼마나 잘 알고 있는지 테스트하거나, 지식을 조금 더 새롭게 하거나, 코딩 면접을 준비하세요! :muscle: :rocket: 이 기록을 매주 새로운 질문으로 업데이트해요. 마지막 업데이트: 7월 14일 +초급부터 고급까지: JavaScript를 얼마나 잘 알고 있는지 테스트하거나, 지식을 조금 더 새롭게 하거나, 코딩 면접을 준비하세요! :muscle: :rocket: 이 기록을 매주 새로운 질문으로 업데이트해요. 마지막 업데이트: 7월 26일 정답은 질문 아래 접힌 부분에 있어요, 그냥 클릭하면 펼칠 수 있어요. 행운을 빌어요 :heart: +질문이 더 추가될 때마다 이메일을 받고 싶나요?
+✨✉이메일 업데이트 구독 ✉✨ + +사용 가능한 언어 목록: * [English](./README.md) * [العربية](./README_AR.md) * [اللغة العامية - Egyptian Arabic](./README_ar-EG.md) -* [Bosanski](./README-bs_BS.md) -* [Deutsch](./README-de_DE.md) +* [Bosanski](./README-bs_BS.md) +* [Deutsch](./README-de_DE.md) * [Español](./README-ES.md) -* [日本語](./README-ja_JA.md) -* [Português Brasil](./README_pt_BR.md) -* [Русский](./README_ru-RU.md) -* [Українська мова](./README-ua_UA.md) +* [Français](./README_fr-FR.md) +* [日本語](./README-ja_JA.md) +* [한국어](./README-ko_KR.md) +* [Português Brasil](./README_pt_BR.md) +* [Русский](./README_ru-RU.md) +* [Українська мова](./README-ua_UA.md) * [Tiếng Việt](./README-vi.md) * [中文版本](./README-zh_CN.md) * [Türkçe](./README-tr_TR.md) @@ -604,7 +610,7 @@ getAge(21); #### 정답: C -스프레드 연산자 (`...args`.)는 인수를 가진 배열을 리턴해요. 배열은 객체이므로, `typeof args`는 `"object"`를 리턴해요. +rest 파라미터 (`...args`.)는 모든 남아있는 인수들을 하나의 배열로 "집합" 해요. 배열은 객체이므로, `typeof args`는 `"object"`를 리턴해요.

@@ -2170,7 +2176,7 @@ console.log(name.padStart(2)) --- -###### 70. 무엇이 출력 될까요? +###### 70. 무엇이 출력 될까요? ```javascript console.log("🥑" + "💻"); @@ -2461,3 +2467,265 @@ console.log(addFunction(5 * 2));

+ +--- + +###### 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: "🍫"}` + +
Answer +

+ +#### Answer: 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]` + +
Answer +

+ +#### Answer: 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` + +
Answer +

+ +#### Answer: 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 `"😎"` + +
Answer +

+ +#### Answer: 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"` + +
Answer +

+ +#### Answer: 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` + +
Answer +

+ +#### 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. + +

+
+ +--- + +###### 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. + +
Answer +

+ +#### Answer: 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` + +
Answer +

+ +#### Answer: A + +With `!!name`, we determine whether the value of `name` is truthy or falsey. 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`. + +

+
From cf933ae958cafa0fe599dd0bbf60957ec30d5f02 Mon Sep 17 00:00:00 2001 From: Jacob Herper Date: Thu, 1 Aug 2019 18:00:42 +0100 Subject: [PATCH 271/915] Questions 70 - 75 translated to German --- README-de_DE.md | 194 ++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 194 insertions(+) diff --git a/README-de_DE.md b/README-de_DE.md index 1eb56566..0b3ef6e1 100644 --- a/README-de_DE.md +++ b/README-de_DE.md @@ -2170,3 +2170,197 @@ Falls der Wert, der an `padStart` übergeben wurde kleiner ist, als die Länge d

+ +--- + +###### 70. Was ist der Output? + +```javascript +console.log("🥑" + "💻"); +``` + +- A: `"🥑💻"` +- B: `257548` +- C: Ein String, der den Emoji Code beinhaltet +- D: Error + +
Antwort +

+ +#### Antwort: A + +Mit dem `+` Operator können Strings zusammengesetzt werden. In diesem Fall werden die Strings `"🥑"` und `"💻"` zusammengesetzt, was `"🥑💻"` ergibt. + +

+
+ +--- + +###### 71. Wie können wir die Werte loggen, die nach dem `console.log` auskommentiert wurden? + +```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` und `game.next().value` +- B: `game.next.value("Yes")` und `game.next.value()` +- C: `game.next().value` und `game.next("Yes").value` +- D: `game.next.value()` und `game.next.value("Yes")` + +
Antwort +

+ +#### Antwort: C + +Eine Generator Funktion pausiert die Ausführung, wenn das `yield` Keyword vorliegt. Zuerst müssen wir den String "Do you love JavaScript?" abwarten, was mit `game.next().value` möglich ist. + +Jede Zeile wird ausgeführt, bis das erste `yield` Keyword auftritt. Da auf der ersten Zeile ein `yield` in der Funktion vorliegt wird die Ausführung damit angehalten. Das bedeutet, dass die Variable `Answer` _noch nicht definiert_ wurde. + +Wenn wir `game.next("Yes").value` aufrufen wird das vorhergehende `yield` durch den Wert des Parameters ersetzt, der an `next()` übergeben wird - `"Yes"` in diesem Fall. Der Wert der Variable `Answer` ist jetzt gleich `"Yes"`. Das if-Statement gibt `false` aus und `JavaScript loves you back ❤️` wird geloggt. + +

+
+ +--- + +###### 72. Was ist der Output? + +```javascript +console.log(String.raw`Hello\nworld`); +``` + +- A: `Hello world!` +- B: `Hello`
     `world` +- C: `Hello\nworld` +- D: `Hello\n`
     `world` + +
Antwort +

+ +#### Antwort: C + +`String.raw` gibt einen String aus, in dem die Escapes (`\n`, `\v`, `\t` etc.) ignoriert werden! Backslashes sind problematisch, weil man mit sowas in der Art rechnen muss: + +`` const path = `C:\Documents\Projects\table.html` `` + +Das würde dann wiefolgt gerendert werden: + +`"C:DocumentsProjects able.html"` + +Mit `String.raw` werden diese ignoriert und das Ergebnis ist: + +`C:\Documents\Projects\table.html` + +In unserem Fall ist das Ergebnis `Hello\nworld`, was geloggt wird. + +

+
+ +--- + +###### 73. Was ist der 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` + +
Antwort +

+ +#### Antwort: C + +Eine `async` Funktion gibt immer ein Promise zurück. Mit `await` wird das Ergebnis des Promises abgewartet und ein ausstehendes Promise wird ausgegeben, wenn wir `getData()` aufrufen um `data` gleich zu setzen. + +Wenn wir auf den finalen Wert `"I made it"` zugreifen wollen, nutzen wir die `.then()` Methode an `data`: + +`data.then(res => console.log(res))` + +Das hätte `"I made it!"` ausgegeben. + +

+
+ +--- + +###### 74. Was ist der 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` + +
Antwort +

+ +#### Antwort: B + +Die `.push()` Methode gibt die _Länge_ des Arrays aus! Das Array beinhaltete zuerst ein einziges Element (`"banana"`) und hatte eine Länge von `1`. Nachdem wir `"apple"` hinzugefügt haben beinhaltet das Array zwei Elemente und hat eine Länge von `2`. Das wird letztlich von der `addToList` Funktion ausgegeben. + +Die `push` Methode verändert das ursprüngliche Array. Wenn wir das _Array_ der Funktion anstelle der _Länge des Arrays_ ausgeben möchten, hätten wir `list` ausgeben müssen. + +

+
+ +--- + +###### 75. Was ist der 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` + +
Antwort +

+ +#### Antwort: B + +`Object.freeze` macht es unmöglich das Objekt zu verändern (hinzufügen, entfernen, verändern), es sei denn der Wert ist ein weiteres Objekt. + +Wenn wir die Variable `shape` erstellen und gleich dem eingefrorenen Objekt `box` setzen, ist `shape` ebenso eingefroren. Man kann mit `Object.isFrozen` prüfen, ob ein Objekt eingefroren ist. +In unserem Fall gibt `Object.isFrozen(shape)` `true` zurück, da die Variable `shape` eine Referenz zu einem eingefrorenen Objekt ist. + +Da `shape` eingefroren ist und der Wert von `x` kein Objekt ist, können wir den Wert von `x` nicht verändern. `x` ist immernoch gleich `10` und `{ x: 10, y: 20 }` wird geloggt. + +

+
From 90729d182b26fd11b0b885b82b218d0349da84f0 Mon Sep 17 00:00:00 2001 From: Jacob Herper Date: Fri, 2 Aug 2019 10:22:46 +0100 Subject: [PATCH 272/915] Questions 76 - 89 translated to German --- README-de_DE.md | 363 ++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 363 insertions(+) diff --git a/README-de_DE.md b/README-de_DE.md index 0b3ef6e1..ccb7fe7a 100644 --- a/README-de_DE.md +++ b/README-de_DE.md @@ -13,6 +13,7 @@ Die Antworten sind unterhalb der Fragen versteckt. Du kannst einfach darauf klic * [Bosanski](./README-bs_BS.md) * [Deutsch](./README-de_DE.md) * [Español](./README-ES.md) +* [Français](./README_fr-FR.md) * [日本語](./README-ja_JA.md) * [한국어](./README-ko_KR.md) * [Português Brasil](./README_pt_BR.md) @@ -2364,3 +2365,365 @@ Da `shape` eingefroren ist und der Wert von `x` kein Objekt ist, können wir den

+ +--- + +###### 76. Was ist der Output? + +```javascript +const { name: myName } = { name: "Lydia" }; + +console.log(name); +``` + +- A: `"Lydia"` +- B: `"myName"` +- C: `undefined` +- D: `ReferenceError` + +
Antwort +

+ +#### Antwort: D + +Wenn wir die Property `name` aus dem Objekt auf der rechten Seite destructuren, weisen wir den Wert einer neuen Variable `myName` zu. + +Mit `{ name: myName }` sagen wir JavaScript, dass wir eine neue Variable mit dem Namen `myName` erstellen möchten und den Wert von `name` zuweisen. + +Da `name` nicht definiert ist, wird ein ReferenceError ausgeworfen. + +

+
+ +--- + +###### 77. Is this a pure function? + +```javascript +function sum(a, b) { + return a + b; +} +``` + +- A: Ja +- B: Nein + +
Antwort +

+ +#### Antwort: A + +Eine pure Funktion ist eine Funktion, die _immer_ das gleiche Ergebnis zurück gibt, wenn die gleichen Argumente eingegeben werden. + +Die `sum` Funktion gibt daher immer das gleiche Ergebnis aus. Wenn wir `1` und `2` eingeben wird _immer_ `3` ausgegeben. Wenn wir `5` und `10` eingeben wird _immer_ `15` ausgegeben usw. Das ist die Definition einer puren Funktion. + +

+
+ +--- + +###### 78. Was ist der 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` + +
Antwort +

+ +#### Antwort: C + +Die `add` Funktion ist _memoized_. Mit Memoization können wir Ergebnisse einer Funktion cachen, um die Performance zu beschleunigen. In diesem Fall erstellen wir ein `cache` Objekt, welches die zuvor ausgegebenen Werte speichert. + +Wenn wir die `addFunction` Funktion erneut mit den gleichen Argumenten aufrufen wird zuerst geprüft, ob der Wert bereits im Cache vorhanden sind. Ist das der Fall, so wird der Cache diesen Wert ausgeben und damit Ausführzeit sparen. Wenn der Wert nicht gecached ist wird der neue Wert berechnet und danach im Cache gespeichert. + +Wir rufen die `addFunction` Funktion drei mal mit dem gleichen Wert auf: bei der ersten Ausführung. ist der Wert der Funktion `10` nicht im Cache. Die Kondition des if-Statements `num in cache` gibt `false` aus und der else Block wird ausgeführt: `Calculated! 20` wird geloggt und der Wert des Ergebnisses wird dem Cache Objekt hinzugefügt. `cache` sieht jetzt wiefolgt aus: `{ 10: 20 }`. + +Bei der zweiten Ausführung beinhaltet das `cache` Objekt den Wert `10`. Die Kondition des if-Statements `num in cache` gibt `true` aus und `'From cache! 20'` wird geloggt. + +Beim dritten Mal geben wir `5 * 2` als Argument in die Funktion ein, was `10` ergibt. Das `cache` Objekt beinhaltet den Wert `10` und das if-Statement `num in cache` gibt wieder `true` aus und `'From cache! 20'` wird geloggt. + +

+
+ +--- + +###### 79. Was ist der 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` und `"☕"` ` "💻"` `"🍷"` `"🍫"` +- B: `"☕"` ` "💻"` `"🍷"` `"🍫"` und `"☕"` ` "💻"` `"🍷"` `"🍫"` +- C: `"☕"` ` "💻"` `"🍷"` `"🍫"` und `0` `1` `2` `3` +- D: `0` `1` `2` `3` und `{0: "☕", 1: "💻", 2: "🍷", 3: "🍫"}` + +
Antwort +

+ +#### Antwort: A + +Mit einer _for-in_ Schleife können wir über **zählbare** Properties iterieren. In einem Array sind die zählbaren Properties die "Keys" des Array Elements, sprich deren Indexe. Ein Array könnte man also wiefolgt sehen: + +`{0: "☕", 1: "💻", 2: "🍷", 3: "🍫"}` + +Daher werden die zählbaren Properties `0` `1` `2` `3` geloggt. + +Mit einer _for-of_ Schleife können wir über **wiederholbare** Elemente iterieren. Ein Array ist wiederholbar. Wenn wir also über das Array iterieren, ist die Variable "item" gleich dem Element, welches momentan iteriert wird: `"☕"` ` "💻"` `"🍷"` `"🍫"` wird geloggt. + +

+
+ +--- + +###### 80. Was ist der 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]` + +
Antwort +

+ +#### Antwort: C + +Array Elemente können jeden Wert halten: Nummern, Strings, Objekte, andere Arrays, null, Booleans, undefined und andere Expressions wie Funktionen, Berechnungen oder ein Datum. + +Das Element ist gleich dem ausgegebenen Wert. `1 + 2` ergibt `3`, `1 * 2` ergibt `2`, und `1 / 2` ergibt `0.5`. + +

+
+ +--- + +###### 81. Was ist der 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` + +
Antwort +

+ +#### Antwort: B + +Standardmäßig haben Argumente den Wert `undefined`, es sei denn der Funktion wurde ein Wert zugewiesen. In diesem Fall haben wir dem `name` Argument keinen Wert zugewiesen, weshalb `name` `undefined` ist. + +In ES6 können wir diesen Standardwert `undefined` mit Standard Parametern überschreiben, zum Beispiel: + +`function sayHi(name = "Lydia") { ... }` + +In diesem Fall, falls wir kein Argument oder `undefined` eingeben ist `name` immer `Lydia`. + +

+
+ +--- + +###### 82. Was ist der 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: `"🥑"` und `"😍"` +- B: `"🥑"` und `"😎"` +- C: `"😍"` und `"😎"` +- D: `"😎"` und `"😎"` + +
Antwort +

+ +#### Antwort: B + +Der Wert des `this` Keywords hängt davon ab, wo es verwendet wird. In einer **Methode**, wie `getStatus` bezieht sich das `this` Keyword auf das _Objekt, zu dem die Methode gehört_. Die Methode gehört zum `data` Objekt, sodass `this` sich auf das `data` Objekt bezieht. Wenn wir `this.status` loggen wird die `status` Property des `data` Objekts geloggt, was `"🥑"` ist. + +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. + + +

+
+ +--- + +###### 83. Was ist der 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"` + +
Antwort +

+ +#### Antwort: A + +Wir setzen die Variable `city` gleich dem Wert der Property `city` am `person` Objekt. Da am `person` Objekt keine Property namens `city` existiert wird der Wert gleich `undefined` gesetzt. + +Da wir _nicht_ das `person` Objekt selbst referenzieren, sondern einfach die Variable `city` gleich dem aktuellen Wert von `city` am `person` Objekt setzen bleibt dieses `undefined`. + +Dann setzen wir `city` gleich dem String `"Amsterdam"`. Das verändert aber nicht das `person` Objekt, da es keine Referenz dazu am Objekt gibt. + +Wenn wir `person` loggen bekommen wir daher das unveränderte Objekt angezeigt. + +

+
+ +--- + +###### 84. Was ist der 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` + +
Antwort +

+ +#### Antwort: C + +Variablen mit dem `const` und `let` Keyword sind _block-scoped_. Ein Block ist alles zwischen geschweiften Klammern (`{ }`), in diesem Fall die geschweiften Klammern des if/else Statements. Es ist nicht möglich eine solche Variable außerhalb des Blocks in dem sie erklärt wurde aufzurufen, daher wird ein ReferenceError ausgegeben. + +

+
+ +--- + +###### 85. Welche Information wird geloggt? + +```javascript +fetch('https://www.website.com/api/user/1') + .then(res => res.json()) + .then(res => console.log(res)) +``` + +- A: Das Ergebnis der `fetch` Methode. +- B: Das Ergebnis des zweiten Aufrufs der `fetch` Methode. +- C: Das Ergebnis des Callbacks im vorhergehenden `.then()`. +- D: Immer `undefined`. + +
Antwort +

+ +#### Antwort: C + +Der Wert von `res` im zweiten `.then` ist gleich dem ausgegebenen Wert des vorhergehenden `.then`. Man kann soviele `.then`s aneinander reihen, wie man möchte und der Wert wird immer an den nächsten Handler übergeben. + +

+
+ +--- + +###### 86. Wie können wir `hasName` gleich `true` setzen, vorausgesetzt wir können `true` nicht als Argument übergeben? + +```javascript +function getName(name) { + const hasName = // +} +``` + +- A: `!!name` +- B: `name` +- C: `new Boolean(name)` +- D: `name.length` + +
Antwort +

+ +#### Antwort: A + +Mit `!!name` können wir feststellen, ob `name` truthy oder falsey ist. Ist `name` truthy, so würde `!name` `false` ausgeben. `!false` (das Gleiche wie `!!name`) ergibt `true`. + +Wenn wir `hasName` gleich `name` setzen, so beinhaltet `hasName` den Wert von `name`, nicht den Boolean Wert `true`. + +`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. +

+
From ad7e650c14f3073382815ce1c769d129010ab090 Mon Sep 17 00:00:00 2001 From: sweetmilkys Date: Sat, 3 Aug 2019 14:28:42 +0900 Subject: [PATCH 273/915] Add translate the questions 79-86 to Korean. --- README-ko_KR.md | 149 ++++++++++++++++++++++++------------------------ 1 file changed, 74 insertions(+), 75 deletions(-) diff --git a/README-ko_KR.md b/README-ko_KR.md index a34ee8e5..ba4d1ca4 100644 --- a/README-ko_KR.md +++ b/README-ko_KR.md @@ -1327,7 +1327,7 @@ console.log(gen.next().value); - A: `[0, 10], [10, 20]` - B: `20, 20` - C: `10, 20` -- D: `0, 10 and 10, 20` +- D: `0, 10` 그리고 `10, 20`
정답

@@ -1503,7 +1503,7 @@ const num = parseInt("7*6", 10); [1, 2, 3].map(num => { if (typeof num === "number") return; return num * 2; -}); + }); ``` - A: `[]` @@ -2011,10 +2011,10 @@ ES6에서는, 기본값으로 파라미터를 초기화할 수 있어요. 함수 [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` +- A: `1` `2` 그리고 `3` `3` 그리고 `6` `4` +- B: `1` `2` 그리고 `2` `3` 그리고 `3` `4` +- C: `1` `undefined` 그리고 `2` `undefined` 그리고 `3` `undefined` 그리고 `4` `undefined` +- D: `1` `2` 그리고 `undefined` `3` 그리고 `undefined` `4`

정답

@@ -2470,48 +2470,48 @@ console.log(addFunction(5 * 2)); --- -###### 79. What is the output? +###### 79. 무엇이 출력 될까요? ```javascript 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: "🍫"}` +- A: `0` `1` `2` `3` 그리고 `"☕"` ` "💻"` `"🍷"` `"🍫"` +- B: `"☕"` ` "💻"` `"🍷"` `"🍫"` 그리고 `"☕"` ` "💻"` `"🍷"` `"🍫"` +- C: `"☕"` ` "💻"` `"🍷"` `"🍫"` 그리고 `0` `1` `2` `3` +- D: `0` `1` `2` `3` 그리고 `{0: "☕", 1: "💻", 2: "🍷", 3: "🍫"}` -

Answer +
정답

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

--- -###### 80. What is the output? +###### 80. 무엇이 출력 될까요? ```javascript const list = [1 + 2, 1 * 2, 1 / 2] -console.log(list) +console.log(list); ``` - A: `["1 + 2", "1 * 2", "1 / 2"]` @@ -2519,28 +2519,28 @@ console.log(list) - C: `[3, 2, 0.5]` - D: `[1, 1, 1]` -
Answer +
정답

#### Answer: 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. +배열 요소들은 모든 값을 포함 할 수 있어요. Numbers, strings, objects, 다른 arrays, null, boolean 값, undefined, 그리고 자료형, 함수, 연산자와 같은 표현식들 -The element will be equal to the returned value. `1 + 2` returns `3`, `1 * 2` returns `2`, and `1 / 2` returns `0.5`. +요소는 리턴된 값과 같아질 거예요. `1 + 2`는 `3`을 리턴하고, `1 * 2`는 `2`를 리턴하고, `1 / 2` 는 `0.5`을 리턴해요.

--- -###### 81. What is the output? +###### 81. 무엇이 출력 될까요? ```javascript function sayHi(name) { return `Hi there, ${name}` } -console.log(sayHi()) +console.log(sayHi()); ``` - A: `Hi there, ` @@ -2548,76 +2548,75 @@ console.log(sayHi()) - C: `Hi there, null` - D: `ReferenceError` -
Answer +
정답

#### Answer: 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. +기본값으로, 함수에 값이 전달되지 않으면, 인수는 `undefined` 값을 가져요. 이 경우, `name` 인수를 위한 값을 전달하지 않았어요. `name`은 `undefined`로 출력돼요. -In ES6, we can overwrite this default `undefined` value with default parameters. For example: +ES6에서, 기본값 `undefined` 값을 기본값 파라미터로 덮어쓸 수 있어요. 예를 들면: `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` +이 경우, 값을 전달하지 않거나 `undefined`를 전달하면, `name`은 항상 문자열 `Lydia`가 될 거예요.

--- -###### 82. What is the output? +###### 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 `"😍"` -- B: `"🥑"` and `"😎"` -- C: `"😍"` and `"😎"` -- D: `"😎"` and `"😎"` +- A: `"🥑"` 그리고 `"😍"` +- B: `"🥑"` 그리고 `"😎"` +- C: `"😍"` 그리고 `"😎"` +- D: `"😎"` 그리고 `"😎"` -
Answer +
정답

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

--- -###### 83. What is the output? +###### 83. 무엇이 출력 될까요? ```javascript const person = { 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 }` @@ -2625,38 +2624,38 @@ console.log(person) - C: `{ name: "Lydia", age: 21, city: undefined }` - D: `"Amsterdam"` -
Answer +
정답

#### Answer: 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`. +`city` 변수를 `person` rorcpdml `city`라고 불리는 속성 값으로 설정 했어요. 이 객체에서는 `city`라고 불리는 속성이 없기 때문에, `city`는 `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. +`person`객체 자체를 참조 _하지않는_ 다는 걸 참고해요! 변수 `city`는 `person` 객체의 `city` 현재 속성 값으로 설정 했을 뿐이죠. -Then, we set `city` equal to the string `"Amsterdam"`. This doesn't change the person object: there is no reference to that object. +그러므로, 우리는 `city`를 문자열 `"Amsterdam"`로 설정 했어요. 이건 person 객체를 바꾸지 않아요: 여기서 객체를 참조하는 건 없어요. -When logging the `person` object, the unmodified object gets returned. +`person`객체를 출력할 때, 수정되지 않은 객체가 리턴 받아요.

--- -###### 84. What is the output? +###### 84. 무엇이 출력 될까요? ```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."` @@ -2664,44 +2663,44 @@ console.log(checkAge(21)) - C: `ReferenceError` - D: `undefined` -
Answer +
정답

#### 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. +`const`와 `let` 키워드를 사용한 변수는 _블록-스코프_ 예요. 블록은 중괄호 (`{ }`) 사이에 있는 것이죠. 이 경우, if/else 표현식의 중괄호를 의미해요. 블록 안에 선언된 건 블록 밖의 변수들을 참조하지 못해, ReferenceError를 던져요.

--- -###### 85. What kind of information would get logged? +###### 85. 어떤 종류의 정보가 출력될까요? ```javascript fetch('https://www.website.com/api/user/1') .then(res => res.json()) - .then(res => console.log(res)) + .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. +- A: `fetch` 메소드의 결과 +- B: `fetch` 메소드의 두번째 호출 결과 +- C: 이전 `.then()`에서 callback된 결과 +- D: 항상 undefined -
Answer +
정답

#### Answer: 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. +두번째 `.then`에서의 `res`의 값은 이전`.then`에서 리턴된 값이에요. 이것 처럼 `.then`을 계속해서 연결할 수 있고, 값은 계속해서 다음 핸들러로 전달 돼요.

--- -###### 86. Which option is a way to set `hasName` equal to `true`, provided you cannot pass `true` as an argument? +###### 86. `true`를 인수로 전달 할 수 없도록 주어졌을 때, `hasName`을 `true`로 세팅할 수 있는 방법은 어느 것 일까요? ```javascript function getName(name) { @@ -2714,18 +2713,18 @@ function getName(name) { - C: `new Boolean(name)` - D: `name.length` -
Answer +
정답

#### Answer: A -With `!!name`, we determine whether the value of `name` is truthy or falsey. If name is truthy, which we want to test for, `!name` returns `false`. `!false` (which is what `!!name` practically is) returns `true`. +`!!name`에서, 우리는 `name`의 값이 참 같은지 거짓 같은지 결정해요. 만약 테스트 하려는 name이 참 같다면, `!name`은 `false`를 리턴해요. `!false` (실제로는 `!!name`)는 `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`. +`hasName`을 `name`으로 설정하면, `hasName`은 불린 값 `true`가 아니라, `getName` 함수에 전달된 값으로 설정해요. -`new Boolean(true)` returns an object wrapper, not the boolean value itself. +`new Boolean(true)`은 불린 값 자체가 아닌, 감싼 객체를 리턴해요. -`name.length` returns the length of the passed argument, not whether it's `true`. +`name.length`은 그것의 `true`의 여부가 아닌, 전달된 인수의 길이를 리턴해요.

From 2ffac5e1b78b0e01d8c7cc530b8281f03970e2af Mon Sep 17 00:00:00 2001 From: Lydia Hallie Date: Mon, 5 Aug 2019 22:26:11 +0200 Subject: [PATCH 274/915] Add questions 87-95 --- README.md | 288 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 288 insertions(+) diff --git a/README.md b/README.md index 05ef5b49..8dfdb20e 100644 --- a/README.md +++ b/README.md @@ -2728,3 +2728,291 @@ 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]) +``` + +- A: `"""` +- B: `"I"` +- C: `SyntaxError` +- D: `undefined` + +
Answer +

+ +#### 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. + +Note that this method is not supported in IE7 and below. In that case, use `.charAt()` + +

+
+ +--- + +###### 88. What's the output? + +```javascript +function sum(num1, num2 = num1) { + console.log(num1 + num2) +} + +sum(10) +``` + +- A: `NaN` +- B: `20` +- C: `ReferenceError` +- D: `undefined` + +
Answer +

+ +#### Answer: 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, amd 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. What's the 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` + +
Answer +

+ +#### 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"`. + +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. What's the 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"` + +
Answer +

+ +#### Answer: B + +Classes are syntactical sugar for function constructors. The equivalent of the `Person` class as a function constructor would be: + +```javascript +function Person() { + this.name = name +} +``` + +Which results in the same value. A class is a function under the hood, the `typeof` keyword returns `"function"` for functions. `typeof Person` returns `"function"`. + +

+
+ +--- + +###### 91. What's the 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` + +
Answer +

+ +#### Answer: 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. What's the output? + +```javascript +function giveLydiaPizza() { + return "Here is pizza!" +} + +function giveLydiaChocolate() { + return "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` + +
Answer +

+ +#### Answer: 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. What's the output? + +```javascript +function giveLydiaPizza() { + return "Here is pizza!" +} + +function giveLydiaChocolate() { + return "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` + +
Answer +

+ +#### Answer: 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`. + +

+
+ +--- + +###### 94. What's the output? + +```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` + +
Answer +

+ +#### Answer: 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. + +

+
+ +--- + +###### 95. What's the 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` + +
Answer +

+ +#### Answer: 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' ]` +

+
\ No newline at end of file From 4c243e98ff3443f685ebffd5dac6d1ac9e2456d0 Mon Sep 17 00:00:00 2001 From: Lydia Hallie Date: Mon, 5 Aug 2019 22:27:48 +0200 Subject: [PATCH 275/915] Separate languages in folders --- README.md | 30 +- README_AR.md => ar-AR/README_AR.md | 0 README_ar-EG.md => ar-EG/README_ar-EG.md | 0 README-bs_BS.md => bs-BS/README-bs_BS.md | 0 README-de_DE.md => de-DE/README-de_DE.md | 0 en-EN/README.md | 3018 ++++++++++++++++++++++ README-ES.md => es-ES/README-ES.md | 0 README_fr-FR.md => fr-FR/README_fr-FR.md | 0 README-ja_JA.md => ja-JA/README-ja_JA.md | 0 README-ko_KR.md => ko-KR/README-ko_KR.md | 0 README_pt_BR.md => pt-BR/README_pt_BR.md | 0 README_ru-RU.md => ru-RU/README_ru-RU.md | 0 README-tr_TR.md => tr-TR/README-tr_TR.md | 0 README-ua_UA.md => ua-UA/README-ua_UA.md | 0 README-vi.md => vi-VI/README-vi.md | 0 README-zh_CN.md => zh-CN/README-zh_CN.md | 0 16 files changed, 3033 insertions(+), 15 deletions(-) rename README_AR.md => ar-AR/README_AR.md (100%) rename README_ar-EG.md => ar-EG/README_ar-EG.md (100%) rename README-bs_BS.md => bs-BS/README-bs_BS.md (100%) rename README-de_DE.md => de-DE/README-de_DE.md (100%) create mode 100644 en-EN/README.md rename README-ES.md => es-ES/README-ES.md (100%) rename README_fr-FR.md => fr-FR/README_fr-FR.md (100%) rename README-ja_JA.md => ja-JA/README-ja_JA.md (100%) rename README-ko_KR.md => ko-KR/README-ko_KR.md (100%) rename README_pt_BR.md => pt-BR/README_pt_BR.md (100%) rename README_ru-RU.md => ru-RU/README_ru-RU.md (100%) rename README-tr_TR.md => tr-TR/README-tr_TR.md (100%) rename README-ua_UA.md => ua-UA/README-ua_UA.md (100%) rename README-vi.md => vi-VI/README-vi.md (100%) rename README-zh_CN.md => zh-CN/README-zh_CN.md (100%) diff --git a/README.md b/README.md index 8dfdb20e..1966f65a 100644 --- a/README.md +++ b/README.md @@ -11,21 +11,21 @@ Want to get an email whenever I've added more questions?
List of available languages: -* [English](./README.md) -* [العربية](./README_AR.md) -* [اللغة العامية - Egyptian Arabic](./README_ar-EG.md) -* [Bosanski](./README-bs_BS.md) -* [Deutsch](./README-de_DE.md) -* [Español](./README-ES.md) -* [Français](./README_fr-FR.md) -* [日本語](./README-ja_JA.md) -* [한국어](./README-ko_KR.md) -* [Português Brasil](./README_pt_BR.md) -* [Русский](./README_ru-RU.md) -* [Українська мова](./README-ua_UA.md) -* [Tiếng Việt](./README-vi.md) -* [中文版本](./README-zh_CN.md) -* [Türkçe](./README-tr_TR.md) +* [English](./en-EN/README.md) +* [العربية](./ar-AR/README_AR.md) +* [اللغة العامية - Egyptian Arabic](./ar-EG/README_ar-EG.md) +* [Bosanski](./bs-BS/README-bs_BS.md) +* [Deutsch](./de-DE/README-de_DE.md) +* [Español](./es-ES/README-ES.md) +* [Français](./fr-FR/README_fr-FR.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_ru-RU.md) +* [Українська мова](./ua-UA/README-ua_UA.md) +* [Tiếng Việt](./vi-VI/README-vi.md) +* [中文版本](./zh-CN/README-zh_CN.md) +* [Türkçe](./tr-TR/README-tr_TR.md) --- diff --git a/README_AR.md b/ar-AR/README_AR.md similarity index 100% rename from README_AR.md rename to ar-AR/README_AR.md diff --git a/README_ar-EG.md b/ar-EG/README_ar-EG.md similarity index 100% rename from README_ar-EG.md rename to ar-EG/README_ar-EG.md diff --git a/README-bs_BS.md b/bs-BS/README-bs_BS.md similarity index 100% rename from README-bs_BS.md rename to bs-BS/README-bs_BS.md diff --git a/README-de_DE.md b/de-DE/README-de_DE.md similarity index 100% rename from README-de_DE.md rename to de-DE/README-de_DE.md diff --git a/en-EN/README.md b/en-EN/README.md new file mode 100644 index 00000000..e25b9ce6 --- /dev/null +++ b/en-EN/README.md @@ -0,0 +1,3018 @@ +# List of (Advanced) JavaScript Questions + +I post daily multiple choice JavaScript questions on my [Instagram](https://www.instagram.com/theavocoder), which I'll also post 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 weekly with new questions. Last update: July 26th + +The answers are in the collapsed sections below the questions, simply click on them to expand it. Good luck :heart: + +Want to get an email whenever I've added more questions?
+✨✉Subscribe to email updates✉✨ + + +List of available languages: +* [English](../en-EN/README.md) +* [العربية](../ar-AR/README_AR.md) +* [اللغة العامية - Egyptian Arabic](../ar-EG/README_ar-EG.md) +* [Bosanski](../bs-BS/README-bs_BS.md) +* [Deutsch](../de-DE/README-de_DE.md) +* [Español](../es-ES/README-ES.md) +* [Français](../fr-FR/README_fr-FR.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_ru-RU.md) +* [Українська мова](../ua-UA/README-ua_UA.md) +* [Tiếng Việt](../vi-VI/README-vi.md) +* [中文版本](../zh-CN/README-zh_CN.md) +* [Türkçe](../tr-TR/README-tr_TR.md) + + +--- + +###### 1. What's the output? + +```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` + +
Answer +

+ +#### Answer: D + +Within the function, we first declare the `name` variable with the `var` keyword. This means that the variable gets hoisted (memory space is set up during the creation phase) with the default value of `undefined`, until we actually get to the line where we define the variable. We haven't defined the variable yet on the line where we try to log the `name` variable, so it still holds the value of `undefined`. + +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`. + +

+
+ +--- + +###### 2. What's the 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` and `0 1 2` +- B: `0 1 2` and `3 3 3` +- C: `3 3 3` and `0 1 2` + +
Answer +

+ +#### Answer: C + +Because of the event queue in JavaScript, the `setTimeout` callback function is called _after_ the loop has been executed. Since the variable `i` in the first loop was declared using the `var` keyword, this value was global. During the loop, we incremented the value of `i` by `1` each time, using the unary operator `++`. By the time the `setTimeout` callback function was invoked, `i` was equal to `3` in the first example. + +In the second loop, the variable `i` was declared using the `let` keyword: variables declared with the `let` (and `const`) keyword are block-scoped (a block is anything between `{ }`). During each iteration, `i` will have a new value, and each value is scoped inside the loop. + +

+
+ +--- + +###### 3. What's the 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` and `62.83185307179586` +- B: `20` and `NaN` +- C: `20` and `63` +- D: `NaN` and `63` + +
Answer +

+ +#### Answer: B + +Note that the value of `diameter` is a regular function, whereas the value of `perimeter` is an arrow function. + +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 `undefined`. + +

+
+ +--- + +###### 4. What's the output? + +```javascript ++true; +!"Lydia"; +``` + +- A: `1` and `false` +- B: `false` and `NaN` +- C: `false` and `false` + +
Answer +

+ +#### Answer: A + +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`. + +

+
+ +--- + +###### 5. Which one is true? + +```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 + +
Answer +

+ +#### Answer: A + +In JavaScript, all object keys are strings (unless it's a Symbol). Even though we might not _type_ them as strings, they are always converted into strings under the hood. + +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. + +`mouse[bird.size]`: First it evaluates `bird.size`, which is `"small"`. `mouse["small"]` returns `true` + +However, with dot notation, this doesn't happen. `mouse` does not have a key called `bird`, which means that `mouse.bird` is `undefined`. Then, we ask for the `size` using dot notation: `mouse.bird.size`. Since `mouse.bird` is `undefined`, we're actually asking `undefined.size`. This isn't valid, and will throw an error similar to `Cannot read property "size" of undefined`. + +

+
+ +--- + + +###### 6. What's the 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` + +
Answer +

+ +#### Answer: A + +In JavaScript, all objects interact by _reference_ when setting them equal to each other. + +First, variable `c` holds a value to an object. Later, we assign `d` with the same reference that `c` has to the object. + + + +When you change one object, you change all of them. + +

+
+ +--- + +###### 7. What's the 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` + +
Answer +

+ +#### Answer: 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`. + +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.` + +

+
+ +--- + +###### 8. What's the 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` + +
Answer +

+ +#### 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. + +

+
+ +--- + +###### 9. What's the output? + +```javascript +let greeting; +greetign = {}; // Typo! +console.log(greetign); +``` + +- A: `{}` +- B: `ReferenceError: greetign is not defined` +- C: `undefined` + +
Answer +

+ +#### 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). + +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. + +

+
+ +--- + +###### 10. What happens when we do this? + +```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` + +
Answer +

+ +#### Answer: A + +This is possible in JavaScript, because functions are objects! (Everything besides primitive types are objects) + +A function is a special type of object. The code you write yourself isn't the actual function. The function is an object with properties. This property is invocable. + +

+
+ +--- + +###### 11. What's the 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` + +
Answer +

+ +#### Answer: A + +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() { + return `${this.firstName} ${this.lastName}`; +}; +``` + +would have made `member.getFullName()` work. Why is this beneficial? Say that we added this method to the constructor itself. Maybe not every `Person` instance needed this method. This would waste a lot of memory space, since they would still have that property, which takes of memory space for each instance. Instead, if we only add it to the prototype, we just have it at one spot in memory, yet they all have access to it! + +

+
+ +--- + +###### 12. What's the 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` + +
Answer +

+ +#### Answer: A + +For `sarah`, we didn't use the `new` keyword. When using `new`, it refers to the new empty object we create. However, if you don't add `new` it 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 + +
Answer +

+ +#### Answer: 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 + +
Answer +

+ +#### Answer: 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. What's the output? + +```javascript +function sum(a, b) { + return a + b; +} + +sum(1, "2"); +``` + +- A: `NaN` +- B: `TypeError` +- C: `"12"` +- D: `3` + +
Answer +

+ +#### Answer: 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. What's the 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` + +
Answer +

+ +#### Answer: 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. What's the 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` + +
Answer +

+ +#### Answer: 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. What's the 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` + +
Answer +

+ +#### Answer: 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. What's the output? + +```javascript +function getAge(...args) { + console.log(typeof args); +} + +getAge(21); +``` + +- A: `"number"` +- B: `"array"` +- C: `"object"` +- D: `"NaN"` + +
Answer +

+ +#### Answer: 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. What's the output? + +```javascript +function getAge() { + "use strict"; + age = 21; + console.log(age); +} + +getAge(); +``` + +- A: `21` +- B: `undefined` +- C: `ReferenceError` +- D: `TypeError` + +
Answer +

+ +#### Answer: 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 value of `sum`? + +```javascript +const sum = eval("10*10+5"); +``` + +- A: `105` +- B: `"105"` +- C: `TypeError` +- D: `"10*10+5"` + +
Answer +

+ +#### 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`. + +

+
+ +--- + +###### 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. + +
Answer +

+ +#### Answer: 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. What's the output? + +```javascript +var num = 8; +var num = 10; + +console.log(num); +``` + +- A: `8` +- B: `10` +- C: `SyntaxError` +- D: `ReferenceError` + +
Answer +

+ +#### Answer: 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. What's the 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` + +
Answer +

+ +#### Answer: 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. What's the 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` + +
Answer +

+ +#### Answer: 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 + +
Answer +

+ +#### Answer: A + +The base execution context is the global execution context: it's what's accessible everywhere in your code. + +

+
+ +--- + +###### 27. What's the 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` + +
Answer +

+ +#### Answer: C + +The `continue` statement skips an iteration if a certain condition returns `true`. + +

+
+ +--- + +###### 28. What's the 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` + +
Answer +

+ +#### 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! + +

+
+ +--- + +###### 29. What's the 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` + +
Answer +

+ +#### Answer: 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. What's the 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` + +
Answer +

+ +#### Answer: 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. + +
Answer +

+ +#### Answer: 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` + +
Answer +

+ +#### 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. + +

+
+ +--- + +###### 33. What's the output? + +```javascript +const person = { name: "Lydia" }; + +function sayHi(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` + +
Answer +

+ +#### Answer: 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. What's the output? + +```javascript +function sayHi() { + return (() => 0)(); +} + +console.log(typeof sayHi()); +``` + +- A: `"object"` +- B: `"number"` +- C: `"function"` +- D: `"undefined"` + +
Answer +

+ +#### Answer: B + +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`, and `symbol`. `"function"` is not a type, since functions are objects, it's of type `"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 + +
Answer +

+ +#### Answer: A + +There are only six falsy values: + +- `undefined` +- `null` +- `NaN` +- `0` +- `''` (empty string) +- `false` + +Function constructors, like `new Number` and `new Boolean` are truthy. + +

+
+ +--- + +###### 36. What's the output? + +```javascript +console.log(typeof typeof 1); +``` + +- A: `"number"` +- B: `"string"` +- C: `"object"` +- D: `"undefined"` + +
Answer +

+ +#### Answer: B + +`typeof 1` returns `"number"`. +`typeof "number"` returns `"string"` + +

+
+ +--- + +###### 37. What's the 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` + +
Answer +

+ +#### Answer: 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, 7 x empty, 11]` + +depending on where you run it (it's different for every browser, node, etc.) + +

+
+ +--- + +###### 38. What's the 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` + +
Answer +

+ +#### Answer: 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 + +
Answer +

+ +#### Answer: 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 object 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. What's the 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]` + +
Answer +

+ +#### Answer: 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. What's the output? + +```javascript +!!null; +!!""; +!!1; +``` + +- A: `false` `true` `false` +- B: `false` `false` `true` +- C: `false` `true` `true` +- D: `true` `true` `false` + +
Answer +

+ +#### Answer: 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` + +
Answer +

+ +#### Answer: 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"]]` + +
Answer +

+ +#### Answer: A + +A string is an iterable. The spread operator maps every character of an iterable to one element. + +

+
+ +--- + +###### 44. What's the 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` + +
Answer +

+ +#### Answer: 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"` + +
Answer +

+ +#### Answer: 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. What's the output? + +```javascript +let person = { name: "Lydia" }; +const members = [person]; +person = null; + +console.log(members); +``` + +- A: `null` +- B: `[null]` +- C: `[{}]` +- D: `[{ name: "Lydia" }]` + +
Answer +

+ +#### Answer: 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. What's the 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]` + +
Answer +

+ +#### Answer: 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. What's the output? + +```javascript +console.log(3 + 4 + "5"); +``` + +- A: `"345"` +- B: `"75"` +- C: `12` +- D: `"12"` + +
Answer +

+ +#### Answer: 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` + +
Answer +

+ +#### 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. + +`*` is not a valid number. It only parses `"7"` into the decimal `7`. `num` now holds the value of `7`. + +

+
+ +--- + +###### 50. What's the 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 ]` + +
Answer +

+ +#### Answer: 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. What's the 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"` + +
Answer +

+ +#### Answer: 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. What's the 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!` + +
Answer +

+ +#### Answer: 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. What's the 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` + +
Answer +

+ +#### 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"`. + +

+
+ +--- + +###### 54. What's the 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"` + +
Answer +

+ +#### Answer: 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 (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. What's the 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` + +
Answer +

+ +#### Answer: 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. What's the 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}` + +
Answer +

+ +#### Answer: 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. What's the 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` + +
Answer +

+ +#### Answer: 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. What's the 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` + +
Answer +

+ +#### 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 `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. What's the 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]` + +
Answer +

+ +#### Answer: 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. What's the 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 }` + +
Answer +

+ +#### Answer: 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. What's the 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"]` + +
Answer +

+ +#### Answer: 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. What's the 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}"` + +
Answer +

+ +#### Answer: 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. What's the 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` + +
Answer +

+ +#### 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. + +`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. What's the 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` + +
Answer +

+ +#### Answer: 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. What's the 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` + +
Answer +

+ +#### Answer: 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 + +
Answer +

+ +#### Answer: 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. What's the 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` + +
Answer +

+ +#### 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_. + +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. What's the 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` + +
Answer +

+ +#### Answer: 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. What's the 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"`, + +
Answer +

+ +#### Answer: 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. What's the output? + +```javascript +console.log("🥑" + "💻"); +``` + +- A: `"🥑💻"` +- B: `257548` +- C: A string containing their code points +- D: Error + +
Answer +

+ +#### Answer: 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 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")` + +
Answer +

+ +#### Answer: 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. What's the output? + +```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` 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. What's the 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` + +
Answer +

+ +#### Answer: 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. What's the 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` + +
Answer +

+ +#### Answer: 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. What's the 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` + +
Answer +

+ +#### Answer: 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)` returns 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. What's the output? + +```javascript +const { name: myName } = { name: "Lydia" }; + +console.log(name); +``` + +- A: `"Lydia"` +- B: `"myName"` +- C: `undefined` +- D: `ReferenceError` + +
Answer +

+ +#### 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, a ReferenceError gets thrown. + +

+
+ +--- + +###### 77. Is this a pure function? + +```javascript +function sum(a, b) { + return a + b; +} +``` + +- A: Yes +- B: No + +
Answer +

+ +#### Answer: 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` + +
Answer +

+ +#### Answer: 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: "🍫"}` + +
Answer +

+ +#### Answer: 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]` + +
Answer +

+ +#### Answer: 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` + +
Answer +

+ +#### Answer: 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 `"😎"` + +
Answer +

+ +#### Answer: 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"` + +
Answer +

+ +#### Answer: 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` + +
Answer +

+ +#### 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. + +

+
+ +--- + +###### 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. + +
Answer +

+ +#### Answer: 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` + +
Answer +

+ +#### Answer: A + +With `!!name`, we determine whether the value of `name` is truthy or falsey. 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. What's the output? + +```javascript +console.log("I want pizza"[0]) +``` + +- A: `"""` +- B: `"I"` +- C: `SyntaxError` +- D: `undefined` + +
Answer +

+ +#### 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. + +Note that this method is not supported in IE7 and below. In that case, use `.charAt()` + +

+
+ +--- + +###### 88. What's the output? + +```javascript +function sum(num1, num2 = num1) { + console.log(num1 + num2) +} + +sum(10) +``` + +- A: `NaN` +- B: `20` +- C: `ReferenceError` +- D: `undefined` + +
Answer +

+ +#### Answer: 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, amd 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. What's the 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` + +
Answer +

+ +#### 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"`. + +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. What's the 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"` + +
Answer +

+ +#### Answer: B + +Classes are syntactical sugar for function constructors. The equivalent of the `Person` class as a function constructor would be: + +```javascript +function Person() { + this.name = name +} +``` + +Which results in the same value. A class is a function under the hood, the `typeof` keyword returns `"function"` for functions. `typeof Person` returns `"function"`. + +

+
+ +--- + +###### 91. What's the 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` + +
Answer +

+ +#### Answer: 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. What's the output? + +```javascript +function giveLydiaPizza() { + return "Here is pizza!" +} + +function giveLydiaChocolate() { + return "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` + +
Answer +

+ +#### Answer: 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. What's the output? + +```javascript +function giveLydiaPizza() { + return "Here is pizza!" +} + +function giveLydiaChocolate() { + return "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` + +
Answer +

+ +#### Answer: 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`. + +

+
+ +--- + +###### 94. What's the output? + +```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` + +
Answer +

+ +#### Answer: 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. + +

+
+ +--- + +###### 95. What's the 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` + +
Answer +

+ +#### Answer: 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' ]` +

+
\ No newline at end of file diff --git a/README-ES.md b/es-ES/README-ES.md similarity index 100% rename from README-ES.md rename to es-ES/README-ES.md diff --git a/README_fr-FR.md b/fr-FR/README_fr-FR.md similarity index 100% rename from README_fr-FR.md rename to fr-FR/README_fr-FR.md diff --git a/README-ja_JA.md b/ja-JA/README-ja_JA.md similarity index 100% rename from README-ja_JA.md rename to ja-JA/README-ja_JA.md diff --git a/README-ko_KR.md b/ko-KR/README-ko_KR.md similarity index 100% rename from README-ko_KR.md rename to ko-KR/README-ko_KR.md diff --git a/README_pt_BR.md b/pt-BR/README_pt_BR.md similarity index 100% rename from README_pt_BR.md rename to pt-BR/README_pt_BR.md diff --git a/README_ru-RU.md b/ru-RU/README_ru-RU.md similarity index 100% rename from README_ru-RU.md rename to ru-RU/README_ru-RU.md diff --git a/README-tr_TR.md b/tr-TR/README-tr_TR.md similarity index 100% rename from README-tr_TR.md rename to tr-TR/README-tr_TR.md diff --git a/README-ua_UA.md b/ua-UA/README-ua_UA.md similarity index 100% rename from README-ua_UA.md rename to ua-UA/README-ua_UA.md diff --git a/README-vi.md b/vi-VI/README-vi.md similarity index 100% rename from README-vi.md rename to vi-VI/README-vi.md diff --git a/README-zh_CN.md b/zh-CN/README-zh_CN.md similarity index 100% rename from README-zh_CN.md rename to zh-CN/README-zh_CN.md From 2f1f358fc12c08f4e93fe00e76884d73877e1c8b Mon Sep 17 00:00:00 2001 From: Lydia Hallie Date: Mon, 5 Aug 2019 22:55:31 +0200 Subject: [PATCH 276/915] Fix date --- README.md | 6 +++--- en-EN/README.md | 6 +++--- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/README.md b/README.md index 1966f65a..af043829 100644 --- a/README.md +++ b/README.md @@ -2,7 +2,7 @@ I post daily multiple choice JavaScript questions on my [Instagram](https://www.instagram.com/theavocoder), which I'll also post 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 weekly with new questions. Last update: July 26th +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 weekly with new questions. Last update: August 5th The answers are in the collapsed sections below the questions, simply click on them to expand it. Good luck :heart: @@ -2469,7 +2469,7 @@ The third time, we pass `5 * 2` to the function which gets evaluated to `10`. Th --- -###### 79. What is the output? +###### 79. What is the output? ```javascript const myLifeSummedUp = ["☕", "💻", "🍷", "🍫"] @@ -2731,7 +2731,7 @@ By setting `hasName` equal to `name`, you set `hasName` equal to whatever value --- -###### 87. What's the output? +###### 87. What's the output? ```javascript console.log("I want pizza"[0]) diff --git a/en-EN/README.md b/en-EN/README.md index e25b9ce6..aa79b21a 100644 --- a/en-EN/README.md +++ b/en-EN/README.md @@ -2,7 +2,7 @@ I post daily multiple choice JavaScript questions on my [Instagram](https://www.instagram.com/theavocoder), which I'll also post 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 weekly with new questions. Last update: July 26th +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 weekly with new questions. Last update: August 5th The answers are in the collapsed sections below the questions, simply click on them to expand it. Good luck :heart: @@ -2469,7 +2469,7 @@ The third time, we pass `5 * 2` to the function which gets evaluated to `10`. Th --- -###### 79. What is the output? +###### 79. What is the output? ```javascript const myLifeSummedUp = ["☕", "💻", "🍷", "🍫"] @@ -2731,7 +2731,7 @@ By setting `hasName` equal to `name`, you set `hasName` equal to whatever value --- -###### 87. What's the output? +###### 87. What's the output? ```javascript console.log("I want pizza"[0]) From d78e477bb1b121cc42d68139cf9a8cb5e0b60e13 Mon Sep 17 00:00:00 2001 From: Srijan R Shetty Date: Tue, 6 Aug 2019 09:57:41 +0530 Subject: [PATCH 277/915] Fix question 92 and remove duplicate of 92 --- README.md | 40 +++------------------------------------- 1 file changed, 3 insertions(+), 37 deletions(-) diff --git a/README.md b/README.md index af043829..4eccfe20 100644 --- a/README.md +++ b/README.md @@ -2889,9 +2889,7 @@ function giveLydiaPizza() { return "Here is pizza!" } -function giveLydiaChocolate() { - return "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) @@ -2916,38 +2914,6 @@ Regular functions, such as the `giveLydiaPizza` function, have a `prototype` pro ###### 93. What's the output? -```javascript -function giveLydiaPizza() { - return "Here is pizza!" -} - -function giveLydiaChocolate() { - return "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` - -
Answer -

- -#### Answer: 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`. - -

-
- ---- - -###### 94. What's the output? - ```javascript const person = { name: "Lydia", @@ -2983,7 +2949,7 @@ The second subarray is `[ "age", 21 ]`, with `x` equal to `"age"`, and `y` equal --- -###### 95. What's the output? +###### 94. What's the output? ```javascript function getItems(fruitList, ...args, favoriteFruit) { @@ -3015,4 +2981,4 @@ getItems(["banana", "apple"], "pear", "orange") The above example works. This returns the array `[ 'banana', 'apple', 'orange', 'pear' ]`

-
\ No newline at end of file +
From 08c0614faa7fd6f06fe38836849f5ff8c62b2794 Mon Sep 17 00:00:00 2001 From: Srijan R Shetty Date: Tue, 6 Aug 2019 10:11:13 +0530 Subject: [PATCH 278/915] Fix incorrect answer and explaination for question 90 --- README.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 4eccfe20..ac52621a 100644 --- a/README.md +++ b/README.md @@ -2826,7 +2826,7 @@ class Person { } } -const member = new Person("John") +const member = Person("John") console.log(typeof member) ``` @@ -2838,7 +2838,7 @@ console.log(typeof member)
Answer

-#### Answer: B +#### Answer: C Classes are syntactical sugar for function constructors. The equivalent of the `Person` class as a function constructor would be: @@ -2848,7 +2848,7 @@ function Person() { } ``` -Which results in the same value. A class is a function under the hood, the `typeof` keyword returns `"function"` for functions. `typeof Person` returns `"function"`. +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"`.

From 81fd3a7bf3c9defc7ca73f71845f8fe70e781490 Mon Sep 17 00:00:00 2001 From: Lydia Hallie Date: Tue, 6 Aug 2019 10:52:21 +0200 Subject: [PATCH 279/915] Fix question 92 --- en-EN/README.md | 46 ++++++---------------------------------------- 1 file changed, 6 insertions(+), 40 deletions(-) diff --git a/en-EN/README.md b/en-EN/README.md index aa79b21a..6db3d2ab 100644 --- a/en-EN/README.md +++ b/en-EN/README.md @@ -2826,7 +2826,7 @@ class Person { } } -const member = new Person("John") +const member = Person("John") console.log(typeof member) ``` @@ -2838,7 +2838,7 @@ console.log(typeof member)
Answer

-#### Answer: B +#### Answer: C Classes are syntactical sugar for function constructors. The equivalent of the `Person` class as a function constructor would be: @@ -2848,7 +2848,7 @@ function Person() { } ``` -Which results in the same value. A class is a function under the hood, the `typeof` keyword returns `"function"` for functions. `typeof Person` returns `"function"`. +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"`.

@@ -2889,9 +2889,7 @@ function giveLydiaPizza() { return "Here is pizza!" } -function giveLydiaChocolate() { - return "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) @@ -2916,38 +2914,6 @@ Regular functions, such as the `giveLydiaPizza` function, have a `prototype` pro ###### 93. What's the output? -```javascript -function giveLydiaPizza() { - return "Here is pizza!" -} - -function giveLydiaChocolate() { - return "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` - -
Answer -

- -#### Answer: 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`. - -

-
- ---- - -###### 94. What's the output? - ```javascript const person = { name: "Lydia", @@ -2983,7 +2949,7 @@ The second subarray is `[ "age", 21 ]`, with `x` equal to `"age"`, and `y` equal --- -###### 95. What's the output? +###### 94. What's the output? ```javascript function getItems(fruitList, ...args, favoriteFruit) { @@ -3015,4 +2981,4 @@ getItems(["banana", "apple"], "pear", "orange") The above example works. This returns the array `[ 'banana', 'apple', 'orange', 'pear' ]`

-
\ No newline at end of file +
From e3b142e8351f121edccb8309d6ab506012e1bb99 Mon Sep 17 00:00:00 2001 From: Alexander Ivanov Date: Tue, 6 Aug 2019 12:35:39 +0300 Subject: [PATCH 280/915] Fix typos --- ru-RU/README_ru-RU.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/ru-RU/README_ru-RU.md b/ru-RU/README_ru-RU.md index c03d087b..c2340a2e 100644 --- a/ru-RU/README_ru-RU.md +++ b/ru-RU/README_ru-RU.md @@ -1669,7 +1669,7 @@ let x = y; --- -###### 55. Какой будет вывод? +###### 55. Какой будет вывод? ```javascript class Dog { @@ -2469,7 +2469,7 @@ console.log(addFunction(5 * 2)); --- -###### 79. Какой будет вывод? +###### 79. Какой будет вывод? ```javascript const myLifeSummedUp = ["☕", "💻", "🍷", "🍫"] From b4b3b6aac59efb64b470e5dfa37842244023a8e9 Mon Sep 17 00:00:00 2001 From: Alexander Ivanov Date: Tue, 6 Aug 2019 12:57:06 +0300 Subject: [PATCH 281/915] Russian. Updates 2019-08/1 Signed-off-by: Alexander Ivanov --- ru-RU/README_ru-RU.md | 254 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 254 insertions(+) diff --git a/ru-RU/README_ru-RU.md b/ru-RU/README_ru-RU.md index c2340a2e..ae3e1914 100644 --- a/ru-RU/README_ru-RU.md +++ b/ru-RU/README_ru-RU.md @@ -2728,3 +2728,257 @@ function getName(name) {

+ +--- + +###### 87. Какой будет вывод? + +```javascript +console.log("I want pizza"[0]) +``` + +- A: `"""` +- B: `"I"` +- C: `SyntaxError` +- D: `undefined` + +
Ответ +

+ +#### Ответ: B + +Чтобы получить символ по определенному индексу в строке, вы можете использовать скобочную нотацию. Первый символ в строке имеет индекс 0 и т.д. В этом случае мы хотим получить элемент с индексом 0, символ `'I'`, который выводится в лог. + +Обратите внимание, что этот метод не поддерживается в IE7 и ниже. В этом случае используйте `.charAt()` + +

+
+ +--- + +###### 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` принимает только один аргумент, это означает, что значение для `num2` не передано, и в этом случае значение `num1` равно переданному значению `10`. Значением по умолчанию `num2` является значение `num1`, которое равно `10`. `num1 + num2` возвращает `20`. + +Если вы пытаетесь установить значение параметра по умолчанию равным параметру, который определен _после_ (справа), то значение параметра еще не было инициализировано; это приведет к ошибке. + +

+
+ +--- + +###### 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` мы импортируем _все exports_ из файла `module.js` в файл `index.js`, тогда и создается новый объект с именем `data`. В файле `module.js` есть два экспорта: экспорт по умолчанию и именованный экспорт. Экспорт по умолчанию - это функция, которая возвращает строку `"Hello World"`, а именованный экспорт - это переменная с именем `name`, которая имеет значение строки `"Lydia"`. + +Объект `data` имеет свойство `default` для экспорта по умолчанию, другие свойства имеют имена именованных экспортов и их соответствующие значения. + +

+
+ +--- + +###### 90. Какой будет вывод? + +```javascript +class Person { + constructor(name) { + this.name = name + } +} + +const member = Person("John") +console.log(typeof member) +``` + +- A: `"class"` +- B: `"function"` +- C: `"object"` +- D: `"string"` + +
Ответ +

+ +#### Ответ: C + +Классы являются синтаксическим сахаром для конструкторов функций. Эквивалентом класса `Person` в качестве конструктора функции будет: + +```javascript +function Person() { + this.name = name +} +``` + +Вызов конструктора функции с `new` приводит к созданию экземпляра `Person`, ключевое слово `typeof` возвращает `"object"` для экземпляра. `typeof member` возвращает `"объект"`. + +

+
+ +--- + +###### 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`. + +Затем мы пытаемся использовать метод `.push` для `newList`. Поскольку `newList` является числовым значением `4`, мы не можем использовать метод `.push`: выдается ошибка TypeError. + +

+
+ +--- + +###### 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`. `undefined` возвращается при попытке доступа к свойству `prototype` с использованием `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 (person)` возвращает массив вложенных массивов, содержащий ключи и объекты: + +`[ [ 'name', 'Lydia' ], [ 'age', 21 ] ]` + +Используя цикл `for-of`, мы можем перебирать каждый элемент массива, в данном случае подмассивы. Мы можем мгновенно деструктурировать подмассивы в цикле for, используя `const [x, y]`. `x` равен первому элементу в подмассиве, `y` равен второму элементу в подмассиве. + +Первым подмассивом является `[ "name", "Lydia" ]`, где `x` равно `"name"`, и `y` равно `"Lydia"`, которые выводятся в лог. +Вторым подмассивом является `[ "age", 21 ]`, где `x` равно `"age"`, и `y` равно `21`, которые выводятся в лог. + +

+
+ +--- + +###### 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' ]` +

+
From f125db5af213a4b3766fdba2884c0b5d85ce152d Mon Sep 17 00:00:00 2001 From: Samuel Espinosa Date: Tue, 6 Aug 2019 12:02:35 +0200 Subject: [PATCH 282/915] Translate questions 44 to 94 into Spanish --- es-ES/README-ES.md | 1699 +++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 1694 insertions(+), 5 deletions(-) diff --git a/es-ES/README-ES.md b/es-ES/README-ES.md index 358e3c92..476bbbe9 100644 --- a/es-ES/README-ES.md +++ b/es-ES/README-ES.md @@ -1,16 +1,29 @@ # 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 💪 + 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. - 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 ❤️ + Las respuestas se encuentran en las secciones contraídas debajo de las preguntas, simplemente haz clic en ellas para expandirlas. Buena suerte ❤️ --- Lista de lenguajes disponibles: -* 🇬🇧[English version](./README.md) -* 🇨🇳[中文版本](./README-zh_CN.md) +* [English](./en-EN/README.md) +* [العربية](./ar-AR/README_AR.md) +* [اللغة العامية - Egyptian Arabic](./ar-EG/README_ar-EG.md) +* [Bosanski](./bs-BS/README-bs_BS.md) +* [Deutsch](./de-DE/README-de_DE.md) +* [Español](./es-ES/README-ES.md) +* [Français](./fr-FR/README_fr-FR.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_ru-RU.md) +* [Українська мова](./ua-UA/README-ua_UA.md) +* [Tiếng Việt](./vi-VI/README-vi.md) +* [中文版本](./zh-CN/README-zh_CN.md) +* [Türkçe](./tr-TR/README-tr_TR.md) --- @@ -1292,3 +1305,1679 @@ Una cadena es un iterable. El [operador de propagación](https://developer.mozil

+ +--- + +###### 44. ¿Cuál es el resultado? + +```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 y 10, 20` + +
Solución +

+ +#### Respuesta correcta: C + +Las funciones regulares no pueden pararse a mitad de ejecución después de invocarse. Sin embargo, una función generadora sí puede ser parada, y más adelante continuar desde donde fue detenida. Cada vez que una función generadora encuentra un `yield`, la función cede el valor especificado después de él. Observa que la función generadora en este caso no _devuelve_ el valor, _cede_ el valor. + +Primero, iniciamos la función generadora con `i` igual a `10`. Invocamos la función generadora usando el método `next()`. La primera vez que invocamos la función generadora, `i` es igual a `10`. Encuentra el primer `yield`: cede el valor de `i`. El generador está ahora "pausado", y `10` es mostrado por consola. + +Después, invocamos la función otra vez con el método `next()`. Continúa donde fue detenida previamente, todavía con `i` igual a `10`. Ahora, encuentra el siguiente `yield`, y cede `i * 2`. `i` es igual a `10`, así que devuelve `10 * 2`, que es `20`. Esto da como resultado `10, 20`. + +

+
+ +--- + +###### 45. ¿Qué devuelve esto? + +```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"` + +
Solución +

+ +#### Respuesta correcta: B + +Cuando pasamos múltiples promesas al método `Promise.race`, resuelve/rechaza la _primera_ promesa que sea resuelta/rechazada. Para el método `setTimeout`, pasamos un cronómetro: 500ms para la primera promesa (`firstPromise`), y 100ms para la segunda promesa (`secondPromise`). Esto significa que `secondPromise` se resuelve primero con el valor de `'two'`. `res` ahora guarda el valor `'two'`, el cual se muestra por consola. + +

+
+ +--- + +###### 46. ¿Cuál es el resultado? + +```javascript +let person = { name: "Lydia" }; +const members = [person]; +person = null; + +console.log(members); +``` + +- A: `null` +- B: `[null]` +- C: `[{}]` +- D: `[{ name: "Lydia" }]` + +
Solución +

+ +#### Respuesta correcta: D + +Primero, declaramos la variable `person` con el valor de un objeto que tiene una propiedad `name`. + + + +Después, declaramos una variable llamada `members`. Asignamos el primer elemento de ese array igual al valor de la variable `person`. Un objeto interactúa por _referencia_ cuando es asignado igual a otro objeto. Cuando asignas una referencia de una variable a otra, haces una _copia_ de esa referencia. (¡observa que no tienen la _misma_ referencia!) + + + +Después, asignamos que la variable `person` es igual a `null`. + + + +Solo estamos modificando el valor de la variable `person`, y no el primer elemento del array, ya que este elemento tiene una referencia diferente (copiada) al objeto. El primer elemento en `members` todavía mantiene su referencia hacia el objeto original. Cuando mostramos por consola el array `members`, el primer elemento todavía mantiene el valor del objeto, el cual se muestra por consola. + +

+
+ +--- + +###### 47. ¿Cuál es el resultado? + +```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]` + +
Solución +

+ +#### Respuesta correcta: B + +Con un bucle `for-in`, podemos iterar sobre claves de objetos, en este caso `name` y `age`. Internamente, las claves de objetos son strings (si no son Symbol). En cada bucle, asignamos `item` igual a la clave actual que se está iterando. Primero, `item` es igual a `name`, y se muestra por consola. Después, `item` es igual a `age`, que se muestra por consola. + +

+
+ +--- + +###### 48. ¿Cuál es el resultado? + +```javascript +console.log(3 + 4 + "5"); +``` + +- A: `"345"` +- B: `"75"` +- C: `12` +- D: `"12"` + +
Solución +

+ +#### Respuesta correcta: B + +La asociatividad de operadores es el orden en el que el compilador evalúa las expresiones, ya sea de izquierda a derecha o de derecha a izquierda. Esto solo pasa si todos los operadores tienen la _misma_ precedencia. Solo tenemos un tipo de operador: `+`. Para la suma, la asociatividad es de izquierda a derecha. + +`3 + 4` se evalúa primero. Esto da como resultado el número `7`. + +`7 + '5'` da `"75"` por la coerción. JavaScript convierte el número `7` a string, mira la pregunta 15. Podemos concatenar dos strings usando el operador `+`. `7 + '5'` da como resultado `"75"`. + +

+
+ +--- + +###### 49. ¿Cuál es el valor de `num`? + +```javascript +const num = parseInt("7*6", 10); +``` + +- A: `42` +- B: `"42"` +- C: `7` +- D: `NaN` + +
Solución +

+ +#### Respuesta correcta: C + +Solo el primer número en el string es devuelto. Según en la _base_ seleccionada (el segundo argumento para especificar a qué tipo de número queremos transformarlo: base 10, hexadecimal, octal, binario, etc.), el `parseInt` comprueba si los caracteres del string son válidos. Una vez encuentra un caracter que no es un número válido en la base seleccionada, deja de recorrer el string e ignora los siguientes caracteres. + +`*` no es un número válido. Solo convierte `"7"` al decimal `7`. `num` tiene el valor `7`. + +

+
+ +--- + +###### 50. ¿Cuál es el resultado? + +```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 huecos vacíos ]` + +
Solución +

+ +#### Respuesta correcta: C + +Cuando se mapea sobre un array, el valor de `num` es igual al elemento que se está iterando. En este caso, los elementos son números, por lo que la condición del if `typeof num === "number"` devuelve `true`. La función de mapeo crea un nuevo array e inserta los valores devueltos por la función. + +Sin embargo, no devolvemos un valor. Cuando no devolvemos un valor desde la función, la función devuelve `undefined`. Para cada elemento en el array, la función de bloque es llamada, así que por cada elemento devolvemos `undefined`. + +

+
+ +--- + +###### 51. ¿Cuál es el resultado? + +```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"` + +
Solución +

+ +#### Respuesta correcta: A + +Los argumentos son pasados por _valor_, a no ser que su valor sea un objeto, en cuyo caso con pasados por _referencia_. `birthYear` es pasado por valor, ya que es un string, no un objeto. Cuando pasamos argumentos por valor, una _copia_ de ese valor es creada (ver pregunta 46). + +La variable `birthYear` tiene una referencia al valor `"1997"`. El argumento `year` también tiene una referencia al valor `"1997"`, pero no es el mismo valor al que `birthYear` referencia. Cuando actualizamos el valor de `year` igualándolo a `"1998"`, solo estamos actualizando el valor de `year`. `birthYear` todavía es igual a `"1997"`. + +El valor de `person` es un objeto. El argumento `member` tiene una referencia (copiada) al _mismo_ objeto. Cuando modificamos la propiedad a la que el objeto `member` referencia, el valor de `person` también será modificado, ya que ambos tienen una referencia al mismo objeto. La propiedad `name` de `person` es ahora igual al valor `"Lydia"`. + +

+
+ +--- + +###### 52. ¿Cuál es el resultado? + +```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!` + +
Solución +

+ +#### Respuesta correcta: D + +Con la sentencia `throw`, podemos crear errores personalizados. Con esta sentencia, puedes lanzar excepciones. Una excepción puede ser un string, un número, un boolean o un objeto. En este caso, nuestra excepción es el string `'Hello world'`. + +Con la sentencia `catch`, podemos especificar qué queremos hacer si una excepción es lanzada en el bloque `try`. Se lanza una excepción: el string `'Hello world'`. `e` es ahora igual a ese string, el cual se muestra por consola. Esto da como resultado `'Oh an error: Hello world'`. + +

+
+ +--- + +###### 53. ¿Cuál es el resultado? + +```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` + +
Solución +

+ +#### Respuesta correcta: B + +Cuando devuelves una propiedad, el valor de la propiedad es igual al valor _retornado_, no el valor indicado en el constructor de la función. Devolvemos el string `"Maserati"`, por lo que `myCar.make` es igual a `"Maserati"`. + +

+
+ +--- + +###### 54. ¿Cuál es el resultado? + +```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"` + +
Solución +

+ +#### Respuesta correcta: A + +`let x = y = 10;` es en realidad una forma más corta de escribir: + +```javascript +y = 10; +let x = y; +``` + +Cuando asignamos `y` igual a `10`, en realidad añadimos una propiedad `y` al objeto global (`window` en navegador, `global` en Node). En un navegador, `window.y` es ahora igual a `10`. + +Después, declaramos una variable `x` con el valor de `y`, el cual es `10`. Las variables declaradas con `let` tienen _alcance de bloque_, solo son definidas dentro del bloque en el que son declaradas; las expresiones de función ejecutadas inmediatamente (IIFE por sus siglas en inglés) en este caso. Cuando usamos el operador `typeof`, el operando `x` no está definido: estamos intentando acceder a `x` fuera del bloque en el que es declarado. Esto significa que `x` no está definido. Los valores a los que no se les ha asignado un valor o que no han sido declarados son de tipo `"undefined"`. `console.log(typeof x)` devuelve `"undefined"`. + +Sin embargo, hemos creado una variable global `y` cuando la hemos igualado a `10`. Este valor es accesible desde cualquier parte en nuestro código. `y` es definida, y tiene un valor de tipo `"number"`. `console.log(typeof y)` devuelve `"number"`. + +

+
+ +--- + +###### 55. ¿Cuál es el resultado? + +```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` + +
Solución +

+ +#### Respuesta correcta: A + +Podemos borrar propiedades de objetos usando `delete`, también en el prototipo (prototype). Borrando una propiedad en el prototipo, hace que no vuelva a estar disponible en la cadena de prototipo. En este caso, la función `bark` deja de estar disponible en el prototipo después de `delete Dog.prototype.bark`, pero aún intentamos acceder a ella. + +Cuando intentamos invocar algo que no es una función, un `TypeError` es lanzado. En este caso `TypeError: pet.bark is not a function`, ya que `pet.bark` es `undefined`. + +

+
+ +--- + +###### 56. ¿Cuál es el resultado? + +```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}` + +
Solución +

+ +#### Respuesta correcta: D + +El objeto `Set` es una colección de valores _únicos_: un valor solo puede aparecer una vez en un set. + +Pasamos el iterable `[1, 1, 2, 3, 4]` con el valor `1` duplicado. Como no podemos tener dos valores iguales en el set, uno de ellos es eliminado. Esto da como resultado `{1, 2, 3, 4}`. + +

+
+ +--- + +###### 57. ¿Cuál es el resultado? + +```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` + +
Solución +

+ +#### Respuesta correcta: C + +Un módulo importado es de _solo lectura_: no puedes modificar el módulo importado. Solo el módulo que los exporta puede cambiar su valor. + +Cuando intentamos incrementar el valor de `myCounter`, lanza un error: `myCounter` es de solo lectura y no puede ser modificado. + +

+
+ +--- + +###### 58. ¿Cuál es el resultado? + +```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` + +
Solución +

+ +#### Respuesta correcta: A + +El operador `delete` devuelve un valor booleano: `true` en una eliminación exitosa, sino devolverá `false`. Sin embargo, las variables declaradas con `var`, `const` o `let` no pueden ser borradas usando el operador `delete`. + +La variable `name` se declara con `const`, por lo que su eliminación no es exitosa: se devuelve `false`. Cuando asignamos `age` igual a `21`, en realidad hemos añadido una propiedad llamada `age` al objeto global. Puedes borrar exitosamente propiedades de objetos de esta forma, también del objeto global, así que `delete age` devuelve `true`. + +

+
+ +--- + +###### 59. ¿Cuál es el resultado? + +```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]` + +
Solución +

+ +#### Respuesta correcta: C + +Podemos desempaquetar valores de arrays o propiedades de objetos con desestructuración. Por ejemplo: + +```javascript +[a, b] = [1, 2]; +``` + + + +El valor de `a` es ahora `1`, y el valor de `b` es ahora `2`. Lo que realmente se hizo en la pregunta es: + +```javascript +[y] = [1, 2, 3, 4, 5]; +``` + + + +Esto significa que el valor de `y` es igual al primer valor del array, el cual es el número `1`. Cuando mostramos por consola `y`, `1` es devuelto. + +

+
+ +--- + +###### 60. ¿Cuál es el resultado? + +```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 }` + +
Solución +

+ +#### Respuesta correcta: B + +Se pueden combinar objetos usando el operador de propagación `...`. Te permite crear copias de los pares clave/valor de un objeto, y añadirlos a otro objeto. En este caso, creamos copias del objeto `user`, y las añadimos al objeto `admin`. El objeto `admin` ahora contiene los pares clave/valor copiados, lo cual da como resultado `{ admin: true, name: "Lydia", age: 21 }`. + +

+
+ +--- + +###### 61. ¿Cuál es el resultado? + +```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"]` + +
Solución +

+ +#### Respuesta correcta: B + +Con el método `defineProperty`, podemos añadir nuevas propiedades a un objeto, o modificar las existentes. Cuando añadimos una propiedad a un objeto usando el método `defineProperty`, es por defecto _no enumerable_. El método `Object.keys` devuelve todos los nombres de propiedades _enumerables_ de un objeto, en este caso solo `"name"`. + +Las propiedades añadidas usando el método `defineProperty` son inmutables por defecto. Puedes sobrescribir este comportamiento usando las propiedades `writable`, `configurable` y `enumerable`. De esta forma, el método `defineProperty` te da mucho más control sobre las propiedades que estás añadiendo a un objeto. + +

+
+ +--- + +###### 62. ¿Cuál es el resultado? + +```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}"` + +
Solución +

+ +#### Respuesta correcta: A + +El segundo argumento de `JSON.stringify` es el _replacer_ (reemplazador). El reemplazador puede ser una función o un array, y te permite controlar qué y cómo deberían convertirse los valores a string. + +Si el reemplazador es un _array_, solo los nombres de las propiedades incluidos en el array serán agregados al string JSON. En este caso, solo las propiedades con nombres `"level"` y `"health"` son incluidas, `"username"` es excluido. `data` es ahora igual a `"{"level":19, "health":90}"`. + +Si el reemplazador es una _función_, esta función es llamada en cada propiedad en el objeto que estás convirtiendo a string. El valor retornado por esta función será el valor de la propiedad cuando es añadida al string JSON. Si el valor es `undefined`, esta propiedad es excluida del string JSON. + +

+
+ +--- + +###### 63. ¿Cuál es el resultado? + +```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` + +
Solución +

+ +#### Respuesta correcta: A + +El operador unario `++` _devuelve primero_ el valor del operando, _y después incrementa_ el valor del operando. El valor de `num1` es `10`, ya que la función `increaseNumber` primero devuelve el valor de `num`, que es `10`, y solo incrementa el valor de `num` después. + +`num2` es `10`, ya que pasamos `num1` a `increasePassedNumber`. `number` es igual a `10` (el valor de `num1`. Una vez más, el operador unario `++` _primero devuelve_ el valor del operando, _y después incrementa_ el valor del operando. El valor de `number` es `10`, así que `num2` es igual a `10`. + +

+
+ +--- + +###### 64. ¿Cuál es el resultado? + +```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` + +
Solución +

+ +#### Respuesta correcta: C + +En ES6, podemos inicializar parámetros con un valor por defecto. El valor del parámetro será el valor por defecto si no se pasa otro valor a la función, o si el valor del parámetro es `"undefined"`. En este caso, propagamos las propiedades del objeto `value` en un nuevo objeto, por lo que `x` tiene el valor por defecto de `{ number: 10 }`. + +¡El argumento por defecto es evaluado _cuando es llamado_! Cada vez que llamamos a la función, un _nuevo_ objeto es creado. Invocamos la función `multiply` las dos primeras veces sin pasar un valor: `x` tiene el valor por defecto de `{ number: 10 }`. Después mostramos por consola el valor multiplicado de ese número, que es `20`. + +La tercera vez que invocamos `multiply`, pasamos un argumento: el objeto llamado `value`. El operador `*=` es en realidad una forma corta de escribir `x.number = x.number * 2`: modificamos el valor de `x.number` y mostramos por consola el valor multiplicado de `20`. + +La cuarta vez, pasamos el objeto `value` otra vez. `x.number` fue previamente modificado a `20`, por lo que `x.number *= 2` devuelve `40`. + +

+
+ +--- + +###### 65. ¿Cuál es el resultado? + +```javascript +[1, 2, 3, 4].reduce((x, y) => console.log(x, y)); +``` + +- A: `1` `2` y `3` `3` y `6` `4` +- B: `1` `2` y `2` `3` y `3` `4` +- C: `1` `undefined` y `2` `undefined` y `3` `undefined` y `4` `undefined` +- D: `1` `2` y `undefined` `3` y `undefined` `4` + +
Solución +

+ +#### Respuesta correcta: D + +El primer argumento que el método `reduce` recibe es el _acumulador_, `x` en este caso. El segundo argumento es el _valor actual_, `y`. Con el método `reduce`, podemos ejecutar una función de callback en cada elemento en el array, lo cual puede resultar en un único valor al final. + +En este ejemplo, no estamos devolviendo ningún valor, simplemente estamos mostrando por consola los valores del acumulador y del valor actual. + +El valor del acumulador es igual al valor previamente devuelto por la función de callback. Si no pasas el argumento opcional `initialValue` al método `reduce`, el acumulador es igual al primer elemento de la primera llamada. + +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`. + +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`. + +

+
+ +--- + +###### 66. ¿Con qué constructor podemos extender correctamente la clase `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 + +
Solución +

+ +#### Respuesta correcta: B + +En una clase derivada, no puedes acceder a `this` antes de llamar a `super`. Si intentas hacerlo, se lanzará un `ReferenceError`: 1 y 4 lanzarían este error. + +Con `super`, llamamos al constructor del padre con unos argumentos. El constructor del padre recibe el argumento `name`, por lo que necesitamos pasar `name` a `super`. + +La clase `Labrador` recibe dos argumentos, `name` porque extiende de `Dog`, y `size` como una propiedad adicional en la clase `Labrador`. Ambos necesitan ser pasados al constructor de `Labrador`, lo cual se realiza correctamente usando el constructor 2. + +

+
+ +--- + +###### 67. ¿Cuál es el resultado? + +```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` + +
Solución +

+ +#### Respuesta correcta: 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`. + +

+
+ +--- + +###### 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')) +``` + +- A: `true`, `true`, `false` +- B: `false`, `true`, `false` +- C: `true`, `false`, `true` +- D: `true`, `true`, `true` + +
Solución +

+ +#### Respuesta correcta: A + +Cada Symbol es completamente único. El propósito del argumento pasado a Symbol es para darle una descripción. El valor de Symbol no depende del argumento pasado. Como se comprueba igualdad, estamos creando dos Symbol completamente nuevos: el primer `Symbol('foo')`, y el segundo `Symbol('foo')`. Estos dos valores son únicos y no iguales, `Symbol('foo') === Symbol('foo')` devuelve `false`. + +

+
+ +--- + +###### 69. ¿Cuál es el resultado? + +```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"` (`"[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"`, + +
Solución +

+ +#### Respuesta correcta: C + +Con el método `padStart`, podemos añadir relleno al principio de un string. El valor pasado a este método es la longitud _total_ del string incluyendo el relleno. El string `"Lydia Hallie"` tiene una longitud de `12`. `name.padStart(13)` inserta 1 espacio al principio del string, porque 12 + 1 es 13. + +Si el argumento pasado al método `padStart` es más pequeño que la longitud del string, no se añade relleno. + +

+
+ +--- + +###### 70. ¿Cuál es el resultado? + +```javascript +console.log("🥑" + "💻"); +``` + +- A: `"🥑💻"` +- B: `257548` +- C: Un string con una secuencia de puntos de código +- D: Error + +
Solución +

+ +#### Respuesta correcta: A + +Con el operador `+` puedes concatenar strings. En este caso, estamos concatenando el string `"🥑"` con el string `"💻"`, lo que da como resultado `"🥑💻"`. + +

+
+ +--- + +###### 71. ¿Cómo puedes mostrar por consola los valores comentados junto a las sentencias 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` y `game.next().value` +- B: `game.next.value("Yes")` y `game.next.value()` +- C: `game.next().value` y `game.next("Yes").value` +- D: `game.next.value()` y `game.next.value("Yes")` + +
Solución +

+ +#### Respuesta correcta: C + +Una función generadora "pausa" su ejecución cuando ve un `yield`. Primero, tenemos que dejar a la función ceder el string "Do you love JavaScript?", lo cual se puede hacer llamando a `game.next().value`. + +Todas las líneas son ejecutadas, hasta que encuentra el primer `yield`. Hay un `yield` en la primera línea dentro de la función: ¡la ejecución se para en el primer yield! _¡Esto significa que la variable `answer` todavía no está definida!_ + +Cuando llamamos a `game.next("Yes").value`, el `yield` anterior se reemplaza con el valor de los parámetros pasados en la función `next()`, `"Yes"` en este caso. El valor de la variable `answer` es ahora igual a `"Yes"`. La condición del if devuelve `false`, y `JavaScript loves you back ❤️` se muestra por consola. + +

+
+ +--- + +###### 72. ¿Cuál es el resultado? + +```javascript +console.log(String.raw`Hello\nworld`); +``` + +- A: `Hello world!` +- B: `Hello`
     `world` +- C: `Hello\nworld` +- D: `Hello\n`
     `world` + +
Solución +

+ +#### Respuesta correcta: C + +`String.raw` devuelve un string donde las secuencias de escape (`\n`, `\v`, `\t` etc.) son ignoradas. Las contrabarras pueden ser un problema ya que puedes acabar con algo como: + +`` const path = `C:\Documents\Projects\table.html` `` + +Que resultaría en: + +`"C:DocumentsProjects able.html"` + +Con `String.raw`, simplemente ignoraría las secuencias de escape e imprimiría: + +`C:\Documents\Projects\table.html` + +En este caso, el string es `Hello\nworld`, que es lo que se muestra por consola. + +

+
+ +--- + +###### 73. ¿Cuál es el 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` + +
Solución +

+ +#### Respuesta correcta: C + +Una función asíncrona siempre devuelve una promesa. El `await` todavía tiene que esperar a que la promesa se resuelva: cuando llamamos a `getData()` para asignarle que es igual a `data`, se devuelve una promesa pendiente. + +Si quisiéramos tener acceso al valor resuelto `"I made it"`, tendríamos que haber usado el método `.then()` en `data`: + +`data.then(res => console.log(res))` + +Esto habría mostrado por consola `"I made it!"` + +

+
+ +--- + +###### 74. ¿Cuál es el 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` + +
Solución +

+ +#### Respuesta correcta: B + +¡El método `.push()` devuelve la _longitud_ del nuevo array! Al principio, el array contenía un elemento (el string `"banana"`) y tenía una longitud de `1`. Después de añadir el string `"apple"` al array, el array contiene dos elementos, y tiene una longitud de `2`. Esto es lo que devuelve la función `addToList`. + +El método `push` modifica el array original. Si quisieras devolver el _array_ de la función en lugar de la _longitud del array_ deberías haber devuelto `list` después de introducir `item` en él. + +

+
+ +--- + +###### 75. ¿Cuál es el 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` + +
Solución +

+ +#### Respuesta correcta: B + +`Object.freeze` congela e imposibilita la adición, eliminación o modificación de las propiedades de un objeto (a no ser que el valor de la propiedad sea otro objeto). + +Cuando creamos la variable `shape` y la igualamos al objeto congelado `box`, `shape` también referencia al objeto congelado. Puedes comprobar si un objeto está congelado usando `Object.isFrozen`. En este caso, `Object.isFrozen(shape)` devuelve `true`, ya que la variable `shape` tiene una referencia a un objeto congelado. + +Como `shape` está congelado, y como el valor de `x` no es un objeto, no podemos modificar la propiedad `x`. `x` es todavía igual a `10`, y `{ x: 10, y: 20 }` se muestra por consola. + +

+
+ +--- + +###### 76. ¿Cuál es el resultado? + +```javascript +const { name: myName } = { name: "Lydia" }; + +console.log(name); +``` + +- A: `"Lydia"` +- B: `"myName"` +- C: `undefined` +- D: `ReferenceError` + +
Solución +

+ +#### Respuesta correcta: D + +Cuando desempaquetamos la propiedad `name` del objeto de la parte derecha, asignamos su valor `"Lydia"` a una variable con el nombre `myName`. + +Con `{ name: myName }`, le decimos a JavaScript que queremos crear una nueva variable llamada `myName` con el valor de la propiedad `name` de la parte derecha. + +Como intentamos mostrar por consola `name`, una variable que no está definida, se lanza un `ReferenceError`. + +

+
+ +--- + +###### 77. ¿Esta es una función pura? + +```javascript +function sum(a, b) { + return a + b; +} +``` + +- A: Sí +- B: No + +
Solución +

+ +#### Respuesta correcta: A + +Una función pura es una función que _siempre_ devuelve el mismo resultado, si se le pasan los mismos argumentos. + +La función `sum` siempre devuelve el mismo resultado. Si pasamos `1` y `2`, _siempre_ devuelve `3` sin efectos secundarios. Si pasamos `5` y `10`, _siempre_ devuelve `15`, etcétera. Esta es la definición de una función pura. + +

+
+ +--- + +###### 78. ¿Cuál es el 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` + +
Solución +

+ +#### Respuesta correcta: C + +La función `add` es una función _memoizada_. Con la memoización, podemos guardar en caché los resultados de una función para acelerar su ejecución. En este caso, creamos el objeto `cache` que guarda los valores previamente retornados. + +Si llamamos a la función `addFunction` otra vez con el mismo argumento, primero comprueba si ya tiene ese valor en su caché. Si es el caso, se devuelve el valor de la caché. Si no está en la caché, calculará el valor y lo almacenará justo después. + +Llamamos a la función `addFunction` tres veces con el mismo valor: en la primera invocación, el valor de la función cuando `num` es igual a `10` no está en caché todavía. La condición del if `num in cache` devuelve `false`, y se ejecuta el bloque `else`: `Calculated! 20` se muestra por consola, y el valor del resultado se añade al objeto `cache`. `cache` ahora contiene `{ 10: 20 }`. + +La segunda vez, el objeto `cache` contiene el valor que se devuelve para `10`. La condición del if `num in cache` devuelve `true`, y se muestra por consola `'From cache! 20'`. + +La tercera vez, pasamos `5 * 2` a la función, que se evalúa como `10`. El objeto `cache` contiene el valor que se devuelve para `10`. La condición del if `num in cache` devuelve `true`, y se muestra por consola `'From cache! 20'`. + +

+
+ +--- + +###### 79. ¿Cuál es el 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` y `"☕"` ` "💻"` `"🍷"` `"🍫"` +- B: `"☕"` ` "💻"` `"🍷"` `"🍫"` y `"☕"` ` "💻"` `"🍷"` `"🍫"` +- C: `"☕"` ` "💻"` `"🍷"` `"🍫"` y `0` `1` `2` `3` +- D: `0` `1` `2` `3` y `{0: "☕", 1: "💻", 2: "🍷", 3: "🍫"}` + +
Solución +

+ +#### Respuesta correcta: A + +Con el bucle _for-in_, podemos iterar sobre propiedades **enumerables**. En un array, las propiedades enumerables son las "claves" de los elementos del array, las cuales son sus índices. Puedes ver el array como: + +`{0: "☕", 1: "💻", 2: "🍷", 3: "🍫"}` + +Donde las claves son las propiedades enumerables. `0` `1` `2` `3` se muestran por consola. + +Con un bucle _for-of_, podemos iterar sobre **iterables**. Un array es un iterable. Cuando iteramos sobre un array, la variable "item" es igual al elemento sobre el que se está iterando en ese momento, `"☕"` ` "💻"` `"🍷"` `"🍫"` se muestra por consola. + +

+
+ +--- + +###### 80. ¿Cuál es el 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]` + +
Solución +

+ +#### Respuesta correcta: C + +Los elementos de un array pueden contener cualquier valor. Números, strings,objetos, otros arrays, null, valores booleanos, undefined, y otras expresiones como fechas, funciones o cálculos. + +El elemento será igual al valor retornado. `1 + 2` devuelve `3`, `1 * 2` devuelve `2`, y `1 / 2` devuelve `0.5`. + +

+
+ +--- + +###### 81. ¿Cuál es el resultado? + +```javascript +function sayHi(name) { + return `Hi there, ${name}` +} + +console.log(sayHi()) +``` + +- A: `Hi there, ` +- B: `Hi there, undefined` +- C: `Hi there, null` +- D: `ReferenceError` + +
Solución +

+ +#### Respuesta correcta: B + +Por defecto, los argumentos tienen el valor `undefined`, a no ser que un valor haya sido pasado a la función. En este caso, no pasamos ningún valor para el argumento `name`. `name` es igual a `undefined`, que es mostrado por consola. + +En ES6, podemos sobrescribir este valor `undefined` por defecto con parámetros por defecto. Por ejemplo: + +`function sayHi(name = "Lydia") { ... }` + +En ese caso, si no pasáramos un valor o si pasáramos `undefined`, `name` siempre sería igual al string `Lydia`. + +

+
+ +--- + +###### 82. ¿Cuál es el resultado? + +```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: `"🥑"` y `"😍"` +- B: `"🥑"` y `"😎"` +- C: `"😍"` y `"😎"` +- D: `"😎"` y `"😎"` + +
Solución +

+ +#### Respuesta correcta: B + +El valor de `this` depende de dónde lo uses. En un método, como el método `getStatus`, `this` referencia al _objeto al que el método pertenece_. El método pertenece al objeto `data`, por lo que `this` referencia al objeto `data`. Cuando mostramos por consola `this.status`, la propiedad `status` en el objeto `data` es mostrada por consola, la cual es `"🥑"`. + +Con el método `call`, podemos cambiar el objeto al cual `this` referencia. En **funciones**, el `this` referencia al _objeto al que la función pertenece_, por lo que dentro de la función `setTimeout`, el `this` referencia al _objeto global_. En el objeto global, hay una variable llamada _status_ con el valor `"😎"`. Cuando se muestra `this.status` por consola, `"😎"` aparece por pantalla. + +

+
+ +--- + +###### 83. ¿Cuál es el resultado? + +```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"` + +
Solución +

+ +#### Respuesta correcta: A + +Asignamos a la variable `city` el valor de la propiedad `city` del objeto `person`. No existe ninguna propiedad en este objeto llamada `city`, por lo que la variable `city` tiene el valor `undefined`. + +¡Observa que _no_ estamos referenciando al objeto `person` en sí mismo! Solo asignamos a la variable `city` el valor actual de la propiedad `city` del objeto `person`. + +Después, asignamos a la variable `city` el string `"Amsterdam"`. Esto no cambia el objeto `person`: no hay ninguna referencia a ese objeto. + +Cuando se muestra por consola el objeto `person`, se devuelve el objeto sin modificar. + +

+
+ +--- + +###### 84. ¿Cuál es el resultado? + +```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` + +
Solución +

+ +#### Respuesta correcta: C + +Las variables con `const` y `let` tienen _alcance de bloque_. Un bloque es cualquier cosa entre llaves (`{ }`). En este caso, las llaves del if/else. No puedes referenciar a una variable fuera del bloque en el que es declarada, se lanza un `ReferenceError`. + +

+
+ +--- + +###### 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)) +``` + +- 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`. + +
Solución +

+ +#### Respuesta correcta: C + +El valor de `res` en el segundo `.then` es igual al valor retornado por el `.then` anterior. Puedes seguir encadenando `.then` como este, pasando el valor al siguiente manejador. + +

+
+ +--- + +###### 86. ¿Qué opción es una forma de igualar `hasName` a `true`, teniendo en cuenta que no se puede pasar `true` como argumento? + +```javascript +function getName(name) { + const hasName = // +} +``` + +- A: `!!name` +- B: `name` +- C: `new Boolean(name)` +- D: `name.length` + +
Solución +

+ +#### Respuesta correcta: A + +Con `!!name`, determinamos si el valor de `name` es convertible a verdadero o convertible a falso. Si `name` es convertible a verdadero, `!name` devuelve `false`. `!false` (el cual es prácticamente lo mismo que `!!name`) devuelve `true`. + +Asignándole a `hasName` el valor de `name`, asignas a `hasName` cualquier valor que se haya pasado a la función `getName`, no el valor booleano `true`. + +`new Boolean(true)` devuelve un envoltorio (wrapper), no el valor booleano en sí. + +`name.length` devuelve la longitud del argumento pasado, no si es `true`. + +

+
+ +--- + +###### 87. ¿Cuál es el resultado? + +```javascript +console.log("I want pizza"[0]) +``` + +- A: `"""` +- B: `"I"` +- C: `SyntaxError` +- D: `undefined` + +
Solución +

+ +#### Respuesta correcta: B + +Para obtener un caracter en un índice específico en un string, puedes usar corchetes. El primer caracter en el string tiene índice 0, y así sucesivamente. En este caso queremos obtener el elemento cuyo índice es 0, el caracter `"I"`, el cual se muestra por consola. + +Observa que este método no está soportado en IE7 y versiones anteriores. En ese caso, usamos `.charAt()`. + +

+
+ +--- + +###### 88. ¿Cuál es el resultado? + +```javascript +function sum(num1, num2 = num1) { + console.log(num1 + num2) +} + +sum(10) +``` + +- A: `NaN` +- B: `20` +- C: `ReferenceError` +- D: `undefined` + +
Solución +

+ +#### Respuesta correcta: B + +Puedes asignar un valor por defecto para un parámetro que sea igual a otro parámetro de la función, siempre y cuando haya sido definido _antes_ del parámetro por defecto. Pasamos el valor `10` a la función `sum`. Si la función `sum` solamente recibe 1 argumento, significa que el valor para `num2` no ha sido pasado, y el valor de `num1` es igual al valor `10` que hemos pasado en este caso. El valor por defecto de `num2` es el valor de `num1`, el cual es `10`. `num1 + num2` devuelve `20`. + +Si estuvieras intentando asignar un valor por defecto a un parámetro igual a otro parámetro que es definido _después_ (a la derecha), el valor del parámetro no habría sido inicializado todavía, lo cual lanzaría un error. + +

+
+ +--- + +###### 89. ¿Cuál es el resultado? + +```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: Objeto global de `module.js` + +
Solución +

+ +#### Respuesta correcta: A + +Con la sintaxis `import * as name`, importamos _todas las exportaciones_ del fichero `module.js` al fichero `index.js` creando un nuevo objeto llamado `data`. En el fichero `module.js` hay dos exportaciones: la exportación por defecto y una exportación con nombre. La exportación por defecto es una función que devuelve el string `"Hello World"`, y la exportación con nombre es una variable llamada `name` que tiene el valor del string `"Lydia"`. + +El objeto `data` tiene una propiedad `default` para la exportación por defecto, el resto de propiedades tienen los nombres de las exportaciones con nombre y sus respectivos valores. + +

+
+ +--- + +###### 90. ¿Cuál es el resultado? + +```javascript +class Person { + constructor(name) { + this.name = name + } +} + +const member = Person("John") +console.log(typeof member) +``` + +- A: `"class"` +- B: `"function"` +- C: `"object"` +- D: `"string"` + +
Solución +

+ +#### Respuesta correcta: C + +Las clases son azúcar sintáctico para los constructores de funciones. El equivalente a la clase `Person` como constructor de función sería: + +```javascript +function Person() { + 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"`. + +

+
+ +--- + +###### 91. ¿Cuál es el resultado? + +```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` + +
Solución +

+ +#### Respuesta correcta: D + +El método `.push` devuelve la _nueva longitud_ del array, ¡no el array en sí mismo! Asignando `newList` igual a `[1, 2, 3].push(4)`, estamos asignando `newList` igual a la nueva longitud del array: `4`. + +Después, intentamos usar el método `.push` en `newList`. Como `newList` es el valor numérico `4`, no podemos usar el método `.push`: se lanza un `TypeError`. + +

+
+ +--- + +###### 92. ¿Cuál es el resultado? + +```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` + +
Solución +

+ +#### Respuesta correcta: D + +Las funciones regulares, como la función `giveLydiaPizza`, tienen la propiedad `prototype`, la cual es un objeto (objeto de prototipo) con una propiedad `constructor`. Sin embargo las funciones flecha, como la función `giveLydiaChocolate`, no tienen esta propiedad `prototype`. Se devuelve `undefined` cuando se intenta acceder a la propiedad `prototype` usando `giveLydiaChocolate.prototype`. + +

+
+ +--- + +###### 93. ¿Cuál es el resultado? + +```javascript +const person = { + name: "Lydia", + age: 21 +} + +for (const [x, y] of Object.entries(person)) { + console.log(x, y) +} +``` + +- A: `name` `Lydia` y `age` `21` +- B: `["name", "Lydia"]` y `["age", 21]` +- C: `["name", "age"]` y `undefined` +- D: `Error` + +
Solución +

+ +#### Respuesta correcta: A + +`Object.entries(person)` devuelve un array de arrays anidados, conteniendo claves y objetos: + +`[ [ '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. + +El primer subarray es `[ "name", "Lydia" ]`, con `x` igual a `"name"` e `y` igual a `"Lydia"`, lo cual es mostrado por consola. + +El segundo subarray es `[ "age", 21 ]`, con `x` igual a `"age"` e `y` igual a `21`, lo cual es mostrado por consola. + +

+
+ +--- + +###### 94. ¿Cuál es el resultado? + +```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` + +
Solución +

+ +#### Respuesta correcta: D + +`...args` es un parámetro rest. El valor del parámetro rest es un array que contiene el resto de argumentos, ¡**y solo puede ser el último parámetro**! En este ejemplo, el parámetro rest es el segundo parámetro. Esto no es correcto y lanzará un error de sintaxis. + +```javascript +function getItems(fruitList, favoriteFruit, ...args) { + return [...fruitList, ...args, favoriteFruit] +} + +getItems(["banana", "apple"], "pear", "orange") +``` + +El ejemplo de arriba sí que funciona. Devuelve el array `[ 'banana', 'apple', 'orange', 'pear' ]` +

+
From f98b2c11f07f45cf664a121b94fbf72e2f284202 Mon Sep 17 00:00:00 2001 From: Jacob Herper Date: Tue, 6 Aug 2019 11:46:47 +0100 Subject: [PATCH 283/915] Added questions 87 - 94 in German --- de-DE/{README-de_DE.md => README.md} | 293 +++++++++++++++++++++++++-- 1 file changed, 274 insertions(+), 19 deletions(-) rename de-DE/{README-de_DE.md => README.md} (90%) diff --git a/de-DE/README-de_DE.md b/de-DE/README.md similarity index 90% rename from de-DE/README-de_DE.md rename to de-DE/README.md index ccb7fe7a..cc0d3104 100644 --- a/de-DE/README-de_DE.md +++ b/de-DE/README.md @@ -7,21 +7,21 @@ Von einfach bis fortgeschritten: teste wie gut du JavaScript kennst, frische dei Die Antworten sind unterhalb der Fragen versteckt. Du kannst einfach darauf klicken um die Antworten anzuzeigen. Viel Glück :heart: ### Alle verfügbaren Sprachen -* [English](./README.md) -* [العربية](./README_AR.md) -* [اللغة العامية - Egyptian Arabic](./README_ar-EG.md) -* [Bosanski](./README-bs_BS.md) -* [Deutsch](./README-de_DE.md) -* [Español](./README-ES.md) -* [Français](./README_fr-FR.md) -* [日本語](./README-ja_JA.md) -* [한국어](./README-ko_KR.md) -* [Português Brasil](./README_pt_BR.md) -* [Русский](./README_ru-RU.md) -* [Türkçe](./README-tr_TR.md) -* [Українська мова](./README-ua_UA.md) -* [Tiếng Việt](./README-vi.md) -* [中文版本](./README-zh_CN.md) +* [English](../en-EN/README.md) +* [العربية](../ar-AR/README_AR.md) +* [اللغة العامية - Egyptian Arabic](../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) +* [日本語](../ja-JA/README-ja_JA.md) +* [한국어](../ko-KR/README-ko_KR.md) +* [Português Brasil](../pt-BR/README_pt_BR.md) +* [Русский](../ru-RU/README_ru-RU.md) +* [Українська мова](../ua-UA/README-ua_UA.md) +* [Tiếng Việt](../vi-VI/README-vi.md) +* [中文版本](../zh-CN/README-zh_CN.md) +* [Türkçe](../tr-TR/README-tr_TR.md) --- @@ -2201,8 +2201,8 @@ Mit dem `+` Operator können Strings zusammengesetzt werden. In diesem Fall werd ```javascript function* startGame() { - const Answer = yield "Do you love JavaScript?"; - if (Answer !== "Yes") { + const Antwort = yield "Do you love JavaScript?"; + if (Antwort !== "Yes") { return "Oh wow... Guess we're gone here"; } return "JavaScript loves you back ❤️"; @@ -2225,9 +2225,9 @@ console.log(/* 2 */); // JavaScript loves you back ❤️ Eine Generator Funktion pausiert die Ausführung, wenn das `yield` Keyword vorliegt. Zuerst müssen wir den String "Do you love JavaScript?" abwarten, was mit `game.next().value` möglich ist. -Jede Zeile wird ausgeführt, bis das erste `yield` Keyword auftritt. Da auf der ersten Zeile ein `yield` in der Funktion vorliegt wird die Ausführung damit angehalten. Das bedeutet, dass die Variable `Answer` _noch nicht definiert_ wurde. +Jede Zeile wird ausgeführt, bis das erste `yield` Keyword auftritt. Da auf der ersten Zeile ein `yield` in der Funktion vorliegt wird die Ausführung damit angehalten. Das bedeutet, dass die Variable `Antwort` _noch nicht definiert_ wurde. -Wenn wir `game.next("Yes").value` aufrufen wird das vorhergehende `yield` durch den Wert des Parameters ersetzt, der an `next()` übergeben wird - `"Yes"` in diesem Fall. Der Wert der Variable `Answer` ist jetzt gleich `"Yes"`. Das if-Statement gibt `false` aus und `JavaScript loves you back ❤️` wird geloggt. +Wenn wir `game.next("Yes").value` aufrufen wird das vorhergehende `yield` durch den Wert des Parameters ersetzt, der an `next()` übergeben wird - `"Yes"` in diesem Fall. Der Wert der Variable `Antwort` ist jetzt gleich `"Yes"`. Das if-Statement gibt `false` aus und `JavaScript loves you back ❤️` wird geloggt.

@@ -2727,3 +2727,258 @@ Wenn wir `hasName` gleich `name` setzen, so beinhaltet `hasName` den Wert von `n `name.length` gibt die Länge des Arguments aus, nicht den Boolean Wert.

+ + +--- + +###### 87. Was ist der Output? + +```javascript +console.log("I want pizza"[0]) +``` + +- A: `"""` +- B: `"I"` +- C: `SyntaxError` +- D: `undefined` + +
Antwort +

+ +#### Antwort: B + +Um ein Zeichen an einer bestimmten Stelle eines Strings zu bekommen kann man Bracket Notation verwenden. Das erste Zeichen in einem String hat den Index 0, usw. In diesem Fall möchten wir das Zeichen mit dem Index 0, was das Zeichen `"I"` loggt. + +Diese Methode funktioniert nicht in IE7 und davor. Hier muss `.charAt()` verwendet werden. + +

+
+ +--- + +###### 88. Was ist der Output? + +```javascript +function sum(num1, num2 = num1) { + console.log(num1 + num2) +} + +sum(10) +``` + +- A: `NaN` +- B: `20` +- C: `ReferenceError` +- D: `undefined` + +
Antwort +

+ +#### Antwort: B + +Man kann den Wert eines Standard Parameters gleich einem anderen Parameter in der Funktion setzen, sofern diese _vor_ dem Standard Parameter definiert wurden. Wir übergeben den Wert `10` an die `sum` Funktion. Wenn die `sum` Funktion nur ein Argument übergeben bekommt bedeutet das, dass der Wert für `num2` nicht gesetzt wurde und der Wert von `num1` ist gleich dem Wert `10`. Der Standardwert von `num2` ist gleich dem Wert von `num1`, sprich `10`. `num1 + num2` gibt `20` aus. + +Wenn man den Wert des Standard Paramenters gleich dem Parameter setztm der _danach_ definiert wurde, bekommen wir einen Fehler ausgegeben, da der Wert noch nicht initialisiert wurde. + +

+
+ +--- + +###### 89. Was ist der 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: Globales Objekt von `module.js` + +
Antwort +

+ +#### Antwort: A + +Mit `import * as name` importieren wir _alle Exporte_ der `module.js` in `index.js` als `data`. In der Datei `module.js` haben wir zwei Exporte: den Standard Export und einen benannten Export. Der Standard Export ist eine Funktion, die `"Hello World"` ausgibt und der benannte Export ist eine Variable namens `name` mit dem Wert `"Lydia"`. + +Das `data` Objekt hat eine Standard Property für alle Standard Exporte, andere Properties haben die Namen des benannten Exports und der entsprechenden Werte. + +

+
+ +--- + +###### 90. Was ist der Output? + +```javascript +class Person { + constructor(name) { + this.name = name + } +} + +const member = Person("John") +console.log(typeof member) +``` + +- A: `"class"` +- B: `"function"` +- C: `"object"` +- D: `"string"` + +
Antwort +

+ +#### Antwort: C + +Klassen sind syntaktischer Zucker für Funktionskontruktoren. Das Equivalent der `Person` Klasse als Funktionskonstruktor wäre: + +```javascript +function Person() { + this.name = name +} +``` + +Das Aufrufen eines Funktionskonstruktors mit `new` hat zur Folge, dass eine Instanz von `Person` erstellt wird. `typeof` gibt `"object"` für die instanz aus. `typeof member` gibt `"object"` aus. + +

+
+ +--- + +###### 91. Was ist der 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` + +
Antwort +

+ +#### Antwort: D + +Die `.push` Methode gibt die _neue Länge_ des Arrays aus, nicht die Länge des Arrays selbst. Wenn wir `newList` gleich `[1, 2, 3].push(4)` setzen, setzen wir `newList` auch gleich der Länge des Arrays: `4`. + +Dann versuchen wir die `.push` Methode auf `newList` anzuwenden. Da `newList` den numerischen Wert `4` beinhaltet können wir die `.push` Methode nicht anwenden: ein TypeError wird ausgegeben. + +

+
+ +--- + +###### 92. Was ist der 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` + +
Antwort +

+ +#### Antwort: D + +Reguläre Funktionen wie `giveLydiaPizza` haben eine `prototype` Property, die ein Objekt (Prototype Object) mit einem `constructor` ist. Arrow Funktionen dagegen (wie `giveLydiaChocolate`) haben keinen `prototype`. `undefined` wird ausgegeben, wenn wir versuchen den `prototype` mit `giveLydiaChocolate.prototype` aufzurufen. + +

+
+ +--- + +###### 93. Was ist der Output? + +```javascript +const person = { + name: "Lydia", + age: 21 +} + +for (const [x, y] of Object.entries(person)) { + console.log(x, y) +} +``` + +- A: `name` `Lydia` und `age` `21` +- B: `["name", "Lydia"]` und `["age", 21]` +- C: `["name", "age"]` und `undefined` +- D: `Error` + +
Antwort +

+ +#### Antwort: A + +`Object.entries(person)` gibt ein Array mit verschachtelten Arrays der Keys aus: + +`[ [ 'name', 'Lydia' ], [ 'age', 21 ] ]` + +Mit der `for-of` Schleife iterieren wir über jedes Element in dem Array, in diesem Fall die verschachtelten Arrays. Wir können die verschachtelten Arrays mit `const [x, y]` in der for-of Schleife destrukturieren. `x` ist gleich dem ersten Element, `y` ist gleich dem zweiten Element in dem verschachtelten Array. + +Das erste verschachtelte Array ist `[ "name", "Lydia" ]`. `x` ist gleich `"name"` und `y` gleich `"Lydia"`, was geloggt wird. +Das zweite verschachtelte Array ist `[ "age", 21 ]`. `x` ist gleich `"age"` und `y` ist gleich `21`, was geloggt wird. + +

+
+ +--- + +###### 94. Was ist der 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` + +
Antwort +

+ +#### Antwort: D + +`...args` ist ein Rest-Parameter. Der Wert des Rest-Parameters ist ein Array mit allen weiteren Argumenten **und kann nur der letzte Parameter sein**! In diesem Beispiel war der Rest-Parameter das zweite Argument, was nicht möglich ist und daher einen Syntax Error ausgibt. + +```javascript +function getItems(fruitList, favoriteFruit, ...args) { + return [...fruitList, ...args, favoriteFruit] +} + +getItems(["banana", "apple"], "pear", "orange") +``` + +Dieses Beispiel würde funktionieren und `[ 'banana', 'apple', 'orange', 'pear' ]` ausgeben. +

+
From e89695b368929a4d6af3c3a00e0c690666dafd6d Mon Sep 17 00:00:00 2001 From: Jacob Herper Date: Tue, 6 Aug 2019 11:47:50 +0100 Subject: [PATCH 284/915] Changed link for German to reference README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index ac52621a..dad5b9bd 100644 --- a/README.md +++ b/README.md @@ -15,7 +15,7 @@ List of available languages: * [العربية](./ar-AR/README_AR.md) * [اللغة العامية - Egyptian Arabic](./ar-EG/README_ar-EG.md) * [Bosanski](./bs-BS/README-bs_BS.md) -* [Deutsch](./de-DE/README-de_DE.md) +* [Deutsch](./de-DE/README.md) * [Español](./es-ES/README-ES.md) * [Français](./fr-FR/README_fr-FR.md) * [日本語](./ja-JA/README-ja_JA.md) From 7a4c1621e0ebd89bb8b9350efb72657bf8da130e Mon Sep 17 00:00:00 2001 From: Jacob Herper Date: Tue, 6 Aug 2019 18:53:46 +0100 Subject: [PATCH 285/915] `new` keyword added to question 90 --- de-DE/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/de-DE/README.md b/de-DE/README.md index cc0d3104..7bf11cf1 100644 --- a/de-DE/README.md +++ b/de-DE/README.md @@ -2826,7 +2826,7 @@ class Person { } } -const member = Person("John") +const member = new Person("John") console.log(typeof member) ``` From d81e7cf735b66619499ff4abab721e1409deafde Mon Sep 17 00:00:00 2001 From: Jacob Herper Date: Tue, 6 Aug 2019 18:55:31 +0100 Subject: [PATCH 286/915] `new` Keyword added to question 90 --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index ac52621a..d28dd02d 100644 --- a/README.md +++ b/README.md @@ -2826,7 +2826,7 @@ class Person { } } -const member = Person("John") +const member = new Person("John") console.log(typeof member) ``` From f8b206298764d06db7eeb20cb15d48776bb26f1a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Samuel=20Espinosa=20Mart=C3=ADnez?= <50044493+saespmar@users.noreply.github.com> Date: Tue, 6 Aug 2019 20:04:14 +0200 Subject: [PATCH 287/915] Fix typo --- es-ES/README-ES.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/es-ES/README-ES.md b/es-ES/README-ES.md index 476bbbe9..b4fb5d76 100644 --- a/es-ES/README-ES.md +++ b/es-ES/README-ES.md @@ -2824,7 +2824,7 @@ class Person { } } -const member = Person("John") +const member = new Person("John") console.log(typeof member) ``` From c281788385c2134ed6585ae63448b8e0e61a58c8 Mon Sep 17 00:00:00 2001 From: Alexander Ivanov Date: Wed, 7 Aug 2019 07:38:56 +0300 Subject: [PATCH 288/915] Fix a typo Signed-off-by: Alexander Ivanov --- ru-RU/README_ru-RU.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ru-RU/README_ru-RU.md b/ru-RU/README_ru-RU.md index ae3e1914..9c095807 100644 --- a/ru-RU/README_ru-RU.md +++ b/ru-RU/README_ru-RU.md @@ -2826,7 +2826,7 @@ class Person { } } -const member = Person("John") +const member = new Person("John") console.log(typeof member) ``` From f7a4991a9c5885ff7bd048f65cc3f1b7cd88feca Mon Sep 17 00:00:00 2001 From: lazy <310195875@qq.com> Date: Thu, 8 Aug 2019 15:48:36 +0800 Subject: [PATCH 289/915] translate zh-CN:question 87-94 --- zh-CN/README-zh_CN.md | 259 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 259 insertions(+) diff --git a/zh-CN/README-zh_CN.md b/zh-CN/README-zh_CN.md index d5898cc5..db9a47ff 100644 --- a/zh-CN/README-zh_CN.md +++ b/zh-CN/README-zh_CN.md @@ -2719,3 +2719,262 @@ function getName(name) {

+ +###### 87. 输出什么? + +```javascript +console.log("I want pizza"[0]) +``` + +- A: `"""` +- B: `"I"` +- C: `SyntaxError` +- D: `undefined` + +
答案 +

+ +#### 答案: B + +可以使用方括号表示法获取字符串中特定索引的字符,字符串中的第一个字符具有索引0,依此类推。 在这种情况下,我们想要得到索引为0的元素,字符`'I'`被记录。 + +请注意,IE7及更低版本不支持此方法。 在这种情况下,应该使用`.charAt()` + +

+
+ +--- + +###### 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 +``` + +

+
+ +--- + +###### 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的名称及其对应的值。 + +

+
+ +--- + +###### 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 + +类是构造函数的语法糖,如果用构造函数的方式来重写`Person`类则将是: + +```javascript +function Person() { + this.name = name +} +``` + +通过`new`来调用构造函数,将会生成构造函数`Person`的实例,对实例执行`typeof`关键字将返回`"object"`,上述情况打印出`"object"`。 + +

+
+ +--- + +###### 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。 + +

+
+ +--- + +###### 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`。 + +

+
+ +--- + +###### 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`。 + +

+
+ +--- + +###### 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' ]` +

+
From 6985d47a9c8c8be3871866737894b3399239ce93 Mon Sep 17 00:00:00 2001 From: lazy <310195875@qq.com> Date: Thu, 8 Aug 2019 16:12:22 +0800 Subject: [PATCH 290/915] typo --- 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 db9a47ff..b167a777 100644 --- a/zh-CN/README-zh_CN.md +++ b/zh-CN/README-zh_CN.md @@ -2937,8 +2937,8 @@ for (const [x, y] of Object.entries(person)) { 使用`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`。

From f54355a4049c82a3c87d7eb4e2f6d56a6cf01fca Mon Sep 17 00:00:00 2001 From: Alexander Ivanov Date: Sun, 11 Aug 2019 06:59:18 +0300 Subject: [PATCH 291/915] Q52. Consistent options --- README.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index ae6283a4..287500f3 100644 --- a/README.md +++ b/README.md @@ -1575,17 +1575,17 @@ function sayHi() { 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(); ``` -- A: `"It worked! Hello world!"` -- B: `"Oh no an error: undefined` +- 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!` +- D: `Oh no an error: Hello world!`
Answer

From 2e560e3afbfaced676fd3aed6bb4e200fbd3e4ba Mon Sep 17 00:00:00 2001 From: Alexander Ivanov Date: Sun, 11 Aug 2019 07:12:08 +0300 Subject: [PATCH 292/915] en-EN Signed-off-by: Alexander Ivanov --- en-EN/README.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/en-EN/README.md b/en-EN/README.md index 6db3d2ab..de2a403c 100644 --- a/en-EN/README.md +++ b/en-EN/README.md @@ -1575,17 +1575,17 @@ function sayHi() { 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(); ``` -- A: `"It worked! Hello world!"` -- B: `"Oh no an error: undefined` +- 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!` +- D: `Oh no an error: Hello world!`

Answer

From e6233a92f663589511bc61f3bcdc273ad5738f32 Mon Sep 17 00:00:00 2001 From: Alexander Ivanov Date: Sun, 11 Aug 2019 07:16:04 +0300 Subject: [PATCH 293/915] Sync EN files --- en-EN/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/en-EN/README.md b/en-EN/README.md index 6db3d2ab..d2bf1b3f 100644 --- a/en-EN/README.md +++ b/en-EN/README.md @@ -2826,7 +2826,7 @@ class Person { } } -const member = Person("John") +const member = new Person("John") console.log(typeof member) ``` From 5540b52964a9bce20254aa0f3de1fcd4a2e47786 Mon Sep 17 00:00:00 2001 From: yusufkaracin Date: Wed, 14 Aug 2019 21:12:35 +0300 Subject: [PATCH 294/915] Syncs to August 5th --- tr-TR/README-tr_TR.md | 256 +++++++++++++++++++++++++++++++++++++++++- 1 file changed, 255 insertions(+), 1 deletion(-) diff --git a/tr-TR/README-tr_TR.md b/tr-TR/README-tr_TR.md index 0b8fd6ba..3cfafdd9 100644 --- a/tr-TR/README-tr_TR.md +++ b/tr-TR/README-tr_TR.md @@ -2,7 +2,7 @@ [Instagram](https://www.instagram.com/theavocoder) hesabımda, günlük olarak çoktan seçmeli Javascript soruları paylaşıyorum, ayrıca burada da paylaşacağım! -Temelden ileri düzeye: Javascript'i ne kadar iyi bildiğinizi test edin, bilginizi biraz tazeleyin ya da mülakatanıza hazırlanın! :muscle: :rocket: Repoyu haftalık olarak yeni sorularla güncelliyorum. Son güncelleme: 26 Temmuz +Temelden ileri düzeye: Javascript'i ne kadar iyi bildiğinizi test edin, bilginizi biraz tazeleyin ya da mülakatanıza hazırlanın! :muscle: :rocket: Repoyu haftalık olarak yeni sorularla güncelliyorum. Son güncelleme: 5 Ağustos Cevaplar, soruların altında gizlenmiştir. Görmek için sadece tıklayın. İyi şanşlar :heart: @@ -2717,3 +2717,257 @@ function getName(name) {

+ +--- + +###### 87. Çıktısı Nedir? + +```javascript +console.log("I want pizza"[0]) +``` + +- A: `"""` +- B: `"I"` +- C: `SyntaxError` +- D: `undefined` + +
Cevap +

+ +#### Cevap: B + +Bir string içindeki belli bir indeksteki karakteri almak için, köşeli parantez notasyonunu kullanabilirsiniz. String içindeki ilk karakterin indeksi 0'dır, ve böylece devam eder. Bu örnekte indeksi 0 olan elemanı istiyoruz, `"I"` karakteri, loglanır. + +Bu yöntemin IE7 ve altında desteklenmediğine dikkat edin. Bu durumda, `.charAt()` kullanabilirsiniz. + +

+
+ +--- + +###### 88. Çıktısı Nedir? + +```javascript +function sum(num1, num2 = num1) { + console.log(num1 + num2) +} + +sum(10) +``` + +- A: `NaN` +- B: `20` +- C: `ReferenceError` +- D: `undefined` + +
Cevap +

+ +#### Cevap: 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, amd 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. Çıktısı Nedir? + +```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` + +
Cevap +

+ +#### Cevap: 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. Çıktısı Nedir? + +```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"` + +
Cevap +

+ +#### Cevap: C + +Classes are syntactical sugar for function constructors. The equivalent of the `Person` class as a function constructor would be: + +```javascript +function Person() { + 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. Çıktısı Nedir? + +```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` + +
Cevap +

+ +#### Cevap: 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. Çıktısı Nedir? + +```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` + +
Cevap +

+ +#### Cevap: 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. Çıktısı Nedir? + +```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` + +
Cevap +

+ +#### Cevap: 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. Çıktısı Nedir? + +```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` + +
Cevap +

+ +#### Cevap: 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' ]` +

+
From 85d4fca34f8232328790d01e651ee1ece40dd7f4 Mon Sep 17 00:00:00 2001 From: yusufkaracin Date: Wed, 14 Aug 2019 21:47:27 +0300 Subject: [PATCH 295/915] Translates 88-91 --- tr-TR/README-tr_TR.md | 20 ++++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/tr-TR/README-tr_TR.md b/tr-TR/README-tr_TR.md index 3cfafdd9..d2238af2 100644 --- a/tr-TR/README-tr_TR.md +++ b/tr-TR/README-tr_TR.md @@ -2765,9 +2765,9 @@ sum(10) #### Cevap: 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, amd 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. +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.

@@ -2790,16 +2790,16 @@ 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` +- D: `module.js`'e ait global nesne
Cevap

#### Cevap: 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"`. +`import * as name` yazımı ile, `module.js` dosyası içindeki _tüm `export`'ları_ `index.js` dosyası içinde `data` olarak adlandırdığımız yeni bir nesneye aktarıyoruz. `module.js` dosyası içinde, iki `export` var: varsayılan export ve isimlendirilmiş export. Varsayılan export `"Hello World"` string'i döndüren bir fonksiyon ve isimlendirilmiş export `"Lydia"` değerine sahip `name` olarak isimlendirilmiş değişken. -The `data` object has a `default` property for the default export, other properties have the names of the named exports and their corresponding values. +`data` nesnesi varsayılan exportlar için `default` özelliğine, isilendirilmiş exportlar için isimlendirilmiş export'un ismi olan ve değeri isimlendirilmiş export'un değeri olan özelliklere sahiptir.

@@ -2829,7 +2829,7 @@ console.log(typeof member) #### Cevap: C -Classes are syntactical sugar for function constructors. The equivalent of the `Person` class as a function constructor would be: +Sınıflar fonksiyon yapıcıları için "syntactical sugar"dır. `Person` sınıfına denk olan sınıf yapıcısı şöyle olabilirdi: ```javascript function Person() { @@ -2837,7 +2837,7 @@ function Person() { } ``` -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"`. +Bir fonksiyon yapıcısını `new` ile çağırmak `Person` "instance" oluşturur, `typeof` anahtar kelimesi instance için `"object"` döndürür. `typeof member` `"object"` döndürür.

@@ -2862,9 +2862,9 @@ console.log(newList.push(5)) #### Cevap: 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`. +`.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`. -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. +Sonra, `.push` methodunu `newList` üzerinde kullanmayo denedik. `newList` sayısal değer `4` olduğundan, `.push` methodunu kullanamayız: TypeError fırlatılır.

From 5291fd1b8422fb698455693a00bd1dcb4d93484c Mon Sep 17 00:00:00 2001 From: yusufkaracin Date: Thu, 15 Aug 2019 20:49:06 +0300 Subject: [PATCH 296/915] Translates 91-94 --- tr-TR/README-tr_TR.md | 15 ++++++++------- 1 file changed, 8 insertions(+), 7 deletions(-) diff --git a/tr-TR/README-tr_TR.md b/tr-TR/README-tr_TR.md index d2238af2..df9c424f 100644 --- a/tr-TR/README-tr_TR.md +++ b/tr-TR/README-tr_TR.md @@ -2894,7 +2894,7 @@ console.log(giveLydiaChocolate.prototype) #### Cevap: 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`. +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.

@@ -2924,14 +2924,14 @@ for (const [x, y] of Object.entries(person)) { #### Cevap: A -`Object.entries(person)` returns an array of nested arrays, containing the keys and objects: +`Object.entries(person)` key ve nesneleri içeren dizilerden oluşan dizi döndürür: `[ [ '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. +`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. -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. +İlk alt dizi `[ "name", "Lydia" ]`, `x` `"name"`'e ve `y` `"Lydia"`'ya eşittir. +İkinci alt dizi `[ "age", 21 ]`, `x` `"age"`'e ve `y` `21`'a eşittir.

@@ -2958,7 +2958,7 @@ getItems(["banana", "apple"], "pear", "orange") #### Cevap: 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` bir "rest" parametredir. "Rest" parametresinin değeri geriye kalan tüm argümanları içeren bir dizidir, ve **sadece son parametre olabilir.** Bu örnekte, rest parametresi ikindi parametreydi. Bu mümkün değildir ve syntax hatası fırlatılacaktır. ```javascript function getItems(fruitList, favoriteFruit, ...args) { @@ -2968,6 +2968,7 @@ function getItems(fruitList, favoriteFruit, ...args) { getItems(["banana", "apple"], "pear", "orange") ``` -The above example works. This returns the array `[ 'banana', 'apple', 'orange', 'pear' ]` +Yukarıdaki örnek çalışır. `[ 'banana', 'apple', 'orange', 'pear' ]` dizisini döndürür. +

From 9c260c437a7bd3c2d9af22f26071a350f282407c Mon Sep 17 00:00:00 2001 From: Lydia Hallie Date: Sat, 17 Aug 2019 16:13:39 +0200 Subject: [PATCH 297/915] Add questions 95-101 --- README.md | 242 +++++++++++++++++++++++++++++++++++++++++++++++- en-EN/README.md | 242 +++++++++++++++++++++++++++++++++++++++++++++++- 2 files changed, 482 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 1966f65a..562836f6 100644 --- a/README.md +++ b/README.md @@ -2,7 +2,7 @@ I post daily multiple choice JavaScript questions on my [Instagram](https://www.instagram.com/theavocoder), which I'll also post 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 weekly with new questions. Last update: July 26th +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 weekly with new questions. Last update: August 17th The answers are in the collapsed sections below the questions, simply click on them to expand it. Good luck :heart: @@ -3014,5 +3014,245 @@ getItems(["banana", "apple"], "pear", "orange") ``` The above example works. This returns the array `[ 'banana', 'apple', 'orange', 'pear' ]` +

+
+ +--- + +###### 95. What's the 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` + +
Answer +

+ +#### Answer: 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. What's the 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` + +
Answer +

+ +#### Answer: 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. What's the output? + +```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 `[]` + +
Answer +

+ +#### Answer: 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. What's the 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]]` 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 }` + +
Answer +

+ +#### Answer: 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, containig 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: + +```const getUser = user => ({ name: user.name, age: user.age })``` + +Since no value gets returned in this case, the function returns `undefined`. + +

+
+ +--- + +###### 99. What's the output? + +```javascript +const name = "Lydia" + +console.log(name()) +``` + +- A: `SyntaxError` +- B: `ReferenceError` +- C: `TypeError` +- D: `undefined` + +
Answer +

+ +#### Answer: C + +The variable `name` holds the value of a string, which is not a function, thus cannot invoke. + +TypeErrors get thrown wehn 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` + +
Answer +

+ +#### Answer: 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` + +
Answer +

+ +#### Answer: 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 past 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 `[]`. +

\ No newline at end of file diff --git a/en-EN/README.md b/en-EN/README.md index e25b9ce6..2d7557f2 100644 --- a/en-EN/README.md +++ b/en-EN/README.md @@ -2,7 +2,7 @@ I post daily multiple choice JavaScript questions on my [Instagram](https://www.instagram.com/theavocoder), which I'll also post 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 weekly with new questions. Last update: July 26th +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 weekly with new questions. Last update: August 17th The answers are in the collapsed sections below the questions, simply click on them to expand it. Good luck :heart: @@ -3014,5 +3014,245 @@ getItems(["banana", "apple"], "pear", "orange") ``` The above example works. This returns the array `[ 'banana', 'apple', 'orange', 'pear' ]` +

+
+ +--- + +###### 95. What's the 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` + +
Answer +

+ +#### Answer: 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. What's the 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` + +
Answer +

+ +#### Answer: 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. What's the output? + +```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 `[]` + +
Answer +

+ +#### Answer: 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. What's the 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]]` 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 }` + +
Answer +

+ +#### Answer: 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, containig 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: + +```const getUser = user => ({ name: user.name, age: user.age })``` + +Since no value gets returned in this case, the function returns `undefined`. + +

+
+ +--- + +###### 99. What's the output? + +```javascript +const name = "Lydia" + +console.log(name()) +``` + +- A: `SyntaxError` +- B: `ReferenceError` +- C: `TypeError` +- D: `undefined` + +
Answer +

+ +#### Answer: C + +The variable `name` holds the value of a string, which is not a function, thus cannot invoke. + +TypeErrors get thrown wehn 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` + +
Answer +

+ +#### Answer: 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` + +
Answer +

+ +#### Answer: 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 past 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 `[]`. +

\ No newline at end of file From a334cbc6ed8d5ed3834bc6a2a074257771e1598a Mon Sep 17 00:00:00 2001 From: Jacob Herper Date: Sat, 17 Aug 2019 17:17:27 +0100 Subject: [PATCH 298/915] Questions 95 - 101 translated to German --- de-DE/README.md | 257 ++++++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 250 insertions(+), 7 deletions(-) diff --git a/de-DE/README.md b/de-DE/README.md index 7bf11cf1..529f825a 100644 --- a/de-DE/README.md +++ b/de-DE/README.md @@ -9,7 +9,7 @@ Die Antworten sind unterhalb der Fragen versteckt. Du kannst einfach darauf klic ### Alle verfügbaren Sprachen * [English](../en-EN/README.md) * [العربية](../ar-AR/README_AR.md) -* [اللغة العامية - Egyptian Arabic](../ar-EG/README_ar-EG.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) @@ -18,10 +18,10 @@ Die Antworten sind unterhalb der Fragen versteckt. Du kannst einfach darauf klic * [한국어](../ko-KR/README-ko_KR.md) * [Português Brasil](../pt-BR/README_pt_BR.md) * [Русский](../ru-RU/README_ru-RU.md) +* [Türkçe](../tr-TR/README-tr_TR.md) * [Українська мова](../ua-UA/README-ua_UA.md) * [Tiếng Việt](../vi-VI/README-vi.md) * [中文版本](../zh-CN/README-zh_CN.md) -* [Türkçe](../tr-TR/README-tr_TR.md) --- @@ -1324,7 +1324,7 @@ console.log(gen.next().value); - A: `[0, 10], [10, 20]` - B: `20, 20` - C: `10, 20` -- D: `0, 10 and 10, 20` +- D: `0, 10 und 10, 20`
Antwort

@@ -2011,10 +2011,10 @@ Beim vierten Mal übergeben wir wieder eine `value`. `x.number` wurde zuvor in ` [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` +- A: `1` `2` und `3` `3` und `6` `4` +- B: `1` `2` und `2` `3` und `3` `4` +- C: `1` `undefined` und `2` `undefined` und `3` `undefined` und `4` `undefined` +- D: `1` `2` und `undefined` `3` und `undefined` `4`

Antwort

@@ -2982,3 +2982,246 @@ getItems(["banana", "apple"], "pear", "orange") Dieses Beispiel würde funktionieren und `[ 'banana', 'apple', 'orange', 'pear' ]` ausgeben.

+ +--- + +###### 95. Was ist der 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` und `b is bigger`, `3` +- B: `a is bigger`, `undefined` und `b is bigger`, `undefined` +- C: `undefined` und `undefined` +- D: `SyntaxError` + +
Antwort +

+ +#### Antwort: B + +In JavaScript muss das Semikolon _nicht_ explizit gesetzt werden, allerdings setzt die JavaScript Engine Semikolons nach Statements. Diesen Vorgang nennt man **automatische Semikolonsetzung**. Ein Statement ist zum Beispiel eine Variable oder ein Keyword wie `throw`, `return`, `break`, usw. + +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 +``` + +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. +Bedenke: Semikolons werden **nicht** automatisch nach `if/else` Statements gesetzt! + +

+
+ +--- + +###### 96. Was ist der 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` + +
Antwort +

+ +#### Antwort: B + +Wir können Klassen gleich anderen Klassen oder Funktions Konstruktoren setzen. In diesem Beispiel setzen wir `Person` gleich `AnotherPerson`. Der Name in diesem Konstruktor ist `Sarah`, sodass die name-Property der neuen `Person` Instanz `member` gleich `"Sarah"` ist. + +

+
+ +--- + +###### 97. Was ist der Output? + +```javascript +const info = { + [Symbol('a')]: 'b' +} + +console.log(info) +console.log(Object.keys(info)) +``` + +- A: `{Symbol('a'): 'b'}` und `["{Symbol('a')"]` +- B: `{}` und `[]` +- C: `{ a: "b" }` und `["a"]` +- D: `{Symbol('a'): 'b'}` und `[]` + +
Antwort +

+ +#### Antwort: D + +Ein Symbol ist nicht _zählbar_. Die `Object.keys` Methode gibt alle zählbaren Key Properties eines Objekts aus. Das Symbol ist nicht sichtbar, sodass ein leeres Array ausgegeben wird. Wenn wir das gesamte Objekt loggen sind alle Properties sichtbar, auch nicht zählbare. + +Das ist einer der vielen Vorteile eines Symbols: nebem einem einzigartigen Wert (welcher verhindert, dass versehentlich zwei Objekte gleiche Namen haben, zum Beispiel wenn wir mit verschiedenen Libraries arbeiten) können Properties von Objekten auf diese Art versteckt werden. +Bedenke: Man kann die Symbole dennoch mit der `Object.getOwnPropertySymbols()` Methode einsehen. + +

+
+ +--- + +###### 98. Was ist der 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]]` und `undefined` +- B: `[1, [2, 3, 4]]` und `{ name: "Lydia", age: 21 }` +- C: `[1, 2, 3, 4]` und `{ name: "Lydia", age: 21 }` +- D: `Error` und `{ name: "Lydia", age: 21 }` + +
Antwort +

+ +#### Antwort: A + +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]` + +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 })``` + +Da kein Wert ausgegeben wird, gibt die Funktion `undefined` aus. + +

+
+ +--- + +###### 99. Was ist der Output? + +```javascript +const name = "Lydia" + +console.log(name()) +``` + +- A: `SyntaxError` +- B: `ReferenceError` +- C: `TypeError` +- D: `undefined` + +
Antwort +

+ +#### Antwort: C + +Die Variable `name` beinhaltet einen String, welcher logischer Weise keine Funktion ist und daher nicht ausgeführt werden kann. + +TypeErrors werden ausgeworfen, wenn ein Wert einen falschen Typ aufweist. JavaScript hat eine Funktion erwartet, da wir `name` ausführen. Da es aber ein String war bekommen wir den TypeError: name is not a function! + +SyntaxErrors werden ausgeworfen, wenn wir etwas schreiben, was kein gültiger JavaScript Code ist, zum Beispiel wenn wir uns vertippen und anstatt `return` `retrun` schreiben. + +ReferenceErrors werden ausgeworfen, wenn JavaScript eine Referenz zu einem Wert nicht finden kann. + +

+
+ +--- + +###### 100. Was ist der Output? + +```javascript +// 🎉✨ Das ist unsere 100. Frage! ✨🎉 + +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` + +
Antwort +

+ +#### Antwort: B + +`[]` ist ein "truthy" Wert. Mit dem `&&` Operator geben wir den rechten Wert aus, wenn der linke truthy ist. In diesem Fall ist `[]` truthy, wodurch `"Im'` ausgegeben wird. + +`""` ein ein "falsy" Wert. Wenn der linke Wert falsy ist wird nichts ausgegeben. In diesem Fall wird `n't` _nicht_ ausgegeben. + +

+
+ +--- + +###### 101. Was ist der 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` + +
Antwort +

+ +#### Antwort: C + +Mit dem `||` Operator geben wir den ersten truthy Operand aus. Wenn alle Werte falsy sind wird der letzte Operand ausgegeben. + +`(false || {} || null)`: das leere Objekt `{}` ist truthy. Das ist der erste und einzige truthy Wert und wird daher ausgegeben. `one` ist gleich `{}`. + +`(null || false || "")`: alle Operanden sind falsy. Das bedeutet, dass der letzte Wert `""` ausgegeben wird. `two` ist gleich `""`. + +`([] || 0 || "")`: das leere Array `[]` ist truthy. Das ist der erste truthy Wert, und wird daher ausgegeben. `three` ist gleich `[]`. + +

+
From 99f0e035d0cca72dad82df3c84cdd1ec4d4615b2 Mon Sep 17 00:00:00 2001 From: Jacob Herper Date: Sat, 17 Aug 2019 17:26:19 +0100 Subject: [PATCH 299/915] Some typos fixed --- en-EN/README.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/en-EN/README.md b/en-EN/README.md index 2221ea9c..c665ae33 100644 --- a/en-EN/README.md +++ b/en-EN/README.md @@ -2718,7 +2718,7 @@ function getName(name) { #### Answer: A -With `!!name`, we determine whether the value of `name` is truthy or falsey. 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 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`. @@ -3121,7 +3121,7 @@ The `getList` function receives an array as its argument. Between the parenthese `[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, containig 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` 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: @@ -3154,7 +3154,7 @@ console.log(name()) The variable `name` holds the value of a string, which is not a function, thus cannot invoke. -TypeErrors get thrown wehn 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! +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. From def44b36208d680cf15f84f3bcf5362164fa25b3 Mon Sep 17 00:00:00 2001 From: lishiqi Date: Sun, 18 Aug 2019 00:42:50 +0800 Subject: [PATCH 300/915] Translate the question 95 - 101 into Chinese --- zh-CN/README-zh_CN.md | 247 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 247 insertions(+) diff --git a/zh-CN/README-zh_CN.md b/zh-CN/README-zh_CN.md index b167a777..aa1fc51d 100644 --- a/zh-CN/README-zh_CN.md +++ b/zh-CN/README-zh_CN.md @@ -2978,3 +2978,250 @@ getItems(["banana", "apple"], "pear", "orange") 上述例子是有效的,将会返回数组:`[ 'banana', 'apple', 'orange', 'pear' ]`

+ + + +###### 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`语句之后没有自动插入! + +

+
+ +--- + +###### 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 + + +我们可以将类设置为等于其他类/函数构造函数。 在这种情况下,我们将`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`。 + +

+
+ +--- + +###### 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`。 + +

+
+ +--- + +###### 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`。 + +

+
+ +--- + +###### 100. 输出什么? + +```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` + +
答案 +

+ +#### 答案: B + + +`[]`是一个真值。 使用`&&`运算符,如果左侧值是真值,则返回右侧值。 在这种情况下,左侧值`[]`是一个真值,所以返回`Im`。 + +`""`是一个假值。 如果左侧值是假的,则不返回任何内容。 `n't`不会被退回。 + +

+
+ +--- + +###### 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`等于`[]`。 + +

+
From 1255b2a90f7d016abaacc371ba8b70fac791ae1c Mon Sep 17 00:00:00 2001 From: Alexander Ivanov Date: Sun, 18 Aug 2019 07:08:22 +0300 Subject: [PATCH 301/915] Russian. Updates 2019-08/2 --- ru-RU/{README_ru-RU.md => README.md} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename ru-RU/{README_ru-RU.md => README.md} (100%) diff --git a/ru-RU/README_ru-RU.md b/ru-RU/README.md similarity index 100% rename from ru-RU/README_ru-RU.md rename to ru-RU/README.md From 9230cb028ac55455bdf7849daf01a4fb0a4ef27a Mon Sep 17 00:00:00 2001 From: Alexander Ivanov Date: Sun, 18 Aug 2019 07:10:44 +0300 Subject: [PATCH 302/915] Sync edits with #207 Signed-off-by: Alexander Ivanov --- ru-RU/README.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/ru-RU/README.md b/ru-RU/README.md index c03d087b..4cd35c31 100644 --- a/ru-RU/README.md +++ b/ru-RU/README.md @@ -1575,17 +1575,17 @@ function sayHi() { 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(); ``` -- A: `"It worked! Hello world!"` -- B: `"Oh no an error: undefined` +- 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!` +- D: `Oh no an error: Hello world!`
Ответ

From 91b1a158d519513d74789627ca852227ce7d9278 Mon Sep 17 00:00:00 2001 From: Alexander Ivanov Date: Sun, 18 Aug 2019 07:53:36 +0300 Subject: [PATCH 303/915] Translate Q95-101 Signed-off-by: Alexander Ivanov --- ru-RU/README.md | 244 +++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 242 insertions(+), 2 deletions(-) diff --git a/ru-RU/README.md b/ru-RU/README.md index 4a909307..33bf0ac1 100644 --- a/ru-RU/README.md +++ b/ru-RU/README.md @@ -2,7 +2,7 @@ Я ежедневно публикую вопросы по JavaScript с вариантами ответов в своем [Instagram](https://www.instagram.com/theavocoder), которые дублируются в этом репозитории. -От базового до продвинутого: проверьте, насколько хорошо вы знаете JavaScript, немного освежите свои знания или подготовьтесь к собеседованию! :muscle: :rocket: Я обновляю репозиторий еженедельно новыми вопросами. Последнее обновление: 26 июля +От базового до продвинутого: проверьте, насколько хорошо вы знаете JavaScript, немного освежите свои знания или подготовьтесь к собеседованию! :muscle: :rocket: Я обновляю репозиторий еженедельно новыми вопросами. Последнее обновление: 17 августа. Ответы находятся в свернутой секции ниже вопросов. Просто нажми на "Ответ", чтобы развернуть. Удачи! :heart: @@ -2731,7 +2731,7 @@ function getName(name) { --- -###### 87. Какой будет вывод? +###### 87. Какой будет вывод? ```javascript console.log("I want pizza"[0]) @@ -2982,3 +2982,243 @@ getItems(["banana", "apple"], "pear", "orange") Приведенный выше пример работает. Это возвращает массив `[ 'banana', 'apple', 'orange', 'pear' ]`

+ +--- + +###### 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` автоматической вставки нет! + +

+
+ +--- + +###### 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 + +Мы можем установить классы равными другим классам/конструкторам функций. В этом случае мы устанавливаем `Person` равным `AnotherPerson`. Свойство `name` этого конструктора - `Sarah`, поэтому свойство `name` для нового экземпляра класса `Person` `member` - это `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` не просматривается таким образом, и возвращается пустой массив. При регистрации всего объекта будут видны все свойства, даже не перечисляемые. + +Это одно из многих качеств символа: помимо представления совершенно уникального значения (которое предотвращает случайное столкновение имен в объектах, например, при работе с 2 библиотеками, которые хотят добавить свойства к одному и тому же объекту), вы также можете "скрыть" свойства объектов таким образом (хотя и не полностью. Вы можете получить доступ к символам, используя метод `Object.getOwnPropertySymbols()`). + +

+
+ +--- + +###### 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 +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: +Функция `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`. + +

+
+ +--- + +###### 99. Какой будет вывод? + +```javascript +const name = "Lydia" + +console.log(name()) +``` + +- A: `SyntaxError` +- B: `ReferenceError` +- C: `TypeError` +- D: `undefined` + +
Ответ +

+ +#### Ответ: C + +Переменная `name` содержит значение строки, которая не является функцией, поэтому не может вызываться. + +Ошибки типа выдаются, когда значение не соответствует ожидаемому типу. JavaScript ожидал, что `name` будет функцией, так как мы пытаемся вызвать ее. Однако это была строка, поэтому выдается ошибка TypeError: name не является функцией! + +Синтаксические ошибки генерируются, когда вы написали что-то, что не является допустимым JavaScript, например, когда вы написали слово `return` как `retrun`. +ReferenceErrors генерируется, когда JavaScript не может найти ссылку на значение, к которому вы пытаетесь получить доступ. + +

+
+ +--- + +###### 100. Какое значение будет на выходе? + +```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` + +
Ответ +

+ +#### Ответ: B + +`[]` - истинное значение. С оператором `&&` будет возвращено правое значение, если левое значение является истинным значением. В этом случае левое значение `[]` является истинным значением, поэтому возвращается `'Im'`. + +`""` - ложное значение. Если левое значение ложно, ничего не возвращается. `n't` не возвращается. + +

+
+ +--- + +###### 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` присвоено `[]`. + +

+
From 5981c65a25b78642996c20ac8fa0aa3c61f4ffe5 Mon Sep 17 00:00:00 2001 From: Alexander Ivanov Date: Sun, 18 Aug 2019 07:58:19 +0300 Subject: [PATCH 304/915] Remove end spaces Signed-off-by: Alexander Ivanov --- ru-RU/README.md | 20 ++++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/ru-RU/README.md b/ru-RU/README.md index 33bf0ac1..57449628 100644 --- a/ru-RU/README.md +++ b/ru-RU/README.md @@ -2686,7 +2686,7 @@ fetch('https://www.website.com/api/user/1') - 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.
Ответ

@@ -2788,11 +2788,11 @@ sum(10) ###### 89. Какой будет вывод? ```javascript -// module.js +// module.js export default () => "Hello world" export const name = "Lydia" -// index.js +// index.js import * as data from "./module" console.log(data) @@ -2895,8 +2895,8 @@ console.log(giveLydiaPizza.prototype) console.log(giveLydiaChocolate.prototype) ``` -- A: `{ constructor: ...}` `{ constructor: ...}` -- B: `{}` `{ constructor: ...}` +- A: `{ constructor: ...}` `{ constructor: ...}` +- B: `{}` `{ constructor: ...}` - C: `{ constructor: ...}` `{}` - D: `{ constructor: ...}` `undefined` @@ -2926,7 +2926,7 @@ for (const [x, y] of Object.entries(person)) { ``` - A: `name` `Lydia` and `age` `21` -- B: `["name", "Lydia"]` and `["age", 21]` +- B: `["name", "Lydia"]` and `["age", 21]` - C: `["name", "age"]` and `undefined` - D: `Error` @@ -2937,7 +2937,7 @@ for (const [x, y] of Object.entries(person)) { `Object.entries (person)` возвращает массив вложенных массивов, содержащий ключи и объекты: -`[ [ 'name', 'Lydia' ], [ 'age', 21 ] ]` +`[ [ 'name', 'Lydia' ], [ 'age', 21 ] ]` Используя цикл `for-of`, мы можем перебирать каждый элемент массива, в данном случае подмассивы. Мы можем мгновенно деструктурировать подмассивы в цикле for, используя `const [x, y]`. `x` равен первому элементу в подмассиве, `y` равен второму элементу в подмассиве. @@ -2960,7 +2960,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` @@ -2992,9 +2992,9 @@ function nums(a, b) { if (a > b) console.log('a is bigger') - else + else console.log('b is bigger') - return + return a + b } From 4bbfcdfc08fc6607d304b7c765de6beee7a3cd2a Mon Sep 17 00:00:00 2001 From: Alexander Ivanov Date: Sun, 18 Aug 2019 08:13:49 +0300 Subject: [PATCH 305/915] Relink ru Signed-off-by: Alexander Ivanov --- README.md | 2 +- es-ES/README-ES.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 64957745..b7b0b895 100644 --- a/README.md +++ b/README.md @@ -21,7 +21,7 @@ List of available languages: * [日本語](./ja-JA/README-ja_JA.md) * [한국어](./ko-KR/README-ko_KR.md) * [Português Brasil](./pt-BR/README_pt_BR.md) -* [Русский](./ru-RU/README_ru-RU.md) +* [Русский](./ru-RU/README.md) * [Українська мова](./ua-UA/README-ua_UA.md) * [Tiếng Việt](./vi-VI/README-vi.md) * [中文版本](./zh-CN/README-zh_CN.md) diff --git a/es-ES/README-ES.md b/es-ES/README-ES.md index b4fb5d76..d6efd0d1 100644 --- a/es-ES/README-ES.md +++ b/es-ES/README-ES.md @@ -19,7 +19,7 @@ Lista de lenguajes disponibles: * [日本語](./ja-JA/README-ja_JA.md) * [한국어](./ko-KR/README-ko_KR.md) * [Português Brasil](./pt-BR/README_pt_BR.md) -* [Русский](./ru-RU/README_ru-RU.md) +* [Русский](./ru-RU/README.md) * [Українська мова](./ua-UA/README-ua_UA.md) * [Tiếng Việt](./vi-VI/README-vi.md) * [中文版本](./zh-CN/README-zh_CN.md) From 9690641c5f35f024a11ad8ef3a587d7bc19b115b Mon Sep 17 00:00:00 2001 From: Alexander Ivanov Date: Sun, 18 Aug 2019 08:14:37 +0300 Subject: [PATCH 306/915] Add updated menu Signed-off-by: Alexander Ivanov --- ru-RU/README.md | 30 +++++++++++++++--------------- 1 file changed, 15 insertions(+), 15 deletions(-) diff --git a/ru-RU/README.md b/ru-RU/README.md index 57449628..a199ff80 100644 --- a/ru-RU/README.md +++ b/ru-RU/README.md @@ -11,21 +11,21 @@ Список доступных переводов: -* [English](./README.md) -* [العربية](./README_AR.md) -* [اللغة العامية - Egyptian Arabic](./README_ar-EG.md) -* [Bosanski](./README-bs_BS.md) -* [Deutsch](./README-de_DE.md) -* [Español](./README-ES.md) -* [Français](./README_fr-FR.md) -* [日本語](./README-ja_JA.md) -* [한국어](./README-ko_KR.md) -* [Português Brasil](./README_pt_BR.md) -* [Русский](./README_ru-RU.md) -* [Українська мова](./README-ua_UA.md) -* [Tiếng Việt](./README-vi.md) -* [中文版本](./README-zh_CN.md) -* [Türkçe](./README-tr_TR.md) +* [English](./en-EN/README.md) +* [العربية](./ar-AR/README_AR.md) +* [اللغة العامية - Egyptian Arabic](./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) +* [日本語](./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) +* [Українська мова](./ua-UA/README-ua_UA.md) +* [Tiếng Việt](./vi-VI/README-vi.md) +* [中文版本](./zh-CN/README-zh_CN.md) +* [Türkçe](./tr-TR/README-tr_TR.md) --- From 4eaaee095a969eaa3901d4f307a7970d41629a02 Mon Sep 17 00:00:00 2001 From: Alexander Ivanov Date: Sun, 18 Aug 2019 08:16:10 +0300 Subject: [PATCH 307/915] Relink ru Signed-off-by: Alexander Ivanov --- README.md | 2 +- ar-AR/README_AR.md | 2 +- de-DE/README.md | 2 +- en-EN/README.md | 2 +- es-ES/README-ES.md | 2 +- fr-FR/README_fr-FR.md | 2 +- ja-JA/README-ja_JA.md | 2 +- ko-KR/README-ko_KR.md | 2 +- tr-TR/README-tr_TR.md | 2 +- vi-VI/README-vi.md | 2 +- 10 files changed, 10 insertions(+), 10 deletions(-) diff --git a/README.md b/README.md index b7b0b895..1e135c30 100644 --- a/README.md +++ b/README.md @@ -21,7 +21,7 @@ List of available languages: * [日本語](./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) +* [Русский](./ru-RU/README.md) * [Українська мова](./ua-UA/README-ua_UA.md) * [Tiếng Việt](./vi-VI/README-vi.md) * [中文版本](./zh-CN/README-zh_CN.md) diff --git a/ar-AR/README_AR.md b/ar-AR/README_AR.md index 09078392..a1324117 100644 --- a/ar-AR/README_AR.md +++ b/ar-AR/README_AR.md @@ -19,7 +19,7 @@ * [Versión en español](./README-ES.md) * [日本語](./README-ja_JA.md) * [한국어](./README-ko_KR.md) -* [Русский](./README_ru-RU.md) +* [Русский](./ru-RU/README.md) * [Western Balkan](./README-bs_BS.md) * [Deutsch](./README-de_DE.md) * [Tiếng Việt](./README-vi.md) diff --git a/de-DE/README.md b/de-DE/README.md index 529f825a..f555a38e 100644 --- a/de-DE/README.md +++ b/de-DE/README.md @@ -17,7 +17,7 @@ Die Antworten sind unterhalb der Fragen versteckt. Du kannst einfach darauf klic * [日本語](../ja-JA/README-ja_JA.md) * [한국어](../ko-KR/README-ko_KR.md) * [Português Brasil](../pt-BR/README_pt_BR.md) -* [Русский](../ru-RU/README_ru-RU.md) +* [Русский](./ru-RU/README.md) * [Türkçe](../tr-TR/README-tr_TR.md) * [Українська мова](../ua-UA/README-ua_UA.md) * [Tiếng Việt](../vi-VI/README-vi.md) diff --git a/en-EN/README.md b/en-EN/README.md index c665ae33..16b9fad9 100644 --- a/en-EN/README.md +++ b/en-EN/README.md @@ -21,7 +21,7 @@ List of available languages: * [日本語](../ja-JA/README-ja_JA.md) * [한국어](../ko-KR/README-ko_KR.md) * [Português Brasil](../pt-BR/README_pt_BR.md) -* [Русский](../ru-RU/README_ru-RU.md) +* [Русский](./ru-RU/README.md) * [Українська мова](../ua-UA/README-ua_UA.md) * [Tiếng Việt](../vi-VI/README-vi.md) * [中文版本](../zh-CN/README-zh_CN.md) diff --git a/es-ES/README-ES.md b/es-ES/README-ES.md index d6efd0d1..1c42de6b 100644 --- a/es-ES/README-ES.md +++ b/es-ES/README-ES.md @@ -19,7 +19,7 @@ Lista de lenguajes disponibles: * [日本語](./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) +* [Русский](./ru-RU/README.md) * [Українська мова](./ua-UA/README-ua_UA.md) * [Tiếng Việt](./vi-VI/README-vi.md) * [中文版本](./zh-CN/README-zh_CN.md) diff --git a/fr-FR/README_fr-FR.md b/fr-FR/README_fr-FR.md index 9dc016b9..36c5aa6f 100644 --- a/fr-FR/README_fr-FR.md +++ b/fr-FR/README_fr-FR.md @@ -11,7 +11,7 @@ Les réponses se trouvent dans les sections repliées en dessous des questions, * [Versión en español](./README-ES.md) * [日本語](./README-ja_JA.md) * [한국어](./README-ko_KR.md) -* [Русский](./README_ru-RU.md) +* [Русский](./ru-RU/README.md) * [Western Balkan](./README-bs_BS.md) * [Deutsch](./README-de_DE.md) * [Tiếng Việt](./README-vi.md) diff --git a/ja-JA/README-ja_JA.md b/ja-JA/README-ja_JA.md index 7bbe1641..c02042f7 100644 --- a/ja-JA/README-ja_JA.md +++ b/ja-JA/README-ja_JA.md @@ -17,7 +17,7 @@ * [日本語](./README-ja_JA.md) * [한국어](./README-ko_KR.md) * [Português Brasil](./README_pt_BR.md) -* [Русский](./README_ru-RU.md) +* [Русский](./ru-RU/README.md) * [Українська мова](./README-ua_UA.md) * [Tiếng Việt](./README-vi.md) * [中文版本](./README-zh_CN.md) diff --git a/ko-KR/README-ko_KR.md b/ko-KR/README-ko_KR.md index fbc30e11..2019b637 100644 --- a/ko-KR/README-ko_KR.md +++ b/ko-KR/README-ko_KR.md @@ -14,7 +14,7 @@ JavaScript 에 관한 객관식 문제를 [Instagram](https://www.instagram.com/ * [Español](./README-ES.md) * [日本語](./README-ja_JA.md) * [Português Brasil](./README_pt_BR.md) -* [Русский](./README_ru-RU.md) +* [Русский](./ru-RU/README.md) * [Українська мова](./README-ua_UA.md) * [Tiếng Việt](./README-vi.md) * [中文版本](./README-zh_CN.md) diff --git a/tr-TR/README-tr_TR.md b/tr-TR/README-tr_TR.md index df9c424f..0e5a3053 100644 --- a/tr-TR/README-tr_TR.md +++ b/tr-TR/README-tr_TR.md @@ -21,7 +21,7 @@ Mevcut dillerin listesi: * [日本語](./README-ja_JA.md) * [한국어](./README-ko_KR.md) * [Português Brasil](./README_pt_BR.md) -* [Русский](./README_ru-RU.md) +* [Русский](./ru-RU/README.md) * [Українська мова](./README-ua_UA.md) * [Tiếng Việt](./README-vi.md) * [中文版本](./README-zh_CN.md) diff --git a/vi-VI/README-vi.md b/vi-VI/README-vi.md index 1f130cd9..4acedbe0 100644 --- a/vi-VI/README-vi.md +++ b/vi-VI/README-vi.md @@ -12,7 +12,7 @@ Danh sách các ngôn ngữ khác: * [Versión en español](./README-ES.md) * [日本語](./README-ja_JA.md) * [한국어](./README-ko_KR.md) -* [Русский](./README_ru-RU.md) +* [Русский](./ru-RU/README.md) * [Western Balkan](./README-bs_BS.md) * [Deutsch](./README-de_DE.md) * [Українська мова](./README-ua_UA.md) From 091ef31f8e1a49183d7fc47ba8cd6c940fd4a6ae Mon Sep 17 00:00:00 2001 From: yusufkaracin Date: Mon, 19 Aug 2019 19:51:01 +0300 Subject: [PATCH 308/915] syncs to August 17 and translates 95-96 --- tr-TR/README-tr_TR.md | 242 +++++++++++++++++++++++++++++++++++++++++- 1 file changed, 241 insertions(+), 1 deletion(-) diff --git a/tr-TR/README-tr_TR.md b/tr-TR/README-tr_TR.md index 0e5a3053..885de080 100644 --- a/tr-TR/README-tr_TR.md +++ b/tr-TR/README-tr_TR.md @@ -2,7 +2,7 @@ [Instagram](https://www.instagram.com/theavocoder) hesabımda, günlük olarak çoktan seçmeli Javascript soruları paylaşıyorum, ayrıca burada da paylaşacağım! -Temelden ileri düzeye: Javascript'i ne kadar iyi bildiğinizi test edin, bilginizi biraz tazeleyin ya da mülakatanıza hazırlanın! :muscle: :rocket: Repoyu haftalık olarak yeni sorularla güncelliyorum. Son güncelleme: 5 Ağustos +Temelden ileri düzeye: Javascript'i ne kadar iyi bildiğinizi test edin, bilginizi biraz tazeleyin ya da mülakatanıza hazırlanın! :muscle: :rocket: Repoyu haftalık olarak yeni sorularla güncelliyorum. Son güncelleme: 17 Ağustos Cevaplar, soruların altında gizlenmiştir. Görmek için sadece tıklayın. İyi şanşlar :heart: @@ -2972,3 +2972,243 @@ Yukarıdaki örnek çalışır. `[ 'banana', 'apple', 'orange', 'pear' ]` dizisi

+ +--- + +###### 95. Çıktısı Nedir? + +```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` ve `b is bigger`, `3` +- B: `a is bigger`, `undefined` ve `b is bigger`, `undefined` +- C: `undefined` ve `undefined` +- D: `SyntaxError` + +
Cevap +

+ +#### 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 + 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! + +

+
+ +--- + +###### 96. Çıktısı Nedir? + +```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` + +
Cevap +

+ +#### Cevap: B + +Sınıfları diğer sınıf/fonksiyon yapıcılara eşitleyebiliriz. Bu örnekte, `Person`'ı `AnotherPerson`'a eşitliyoruz. Bu yapıcıdaki `name` `Sarah`'dır, yani `Person` instance'ı olan `member` üzerindeki `name` özelliği `"Sarah"`'tır. + +

+
+ +--- + +###### 97. Çıktısı Nedir? + +```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 `[]` + +
Cevap +

+ +#### Cevap: 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. Çıktısı Nedir? + +```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 }` + +
Cevap +

+ +#### Cevap: 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, containig 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: + +```const getUser = user => ({ name: user.name, age: user.age })``` + +Since no value gets returned in this case, the function returns `undefined`. + +

+
+ +--- + +###### 99. Çıktısı Nedir? + +```javascript +const name = "Lydia" + +console.log(name()) +``` + +- A: `SyntaxError` +- B: `ReferenceError` +- C: `TypeError` +- D: `undefined` + +
Cevap +

+ +#### Cevap: C + +The variable `name` holds the value of a string, which is not a function, thus cannot invoke. + +TypeErrors get thrown wehn 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` + +
Cevap +

+ +#### Cevap: 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` + +
Cevap +

+ +#### Cevap: 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 past 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 `[]`. + +

+
From 464d5ac0dcf7951230ea927f3cdcc62de3199f3c Mon Sep 17 00:00:00 2001 From: Alexander Ivanov Date: Wed, 21 Aug 2019 14:40:29 +0300 Subject: [PATCH 309/915] Sync EN files --- README.md | 6 +++--- en-EN/README.md | 2 +- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index 1e135c30..07b0c2cf 100644 --- a/README.md +++ b/README.md @@ -2718,7 +2718,7 @@ function getName(name) { #### Answer: A -With `!!name`, we determine whether the value of `name` is truthy or falsey. 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 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`. @@ -3121,7 +3121,7 @@ The `getList` function receives an array as its argument. Between the parenthese `[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, containig 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` 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: @@ -3154,7 +3154,7 @@ console.log(name()) The variable `name` holds the value of a string, which is not a function, thus cannot invoke. -TypeErrors get thrown wehn 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! +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. diff --git a/en-EN/README.md b/en-EN/README.md index 16b9fad9..ebb900a4 100644 --- a/en-EN/README.md +++ b/en-EN/README.md @@ -21,7 +21,7 @@ List of available languages: * [日本語](../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) +* [Русский](../ru-RU/README.md) * [Українська мова](../ua-UA/README-ua_UA.md) * [Tiếng Việt](../vi-VI/README-vi.md) * [中文版本](../zh-CN/README-zh_CN.md) From 98a4715683f0613260ed2f328c2bff278fdd18b8 Mon Sep 17 00:00:00 2001 From: yusufkaracin Date: Wed, 21 Aug 2019 22:46:37 +0300 Subject: [PATCH 310/915] Translates 97-101 --- tr-TR/README-tr_TR.md | 55 ++++++++++++++++++++++--------------------- 1 file changed, 28 insertions(+), 27 deletions(-) diff --git a/tr-TR/README-tr_TR.md b/tr-TR/README-tr_TR.md index 885de080..59538b45 100644 --- a/tr-TR/README-tr_TR.md +++ b/tr-TR/README-tr_TR.md @@ -3065,19 +3065,19 @@ 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 `[]` +- A: `{Symbol('a'): 'b'}` ve `["{Symbol('a')"]` +- B: `{}` ve `[]` +- C: `{ a: "b" }` ve `["a"]` +- D: `{Symbol('a'): 'b'}` ve `[]`
Cevap

#### Cevap: 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. +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. -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). +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).

@@ -3097,27 +3097,27 @@ 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: `[1, [2, 3, 4]]` ve `undefined` +- B: `[1, [2, 3, 4]]` ve `{ name: "Lydia", age: 21 }` +- C: `[1, 2, 3, 4]` ve `{ name: "Lydia", age: 21 }` +- D: `Error` ve `{ name: "Lydia", age: 21 }`
Cevap

#### Cevap: 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: +`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]` - 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, containig 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. + `...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. - 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: + `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 })``` -Since no value gets returned in this case, the function returns `undefined`. +Bu örnekte değer döndürülmediği için, fonksiyon `undefined` döndürür.

@@ -3142,22 +3142,23 @@ console.log(name()) #### Cevap: C -The variable `name` holds the value of a string, which is not a function, thus cannot invoke. + `name` değişkeni string bir değer saklıyor, ki bu bir fonksiyon değil, bu yüzden çağrılamaz. -TypeErrors get thrown wehn 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! +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! -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. +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.

--- -###### 100. What's the value of output? +###### 100. Çıktısı Nedir? ```javascript -// 🎉✨ This is my 100th question! ✨🎉 +// 🎉✨ 100. soru! ✨🎉 const output = `${[] && 'Im'}possible! You should${'' && `n't`} see a therapist after so much JavaScript lol` @@ -3173,16 +3174,16 @@ You should${'' && `n't`} see a therapist after so much JavaScript lol` #### Cevap: 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. +`[]` 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. -`""` is a falsy value. If the left-hand value is falsy, nothing gets returned. `n't` doesn't get returned. +`""` 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.

--- -###### 101. What's the value of output? +###### 101. Çıktısı Nedir? ```javascript const one = (false || {} || null) @@ -3202,13 +3203,13 @@ console.log(one, two, three) #### Cevap: C -With the `||` operator, we can return the first truthy operand. If all values are falsy, the last operand gets returned. +`||` operatörü ile, ile doğrusal operand'ı döndürebiliriz. Eğer tüm değerler yanlış-ımsı ise, son operand döndürülür. -`(false || {} || null)`: the empty object `{}` is a truthy value. This is the first (and only) truthy value, which gets returned. `one` is equal to `{}`. +`(false || {} || null)`: boş nesne `{}` doğrusal bir değerdir. İlk (ve tek) doğrusal değer, döndürülür. `one` `{}` eşittir. -`(null || false || "")`: all operands are falsy values. This means that the past operand, `""` gets returned. `two` is equal to `""`. +`(null || false || "")`: tüm operand'lar yanlış-ımsı. Bu demektir ki son operand, `""` döndürülür. `two` `""` eşittir. -`([] || 0 || "")`: the empty array`[]` is a truthy value. This is the first truthy value, which gets returned. `three` is equal to `[]`. +`([] || 0 || "")`: boş dizi `[]` doğrusal bir değerdir. Bu ilk doğrusal değer, döndürülür. `three` `[]` eşittir.

From d7a50bb6e5df722c9c1da2dcaa3945b7e32a588e Mon Sep 17 00:00:00 2001 From: Raja Malik Date: Thu, 22 Aug 2019 12:59:26 +0530 Subject: [PATCH 311/915] Updated Q4 - added console.log and updated question statement --- en-EN/README.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/en-EN/README.md b/en-EN/README.md index 16b9fad9..2a7d6575 100644 --- a/en-EN/README.md +++ b/en-EN/README.md @@ -128,11 +128,11 @@ There is no value `radius` on that object, which returns `undefined`. --- -###### 4. What's the output? +###### 4. What's printed on console? ```javascript -+true; -!"Lydia"; +console.log(+true); +console.log(!"Lydia"); ``` - A: `1` and `false` From c94ea132c1e0736459a61d161be3ace929e2b796 Mon Sep 17 00:00:00 2001 From: Raja Malik Date: Fri, 23 Aug 2019 08:57:59 +0530 Subject: [PATCH 312/915] Reverted the question as per convention followed --- en-EN/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/en-EN/README.md b/en-EN/README.md index 2a7d6575..d2a5e771 100644 --- a/en-EN/README.md +++ b/en-EN/README.md @@ -128,7 +128,7 @@ There is no value `radius` on that object, which returns `undefined`. --- -###### 4. What's printed on console? +###### 4. What's the output? ```javascript console.log(+true); From 6c856509e79492c579f1f5bc066bc73c820d11bc Mon Sep 17 00:00:00 2001 From: Alexander Ivanov Date: Fri, 23 Aug 2019 07:16:38 +0300 Subject: [PATCH 313/915] Missed dots --- ru-RU/README.md | 30 +++++++++++++++--------------- 1 file changed, 15 insertions(+), 15 deletions(-) diff --git a/ru-RU/README.md b/ru-RU/README.md index a199ff80..beaba310 100644 --- a/ru-RU/README.md +++ b/ru-RU/README.md @@ -11,21 +11,21 @@ Список доступных переводов: -* [English](./en-EN/README.md) -* [العربية](./ar-AR/README_AR.md) -* [اللغة العامية - Egyptian Arabic](./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) -* [日本語](./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) -* [Українська мова](./ua-UA/README-ua_UA.md) -* [Tiếng Việt](./vi-VI/README-vi.md) -* [中文版本](./zh-CN/README-zh_CN.md) -* [Türkçe](./tr-TR/README-tr_TR.md) +* [English](../en-EN/README.md) +* [العربية](../ar-AR/README_AR.md) +* [اللغة العامية - Egyptian Arabic](../ar-EG/README_ar-EG.md) +* [Bosanski](../bs-BS/README-bs_BS.md) +* [Deutsch](../de-DE/README-de_DE.md) +* [Español](../es-ES/README-ES.md) +* [Français](../fr-FR/README_fr-FR.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) +* [Українська мова](../ua-UA/README-ua_UA.md) +* [Tiếng Việt](../vi-VI/README-vi.md) +* [中文版本](../zh-CN/README-zh_CN.md) +* [Türkçe](../tr-TR/README-tr_TR.md) --- From f955d9bb62e3255dd0876f8686303afef4fc81b0 Mon Sep 17 00:00:00 2001 From: Alexander Ivanov Date: Fri, 23 Aug 2019 07:27:25 +0300 Subject: [PATCH 314/915] Fix de-DE Signed-off-by: Alexander 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 beaba310..6c41c670 100644 --- a/ru-RU/README.md +++ b/ru-RU/README.md @@ -15,7 +15,7 @@ * [العربية](../ar-AR/README_AR.md) * [اللغة العامية - Egyptian Arabic](../ar-EG/README_ar-EG.md) * [Bosanski](../bs-BS/README-bs_BS.md) -* [Deutsch](../de-DE/README-de_DE.md) +* [Deutsch](../de-DE/README.md) * [Español](../es-ES/README-ES.md) * [Français](../fr-FR/README_fr-FR.md) * [日本語](../ja-JA/README-ja_JA.md) From ce5b127bdca1a542e0f623be41affb23f74e01e8 Mon Sep 17 00:00:00 2001 From: Zavier Tang Date: Mon, 26 Aug 2019 21:00:34 +0800 Subject: [PATCH 315/915] fix: incorrect punctuation --- 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 aa1fc51d..e68ad7ec 100644 --- a/zh-CN/README-zh_CN.md +++ b/zh-CN/README-zh_CN.md @@ -2492,7 +2492,7 @@ for (let item of myLifeSummedUp) { 其中键则是可枚举属性,因此 `0`,`1`,`2`,`3`被记录。 -通过`for-of`循环,我们可以迭代**可迭代对象**(包括 `Array`,`Map`,`Set`,`String`,`arguments`等)。当我们迭代数组时,在每次迭代中,不同属性的值将被分配给变量`item`, 因此`“☕”`,`“💻“`,`”🍷”`,`“🍫“`被打印。 +通过`for-of`循环,我们可以迭代**可迭代对象**(包括 `Array`,`Map`,`Set`,`String`,`arguments`等)。当我们迭代数组时,在每次迭代中,不同属性的值将被分配给变量`item`, 因此`“☕”`,`“💻”`,`“🍷”`,`“🍫”`被打印。

From 7266422e1a83fd93ed5aefe08c34e4f242ef0a8a Mon Sep 17 00:00:00 2001 From: limbo Date: Mon, 26 Aug 2019 21:54:23 +0800 Subject: [PATCH 316/915] Update README-zh_CN.md translate error --- 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 aa1fc51d..be813764 100644 --- a/zh-CN/README-zh_CN.md +++ b/zh-CN/README-zh_CN.md @@ -1707,7 +1707,7 @@ console.log(set); #### 答案: D -`Set`对象手机 _独一无二_ 的值:也就是说同一个值在其中仅出现一次。 +`Set`对象是独一无二的值的集合:也就是说同一个值在其中仅出现一次。 我们传入了数组`[1, 1, 2, 3, 4]`,他有一个重复值`1`.以为一个集合里不能有两个重复的值,其中一个就被移除了。所以结果是 `{1, 2, 3, 4}`. From 43544e8050157e73e8606c09c978d1523d581c1a Mon Sep 17 00:00:00 2001 From: Mohamed ELBARCHANY Date: Tue, 27 Aug 2019 17:47:17 +0100 Subject: [PATCH 317/915] Fix typos on README_AR --- ar-AR/README_AR.md | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/ar-AR/README_AR.md b/ar-AR/README_AR.md index a1324117..2478aff8 100644 --- a/ar-AR/README_AR.md +++ b/ar-AR/README_AR.md @@ -86,7 +86,7 @@ for (let i = 0; i < 3; i++) {
الإجابة هي الخيار الثالث: C -بسبب ترتيب تسلسل الأحداث في الجافا سكريبت, دالة `setTimeout` والتي هي دالة من نوع callbackقد تم استدعائها بعد ان تم تنفيذ ال loop. بماأن المتغير `i` في الloop الاولى قد تم تعريفه عن طريق الكلمة المفتاحية `var` فإن هذه القيمة هي glopal. أثناء تنفيذ هذه ال loop قد تم إضافة 1 الى المتغير `var` في كل دورة باستخدام العملية `++`. بنهاية الدورة و عندما تم استدعاء الدالة `setTimeout` كانت قيمة المتغير `i` قد أصبحت تساوي `3` في المثال الأول. +بسبب ترتيب تسلسل الأحداث في الجافا سكريبت, دالة `setTimeout` والتي هي دالة من نوع callbackقد تم استدعائها بعد ان تم تنفيذ ال loop. بماأن المتغير `i` في الloop الاولى قد تم تعريفه عن طريق الكلمة المفتاحية `var` فإن هذه القيمة هي global. أثناء تنفيذ هذه ال loop قد تم إضافة 1 الى المتغير `var` في كل دورة باستخدام العملية `++`. بنهاية الدورة و عندما تم استدعاء الدالة `setTimeout` كانت قيمة المتغير `i` قد أصبحت تساوي `3` في المثال الأول. في الloop الثانية ,تم تعريف المتغير `i` باستخدام الكلمة المفتاحية `let` المتغيرات التي يتم تعريفها باستخدام الكلمات المفتاحية `let` و `const` هي متغيرات تنتمي فقط للBlock الذي تم تعريفها بداخله, والذي هو بين القوسين, أثناءتنفيذ الloop, سنقوم بالتحصل على قيمة جديدة للمتغير `i` في نهاية كل دورة , وأي قيمة تكون منتمية للScope بداخل الloop.

@@ -316,7 +316,7 @@ console.log(greetign);
الجواب هو الخيار الأول : A -تقوم بعمل log على الconsole ل object. و لأننا قمنا بإنشاء object فارغ في glopal object! عندما قمنا بالخطأ بطباعة `greetign` بدل ان نقوم بطباعتها بصورة صحيحة هكذا `greeting`, هنا قام مترجم الجافاسكريبت بترجمة الآتي `global.greetign = {}` أو `window.greetign = {}` في المتصفح. +تقوم بعمل log على الconsole ل object. و لأننا قمنا بإنشاء object فارغ في global object! عندما قمنا بالخطأ بطباعة `greetign` بدل ان نقوم بطباعتها بصورة صحيحة هكذا `greeting`, هنا قام مترجم الجافاسكريبت بترجمة الآتي `global.greetign = {}` أو `window.greetign = {}` في المتصفح. لكي نتجنب حدوث مثل هذه الحالة, بإمكاننا إستخدام `"use strict"`. بفعل هذه الخطوة ستتأكد من أنك قد عرفت المتغير قبل ان تساويه بأي شي آخر.

@@ -658,7 +658,7 @@ getAge();
الجواب هو الخيار الثالث: C -بإستخدام `"use strict"`, يمكنك التأكد بأنك لن تقوم عن طريق الخطأ بتعريف glopal variables. نحن لم نقم قط بتعريف المتغير `age`, و بما أننا قمنا بإستخدام `"use strict"` ستقوم بإرجاع reference error. اذا لم نقم بإستخدام `"use strict"` لكانت قد أدت المطلوب, بما أن الخاصية `age` تم إضافتها لل glopal object. +بإستخدام `"use strict"`, يمكنك التأكد بأنك لن تقوم عن طريق الخطأ بتعريف global variables. نحن لم نقم قط بتعريف المتغير `age`, و بما أننا قمنا بإستخدام `"use strict"` ستقوم بإرجاع reference error. اذا لم نقم بإستخدام `"use strict"` لكانت قد أدت المطلوب, بما أن الخاصية `age` تم إضافتها لل global object.

@@ -806,7 +806,7 @@ console.log(obj); ---
-26. في سياق تنفيذ glopal في لغة الجافاسكريبت, فإن الجافاسكريبت تقوم بإنشاء شيئين لك: الglopal object و الكلمة المفتاحية "this". +26. في سياق تنفيذ global في لغة الجافاسكريبت, فإن الجافاسكريبت تقوم بإنشاء شيئين لك: الglobal object و الكلمة المفتاحية "this".
- A: true @@ -818,7 +818,7 @@ console.log(obj);
الجواب هو الخيارالأول: A -سياق التنفيذ الأساسي هو سياق تنفيذ الglopal, وهي الشيء الذي يمكن الوصول إليه من أي مكان في الكود الذي ببرنامجك. +سياق التنفيذ الأساسي هو سياق تنفيذ الglobal, وهي الشيء الذي يمكن الوصول إليه من أي مكان في الكود الذي ببرنامجك.

@@ -1725,7 +1725,7 @@ let x = y;
-عندما نقوم بضبط قيمة`y` لكي تساوي `10`, فنحن فعليا نقوم بإضافة الخاصية `y` للglopal 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"`. @@ -1862,7 +1862,7 @@ console.log(delete age); العامل `delete` تقوم بإرجاع قيمة boolen و هي `true` عندما تتم عملية المسح بنجاح, خلاف ذلك ستقوم بإرجاع `false`, ولكن المتغيرات المعرفة بالكلمات المفتاحية `var`, `const` أو `let` ليس بالإمكان مسحها بإستخدام العامل `delete`. -المتغير `name` تم تعريفه باستخدام الكلمة المفتاحية `const`, لهذا فإن عملية مسحه لم تتم بنجاح, وتم إرجاع القيمة `false`, عندما نقوم بضبط المتغير `age` ليساوي القيمة `21` فإننا فعليا نقوم بإضافة خاصية تسمى `age` للglopal object. بإمكانك أن تمسح خصائص من الobjects بنجاح بإستخدام هذه الطريقة , أيضا الglopal objects, لذا فإن `delete age` تقوم بإرجاع `true`. +المتغير `name` تم تعريفه باستخدام الكلمة المفتاحية `const`, لهذا فإن عملية مسحه لم تتم بنجاح, وتم إرجاع القيمة `false`, عندما نقوم بضبط المتغير `age` ليساوي القيمة `21` فإننا فعليا نقوم بإضافة خاصية تسمى `age` للglobal object. بإمكانك أن تمسح خصائص من الobjects بنجاح بإستخدام هذه الطريقة , أيضا الglobal objects, لذا فإن `delete age` تقوم بإرجاع `true`.

From ebef0414dd156de1c48b28e69ed462e840857a3b Mon Sep 17 00:00:00 2001 From: Intakhab Ali Date: Thu, 29 Aug 2019 01:06:58 +0530 Subject: [PATCH 318/915] fix typo in question no. 88 --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 07b0c2cf..a609f5e7 100644 --- a/README.md +++ b/README.md @@ -2776,7 +2776,7 @@ sum(10) #### Answer: 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, amd 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. From 4df2e6ec6450a0797403be775a3b8436c661af72 Mon Sep 17 00:00:00 2001 From: Do Trung Kien Date: Thu, 29 Aug 2019 10:11:39 +0700 Subject: [PATCH 319/915] translate next 10 questions (from 64 to 73) into Vietnamese --- vi-VI/README-vi.md | 336 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 336 insertions(+) diff --git a/vi-VI/README-vi.md b/vi-VI/README-vi.md index 4acedbe0..dba57de3 100644 --- a/vi-VI/README-vi.md +++ b/vi-VI/README-vi.md @@ -1959,3 +1959,339 @@ Phép toán `++` sẽ _trả về trước_ giá trị của toán hạng, _sau

+ +--- + +###### 64. Output là gì? + +```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 án +

+ +#### Đáp án: C + +Trong ES6 thì chúng ta có thể khởi tạo tham số với giá trị mặc định. Giá trị của tham số sẽ là giá trị mặc định nếu ta không truyền gì vào hàm, hoặc khi giá trị truyền vào là `"undefined"`. Trong trường hợp này, ta dùng `spread operator` (toán tử mở rộng) để biến `value` thành một object mới, do đó `x` sẽ có giá trị mặc định là `{ number: 10 }`. + +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`. + +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`. + +

+
+ +--- + +###### 65. Output là gì? + +```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` + +
Đáp án +

+ +#### Đá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. + +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. + +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. +

+
+ +--- + +###### 66. Với cách nào chúng ta có thể kế thừa `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 + +
Đáp án +

+ +#### Đáp án: B + +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`. + +`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. +

+
+ +--- + +###### 67. Output là gì? + +```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 án +

+ +#### Đáp án: 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. + +

+
+ +--- + +###### 68. Output là gì? + +```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 án +

+ +#### Đá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`. + +

+
+ +--- + +###### 69. Output là gì? + +```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 án +

+ +#### Đáp án: C + +Với hàm `padStart` chúng ta có thể thêm vào khoảng trắng đằng trước mỗi chuỗi. Giá trị đưa vào trong hàm là _tổng độ dài_ của chuỗi sau khi thêm vào khoảng trắng. Chuỗi `"Lydia Hallie"` có độ dài là `12` nên `name.padStart(13)` sẽ thêm vào một khoảng trắng đằng trước chuỗi. + +Nếu đối số truyền vào cho hàm `padStart` nhỏ hơn độ dài của chuỗi, không có khoảng trắng nào được thêm vào. + +

+
+ +--- + +###### 70. Output là gì? + +```javascript +console.log("🥑" + "💻"); +``` + +- A: `"🥑💻"` +- B: `257548` +- C: A string containing their code points +- D: Error + +
Đáp án +

+ +#### Đáp án: A + +Với phép toán `+`, ta có thể nối các xâu chuỗi. Trong trường hợp này, ta nối chuỗi `"🥑"` với chuỗi `"💻"`, kết quả tạo ra `"🥑💻"`. + +

+
+ +--- + +###### 71. Làm thế nào có thể ghi ra giá trị giống như trong comment khi 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")` + +
Đáp án +

+ +#### Đáp án: C + +Một _generator_ sẽ "tạm dừng" khi nhìn thấy từ khóa `yield`. Đầu tiên ra sẽ đưa ra chuỗi "Do you love JavaScript?", bằng cách gọi `game.next().value`. + +Chương trình sẽ chạy từng dòng, cho tới khi nó tìm thấy từ khóa `yield`. Có một từ khóa `yield` tại dòng đầu tiên của hàm: chương trình sẽ dừng tại đâ! _Điều đó có nghĩa là biến `answer` chưa hề được định nghĩa!_ + +Khi ta gọi `game.next("Yes").value`, `yield` trước đó sẽ được thay thế bởi giá trị được truyền vào hàm `next()`, trong trường hợp này là`"Yes"`. Theo đó giá trị của biến `answer` giờ sẽ là `"Yes"`. Điều kiện if sẽ trả về `false`, và `JavaScript loves you back ❤️` sẽ được ghi ra. + +

+
+ +--- +**** +###### 72. Output là gì? + +```javascript +console.log(String.raw`Hello\nworld`); +``` + +- A: `Hello world!` +- B: `Hello`
     `world` +- C: `Hello\nworld` +- D: `Hello\n`
     `world` + +
Đáp án +

+ +#### Đáp án: C + +`String.raw` trả về chuỗi nguyên bản, các ký tự (`\n`, `\v`, `\t` etc.) sẽ vẫn là nguyên bản và không biến thành xuống dòng hay khoảng trắng! Nếu ta không để là chuỗi nguyên bản, sẽ có trường hợp xảy ra lỗi không mong muốn, ví dụ với đường dẫn: + +`` const path = `C:\Documents\Projects\table.html` `` + +Sẽ cho ta chuỗi là: + +`"C:DocumentsProjects able.html"` + +Với `String.raw`, nó sẽ trả về là: + +`C:\Documents\Projects\table.html` + +Do đó, trong trường hợp này `Hello\nworld` sẽ được ghi ra. + +

+
+ +--- + +###### 73. Output là gì? + +```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 án +

+ +#### Đáp án: C + +Một hàm `async` luôn luôn trả về một `promise`. `await` sẽ chờ cho tới khi promise đó được hoàn thành: một pending promise sẽ được trả về khi ta gọi `getData()` bằng cách gán nó cho biến `data`. + +Nếu ta muốn truy cập giá trị đã hoàn thành của promise, trong trường hợp này là `"I made it"`, ta có thể sử dụng hàm `.then()` ngay sau `data` như sau: + +`data.then(res => console.log(res))` + +Khi này nó sẽ ghi ra `"I made it!"` + +

+
From 14d460d18eb5fcf6c70c197af94e6e0d2fa0bc7b Mon Sep 17 00:00:00 2001 From: Do Trung Kien Date: Thu, 29 Aug 2019 13:46:43 +0700 Subject: [PATCH 320/915] translate next 10 questions (from 74 to 83) into Vietnamese --- vi-VI/README-vi.md | 337 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 337 insertions(+) diff --git a/vi-VI/README-vi.md b/vi-VI/README-vi.md index dba57de3..858a3648 100644 --- a/vi-VI/README-vi.md +++ b/vi-VI/README-vi.md @@ -2295,3 +2295,340 @@ Khi này nó sẽ ghi ra `"I made it!"`

+ +--- + +###### 74. Output là gì? + +```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 án +

+ +#### Đáp án: B + +Hàm `.push()` trả về _độ dài_ của mảng mới! Trước đó, mảng chỉ hồm một phần tử là `"banana"` và có độ dài là `1`. Sau khi thêm chuỗi `"apple"` vào mảng, mảng lúc này có hai chuỗi và có độ dài là `2`. Do đó hàm `addToList` sẽ trả về 2. + +Hàm `push` sẽ thay đổi chính bản thân mảng truyền vào. Do đó nếu chúng ta muốn trả về _mảng_ thay vì chỉ trả về _độ dài_, chúng ta nên trả về trực tiếp mảng `list` sau khi đã thêm `item` vào đó. + +

+
+ +--- + +###### 75. Output là gì? + +```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 án +

+ +#### Đáp án: B + +`Object.freeze` khiến cho chúng ta không thể thêm vào, xóa đi hay thay đổi bất kì thuộc tính nào của object (trừ phi giá trị của thuộc tính lại chính là một object khác). + +Khi chúng ta tạo ra biến `shape` và set cho nó giá trị bằng với một object đã được đóng băng là `box`, thì `shape` cũng sẽ trỏ tới một object đã được đóng băng. Ta có thể check một object có đang bị đóng băng hay không bằng `Object.isFrozen`. Trong trường hợp này, `Object.isFrozen(shape)` trả về true, vì `shape` đang trỏ tới một object bị đóng băng. + +Do đó, cộng với việc `x` không phải là object, ta sẽ không thể thay đổi giá trị của `x`. `x` sẽ vẫn là `10`, và `{ x: 10, y: 20 }` được ghi ra. + +

+
+ +--- + +###### 76. Output là gì? + +```javascript +const { name: myName } = { name: "Lydia" }; + +console.log(name); +``` + +- A: `"Lydia"` +- B: `"myName"` +- C: `undefined` +- D: `ReferenceError` + +
Đáp án +

+ +#### Đáp án: D + +Khi ta tiến hành unpack giá trị `name` từ object ở phía bên phải, ta đã gán giá trị `"Lydia"` của nó cho biến có tên là `myName`. + +Với cú pháp `{ name: myName }`, chúng ta muốn khai báo một biến `myName` với giá trị là giá trị của thuộc tính `name` trong object phía bên phải. + +Do `name` chưa được định nghĩa, nên ghi log ra, nó sẽ throw ra một ReferenceError. + +

+
+ +--- + +###### 77. Đây có phải là một pure function không? + +```javascript +function sum(a, b) { + return a + b; +} +``` + +- A: Yes +- B: No + +
Đáp án +

+ +#### Đáp án: A + +Một hàm được gọi là _pure function_ khi nó luôn luôn trả về một giá trị giống nhau, nếu đối số đưa vào là giống nhau. + +Hàm `sum` luôn trả về giá trị giống nhau. Nếu ta đưa vào `1` và `2`, nó sẽ _luôn_ trả về `3`. Nếu ta đưa vào `5` và `10`, nó _luôn_ trả về `15`. Cứ như vậy, đây là một _pure function_. + +

+
+ +--- + +###### 78. Output là gì? + +```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 án +

+ +#### Đáp án: C + +Hàm `add` chính là một hàm _memoized_ (hàm có nhớ). Với việc có nhớ, chúng ta có thể cache lại kết quả của function để tăng tốc độ tính toán lên. Trong trường hợp này, chúng ta tạo ra một `cache` object để lưu trữ những kết quả tính toán trước đó. + +Mỗi lần chúng ta gọi hàm `addFunction` với đối số giống nhau, đầu tiên nó sẽ check xem đối số đó có tồn tại trong cache hay không. Nếu có, giá trị trong cache sẽ được trả về luôn, tiết kiệm thời gian tính toán. Còn nếu không thì nó sẽ tiến hành tính toán kết quả và tiếp tục lưu vào cache. + +Chúng ta gọi hàm `addFunction` ba lần với cùng một đối số: trong lần gọi đầu tiên, giá trị của `num` là `10` và chưa có mặt trong cache. Do đó `num in cache` trả về `false`, và sẽ chạy vào else block: `Calculated! 20` sẽ được ghi ra, và 10 sẽ được đưa vào cạche. `cache` khi này sẽ là `{ 10: 20 }`. + +Tại lần gọi thứ hai, `cache` object đã có giá trị `10`. `num in cache` trả về `true`, và `'From cache! 20'` được ghi ra. + +Tại lần gọi thứ ba, ta đưa vào `5 * 2`, tức `10` vào hàm. Tiếp tục giống như trên, `'From cache! 20'` sẽ được ghi ra. + +

+
+ +--- + +###### 79. Output là gì? + +```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: "🍫"}` + +
Đáp án +

+ +#### Đáp án: A + +Với vòng lặp _for-in_, chúng ta có thể duyệt qua các thuộc tính **enumerable** của object. Với mảng, thuộc tính enumerable chính là các "key" của mảng, hay chính là các index của mảng đó. Ta có thể coi mảng như là: + +`{0: "☕", 1: "💻", 2: "🍷", 3: "🍫"}` + +Do đó `0` `1` `2` `3` được ghi ra. + +Với vòng lặp _for-of_, chúng ta sẽ duyệt qua các phần tử của một **iterable**. Một mảng chính là một iterable. Khi chúng ta duyệt qua mảng, biến "item" chính là phần tử mà nó đang duyệt qua, do đó `"☕"` ` "💻"` `"🍷"` `"🍫"` được ghi ra. + +

+
+ +--- + +###### 80. Output là gì? + +```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 án +

+ +#### Đáp án: C + +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`. + +

+
+ +--- + +###### 81. Output là gì? + +```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 án +

+ +#### Đáp án: B + +Mặc định, đối số sẽ có giá trị là `undefined`, trừ phi ta gán giá trị cho nó khi đưa vào hàm. Trong trường hợp này, ta không đưa vào giá trị nào cho đối số `name` cả. Do đó `name` sẽ là `undefined` và được ghi ra. + +Với cú pháp ES6, ta có thể thay đổi giá trị mặc định `undefined` bằng một giá trị mặc định khác. Ví dụ: + +`function sayHi(name = "Lydia") { ... }` + +Trong trường hợp này, nếu ta không đưa giá trị nào vào hoặc đưa vào `undefined`, `name` cũng sẽ nhận giá trị mặc định là `Lydia`. + +

+
+ +--- + +###### 82. Output là gì? + +```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 án +

+ +#### Đáp án: B + +Giá trị của `this` phụ thuộc vào vị trí mà nó được gọi. Trong một **phương thức**, ví dụ `getStatus`, `this` trỏ tới _object chứa phương thức đó_. Phương thức này thuộc `data` object, do đó `this` trỏ tới `data` object. Khi chúng ta gọi `this.status` thì thuộc tính `status` của `data` sẽ được ghi ra, chính là `"🥑"`. + +Với phương thức `call`, chúng ta thay đổi tham chiếu mà `this` trỏ tới. Trong **hàm**, từ khóa `this` trỏ tới _object chứa hàm đó_. Chúng ta khai báo hàm `setTimeout` trong _global object_, do đó bên trong hàm `setTimeout` thì `this` sẽ trỏ tới _global object_. Tại biến global object, có một biến _status_ với giá trị `"😎"`. Do đó khi gọi `this.status`, `"😎"` sẽ được ghi ra. + +

+
+ +--- + +###### 83. Output là gì? + +```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 án +

+ +#### Đá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ú ý 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ả. + +

+
From 4f56f5c4fa3e9633687b67ab079d418484332f24 Mon Sep 17 00:00:00 2001 From: Do Trung Kien Date: Thu, 29 Aug 2019 15:31:47 +0700 Subject: [PATCH 321/915] update link of language list because of the restruction of project --- vi-VI/README-vi.md | 26 ++++++++++++++------------ 1 file changed, 14 insertions(+), 12 deletions(-) diff --git a/vi-VI/README-vi.md b/vi-VI/README-vi.md index 858a3648..faf71ded 100644 --- a/vi-VI/README-vi.md +++ b/vi-VI/README-vi.md @@ -7,18 +7,20 @@ 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: -* [English](./README.md) -* [中文版本](./README-zh_CN.md) -* [Versión en español](./README-ES.md) -* [日本語](./README-ja_JA.md) -* [한국어](./README-ko_KR.md) -* [Русский](./ru-RU/README.md) -* [Western Balkan](./README-bs_BS.md) -* [Deutsch](./README-de_DE.md) -* [Українська мова](./README-ua_UA.md) -* [Português Brasil](./README_pt_BR.md) -* [العربية](./README_AR.md) -* [اللغة العامية - Egyptian Arabic](./README_ar-EG.md) +* [English](../en-EN/README.md) +* [العربية](../ar-AR/README_AR.md) +* [اللغة العامية - Egyptian Arabic](../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) +* [日本語](../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) +* [Українська мова](../ua-UA/README-ua_UA.md) +* [中文版本](../zh-CN/README-zh_CN.md) +* [Türkçe](../tr-TR/README-tr_TR.md) --- From 253c060f8c3c5935d1e0cab6be174a273ffc1030 Mon Sep 17 00:00:00 2001 From: Do Trung Kien Date: Fri, 30 Aug 2019 07:59:31 +0700 Subject: [PATCH 322/915] translate next 10 questions (from 84 to 93) into Vietnamese --- vi-VI/README-vi.md | 310 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 310 insertions(+) diff --git a/vi-VI/README-vi.md b/vi-VI/README-vi.md index faf71ded..b6fb6cba 100644 --- a/vi-VI/README-vi.md +++ b/vi-VI/README-vi.md @@ -2634,3 +2634,313 @@ Do đó khi ghi object `person` ra, Tất cả các thuộc tính vẫn như cũ

+ +--- + +###### 84. Output là gì? + +```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 án +

+ +#### Đáp án: C + +Biến số được khai báo với các từ khóa như `const` hay `let` đều là _block-scoped_. Block chính là những khối được bao bọc bởi cặp ngoặc nhọn (`{ }`). Trong trường hợp này nó chính là cặp ngoặc bao quanh những câu lệnh `if/else`. Chúng ta không thể truy cập đến biến đó bên ngoài block, và kết quả là throw một ReferenceError. + +

+
+ +--- + +###### 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)) +``` + +- 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. + +
Đáp án +

+ +#### Đáp án: 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. +Giá trị của `res` trong `.then` thứ hai chính là giá trị trả về từ `.then` trước đó. Chúng ta có thể thực hiện `.then` liên tiếp như vậy, các giá trị sẽ liên tiếp được truyền tới hàm xử lý tiếp theo. + +

+
+ +--- + +###### 86. Bằng cách nào chúng ta có thể set `hasName` bằng `true`, nếu chúng ta không đưa `true` vào đối số? + +```javascript +function getName(name) { + const hasName = // +} +``` + +- A: `!!name` +- B: `name` +- C: `new Boolean(name)` +- D: `name.length` + +
Đáp án +

+ +#### Đáp án: A + +Với `!!name`, chúng ta sẽ đánh giá giá trị của `name` là _truthy_ hay _falsy_. Nếu name là truthy, thì `!name` sẽ trả về `false`. `!false` (hay chính là `!!name` khi này) sẽ trả về `true`. + +Bằng cách set `hasName` bằng với `name`, chúng ta set `hasName` bằng với giá trị đối số đưa vào trong hàm `getName`, không thỏa mãn vì ta đã giới hạn là không đưa `true` vào. + +`new Boolean(true)` trả về một object wrapper, chứ không phải là một giá trị boolean. + +`name.length` trả về độ dài của đối số, chứ không phải `true`. + +

+
+ +--- + +###### 87. Output là gì? + +```javascript +console.log("I want pizza"[0]) +``` + +- A: `"""` +- B: `"I"` +- C: `SyntaxError` +- D: `undefined` + +
Đáp án +

+ +#### Đáp án: B + +Trong trường hợp ta muốn lấy ra một ký tự trong một chuỗi, ta có thể sử dụng toán tử ngoặc vuông. Ký tự đầu tiên sẽ có thứ tự là 0, và cứ tiếp tục như vậy. Trong trường hợp này chúng ta lấy ra ký tự có thứ tự là 0, đó chính là ký tự `"I'`. + +Chú ý là phương thức này không hoạt động với IE7 trở xuống. Thay vì thế ta sử dụng `.charAt()` + +

+
+ +--- + +###### 88. Output là gì? + +```javascript +function sum(num1, num2 = num1) { + console.log(num1 + num2) +} + +sum(10) +``` + +- A: `NaN` +- B: `20` +- C: `ReferenceError` +- D: `undefined` + +
Đáp án +

+ +#### Đáp án: B + +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. + +

+
+ +--- + +###### 89. Output là gì? + +```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 án +

+ +#### Đá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"`. + +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. + +

+
+ +--- + +###### 90. Output là gì? + +```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 án +

+ +#### Đáp án: C + +Classes are syntactical sugar for function constructors. The equivalent of the `Person` class as a function constructor would be: +Classes chỉ đơn thuần là `syntactical sugar` (cú pháp đặc biệt) của function constructors mà thôi. Nó tương đương với việc ta viết một function thế này: + +```javascript +function Person() { + 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"`. + +

+
+ +--- + +###### 91. Output là gì? + +```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 án +

+ +#### Đá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. + +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. + +

+
+ +--- + +###### 92. Output là gì? + +```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 án +

+ +#### Đá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`. + +

+
+ +--- + +###### 93. Output là gì? + +```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 án +

+ +#### Đáp án: A + +`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 ] ]` + +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. + +

+
+ From 1b9f898218cf03e51f58a958872f629a20178b02 Mon Sep 17 00:00:00 2001 From: Do Trung Kien Date: Fri, 30 Aug 2019 09:38:17 +0700 Subject: [PATCH 323/915] translate next questions (from 94 to 101) into Vietnamese --- vi-VI/README-vi.md | 284 ++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 279 insertions(+), 5 deletions(-) diff --git a/vi-VI/README-vi.md b/vi-VI/README-vi.md index b6fb6cba..69ca5835 100644 --- a/vi-VI/README-vi.md +++ b/vi-VI/README-vi.md @@ -2688,7 +2688,6 @@ fetch('https://www.website.com/api/user/1') #### Đáp án: 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. Giá trị của `res` trong `.then` thứ hai chính là giá trị trả về từ `.then` trước đó. Chúng ta có thể thực hiện `.then` liên tiếp như vậy, các giá trị sẽ liên tiếp được truyền tới hàm xử lý tiếp theo.

@@ -2836,7 +2835,6 @@ console.log(typeof member) #### Đáp án: C -Classes are syntactical sugar for function constructors. The equivalent of the `Person` class as a function constructor would be: Classes chỉ đơn thuần là `syntactical sugar` (cú pháp đặc biệt) của function constructors mà thôi. Nó tương đương với việc ta viết một function thế này: ```javascript @@ -2922,9 +2920,9 @@ for (const [x, y] of Object.entries(person)) { } ``` -- A: `name` `Lydia` and `age` `21` -- B: `["name", "Lydia"]` and `["age", 21]` -- C: `["name", "age"]` and `undefined` +- A: `name` `Lydia` và `age` `21` +- B: `["name", "Lydia"]` và `["age", 21]` +- C: `["name", "age"]` và `undefined` - D: `Error`
Đáp án @@ -2944,3 +2942,279 @@ Mảng con thứ hai là `[ "age", 21 ]`, nên `x` sẽ là `"age"`, và `y` s

+--- + +###### 94. Output là gì? + +```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 án +

+ +#### Đá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. + +```javascript +function getItems(fruitList, favoriteFruit, ...args) { + return [...fruitList, ...args, favoriteFruit] +} + +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' ]` +

+
+ +--- + +###### 95. Output là gì? + +```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` và `b is bigger`, `3` +- B: `a is bigger`, `undefined` và `b is bigger`, `undefined` +- C: `undefined` và `undefined` +- D: `SyntaxError` + +
Đáp án +

+ +#### Đá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. + +Ở đâ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 +``` + +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é! + +

+
+ +--- + +###### 96. Output là gì? + +```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 án +

+ +#### Đáp án: B + +Chúng ta có thể set một class với giá trị là một classes/function constructor khác. Trong trường hợp này, ta set `Person` bằng với `AnotherPerson`. Trong constructor, `this.name` là `Sarah`, do đó giá trị của thuộc tính này trong instance `member` chính là `"Sarah"`. + +

+
+ +--- + +###### 97. Output là gì? + +```javascript +const info = { + [Symbol('a')]: 'b' +} + +console.log(info) +console.log(Object.keys(info)) +``` + +- A: `{Symbol('a'): 'b'}` và `["{Symbol('a')"]` +- B: `{}` và `[]` +- C: `{ a: "b" }` và `["a"]` +- D: `{Symbol('a'): 'b'}` và `[]` + +
Đáp án +

+ +#### Đáp án: D + +Phương thức `Object.keys` sẽ trả về toàn bộ những key của các thuộc tính _enumerable_ trên một object. Nhưng Symbol không phải dạng _enumerable_. do đó nó sẽ trả về một mảng rỗng. Tuy nhiên khi ta log ra toàn bộ object, thì ta sẽ ghi ra toàn bộ các thuộc tính, cho dù đó có là thuộc tính _enumerable_ hay không. + +Đó chính là một đặc trưng của Symbol: Bên cạnh việc nó biểu diễn một giá trị duy nhất (tránh việc xảy ra xung đột tên gọi, ví dụ khi ta sử dụng 2 thư viện mà muốn thêm thuộc tính vào cho cùng một object chẳng hạn), nó còn giúp "ẩn" thuộc tính đó đi (dù không hoàn toàn, ta vẫn có thể truy cập được bằng cách sử dụng phương thức `Object.getOwnPropertySymbols()`). + +

+
+ +--- + +###### 98. Output là gì? + +```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]]` và `undefined` +- B: `[1, [2, 3, 4]]` và `{ name: "Lydia", age: 21 }` +- C: `[1, 2, 3, 4]` và `{ name: "Lydia", age: 21 }` +- D: `Error` và `{ name: "Lydia", age: 21 }` + +
Đáp án +

+ +#### Đáp án: A + +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]` + + 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 })``` + +Do không giá trị nào được trả về, kết quả sẽ là `undefined`. + +

+
+ +--- + +###### 99. Output là gì? + +```javascript +const name = "Lydia" + +console.log(name()) +``` + +- A: `SyntaxError` +- B: `ReferenceError` +- C: `TypeError` +- D: `undefined` + +
Đáp án +

+ +#### Đá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. + +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`. + +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. + +

+
+ +--- + +###### 100. Output là gì? + +```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` +``` + +- 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 án +

+ +#### Đáp án: B + +`[]` là một giá trị truthy. Với phép toán `&&` , giá trị bên phải sẽ được trả về nếu giá trị bên trái là truthy. Trong trường hợp này giá trị bên trái `[]` là truthy, nên `"Im'` sẽ được trả về. + +`""` là một giá trị falsy. Nếu giá trị bên trái là falsy, không có gì được trả về cả. Do đó `n't` sẽ không được trả về. + +

+
+ +--- + +###### 101. Output là gì? + +```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 án +

+ +#### Đáp án: C + +Với phép toán `||`, ta sẽ trả về giá trị truethy đầu tiên. Nếu tất cả đều là falsy, giá trị cuối cùng sẽ được trả về. + +`(false || {} || null)`: object rỗng `{}` là một giá trị truthy. Nó là giá trị truethy đầu tiên và duy nhất nên sẽ được trả về. Do đó `one` sẽ là `{}`. + +`(null || false || "")`: Tất cả toán hạng đều là falsy. Có nghĩa là toán hạng cuối cùng `""` sẽ được trả về. Do đó `two` sẽ là `""`. + +`([] || 0 || "")`: mảng rỗng `[]` là một giá trị truthy. Nó là giá trị truthy đầu tiên nên sẽ được trả về. Do đó `three` sẽ là `[]`. + +

+
From 57fc47ba4a455a0c5e364617df1b83f531af905b Mon Sep 17 00:00:00 2001 From: sweetmilkys Date: Sun, 1 Sep 2019 14:01:35 +0900 Subject: [PATCH 324/915] Add translate the questions 87-94 to Korean. --- ko-KR/README-ko_KR.md | 514 +++++++++++++++++++++++++++++++++++++++++- 1 file changed, 504 insertions(+), 10 deletions(-) diff --git a/ko-KR/README-ko_KR.md b/ko-KR/README-ko_KR.md index 686f0d76..09a930f3 100644 --- a/ko-KR/README-ko_KR.md +++ b/ko-KR/README-ko_KR.md @@ -2,7 +2,7 @@ JavaScript 에 관한 객관식 문제를 [Instagram](https://www.instagram.com/theavocoder)에 매일 게시하고 있어요, 물론 여기에도 게시할 거예요! -초급부터 고급까지: JavaScript를 얼마나 잘 알고 있는지 테스트하거나, 지식을 조금 더 새롭게 하거나, 코딩 면접을 준비하세요! :muscle: :rocket: 이 기록을 매주 새로운 질문으로 업데이트해요. 마지막 업데이트: 7월 26일 +초급부터 고급까지: JavaScript를 얼마나 잘 알고 있는지 테스트하거나, 지식을 조금 더 새롭게 하거나, 코딩 면접을 준비하세요! :muscle: :rocket: 이 기록을 매주 새로운 질문으로 업데이트해요. 마지막 업데이트: 8월 17일 정답은 질문 아래 접힌 부분에 있어요, 그냥 클릭하면 펼칠 수 있어요. 행운을 빌어요 :heart: @@ -2471,7 +2471,7 @@ console.log(addFunction(5 * 2)); --- -###### 79. 무엇이 출력 될까요? +###### 79. 무엇이 출력 될까요? ```javascript const myLifeSummedUp = ["☕", "💻", "🍷", "🍫"] @@ -2493,7 +2493,7 @@ for (let item of myLifeSummedUp) {
정답

-#### Answer: A +#### 정답: A _for-in_ 루프에서는, **열거 가능한** 속성들에 대해 반복 할 수 있어요. 배열에서, 열거 가능한 속성들은 배열 요소들의 "키"이고, 실제로는 그들의 인덱스죠. 배열을 다음과 같이 볼 수 있어요: @@ -2523,7 +2523,7 @@ console.log(list);

정답

-#### Answer: C +#### 정답: C 배열 요소들은 모든 값을 포함 할 수 있어요. Numbers, strings, objects, 다른 arrays, null, boolean 값, undefined, 그리고 자료형, 함수, 연산자와 같은 표현식들 @@ -2552,7 +2552,7 @@ console.log(sayHi());

정답

-#### Answer: B +#### 정답: B 기본값으로, 함수에 값이 전달되지 않으면, 인수는 `undefined` 값을 가져요. 이 경우, `name` 인수를 위한 값을 전달하지 않았어요. `name`은 `undefined`로 출력돼요. @@ -2595,7 +2595,7 @@ setTimeout(() => {

정답

-#### Answer: B +#### 정답: B `this`키워드의 값은 사용하는 곳에 따라 달라요. **메소드**에서 `getStatus`메소드 처럼, `this`키워드는 _메소드가 속한 객체_ 를 참조해요. 이 메소드는 `data` 객체에 속해 있어, `this`는 `data`객체를 참조해요. `this.status`를 출력할 때, `data`객체의 `status` 속성 `"🥑"`이 출력돼요. @@ -2628,7 +2628,7 @@ console.log(person);

정답

-#### Answer: A +#### 정답: A `city` 변수를 `person` rorcpdml `city`라고 불리는 속성 값으로 설정 했어요. 이 객체에서는 `city`라고 불리는 속성이 없기 때문에, `city`는 `undefined`의 값을 가져요. @@ -2667,7 +2667,7 @@ console.log(checkAge(21));

정답

-#### Answer: C +#### 정답: C `const`와 `let` 키워드를 사용한 변수는 _블록-스코프_ 예요. 블록은 중괄호 (`{ }`) 사이에 있는 것이죠. 이 경우, if/else 표현식의 중괄호를 의미해요. 블록 안에 선언된 건 블록 밖의 변수들을 참조하지 못해, ReferenceError를 던져요. @@ -2692,7 +2692,7 @@ fetch('https://www.website.com/api/user/1')

정답

-#### Answer: C +#### 정답: C 두번째 `.then`에서의 `res`의 값은 이전`.then`에서 리턴된 값이에요. 이것 처럼 `.then`을 계속해서 연결할 수 있고, 값은 계속해서 다음 핸들러로 전달 돼요. @@ -2717,7 +2717,7 @@ function getName(name) {

정답

-#### Answer: A +#### 정답: A `!!name`에서, 우리는 `name`의 값이 참 같은지 거짓 같은지 결정해요. 만약 테스트 하려는 name이 참 같다면, `!name`은 `false`를 리턴해요. `!false` (실제로는 `!!name`)는 `true`를 리턴해요. @@ -2729,3 +2729,497 @@ function getName(name) {

+ +--- + +###### 87. 무엇이 출력 될까요? + +```javascript +console.log("I want pizza"[0]); +``` + +- A: `"""` +- B: `"I"` +- C: `SyntaxError` +- D: `undefined` + +
정답 +

+ +#### 정답: B + +문자열의 특정 인덱스의 문자를 얻으려면, 대괄호 표기법을 사용하면 돼요. 문자열의 첫 번째 문자는 인덱스 0과 기타등등을 가지고 있어요. 이 경우 문자 `"I'`인 인덱스 0이 출력되는 요소를 갖길 원해요. + +이 방법은 IE7 이하에서는 지원되지 않는다는 것을 유의하세요. 이 경우, `.charAt()`를 사용하세요. + +

+
+ +--- + +###### 88. 무엇이 출력 될까요? + +```javascript +function sum(num1, num2 = num1) { + console.log(num1 + num2) +} + +sum(10) +``` + +- A: `NaN` +- B: `20` +- C: `ReferenceError` +- D: `undefined` + +
정답 +

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

+
+ +--- + +###### 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` 파일에 있는 _모든 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의 이름들과 그에 해당하는 값들을 가져요. + +

+
+ +--- + +###### 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` 클래스와 동등한 것은 다음과 같아요: + +```javascript +function Person() { + this.name = name; +} +``` + +`new`와 함께 불려진 함수 생성자는 `Person`의 인스턴스를 생성하고, `typeof` 키워드는 인스턴스의 `"object"`를 리턴해요. `typeof member`는 `"object"`을 리턴해요. + +

+
+ +--- + +###### 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`. + +그리고나서, `.push` 메소드를 `newList`에 사용하려고 했어요. `newList`는 숫자 값 `4` 이기 때문에, `.push` 메소드를 사용할 수 없어요: TypeError가 던져져요. + +

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

+
+ +--- + +###### 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(person)`은 키와 값을 세트로 가진 배열의 배열을 리턴해요: + +`[ [ '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`을 출력해요. + +

+
+ +--- + +###### 94. 무엇이 출력 될까요? + +```javascript +function getItems(fruitList, ...args, favoriteFruit) { + return [...fruitList, ...args, favoriteFruit] +} + +console.log(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") +``` + +The above example works. This returns the array `[ 'banana', 'apple', 'orange', 'pear' ]` +

+
+ +--- + +###### 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 + +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. 무엇이 출력 될까요? + +```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 + +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. 무엇이 출력 될까요? + +```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 + +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. 무엇이 출력 될까요? + +```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 + +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, containig 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: + +```const getUser = user => ({ name: user.name, age: user.age })``` + +Since no value gets returned in this case, the function returns `undefined`. + +

+
+ +--- + +###### 99. 무엇이 출력 될까요? + +```javascript +const name = "Lydia" + +console.log(name()) +``` + +- A: `SyntaxError` +- B: `ReferenceError` +- C: `TypeError` +- D: `undefined` + +
정답 +

+ +#### 정답: C + +The variable `name` holds the value of a string, which is not a function, thus cannot invoke. + +TypeErrors get thrown wehn 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` + +
정답 +

+ +#### 정답: 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` + +
정답 +

+ +#### 정답: 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 past 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 `[]`. + +

+
From be73a4f05920e6aba47a1481eefdce871d8c5feb Mon Sep 17 00:00:00 2001 From: sweetmilkys Date: Sun, 1 Sep 2019 23:54:03 +0900 Subject: [PATCH 325/915] Add translate the questions 95-97 to Korean. --- ko-KR/README-ko_KR.md | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/ko-KR/README-ko_KR.md b/ko-KR/README-ko_KR.md index 09a930f3..0e58cada 100644 --- a/ko-KR/README-ko_KR.md +++ b/ko-KR/README-ko_KR.md @@ -3013,16 +3013,16 @@ 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. +자바스크립트에서, 세미콜론을 (`;`)을 명시적으로 포함하여 쓰지 _않_ 더라도, 자바스크립트 엔진은 여전히 문 뒤에 그들을 추가해줘요. 이것은 **자동 세미콜론 삽입**이라고 불려요. 예를 들어 문은 변수, 또는 `throw`, `return`, `break` 등과 같은 키워드가 될 수도 있어요. -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: +여기, `return`문을 썼고, 다른 값 `a + b`은 _새로운 줄_ 에 쓰였어요. 그러나, 새로운 줄이기 때문에, 엔진은 실제로 그 값이 리턴되길 바라는지 알 수 없어요. 대신에, 자동적으로 `return` 뒤에 세미콜론을 더해줘요. 이것을 볼 수 있을거에요: ```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! +`return` 키워드 뒤에 함수가 실행되는 것이 중단되기 때문에, `a + b`의 의미는 도달되지 않아요. 여기서 처럼, 만약 아무 값도 리턴되지 않는다면, 함수는 `undefined`를 리턴할 거예요. `if/else`문 뒤에는 자동으로 삽입되는 게 없다는 걸 유의해요!

@@ -3058,7 +3058,7 @@ console.log(member.name) #### 정답: 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"`. +다른 클래스/함수 생성자로 클래스를 설정할 수 있어요. 이 경우, `Person`을 `AnotherPerson`로 설정했어요. 이 생성자의 name은 `Sarah`예요, 따라서 새로운 `Person`의 인스턴스 `member`의 name 속성은 `"Sarah"`예요.

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

From 2652e4aaa37305cc300bce985031ed3b296fb67c Mon Sep 17 00:00:00 2001 From: sweetmilkys Date: Sun, 8 Sep 2019 16:14:02 +0900 Subject: [PATCH 326/915] Add translate the questions 98-101 to Korean. --- ko-KR/README-ko_KR.md | 67 ++++++++++++++++++++++--------------------- 1 file changed, 34 insertions(+), 33 deletions(-) diff --git a/ko-KR/README-ko_KR.md b/ko-KR/README-ko_KR.md index 0e58cada..4ef08020 100644 --- a/ko-KR/README-ko_KR.md +++ b/ko-KR/README-ko_KR.md @@ -2926,9 +2926,9 @@ for (const [x, y] of Object.entries(person)) { } ``` -- A: `name` `Lydia` and `age` `21` -- B: `["name", "Lydia"]` and `["age", 21]` -- C: `["name", "age"]` and `undefined` +- A: `name` `Lydia` 그리고 `age` `21` +- B: `["name", "Lydia"]` 그리고 `["age", 21]` +- C: `["name", "age"]` 그리고 `undefined` - D: `Error`
정답 @@ -3003,9 +3003,9 @@ 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` +- A: `a is bigger`, `6` 그리고 `b is bigger`, `3` +- B: `a is bigger`, `undefined` 그리고 `b is bigger`, `undefined` +- C: `undefined` 그리고 `undefined` - D: `SyntaxError`
정답 @@ -3013,7 +3013,7 @@ console.log(nums(1, 2)) #### 정답: B -자바스크립트에서, 세미콜론을 (`;`)을 명시적으로 포함하여 쓰지 _않_ 더라도, 자바스크립트 엔진은 여전히 문 뒤에 그들을 추가해줘요. 이것은 **자동 세미콜론 삽입**이라고 불려요. 예를 들어 문은 변수, 또는 `throw`, `return`, `break` 등과 같은 키워드가 될 수도 있어요. +JavaScript에서, 세미콜론을 (`;`)을 명시적으로 포함하여 쓰지 _않_ 더라도, JavaScript 엔진은 여전히 문 뒤에 그들을 추가해줘요. 이것은 **자동 세미콜론 삽입**이라고 불려요. 예를 들어 문은 변수, 또는 `throw`, `return`, `break` 등과 같은 키워드가 될 수도 있어요. 여기, `return`문을 썼고, 다른 값 `a + b`은 _새로운 줄_ 에 쓰였어요. 그러나, 새로운 줄이기 때문에, 엔진은 실제로 그 값이 리턴되길 바라는지 알 수 없어요. 대신에, 자동적으로 `return` 뒤에 세미콜론을 더해줘요. 이것을 볼 수 있을거에요: @@ -3076,17 +3076,17 @@ 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 `[]` +- A: `{Symbol('a'): 'b'}` 그리고 `["{Symbol('a')"]` +- B: `{}` 그리고 `[]` +- C: `{ a: "b" }` 그리고 `["a"]` +- D: `{Symbol('a'): 'b'}` 그리고 `[]`
정답

#### 정답: D -심볼은 _열거 가능_ 하지 않아요. Object.keys 메소드는 객체의 모든 _열거 가능_ 한 키 속성들을 리턴해요. 심볼은 보이지 않고, 빈 객체가 리턴돼요. 객체 전체를 출력할때, 모든 속성들은 보여요, 심지어 열거 불가능한 것이라해도. +심볼은 _열거 불가능_ 해요. Object.keys 메소드는 객체의 모든 _열거 가능_ 한 키 속성들을 리턴해요. 심볼은 보이지 않고, 빈 객체가 리턴돼요. 객체 전체를 출력할때, 모든 속성들은 보여요, 심지어 열거 불가능한 것이라해도. 이것은 심볼의 많은 특성 중 하나에요: 완전히 고유한 값(예를들어 2개의 라이브러리를 같은 객체의 속성으로 추가하고 싶을때, 객체의 우연한 이름 충돌을 방지해요)을 나타내는 것 외에, 이 방법으로 객체의 속성을 "숨길" 수 있어요(비록 완전히는 아닐지라도. 여전히 `Object.getOwnPropertySymbols()` 메소드를 사용해 심볼에 접근 할 수 있어요). @@ -3108,27 +3108,27 @@ 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: `[1, [2, 3, 4]]` 그리고 `undefined` +- B: `[1, [2, 3, 4]]` 그리고 `{ name: "Lydia", age: 21 }` +- C: `[1, 2, 3, 4]` 그리고 `{ name: "Lydia", age: 21 }` +- D: `Error` 그리고 `{ name: "Lydia", age: 21 }`

정답

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

@@ -3153,22 +3153,23 @@ console.log(name()) #### 정답: C -The variable `name` holds the value of a string, which is not a function, thus cannot invoke. +변수 `name`은 문자열을 값으로 가지고 있고, 함수가 아니죠, 따라서 호출할 수 없어요. -TypeErrors get thrown wehn 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! +TypeErrors는 값이 예상된 유형이 아닐 경우 던져져요. JavaScript는 `name`을 호출하려고 했기 때문에 함수일거라 예상했어요. 그러나 문자열이였기 때문에, TypeError가 던져져요: name은 함수가 아니죠! -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. +SyntaxErrors는 어떤 것을 썼을때 JavaScript에서 유효하지 않을 때 던져져요, 예를들어 `return`을 `retrun`로 썼을때 말이죠. + +ReferenceErrors는 JavaScript가 접근하려고 하는 값의 참조를 찾을 수 없을 때 던져져요.

--- -###### 100. What's the value of output? +###### 100. output의 값은 무엇일까요? ```javascript -// 🎉✨ This is my 100th question! ✨🎉 +// 🎉✨ 이번이 내 100번째 질문이에요! ✨🎉 const output = `${[] && 'Im'}possible! You should${'' && `n't`} see a therapist after so much JavaScript lol` @@ -3184,16 +3185,16 @@ You should${'' && `n't`} see a therapist after so much JavaScript lol` #### 정답: 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. +`[]`은 참 같은 값이에요. `&&` 연산자를 사용할 때, 만약 왼쪽에 있는 값이 참 같은 값이라면 오른쪽 값은 리턴될 거에요. 이 경우, 왼쪽의 값 `[]`은 참 같은 값이에요, 따라서 `'Im'`은 리턴될 거예요. -`""` is a falsy value. If the left-hand value is falsy, nothing gets returned. `n't` doesn't get returned. +`""`은 거짓 같은 값이에요. 만약 왼쪽 값이 거짓 같은 값이라면, 리턴되는 것은 없어요. `n't`은 리턴되지 않아요.

--- -###### 101. What's the value of output? +###### 101. 무엇이 출력 될까요? ```javascript const one = (false || {} || null) @@ -3213,13 +3214,13 @@ console.log(one, two, three) #### 정답: 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 `{}`. +`(false || {} || null)`: 빈 객체 `{}`는 진짜 같은 값이에요. 이것은 최초로(그리고 유일하게) 진짜 같은 값이라 리턴돼요. `one`은 `{}`이에요. -`(null || false || "")`: all operands are falsy values. This means that the past operand, `""` gets returned. `two` is equal to `""`. +`(null || false || "")`: 모든 피연산자는 가짜 같은 값이에요. 이것은 마지막 피연산자 `""`가 리턴된다는 것을 의미해요. `two`는 `""`이에요. -`([] || 0 || "")`: the empty array`[]` is a truthy value. This is the first truthy value, which gets returned. `three` is equal to `[]`. +`([] || 0 || "")`: 빈 배열 `[]`은 진짜 같은 값이에요. 이것은 최초의 진짜 같은 값이라 리턴돼요. `three`은 `[]`이에요.

From e9166f5dd560b1ad518d5a9658049884c5677fa5 Mon Sep 17 00:00:00 2001 From: amullabaev Date: Sat, 21 Sep 2019 23:20:07 +0600 Subject: [PATCH 327/915] fix: improved russian translation --- ru-RU/README.md | 51 ++++++++++++++++++++++++------------------------- 1 file changed, 25 insertions(+), 26 deletions(-) diff --git a/ru-RU/README.md b/ru-RU/README.md index a199ff80..376c08f8 100644 --- a/ru-RU/README.md +++ b/ru-RU/README.md @@ -1083,7 +1083,7 @@ undefined; - `null` - `NaN` - `0` -- `''` (empty string) +- `''` (пустая строка) - `false` Конструкторы функций, такие как `new Number` и `new Boolean` являются "истинными". @@ -1337,9 +1337,9 @@ console.log(gen.next().value); Обычные функции не могут быть остановлены на полпути после вызова. Однако функцию генератор можно "остановить" на полпути, а затем продолжить с того места, где она остановилась. Каждый раз, когда в функции-генераторе встречает ключевое слово `yield`, функция возвращает значение, указанное после него. Обратите внимание, что функция генератора в этом случае не _return_ значение, оно _yields_ значение. -Сначала мы инициализируем функцию генератор с `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.

@@ -1370,7 +1370,7 @@ Promise.race([firstPromise, secondPromise]).then(res => console.log(res)); #### Ответ: B -Когда мы передаем несколько промисов методу `Promise.race`, он разрешает/отклоняет _первый_ промис, который разрешает/отклоняет. В метод `setTimeout` мы передаем таймер: 500 мс для первого промиса (`firstPromise`) и 100 мс для второго промиса (`secondPromise`). Это означает, что `secondPromise` разрешается первым со значением `'два'`. `res` теперь содержит значение `'два'`, которое выводиться в консоль. +Когда мы передаем несколько промисов методу `Promise.race`, он разрешает/отклоняет _первый_ промис, который разрешается/отклоняется. В метод `setTimeout` мы передаем таймер: 500 мс для первого промиса (`firstPromise`) и 100 мс для второго промиса (`secondPromise`). Это означает, что `secondPromise` разрешается первым со значением `'два'`. `res` теперь содержит значение `'два'`, которое выводиться в консоль.

@@ -1660,7 +1660,7 @@ let x = y; Когда мы устанавливаем `y` равным` 10`, мы фактически добавляем свойство `y` к глобальному объекту (`window` в браузере, `global` в Node). В браузере `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"`. @@ -1993,13 +1993,13 @@ multiply(value); #### Ответ: C -В ES6 мы можем инициализировать параметры значением по умолчанию. Значением параметра будет значение по умолчанию, если никакое другое значение не было передано функции, или если значение параметра равно `"undefined"`. В этом случае мы распространяем свойства объекта `value` на новый объект, поэтому значение` x` по умолчанию равно `{number: 10}`. +В ES6 мы можем инициализировать параметры значением по умолчанию. Значением параметра будет значение по умолчанию, если никакое другое значение не было передано функции или если значение параметра равно `"undefined"`. В этом случае мы распространяем свойства объекта `value` на новый объект, поэтому значение `x` по умолчанию равно `{number: 10}`. Аргумент по умолчанию реализуется в момент _call time_! Каждый раз, когда мы вызываем функцию, создается _new_ объект. Мы вызываем функцию `multiply` первые два раза, не передавая значение: `x` имеет значение по умолчанию `{number: 10}`. Затем мы записываем умноженное значение этого числа, которое равно `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`.

@@ -2012,10 +2012,10 @@ multiply(value); [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` +- A: `1` `2`, `3` `3` и `6` `4` +- B: `1` `2`, `2` `3` и `3` `4` +- C: `1` `undefined`, `2` `undefined`, `3` `undefined` и `4` `undefined` +- D: `1` `2`, `undefined` `3` и `undefined` `4`
Ответ

@@ -2166,7 +2166,7 @@ console.log(name.padStart(2)) #### Ответ: 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,7 +2183,7 @@ console.log("🥑" + "💻"); - A: `"🥑💻"` - B: `257548` -- C: A string containing their code points +- C: Строка, содержащая кодовые обозначения - D: Error

Ответ @@ -2214,17 +2214,17 @@ 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")` +- A: `game.next("Yes").value` и `game.next().value` +- B: `game.next.value("Yes")` и `game.next.value()` +- C: `game.next().value` и `game.next("Yes").value` +- D: `game.next.value()` и `game.next.value("Yes")`
Ответ

#### Ответ: C -Функция генератора "приостанавливает" выполнение, когда видит ключевое слово yield. Во-первых, мы должны позволить функции выдать строку "Do you love JavaScript?", Что можно сделать, вызвав `game.next (). Value`. +Функция генератора "приостанавливает" выполнение, когда видит ключевое слово yield. Во-первых, мы должны позволить функции выдать строку "Do you love JavaScript?", что можно сделать, вызвав `game.next().value`. Каждая строка выполняется до тех пор, пока не найдет первое ключевое слово `yield`. В первой строке функции есть ключевое слово `yield` на первом месте: выполнение останавливается с первым выходом! _Это означает, что переменная `answer` еще не определена!_ @@ -2405,8 +2405,8 @@ function sum(a, b) { } ``` -- A: Yes -- B: No +- A: Да +- B: Нет

Ответ

@@ -2668,7 +2668,7 @@ console.log(checkAge(21)) #### Ответ: C -Переменные с ключевыми словами `const` и `let` являются _block-scoped_. Блок - это что-то между фигурными скобками (`{}`). В этом случае в фигурных скобках операторов if/else. Вы не можете ссылаться на переменную за пределами блока, в котором она объявлена, вызывается ReferenceError. +Переменные с ключевыми словами `const` и `let` имеют _блочную видимость_. Блок - это что-то между фигурными скобками (`{}`). В этом случае в фигурных скобках операторов if/else. Вы не можете ссылаться на переменную за пределами блока, в котором она объявлена, вызывается ReferenceError.

@@ -2683,10 +2683,10 @@ fetch('https://www.website.com/api/user/1') .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. +- A: Результат метода `fetch`. +- B: Результат второго вызова метода `fetch`. +- C: Результат коллбэка в предыдущем `.then()`. +- D: Всегда будет `undefined`.
Ответ

@@ -3116,7 +3116,6 @@ console.log(getUser(user))

#### Ответ: 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: Функция `getList` получает массив в качестве аргумента. Между скобками функции `getList` мы сразу же деструктурируем этот массив. Вы можете увидеть это как: `[x, ...y] = [1, 2, 3, 4]` From 4794cfb60fc26209c4105c46e6986160cd9d8e3e Mon Sep 17 00:00:00 2001 From: amullabaev Date: Thu, 26 Sep 2019 14:52:02 +0600 Subject: [PATCH 328/915] fix: returned comma back --- 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 376c08f8..28d243d8 100644 --- a/ru-RU/README.md +++ b/ru-RU/README.md @@ -1993,7 +1993,7 @@ multiply(value); #### Ответ: C -В ES6 мы можем инициализировать параметры значением по умолчанию. Значением параметра будет значение по умолчанию, если никакое другое значение не было передано функции или если значение параметра равно `"undefined"`. В этом случае мы распространяем свойства объекта `value` на новый объект, поэтому значение `x` по умолчанию равно `{number: 10}`. +В ES6 мы можем инициализировать параметры значением по умолчанию. Значением параметра будет значение по умолчанию, если никакое другое значение не было передано функции, или если значение параметра равно `"undefined"`. В этом случае мы распространяем свойства объекта `value` на новый объект, поэтому значение `x` по умолчанию равно `{number: 10}`. Аргумент по умолчанию реализуется в момент _call time_! Каждый раз, когда мы вызываем функцию, создается _new_ объект. Мы вызываем функцию `multiply` первые два раза, не передавая значение: `x` имеет значение по умолчанию `{number: 10}`. Затем мы записываем умноженное значение этого числа, которое равно `20`. From 60cd7ced1dcf42a956a0288279b1947dfac45a0d Mon Sep 17 00:00:00 2001 From: Lydia Hallie Date: Fri, 27 Sep 2019 13:15:45 -0400 Subject: [PATCH 329/915] Add questions 102-108 --- README.md | 232 ++++++++++++++++++++++++++++++++++++++++++++++++ en-EN/README.md | 232 ++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 464 insertions(+) diff --git a/README.md b/README.md index 562836f6..5aafc3bb 100644 --- a/README.md +++ b/README.md @@ -3254,5 +3254,237 @@ With the `||` operator, we can return the first truthy operand. If all values ar `([] || 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') +} + +function secondFunction() { + console.log(await myPromise()) + console.log('second') +} +``` + +- 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` + +
Answer +

+ +#### Answer: 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 befoer 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` + +
Answer +

+ +#### Answer: 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 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, 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"`. + +

+
+ +--- + +###### 104. What's its value? + +```javascript +Promise.resolve(5) +``` + +- A: `5` +- B: `Promise {: 5}` +- C: `Promise {: 5}` +- D: `Error` + +
Answer +

+ +#### Answer: 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(perosn) +``` + +- A: `Not the same!` +- B: `They are the same!` +- C: `ReferenceError` +- D: `SyntaxError` + +
Answer +

+ +#### Answer: 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` + +
Answer +

+ +#### Answer: 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 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. + +

+
+ +--- + +###### 107. What's its value? + +```javascript +console.log('❤️' === '❤️') +``` + +- A: `true` +- B: `false` + +
Answer +

+ +#### Answer: 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` + +
Answer +

+ +#### Answer: 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. +

\ No newline at end of file diff --git a/en-EN/README.md b/en-EN/README.md index 2d7557f2..b01a834e 100644 --- a/en-EN/README.md +++ b/en-EN/README.md @@ -3254,5 +3254,237 @@ With the `||` operator, we can return the first truthy operand. If all values ar `([] || 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') +} + +function secondFunction() { + console.log(await myPromise()) + console.log('second') +} +``` + +- 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` + +
Answer +

+ +#### Answer: 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 befoer 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` + +
Answer +

+ +#### Answer: 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 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, 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"`. + +

+
+ +--- + +###### 104. What's its value? + +```javascript +Promise.resolve(5) +``` + +- A: `5` +- B: `Promise {: 5}` +- C: `Promise {: 5}` +- D: `Error` + +
Answer +

+ +#### Answer: 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(perosn) +``` + +- A: `Not the same!` +- B: `They are the same!` +- C: `ReferenceError` +- D: `SyntaxError` + +
Answer +

+ +#### Answer: 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` + +
Answer +

+ +#### Answer: 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 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. + +

+
+ +--- + +###### 107. What's its value? + +```javascript +console.log('❤️' === '❤️') +``` + +- A: `true` +- B: `false` + +
Answer +

+ +#### Answer: 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` + +
Answer +

+ +#### Answer: 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. +

\ No newline at end of file From 8ac6eb4eafb3aae6859a3e07c1c31cda33af84ed Mon Sep 17 00:00:00 2001 From: Lydia Hallie Date: Fri, 27 Sep 2019 13:23:31 -0400 Subject: [PATCH 330/915] Update README.md --- README.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index 12e6c391..b7a6dc0c 100644 --- a/README.md +++ b/README.md @@ -2,7 +2,7 @@ I post daily multiple choice JavaScript questions on my [Instagram](https://www.instagram.com/theavocoder), which I'll also post 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 weekly with new questions. Last update: August 17th +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 weekly with new questions. Last update: September 27th The answers are in the collapsed sections below the questions, simply click on them to expand it. Good luck :heart: @@ -2985,7 +2985,7 @@ The above example works. This returns the array `[ 'banana', 'apple', 'orange', --- -###### 95. What's the output? +###### 95. What's the output? ```javascript function nums(a, b) { @@ -3225,7 +3225,7 @@ With the `||` operator, we can return the first truthy operand. If all values ar --- -###### 102. What's the value of output? +###### 102. What's the value of output? ```javascript const myPromise = () => Promise.resolve('I have resolved!') @@ -3453,4 +3453,4 @@ With `splice` method, we modify the original array by deleting, replacing or add `map`, `filter` and `slice` return a new array, `find` returns an element, and `reduce` returns a reduced value.

-
\ No newline at end of file +
From 6510130846895ea3d71a37d5e17126b0c160304a Mon Sep 17 00:00:00 2001 From: Jacob Herper Date: Fri, 27 Sep 2019 21:29:22 +0100 Subject: [PATCH 331/915] Typos fixed in English --- en-EN/README.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/en-EN/README.md b/en-EN/README.md index dd6a8d39..df50f838 100644 --- a/en-EN/README.md +++ b/en-EN/README.md @@ -3257,7 +3257,7 @@ We can get this value with both `.then` and the `await` keyword in an `async` fu 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 befoer moving to the next line. +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. @@ -3290,11 +3290,11 @@ for (let item of set) { #### Answer: 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 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, 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"` 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"`. @@ -3453,4 +3453,4 @@ With `splice` method, we modify the original array by deleting, replacing or add `map`, `filter` and `slice` return a new array, `find` returns an element, and `reduce` returns a reduced value.

-
\ No newline at end of file + From c9705e437391ccb7ebb90da6666760210748c3e0 Mon Sep 17 00:00:00 2001 From: Jacob Herper Date: Fri, 27 Sep 2019 21:30:56 +0100 Subject: [PATCH 332/915] Questions 102 - 108 translated to German --- de-DE/README.md | 233 ++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 233 insertions(+) diff --git a/de-DE/README.md b/de-DE/README.md index f555a38e..f76b7374 100644 --- a/de-DE/README.md +++ b/de-DE/README.md @@ -3225,3 +3225,236 @@ 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!') + +function firstFunction() { + myPromise().then(res => console.log(res)) + console.log('second') +} + +function secondFunction() { + console.log(await myPromise()) + console.log('second') +} +``` + +- A: `I have resolved!`, `second` und `I have resolved!`, `second` +- B: `second`, `I have resolved!` und `second`, `I have resolved!` +- C: `I have resolved!`, `second` und `second`, `I have resolved!` +- D: `second`, `I have resolved!` und `I have resolved!`, `second` + +
Antwort +

+ +#### Antwort: D + +Mit einem Promise sagen wir _Ich möchte diese Funktion ausführen, aber ich lege sie erstmal beiseite, weil sie eine Weile braucht. Erst wenn ein bestimmter Wert ausgegeben (oder rejected) wird und der Call Stack leer ist möchte ich den Wert nutzen._ + +Wir können auf den Wert mit `.then()` oder `await` in einer `async` Funktion zugreifen, aber `.then()` und `await` unterscheiden sich in einem bestimmten Punkt. + +In `firstFunction` legen wir `myPromise` beiseite, während die Funktion durchläuft, aber wir arbeiten anderen Code ab, hier `console.log('second')`. +Dann wird die Funktion abgeschlossen und der String `I have resolved` wird ausgegeben, nachdem sich der Call Stack geleert hat. + +Mit dem `await` Keyword in `secondFunction` wird die Funktion gestoppt bis der Wert ausgegeben wurde, erst dann wird die nächste Zeile ausgeführt. + +Das bedeutet, dass auf `myPromise` gewartet und dann der Wert `I have resolved` ausgegeben wird und erst dann wird die nächste Zeile ausgeführt und `second` wird geloggt. + +

+
+ +--- + +###### 103. Was ist der 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` + +
Antwort +

+ +#### Antwort: C + +Der `+` Operator wird nicht nur für numerische Werte verwendet, wir können mit ihm ebenso Strings zusammenfügen. Immer, wenn JavaScript merkt, dass mindestens ein Wert keine Nummer ist, wird ein String erstellt. + +Der erste Wert ist `1`, was ein numerischer Wert ist. `1 + 2` ergibt die Zahl `3`. + +Der zweite Wert hingegen ist der String `"Lydia"`. `"Lydia"` ist ein String und `2` ist eine Nummer: `2` wird in einem String umgewandelt. `"Lydia"` und `"2"` werden zusammengesetzt, was den String `"Lydia2"` ausgibt. + +`{ name: "Lydia" }` ist ein Objekt. Weder eine Nummer, noch ein Objekt sind ein String, aber beide werden zu Strings konvertiert und `"[Object object]"` wird ausgegeben. `"[Object object]"` zusammengesetzt mit `"2"` wird `"[Object object]2"`. + +

+
+ +--- + +###### 104. Was wird ausgegeben? + +```javascript +Promise.resolve(5) +``` + +- A: `5` +- B: `Promise {: 5}` +- C: `Promise {: 5}` +- D: `Error` + +
Antwort +

+ +#### Antwort: C + +Wir können jeden Wert an `Promise.resolve` übergeben, es muss nicht unbedingt ein Promise sein. Die Methode selbst gibt ein Promise zurück, was einen Wert ausgibt. Wenn man eine normale Funktion übergibt wird das Promise einen normalen Wert ausgeben. Wenn ein Promise übergeben wird so wird ein Promise gelöst und der Wert des gelösten Promises ausgegeben. + +In diesem Fall haben wir nur die Zahl `5` übergeben und diese wird genauso ausgegeben: `5`. + +

+
+ +--- + +###### 105. Was wird ausgegeben? + +```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(perosn) +``` + +- A: `Not the same!` +- B: `They are the same!` +- C: `ReferenceError` +- D: `SyntaxError` + +
Antwort +

+ +#### Antwort: B + +Objekte werden durch eine Referenz übergeben. Wenn wir Objekte auf strikte Gleichheit (`===`) prüfen, vergleichen wir nur deren Referenz. + +Wir setzen den Standardwert für `person2` gleich dem `person` Objekt und übergeben dem `person` Objekt den Wert von `person1`. + +Das bedeutet, dass beide Werte eine Referenz zum gleichen Ort im Speicher aufweisen und daher gleich sind. + +Der Code im `else` Statement wird aufgerufen und `They are the same!` wird geloggt. + +

+
+ +--- + +###### 106. Was wird ausgegeben? + +```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` + +
Antwort +

+ +#### Antwort: D + +In JavaScript gibt es zwei Wege auf Properties an Objekten zuzugreifen: Punkt-Notation oder Klammern-Notation. In diesem Beispiel nutzen wir Punkt-Notation (`colorConfig.colors`) anstelle von Klammern-Notation (`colorConfig["colors"]`). + +Mit Punkt-Notation versucht JavaScript die Property am Objekt mit diesem exakten Namen zu finden. In unserem Beispiel `colors` im `colorConfig` Objekt. Da es keine Property `colorConfig` gibt wird `undefined` ausgegeben. Dann versuchen wir den Wert des ersten Elements mit `[1]` aufzurufen, was an `undefined` nicht möglich ist, wodurch wir `TypeError: Cannot read property '1' of undefined` ausgegeben bekommen. + +JavaScript interpretiert Statements. Wenn wir Klammern-Notation verwenden wird die erste Klammer `[` gefunden und JavaScript sucht solange, bis eine schließende Klammer `]` gefunden wird. Erst dann wird das Statement interpretiert. Hätten wir `colorConfig[colors[1]]` verwendet, wäre der Wert `red` ausgegeben worden. + +

+
+ +--- + +###### 107. Was wird ausgegeben? + +```javascript +console.log('❤️' === '❤️') +``` + +- A: `true` +- B: `false` + +
Antwort +

+ +#### Antwort: A + +Emojis sind im Endeffekt nur Unicodes. Der Unicode für das Herz Emoji ist `"U+2764 U+FE0F"`. Dieser ist immer gleich, für das selbe Emoji und daher wird `true` ausgegeben. + +

+
+ +--- + +###### 108. Welche Methode verändert das ursprüngliche 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` + +
Antwort +

+ +#### Antwort: D + +Mit der `splice` Methode ändern wir das ursprüngliche Array durch löschen, ersetzen oder ergänzen von Elementen. In diesem Fall haben wir 2 Elemente vom Index 1 (`'🥑'` und `'😍'`) entfernt und ✨ stattdessen eingefügt. + +`map`, `filter` und `slice` geben ein neues Array aus, `find` gibt ein Element aus und `reduce` gibt einen neuen Wert aus. + +

+
From b3774fdaee31cd029f517b39c264f344c9d41188 Mon Sep 17 00:00:00 2001 From: Alexander Ivanov Date: Mon, 30 Sep 2019 09:29:56 +0300 Subject: [PATCH 333/915] Fix Q102 sample --- README.md | 15 +++++++++------ en-EN/README.md | 15 +++++++++------ 2 files changed, 18 insertions(+), 12 deletions(-) diff --git a/README.md b/README.md index b7a6dc0c..18c98b89 100644 --- a/README.md +++ b/README.md @@ -3228,17 +3228,20 @@ 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"); } -function secondFunction() { - console.log(await myPromise()) - 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` diff --git a/en-EN/README.md b/en-EN/README.md index dd6a8d39..e42c74a8 100644 --- a/en-EN/README.md +++ b/en-EN/README.md @@ -3228,17 +3228,20 @@ 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"); } -function secondFunction() { - console.log(await myPromise()) - 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` From 7d9b1f7d3a2947f96179cf13fc14eac9a33fe3c9 Mon Sep 17 00:00:00 2001 From: Alexander Ivanov Date: Mon, 30 Sep 2019 09:33:03 +0300 Subject: [PATCH 334/915] Quotes Signed-off-by: Alexander Ivanov --- README.md | 6 +++--- en-EN/README.md | 6 +++--- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/README.md b/README.md index 18c98b89..8e3af826 100644 --- a/README.md +++ b/README.md @@ -3228,16 +3228,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"); + console.log('second'); } async function secondFunction() { console.log(await myPromise()); - console.log("second"); + console.log('second'); } firstFunction(); diff --git a/en-EN/README.md b/en-EN/README.md index e42c74a8..da2cbbe9 100644 --- a/en-EN/README.md +++ b/en-EN/README.md @@ -3228,16 +3228,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"); + console.log('second'); } async function secondFunction() { console.log(await myPromise()); - console.log("second"); + console.log('second'); } firstFunction(); From 124e16bfa04299f24a1169c304a5c8411e65aa48 Mon Sep 17 00:00:00 2001 From: Alexander Ivanov Date: Mon, 30 Sep 2019 09:34:26 +0300 Subject: [PATCH 335/915] Commas Signed-off-by: Alexander Ivanov --- README.md | 14 +++++++------- en-EN/README.md | 14 +++++++------- 2 files changed, 14 insertions(+), 14 deletions(-) diff --git a/README.md b/README.md index 8e3af826..1855cc51 100644 --- a/README.md +++ b/README.md @@ -3228,20 +3228,20 @@ 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(await myPromise()) + console.log('second') } -firstFunction(); -secondFunction(); +firstFunction() +secondFunction() ``` - A: `I have resolved!`, `second` and `I have resolved!`, `second` diff --git a/en-EN/README.md b/en-EN/README.md index da2cbbe9..d0ee584b 100644 --- a/en-EN/README.md +++ b/en-EN/README.md @@ -3228,20 +3228,20 @@ 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(await myPromise()) + console.log('second') } -firstFunction(); -secondFunction(); +firstFunction() +secondFunction() ``` - A: `I have resolved!`, `second` and `I have resolved!`, `second` From a036e033d9c1c3e9d4d3e435b21ba3a3e441861a Mon Sep 17 00:00:00 2001 From: Alexander Ivanov Date: Mon, 30 Sep 2019 11:34:37 +0300 Subject: [PATCH 336/915] Fix Q105 Signed-off-by: Alexander Ivanov --- README.md | 2 +- en-EN/README.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 1855cc51..58d827df 100644 --- a/README.md +++ b/README.md @@ -3344,7 +3344,7 @@ function compareMembers(person1, person2 = person) { const person = { name: "Lydia" } -compareMembers(perosn) +compareMembers(person) ``` - A: `Not the same!` diff --git a/en-EN/README.md b/en-EN/README.md index d0ee584b..819f7648 100644 --- a/en-EN/README.md +++ b/en-EN/README.md @@ -3344,7 +3344,7 @@ function compareMembers(person1, person2 = person) { const person = { name: "Lydia" } -compareMembers(perosn) +compareMembers(person) ``` - A: `Not the same!` From 39a288149efd6e7dca8607772f0952469de220b1 Mon Sep 17 00:00:00 2001 From: Alexander Ivanov Date: Mon, 30 Sep 2019 11:49:20 +0300 Subject: [PATCH 337/915] Russian. Updates 2019-09/1 --- ru-RU/README.md | 235 +++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 234 insertions(+), 1 deletion(-) diff --git a/ru-RU/README.md b/ru-RU/README.md index 829db745..1c8c4440 100644 --- a/ru-RU/README.md +++ b/ru-RU/README.md @@ -2985,7 +2985,7 @@ getItems(["banana", "apple"], "pear", "orange") --- -###### 95. Какой будет вывод? +###### 95. Какой будет вывод? ```javascript function nums(a, b) { @@ -3116,6 +3116,7 @@ console.log(getUser(user))

#### Ответ: A + Функция `getList` получает массив в качестве аргумента. Между скобками функции `getList` мы сразу же деструктурируем этот массив. Вы можете увидеть это как: `[x, ...y] = [1, 2, 3, 4]` @@ -3221,3 +3222,235 @@ console.log(one, two, three)

+ +--- + +###### 102. Какое значение будет на выходе? + +```javascript +const myPromise = () => Promise.resolve('I have resolved!') + +function firstFunction() { + myPromise().then(res => console.log(res)) + console.log('second') +} + +function secondFunction() { + console.log(await myPromise()) + console.log('second') +} +``` + +- 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 + +С обещанием мы в основном говорим: "Я хочу выполнить эту функцию и откладываю ее, пока она выполняется, поскольку это может занять некоторое время". Только когда определенное значение разрешено (или отклонено), и когда стек вызовов пуст, я хочу использовать это значение. + +Мы можем получить это значение с помощью ключевого слова `.then` и `await` в функции `async`. Хотя мы можем получить значение обещания с помощью `.then` и `await`, они работают немного по-разному. + +В `firstFunction` мы (вроде) отложили функцию `myPromise` во время ее работы, но продолжили выполнение другого кода, в данном случае `console.log ('second')`. Затем функция разрешается строкой `I have resolved`, которая затем логируется после того, как она увидела, что стек вызовов пуст. + +Используя ключевое слово `await` в `secondFunction`, мы буквально приостанавливаем выполнение асинхронной функции до тех пор, пока значение не будет разрешено до перехода на следующую строку. + +Это означает, что мы ожидали разрешения `myPromise` со значением `I have resolved`, и только когда это произошло, мы перешли к следующей строке: `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]"`. `"[Object object]"`, объединенный с `"2"`, становится `"[Object object]2"`. + +

+
+ +--- + +###### 104. Чему равно значение? + +```javascript +Promise.resolve(5) +``` + +- A: `5` +- B: `Promise {: 5}` +- C: `Promise {: 5}` +- D: `Error` + +
Ответ +

+ +#### Ответ: C + +Мы можем передать любой тип значения, которое мы хотим, в `Promise.resolve`, либо обещание, либо не обещание. Сам метод возвращает обещание с разрешенным значением. Если вы передадите обычную функцию, это будет разрешенное обещание с обычным значением. Если вы передадите обещание, это будет разрешенное обещание с разрешенным значением этого пройденного обещания. + +В этом случае мы просто передали числовое значение `5`. Возвращается разрешенное обещание со значением `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!`. + +

+
+ +--- + +###### 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 пытается найти свойство с именем `colors` в объекте `colorConfig`. Не существует свойства с именем `colorConfig`, поэтому возвращается `undefined`. Затем мы пытаемся получить доступ к значению первого элемента, используя `[1]`. Мы не можем сделать это для значения, которое `undefined`, поэтому оно выдает `TypeError`: `Cannot read свойство '1' of undefined`. + +JavaScript интерпретирует (или распаковывает) операторы. Когда мы используем скобочные обозначения, он видит первую открывающую скобку `[` и продолжает работать, пока не найдет закрывающую скобку `]`. Только тогда он оценит утверждение. Если бы мы использовали `colorConfig[colors [1]]`, он бы возвратил значение свойства `red` объекта `colorConfig`. + +

+
+ +--- + +###### 107. Чему равно значение? + +```javascript +console.log('❤️' === '❤️') +``` + +- A: `true` +- B: `false` + +
Ответ +

+ +#### Ответ: A + +Под капотом смайлики - это юникоды. Юникод для сердца смайликов `"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`, мы модифицируем исходный массив, удаляя, заменяя или добавляя элементы. В этом случае мы удалили 2 элемента из индекса 1 (мы удалили `'🥑'` и `'😍'`) и добавили `✨` emoji. + +`map`, `filter` и `slice` возвращают новый массив, `find` возвращает элемент, а `reduce` возвращает аккумулированное значение. + +

+
From eab13eeaca31ae9564ab89761a26488ef39d71f4 Mon Sep 17 00:00:00 2001 From: Jacob Herper Date: Mon, 30 Sep 2019 13:53:06 +0100 Subject: [PATCH 338/915] Errors fixed --- de-DE/README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/de-DE/README.md b/de-DE/README.md index f76b7374..526d58cd 100644 --- a/de-DE/README.md +++ b/de-DE/README.md @@ -3238,7 +3238,7 @@ function firstFunction() { console.log('second') } -function secondFunction() { +async function secondFunction() { console.log(await myPromise()) console.log('second') } @@ -3345,7 +3345,7 @@ function compareMembers(person1, person2 = person) { const person = { name: "Lydia" } -compareMembers(perosn) +compareMembers(person) ``` - A: `Not the same!` From 9d100ff25d0cffe7d3f0116c1081582720405c62 Mon Sep 17 00:00:00 2001 From: sweetmilkys Date: Thu, 3 Oct 2019 16:11:25 +0900 Subject: [PATCH 339/915] Fix typos --- README.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index f4ca1f0b..606f5960 100644 --- a/README.md +++ b/README.md @@ -3293,11 +3293,11 @@ for (let item of set) { #### Answer: 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 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, 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"` 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"`. @@ -3398,7 +3398,7 @@ console.log(colorConfig.colors[1]) 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`. +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 `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. From 06f669a0dc195c1a5aeb0fd2edae12bc9f395538 Mon Sep 17 00:00:00 2001 From: sweetmilkys Date: Thu, 3 Oct 2019 16:12:10 +0900 Subject: [PATCH 340/915] Add translate the questions 102-108 to Korean. --- ko-KR/README-ko_KR.md | 239 +++++++++++++++++++++++++++++++++++++++++- 1 file changed, 237 insertions(+), 2 deletions(-) diff --git a/ko-KR/README-ko_KR.md b/ko-KR/README-ko_KR.md index 4ef08020..aa284ca2 100644 --- a/ko-KR/README-ko_KR.md +++ b/ko-KR/README-ko_KR.md @@ -2,9 +2,9 @@ JavaScript 에 관한 객관식 문제를 [Instagram](https://www.instagram.com/theavocoder)에 매일 게시하고 있어요, 물론 여기에도 게시할 거예요! -초급부터 고급까지: JavaScript를 얼마나 잘 알고 있는지 테스트하거나, 지식을 조금 더 새롭게 하거나, 코딩 면접을 준비하세요! :muscle: :rocket: 이 기록을 매주 새로운 질문으로 업데이트해요. 마지막 업데이트: 8월 17일 +초급부터 고급까지: JavaScript를 얼마나 잘 알고 있는지 테스트하거나, 지식을 조금 더 새롭게 하거나, 코딩 면접을 준비하세요! :muscle: :rocket: 이 기록을 매주 새로운 질문으로 업데이트해요. 마지막 업데이트: 9월 27일 -정답은 질문 아래 접힌 부분에 있어요, 그냥 클릭하면 펼칠 수 있어요. 행운을 빌어요 :heart: +정답은 질문 아래 접힌 부분에 있고, 간단히 클릭하면 펼칠 수 있어요. 행운을 빌어요 :heart: 질문이 더 추가될 때마다 이메일을 받고 싶나요?
✨✉이메일 업데이트 구독 ✉✨ @@ -3224,3 +3224,238 @@ console.log(one, two, 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` 그리고 `I have resolved!`, `second` +- B: `second`, `I have resolved!` 그리고 `second`, `I have resolved!` +- C: `I have resolved!`, `second` 그리고 `second`, `I have resolved!` +- D: `second`, `I have resolved!` 그리고 `I have resolved!`, `second` + +
정답 +

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

+
+ +--- + +###### 104. 값은 무엇일까요? + +```javascript +Promise.resolve(5) +``` + +- A: `5` +- B: `Promise {: 5}` +- C: `Promise {: 5}` +- D: `Error` + +
정답 +

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

+
+ +--- + +###### 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!`을 출력해요. + +

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

+
+ +--- + +###### 107. 값은 무엇일까요? + +```javascript +console.log('❤️' === '❤️') +``` + +- A: `true` +- B: `false` + +
정답 +

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

+
+ +--- + +###### 108. 다음 중 원본 배열을 수정하는 method는 무엇일까요? + +```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` method를 사용하면, 요소를 삭제, 대체하거나 추가함으로써 원본 배열을 수정해요. 이 경우에서, 인덱스 1에서 부터 2개의 아이템을 제거했어요. (`'🥑'` 와 `'😍'`를 삭제했어요) 그리고 ✨ 이모티콘을 대신 추가했죠. + +`map`, `filter` 그리고 `slice` 는 새로운 배열을 리턴해하고, `find` 요소를 리턴하며, `reduce` 감소된 값을 리턴해요. + +

+
From 3491442f7c1f75c4dba834fc29a5e52b36a0fa59 Mon Sep 17 00:00:00 2001 From: Mo Sureerat Date: Fri, 4 Oct 2019 22:55:27 +0700 Subject: [PATCH 341/915] Add translation to Thai --- README.md | 1 + th-TH/README.md | 3460 +++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 3461 insertions(+) create mode 100644 th-TH/README.md diff --git a/README.md b/README.md index f4ca1f0b..06e000f9 100644 --- a/README.md +++ b/README.md @@ -26,6 +26,7 @@ List of available languages: * [Tiếng Việt](./vi-VI/README-vi.md) * [中文版本](./zh-CN/README-zh_CN.md) * [Türkçe](./tr-TR/README-tr_TR.md) +* [ไทย](./th-TH/README-th_TH.md) --- diff --git a/th-TH/README.md b/th-TH/README.md new file mode 100644 index 00000000..9b518bcc --- /dev/null +++ b/th-TH/README.md @@ -0,0 +1,3460 @@ +# รายการคำถามเกี่ยวกับ JavaScript (ขั้นสูง) + +ผมโพสต์โจทย์ JavaScript แบบตัวเลือกทุกวันบน [Instagram](https://www.instagram.com/theavocoder) ของผม ซึ่งผมก็ได้นำมาโพสต์ไว้ที่นี่ด้วย + +จากขั้นพื้นฐานสู่ขั้นสูง มาทดสอบกันว่าคุณมีความรู้เรื่อง JavaScript ดีขนาดไหน มาทบทวนความรู้ของคุณกันหน่อย หรือเตรียมตัวสำหรับการสัมภาษณ์เกี่ยวกับการเขียนโปรแกรม :muscle: :rocket: ผมอัพเดทคำถามใหม่ๆ ใน repo นี้ทุกๆ สัปดาห์ อัพเดทล่าสุดวันที่ September 27th + +คำตอบจะอยู่ในหมวดที่ซ่อนไว้ใต้คำถาม เพียงแค่คลิก คำตอบก็จะแสดงขึ้นมา ขอให้โชคดีครับ :heart: + +หากต้องการได้รับอีเมลล์แจ้งหากผมมีการเพิ่มโจทย์ใหม่ๆ
+✨✉กรุณาลงทะเบียนรับอีเมลล์อัพเดท✉✨ + + +ลิสต์ภาษาอื่นๆ: +* [English](./en-EN/README.md) +* [العربية](./ar-AR/README_AR.md) +* [اللغة العامية - Egyptian Arabic](./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) +* [日本語](./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) +* [Українська мова](./ua-UA/README-ua_UA.md) +* [Tiếng Việt](./vi-VI/README-vi.md) +* [中文版本](./zh-CN/README-zh_CN.md) +* [Türkçe](./tr-TR/README-tr_TR.md) +* [ไทย](./th-TH/README-th_TH.md) + + +--- + +###### 1. ผลลัพธ์ที่ได้คืออะไร? + +```javascript +function sayHi() { + console.log(name); + console.log(age); + var name = "Lydia"; + let age = 21; +} + +sayHi(); +``` + +- A: `Lydia` และ `undefined` +- B: `Lydia` และ `ReferenceError` +- C: `ReferenceError` และ `21` +- D: `undefined` และ `ReferenceError` + +
คำตอบ +

+ +#### คำตอบ: D + +Within the function, we first declare the `name` variable with the `var` keyword. This means that the variable gets hoisted (memory space is set up during the creation phase) with the default value of `undefined`, until we actually get to the line where we define the variable. We haven't defined the variable yet on the line where we try to log the `name` variable, so it still holds the value of `undefined`. + +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`. + +

+
+ +--- + +###### 2. ผลลัพธ์ที่ได้คืออะไร? + +```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` และ `0 1 2` +- B: `0 1 2` และ `3 3 3` +- C: `3 3 3` และ `0 1 2` + +
คำตอบ +

+ +#### คำตอบ: C + +Because of the event queue in JavaScript, the `setTimeout` callback function is called _after_ the loop has been executed. Since the variable `i` in the first loop was declared using the `var` keyword, this value was global. During the loop, we incremented the value of `i` by `1` each time, using the unary operator `++`. By the time the `setTimeout` callback function was invoked, `i` was equal to `3` in the first example. + +In the second loop, the variable `i` was declared using the `let` keyword: variables declared with the `let` (and `const`) keyword are block-scoped (a block is anything between `{ }`). During each iteration, `i` will have a new value, and each value is scoped inside the loop. + +

+
+ +--- + +###### 3. ผลลัพธ์ที่ได้คืออะไร? + +```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` และ `62.83185307179586` +- B: `20` และ `NaN` +- C: `20` และ `63` +- D: `NaN` และ `63` + +
คำตอบ +

+ +#### คำตอบ: B + +Note that the value of `diameter` is a regular function, whereas the value of `perimeter` is an arrow function. + +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 `undefined`. + +

+
+ +--- + +###### 4. ผลลัพธ์ที่ได้คืออะไร? + +```javascript ++true; +!"Lydia"; +``` + +- A: `1` และ `false` +- B: `false` และ `NaN` +- C: `false` และ `false` + +
คำตอบ +

+ +#### คำตอบ: A + +The unary plus tries to convert an operand to a number. `true` is `1`, และ `false` is `0`. + +The string `'Lydia'` is a truthy value. What we're actually asking, is "is this truthy value falsy?". This returns `false`. + +

+
+ +--- + +###### 5. ข้อใดถูกต้อง? + +```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 + +
คำตอบ +

+ +#### คำตอบ: A + +In JavaScript, all object keys are strings (unless it's a Symbol). Even though we might not _type_ them as strings, they are always converted into strings under the hood. + +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. + +`mouse[bird.size]`: First it evaluates `bird.size`, which is `"small"`. `mouse["small"]` returns `true` + +However, with dot notation, this doesn't happen. `mouse` does not have a key called `bird`, which means that `mouse.bird` is `undefined`. Then, we ask for the `size` using dot notation: `mouse.bird.size`. Since `mouse.bird` is `undefined`, we're actually asking `undefined.size`. This isn't valid, and will throw an error similar to `Cannot read property "size" of undefined`. + +

+
+ +--- + + +###### 6. ผลลัพธ์ที่ได้คืออะไร? + +```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` + +
คำตอบ +

+ +#### คำตอบ: A + +In JavaScript, all objects interact by _reference_ when setting them equal to each other. + +First, variable `c` holds a value to an object. Later, we assign `d` with the same reference that `c` has to the object. + + + +When you change one object, you change all of them. + +

+
+ +--- + +###### 7. ผลลัพธ์ที่ได้คืออะไร? + +```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` + +
คำตอบ +

+ +#### คำตอบ: 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`. + +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.` + +

+
+ +--- + +###### 8. ผลลัพธ์ที่ได้คืออะไร? + +```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` + +
คำตอบ +

+ +#### คำตอบ: 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. + +

+
+ +--- + +###### 9. ผลลัพธ์ที่ได้คืออะไร? + +```javascript +let greeting; +greetign = {}; // Typo! +console.log(greetign); +``` + +- A: `{}` +- B: `ReferenceError: greetign is not defined` +- C: `undefined` + +
คำตอบ +

+ +#### คำตอบ: 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). + +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. + +

+
+ +--- + +###### 10. จะเกิดอะไรขึ้นหากเราทำเช่นนี้? + +```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` + +
คำตอบ +

+ +#### คำตอบ: A + +This is possible in JavaScript, because functions are objects! (Everything besides primitive types are objects) + +A function is a special type of object. The code you write yourself isn't the actual function. The function is an object with properties. This property is invocable. + +

+
+ +--- + +###### 11. ผลลัพธ์ที่ได้คืออะไร? + +```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` + +
คำตอบ +

+ +#### คำตอบ: A + +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() { + return `${this.firstName} ${this.lastName}`; +}; +``` + +would have made `member.getFullName()` work. Why is this beneficial? Say that we added this method to the constructor itself. Maybe not every `Person` instance needed this method. This would waste a lot of memory space, since they would still have that property, which takes of memory space for each instance. Instead, if we only add it to the prototype, we just have it at one spot in memory, yet they all have access to it! + +

+
+ +--- + +###### 12. ผลลัพธ์ที่ได้คืออะไร? + +```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"}` และ `undefined` +- B: `Person {firstName: "Lydia", lastName: "Hallie"}` และ `Person {firstName: "Sarah", lastName: "Smith"}` +- C: `Person {firstName: "Lydia", lastName: "Hallie"}` และ `{}` +- D:`Person {firstName: "Lydia", lastName: "Hallie"}` และ `ReferenceError` + +
คำตอบ +

+ +#### คำตอบ: A + +For `sarah`, we didn't use the `new` keyword. When using `new`, it refers to the new empty object we create. However, if you don't add `new` it refers to the **global object**! + +We said that `this.firstName` equals `"Sarah"` และ `this.lastName` equals `"Smith"`. What we actually did, is defining `global.firstName = 'Sarah'` และ `global.lastName = 'Smith'`. `sarah` itself is left `undefined`, since we don't return a value from the `Person` function. + +

+
+ +--- + +###### 13. อะไรคือ three phases ของ event propagation? + +- A: Target > Capturing > Bubbling +- B: Bubbling > Target > Capturing +- C: Target > Bubbling > Capturing +- D: Capturing > Target > Bubbling + +
คำตอบ +

+ +#### คำตอบ: 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. ทุกๆ object มี prototypes. + +- A: true +- B: false + +
คำตอบ +

+ +#### คำตอบ: 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. ผลลัพธ์ที่ได้คืออะไร? + +```javascript +function sum(a, b) { + return a + b; +} + +sum(1, "2"); +``` + +- A: `NaN` +- B: `TypeError` +- C: `"12"` +- D: `3` + +
คำตอบ +

+ +#### คำตอบ: 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. ผลลัพธ์ที่ได้คืออะไร? + +```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` + +
คำตอบ +

+ +#### คำตอบ: 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. ผลลัพธ์ที่ได้คืออะไร? + +```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` + +
คำตอบ +

+ +#### คำตอบ: 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. ผลลัพธ์ที่ได้คืออะไร? + +```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` + +
คำตอบ +

+ +#### คำตอบ: 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 }` และ `{ age: 18 } == { age: 18 }` return `false`. + +

+
+ +--- + +###### 19. ผลลัพธ์ที่ได้คืออะไร? + +```javascript +function getAge(...args) { + console.log(typeof args); +} + +getAge(21); +``` + +- A: `"number"` +- B: `"array"` +- C: `"object"` +- D: `"NaN"` + +
คำตอบ +

+ +#### คำตอบ: 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. ผลลัพธ์ที่ได้คืออะไร? + +```javascript +function getAge() { + "use strict"; + age = 21; + console.log(age); +} + +getAge(); +``` + +- A: `21` +- B: `undefined` +- C: `ReferenceError` +- D: `TypeError` + +
คำตอบ +

+ +#### คำตอบ: 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. จากโจทย์ `sum` มีค่าเท่ากับเท่าไหร่? + +```javascript +const sum = eval("10*10+5"); +``` + +- A: `105` +- B: `"105"` +- C: `TypeError` +- D: `"10*10+5"` + +
คำตอบ +

+ +#### คำตอบ: 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. 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. + +
คำตอบ +

+ +#### คำตอบ: 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. ผลลัพธ์ที่ได้คืออะไร? + +```javascript +var num = 8; +var num = 10; + +console.log(num); +``` + +- A: `8` +- B: `10` +- C: `SyntaxError` +- D: `ReferenceError` + +
คำตอบ +

+ +#### คำตอบ: 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. ผลลัพธ์ที่ได้คืออะไร? + +```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` + +
คำตอบ +

+ +#### คำตอบ: 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. ผลลัพธ์ที่ได้คืออะไร? + +```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` + +
คำตอบ +

+ +#### คำตอบ: 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. Global execution context ใน JavaScript สร้าง 2 สิ่งคือ: global object และคีย์เวิร์ด "this" + +- A: true +- B: false +- C: it depends + +
คำตอบ +

+ +#### คำตอบ: A + +The base execution context is the global execution context: it's what's accessible everywhere in your code. + +

+
+ +--- + +###### 27. ผลลัพธ์ที่ได้คืออะไร? + +```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` + +
คำตอบ +

+ +#### คำตอบ: C + +The `continue` statement skips an iteration if a certain condition returns `true`. + +

+
+ +--- + +###### 28. ผลลัพธ์ที่ได้คืออะไร? + +```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` + +
คำตอบ +

+ +#### คำตอบ: 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. ผลลัพธ์ที่ได้คืออะไร? + +```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` + +
คำตอบ +

+ +#### คำตอบ: 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. ผลลัพธ์ที่ได้คืออะไร? + +```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` + +
คำตอบ +

+ +#### คำตอบ: 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. event.target คืออะไรเมื่อคลิก button? + +```html +
+
+ +
+
+``` + +- A: Outer `div` +- B: Inner `div` +- C: `button` +- D: An array of all nested elements. + +
คำตอบ +

+ +#### คำตอบ: C + +The deepest nested element that caused the event is the target of the event. You can stop bubbling by `event.stopPropagation` + +

+
+ +--- + +###### 32. เมื่อคุณคลิกที่ paragraph, ผลลัพธ์ที่ได้ใน console log คืออะไร? + +```html +
+

+ Click here! +

+
+``` + +- A: `p` `div` +- B: `div` `p` +- C: `p` +- D: `div` + +
คำตอบ +

+ +#### คำตอบ: A + +If we click `p`, we see two logs: `p` และ `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. ผลลัพธ์ที่ได้คืออะไร? + +```javascript +const person = { name: "Lydia" }; + +function sayHi(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` + +
คำตอบ +

+ +#### คำตอบ: 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. ผลลัพธ์ที่ได้คืออะไร? + +```javascript +function sayHi() { + return (() => 0)(); +} + +console.log(typeof sayHi()); +``` + +- A: `"object"` +- B: `"number"` +- C: `"function"` +- D: `"undefined"` + +
คำตอบ +

+ +#### คำตอบ: B + +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`. `"function"` is not a type, since functions are objects, it's of type `"object"`. +

+
+ +--- + +###### 35. ค่าใดต่อไปนี้ที่เป็น 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: All of them are falsy + +
คำตอบ +

+ +#### คำตอบ: A + +There are only six falsy values: + +- `undefined` +- `null` +- `NaN` +- `0` +- `''` (empty string) +- `false` + +Function constructors, like `new Number` และ `new Boolean` are truthy. + +

+
+ +--- + +###### 36. ผลลัพธ์ที่ได้คืออะไร? + +```javascript +console.log(typeof typeof 1); +``` + +- A: `"number"` +- B: `"string"` +- C: `"object"` +- D: `"undefined"` + +
คำตอบ +

+ +#### คำตอบ: B + +`typeof 1` returns `"number"`. +`typeof "number"` returns `"string"` + +

+
+ +--- + +###### 37. ผลลัพธ์ที่ได้คืออะไร? + +```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` + +
คำตอบ +

+ +#### คำตอบ: 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, 7 x empty, 11]` + +depending on where you run it (it's different for every browser, node, etc.) + +

+
+ +--- + +###### 38. ผลลัพธ์ที่ได้คืออะไร? + +```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` + +
คำตอบ +

+ +#### คำตอบ: 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`, และ `y` is `2`. When we want to `console.log(x)` outside of the `catch` block, it returns `undefined`, และ `y` returns `2`. + +

+
+ +--- + +###### 39. ข้อใดคือ JavaScript + +- A: primitive or object +- B: function or object +- C: trick question! only objects +- D: number or object + +
คำตอบ +

+ +#### คำตอบ: A + +JavaScript only has primitive types and objects. + +Primitive types are `boolean`, `null`, `undefined`, `bigint`, `number`, `string`, และ `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 object using one of the wrapper classes, i.e. `String`, and then immediately discard the wrapper after the expression evaluates. All primitives except for `null`และd `undefined` exhibit this behaviour. + +

+
+ +--- + +###### 40. ผลลัพธ์ที่ได้คืออะไร? + +```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]` + +
คำตอบ +

+ +#### คำตอบ: 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]`, และ `cur` is `[0, 1]`. We concatenate them, which results in `[1, 2, 0, 1]`. + +Then, `[1, 2, 0, 1]` is `acc` และ `[2, 3]` is `cur`. We concatenate them, and get `[1, 2, 0, 1, 2, 3]` + +

+
+ +--- + +###### 41. ผลลัพธ์ที่ได้คืออะไร? + +```javascript +!!null; +!!""; +!!1; +``` + +- A: `false` `true` `false` +- B: `false` `false` `true` +- C: `false` `true` `true` +- D: `true` `true` `false` + +
คำตอบ +

+ +#### คำตอบ: 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. `setInterval` method ส่งค่าอะไรให้เบราว์เซอร์? + +```javascript +setInterval(() => console.log("Hi"), 1000); +``` + +- A: a unique id +- B: the amount of milliseconds specified +- C: the passed function +- D: `undefined` + +
คำตอบ +

+ +#### คำตอบ: A + +It returns a unique id. This id can be used to clear that interval with the `clearInterval()` function. + +

+
+ +--- + +###### 43. ผลลัพธ์ทีได้คืออะไร? + +```javascript +[..."Lydia"]; +``` + +- A: `["L", "y", "d", "i", "a"]` +- B: `["Lydia"]` +- C: `[[], "Lydia"]` +- D: `[["L", "y", "d", "i", "a"]]` + +
คำตอบ +

+ +#### คำตอบ: A + +A string is an iterable. The spread operator maps every character of an iterable to one element. + +

+
+ +--- + +###### 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` + +
คำตอบ +

+ +#### คำตอบ: 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. ผลลัพธ์ทีได้คืออะไร? + +```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"` + +
คำตอบ +

+ +#### คำตอบ: 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. ผลลัพธ์ที่ได้คืออะไร? + +```javascript +let person = { name: "Lydia" }; +const members = [person]; +person = null; + +console.log(members); +``` + +- A: `null` +- B: `[null]` +- C: `[{}]` +- D: `[{ name: "Lydia" }]` + +
คำตอบ +

+ +#### คำตอบ: 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. ผลลัพธ์ที่ได้คืออะไร? + +```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]` + +
คำตอบ +

+ +#### คำตอบ: B + +With a `for-in` loop, we can iterate through object keys, in this case `name` และ `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. ผลลัพธ์ที่ได้คืออะไร? + +```javascript +console.log(3 + 4 + "5"); +``` + +- A: `"345"` +- B: `"75"` +- C: `12` +- D: `"12"` + +
คำตอบ +

+ +#### คำตอบ: 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. `num` เท่ากับเท่าไหร่? + +```javascript +const num = parseInt("7*6", 10); +``` + +- A: `42` +- B: `"42"` +- C: `7` +- D: `NaN` + +
คำตอบ +

+ +#### คำตอบ: 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. ผลลัพธ์ที่ได้คืออะไร? + +```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 ]` + +
คำตอบ +

+ +#### คำตอบ: 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. ผลลัพธ์ที่ได้คืออะไร? + +```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"` + +
คำตอบ +

+ +#### คำตอบ: 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. ผลลัพธ์ที่ได้คืออะไร? + +```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!` + +
คำตอบ +

+ +#### คำตอบ: 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. ผลลัพธ์ที่ได้คืออะไร? + +```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` + +
คำตอบ +

+ +#### คำตอบ: 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. ผลลัพธ์ที่ได้คืออะไร? + +```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"` + +
คำตอบ +

+ +#### คำตอบ: 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 (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. ผลลัพธ์ที่ได้คืออะไร? + +```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` + +
คำตอบ +

+ +#### คำตอบ: 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. ผลลัพธ์ที่ได้คืออะไร? + +```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}` + +
คำตอบ +

+ +#### คำตอบ: 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. ผลลัพธ์ที่ได้คืออะไร? + +```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` + +
คำตอบ +

+ +#### คำตอบ: 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. ผลลัพธ์ที่ได้คืออะไร? + +```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` + +
คำตอบ +

+ +#### คำตอบ: 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. ผลลัพธ์ที่ได้คืออะไร? + +```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]` + +
คำตอบ +

+ +#### คำตอบ: 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. ผลลัพธ์ที่ได้คืออะไร? + +```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 }` + +
คำตอบ +

+ +#### คำตอบ: 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. ผลลัพธ์ที่ได้คืออะไร? + +```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"]` + +
คำตอบ +

+ +#### คำตอบ: 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` และ `enumerable` properties. This way, the `defineProperty` method gives you a lot more control over the properties you're adding to an object. + +

+
+ +--- + +###### 62. ผลลัพธ์ที่ได้คืออะไร? + +```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}"` + +
คำตอบ +

+ +#### คำตอบ: 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"`และd `"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. ผลลัพธ์ที่ได้คืออะไร? + +```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` + +
คำตอบ +

+ +#### คำตอบ: 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. ผลลัพธ์ที่ได้คืออะไร? + +```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` + +
คำตอบ +

+ +#### คำตอบ: 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. ผลลัพธ์ที่ได้คืออะไร? + +```javascript +[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` +- D: `1` `2` และ `undefined` `3` และ `undefined` `4` + +
คำตอบ +

+ +#### คำตอบ: 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` และ `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. + +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. +

+
+ +--- + +###### 66. constructor ไหนที่เราสามารถใช้ extend ให้กับ `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 + +
คำตอบ +

+ +#### คำตอบ: 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`, และ `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. ผลลัพธ์ที่ได้คืออะไร? + +```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 + +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. ผลลัพธ์ที่ได้คืออะไร? + +```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 + +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. ผลลัพธ์ที่ได้คืออะไร? + +```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 + +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. ผลลัพธ์ที่ได้คืออะไร? + +```javascript +console.log("🥑" + "💻"); +``` + +- A: `"🥑💻"` +- B: `257548` +- C: A string containing their code points +- D: Error + +
คำตอบ +

+ +#### คำตอบ: A + +With the `+` operator, you can concatenate strings. In this case, we are concatenating the string `"🥑"` with the string `"💻"`, resulting in `"🥑💻"`. + +

+
+ +--- + +###### 71. ค่าที่แสดงใน log หลังจากที่เรา commented out ใน 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` และ `game.next().value` +- B: `game.next.value("Yes")` และ `game.next.value()` +- C: `game.next().value` และ `game.next("Yes").value` +- D: `game.next.value()` และ `game.next.value("Yes")` + +
คำตอบ +

+ +#### คำตอบ: 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`, และ `JavaScript loves you back ❤️` gets logged. + +

+
+ +--- + +###### 72. ผลลัพธ์ที่ได้คืออะไร? + +```javascript +console.log(String.raw`Hello\nworld`); +``` + +- A: `Hello world!` +- B: `Hello`
     `world` +- C: `Hello\nworld` +- D: `Hello\n`
     `world` + +
คำตอบ +

+ +#### คำตอบ: 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. ผลลัพธ์ที่ได้คืออะไร? + +```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 + +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. ผลลัพธ์ที่ได้คืออะไร? + +```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 + +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. ผลลัพธ์ที่ได้คืออะไร? + +```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` 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. + +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`, และ `{ x: 10, y: 20 }` gets logged. + +

+
+ +--- + +###### 76. ผลลัพธ์ที่ได้คืออะไร? + +```javascript +const { name: myName } = { name: "Lydia" }; + +console.log(name); +``` + +- A: `"Lydia"` +- B: `"myName"` +- C: `undefined` +- D: `ReferenceError` + +
คำตอบ +

+ +#### คำตอบ: 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, a ReferenceError gets thrown. + +

+
+ +--- + +###### 77. นี่เป็น pure function หรือไม่? + +```javascript +function sum(a, b) { + return a + b; +} +``` + +- A: Yes +- B: No + +
คำตอบ +

+ +#### คำตอบ: 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` และ `2`, it will _always_ return `3` without side effects. If we pass `5` และ `10`, it will _always_ return `15`, and so on. This is the definition of a pure function. + +

+
+ +--- + +###### 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 + +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`, และ `'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`, และ `'From cache! 20'` gets logged. + +

+
+ +--- + +###### 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` และ `"☕"` ` "💻"` `"🍷"` `"🍫"` +- B: `"☕"` ` "💻"` `"🍷"` `"🍫"` และ `"☕"` ` "💻"` `"🍷"` `"🍫"` +- C: `"☕"` ` "💻"` `"🍷"` `"🍫"` และ `0` `1` `2` `3` +- D: `0` `1` `2` `3` และ `{0: "☕", 1: "💻", 2: "🍷", 3: "🍫"}` + +
คำตอบ +

+ +#### คำตอบ: 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. ผลลัพธ์ที่ได้คืออะไร? + +```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 + +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`. + +

+
+ +--- + +###### 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 + +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. ผลลัพธ์ที่ได้คืออะไร? + +```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: `"🥑"` และ `"😍"` +- B: `"🥑"` และ `"😎"` +- C: `"😍"` และ `"😎"` +- D: `"😎"` และ `"😎"` + +
คำตอบ +

+ +#### คำตอบ: 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. ผลลัพธ์ที่ได้คืออะไร? + +```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 + +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. ผลลัพธ์ที่ได้คืออะไร? + +```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 + +Variables with the `const` และ `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. ข้อมูลแบบไหนที่เราได้ใน log? + +```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. + +
คำตอบ +

+ +#### คำตอบ: 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. ข้อไหนคือวิธีที่เราสามารถเซ็ตให้ `hasName` มีค่าเป็น `true` กรณีที่คุณไม่สามารถส่งค่า `true` ใน argument ได้? + +```javascript +function getName(name) { + const hasName = // +} +``` + +- A: `!!name` +- B: `name` +- C: `new Boolean(name)` +- D: `name.length` + +
คำตอบ +

+ +#### คำตอบ: 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. ผลลัพธ์ที่ได้คืออะไร? + +```javascript +console.log("I want pizza"[0]) +``` + +- A: `"""` +- B: `"I"` +- C: `SyntaxError` +- D: `undefined` + +
คำตอบ +

+ +#### คำตอบ: 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. + +Note that this method is not supported in IE7 and below. In that case, use `.charAt()` + +

+
+ +--- + +###### 88. ผลลัพธ์ที่ได้คืออะไร? + +```javascript +function sum(num1, num2 = num1) { + console.log(num1 + num2) +} + +sum(10) +``` + +- A: `NaN` +- B: `20` +- C: `ReferenceError` +- D: `undefined` + +
คำตอบ +

+ +#### คำตอบ: 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. ผลลัพธ์ที่ได้คืออะไร? + +```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 + +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. ผลลัพธ์ที่ได้คืออะไร? + +```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 + +Classes are syntactical sugar for function constructors. The equivalent of the `Person` class as a function constructor would be: + +```javascript +function Person() { + 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. ผลลัพธ์ที่ได้คืออะไร? + +```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 + +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. ผลลัพธ์ที่ได้คืออะไร? + +```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 + +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. ผลลัพธ์ที่ได้คืออะไร? + +```javascript +const person = { + name: "Lydia", + age: 21 +} + +for (const [x, y] of Object.entries(person)) { + console.log(x, y) +} +``` + +- A: `name` `Lydia` และ `age` `21` +- B: `["name", "Lydia"]` และ `["age", 21]` +- C: `["name", "age"]` และ `undefined` +- D: `Error` + +
คำตอบ +

+ +#### คำตอบ: 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"`, และ `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. + +

+
+ +--- + +###### 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` 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. ผลลัพธ์ที่ได้คืออะไร? + +```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` และ `b is bigger`, `3` +- B: `a is bigger`, `undefined` และ `b is bigger`, `undefined` +- C: `undefined` และ `undefined` +- D: `SyntaxError` + +
คำตอบ +

+ +#### คำตอบ: 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. ผลลัพธ์ที่ได้คืออะไร? + +```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 + +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. ผลลัพธ์ที่ได้คืออะไร? + +```javascript +const info = { + [Symbol('a')]: 'b' +} + +console.log(info) +console.log(Object.keys(info)) +``` + +- A: `{Symbol('a'): 'b'}` และ `["{Symbol('a')"]` +- B: `{}` และ `[]` +- C: `{ a: "b" }` และ `["a"]` +- D: `{Symbol('a'): 'b'}` และ `[]` + +
คำตอบ +

+ +#### คำตอบ: 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. ผลลัพธ์ที่ได้คืออะไร? + +```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]]` และ `undefined` +- B: `[1, [2, 3, 4]]` และ `{ name: "Lydia", age: 21 }` +- C: `[1, 2, 3, 4]` และ `{ name: "Lydia", age: 21 }` +- D: `Error` และ `{ name: "Lydia", age: 21 }` + +
คำตอบ +

+ +#### คำตอบ: 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` และ `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: + +```const getUser = user => ({ name: user.name, age: user.age })``` + +Since no value gets returned in this case, the function returns `undefined`. + +

+
+ +--- + +###### 99. ผลลัพธ์ที่ได้คืออะไร? + +```javascript +const name = "Lydia" + +console.log(name()) +``` + +- A: `SyntaxError` +- B: `ReferenceError` +- C: `TypeError` +- D: `undefined` + +
คำตอบ +

+ +#### คำตอบ: 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. ผลลัพธ์ที่ได้คืออะไร? + +```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` + +
คำตอบ +

+ +#### คำตอบ: 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. ผลลัพธ์ที่ได้คืออะไร? + +```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 + +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 past 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. ผลลัพธ์ที่ได้คืออะไร? + +```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 have resolved!`, `second` +- B: `second`, `I have resolved!` และ `second`, `I have resolved!` +- C: `I have resolved!`, `second` และ `second`, `I have resolved!` +- D: `second`, `I have resolved!` และ `I have resolved!`, `second` + +
คำตอบ +

+ +#### คำตอบ: 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` และ `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 befoer 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. ผลลัพธ์ที่ได้คืออะไร? + +```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 + +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"`. + +`{ 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. ผลลัพธ์ที่ได้คืออะไร? + +```javascript +Promise.resolve(5) +``` + +- A: `5` +- B: `Promise {: 5}` +- C: `Promise {: 5}` +- D: `Error` + +
คำตอบ +

+ +#### คำตอบ: 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. ผลลัพธ์ที่ได้คืออะไร? + +```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 + +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. ผลลัพธ์ที่ได้คืออะไร? + +```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 + +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. + +

+
+ +--- + +###### 107. ผลลัพธ์ที่ได้คืออะไร? + +```javascript +console.log('❤️' === '❤️') +``` + +- A: `true` +- B: `false` + +
คำตอบ +

+ +#### คำตอบ: 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` + +
คำตอบ +

+ +#### คำตอบ: 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. + +`map`, `filter` และ `slice` return a new array, `find` returns an element, and `reduce` returns a reduced value. + +

+
From b8a5e3fa6c4c5ee56e19410bac5a2e97fec3f595 Mon Sep 17 00:00:00 2001 From: Alexander Ivanov Date: Sat, 5 Oct 2019 09:27:19 +0300 Subject: [PATCH 342/915] Sync w latest fixes Signed-off-by: Alexander Ivanov --- ru-RU/README.md | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/ru-RU/README.md b/ru-RU/README.md index 1c8c4440..f9d7aa1e 100644 --- a/ru-RU/README.md +++ b/ru-RU/README.md @@ -3235,10 +3235,13 @@ function firstFunction() { console.log('second') } -function secondFunction() { +async function secondFunction() { console.log(await myPromise()) console.log('second') } + +firstFunction() +secondFunction() ``` - A: `I have resolved!`, `second` and `I have resolved!`, `second` From ac3ac4b09de465a49d6f4b38a21755f69e734565 Mon Sep 17 00:00:00 2001 From: Mohamed ELBARCHANY Date: Mon, 7 Oct 2019 08:26:55 +0100 Subject: [PATCH 343/915] Update French questions --- fr-FR/README_fr-FR.md | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/fr-FR/README_fr-FR.md b/fr-FR/README_fr-FR.md index 36c5aa6f..41a67855 100644 --- a/fr-FR/README_fr-FR.md +++ b/fr-FR/README_fr-FR.md @@ -136,7 +136,7 @@ Il n'y a pas de valeur `radius` dans cet objet, on retournera `undefined`. L'opérateur arithmétique `+` essait de convertir un opérande en une valeur numérique. `true` devient `1`, et `false` devient `0`. -La chaine de caractère `'Lydia'` est une valeur considérée comme vraie _(truthy)_. Ce que nous sommes actuellement en train de demander, c'est "est-ce que cette valeur considérée comme vraie est fausse ?". Ce qui retournera `false`. +La chaîne de caractère `'Lydia'` est une valeur considérée comme vraie _(truthy)_. Ce que nous sommes actuellement en train de demander, c'est "est-ce que cette valeur considérée comme vraie est fausse ?". Ce qui retournera `false`.

@@ -166,7 +166,7 @@ const mouse = { #### Réponse : A -En JavaScript, toutes les clés d'objet sont des chaines de caractères (sauf si c'est un Symbol). Bien que nous ne puissions pas les _typer_ comme des chaines de caractères, elles sont converties en chaines de caractères sous le capot. +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. @@ -205,7 +205,7 @@ console.log(d.greeting); En JavaScript, tous les objets interagissent par _référence_ lorsqu'on les définit égaux les uns aux autres. -Premièrement, la variable `c` contaient une valeur d'objet. Plus tard, nous assignons `d` avec la même réference que `c` à l'objet. +Premièrement, la variable `c` contaient une valeur d'objet. Plus tard, nous assignons `d` avec la même référence que `c` à l'objet. @@ -474,7 +474,7 @@ sum(1, "2"); JavaScript est un **langage à types dynamiques** : nous n'avons pas besoin de spécifier le types des variables. Les valeurs peuvent être automatiquement converties vers les autres types sans que vous le sachiez, c'est ce que l'on appelle _la conversion de types implicites_ _(implicit type coercion)_. -Dans cette exemple, JavaScript convertit le nombre `1` en un chaine de caractère, afin que la fonction ait du sens et puisse renvoyer une valeur. Durant l'addition d'un type numérique (`1`) et d'un type chaine de caractère (`'2'`), le nombre est traité comme une chaine de caractère. Nous pouvons concaténer les chaines de caractères comme `"Hello" + "World"`, c'est donc ce qui arrive ici avec `"1" + "2"` qui retourne `"12"`. +Dans cette exemple, JavaScript convertit le nombre `1` en une chaîne de caractère, afin que la fonction ait du sens et puisse renvoyer une valeur. Durant l'addition d'un type numérique (`1`) et d'un type chaîne de caractère (`'2'`), le nombre est traité comme une chaîne de caractère. Nous pouvons concaténer les chaînes de caractères comme `"Hello" + "World"`, c'est donc ce qui arrive ici avec `"1" + "2"` qui retourne `"12"`.

@@ -541,7 +541,7 @@ getPersonInfo`${person} is ${age} years old`; #### Réponse : B -Si vous utilisez les littéraux de gabarits, la valeur du premier argument sera toujours un tableau de valeurs des chaines de caractère. Le reste des arguments seront les valeurs des expressions utilisées ! +Si vous utilisez les littéraux de gabarits, la valeur du premier argument sera toujours un tableau de valeurs des chaînes de caractère. Le reste des arguments seront les valeurs des expressions utilisées !

@@ -869,7 +869,7 @@ console.log(a[b]); Les clés d'objet sont automatiquement converties en chaînes de caractères. Nous essayons de définir un objet en tant que clé de l'objet `a`, avec la valeur `123`. -Cependant, lorsque nous transformons un objet en chaine de caractère, il devient `"[Objet objet]"`. Donc, ce que nous disons ici, c'est que un `a["Objet objet"] = 123`. Ensuite, nous pouvons essayer de refaire la même chose. `c` est un autre objet que nous sommes implicitement en train de transformer en chaine de carctère. Donc, `a["Objet objet"] = 456`. +Cependant, lorsque nous transformons un objet en chaîne de caractère, il devient `"[Objet objet]"`. Donc, ce que nous disons ici, c'est que un `a["Objet objet"] = 123`. Ensuite, nous pouvons essayer de refaire la même chose. `c` est un autre objet que nous sommes implicitement en train de transformer en chaîne de caractère. Donc, `a["Objet objet"] = 456`. Ensuite, nous affichons `a[b]`, qui est en fait `a["Objet objet"]`. Que nous venons de définir à `456`, nous renvoyons donc `456`. @@ -1075,7 +1075,7 @@ Il n'y a que six valeurs de fausses : - `null` - `NaN` - `0` -- `''` (chaine de caractère vide) +- `''` (chaîne de caractère vide) - `false` Les constructeurs de fonctions, comme `new Number` et `new Boolean` sont la vraies. @@ -1544,7 +1544,7 @@ console.log(person, birthYear); #### Réponse : A -Les arguments sont passés par _valeur_, à moins que leur valeur ne soit un objet, ils sont passés par _réfèrence_. `birthYear` est passée par valeur, car c'est une chaîne, pas un objet. Lorsque nous passons des arguments par valeur, une copie de cette valeur est créée (voir question 46). +Les arguments sont passés par _valeur_, à moins que leur valeur ne soit un objet, ils sont passés par _référence_. `birthYear` est passée par valeur, car c'est une chaîne, pas un objet. Lorsque nous passons des arguments par valeur, une copie de cette valeur est créée (voir question 46). La variable `birthYear` a une référence à la valeur `"1997"`. L'argument `year` fait également référence à la valeur `"1997"`, mais il ne s'agit pas de la même valeur que celle de `birthYear`. Lorsque nous mettons à jour la valeur de `year` en plaçant `year` égal à `"1998"`, nous ne mettons à jour que la valeur de `year`. `birthYear` est toujours égal à `"1997"`. @@ -1919,7 +1919,7 @@ Le second argument de `JSON.stringify` est le _replaçant_. Le remplaçant peut Si le remplaçant est un _tableau_, seules les propriétés dont les noms sont inclus dans le tableau seront ajoutées à la chaîne JSON. Dans ce cas, seules les propriétés avec les noms `"level"` et `"health"` sont incluses, `"username"` est exclu. `data` est maintenant égal à `"{"level":19, "health":90}"`. -Si le remplaceur est une _fonction_, cette fonction est appelée sur chaque propriété de l'objet que vous personnalisez. La valeur renvoyée par cette fonction sera la valeur de la propriété lorsqu'elle sera ajoutée à la chaîne JSON. Si la valeur est `undefined`, cette propriété est exclue de la chaîne JSON. +Si le remplaçant est une _fonction_, cette fonction est appelée sur chaque propriété de l'objet que vous personnalisez. La valeur renvoyée par cette fonction sera la valeur de la propriété lorsqu'elle sera ajoutée à la chaîne JSON. Si la valeur est `undefined`, cette propriété est exclue de la chaîne JSON.

From 11e1c01526f27a9c36ad4205f5dc610d6b93ea7e Mon Sep 17 00:00:00 2001 From: Lydia Hallie Date: Wed, 9 Oct 2019 18:52:17 -0700 Subject: [PATCH 344/915] Add questions 109-116 --- README.md | 299 ++++++++++++++++++++++++++++++++++++++++++++- en-EN/README.md | 313 ++++++++++++++++++++++++++++++++++++++++++++++-- 2 files changed, 599 insertions(+), 13 deletions(-) diff --git a/README.md b/README.md index f4ca1f0b..d7493d96 100644 --- a/README.md +++ b/README.md @@ -2,7 +2,7 @@ I post daily multiple choice JavaScript questions on my [Instagram](https://www.instagram.com/theavocoder), which I'll also post 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 weekly with new questions. Last update: September 27th +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 weekly with new questions. Last update: October 9th The answers are in the collapsed sections below the questions, simply click on them to expand it. Good luck :heart: @@ -2731,7 +2731,7 @@ By setting `hasName` equal to `name`, you set `hasName` equal to whatever value --- -###### 87. What's the output? +###### 87. What's the output? ```javascript console.log("I want pizza"[0]) @@ -3225,7 +3225,7 @@ With the `||` operator, we can return the first truthy operand. If all values ar --- -###### 102. What's the value of output? +###### 102. What's the value of output? ```javascript const myPromise = () => Promise.resolve('I have resolved!') @@ -3457,3 +3457,296 @@ With `splice` method, we modify the original array by deleting, replacing or add

+ +--- + +###### 109. What's the output? + +```javascript +const food = ['🍕', '🍫', '🥑', '🍔'] +const info = { favoriteFood: food[0] } + +info.favoriteFood = '🍝' + +console.log(food) +``` + +- A: `['🍕', '🍫', '🥑', '🍔']` +- B: `['🍝', '🍫', '🥑', '🍔']` +- C: `['🍝', '🍕', '🍫', '🥑', '🍔']` +- D: `ReferenceError` + +
Answer +

+ +#### Answer: 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 act 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 + +
Answer +

+ +#### Answer: 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. What's the output? + +```javascript +let name = 'Lydia' + +function getName() { + console.log(name) + let name = 'Sarah' +} + +getName() +``` + +- A: Lydia +- B: Sarah +- C: `undefined` +- D: `ReferenceError` + +
Answer +

+ +#### Answer: 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. What's the 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` and `a` +- B: `a` and `undefined` +- C: `['a', 'b', 'c']` and `a` +- D: `a` and `['a', 'b', 'c']` + +
Answer +

+ +#### Answer: 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. What's the 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` + +
Answer +

+ +#### Answer: 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` + +
Answer +

+ +#### 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). + +

+
+ +--- + +###### 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 + +
Answer +

+ +#### Answer: 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. What's the 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}` + +
Answer +

+ +#### Answer: 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 }`. + +

+
\ No newline at end of file diff --git a/en-EN/README.md b/en-EN/README.md index 371b3a67..a977544a 100644 --- a/en-EN/README.md +++ b/en-EN/README.md @@ -2,7 +2,7 @@ I post daily multiple choice JavaScript questions on my [Instagram](https://www.instagram.com/theavocoder), which I'll also post 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 weekly with new questions. Last update: August 17th +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 weekly with new questions. Last update: October 9th The answers are in the collapsed sections below the questions, simply click on them to expand it. Good luck :heart: @@ -15,7 +15,7 @@ List of available languages: * [العربية](../ar-AR/README_AR.md) * [اللغة العامية - Egyptian Arabic](../ar-EG/README_ar-EG.md) * [Bosanski](../bs-BS/README-bs_BS.md) -* [Deutsch](../de-DE/README-de_DE.md) +* [Deutsch](../de-DE/README.md) * [Español](../es-ES/README-ES.md) * [Français](../fr-FR/README_fr-FR.md) * [日本語](../ja-JA/README-ja_JA.md) @@ -131,8 +131,8 @@ There is no value `radius` on that object, which returns `undefined`. ###### 4. What's the output? ```javascript -console.log(+true); -console.log(!"Lydia"); ++true; +!"Lydia"; ``` - A: `1` and `false` @@ -2731,7 +2731,7 @@ By setting `hasName` equal to `name`, you set `hasName` equal to whatever value --- -###### 87. What's the output? +###### 87. What's the output? ```javascript console.log("I want pizza"[0]) @@ -2776,7 +2776,7 @@ sum(10) #### Answer: 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, amd 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. @@ -2985,7 +2985,7 @@ The above example works. This returns the array `[ 'banana', 'apple', 'orange', --- -###### 95. What's the output? +###### 95. What's the output? ```javascript function nums(a, b) { @@ -3260,7 +3260,7 @@ We can get this value with both `.then` and the `await` keyword in an `async` fu 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. +With the await keyword in `secondFunction`, we literally pause the execution of an async function until the value has been resolved befoer 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. @@ -3293,11 +3293,11 @@ for (let item of set) { #### Answer: 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 `+` 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"` and `"2"` get concatenated, which results 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"` and `"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"`. @@ -3457,3 +3457,296 @@ With `splice` method, we modify the original array by deleting, replacing or add

+ +--- + +###### 109. What's the output? + +```javascript +const food = ['🍕', '🍫', '🥑', '🍔'] +const info = { favoriteFood: food[0] } + +info.favoriteFood = '🍝' + +console.log(food) +``` + +- A: `['🍕', '🍫', '🥑', '🍔']` +- B: `['🍝', '🍫', '🥑', '🍔']` +- C: `['🍝', '🍕', '🍫', '🥑', '🍔']` +- D: `ReferenceError` + +
Answer +

+ +#### Answer: 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 act 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 + +
Answer +

+ +#### Answer: 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. What's the output? + +```javascript +let name = 'Lydia' + +function getName() { + console.log(name) + let name = 'Sarah' +} + +getName() +``` + +- A: Lydia +- B: Sarah +- C: `undefined` +- D: `ReferenceError` + +
Answer +

+ +#### Answer: 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. What's the 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` and `a` +- B: `a` and `undefined` +- C: `['a', 'b', 'c']` and `a` +- D: `a` and `['a', 'b', 'c']` + +
Answer +

+ +#### Answer: 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. What's the 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` + +
Answer +

+ +#### Answer: 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` + +
Answer +

+ +#### 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). + +

+
+ +--- + +###### 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 + +
Answer +

+ +#### Answer: 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. What's the 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}` + +
Answer +

+ +#### Answer: 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 }`. + +

+
\ No newline at end of file From 6698bde0653740a3831f984c927b6fd17084bcfd Mon Sep 17 00:00:00 2001 From: Alexander Ivanov Date: Thu, 10 Oct 2019 14:00:51 +0300 Subject: [PATCH 345/915] fix_typo Signed-off-by: Alexander Ivanov --- README.md | 2 +- en-EN/README.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index d7493d96..09b391ba 100644 --- a/README.md +++ b/README.md @@ -3652,7 +3652,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) } diff --git a/en-EN/README.md b/en-EN/README.md index a977544a..efd941f1 100644 --- a/en-EN/README.md +++ b/en-EN/README.md @@ -3652,7 +3652,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) } From 121b00858e860bcf8eb53476d1e6dd4f8ba1242d Mon Sep 17 00:00:00 2001 From: Alex Ivanov Date: Thu, 10 Oct 2019 14:43:08 +0300 Subject: [PATCH 346/915] typo Signed-off-by: Alex Ivanov --- README.md | 2 +- en-EN/README.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 00097661..d2491cc8 100644 --- a/README.md +++ b/README.md @@ -3689,7 +3689,7 @@ myMap.get('greeting') //2 myMap.get(myFunc) //3 -myMap.get(() => 'greeting')) +myMap.get(() => 'greeting') ``` - A: 1 diff --git a/en-EN/README.md b/en-EN/README.md index efd941f1..71d304e4 100644 --- a/en-EN/README.md +++ b/en-EN/README.md @@ -3689,7 +3689,7 @@ myMap.get('greeting') //2 myMap.get(myFunc) //3 -myMap.get(() => 'greeting')) +myMap.get(() => 'greeting') ``` - A: 1 From a1e956f1327165e055b07088ba2c20fbf5b2b9fa Mon Sep 17 00:00:00 2001 From: Alex Ivanov Date: Thu, 10 Oct 2019 15:39:28 +0300 Subject: [PATCH 347/915] Russian updates Q109-116 Signed-off-by: Alex Ivanov --- ru-RU/README.md | 297 +++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 295 insertions(+), 2 deletions(-) diff --git a/ru-RU/README.md b/ru-RU/README.md index f9d7aa1e..a3ec26e1 100644 --- a/ru-RU/README.md +++ b/ru-RU/README.md @@ -2,7 +2,7 @@ Я ежедневно публикую вопросы по JavaScript с вариантами ответов в своем [Instagram](https://www.instagram.com/theavocoder), которые дублируются в этом репозитории. -От базового до продвинутого: проверьте, насколько хорошо вы знаете JavaScript, немного освежите свои знания или подготовьтесь к собеседованию! :muscle: :rocket: Я обновляю репозиторий еженедельно новыми вопросами. Последнее обновление: 17 августа. +От базового до продвинутого: проверьте, насколько хорошо вы знаете JavaScript, немного освежите свои знания или подготовьтесь к собеседованию! :muscle: :rocket: Я обновляю репозиторий еженедельно новыми вопросами. Последнее обновление: 9 октября. Ответы находятся в свернутой секции ниже вопросов. Просто нажми на "Ответ", чтобы развернуть. Удачи! :heart: @@ -3225,7 +3225,7 @@ console.log(one, two, three) --- -###### 102. Какое значение будет на выходе? +###### 102. Какое значение будет на выходе? ```javascript const myPromise = () => Promise.resolve('I have resolved!') @@ -3457,3 +3457,296 @@ emojis.splice(1, 2, '✨')

+ +--- + +###### 109. Какое значение будет на выходе? + +```javascript +const food = ['🍕', '🍫', '🥑', '🍔'] +const info = { favoriteFood: food[0] } + +info.favoriteFood = '🍝' + +console.log(food) +``` + +- A: `['🍕', '🍫', '🥑', '🍔']` +- B: `['🍝', '🍫', '🥑', '🍔']` +- C: `['🍝', '🍕', '🍫', '🥑', '🍔']` +- D: `ReferenceError` + +
Ответ +

+ +#### Ответ: A + +Мы устанавливаем значение свойства `favourFood` для объекта `info` равным строке со смайликами для пиццы, `'🍕'`. Строка является примитивным типом данных. В JavaScript примитивные типы данных передаются по ссылке ... + +В JavaScript примитивные типы данных (все, что не является объектом) передаются как _значение_. В этом случае мы устанавливаем значение свойства `favourFood` объекта `info` равным значению первого элемента в массиве `food`, в данном случае это строка с emoji пиццы (`'🍕'`). Строка является примитивным типом данных и взаимодействует по значению (см. мой [пост в блоге](https://www.theavocoder.com/complete-javascript/2018/12/21/by-value-vs-by-reference), если вы заинтересованы в получении дополнительной информации). + +Затем мы меняем значение свойства `favourFood` объекта `info`. Массив `food` не изменился, поскольку значение `favourFood` было просто _скопировано_ из значения первого элемента в массиве и не имеет ссылки на то же место в памяти, что и элемент на `food[0]`. Когда мы выводим в лог `food`, это все равно исходный массив, `['🍕', '🍫', '🥑', '🍔']`. + +

+
+ +--- + +###### 110. Что делает этот метод? + +```javascript +JSON.parse() +``` + +- A: Разбирает JSON в значение JavaScript +- B: Разбирает объект JavaScript в JSON +- C: Разбирает любое значение JavaScript в JSON +- D: Разбирает JSON непосредственно в объект JavaScript + +
Ответ +

+ +#### Ответ: 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`: мы объявляем переменную `name` с ключевым словом `let` и значением `'Sarah'`. + +Переменные с ключевым словом `let` (и `const`) поднимаются в начало функции, в отличие от `var`, которые не инициализируется. Они недоступны до того, как мы объявим (инициализируем) их строку. Это называется "временной мертвой зоной". Когда мы пытаемся получить доступ к переменным до их объявления, JavaScript выдает `ReferenceError`. + +Если бы мы не объявили переменную `name` в функции `getName`, движок javascript посмотрел бы вниз по _цепочки области действия_. Внешняя область имеет переменную с именем `name` со значением `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`, мы получаем значения в функции генератора. С помощью ключевого слова `yield*` мы можем получить значения из другой функции-генератора или итерируемого объекта (например, массива). + +В `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 +``` + +В файле `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 +``` + +

+
+ +--- + +###### 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')`. Мы передаем значение `'I love'` в качестве аргумента стрелочной функции `x => x`. `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`, эти объекты получают метку _собрано в мусор_, так как больше нет ссылок на этот объект. Однако, поскольку функция обратного вызова в `setInterval` является стрелочной функцией стрелки (таким образом, привязанной к объекту `config`), функция обратного вызова все еще содержит ссылку на объект `config`. Пока есть ссылка, объект не будет собран в мусор. Поскольку сборщик мусора не отрабатывает, функция обратного вызова `setInterval` будет по-прежнему вызываться каждые 1000 мс (1с). + +

+
+ +--- + +###### 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 и 3 +- D: Каждый из них + +
Ответ +

+ +#### Ответ: B + +При добавлении пары ключ/значение с использованием метода `set` имя ключа будет равно значению первого аргумента, переданного в функцию `set`, а значением будет второй аргумент, переданный в функцию `set`. В данном случае ключом является _функция_ `() => '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`. + +Сначала мы вызываем функцию `changeAge` и передаем объект `person` в качестве аргумента. Эта функция увеличивает значение свойства `age` на 1. `person` теперь `{name: "Lydia", age: 22}`. + +Затем мы вызываем функцию `changeAgeAndName`, однако мы не передаем параметр. Вместо этого значение `x` равно новому объекту: `{ ... person }`. Поскольку это новый объект, он не влияет на значения свойств объекта `person`. `person` по-прежнему равен `{name: "Lydia", age: 22}`. + +

+
\ No newline at end of file From d566d2c7ae3681d20dde9d5f225e33bbc45aa1d3 Mon Sep 17 00:00:00 2001 From: Jacob Herper Date: Thu, 10 Oct 2019 18:01:20 +0100 Subject: [PATCH 348/915] Questions 109 - 116 translated into German --- de-DE/README.md | 292 ++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 292 insertions(+) diff --git a/de-DE/README.md b/de-DE/README.md index 526d58cd..2a0cdd91 100644 --- a/de-DE/README.md +++ b/de-DE/README.md @@ -3458,3 +3458,295 @@ Mit der `splice` Methode ändern wir das ursprüngliche Array durch löschen, er

+ + +--- + +###### 109. Was ist der Output? + +```javascript +const food = ['🍕', '🍫', '🥑', '🍔'] +const info = { favoriteFood: food[0] } + +info.favoriteFood = '🍝' + +console.log(food) +``` + +- A: `['🍕', '🍫', '🥑', '🍔']` +- B: `['🍝', '🍫', '🥑', '🍔']` +- C: `['🍝', '🍕', '🍫', '🥑', '🍔']` +- D: `ReferenceError` + +
Antwort +

+ +#### Antwort: A + +In JavaScript interagieren primitive Datentypen (alles außer Objekte) anhand des _Wertes_. In diesem Beispiel setzen wir den Wert von `favoriteFood` am `info` Objekt gleich dem Wert des ersten Elements im `food` Array, in dem Fall ein String mit dem Pizza Emoji (`'🍕'`). Ein String ist ein primitiver Datentyp und agiert daher in JavaScript nach Referenz. (Siehe mein [Blogpost](https://www.theavocoder.com/complete-javascript/2018/12/21/by-value-vs-by-reference) für mehr Informationen) + +Dann ändern wir den Wert von `favoriteFood` am `info` Objekt. Das `food` Array hat sich nicht verändert, da der Wert von `favoriteFood` nur eine _Kopie_ des Wertes des ersten Elements im Array war und keine Referenz zum Element `food[0]` im Speicher finden kann. Wenn wir also das Essen loggen ist es immernoch das ursprüngliche Array `['🍕', '🍫', '🥑', '🍔']`. + +

+
+ +--- + +###### 110. Was macht diese Methode? + +```javascript +JSON.parse() +``` + +- A: Parsed JSON in einen JavaScript Wert +- B: Parsed ein JavaScript Objekt zu JSON +- C: Parsed jegliche JavaScript Werte zu JSON +- D: Parsed JSON zu jeglichem JavaScript Objekt + +
Antwort +

+ +#### Antwort: A + +Mit der `JSON.parse()` Methode können wir einen JSON String zu einem JavaScript Wert umwandeln. + +```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. Was ist der Output? + +```javascript +let name = 'Lydia' + +function getName() { + console.log(name) + let name = 'Sarah' +} + +getName() +``` + +- A: Lydia +- B: Sarah +- C: `undefined` +- D: `ReferenceError` + +
Antwort +

+ +#### Antwort: D + +Jede Funktion hat ihren eigenen _Ausführungskontext_ (oder _scope_). Die `getName` Funktion sucht zuerst in ihrem eigenen Kontext (scope) um zu sehen, ob sie den Wert `name` finden kann. In diesem Fall beinhaltet die `getName` Funktion ihre eigene Variable `name`: wir setzen die Variable `name` mit dem `let` Keyword und dem Wert `'Sarah'`. + +Variablen mit dem `let` und `const` Keyword werden gehoisted, aber entgegen `var` werden diese nicht _initialisiert_. Sie sind nicht aufrufbar, bevor wir sie deklarieren (initialisieren). Das ist eine "vorübergehende tote Zone" (temporal dead zone). Wir bekommen einen `ReferenceError` ausgegeben. + +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' + +function getName() { + console.log(name) +} + +getName() // Lydia +``` + +

+
+ +--- + +###### 112. Was ist der 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` and `a` +- B: `a` and `undefined` +- C: `['a', 'b', 'c']` and `a` +- D: `a` and `['a', 'b', 'c']` + +
Antwort +

+ +#### Antwort: C + +Mit dem `yield` Keyword, halten wir Werte in einer Generator-Funktion. Mit dem `yield*` Keyword können wir Werte einer anderen Generator-Funktion oder Objekte und Arrays halten. + +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 +``` + +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 +``` + +

+
+ +--- + +###### 113. Was ist der 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` + +
Antwort +

+ +#### Antwort: A + +Expressions innerhalb von Template Literals werden zuerst berechnet. Das bedeutet, dass der String den ausgegebenen Wert der Expression beinhaltet, hier die IIFE (immediately invoked Function) `(x => x)('I love')`. Wir geben den Wert `'I love'` als Argument an die `x => x` Arrow Funktion. `x` ist gleich `'I love'` und wird ausgegeben. Das Ergebnis ist `I love to program`. + +

+
+ +--- + +###### 114. What will happen? + +```javascript +let config = { + alert: setInterval(() => { + console.log('Alert!) + }, 1000) +} + +config = null +``` + +- A: Die `setInterval` Callback Funktion wird nicht aufgerufen +- B: Die `setInterval` Callback Funktion wird ein Mal aufgerufen +- C: Die `setInterval` Callback Funktion wird weiterhin jede Sekunde aufgerufen +- D: Wir haben `config.alert()` nie aufgerufen, `config` ist `null` + +
Antwort +

+ +#### Antwort: C + +Wenn wir normalerweise Objekte gleich `null` setzen, werden diese _verworfen_, weil keine Referenz mehr zu ihnen existiert. Da die Callback Funktion in `setInterval` eine Arrow Funktion (und daher an `config` gebunden) ist, hält die Callback Funktion immernoch eine Referenz zum `config` Objekt. Solange eine Referenz besteht, wird das Objekt nicht verworfen und die `setInterval` Funktion wird weiterhin alle 1000ms (1 Sekunde) aufgerufen. + +

+
+ +--- + +###### 115. Welche Methode(n) geben den Wert `'Hello world!'` aus? + +```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 und 3 +- D: Alle + +
Antwort +

+ +#### Antwort: B + +Beim Setzen eines Key/Wert Paars mit der `set` Methode wird der Key als erstes Argument an die `set` Funktion übergeben und der Wert wird als zweites Argument eingegeben. Der Key ist die _Funktion_ `() => 'greeting'` und der Wert ist `'Hello world'`. `myMap` ist jetzt `{ () => 'greeting' => 'Hello world!' }`. + +1 ist falsch, weil der Key nicht `'greeting'`, sondern `() => 'greeting'` ist. +3 ist falsch, weil wir eine neue Funktion erstellen, indem wir sie als Argument übergeben. Objekte interagieren anhand von _Referenzen_. Funktionen sind Objekte, weshalb zwei Funktionen streng gesehen nie gleich sind, selbst wenn sie sich nicht unterscheiden. + +

+
+ +--- + +###### 116. Was ist der 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}` + +
Antwort +

+ +#### Antwort: C + +Beide Funktionen, `changeAge` und `changeAgeAndName`, haben Standard Parameter, nämlich ein neu erstelltes Objekt `{ ...person }`. Dieses Objekt hat Kopien aller Key/Werte Paare im `person` Objekt. + +Zuerst führen wir die `changeAge` Funktion aus und übergeben ihr das `person` Objekt als Argument. Daher wird `age` um 1 erhöht. `person` ist jetzt `{ name: "Lydia", age: 22 }`. + +Dann führen wir `changeAgeAndName` aus, allerdings ohne Parameter. Stattdessen ist der Wert von `x` gleich dem neuen Objekt `{ ...person }`. Da dies ein neues Objekt ist hat es keinen Einfluss auf die Werte des `person` Objekts. `person` ist immernoch gleich `{ name: "Lydia", age: 22 }`. + +

+
From e5604d199b2256a15d657b58f4b6a3c3409448a5 Mon Sep 17 00:00:00 2001 From: Mo Sureerat Date: Fri, 11 Oct 2019 03:14:42 +0700 Subject: [PATCH 349/915] Add TH link in other language README --- ar-AR/README_AR.md | 1 + bs-BS/README-bs_BS.md | 1 + de-DE/README.md | 1 + en-EN/README.md | 1 + es-ES/README-ES.md | 1 + fr-FR/README_fr-FR.md | 1 + ja-JA/README-ja_JA.md | 1 + ko-KR/README-ko_KR.md | 1 + pt-BR/README_pt_BR.md | 1 + ru-RU/README.md | 1 + tr-TR/README-tr_TR.md | 1 + ua-UA/README-ua_UA.md | 1 + vi-VI/README-vi.md | 1 + 13 files changed, 13 insertions(+) diff --git a/ar-AR/README_AR.md b/ar-AR/README_AR.md index 2478aff8..345dc75b 100644 --- a/ar-AR/README_AR.md +++ b/ar-AR/README_AR.md @@ -25,6 +25,7 @@ * [Tiếng Việt](./README-vi.md) * [Українська мова](./README-ua_UA.md) * [Português Brasil](./README_pt_BR.md) +* [ไทย](../th-TH/README-th_TH.md)
____________ diff --git a/bs-BS/README-bs_BS.md b/bs-BS/README-bs_BS.md index 7b05b601..3646acb9 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: [Njemački](./README-de_DE.md)
[Vijetnamski](./README-vi.md) [Українська мова](./README-ua_UA.md) +[ไทย](../th-TH/README-th_TH.md) * * * * * diff --git a/de-DE/README.md b/de-DE/README.md index 526d58cd..9fa161a6 100644 --- a/de-DE/README.md +++ b/de-DE/README.md @@ -22,6 +22,7 @@ Die Antworten sind unterhalb der Fragen versteckt. Du kannst einfach darauf klic * [Українська мова](../ua-UA/README-ua_UA.md) * [Tiếng Việt](../vi-VI/README-vi.md) * [中文版本](../zh-CN/README-zh_CN.md) +* [ไทย](../th-TH/README-th_TH.md) --- diff --git a/en-EN/README.md b/en-EN/README.md index 371b3a67..4626942b 100644 --- a/en-EN/README.md +++ b/en-EN/README.md @@ -26,6 +26,7 @@ List of available languages: * [Tiếng Việt](../vi-VI/README-vi.md) * [中文版本](../zh-CN/README-zh_CN.md) * [Türkçe](../tr-TR/README-tr_TR.md) +* [ไทย](../th-TH/README-th_TH.md) --- diff --git a/es-ES/README-ES.md b/es-ES/README-ES.md index 1c42de6b..7d7ff019 100644 --- a/es-ES/README-ES.md +++ b/es-ES/README-ES.md @@ -24,6 +24,7 @@ Lista de lenguajes disponibles: * [Tiếng Việt](./vi-VI/README-vi.md) * [中文版本](./zh-CN/README-zh_CN.md) * [Türkçe](./tr-TR/README-tr_TR.md) +* [ไทย](../th-TH/README-th_TH.md) --- diff --git a/fr-FR/README_fr-FR.md b/fr-FR/README_fr-FR.md index 36c5aa6f..27577014 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, * [Tiếng Việt](./README-vi.md) * [Українська мова](./README-ua_UA.md) * [Português Brasil](./README_pt_BR.md) +* [ไทย](../th-TH/README-th_TH.md) --- diff --git a/ja-JA/README-ja_JA.md b/ja-JA/README-ja_JA.md index c02042f7..86a0abef 100644 --- a/ja-JA/README-ja_JA.md +++ b/ja-JA/README-ja_JA.md @@ -22,6 +22,7 @@ * [Tiếng Việt](./README-vi.md) * [中文版本](./README-zh_CN.md) * [Türkçe](./README-tr_TR.md) +* [ไทย](../th-TH/README-th_TH.md) --- diff --git a/ko-KR/README-ko_KR.md b/ko-KR/README-ko_KR.md index 4ef08020..3f11c3ba 100644 --- a/ko-KR/README-ko_KR.md +++ b/ko-KR/README-ko_KR.md @@ -25,6 +25,7 @@ JavaScript 에 관한 객관식 문제를 [Instagram](https://www.instagram.com/ * [Tiếng Việt](../vi-VI/README-vi.md) * [中文版本](../zh-CN/README-zh_CN.md) * [Türkçe](../tr-TR/README-tr_TR.md) +* [ไทย](../th-TH/README-th_TH.md) --- diff --git a/pt-BR/README_pt_BR.md b/pt-BR/README_pt_BR.md index ae5f387d..4e8900ba 100644 --- a/pt-BR/README_pt_BR.md +++ b/pt-BR/README_pt_BR.md @@ -12,6 +12,7 @@ As respostas estão em seções recolhidas abaixo das questões, basta clicar ne [Western Balkan](./README-bs.md) [Deutsch](./README-de_DE.md) [Tiếng Việt](./README-vi.md) +[ไทย](../th-TH/README-th_TH.md) --- diff --git a/ru-RU/README.md b/ru-RU/README.md index 1c8c4440..d1513093 100644 --- a/ru-RU/README.md +++ b/ru-RU/README.md @@ -26,6 +26,7 @@ * [Tiếng Việt](../vi-VI/README-vi.md) * [中文版本](../zh-CN/README-zh_CN.md) * [Türkçe](../tr-TR/README-tr_TR.md) +* [ไทย](../th-TH/README-th_TH.md) --- diff --git a/tr-TR/README-tr_TR.md b/tr-TR/README-tr_TR.md index 59538b45..999a5b70 100644 --- a/tr-TR/README-tr_TR.md +++ b/tr-TR/README-tr_TR.md @@ -26,6 +26,7 @@ Mevcut dillerin listesi: * [Tiếng Việt](./README-vi.md) * [中文版本](./README-zh_CN.md) * [Türkçe](./README-tr_TR.md) +* [ไทย](../th-TH/README-th_TH.md) --- diff --git a/ua-UA/README-ua_UA.md b/ua-UA/README-ua_UA.md index 54eb1f99..17588122 100644 --- a/ua-UA/README-ua_UA.md +++ b/ua-UA/README-ua_UA.md @@ -12,6 +12,7 @@ [Deutsch](./README-de_DE.md) [Tiếng Việt](./README-vi.md) [日本語](./README-ja_JA.md) +[ไทย](../th-TH/README-th_TH.md) --- diff --git a/vi-VI/README-vi.md b/vi-VI/README-vi.md index 69ca5835..872d0597 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: * [Українська мова](../ua-UA/README-ua_UA.md) * [中文版本](../zh-CN/README-zh_CN.md) * [Türkçe](../tr-TR/README-tr_TR.md) +* [ไทย](../th-TH/README-th_TH.md) --- From 8af947b2086a39caabe3f16cab8f10d8e8e537ee Mon Sep 17 00:00:00 2001 From: Mo Sureerat Date: Fri, 11 Oct 2019 03:22:04 +0700 Subject: [PATCH 350/915] Update links in other language --- ar-AR/README_AR.md | 26 +++++++++++++++----------- bs-BS/README-bs_BS.md | 24 ++++++++++++++++-------- de-DE/README.md | 6 +++--- es-ES/README-ES.md | 30 +++++++++++++++--------------- fr-FR/README_fr-FR.md | 26 +++++++++++++++----------- ja-JA/README-ja_JA.md | 29 +++++++++++++++-------------- pt-BR/README_pt_BR.md | 23 ++++++++++++++++------- ru-RU/README.md | 12 ++++++------ th-TH/README.md | 31 +++++++++++++++---------------- tr-TR/README-tr_TR.md | 29 +++++++++++++++-------------- ua-UA/README-ua_UA.md | 23 ++++++++++++++++------- vi-VI/README-vi.md | 1 + 12 files changed, 148 insertions(+), 112 deletions(-) diff --git a/ar-AR/README_AR.md b/ar-AR/README_AR.md index 345dc75b..c32cd071 100644 --- a/ar-AR/README_AR.md +++ b/ar-AR/README_AR.md @@ -14,17 +14,21 @@ اللغات المتوفرة: -* [English](./README.md) -* [中文版本](./README-zh_CN.md) -* [Versión en español](./README-ES.md) -* [日本語](./README-ja_JA.md) -* [한국어](./README-ko_KR.md) -* [Русский](./ru-RU/README.md) -* [Western Balkan](./README-bs_BS.md) -* [Deutsch](./README-de_DE.md) -* [Tiếng Việt](./README-vi.md) -* [Українська мова](./README-ua_UA.md) -* [Português Brasil](./README_pt_BR.md) +* [English](../en-EN/README.md) +* [العربية](../ar-AR/README_AR.md) +* [اللغة العامية - Egyptian Arabic](../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) +* [日本語](../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) +* [Українська мова](../ua-UA/README-ua_UA.md) +* [Tiếng Việt](../vi-VI/README-vi.md) +* [中文版本](../zh-CN/README-zh_CN.md) +* [Türkçe](../tr-TR/README-tr_TR.md) * [ไทย](../th-TH/README-th_TH.md)
diff --git a/bs-BS/README-bs_BS.md b/bs-BS/README-bs_BS.md index 3646acb9..29063aea 100644 --- a/bs-BS/README-bs_BS.md +++ b/bs-BS/README-bs_BS.md @@ -12,14 +12,22 @@ Ovaj tjedni repo ažuriram s novim pitanjima. Odgovori su jednostavno dijelovima ispod pitanja kliknite na njih da biste ih proširili. Sretno :heart: - -[Kineski 中文版本](./README-zh_CN.md) -[Ruski](./README_ru-RU.md) -[Zapadni balkan](./README-bs_BS.md) -[Njemački](./README-de_DE.md)
-[Vijetnamski](./README-vi.md) -[Українська мова](./README-ua_UA.md) -[ไทย](../th-TH/README-th_TH.md) +* [English](../en-EN/README.md) +* [العربية](../ar-AR/README_AR.md) +* [اللغة العامية - Egyptian Arabic](../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) +* [日本語](../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) +* [Українська мова](../ua-UA/README-ua_UA.md) +* [Tiếng Việt](../vi-VI/README-vi.md) +* [中文版本](../zh-CN/README-zh_CN.md) +* [Türkçe](../tr-TR/README-tr_TR.md) +* [ไทย](../th-TH/README-th_TH.md) * * * * * diff --git a/de-DE/README.md b/de-DE/README.md index 9fa161a6..b2a35a96 100644 --- a/de-DE/README.md +++ b/de-DE/README.md @@ -9,7 +9,7 @@ Die Antworten sind unterhalb der Fragen versteckt. Du kannst einfach darauf klic ### Alle verfügbaren Sprachen * [English](../en-EN/README.md) * [العربية](../ar-AR/README_AR.md) -* [اللغة العامية](../ar-EG/README_ar-EG.md) +* [اللغة العامية - Egyptian Arabic](../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) @@ -17,11 +17,11 @@ Die Antworten sind unterhalb der Fragen versteckt. Du kannst einfach darauf klic * [日本語](../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) -* [Türkçe](../tr-TR/README-tr_TR.md) +* [Русский](../ru-RU/README.md) * [Українська мова](../ua-UA/README-ua_UA.md) * [Tiếng Việt](../vi-VI/README-vi.md) * [中文版本](../zh-CN/README-zh_CN.md) +* [Türkçe](../tr-TR/README-tr_TR.md) * [ไทย](../th-TH/README-th_TH.md) --- diff --git a/es-ES/README-ES.md b/es-ES/README-ES.md index 7d7ff019..fc24f9fe 100644 --- a/es-ES/README-ES.md +++ b/es-ES/README-ES.md @@ -9,21 +9,21 @@ --- Lista de lenguajes disponibles: -* [English](./en-EN/README.md) -* [العربية](./ar-AR/README_AR.md) -* [اللغة العامية - Egyptian Arabic](./ar-EG/README_ar-EG.md) -* [Bosanski](./bs-BS/README-bs_BS.md) -* [Deutsch](./de-DE/README-de_DE.md) -* [Español](./es-ES/README-ES.md) -* [Français](./fr-FR/README_fr-FR.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) -* [Українська мова](./ua-UA/README-ua_UA.md) -* [Tiếng Việt](./vi-VI/README-vi.md) -* [中文版本](./zh-CN/README-zh_CN.md) -* [Türkçe](./tr-TR/README-tr_TR.md) +* [English](../en-EN/README.md) +* [العربية](../ar-AR/README_AR.md) +* [اللغة العامية - Egyptian Arabic](../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) +* [日本語](../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) +* [Українська мова](../ua-UA/README-ua_UA.md) +* [Tiếng Việt](../vi-VI/README-vi.md) +* [中文版本](../zh-CN/README-zh_CN.md) +* [Türkçe](../tr-TR/README-tr_TR.md) * [ไทย](../th-TH/README-th_TH.md) diff --git a/fr-FR/README_fr-FR.md b/fr-FR/README_fr-FR.md index 27577014..eee56ec5 100644 --- a/fr-FR/README_fr-FR.md +++ b/fr-FR/README_fr-FR.md @@ -6,17 +6,21 @@ 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: -* [English](./README.md) -* [中文版本](./README-zh_CN.md) -* [Versión en español](./README-ES.md) -* [日本語](./README-ja_JA.md) -* [한국어](./README-ko_KR.md) -* [Русский](./ru-RU/README.md) -* [Western Balkan](./README-bs_BS.md) -* [Deutsch](./README-de_DE.md) -* [Tiếng Việt](./README-vi.md) -* [Українська мова](./README-ua_UA.md) -* [Português Brasil](./README_pt_BR.md) +* [English](../en-EN/README.md) +* [العربية](../ar-AR/README_AR.md) +* [اللغة العامية - Egyptian Arabic](../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) +* [日本語](../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) +* [Українська мова](../ua-UA/README-ua_UA.md) +* [Tiếng Việt](../vi-VI/README-vi.md) +* [中文版本](../zh-CN/README-zh_CN.md) +* [Türkçe](../tr-TR/README-tr_TR.md) * [ไทย](../th-TH/README-th_TH.md) --- diff --git a/ja-JA/README-ja_JA.md b/ja-JA/README-ja_JA.md index 86a0abef..2e480853 100644 --- a/ja-JA/README-ja_JA.md +++ b/ja-JA/README-ja_JA.md @@ -8,20 +8,21 @@ 利用可能な言語リスト: -* [English](./README.md) -* [العربية](./README_AR.md) -* [اللغة العامية - Egyptian Arabic](./README_ar-EG.md) -* [Bosanski](./README-bs_BS.md) -* [Deutsch](./README-de_DE.md) -* [Español](./README-ES.md) -* [日本語](./README-ja_JA.md) -* [한국어](./README-ko_KR.md) -* [Português Brasil](./README_pt_BR.md) -* [Русский](./ru-RU/README.md) -* [Українська мова](./README-ua_UA.md) -* [Tiếng Việt](./README-vi.md) -* [中文版本](./README-zh_CN.md) -* [Türkçe](./README-tr_TR.md) +* [English](../en-EN/README.md) +* [العربية](../ar-AR/README_AR.md) +* [اللغة العامية - Egyptian Arabic](../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) +* [日本語](../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) +* [Українська мова](../ua-UA/README-ua_UA.md) +* [Tiếng Việt](../vi-VI/README-vi.md) +* [中文版本](../zh-CN/README-zh_CN.md) +* [Türkçe](../tr-TR/README-tr_TR.md) * [ไทย](../th-TH/README-th_TH.md) --- diff --git a/pt-BR/README_pt_BR.md b/pt-BR/README_pt_BR.md index 4e8900ba..694b81a3 100644 --- a/pt-BR/README_pt_BR.md +++ b/pt-BR/README_pt_BR.md @@ -6,13 +6,22 @@ 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: -[English](./README.md) -[中文版本](./README-zh_CN.md) -[Русский](./README_ru-RU.md) -[Western Balkan](./README-bs.md) -[Deutsch](./README-de_DE.md) -[Tiếng Việt](./README-vi.md) -[ไทย](../th-TH/README-th_TH.md) +* [English](../en-EN/README.md) +* [العربية](../ar-AR/README_AR.md) +* [اللغة العامية - Egyptian Arabic](../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) +* [日本語](../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) +* [Українська мова](../ua-UA/README-ua_UA.md) +* [Tiếng Việt](../vi-VI/README-vi.md) +* [中文版本](../zh-CN/README-zh_CN.md) +* [Türkçe](../tr-TR/README-tr_TR.md) +* [ไทย](../th-TH/README-th_TH.md) --- diff --git a/ru-RU/README.md b/ru-RU/README.md index d1513093..d7a903e7 100644 --- a/ru-RU/README.md +++ b/ru-RU/README.md @@ -14,15 +14,15 @@ * [English](../en-EN/README.md) * [العربية](../ar-AR/README_AR.md) * [اللغة العامية - Egyptian Arabic](../ar-EG/README_ar-EG.md) -* [Bosanski](../bs-BS/README-bs_BS.md) -* [Deutsch](../de-DE/README.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) -* [日本語](../ja-JA/README-ja_JA.md) -* [한국어](../ko-KR/README-ko_KR.md) -* [Português Brasil](../pt-BR/README_pt_BR.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) -* [Українська мова](../ua-UA/README-ua_UA.md) +* [Українська мова](../ua-UA/README-ua_UA.md) * [Tiếng Việt](../vi-VI/README-vi.md) * [中文版本](../zh-CN/README-zh_CN.md) * [Türkçe](../tr-TR/README-tr_TR.md) diff --git a/th-TH/README.md b/th-TH/README.md index 9b518bcc..dd5e7885 100644 --- a/th-TH/README.md +++ b/th-TH/README.md @@ -11,22 +11,21 @@ ลิสต์ภาษาอื่นๆ: -* [English](./en-EN/README.md) -* [العربية](./ar-AR/README_AR.md) -* [اللغة العامية - Egyptian Arabic](./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) -* [日本語](./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) -* [Українська мова](./ua-UA/README-ua_UA.md) -* [Tiếng Việt](./vi-VI/README-vi.md) -* [中文版本](./zh-CN/README-zh_CN.md) -* [Türkçe](./tr-TR/README-tr_TR.md) -* [ไทย](./th-TH/README-th_TH.md) +* [English](../en-EN/README.md) +* [العربية](../ar-AR/README_AR.md) +* [اللغة العامية - Egyptian Arabic](../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) +* [日本語](../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) +* [Українська мова](../ua-UA/README-ua_UA.md) +* [Tiếng Việt](../vi-VI/README-vi.md) +* [中文版本](../zh-CN/README-zh_CN.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 999a5b70..8b152ae1 100644 --- a/tr-TR/README-tr_TR.md +++ b/tr-TR/README-tr_TR.md @@ -12,20 +12,21 @@ Daha fazla soru eklendikçe eposta almak ister misiniz?
Mevcut dillerin listesi: -* [English](./README.md) -* [العربية](./README_AR.md) -* [اللغة العامية - Egyptian Arabic](./README_ar-EG.md) -* [Bosanski](./README-bs_BS.md) -* [Deutsch](./README-de_DE.md) -* [Español](./README-ES.md) -* [日本語](./README-ja_JA.md) -* [한국어](./README-ko_KR.md) -* [Português Brasil](./README_pt_BR.md) -* [Русский](./ru-RU/README.md) -* [Українська мова](./README-ua_UA.md) -* [Tiếng Việt](./README-vi.md) -* [中文版本](./README-zh_CN.md) -* [Türkçe](./README-tr_TR.md) +* [English](../en-EN/README.md) +* [العربية](../ar-AR/README_AR.md) +* [اللغة العامية - Egyptian Arabic](../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) +* [日本語](../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) +* [Українська мова](../ua-UA/README-ua_UA.md) +* [Tiếng Việt](../vi-VI/README-vi.md) +* [中文版本](../zh-CN/README-zh_CN.md) +* [Türkçe](../tr-TR/README-tr_TR.md) * [ไทย](../th-TH/README-th_TH.md) --- diff --git a/ua-UA/README-ua_UA.md b/ua-UA/README-ua_UA.md index 17588122..f8bac018 100644 --- a/ua-UA/README-ua_UA.md +++ b/ua-UA/README-ua_UA.md @@ -6,13 +6,22 @@ Відповіді знаходяться в згорнутої секції нижче питань. Просто натисни на відповідь, щоб розгорнути. Успіхів! :heart: -[中文版本](./README-zh_CN.md) -[Русский](./README_ru-RU.md) -[Western Balkan](./README-bs_BS.md) -[Deutsch](./README-de_DE.md) -[Tiếng Việt](./README-vi.md) -[日本語](./README-ja_JA.md) -[ไทย](../th-TH/README-th_TH.md) +* [English](../en-EN/README.md) +* [العربية](../ar-AR/README_AR.md) +* [اللغة العامية - Egyptian Arabic](../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) +* [日本語](../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) +* [Українська мова](../ua-UA/README-ua_UA.md) +* [Tiếng Việt](../vi-VI/README-vi.md) +* [中文版本](../zh-CN/README-zh_CN.md) +* [Türkçe](../tr-TR/README-tr_TR.md) +* [ไทย](../th-TH/README-th_TH.md) --- diff --git a/vi-VI/README-vi.md b/vi-VI/README-vi.md index 872d0597..90b7090c 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: * [Português Brasil](../pt-BR/README_pt_BR.md) * [Русский](../ru-RU/README.md) * [Українська мова](../ua-UA/README-ua_UA.md) +* [Tiếng Việt](../vi-VI/README-vi.md) * [中文版本](../zh-CN/README-zh_CN.md) * [Türkçe](../tr-TR/README-tr_TR.md) * [ไทย](../th-TH/README-th_TH.md) From d4ccfd4c5fa9fabd6fb97e19c5cb7a0c6a5d1754 Mon Sep 17 00:00:00 2001 From: Alex Ivanov Date: Sun, 13 Oct 2019 14:48:03 +0300 Subject: [PATCH 351/915] Resolve conflicts #97 Signed-off-by: Alex Ivanov --- README.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index 989743d7..87cc4d64 100644 --- a/README.md +++ b/README.md @@ -1499,7 +1499,7 @@ Only the first numbers in the string is returned. Based on the _radix_ (the seco --- -###### 50. What's the output`? +###### 50. What's the output? ```javascript [1, 2, 3].map(num => { @@ -1593,9 +1593,9 @@ sayHi(); #### Answer: 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 `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'`. +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!'`.

@@ -1652,7 +1652,7 @@ console.log(typeof y); #### Answer: A -`let x = y = 10;` is actually shorthand for: +`let x = (y = 10);` is actually shorthand for: ```javascript y = 10; From c0948ce6058d8e38b835bde68a544c2bf244afd0 Mon Sep 17 00:00:00 2001 From: gankai Date: Thu, 17 Oct 2019 10:48:56 +0800 Subject: [PATCH 352/915] Fix a bug in en-EN/README.md and translate questions from 102 to 108 into Chinese --- en-EN/README.md | 2 +- zh-CN/README-zh_CN.md | 239 ++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 240 insertions(+), 1 deletion(-) diff --git a/en-EN/README.md b/en-EN/README.md index cecdbd86..455db922 100644 --- a/en-EN/README.md +++ b/en-EN/README.md @@ -3399,7 +3399,7 @@ console.log(colorConfig.colors[1]) 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`. +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 `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. diff --git a/zh-CN/README-zh_CN.md b/zh-CN/README-zh_CN.md index 0951e51c..c46d6759 100644 --- a/zh-CN/README-zh_CN.md +++ b/zh-CN/README-zh_CN.md @@ -3225,3 +3225,242 @@ console.log(one, two, 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)并且调用栈为空时,我才想使用这个值。_ + +我们可以在异步函数中同时使用`.then`和`await`关键字来获取promise的返回值。尽管我们可以同时使用`.then`和`await`来获得promise的返回值,但它们的运行方式有所不同。 + +在`firstFunction`函数中,当这个函数运行的时候,代码执行到myPromise函数时,系统会将其放在一边,继续执行下一行代码,在本例中为`console.log('second')`,执行完成之后,myPromise函数返回一个resolved后的字符串'I have resolved!' 在看到调用堆栈为空之后将其记录下来。 + +由于在`secondFunction`函数中使用了`await`关键字,从字面上暂停了异步函数的执行,程序将会等到myPromise函数返回结果之后,才会执行下一行代码, + +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. + +这意味着,程序在等待`myPromise`的resolved的值`I have resolved!`,只有发生这种情况后,程序才会执行下一行代码:`console.log('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”。 + +

+
+ +--- + +###### 104. 它的值是什么? + +```javascript +Promise.resolve(5) +``` + +- A: `5` +- B: `Promise {: 5}` +- C: `Promise {: 5}` +- D: `Error` + +
答案 +

+ +#### 答案: C + +我们可以将我们想要的任何类型的值传递给Promise.resolve,无论是Promise还是非Promise。 该方法本身返回带有resolved值的Promise。 +如果您传递常规函数,它将是具有常规值的resolved的Promise。 如果您传入一个promise,它将是resolved的promise,其中包含已传入promise的resolved值。 + +在这种情况下,我们只传递了数值 5 。 它返回值为 5 的resolved的promise。 + +

+
+ +--- + +###### 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!` 。 + +

+
+ +--- + +###### 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属性的值。 + +

+
+ +--- + +###### 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”返回一个减小的值。 + +

+
\ No newline at end of file From d5771951b229c06468dc077b6bad99902d5b719f Mon Sep 17 00:00:00 2001 From: MaheshKonne Date: Fri, 18 Oct 2019 23:03:20 +0530 Subject: [PATCH 353/915] Typo correction of serialisation of an object --- README.md | 12 ++++++------ ar-AR/README_AR.md | 6 +++--- ar-EG/README_ar-EG.md | 4 ++-- de-DE/README.md | 10 +++++----- en-EN/README.md | 12 ++++++------ es-ES/README-ES.md | 2 +- ja-JA/README-ja_JA.md | 6 +++--- ko-KR/README-ko_KR.md | 10 +++++----- pt-BR/README_pt_BR.md | 4 ++-- ru-RU/README.md | 12 ++++++------ th-TH/README.md | 10 +++++----- tr-TR/README-tr_TR.md | 4 ++-- ua-UA/README-ua_UA.md | 4 ++-- vi-VI/README-vi.md | 4 ++-- 14 files changed, 50 insertions(+), 50 deletions(-) diff --git a/README.md b/README.md index 989743d7..685b746a 100644 --- a/README.md +++ b/README.md @@ -879,9 +879,9 @@ console.log(a[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`. +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`. +Then, we log `a[b]`, which is actually `a["object Object"]`. We just set that to `456`, so it returns `456`.

@@ -3286,8 +3286,8 @@ for (let item of set) { - A: `3`, `NaN`, `NaN` - B: `3`, `7`, `NaN` -- C: `3`, `Lydia2`, `[Object object]2` -- D: `"12"`, `Lydia2`, `[Object object]2` +- C: `3`, `Lydia2`, `[object Object]2` +- D: `"12"`, `Lydia2`, `[object Object]2`
Answer

@@ -3300,7 +3300,7 @@ 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"`. +`{ 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"`.

@@ -3750,4 +3750,4 @@ First, we invoke the `changeAge` function and pass the `person` object as its ar 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 }`.

- \ No newline at end of file + diff --git a/ar-AR/README_AR.md b/ar-AR/README_AR.md index c32cd071..fb8ae229 100644 --- a/ar-AR/README_AR.md +++ b/ar-AR/README_AR.md @@ -910,10 +910,10 @@ console.log(a[b]); مفاتيح ال object يتم تحويلها اوتوماتيكيا الى strings. نحن نحاول أن نقوم بجعل object عبارة عن مفتاح للobject `a`, و الذي يحمل القيمة `123`. -و لكن, عندما نقوم بمحاول جعل object الى نوع string, سيصبح `"[Object object]"`. لذا ما نحاول أن نقوله هنا, هو أن `a["Object object"] = 123`. -إذا, سنحاول أن نفعل هذا مرة أخرى , `c` هو object آخر سنقوم بتحويله الى string بصورة صريحة, لذا `a["Object object"] = 456`. +و لكن, عندما نقوم بمحاول جعل object الى نوع string, سيصبح `"[object Object]"`. لذا ما نحاول أن نقوله هنا, هو أن `a["object Object"] = 123`. +إذا, سنحاول أن نفعل هذا مرة أخرى , `c` هو object آخر سنقوم بتحويله الى string بصورة صريحة, لذا `a["object Object"] = 456`. -إذاَ, نحن نقوم بعمل log ل `a[b]`, و التي هي في الحقيقة `a["Object object"]`. و نحن قبل قليل قمنا بوضع قيمتها التي تساوي `456`, لذا ستقوم بإرجاع `456`. +إذاَ, نحن نقوم بعمل log ل `a[b]`, و التي هي في الحقيقة `a["object Object"]`. و نحن قبل قليل قمنا بوضع قيمتها التي تساوي `456`, لذا ستقوم بإرجاع `456`.

diff --git a/ar-EG/README_ar-EG.md b/ar-EG/README_ar-EG.md index 5e3dd9f5..656a2ccf 100644 --- a/ar-EG/README_ar-EG.md +++ b/ar-EG/README_ar-EG.md @@ -940,7 +940,7 @@ console.log(a[b]); #### الاجابة الصحيحة: ب -مفاتيح العناصر `Object keys` بيتم تحويلهم تلقائياً الى string. احنا هنا بنحاول نحط اوبجكت على انه مفتاح لأوبجكت تاني. بس المشكلة ان لما نعمل كده مش بيترجم لأسمه او لمحتوياته بل بيتحول الى `[Object object] و بالتالي احنا كنا كأننا بالظبط عاملين `a["Object object"]=123` و بنكرر كده مع `c` و بعد كده بنقوم طابعين `a[b]` اللي احنا لسه مخليين مفتاحها من شوية `a["Object object"]` و خلينا القيمة بتاعته 456 و بالتالي دي اللي بتطبع. +مفاتيح العناصر `Object keys` بيتم تحويلهم تلقائياً الى string. احنا هنا بنحاول نحط اوبجكت على انه مفتاح لأوبجكت تاني. بس المشكلة ان لما نعمل كده مش بيترجم لأسمه او لمحتوياته بل بيتحول الى `[object Object] و بالتالي احنا كنا كأننا بالظبط عاملين `a["object Object"]=123` و بنكرر كده مع `c` و بعد كده بنقوم طابعين `a[b]` اللي احنا لسه مخليين مفتاحها من شوية `a["object Object"]` و خلينا القيمة بتاعته 456 و بالتالي دي اللي بتطبع.

@@ -1403,4 +1403,4 @@ setInterval(() => console.log("Hi"), 1000);

- \ No newline at end of file + diff --git a/de-DE/README.md b/de-DE/README.md index 536cd7da..b5e6ff78 100644 --- a/de-DE/README.md +++ b/de-DE/README.md @@ -874,9 +874,9 @@ console.log(a[b]); Objekt Keys werden automatisch in Strings umgewandelt. Wir versuchen ein Objekt mit dem Wert `123` als Key dem Objekt `a` zuzuweisen. -Allerdings wird ein Object, wenn es in einen String umgewandelt wird als `"[Object object]"` ausgegeben. Was wir hier also sagen ist, dass `a["Object object"] = 123` ist. Wir versuchen das gleiche erneut - `c` ist ein anderes Objekt, welches wir implizit zu einem String umwandeln, sodass `a["Object object"] = 456` ist. +Allerdings wird ein Object, wenn es in einen String umgewandelt wird als `"[object Object]"` ausgegeben. Was wir hier also sagen ist, dass `a["object Object"] = 123` ist. Wir versuchen das gleiche erneut - `c` ist ein anderes Objekt, welches wir implizit zu einem String umwandeln, sodass `a["object Object"] = 456` ist. -Dann loggen wir `a[b]`, was eigentlich `a["Object object"]` ist und gerade von uns zu `456` gesetzt wurde, sodass `456` ausgegeben wird. +Dann loggen wir `a[b]`, was eigentlich `a["object Object"]` ist und gerade von uns zu `456` gesetzt wurde, sodass `456` ausgegeben wird.

@@ -3287,8 +3287,8 @@ for (let item of set) { - A: `3`, `NaN`, `NaN` - B: `3`, `7`, `NaN` -- C: `3`, `Lydia2`, `[Object object]2` -- D: `"12"`, `Lydia2`, `[Object object]2` +- C: `3`, `Lydia2`, `[object Object]2` +- D: `"12"`, `Lydia2`, `[object Object]2`
Antwort

@@ -3301,7 +3301,7 @@ Der erste Wert ist `1`, was ein numerischer Wert ist. `1 + 2` ergibt die Zahl `3 Der zweite Wert hingegen ist der String `"Lydia"`. `"Lydia"` ist ein String und `2` ist eine Nummer: `2` wird in einem String umgewandelt. `"Lydia"` und `"2"` werden zusammengesetzt, was den String `"Lydia2"` ausgibt. -`{ name: "Lydia" }` ist ein Objekt. Weder eine Nummer, noch ein Objekt sind ein String, aber beide werden zu Strings konvertiert und `"[Object object]"` wird ausgegeben. `"[Object object]"` zusammengesetzt mit `"2"` wird `"[Object object]2"`. +`{ name: "Lydia" }` ist ein Objekt. Weder eine Nummer, noch ein Objekt sind ein String, aber beide werden zu Strings konvertiert und `"[object Object]"` wird ausgegeben. `"[object Object]"` zusammengesetzt mit `"2"` wird `"[object Object]2"`.

diff --git a/en-EN/README.md b/en-EN/README.md index cecdbd86..1911c2f8 100644 --- a/en-EN/README.md +++ b/en-EN/README.md @@ -879,9 +879,9 @@ console.log(a[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`. +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`. +Then, we log `a[b]`, which is actually `a["object Object"]`. We just set that to `456`, so it returns `456`.

@@ -3286,8 +3286,8 @@ for (let item of set) { - A: `3`, `NaN`, `NaN` - B: `3`, `7`, `NaN` -- C: `3`, `Lydia2`, `[Object object]2` -- D: `"12"`, `Lydia2`, `[Object object]2` +- C: `3`, `Lydia2`, `[object Object]2` +- D: `"12"`, `Lydia2`, `[object Object]2`
Answer

@@ -3300,7 +3300,7 @@ 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, 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"`. +`{ 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"`.

@@ -3750,4 +3750,4 @@ First, we invoke the `changeAge` function and pass the `person` object as its ar 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 }`.

- \ No newline at end of file + diff --git a/es-ES/README-ES.md b/es-ES/README-ES.md index fc24f9fe..9c2e713f 100644 --- a/es-ES/README-ES.md +++ b/es-ES/README-ES.md @@ -874,7 +874,7 @@ console.log(a[b]); Las claves se convierten automáticamente en strings. Estamos tratando en este pregunta de establecer un objeto como clave para el objeto `a`, con el valor de `123`. -Sin embargo, cuando se _stringfy_ (compleja traducción) un objeto, se convierte en `"[Object object]"`. Así que lo que estamos diciendo aquí, es que `a["Object object"] = 123`. Entonces, podemos intentar hacer lo mismo de nuevo. `c` es otro objeto que estamos implícitamente encadenando. Entonces, `a["Object object"] = 456`. +Sin embargo, cuando se _stringfy_ (compleja traducción) un objeto, se convierte en `"[object Object]"`. Así que lo que estamos diciendo aquí, es que `a["object Object"] = 123`. Entonces, podemos intentar hacer lo mismo de nuevo. `c` es otro objeto que estamos implícitamente encadenando. Entonces, `a["object Object"] = 456`. Para finalizar, registramos `a[b]`, que en realidad es `a["Object"]`. Acabamos de ponerlo en `456`, así que devuelve `456`. diff --git a/ja-JA/README-ja_JA.md b/ja-JA/README-ja_JA.md index 2e480853..4b081ae8 100644 --- a/ja-JA/README-ja_JA.md +++ b/ja-JA/README-ja_JA.md @@ -902,11 +902,11 @@ console.log(a[b]); オブジェクトキーは自動的に文字列に変換されます。オブジェクトaのキーとして、値123で設定しようとしています。 -しかし、オブジェクトを文字列化すると、それは`"[Object object]"`​​になってしまいます。なので、ここで行っているのは、 `a["Object object"] = 123`です。 +しかし、オブジェクトを文字列化すると、それは`"[object Object]"`​​になってしまいます。なので、ここで行っているのは、 `a["object Object"] = 123`です。 -その後、同じことをもう一度試みています。`c`は暗黙のうちに文字列化している別のオブジェクトです。そのため、`a["Object object"] = 456`となります。 +その後、同じことをもう一度試みています。`c`は暗黙のうちに文字列化している別のオブジェクトです。そのため、`a["object Object"] = 456`となります。 -その後、`a[b]`でログ出力。実際には`a["Object object"]`です。これを `456`に設定しただけなので、`456`を返します。 +その後、`a[b]`でログ出力。実際には`a["object Object"]`です。これを `456`に設定しただけなので、`456`を返します。

diff --git a/ko-KR/README-ko_KR.md b/ko-KR/README-ko_KR.md index f9d8e4d5..1dcde230 100644 --- a/ko-KR/README-ko_KR.md +++ b/ko-KR/README-ko_KR.md @@ -877,9 +877,9 @@ console.log(a[b]); 객체 키는 자동으로 문자열로 변환돼요. 객체 `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`을 리턴해요.

@@ -3288,8 +3288,8 @@ for (let item of set) { - A: `3`, `NaN`, `NaN` - B: `3`, `7`, `NaN` -- C: `3`, `Lydia2`, `[Object object]2` -- D: `"12"`, `Lydia2`, `[Object object]2` +- C: `3`, `Lydia2`, `[object Object]2` +- D: `"12"`, `Lydia2`, `[object Object]2`
정답

@@ -3302,7 +3302,7 @@ for (let item of set) { 그러나, 두번째는 문자열 `"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"`가 돼요.

diff --git a/pt-BR/README_pt_BR.md b/pt-BR/README_pt_BR.md index 694b81a3..b9456327 100644 --- a/pt-BR/README_pt_BR.md +++ b/pt-BR/README_pt_BR.md @@ -878,9 +878,9 @@ console.log(a[b]); Chaves de objeto são automaticamente convertidas em strings. Estamos tentando usar um objeto como chave do objeto `a`, com o valor de `123`. -Contudo, quando transformamos um objeto em string, ele vira um `"[Object object]"`. Então, o que estamos afirmando é `a["Object object"] = 123`. Após, tentamos a mesma coisa. `c` é outro objeto que (implicitamente) convertemos para string. Então, temos `a["Object object"] = 456`. +Contudo, quando transformamos um objeto em string, ele vira um `"[object Object]"`. Então, o que estamos afirmando é `a["object Object"] = 123`. Após, tentamos a mesma coisa. `c` é outro objeto que (implicitamente) convertemos para string. Então, temos `a["object Object"] = 456`. -Então, fazemos o log de `a[b]`, o que na verdade é `a["Object object"]`. Acabmos de definir esse valor, como `456`, e é isso que ele retorna. +Então, fazemos o log de `a[b]`, o que na verdade é `a["object Object"]`. Acabmos de definir esse valor, como `456`, e é isso que ele retorna.

diff --git a/ru-RU/README.md b/ru-RU/README.md index c93d0c17..e709d4da 100644 --- a/ru-RU/README.md +++ b/ru-RU/README.md @@ -879,9 +879,9 @@ console.log(a[b]); Ключи объекта автоматически конвертируются в строки. Мы собираемся добавить объект в качестве ключа к объекту `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`.

@@ -3286,8 +3286,8 @@ for (let item of set) { - A: `3`, `NaN`, `NaN` - B: `3`, `7`, `NaN` -- C: `3`, `Lydia2`, `[Object object]2` -- D: `"12"`, `Lydia2`, `[Object object]2` +- C: `3`, `Lydia2`, `[object Object]2` +- D: `"12"`, `Lydia2`, `[object Object]2`
Ответ

@@ -3300,7 +3300,7 @@ for (let item of set) { Тем не менее, вторая строка `"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"`.

@@ -3750,4 +3750,4 @@ console.log(person) Затем мы вызываем функцию `changeAgeAndName`, однако мы не передаем параметр. Вместо этого значение `x` равно новому объекту: `{ ... person }`. Поскольку это новый объект, он не влияет на значения свойств объекта `person`. `person` по-прежнему равен `{name: "Lydia", age: 22}`.

- \ No newline at end of file + diff --git a/th-TH/README.md b/th-TH/README.md index dd5e7885..c20e707a 100644 --- a/th-TH/README.md +++ b/th-TH/README.md @@ -878,9 +878,9 @@ console.log(a[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`. +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`. +Then, we log `a[b]`, which is actually `a["object Object"]`. We just set that to `456`, so it returns `456`.

@@ -3285,8 +3285,8 @@ for (let item of set) { - A: `3`, `NaN`, `NaN` - B: `3`, `7`, `NaN` -- C: `3`, `Lydia2`, `[Object object]2` -- D: `"12"`, `Lydia2`, `[Object object]2` +- C: `3`, `Lydia2`, `[object Object]2` +- D: `"12"`, `Lydia2`, `[object Object]2`
คำตอบ

@@ -3299,7 +3299,7 @@ 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"`. -`{ 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"`. +`{ 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"`.

diff --git a/tr-TR/README-tr_TR.md b/tr-TR/README-tr_TR.md index 8b152ae1..f09a2ccb 100644 --- a/tr-TR/README-tr_TR.md +++ b/tr-TR/README-tr_TR.md @@ -869,9 +869,9 @@ console.log(a[b]); Nesne keyleri otomatik olarak stringe dönüştürülür. `a` nesnesine değeri `123` olacak şekilde, bir nesneyi key olarak atamaya çalışıyoruz. -Ancak, bir nesnesi string hale getirince, `"[Object object]"` olur. Dolayısıyla burada söylediğimiz, `a["Object object"] = 123`. Sonra, aynı şeyi tekrar yapmayı deniyoruz. `c`, dolaylı olarak string hale getirdiğimiz başka bir nesne. O halde, `a["Object object"] = 456`. +Ancak, bir nesnesi string hale getirince, `"[object Object]"` olur. Dolayısıyla burada söylediğimiz, `a["object Object"] = 123`. Sonra, aynı şeyi tekrar yapmayı deniyoruz. `c`, dolaylı olarak string hale getirdiğimiz başka bir nesne. O halde, `a["object Object"] = 456`. -Sonra, `a[b]`'yi logluyoruz, ki aslında o da `a["Object object"]`. Onu da `456` olarak atamıştık, o yüzden `456` döndürür. +Sonra, `a[b]`'yi logluyoruz, ki aslında o da `a["object Object"]`. Onu da `456` olarak atamıştık, o yüzden `456` döndürür.

diff --git a/ua-UA/README-ua_UA.md b/ua-UA/README-ua_UA.md index f8bac018..73677c00 100644 --- a/ua-UA/README-ua_UA.md +++ b/ua-UA/README-ua_UA.md @@ -872,9 +872,9 @@ console.log(a[b]); Ключі об'єкта автоматично конвертуються в рядки. Ми збираємося додати об'єкт в якості ключа до об'єкта `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`.

diff --git a/vi-VI/README-vi.md b/vi-VI/README-vi.md index 90b7090c..36ddfb77 100644 --- a/vi-VI/README-vi.md +++ b/vi-VI/README-vi.md @@ -875,9 +875,9 @@ console.log(a[b]); Object keys sẽ tự động được convert sang dạng string. Chúng ta đang set một object như là một key cho object `a`, với giá trị là `123`. -Tuy nhiên khi ta string hóa một object, nó sẽ trở thành `"[Object object]"`. Nên tại đây phép gán này thực chất chính là `a["Object object"] = 123`. Phép gán tiếp theo cũng giống hệt vậy. `c` là một object khác mà chúng ta đang string hóa nó. Theo đó, `a["Object object"] = 456`. +Tuy nhiên khi ta string hóa một object, nó sẽ trở thành `"[object Object]"`. Nên tại đây phép gán này thực chất chính là `a["object Object"] = 123`. Phép gán tiếp theo cũng giống hệt vậy. `c` là một object khác mà chúng ta đang string hóa nó. Theo đó, `a["object Object"] = 456`. -Cuối cùng khi gọi `a[b]`, thực chất chính là gọi `a["Object object"]`. Giá trị của nó là `456`, nên trả về là `456`. +Cuối cùng khi gọi `a[b]`, thực chất chính là gọi `a["object Object"]`. Giá trị của nó là `456`, nên trả về là `456`.

From 322356d29f5265f75e34ac0d3d14ef4354ee9f46 Mon Sep 17 00:00:00 2001 From: Jonas Talavera Date: Wed, 23 Oct 2019 20:03:17 +0200 Subject: [PATCH 354/915] Translate question 95 --- es-ES/README-ES.md | 50 +++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 49 insertions(+), 1 deletion(-) diff --git a/es-ES/README-ES.md b/es-ES/README-ES.md index fc24f9fe..efeb13c1 100644 --- a/es-ES/README-ES.md +++ b/es-ES/README-ES.md @@ -7,7 +7,10 @@ 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: * [English](../en-EN/README.md) * [العربية](../ar-AR/README_AR.md) @@ -2982,3 +2985,48 @@ getItems(["banana", "apple"], "pear", "orange") El ejemplo de arriba sí que funciona. Devuelve el array `[ 'banana', 'apple', 'orange', 'pear' ]`

+ +--- + +###### 95. ¿Cuál es el resultado? + +```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` y `b is bigger`, `3` +- B: `a is bigger`, `undefined` y `b is bigger`, `undefined` +- C: `undefined` y `undefined` +- D: `SyntaxError` + +
Solución +

+ +#### 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. + +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 +``` + +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`! + +

+
+ +--- From 2f6ef1f70e163c6b0ca554202e817963188dff79 Mon Sep 17 00:00:00 2001 From: Jonas Talavera Date: Wed, 23 Oct 2019 20:14:15 +0200 Subject: [PATCH 355/915] Translate question 96 --- es-ES/README-ES.md | 37 +++++++++++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) diff --git a/es-ES/README-ES.md b/es-ES/README-ES.md index efeb13c1..6178b90d 100644 --- a/es-ES/README-ES.md +++ b/es-ES/README-ES.md @@ -3030,3 +3030,40 @@ Esto significa que nunca se alcanza `a + b`, ya que una función deja de ejecuta --- + +###### 96. ¿Cuál es el resultado? + +```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` + +
Solución +

+ +#### Answer: B + +Podemos establecer clases iguales a otros constructures de clases/funciones. En este caso, establecemos `Person` igual a `AnotherPerson`. El nombre en este constructor es `Sarah`, por lo que la propiedad nombre en la nueva instancia de `Person` de `member` es `"Sarah"`. + +

+
+ +--- + From 40a2b4d684f1c713e76776e5f01c088c1846c0ab Mon Sep 17 00:00:00 2001 From: Jonas Talavera Date: Wed, 23 Oct 2019 20:34:39 +0200 Subject: [PATCH 356/915] Translate question 97 --- es-ES/README-ES.md | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) diff --git a/es-ES/README-ES.md b/es-ES/README-ES.md index 6178b90d..05891de3 100644 --- a/es-ES/README-ES.md +++ b/es-ES/README-ES.md @@ -3067,3 +3067,33 @@ Podemos establecer clases iguales a otros constructures de clases/funciones. En --- +###### 97. ¿Cuál es el resultado? + +```javascript +const info = { + [Symbol('a')]: 'b' +} + +console.log(info) +console.log(Object.keys(info)) +``` + +- A: `{Symbol('a'): 'b'}` y `["{Symbol('a')"]` +- B: `{}` y `[]` +- C: `{ a: "b" }` y `["a"]` +- D: `{Symbol('a'): 'b'}` y `[]` + +
Solución +

+ +#### Answer: D + +Un símbolo no es _enumerable_. El método Object.keys devuelve todas las propiedades _enumerables_ de un objeto. El símbolo no será visible, y un array vacío será devuelto. Cuando se imprime el objeto completo, se mostrarán todas las propiedades, incluidas las no-enumerables. + +Esta es una de las muchas cualidades de un símbolo: además de representar un valor completamente único (que evita la colisión accidental de nombres en los objetos, por ejemplo, cuando se utilizan 2 bibliotecas que desean agregar propiedades al mismo objeto), también puedes "ocultar" propiedades en los objetos de esta manera (aunque no del todo. Todavía puedes acceder a los símbolos utilizando el método `Object.getOwnPropertySymbols()`). + +

+
+ +--- + From 90a63bca85bc8c7c5339fcad32b5513f0acd98cf Mon Sep 17 00:00:00 2001 From: Jonas Talavera Date: Wed, 23 Oct 2019 21:09:27 +0200 Subject: [PATCH 357/915] Translate question 98 --- es-ES/README-ES.md | 40 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 40 insertions(+) diff --git a/es-ES/README-ES.md b/es-ES/README-ES.md index 05891de3..069bd4ed 100644 --- a/es-ES/README-ES.md +++ b/es-ES/README-ES.md @@ -3097,3 +3097,43 @@ Esta es una de las muchas cualidades de un símbolo: además de representar un v --- +###### 98. ¿Cuál es el resultado? + +```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]]` y `undefined` +- B: `[1, [2, 3, 4]]` y `{ name: "Lydia", age: 21 }` +- C: `[1, 2, 3, 4]` y `{ name: "Lydia", age: 21 }` +- D: `Error` y `{ name: "Lydia", age: 21 }` + +
Solución +

+ +#### Answer: A + +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]` + +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: + +```const getUser = user => ({ name: user.name, age: user.age })``` + +Como no se devuelve ningún valor en este caso, la función devuelve `undefined`. + +

+
+ +--- + From 6e77d76ef0df066759534c35cb3899684b0a9976 Mon Sep 17 00:00:00 2001 From: Jonas Talavera Date: Wed, 23 Oct 2019 21:21:37 +0200 Subject: [PATCH 358/915] Translate question 99 --- es-ES/README-ES.md | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) diff --git a/es-ES/README-ES.md b/es-ES/README-ES.md index 069bd4ed..ca379aba 100644 --- a/es-ES/README-ES.md +++ b/es-ES/README-ES.md @@ -3137,3 +3137,33 @@ 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" + +console.log(name()) +``` + +- A: `SyntaxError` +- B: `ReferenceError` +- C: `TypeError` +- D: `undefined` + +
Solución +

+ +#### Answer: C + +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 ReferenceError cuando JavaScript no puede encontrar una referencia a un valor al que estás intentando acceder. + +

+
+ +--- + From 9823224de479b59960c0569465ec117389ddecfe Mon Sep 17 00:00:00 2001 From: Jonas Talavera Date: Wed, 23 Oct 2019 21:38:30 +0200 Subject: [PATCH 359/915] =?UTF-8?q?Translate=20question=20=C2=A1100!?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- es-ES/README-ES.md | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/es-ES/README-ES.md b/es-ES/README-ES.md index ca379aba..96dd3f21 100644 --- a/es-ES/README-ES.md +++ b/es-ES/README-ES.md @@ -3167,3 +3167,31 @@ Se lanzan errores del tipo ReferenceError cuando JavaScript no puede encontrar u --- +###### 100. ¿Cuál es el valor de la salida? + +```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` + +
Solución +

+ +#### Answer: B + +`[]` es un valor verdadero (se convierte a un valor verdadero en un contexto booleano). Con el operador `&&`, se devolverá el valor de la derecha si el valor de la izquierda es un valor verdadero. En este caso, el valor de la izquierda `[]` es un valor verdadero, por lo tanto se devuelve `"Im'`. + +`""` es un valor falso (se convierte a un valor falso en un contexto booleano). Si el valor de la izquierda es falso, no se devuelve nada. `n't` no se devuelve. + +

+
+ +--- + From 8eefd61e9954d34bf4e2c76587caa8cc4dbd1c22 Mon Sep 17 00:00:00 2001 From: Jonas Talavera Date: Wed, 23 Oct 2019 21:48:03 +0200 Subject: [PATCH 360/915] Translate question 101 --- es-ES/README-ES.md | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) diff --git a/es-ES/README-ES.md b/es-ES/README-ES.md index 96dd3f21..f81991d3 100644 --- a/es-ES/README-ES.md +++ b/es-ES/README-ES.md @@ -3195,3 +3195,36 @@ 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) + +console.log(one, two, three) +``` + +- A: `false` `null` `[]` +- B: `null` `""` `true` +- C: `{}` `""` `[]` +- D: `null` `null` `true` + +
Solución +

+ +#### Answer: C + +Con el operador `||`, podemos devolver el primer operando verdadero. Si todos los valores son falsos, se devuelve el último operando. + +`(false || {} || null)`: el objecto vacío `{}` es un valor verdadero. Este es el primero (y único) valor verdadero, que se devuelve. `one` es igual a `{}`. + +`(null || false || "")`: todos los operandos son valores falsos. Esto significa que el último operando, `""` es devuelto. `two` es igual a `""`. + +`([] || 0 || "")`: el array vacío `[]` es un valor verdadero. Este es el primer valor verdadero, que se devuelve. `three` es igual a `[]`. + +

+
+ +--- + From 80c97ed8ba2b82b0dc288d2ec5caf4bd7e0c3e1f Mon Sep 17 00:00:00 2001 From: Jonas Talavera Date: Wed, 23 Oct 2019 22:46:16 +0200 Subject: [PATCH 361/915] Translate question 102 --- es-ES/README-ES.md | 43 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 43 insertions(+) diff --git a/es-ES/README-ES.md b/es-ES/README-ES.md index f81991d3..4e3f9dd4 100644 --- a/es-ES/README-ES.md +++ b/es-ES/README-ES.md @@ -3228,3 +3228,46 @@ 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!') + +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` y `I have resolved!`, `second` +- B: `second`, `I have resolved!` y `second`, `I have resolved!` +- C: `I have resolved!`, `second` y `second`, `I have resolved!` +- D: `second`, `I have resolved!` y `I have resolved!`, `second` + +
Solución +

+ +#### Answer: D + +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. + +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. + +

+
+ +--- From b99d47746732ff030fc17b6d5a23c63b75b448de Mon Sep 17 00:00:00 2001 From: Jonas Talavera Date: Wed, 23 Oct 2019 22:55:32 +0200 Subject: [PATCH 362/915] Translate question 103 --- es-ES/README-ES.md | 38 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) diff --git a/es-ES/README-ES.md b/es-ES/README-ES.md index 4e3f9dd4..1d35aab1 100644 --- a/es-ES/README-ES.md +++ b/es-ES/README-ES.md @@ -3271,3 +3271,41 @@ 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() + +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` + +
Solución +

+ +#### 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 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"`. + +`{ 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"`. + +

+
+ +--- + From 2dc566ae00d356000591f897c2ffb8427cb10a66 Mon Sep 17 00:00:00 2001 From: Jonas Talavera Date: Wed, 23 Oct 2019 23:01:59 +0200 Subject: [PATCH 363/915] Translate question 104 --- es-ES/README-ES.md | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/es-ES/README-ES.md b/es-ES/README-ES.md index 1d35aab1..b2616ff8 100644 --- a/es-ES/README-ES.md +++ b/es-ES/README-ES.md @@ -3309,3 +3309,28 @@ 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) +``` + +- A: `5` +- B: `Promise {: 5}` +- C: `Promise {: 5}` +- D: `Error` + +
Solución +

+ +#### Answer: C + +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`. + +

+
+ +--- + From 63878afcb140902baa011e44ca66a6c2b30a2bdb Mon Sep 17 00:00:00 2001 From: Jonas Talavera Date: Wed, 23 Oct 2019 23:07:48 +0200 Subject: [PATCH 364/915] Translate question 105 --- es-ES/README-ES.md | 39 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) diff --git a/es-ES/README-ES.md b/es-ES/README-ES.md index b2616ff8..0710a31d 100644 --- a/es-ES/README-ES.md +++ b/es-ES/README-ES.md @@ -3334,3 +3334,42 @@ En este caso, acabamos de pasar el valor numérico `5`. Devuelve una promesa res --- +###### 105. ¿Cuál es el valor? + +```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` + +
Solución +

+ +#### Answer: B + +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!`. + +

+
+ +--- + From c2652043097f2c04f033ed5a650ae40eb3ffecf5 Mon Sep 17 00:00:00 2001 From: lazy <310195875@qq.com> Date: Thu, 24 Oct 2019 22:36:13 +0800 Subject: [PATCH 365/915] update zh-CN: translate question 102-111 --- zh-CN/README-zh_CN.md | 342 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 342 insertions(+) diff --git a/zh-CN/README-zh_CN.md b/zh-CN/README-zh_CN.md index 0951e51c..b24f6131 100644 --- a/zh-CN/README-zh_CN.md +++ b/zh-CN/README-zh_CN.md @@ -3225,3 +3225,345 @@ console.log(one, two, 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`被解决之后,下一行`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]”`。 + +

+
+ +--- + +###### 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` + +

+
+ +--- + +###### 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`的值传递。 + +这意味着两个值都引用内存中的同一位置,因此它们是相等的。 + +

+
+ +--- + +###### 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]`访问第一个元素的值。我们无法对`undefined`执行此操作,因此会抛出`TypeError`: `Cannot read property '1' of undefined` + +当我们使用方括号表示法时,JavaScript会看到第一个左方括号`[`,并且一直走到找到右方括号`]`。只有这样,它才会解析该语句。如果我们使用了`colorConfig[colors[1]]`,它将返回`colorConfig`对象上`red`属性的值。 + +

+
+ +--- + +###### 107. 输出什么? + +```javascript +console.log('❤️' === '❤️') +``` + +- A: `true` +- B: `false` + +
答案 +

+ +#### 答案: A + +在内部,表情符号是unicode。 心表情符号的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 +``` + +

+
From c4858134d1b1cd4a49e7da89c230977b58cc9b33 Mon Sep 17 00:00:00 2001 From: Jonas Talavera Date: Thu, 24 Oct 2019 19:09:22 +0200 Subject: [PATCH 366/915] Translate question 106 --- es-ES/README-ES.md | 37 +++++++++++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) diff --git a/es-ES/README-ES.md b/es-ES/README-ES.md index 0710a31d..5e70a9f5 100644 --- a/es-ES/README-ES.md +++ b/es-ES/README-ES.md @@ -3373,3 +3373,40 @@ El bloque de código en la instrucción `else` se ejecuta, y se imprime `They ar --- +###### 106. ¿Cuál es el valor? + +```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` + +
Solución +

+ +#### 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"]`). + +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`. + +

+
+ +--- + From 78649b81be9b0fe0fb95a880c16b3d3ce3bcd6e8 Mon Sep 17 00:00:00 2001 From: Jonas Talavera Date: Thu, 24 Oct 2019 19:13:31 +0200 Subject: [PATCH 367/915] Translate question 107 --- es-ES/README-ES.md | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/es-ES/README-ES.md b/es-ES/README-ES.md index 5e70a9f5..c960c6f3 100644 --- a/es-ES/README-ES.md +++ b/es-ES/README-ES.md @@ -3410,3 +3410,24 @@ JavaScript interpreta (o descompone) las sentencias. Cuando usamos la notación --- +###### 107. ¿Cuál es el valor? + +```javascript +console.log('❤️' === '❤️') +``` + +- A: `true` +- B: `false` + +
Solución +

+ +#### 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. + +

+
+ +--- + From 614824fd5e6a2f0a0195e11e5e212a37c59ec7c8 Mon Sep 17 00:00:00 2001 From: Jonas Talavera Date: Thu, 24 Oct 2019 19:23:17 +0200 Subject: [PATCH 368/915] Translate question 108 --- es-ES/README-ES.md | 32 ++++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) diff --git a/es-ES/README-ES.md b/es-ES/README-ES.md index c960c6f3..47dd3098 100644 --- a/es-ES/README-ES.md +++ b/es-ES/README-ES.md @@ -3431,3 +3431,35 @@ 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 = ['✨', '🥑', '😍'] + +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` + +
Solución +

+ +#### 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. + +`map`, `filter` y `slice` devuelven un nuevo array, `find` devuelve un elemento, y `reduce` devuelve un valor reducido. + +

+
+ +--- + From e8dc2f52ac2a52d4e561b1a6cf1f8c5c7710b562 Mon Sep 17 00:00:00 2001 From: Jonas Talavera Date: Thu, 24 Oct 2019 19:34:59 +0200 Subject: [PATCH 369/915] Translate question 109 --- es-ES/README-ES.md | 32 ++++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) diff --git a/es-ES/README-ES.md b/es-ES/README-ES.md index 47dd3098..68f918a0 100644 --- a/es-ES/README-ES.md +++ b/es-ES/README-ES.md @@ -3463,3 +3463,35 @@ 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] } + +info.favoriteFood = '🍝' + +console.log(food) +``` + +- A: `['🍕', '🍫', '🥑', '🍔']` +- B: `['🍝', '🍫', '🥑', '🍔']` +- C: `['🍝', '🍕', '🍫', '🥑', '🍔']` +- D: `ReferenceError` + +
Solución +

+ +#### 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 + +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) + +Luego, cambiamos el valor de la propiedad `favoriteFood` en el objeto` info`. El array `food` no cambia, ya que el valor de `favoriteFood` era simplemente una _copia_ del valor del primer elemento del array, y no tiene una referencia al mismo punto en la memoria que el elemento en `food[0]`. Cuando imprimimos food, éste sigue siendo el array original, `['🍕', '🍫', '🥑', '🍔']`. + +

+
+ +--- + From de0b22dd663f42bba83675006cbd737b224d26f4 Mon Sep 17 00:00:00 2001 From: Jonas Talavera Date: Thu, 24 Oct 2019 19:56:06 +0200 Subject: [PATCH 370/915] Translate question 110 --- es-ES/README-ES.md | 37 +++++++++++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) diff --git a/es-ES/README-ES.md b/es-ES/README-ES.md index 68f918a0..1b77aad3 100644 --- a/es-ES/README-ES.md +++ b/es-ES/README-ES.md @@ -3495,3 +3495,40 @@ Luego, cambiamos el valor de la propiedad `favoriteFood` en el objeto` info`. El --- +###### 110. ¿Qué hace este método? + +```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 + +
Solución +

+ +#### Answer: A + +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 + +// 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' } +``` + +

+
+ +--- + From d8e92d2200b870cfe1be5d346cd155e346f46e5b Mon Sep 17 00:00:00 2001 From: Jonas Talavera Date: Thu, 24 Oct 2019 20:07:55 +0200 Subject: [PATCH 371/915] Translate question 111 --- es-ES/README-ES.md | 44 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 44 insertions(+) diff --git a/es-ES/README-ES.md b/es-ES/README-ES.md index 1b77aad3..b94bc911 100644 --- a/es-ES/README-ES.md +++ b/es-ES/README-ES.md @@ -3532,3 +3532,47 @@ JSON.parse(jsonArray) // { name: 'Lydia' } --- +###### 111. ¿Cuál es el resultado? + +```javascript +let name = 'Lydia' + +function getName() { + console.log(name) + let name = 'Sarah' +} + +getName() +``` + +- A: Lydia +- B: Sarah +- C: `undefined` +- D: `ReferenceError` + +
Solución +

+ +#### 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'`. + +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`. + +```javascript +let name = 'Lydia' + +function getName() { + console.log(name) +} + +getName() // Lydia +``` + +

+
+ +--- + From 264fa608c33ba4502f048164d75b3d52bafbe52f Mon Sep 17 00:00:00 2001 From: Jonas Talavera Date: Thu, 24 Oct 2019 20:15:48 +0200 Subject: [PATCH 372/915] Translate question 112 --- es-ES/README-ES.md | 51 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 51 insertions(+) diff --git a/es-ES/README-ES.md b/es-ES/README-ES.md index b94bc911..4367e01c 100644 --- a/es-ES/README-ES.md +++ b/es-ES/README-ES.md @@ -3576,3 +3576,54 @@ getName() // Lydia --- +###### 112. ¿Cuál es el resultado? + +```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` y `a` +- B: `a` y `undefined` +- C: `['a', 'b', 'c']` y `a` +- D: `a` y `['a', 'b', 'c']` + +
Solución +

+ +#### Answer: C + +Con la palabra clave `yield`, cedemos valores en una función generadora. Con la palabra clave `yield*`, podemos obtener valores de otra función generadora u objeto iterable (por ejemplo, un array). + +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 +``` + +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 +``` + +

+
+ +--- + From 7f91e31786500dbb61c55f2174910f19c2e67610 Mon Sep 17 00:00:00 2001 From: Jonas Talavera Date: Thu, 24 Oct 2019 20:20:50 +0200 Subject: [PATCH 373/915] Translate question 113 --- es-ES/README-ES.md | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/es-ES/README-ES.md b/es-ES/README-ES.md index 4367e01c..fb63acb7 100644 --- a/es-ES/README-ES.md +++ b/es-ES/README-ES.md @@ -3627,3 +3627,26 @@ console.log(two.next().value) // undefined --- +###### 113. ¿Cuál es el resultado? + +```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` + +
Solución +

+ +#### 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`. + +

+
+ +--- + From 06fd922c58cd2c14e8fa0aedcfe483ec9539a932 Mon Sep 17 00:00:00 2001 From: Jonas Talavera Date: Thu, 24 Oct 2019 20:30:01 +0200 Subject: [PATCH 374/915] Translate question 114 --- es-ES/README-ES.md | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) diff --git a/es-ES/README-ES.md b/es-ES/README-ES.md index fb63acb7..f0ac3c6d 100644 --- a/es-ES/README-ES.md +++ b/es-ES/README-ES.md @@ -3650,3 +3650,32 @@ Las expresiones dentro de las plantillas de cadena de texto se evalúan primero. --- +###### 114. ¿Qué ocurrirá? + +```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` + +
Solución +

+ +#### Answer: C + +Normalmente, cuando establecemos objetos iguales a `null`, esos objetos se recogen por el _recolector de basura_ ya que ya no hay ninguna referencia a ese objeto. Sin embargo, dado que la función de devolución de llamada dentro de `setInterval` es una función flecha (por lo tanto vinculada al objeto` config`), la función de devolución de llamada todavía tiene una referencia al objeto `config`. Mientras haya una referencia, el objeto no será recolectado. Como no es recolectado, la función de devolución de llamada `setInterval` aún se invocará cada 1000ms (1s). + +

+
+ +--- + From 2080004b3c0e45c42975ef7feb4981d6e32c4d04 Mon Sep 17 00:00:00 2001 From: Jonas Talavera Date: Thu, 24 Oct 2019 20:37:35 +0200 Subject: [PATCH 375/915] Translate question 115 --- es-ES/README-ES.md | 36 ++++++++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) diff --git a/es-ES/README-ES.md b/es-ES/README-ES.md index f0ac3c6d..0d622326 100644 --- a/es-ES/README-ES.md +++ b/es-ES/README-ES.md @@ -3679,3 +3679,39 @@ 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' + +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 + +
Solución +

+ +#### 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!' }`. + +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. + +

+
+ +--- + From d9a9d657a2bc24983bde9500f38fff002b48269b Mon Sep 17 00:00:00 2001 From: Jonas Talavera Date: Thu, 24 Oct 2019 20:45:08 +0200 Subject: [PATCH 376/915] Translate question 116 --- es-ES/README-ES.md | 38 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) diff --git a/es-ES/README-ES.md b/es-ES/README-ES.md index 0d622326..5da7f0a0 100644 --- a/es-ES/README-ES.md +++ b/es-ES/README-ES.md @@ -3715,3 +3715,41 @@ Al agregar un par clave/valor utilizando el método `set`, la clave será el val --- +###### 116. ¿Cuál es el resultado? + +```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}` + +
Solución +

+ +#### 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`. + +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}`. + +Luego, invocamos la función `changeAgeAndName`, sin embargo, no pasamos un parámetro. En cambio, el valor de `x` es igual a un _nuevo_ objeto: `{ ...person }`. Dado que es un objeto nuevo, no afecta los valores de las propiedades en el objeto `person`. `person` sigue siendo igual a `{ name: "Lydia",age: 22 }`. + +

+
From d4b4de4df0dadfcda2a1ce2dd7af63d737d922b2 Mon Sep 17 00:00:00 2001 From: danahkim Date: Fri, 25 Oct 2019 09:56:41 +0900 Subject: [PATCH 377/915] Add translate the questions 109-116 to Korean. --- ko-KR/README-ko_KR.md | 301 +++++++++++++++++++++++++++++++++++++++++- 1 file changed, 297 insertions(+), 4 deletions(-) diff --git a/ko-KR/README-ko_KR.md b/ko-KR/README-ko_KR.md index f9d8e4d5..c9d342b7 100644 --- a/ko-KR/README-ko_KR.md +++ b/ko-KR/README-ko_KR.md @@ -2,7 +2,7 @@ JavaScript 에 관한 객관식 문제를 [Instagram](https://www.instagram.com/theavocoder)에 매일 게시하고 있어요, 물론 여기에도 게시할 거예요! -초급부터 고급까지: JavaScript를 얼마나 잘 알고 있는지 테스트하거나, 지식을 조금 더 새롭게 하거나, 코딩 면접을 준비하세요! :muscle: :rocket: 이 기록을 매주 새로운 질문으로 업데이트해요. 마지막 업데이트: 9월 27일 +초급부터 고급까지: JavaScript를 얼마나 잘 알고 있는지 테스트하거나, 지식을 조금 더 새롭게 하거나, 코딩 면접을 준비하세요! :muscle: :rocket: 이 기록을 매주 새로운 질문으로 업데이트해요. 마지막 업데이트: 10월 09일 정답은 질문 아래 접힌 부분에 있고, 간단히 클릭하면 펼칠 수 있어요. 행운을 빌어요 :heart: @@ -2987,7 +2987,7 @@ The above example works. This returns the array `[ 'banana', 'apple', 'orange', --- -###### 95. 무엇이 출력 될까요? +###### 95. 무엇이 출력 될까요? ```javascript function nums(a, b) { @@ -3228,7 +3228,7 @@ console.log(one, two, three) --- -###### 102. 무엇이 출력 될까요? +###### 102. 무엇이 출력 될까요? ```javascript const myPromise = () => Promise.resolve('I have resolved!') @@ -3403,7 +3403,7 @@ JavaScript에서, 객체의 속성에 접근하는 2가지 방법을 가지고 점 표기법에서, 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` 의 값이 리턴될 거에요.

@@ -3460,3 +3460,296 @@ emojis.splice(1, 2, '✨')

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

+
+ +--- + +###### 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 값으로 생성해요. +With the `JSON.parse()` method, we can parse JSON string to a JavaScript value. + +```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`이 포함되어 있는지 살펴봐요: `let` 키워드와 함께 선언 했기 때문에 `'Sarah'`의 값을 가져요. + +`let` 키워드 (그리고 `const`)를 사용한 변수는 끌어올려지지만, `var`와 다르게 초기화 되지는 않아요. 그들을 선언 (초기화) 하는 줄 전에 접근 할 수 없어요. "일시적 사각지대"라고 불려요. 그들을 선언하기 전에 접근하려고 한다면, JavaScript는 `ReferenceError`를 던져요. + +`getName` 함수 안에 `name` 변수를 선언하지 않았다면, javaScript 엔진은 _스코프 체인_ 을 내려다 보지 않았을 거예요. 외부 범위에 `Lydia`의 값을 가진 `name` 변수가 있어요. 이 경우엔 `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` 그리고 `a` +- B: `a` 그리고 `undefined` +- C: `['a', 'b', 'c']` 그리고 `a` +- D: `a` 그리고 `['a', 'b', 'c']` + +
정답 +

+ +#### 정답: C + +`yield` 키워드를 사용하면, 제너레이터 함수 안의 값을 `중단` 했어요. `yield`키워드를 사용하면, 다른 제너레이터 함수 또는 반복 가능한 객체(예를들면 배열)의 값을 중단 시킬 수 있어요. + +`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`를 리턴해요. + +```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`로 설정했을때, 객체는 더 이상의 객체 참조가 없어 _쓰레기 수집_ 되어요. 그러나, `setInterval`을 가진 콜백 함수는 화살표 함수 (`config` 객체로 감싸진) 이기 때문에, 콜백 함수는 여전히 `config` 객체의 참조를 갖고 있고, 객체는 쓰레기 수집 되지 않아요. 쓰레기 수집 되지 않았기 때문에, `setInterval` 콜백 함수는 여전히 매 1000ms (1s) 마다 호출 돼요, + +

+
+ +--- + +###### 115. 어느 method가 값 `'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 그리고 3 +- D: 모두 + +
정답 +

+ +#### 정답: B + +`set` 메소드를 사용해서 키/값을 쌍으로 추가할 때, 키는 `set`함수로 전달 된 첫 번째 인수의 값이 되고, 값은 `set`함수로 전달된 두 번째 인수의 값이 될거에요. 이 경우에선 키는 _함수_ `() => '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` 객체의 모든 키/값의 복사본을 가지고 있어요. + +첫번째로, `changeAge`함수를 호출 했고, 그것의 인수로 `person` 객체를 전달 했어요. 이 함수는 `age`속성의 값을 1 증가 시켜요. `person`은 이제 `{ name: "Lydia", age: 22 }`이에요. + +그리고나서, `changeAgeAndName` 함수를 호출 했지만, 파라미터를 전달하지 않았어요. 대신에, `x`의 값은 _새로운_ 객체와 같아요: `{ ...person }`. 새로운 객체이기 때문에, `person`객체의 속성들의 값에 영향을 주지 않아요. `person`은 여전히 `{ name: "Lydia", age: 22 }`와 같아요. + +

+
\ No newline at end of file From 031ea4efc4b9b43a21218155bd9c2a6cd80a9ba7 Mon Sep 17 00:00:00 2001 From: Lydia Hallie Date: Mon, 18 Nov 2019 16:55:57 -0800 Subject: [PATCH 378/915] Add 117-131 --- README.md | 425 +++++++++++++++++++++++++++++++++++++++++++++++- en-EN/README.md | 423 +++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 847 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 989743d7..2b496620 100644 --- a/README.md +++ b/README.md @@ -3750,4 +3750,427 @@ First, we invoke the `changeAge` function and pass the `person` object as its ar 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 }`.

- \ No newline at end of file + + +###### 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])` + +
Answer +

+ +#### Answer: 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. What's the output? + +```javascript +let num = 1; +const list = ["🥳", "🤠", "🥰", "🤪"]; + +console.log(list[(num += 1)]); +``` + +- A: `🤠` +- B: `🥰` +- C: `SyntaxError` +- D: `ReferenceError` + +
Answer +

+ +#### 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 🥰. + +

+
+ +###### 119. What's the 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` `undefined` +- C: `Mara` `null` `Lydia Hallie` `null` +- D: `null` `ReferenceError` `null` `ReferenceError` + +
Answer +

+ +#### Answer: 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?.()`: `member` is not defined: `member.getLastName()` is nullish. The expression returns `undefined`. + +

+
+ +###### 120. What's the 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` + +
Answer +

+ +#### Answer: 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. What's the 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` + +
Answer +

+ +#### Answer: 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. What's the 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` + +
Answer +

+ +#### Answer: 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. What's the 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` + +
Answer +

+ +#### Answer: 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. What's the 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` + +
Answer +

+ +#### 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`. + +

+
+ +###### 125. What's the 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` + +
Answer +

+ +#### Answer: 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. What's the 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 + +
Answer +

+ +#### Answer: 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 `currentcy` in `USD` results in `$300.00`. + +

+
+ +###### 127. What's the output? + +```javascript +const spookyItems = ["👻", "🎃", "🕸"]; +({ item: spookyItems[3] } = { item: "💀" }); + +console.log(spookyItems); +``` + +- A: `["👻", "🎃", "🕸"]` +- B: `["👻", "🎃", "🕸", "💀"]` +- C: `["👻", "🎃", "🕸", { item: "💀" }]` +- D: `["👻", "🎃", "🕸", "[Object object]"]` + +
Answer +

+ +#### Answer: 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. What's the 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` + +
Answer +

+ +#### Answer: 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. What's the output? + +```javascript +const randomValue = 21; + +function getInfo() { + console.log(typeof randomValue); + const randomValue = "Lydia Hallie"; +} + +getInfo(); +``` + +- A: `"number"` +- B: `"string"` +- C: `undefined` +- D: `ReferenceError` + +
Answer +

+ +#### 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. + +

+
+ +###### 130. What's the 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!` + +
Answer +

+ +#### Answer: 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. What's the output? + +```javascript +const emojis = ["🥑", ["✨", "✨", ["🍕", "🍕"]]]; + +console.log(emojis.flat(1)); +``` + +- A: `['🥑', ['✨', '✨', ['🍕', '🍕']]]` +- B: `['🥑', '✨', '✨', ['🍕', '🍕']]` +- C: `['🥑', ['✨', '✨', '🍕', '🍕']]` +- D: `['🥑', '✨', '✨', '🍕', '🍕']` + +
Answer +

+ +#### Answer: 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 `['🥑', '✨', '✨', ['🍕', '🍕']]`. + +

+
diff --git a/en-EN/README.md b/en-EN/README.md index cecdbd86..d69d963f 100644 --- a/en-EN/README.md +++ b/en-EN/README.md @@ -3749,5 +3749,428 @@ First, we invoke the `changeAge` function and pass the `person` object as its ar 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])` + +
Answer +

+ +#### Answer: 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. What's the output? + +```javascript +let num = 1; +const list = ["🥳", "🤠", "🥰", "🤪"]; + +console.log(list[(num += 1)]); +``` + +- A: `🤠` +- B: `🥰` +- C: `SyntaxError` +- D: `ReferenceError` + +
Answer +

+ +#### 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 🥰. + +

+
+ +###### 119. What's the 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` `undefined` +- C: `Mara` `null` `Lydia Hallie` `null` +- D: `null` `ReferenceError` `null` `ReferenceError` + +
Answer +

+ +#### Answer: 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?.()`: `member` is not defined: `member.getLastName()` is nullish. The expression returns `undefined`. + +

+
+ +###### 120. What's the 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` + +
Answer +

+ +#### Answer: 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. What's the 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` + +
Answer +

+ +#### Answer: 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. What's the 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` + +
Answer +

+ +#### Answer: 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. What's the 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` + +
Answer +

+ +#### Answer: 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. What's the 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` + +
Answer +

+ +#### 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`. + +

+
+ +###### 125. What's the 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` + +
Answer +

+ +#### Answer: 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. What's the 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 + +
Answer +

+ +#### Answer: 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 `currentcy` in `USD` results in `$300.00`. + +

+
+ +###### 127. What's the output? + +```javascript +const spookyItems = ["👻", "🎃", "🕸"]; +({ item: spookyItems[3] } = { item: "💀" }); + +console.log(spookyItems); +``` + +- A: `["👻", "🎃", "🕸"]` +- B: `["👻", "🎃", "🕸", "💀"]` +- C: `["👻", "🎃", "🕸", { item: "💀" }]` +- D: `["👻", "🎃", "🕸", "[Object object]"]` + +
Answer +

+ +#### Answer: 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. What's the 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` + +
Answer +

+ +#### Answer: 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. What's the output? + +```javascript +const randomValue = 21; + +function getInfo() { + console.log(typeof randomValue); + const randomValue = "Lydia Hallie"; +} + +getInfo(); +``` + +- A: `"number"` +- B: `"string"` +- C: `undefined` +- D: `ReferenceError` + +
Answer +

+ +#### 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. + +

+
+ +###### 130. What's the 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!` + +
Answer +

+ +#### Answer: 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. What's the output? + +```javascript +const emojis = ["🥑", ["✨", "✨", ["🍕", "🍕"]]]; + +console.log(emojis.flat(1)); +``` + +- A: `['🥑', ['✨', '✨', ['🍕', '🍕']]]` +- B: `['🥑', '✨', '✨', ['🍕', '🍕']]` +- C: `['🥑', ['✨', '✨', '🍕', '🍕']]` +- D: `['🥑', '✨', '✨', '🍕', '🍕']` + +
Answer +

+ +#### Answer: 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 `['🥑', '✨', '✨', ['🍕', '🍕']]`. +

\ No newline at end of file From 7c62b15f578264eea447cce184cc21efd1870190 Mon Sep 17 00:00:00 2001 From: Lydia Hallie Date: Mon, 18 Nov 2019 17:02:33 -0800 Subject: [PATCH 379/915] Fix updated date --- README.md | 4 ++-- en-EN/README.md | 6 +++--- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/README.md b/README.md index 2b496620..14926d28 100644 --- a/README.md +++ b/README.md @@ -2,7 +2,7 @@ I post daily multiple choice JavaScript questions on my [Instagram](https://www.instagram.com/theavocoder), which I'll also post 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 weekly with new questions. Last update: October 9th +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 weekly with new questions. Last update: November 18th The answers are in the collapsed sections below the questions, simply click on them to expand it. Good luck :heart: @@ -3752,7 +3752,7 @@ Then, we invoke the `changeAgeAndName` function, however we don't pass a paramet

-###### 117. Which of the following options will return `6`? +###### 117. Which of the following options will return `6`? ```javascript function sumValues(x, y, z) { diff --git a/en-EN/README.md b/en-EN/README.md index d69d963f..b35a8516 100644 --- a/en-EN/README.md +++ b/en-EN/README.md @@ -2,7 +2,7 @@ I post daily multiple choice JavaScript questions on my [Instagram](https://www.instagram.com/theavocoder), which I'll also post 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 weekly with new questions. Last update: October 9th +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 weekly with new questions. Last update: November 18th The answers are in the collapsed sections below the questions, simply click on them to expand it. Good luck :heart: @@ -3461,7 +3461,7 @@ With `splice` method, we modify the original array by deleting, replacing or add --- -###### 109. What's the output? +###### 109. What's the output? ```javascript const food = ['🍕', '🍫', '🥑', '🍔'] @@ -3752,7 +3752,7 @@ Then, we invoke the `changeAgeAndName` function, however we don't pass a paramet

-###### 117. Which of the following options will return `6`? +###### 117. Which of the following options will return `6`? ```javascript function sumValues(x, y, z) { From d15dc7d4610b44f814f35e465f27f637a9bbec01 Mon Sep 17 00:00:00 2001 From: Lydia Hallie Date: Mon, 18 Nov 2019 17:46:18 -0800 Subject: [PATCH 380/915] Rephrase question 33 --- README.md | 6 +++--- en-EN/README.md | 6 +++--- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/README.md b/README.md index 14926d28..18f7373e 100644 --- a/README.md +++ b/README.md @@ -1003,11 +1003,11 @@ If we click `p`, we see two logs: `p` and `div`. During event propagation, there const person = { name: "Lydia" }; function sayHi(age) { - console.log(`${this.name} is ${age}`); + return `${this.name} is ${age}`; } -sayHi.call(person, 21); -sayHi.bind(person, 21); +console.log(sayHi.call(person, 21)); +console.log(sayHi.bind(person, 21)); ``` - A: `undefined is 21` `Lydia is 21` diff --git a/en-EN/README.md b/en-EN/README.md index b35a8516..da1e6733 100644 --- a/en-EN/README.md +++ b/en-EN/README.md @@ -1003,11 +1003,11 @@ If we click `p`, we see two logs: `p` and `div`. During event propagation, there const person = { name: "Lydia" }; function sayHi(age) { - console.log(`${this.name} is ${age}`); + return `${this.name} is ${age}`; } -sayHi.call(person, 21); -sayHi.bind(person, 21); +console.log(sayHi.call(person, 21)); +console.log(sayHi.bind(person, 21)); ``` - A: `undefined is 21` `Lydia is 21` From 2c6f0536aac9c3035a1b9faef71edc58a81289c3 Mon Sep 17 00:00:00 2001 From: Lydia Hallie Date: Mon, 18 Nov 2019 17:53:41 -0800 Subject: [PATCH 381/915] Add break lines --- README.md | 32 +++++++++++++++++++++++++++++++- en-EN/README.md | 32 +++++++++++++++++++++++++++++++- 2 files changed, 62 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 18f7373e..d766b910 100644 --- a/README.md +++ b/README.md @@ -3752,6 +3752,8 @@ Then, we invoke the `changeAgeAndName` function, however we don't pass a paramet

+--- + ###### 117. Which of the following options will return `6`? ```javascript @@ -3775,6 +3777,8 @@ With the spread operator `...`, we can _spread_ iterables to individual elements

+--- + ###### 118. What's the output? ```javascript @@ -3799,6 +3803,8 @@ With the `+=` operand, we're incrementing the value of `num` by `1`. `num` had t

+--- + ###### 119. What's the output? ```javascript @@ -3840,6 +3846,8 @@ With the optional chaining operator `?.`, we no longer have to explicitly check

+--- + ###### 120. What's the output? ```javascript @@ -3867,6 +3875,8 @@ We passed the condition `groceries.indexOf("banana")` to the if-statement. `groc

+--- + ###### 121. What's the output? ```javascript @@ -3895,6 +3905,8 @@ The `language` method is a `setter`. Setters don't hold an actual value, their p

+--- + ###### 122. What's the output? ```javascript @@ -3921,6 +3933,8 @@ console.log(!typeof name === "string");

+--- + ###### 123. What's the output? ```javascript @@ -3947,6 +3961,8 @@ The `add` function returns an arrow function, which returns an arrow function, w

+--- + ###### 124. What's the output? ```javascript @@ -3979,6 +3995,8 @@ The generator function `range` returns an async object with promises for each it

+--- + ###### 125. What's the output? ```javascript @@ -4004,6 +4022,8 @@ myFunc(1, 2, 3);

+--- + ###### 126. What's the output? ```javascript @@ -4039,6 +4059,8 @@ With the `Intl.NumberFormat` method, we can format numeric values to any locale.

+--- + ###### 127. What's the output? ```javascript @@ -4051,7 +4073,7 @@ console.log(spookyItems); - A: `["👻", "🎃", "🕸"]` - B: `["👻", "🎃", "🕸", "💀"]` - C: `["👻", "🎃", "🕸", { item: "💀" }]` -- D: `["👻", "🎃", "🕸", "[Object object]"]` +- D: `["👻", "🎃", "🕸", "[object Object]"]`
Answer

@@ -4063,6 +4085,8 @@ By destructuring objects, we can unpack values from the right-hand object, and a

+--- + ###### 128. What's the output? ```javascript @@ -4093,6 +4117,8 @@ With the `isNaN` method, you can check if the value you pass is not a number. `n

+--- + ###### 129. What's the output? ```javascript @@ -4121,6 +4147,8 @@ Variables declared with the `const` keyword are not referencable before their in

+--- + ###### 130. What's the output? ```javascript @@ -4152,6 +4180,8 @@ In the `try` block, we're logging the awaited value of the `myPromise` variable:

+--- + ###### 131. What's the output? ```javascript diff --git a/en-EN/README.md b/en-EN/README.md index da1e6733..14ba8cec 100644 --- a/en-EN/README.md +++ b/en-EN/README.md @@ -3752,6 +3752,8 @@ Then, we invoke the `changeAgeAndName` function, however we don't pass a paramet

+--- + ###### 117. Which of the following options will return `6`? ```javascript @@ -3775,6 +3777,8 @@ With the spread operator `...`, we can _spread_ iterables to individual elements

+--- + ###### 118. What's the output? ```javascript @@ -3799,6 +3803,8 @@ With the `+=` operand, we're incrementing the value of `num` by `1`. `num` had t

+--- + ###### 119. What's the output? ```javascript @@ -3840,6 +3846,8 @@ With the optional chaining operator `?.`, we no longer have to explicitly check

+--- + ###### 120. What's the output? ```javascript @@ -3867,6 +3875,8 @@ We passed the condition `groceries.indexOf("banana")` to the if-statement. `groc

+--- + ###### 121. What's the output? ```javascript @@ -3895,6 +3905,8 @@ The `language` method is a `setter`. Setters don't hold an actual value, their p

+--- + ###### 122. What's the output? ```javascript @@ -3921,6 +3933,8 @@ console.log(!typeof name === "string");

+--- + ###### 123. What's the output? ```javascript @@ -3947,6 +3961,8 @@ The `add` function returns an arrow function, which returns an arrow function, w

+--- + ###### 124. What's the output? ```javascript @@ -3979,6 +3995,8 @@ The generator function `range` returns an async object with promises for each it

+--- + ###### 125. What's the output? ```javascript @@ -4004,6 +4022,8 @@ myFunc(1, 2, 3);

+--- + ###### 126. What's the output? ```javascript @@ -4039,6 +4059,8 @@ With the `Intl.NumberFormat` method, we can format numeric values to any locale.

+--- + ###### 127. What's the output? ```javascript @@ -4051,7 +4073,7 @@ console.log(spookyItems); - A: `["👻", "🎃", "🕸"]` - B: `["👻", "🎃", "🕸", "💀"]` - C: `["👻", "🎃", "🕸", { item: "💀" }]` -- D: `["👻", "🎃", "🕸", "[Object object]"]` +- D: `["👻", "🎃", "🕸", "[object Object]"]`
Answer

@@ -4063,6 +4085,8 @@ By destructuring objects, we can unpack values from the right-hand object, and a

+--- + ###### 128. What's the output? ```javascript @@ -4093,6 +4117,8 @@ With the `isNaN` method, you can check if the value you pass is not a number. `n

+--- + ###### 129. What's the output? ```javascript @@ -4121,6 +4147,8 @@ Variables declared with the `const` keyword are not referencable before their in

+--- + ###### 130. What's the output? ```javascript @@ -4152,6 +4180,8 @@ In the `try` block, we're logging the awaited value of the `myPromise` variable:

+--- + ###### 131. What's the output? ```javascript From cb81b9d6346fef33a8d4704633eb1dfdf5a0a8df Mon Sep 17 00:00:00 2001 From: ViavaCos <13811092694@163.com> Date: Tue, 19 Nov 2019 22:54:21 +0800 Subject: [PATCH 382/915] fixed translation issue with fifth question --- zh-CN/README-zh_CN.md | 17 ++++++++--------- 1 file changed, 8 insertions(+), 9 deletions(-) diff --git a/zh-CN/README-zh_CN.md b/zh-CN/README-zh_CN.md index b24f6131..c6444319 100644 --- a/zh-CN/README-zh_CN.md +++ b/zh-CN/README-zh_CN.md @@ -132,7 +132,7 @@ shape.perimeter() --- -###### 5. 哪一个是无效的? +###### 5. 哪一个是正确的? ```javascript const bird = { @@ -145,10 +145,10 @@ const mouse = { } ``` -- A: `mouse.bird.size` -- B: `mouse[bird.size]` -- C: `mouse[bird["size"]]` -- D: All of them are valid +- A: `mouse.bird.size`是无效的 +- B: `mouse[bird.size]`是无效的 +- C: `mouse[bird["size"]]`是无效的 +- D: 以上三个选项都是有效的
答案

@@ -1352,7 +1352,6 @@ Promise.race([firstPromise, secondPromise]).then(res => console.log(res));

- --- ###### 46. 输出是什么? @@ -2014,7 +2013,7 @@ multiply(value); `reducer` 函数还有一个可选参数`initialValue`, 该参数将作为第一次调用回调函数时的第一个参数的值。如果没有提供`initialValue`,则将使用数组中的第一个元素。 在上述例子,`reduce`方法接收的第一个参数(Accumulator)是`x`, 第二个参数(Current Value)是`y`。 - + 在第一次调用时,累加器`x`为`1`,当前值`“y”`为`2`,打印出累加器和当前值:`1`和`2`。 例子中我们的回调函数没有返回任何值,只是打印累加器的值和当前值。如果函数没有返回值,则默认返回`undefined`。 在下一次调用时,累加器为`undefined`,当前值为“3”, 因此`undefined`和`3`被打印出。 @@ -2022,7 +2021,7 @@ multiply(value); 在第四次调用时,回调函数依然没有返回值。 累加器再次为 `undefined` ,当前值为“4”。 `undefined`和`4`被打印出。

- + --- ###### 66. 使用哪个构造函数可以成功继承`Dog`类? @@ -3120,7 +3119,7 @@ console.log(getUser(user)) `getList`函数接收一个数组作为其参数。 在`getList`函数的括号之间,我们立即解构这个数组。 您可以将其视为: `[x, ...y] = [1, 2, 3, 4]` - + 使用剩余的参数`... y`,我们将所有剩余参数放在一个数组中。 在这种情况下,其余的参数是`2`,`3`和`4`。 `y`的值是一个数组,包含所有其余参数。 在这种情况下,`x`的值等于`1`,所以当我们打印`[x,y]`时,会打印`[1,[2,3,4]]`。 From c85b88bdb164189b642b326f524e311ec93e25a4 Mon Sep 17 00:00:00 2001 From: Alex Ivanov Date: Wed, 27 Nov 2019 08:37:14 +0300 Subject: [PATCH 383/915] Russian updates 2019-11 1 Signed-off-by: Alex Ivanov --- ru-RU/README.md | 455 +++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 454 insertions(+), 1 deletion(-) diff --git a/ru-RU/README.md b/ru-RU/README.md index e709d4da..dfbebaad 100644 --- a/ru-RU/README.md +++ b/ru-RU/README.md @@ -2,7 +2,7 @@ Я ежедневно публикую вопросы по JavaScript с вариантами ответов в своем [Instagram](https://www.instagram.com/theavocoder), которые дублируются в этом репозитории. -От базового до продвинутого: проверьте, насколько хорошо вы знаете JavaScript, немного освежите свои знания или подготовьтесь к собеседованию! :muscle: :rocket: Я обновляю репозиторий еженедельно новыми вопросами. Последнее обновление: 9 октября. +От базового до продвинутого: проверьте, насколько хорошо вы знаете JavaScript, немного освежите свои знания или подготовьтесь к собеседованию! :muscle: :rocket: Я обновляю репозиторий еженедельно новыми вопросами. Последнее обновление: 18 ноября. Ответы находятся в свернутой секции ниже вопросов. Просто нажми на "Ответ", чтобы развернуть. Удачи! :heart: @@ -3751,3 +3751,456 @@ 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` принимает три аргумента:`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 + +С необязательным оператором связывания `?.` нам больше не нужно явно проверять, действительны ли более глубокие вложенные значения или нет. Если мы пытаемся получить доступ к свойству со (_нулевым_) значением `undefined` или `null`, выражение замыкается и возвращает `undefined`. + +`person.pet?.name`: `person` имеет свойство с именем `pet`: `person.pet` не нулевое. Оно имеет свойство с именем `name`, и возвращает `Mara`. +`person.pet?.family?.name`: `person` имеет свойство с именем `pet`: `person.pet` не нулевое. `pet` _не_ имеет свойство с именем `family`, `person.pet.family` нулевое. Выражение возвращает `undefined`. +`person.getFullName?.()`: `person` имеет свойство с именем `getFullName`: `person.getFullName()` не нулевое, и может быть вызвано, возвращает `Lydia Hallie`. +`member.getLastName?.()`: `member` не определено: `member.getLastName()` нулевое. Выражение возвращает `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`, что является ложным значением. Поскольку условие в операторе `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` возвращается `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"` является истинным значением, поэтому `!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` возвращает стрелочную функцию, которая возвращает стрелочную функцию, которая возвращает стрелочную функцию (все еще у тут?). Первая функция получает аргумент `x` со значением `4`. Мы вызываем вторую функцию, которая получает аргумент `y` со значением `5`. Затем мы вызываем третью функцию, которая получает аргумент `z` со значением `6`. Когда мы пытаемся получить доступ к значениям `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}`. Мы устанавливаем переменную `gen` равной асинхронному объекту, после чего зацикливаем ее, используя цикл `for await ... of`. Мы устанавливаем переменную `item` равной возвращаемым значениям `Promise`: сначала `Promise {1}`, затем `Promise {2}`, затем `Promise {3}`. Так как мы _ожидаем_ значение `item`, разрешается обещание, возвращаются разрешенные _значения_ обещания: `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` для локали `en-US` как `unit` в `mile-per-hour`, что приводит к `130 mph`. Числовое значение `300` для локали `en-US` в качестве `currentcy` в `USD` приводит к `$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` вы можете проверить, не является ли передаваемое вами значение числом. `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`: `"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` (которое нам не нужно, это значение по умолчанию), что означает, что будут объединены только массивы на первой глубине. `['🥑']` и `['✨', '✨', ['🍕', '🍕']]` в этом случае. Конкатенация этих двух массивов приводит к `['🥑', '✨', '✨', ['🍕', '🍕']]`. + +

+
From b284ffc21dbf677312237230d30aab320c9ef54a Mon Sep 17 00:00:00 2001 From: Alex Ivanov Date: Wed, 27 Nov 2019 08:46:28 +0300 Subject: [PATCH 384/915] Fix Q126 #279 --- README.md | 18 +++++++++--------- en-EN/README.md | 18 +++++++++--------- 2 files changed, 18 insertions(+), 18 deletions(-) diff --git a/README.md b/README.md index 7614b549..c206f113 100644 --- a/README.md +++ b/README.md @@ -4028,17 +4028,17 @@ myFunc(1, 2, 3); ```javascript function getFine(speed, amount) { - const formattedSpeed = new Intl.NumberFormat({ - 'en-US', - { style: 'unit', unit: 'mile-per-hour' } - }).format(speed) + 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) + const formattedAmount = new Intl.NumberFormat('en-US', { + style: 'currency', + currency: 'USD' + }).format(amount); - return `The driver drove ${formattedSpeed} and has to pay ${formattedAmount}` + return `The driver drove ${formattedSpeed} and has to pay ${formattedAmount}`; } console.log(getFine(130, 300)) diff --git a/en-EN/README.md b/en-EN/README.md index 1a71780e..95796231 100644 --- a/en-EN/README.md +++ b/en-EN/README.md @@ -4028,17 +4028,17 @@ myFunc(1, 2, 3); ```javascript function getFine(speed, amount) { - const formattedSpeed = new Intl.NumberFormat({ - 'en-US', - { style: 'unit', unit: 'mile-per-hour' } - }).format(speed) + 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) + const formattedAmount = new Intl.NumberFormat('en-US', { + style: 'currency', + currency: 'USD' + }).format(amount); - return `The driver drove ${formattedSpeed} and has to pay ${formattedAmount}` + return `The driver drove ${formattedSpeed} and has to pay ${formattedAmount}`; } console.log(getFine(130, 300)) From cc2a5eeaac5245273009cfa430a3958640cd3309 Mon Sep 17 00:00:00 2001 From: Alex Ivanov Date: Wed, 27 Nov 2019 09:12:50 +0300 Subject: [PATCH 385/915] Fix Q119 #278 --- README.md | 2 +- en-EN/README.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 7614b549..389b6135 100644 --- a/README.md +++ b/README.md @@ -3827,7 +3827,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` diff --git a/en-EN/README.md b/en-EN/README.md index 1a71780e..e3cbe3ae 100644 --- a/en-EN/README.md +++ b/en-EN/README.md @@ -3827,7 +3827,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` From b805d666fe61dff4a57d2b84d37868d693e41364 Mon Sep 17 00:00:00 2001 From: Jacob Herper Date: Wed, 27 Nov 2019 17:45:55 +0000 Subject: [PATCH 386/915] Questions 117-125 translated to German --- de-DE/README.md | 270 ++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 270 insertions(+) diff --git a/de-DE/README.md b/de-DE/README.md index b5e6ff78..024f4e46 100644 --- a/de-DE/README.md +++ b/de-DE/README.md @@ -3751,3 +3751,273 @@ Dann führen wir `changeAgeAndName` aus, allerdings ohne Parameter. Stattdessen

+ +--- + +###### 117. Welche der beiden Optionen wird `6` ausgeben? + +```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])` + +
Antwort +

+ +#### Antwort: C + +Mit dem Spread-Operator `...` können wir Werte _spreaden_ ("verstreichen"). Die `sumValues` Funktion erhält drei Argumente: `x`, `y` und `z`. `...[1, 2, 3]` ergibt `1, 2, 3`, was wir an `sumValues` übergeben. + +

+
+ +--- + +###### 118. Was ist der Output?? + +```javascript +let num = 1; +const list = ["🥳", "🤠", "🥰", "🤪"]; + +console.log(list[(num += 1)]); +``` + +- A: `🤠` +- B: `🥰` +- C: `SyntaxError` +- D: `ReferenceError` + +
Antwort +

+ +#### Antwort: B + +Mit dem`+=` Operanden erhöhen wir den Wert von `num` um `1`. `num` hatte den ursprünglichen Wert `1` und `1 + 1` ergibt `2`. Der Wert an zweiter Stelle im `list` Array ist 🥰. `console.log(list[2])` gibt 🥰 aus. + +

+
+ +--- + +###### 119. Was ist der 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` `undefined` +- C: `Mara` `null` `Lydia Hallie` `null` +- D: `null` `ReferenceError` `null` `ReferenceError` + +
Antwort +

+ +#### Antwort: B + +Mit den optionalen Kettenoperator `?.` müssen wir nicht mehr prüfen, ob die tiefer genesteten Werte gültig sind oder nicht. Wenn wir die Property von `undefined` oder `null` aufrufen (_nullish_) gibt die Expression direkt `undefined` aus. + +`person.pet?.name`: `person` hat eine Property `pet`: `person.pet` ist nicht nullish. Diese hat eine Property `name` und gibt `Mara` aus. +`person.pet?.family?.name`: `person` hat eine Property `pet`: `person.pet` ist nicht nullish. `pet` hat _keine_ Property `family`, `person.pet.family` ist nullish. Die Expression gibt `undefined` aus. +`person.getFullName?.()`: `person` hat eine Property `getFullName`: `person.getFullName()` ist nicht nullish und wird ausgeführt: `Lydia Hallie` wird ausgegeben. +`member.getLastName?.()`: `member` ist undefined: `member.getLastName()` ist nullish. Die Expression gibt `undefined` aus. + +

+
+ +--- + +###### 120. Was ist der 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` + +
Antwort +

+ +#### Antwort: B + +Wir haben die Kondition `groceries.indexOf("banana")` an das if-Statement übergeben. `groceries.indexOf("banana")` gibt `0` aus, was ein _falsy_ Wert ist. Da die Kondition nicht erfüllt ist wird der `else` Block ausgeführt und `We don't have to buy bananas!` wird geloggt. + +

+
+ +--- + +###### 121. Was ist der 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` + +
Antwort +

+ +#### Antwort: D + +Die Methode `language` ist ein `setter`. Setter halten keinen Wert, sondern ändern Properties. Wenn eine `setter` Methode aufgerufen wird, wird `undefined` zurückgegeben. + +

+
+ +--- + +###### 122. Was ist der 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` + +
Antwort +

+ +#### Antwort: C + +`typeof name` gibt `"string"` aus. Der String `"string"` ist _truthy_, sodass `!typeof name` den Boolean-Wert `false` ergibt. `false === "object"` und `false === "string"` geben beide `false` aus. + +(Würden wir prüfen wollen, oob der Typ (un)gleich zu einem bestimmten anderen Typen ist hätten wir `!==` anstelle von `!typeof` schreiben müssen) + +

+
+ +--- + +###### 123. Was ist der 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` + +
Antwort +

+ +#### Antwort: A + +Die `add` Funktion gibt eine Arrow Funktion zurück, welche eine Arrow Funktion zurückgibt, welche eine Arrow Funktion zurückgibt. Die erste Funktion erhält ein Argument `x` mit dem Wert `4`. Wir führen die zweite Funktion aus, welche ein Argument `y` mit dem Wert `5` erhält. Dann führen wir die dritte Funktion aus, die ein Argument `z` mit dem Wert `6` erhält. Wenn wir versuchen die Werte von `x`, `y` und `z` der jeweils letzten Arrow Funktion aufzurufen geht die JavaScript Engine in der Scope-Kette nach oben um die jeweiligen Werte zu finden. Das gibt `4` `5` `6` aus. + +

+
+ +--- + +###### 124. Was ist der 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` + +
Antwort +

+ +#### Antwort: C + +Die Generator-Funktion `range` gibt ein asynchrones Objekt mit Promisen für jeden Wert zurück: `Promise{1}`, `Promise{2}`, `Promise{3}`. Wir setzen die Variable `gen` gleich dem asynchronen Objekt. Danach loopen wir mit einer `for await ... of` Schleife darüber. Wir setzen die Variable `item` gleich dem ausgegebenen Promise: zuerst `Promise{1}`, dann `Promise{2}`, und dann `Promise{3}`. Da wir das Ergebnis von `item` _await_-en (erwarten), werden die gelösten Ergebnisse der Promises ausgegeben: `1`, `2` und `3`. + +

+
+ +--- + +###### 125. Was ist der 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` + +
Antwort +

+ +#### Antwort: D + +`myFunc` erwartet ein Objekt mit den Properties `x`, `y` und `z` als Argumente. Da wir nur drei separate Werte anstelle eines Objektes mit den Properties `x`, `y` und `z` ({x: 1, y: 2, z: 3}) eingeben, bekommen `x`, `y` und `z` den Standardwert `undefined` zugewiesen. + +

+
From 8feb4eac9d3f9b5d69cdb0cf7f77e3ac53eeb395 Mon Sep 17 00:00:00 2001 From: Povilas Pasausis Date: Mon, 2 Dec 2019 13:06:01 +0100 Subject: [PATCH 387/915] Fixes typo in Question 102. --- README.md | 2 +- en-EN/README.md | 2 +- th-TH/README.md | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 7614b549..e99e319d 100644 --- a/README.md +++ b/README.md @@ -3261,7 +3261,7 @@ We can get this value with both `.then` and the `await` keyword in an `async` fu 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 befoer moving to the next line. +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. diff --git a/en-EN/README.md b/en-EN/README.md index 1a71780e..7bffb2ed 100644 --- a/en-EN/README.md +++ b/en-EN/README.md @@ -3261,7 +3261,7 @@ We can get this value with both `.then` and the `await` keyword in an `async` fu 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 befoer moving to the next line. +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. diff --git a/th-TH/README.md b/th-TH/README.md index c20e707a..2ab9feb0 100644 --- a/th-TH/README.md +++ b/th-TH/README.md @@ -3260,7 +3260,7 @@ We can get this value with both `.then` and the `await` keyword in an `async` fu 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 befoer moving to the next line. +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. From 383ac64ac2ab27d290a7a7280470c7ef77a92666 Mon Sep 17 00:00:00 2001 From: Thomas Shinnick Date: Mon, 23 Dec 2019 15:38:10 -0600 Subject: [PATCH 388/915] Typo fixes README.md en-EN/README.md Some have been fixed previously but reappeared; some were fixed in the various translated files but not applied to originals; and some are also fixed in other PRs e.g. #287 numerica l whic h proprety befoer Also an unneeded overlooked anchor deleted --- README.md | 6 +++--- en-EN/README.md | 8 ++++---- 2 files changed, 7 insertions(+), 7 deletions(-) diff --git a/README.md b/README.md index 7614b549..db5cffea 100644 --- a/README.md +++ b/README.md @@ -3261,7 +3261,7 @@ We can get this value with both `.then` and the `await` keyword in an `async` fu 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 befoer moving to the next line. +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. @@ -3399,7 +3399,7 @@ console.log(colorConfig.colors[1]) 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 `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`. +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. @@ -3461,7 +3461,7 @@ With `splice` method, we modify the original array by deleting, replacing or add --- -###### 109. What's the output? +###### 109. What's the output? ```javascript const food = ['🍕', '🍫', '🥑', '🍔'] diff --git a/en-EN/README.md b/en-EN/README.md index 1a71780e..783b5d3a 100644 --- a/en-EN/README.md +++ b/en-EN/README.md @@ -3261,7 +3261,7 @@ We can get this value with both `.then` and the `await` keyword in an `async` fu 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 befoer moving to the next line. +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. @@ -3294,11 +3294,11 @@ for (let item of set) { #### Answer: 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 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, 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"` 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"`. @@ -3399,7 +3399,7 @@ console.log(colorConfig.colors[1]) 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 `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`. +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. From bac5d7b8af30a9822ae3ffbf693749d863428d86 Mon Sep 17 00:00:00 2001 From: Lydia Hallie Date: Tue, 24 Dec 2019 23:48:19 +0100 Subject: [PATCH 389/915] Add questions 132-145 and update intro --- README.md | 588 ++++++++++++++++++++++++++++++++++++++++++++++- en-EN/README.md | 598 ++++++++++++++++++++++++++++++++++++++++++++++-- 2 files changed, 1163 insertions(+), 23 deletions(-) diff --git a/README.md b/README.md index 14926d28..0ab20051 100644 --- a/README.md +++ b/README.md @@ -1,16 +1,21 @@ -# List of (Advanced) JavaScript Questions +
+ +

JavaScript Questions

+ --- -I post daily multiple choice JavaScript questions on my [Instagram](https://www.instagram.com/theavocoder), which I'll also post here! + I post multiple choice JavaScript questions on my [Instagram](https://www.instagram.com/theavocoder) **stories**, which I'll also post 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 weekly with new questions. Last update: November 18th + 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: -The answers are in the collapsed sections below the questions, simply click on them to expand it. Good luck :heart: + Feel free to reach out to me! 😊
+ Instagram || Twitter || LinkedIn || Blog +
-Want to get an email whenever I've added more questions?
-✨✉Subscribe to email updates✉✨ +--- +
See 16 Available Translations 🇪🇸🇮🇹🇩🇪 🇫🇷🇷🇺🇨🇳🇵🇹 +

-List of available languages: * [English](./en-EN/README.md) * [العربية](./ar-AR/README_AR.md) * [اللغة العامية - Egyptian Arabic](./ar-EG/README_ar-EG.md) @@ -28,8 +33,10 @@ List of available languages: * [Türkçe](./tr-TR/README-tr_TR.md) * [ไทย](./th-TH/README-th_TH.md) +

+
---- +=== ###### 1. What's the output? @@ -3752,7 +3759,9 @@ Then, we invoke the `changeAgeAndName` function, however we don't pass a paramet

-###### 117. Which of the following options will return `6`? +--- + +###### 117. Which of the following options will return `6`? ```javascript function sumValues(x, y, z) { @@ -3775,6 +3784,8 @@ With the spread operator `...`, we can _spread_ iterables to individual elements

+--- + ###### 118. What's the output? ```javascript @@ -3799,6 +3810,8 @@ With the `+=` operand, we're incrementing the value of `num` by `1`. `num` had t

+--- + ###### 119. What's the output? ```javascript @@ -3840,6 +3853,8 @@ With the optional chaining operator `?.`, we no longer have to explicitly check

+--- + ###### 120. What's the output? ```javascript @@ -3867,6 +3882,8 @@ We passed the condition `groceries.indexOf("banana")` to the if-statement. `groc

+--- + ###### 121. What's the output? ```javascript @@ -3895,6 +3912,8 @@ The `language` method is a `setter`. Setters don't hold an actual value, their p

+--- + ###### 122. What's the output? ```javascript @@ -3921,6 +3940,8 @@ console.log(!typeof name === "string");

+--- + ###### 123. What's the output? ```javascript @@ -3947,6 +3968,8 @@ The `add` function returns an arrow function, which returns an arrow function, w

+--- + ###### 124. What's the output? ```javascript @@ -3979,6 +4002,8 @@ The generator function `range` returns an async object with promises for each it

+--- + ###### 125. What's the output? ```javascript @@ -4004,6 +4029,8 @@ myFunc(1, 2, 3);

+--- + ###### 126. What's the output? ```javascript @@ -4039,6 +4066,8 @@ With the `Intl.NumberFormat` method, we can format numeric values to any locale.

+--- + ###### 127. What's the output? ```javascript @@ -4063,6 +4092,8 @@ By destructuring objects, we can unpack values from the right-hand object, and a

+--- + ###### 128. What's the output? ```javascript @@ -4093,6 +4124,8 @@ With the `isNaN` method, you can check if the value you pass is not a number. `n

+--- + ###### 129. What's the output? ```javascript @@ -4121,6 +4154,8 @@ Variables declared with the `const` keyword are not referencable before their in

+--- + ###### 130. What's the output? ```javascript @@ -4152,6 +4187,8 @@ In the `try` block, we're logging the awaited value of the `myPromise` variable:

+--- + ###### 131. What's the output? ```javascript @@ -4174,3 +4211,536 @@ With the `flat` method, we can create a new, flattened array. The depth of the f

+ +--- + +###### 132. What's the 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` + +
Answer +

+ +#### Answer: 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 the `counterTwo.increment()`, which sets the `count` to `3`. Then, we log the count on `counterOne`, which logs `3`. + + + +

+
+ +--- + +###### 133. What's the output? + +```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!` + +
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.) + +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. + +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!`. + +The next line is the _asynchronous_ `setTimeout` function, from which the callback is sent to the Web API. + +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!` + +

+
+ +--- + +###### 134. How can we invoke `sum` in `index.js` from `sum.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 + +
Answer +

+ +#### Answer: 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. What's the 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: Nothing gets logged + +
Answer +

+ +#### Answer: C + +With a Proxy object, we can add custom behavior to an object that we pass to it as the second argument. In tis 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. + +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 })` + +
Answer +

+ +#### Answer: A + +With `Object.seal` we can prevent new properies 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" }` + +
Answer +

+ +#### Answer: 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. 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" }` + +
Answer +

+ +#### Answer: 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. + +

+
+ +--- + +###### 139. What's the 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` + +
Answer +

+ +#### 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`. + +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`. + +

+
+ +--- + +###### 140. What's the 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` + +
Answer +

+ +#### 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! + +

+
+ +--- + +###### 141. What's the output? + +```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)` + +
Answer +

+ +#### Answer: 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. + +

+
+ +--- + +###### 142. What's the 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"]` + +
Answer +

+ +#### Answer: 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 `y`, `"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 `"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. + +After pushing `dancing` and `baking`, the value of `person.hobbies` is `["coding", "dancing", "baking"]` + +

+
+ +--- + +###### 143. What's the 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: Nothing, we didn't call any method + +
Answer +

+ +#### Answer: 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. 🦢"`. + +

+
+ +--- + +###### 144. 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 + +
Answer +

+ +#### Answer: 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 propeties on the `emojis` array can be modified, for example by pushing new values, splicing them, or setting the length of the array to 0. + +

+
+ +--- + +###### 145. 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]() { for (let x in this) yield* Object.values(this) }` +- D: `*[Symbol.iterator]() { for (let x in this) yield this }` + +
Answer +

+ +#### Answer: 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)`. + +

+
+ diff --git a/en-EN/README.md b/en-EN/README.md index b35a8516..2dfdec30 100644 --- a/en-EN/README.md +++ b/en-EN/README.md @@ -1,16 +1,21 @@ -# List of (Advanced) JavaScript Questions +
+ +

JavaScript Questions

+ --- -I post daily multiple choice JavaScript questions on my [Instagram](https://www.instagram.com/theavocoder), which I'll also post here! + I post multiple choice JavaScript questions on my [Instagram](https://www.instagram.com/theavocoder) **stories**, which I'll also post here! Last updated: December 24th -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 weekly with new questions. Last update: November 18th + 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: -The answers are in the collapsed sections below the questions, simply click on them to expand it. Good luck :heart: + Feel free to reach out to me! 😊
+ Instagram || Twitter || LinkedIn || Blog +
-Want to get an email whenever I've added more questions?
-✨✉Subscribe to email updates✉✨ +--- +
See 16 Available Translations 🇪🇸🇮🇹🇩🇪 🇫🇷🇷🇺🇨🇳🇵🇹 +

-List of available languages: * [English](../en-EN/README.md) * [العربية](../ar-AR/README_AR.md) * [اللغة العامية - Egyptian Arabic](../ar-EG/README_ar-EG.md) @@ -28,8 +33,10 @@ List of available languages: * [Türkçe](../tr-TR/README-tr_TR.md) * [ไทย](../th-TH/README-th_TH.md) +

+
---- +=== ###### 1. What's the output? @@ -3294,11 +3301,11 @@ for (let item of set) { #### Answer: 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 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, 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"` 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"`. @@ -3399,7 +3406,7 @@ console.log(colorConfig.colors[1]) 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`. +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 `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. @@ -3461,7 +3468,7 @@ With `splice` method, we modify the original array by deleting, replacing or add --- -###### 109. What's the output? +###### 109. What's the output? ```javascript const food = ['🍕', '🍫', '🥑', '🍔'] @@ -3752,7 +3759,9 @@ Then, we invoke the `changeAgeAndName` function, however we don't pass a paramet

-###### 117. Which of the following options will return `6`? +--- + +###### 117. Which of the following options will return `6`? ```javascript function sumValues(x, y, z) { @@ -3775,6 +3784,8 @@ With the spread operator `...`, we can _spread_ iterables to individual elements

+--- + ###### 118. What's the output? ```javascript @@ -3799,6 +3810,8 @@ With the `+=` operand, we're incrementing the value of `num` by `1`. `num` had t

+--- + ###### 119. What's the output? ```javascript @@ -3840,6 +3853,8 @@ With the optional chaining operator `?.`, we no longer have to explicitly check

+--- + ###### 120. What's the output? ```javascript @@ -3867,6 +3882,8 @@ We passed the condition `groceries.indexOf("banana")` to the if-statement. `groc

+--- + ###### 121. What's the output? ```javascript @@ -3895,6 +3912,8 @@ The `language` method is a `setter`. Setters don't hold an actual value, their p

+--- + ###### 122. What's the output? ```javascript @@ -3921,6 +3940,8 @@ console.log(!typeof name === "string");

+--- + ###### 123. What's the output? ```javascript @@ -3947,6 +3968,8 @@ The `add` function returns an arrow function, which returns an arrow function, w

+--- + ###### 124. What's the output? ```javascript @@ -3979,6 +4002,8 @@ The generator function `range` returns an async object with promises for each it

+--- + ###### 125. What's the output? ```javascript @@ -4004,6 +4029,8 @@ myFunc(1, 2, 3);

+--- + ###### 126. What's the output? ```javascript @@ -4039,6 +4066,8 @@ With the `Intl.NumberFormat` method, we can format numeric values to any locale.

+--- + ###### 127. What's the output? ```javascript @@ -4063,6 +4092,8 @@ By destructuring objects, we can unpack values from the right-hand object, and a

+--- + ###### 128. What's the output? ```javascript @@ -4093,6 +4124,8 @@ With the `isNaN` method, you can check if the value you pass is not a number. `n

+--- + ###### 129. What's the output? ```javascript @@ -4121,6 +4154,8 @@ Variables declared with the `const` keyword are not referencable before their in

+--- + ###### 130. What's the output? ```javascript @@ -4152,6 +4187,8 @@ In the `try` block, we're logging the awaited value of the `myPromise` variable:

+--- + ###### 131. What's the output? ```javascript @@ -4173,4 +4210,537 @@ console.log(emojis.flat(1)); 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 `['🥑', '✨', '✨', ['🍕', '🍕']]`.

- \ No newline at end of file + + +--- + +###### 132. What's the 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` + +
Answer +

+ +#### Answer: 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 the `counterTwo.increment()`, which sets the `count` to `3`. Then, we log the count on `counterOne`, which logs `3`. + + + +

+
+ +--- + +###### 133. What's the output? + +```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!` + +
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.) + +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. + +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!`. + +The next line is the _asynchronous_ `setTimeout` function, from which the callback is sent to the Web API. + +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!` + +

+
+ +--- + +###### 134. How can we invoke `sum` in `index.js` from `sum.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 + +
Answer +

+ +#### Answer: 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. What's the 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: Nothing gets logged + +
Answer +

+ +#### Answer: C + +With a Proxy object, we can add custom behavior to an object that we pass to it as the second argument. In tis 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. + +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 })` + +
Answer +

+ +#### Answer: A + +With `Object.seal` we can prevent new properies 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" }` + +
Answer +

+ +#### Answer: 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. 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" }` + +
Answer +

+ +#### Answer: 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. + +

+
+ +--- + +###### 139. What's the 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` + +
Answer +

+ +#### 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`. + +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`. + +

+
+ +--- + +###### 140. What's the 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` + +
Answer +

+ +#### 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! + +

+
+ +--- + +###### 141. What's the output? + +```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)` + +
Answer +

+ +#### Answer: 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. + +

+
+ +--- + +###### 142. What's the 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"]` + +
Answer +

+ +#### Answer: 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 `y`, `"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 `"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. + +After pushing `dancing` and `baking`, the value of `person.hobbies` is `["coding", "dancing", "baking"]` + +

+
+ +--- + +###### 143. What's the 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: Nothing, we didn't call any method + +
Answer +

+ +#### Answer: 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. 🦢"`. + +

+
+ +--- + +###### 144. 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 + +
Answer +

+ +#### Answer: 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 propeties on the `emojis` array can be modified, for example by pushing new values, splicing them, or setting the length of the array to 0. + +

+
+ +--- + +###### 145. 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]() { for (let x in this) yield* Object.values(this) }` +- D: `*[Symbol.iterator]() { for (let x in this) yield this }` + +
Answer +

+ +#### Answer: 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)`. + +

+
+ From 38098f760b197a7db3ab36dbef0373c2373d1c2f Mon Sep 17 00:00:00 2001 From: Lydia Hallie Date: Tue, 24 Dec 2019 23:50:13 +0100 Subject: [PATCH 390/915] Fix lines --- README.md | 7 ++++--- en-EN/README.md | 3 ++- 2 files changed, 6 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index 0ab20051..bf8240b6 100644 --- a/README.md +++ b/README.md @@ -1,9 +1,10 @@

JavaScript Questions

+ --- - I post multiple choice JavaScript questions on my [Instagram](https://www.instagram.com/theavocoder) **stories**, which I'll also post here! + I post multiple choice JavaScript questions on my [Instagram](https://www.instagram.com/theavocoder) **stories**, which I'll also post here! Last updated: December 24th 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: @@ -36,7 +37,7 @@

-=== +--- ###### 1. What's the output? @@ -4214,7 +4215,7 @@ With the `flat` method, we can create a new, flattened array. The depth of the f --- -###### 132. What's the output? +###### 132. What's the output? ```javascript class Counter { diff --git a/en-EN/README.md b/en-EN/README.md index 2dfdec30..58e42c6d 100644 --- a/en-EN/README.md +++ b/en-EN/README.md @@ -1,6 +1,7 @@

JavaScript Questions

+ --- I post multiple choice JavaScript questions on my [Instagram](https://www.instagram.com/theavocoder) **stories**, which I'll also post here! Last updated: December 24th @@ -36,7 +37,7 @@

-=== +--- ###### 1. What's the output? From 2225d04c45b335b7fd63959a78f8cc5ed2bd9330 Mon Sep 17 00:00:00 2001 From: Keven Date: Fri, 3 Jan 2020 15:51:43 -0300 Subject: [PATCH 391/915] Translated Brazilian questions of 44 to 50 --- pt-BR/README_pt_BR.md | 221 +++++++++++++++++++++++++++++++++++++++++- 1 file changed, 219 insertions(+), 2 deletions(-) diff --git a/pt-BR/README_pt_BR.md b/pt-BR/README_pt_BR.md index b9456327..e3531c29 100644 --- a/pt-BR/README_pt_BR.md +++ b/pt-BR/README_pt_BR.md @@ -1131,10 +1131,10 @@ console.log(numbers); - C: `[1, 2, 3, 7 x empty, 11]` - D: `SyntaxError` -
Answer +
Resposta

-#### Answer: C +#### Resposta: 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: @@ -1309,3 +1309,220 @@ Strings são iteráveis. O operador do spread `...` mapeia todo caractére de um

+ +--- + +###### 44. Qual é a saída? + +```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` + +
Resposta +

+ +#### Resposta: C + +Funções regulares não podem ser interrompidas durante execução após sua invocação. Entretanto, uma função generator pode ser interrompida, e depois continuar de onde parou. Uma função generator sempre possue a palavra chave `yield`, a função gera o valor específicado logo após. Note que a função generator, neste caso não retorna o valor, ele utiliza _yields_ no valor. + +Primeiro, nós inicializamos a função generator com `i` igual a `10`. Nós chamamos a função generator utilizando o `next()` para próxima função. A primeira vez que executamos a função generator o `i` é igual a `10`. que possue a palavra chave `yield`: que atribue o yields ao valor de `i`. O generator é pausado e `10` é logado. + +Então, chamamos a próxima função novamente com o `next()`. Que continua de onde foi interrompido anteirormente, ainda com `i` igual a `10`. Agora, ele encontra o próximo `yield`, e yields `i * 2`. `i` é igual a `10`, que então retorna `10 * 2`, que é `20`. Seu resultado é `10, 20`. + +

+
+ +--- + +###### 45. Qual o retorno? + +```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"` + +
Resposta +

+ +#### Resposta: B + +Quando passamos múltiplas "promises" para a função `Promise.race`, ele resolve ou rejeita a primeira "promise". Para a função de `setTimeout`, nós passamos um tempo de 500ms para a primeira promise (`firstPromise`), e 100ms para a segunda promise (`secondPromise`). Isso significa que o `secondPromise` resolve primeiro com o valor de `'two'`. `res` que agora possui o valor `'two'`, que foi logado. + +

+
+ +--- + +###### 46. Qual é a saída? + +```javascript +let person = { name: "Lydia" }; +const members = [person]; +person = null; + +console.log(members); +``` + +- A: `null` +- B: `[null]` +- C: `[{}]` +- D: `[{ name: "Lydia" }]` + +
Resposta +

+ +#### Resposta: D + +Primeiro, declaramos a variável `person` com o valor de um objeto que possui o propriedade `name`. + + + +Então, declaramos a variável chamada `members`. Setamos o valor do primeiro elemento do array igual ao valor da variável `person`. Objetos interados por _referência_ quando ao defini-los iguais entre si. Quando você atribui uma referência de uma variável para outra, você faz uma _cópia_ de sua referência. (note que eles não possuem a _mesma_ referência!) + + + +Então, setamos a variável `person` igual a `null`. + + + +Estamos apenas modificando o valor da variável `person`, e não o primeiro elemento do array, desde que o elemento tem uma diferente referência (copiada) de um objeto. O primeiro elemento de `members` ainda mantém sua referência com o objeto original. Quando logamos o array de `members`, o primeiro elemento ainda mantém o valor do objeto, que é logado. + +

+
+ +--- + +###### 47. Qual é a saída? + +```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]` + +
Resposta +

+ +#### Resposta: B + +Utilizando o loop `for-in`, podemos interar através das chaves do objeto, neste caso o `name` e `age`. Por baixo dos panos, chaves de objetos são strings (eles não são um símbolo). Em cada loop, setamos ao valor do `item` igual ao da chave atual, que se intera. Primeiro, `item` é igual ao `name`, e é logado. Então, `item` é igual a idade `age`, que é logado. + +

+
+ +--- + +###### 48. Qual é a saída? + +```javascript +console.log(3 + 4 + "5"); +``` + +- A: `"345"` +- B: `"75"` +- C: `12` +- D: `"12"` + +
Resposta +

+ +#### Resposta: B + +Associatividade do operador é a ordem na qual o compilador avalia as expressões, ou esquerda-para-direita ou direita-para-esquerda. Isso apenas acontece se todos os operatores possuem a _mesma_ precedência. Apenas temos um tipo de operador: `+`. Para adição, a associatividade é esquerda-para-direita. + +`3 + 4` é avaliado primeiro. Seu resultado é o número `7`. + +`7 + '5'` resulta em `"75"` por causa da coerção. JavaScript converte o número `7` em string, veja a questão 15. Podemos concatenar duas strings com o operador de `+`. `"7" + "5"` resulta em `"75"`. + +

+
+ +--- + +###### 49. Qual o retorno de `num`? + +```javascript +const num = parseInt("7*6", 10); +``` + +- A: `42` +- B: `"42"` +- C: `7` +- D: `NaN` + +
Resposta +

+ +#### Resposta: C + +Apenas os primeiros números da string é retornado. Baseado no _radix_ (o segundo parametro na ordem especifica qual o tipo de número queremos atribuir o parse: base 10, hexadecimal, octal, binary, etc.), o `parseInt` checa se os caracteres na string são válidos. Depois de encontrar um caracter que não é um número válido no radix, ele interrompe o parse e ignora os seguintes caracteres. + +`*` não é um número válido. Ele apenas usa o parse no `"7"` em decimal `7`. `num` possui o valor `7`. + +

+
+ +--- + +###### 50. Qual é a saída? + +```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 ]` + +
Resposta +

+ +#### Resposta: C + +Quando mapeamos um array (map), o valor de `num` é igual ao elemento que está percorrendo. Neste caso, os elementos são números, então a condição do se (if) `typeof num === "number"` retorna `true`. A função map cria um novo array e insere os valores retornados da função. + +Entretanto, não se retorna o valor. Quando não se retorna um valor para a função, a função retorna `undefined`. Para cada elemento do array, o bloco de função é chamado, então para cada elemento é retornado `undefined`. + +

+
+ +--- \ No newline at end of file From 86a2b8bdff05e425987053a6ca74d89362042f3f Mon Sep 17 00:00:00 2001 From: i-have-no-name Date: Sat, 4 Jan 2020 21:51:15 +0300 Subject: [PATCH 392/915] Fix question 145 --- README.md | 2 +- en-EN/README.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index d3d60814..0336e02a 100644 --- a/README.md +++ b/README.md @@ -4732,7 +4732,7 @@ const person = { - A: Nothing, object are iterable by default - 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 }`
Answer diff --git a/en-EN/README.md b/en-EN/README.md index ddf67054..20f81060 100644 --- a/en-EN/README.md +++ b/en-EN/README.md @@ -4732,7 +4732,7 @@ const person = { - A: Nothing, object are iterable by default - 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 }`
Answer From 19fad794f922754357615dda8e8c5a3076d4c4d6 Mon Sep 17 00:00:00 2001 From: Stella Yu Date: Sun, 5 Jan 2020 20:03:00 +0900 Subject: [PATCH 393/915] Fix typo --- 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 84ab3893..1ed1978c 100644 --- a/ko-KR/README-ko_KR.md +++ b/ko-KR/README-ko_KR.md @@ -2631,7 +2631,7 @@ console.log(person); #### 정답: A -`city` 변수를 `person` rorcpdml `city`라고 불리는 속성 값으로 설정 했어요. 이 객체에서는 `city`라고 불리는 속성이 없기 때문에, `city`는 `undefined`의 값을 가져요. +`city` 변수를 `person` 객체의 `city`라고 불리는 속성 값으로 설정 했어요. 이 객체에서는 `city`라고 불리는 속성이 없기 때문에, `city`는 `undefined`의 값을 가져요. `person`객체 자체를 참조 _하지않는_ 다는 걸 참고해요! 변수 `city`는 `person` 객체의 `city` 현재 속성 값으로 설정 했을 뿐이죠. @@ -3257,7 +3257,7 @@ secondFunction() #### 정답: D -promise를 사용하면, 기본적으로 _이 함수를 실행하고 싶지만, 시간이 좀 걸릴 수 있으니 실행중에 잠시 미뤄둘거에요. 확실한 값이 resoloved(혹은 rejected)로 전달되었을 때와 콜 스택이 비었을 때 이 값을 사용하고 싶어요_ 라고 말해요. +promise를 사용하면, 기본적으로 _이 함수를 실행하고 싶지만, 시간이 좀 걸릴 수 있으니 실행 중에 잠시 미뤄둘거에요. 확실한 값이 resoloved(혹은 rejected)로 전달되었을 때와 콜 스택이 비었을 때 이 값을 사용하고 싶어요_ 라고 말해요. `async` 함수 안에서 `.then`과 `await` 두개의 키워드에서 값을 얻을 수 있어요. 비록 `.then`과 `await`에서 프라미스의 값을 얻을 수 있지만, 그들은 약간 다르게 작동해요. From f27f40bdaeab6bfb3b0a14d293743d6682cf61d4 Mon Sep 17 00:00:00 2001 From: MrHanson Date: Sun, 5 Jan 2020 23:51:40 +0800 Subject: [PATCH 394/915] Supplementary translation for pervious --- zh-CN/README-zh_CN.md | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/zh-CN/README-zh_CN.md b/zh-CN/README-zh_CN.md index 443f5cd9..71529582 100644 --- a/zh-CN/README-zh_CN.md +++ b/zh-CN/README-zh_CN.md @@ -424,8 +424,8 @@ console.log(sarah) ###### 14. 所有对象都有原型。 -- A: true -- B: false +- A: 对 +- B: 错
答案

@@ -760,9 +760,9 @@ console.log(obj) ###### 26. JavaScript 全局执行上下文为你做了两件事:全局对象和 this 关键字。 -- A: true -- B: false -- C: it depends +- A: 对 +- B: 错 +- C: 看情况

答案

From c5ab2fafd28a62565dfee3a476982385ff17305b Mon Sep 17 00:00:00 2001 From: Nusendra Hanggarawan Date: Mon, 6 Jan 2020 14:49:27 +0700 Subject: [PATCH 395/915] Added Indonesia translations --- id-ID/README.md | 4750 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 4750 insertions(+) create mode 100644 id-ID/README.md diff --git a/id-ID/README.md b/id-ID/README.md new file mode 100644 index 00000000..a5c0becb --- /dev/null +++ b/id-ID/README.md @@ -0,0 +1,4750 @@ +

+ +

Pertanyaan JavaScript

+ +--- + +Saya menerbitkan beberapa pilihan pertanyaan Javascript di akun Instagram Story [Instagram](https://www.instagram.com/theavocoder), yang mana diterbitkan disini juga! Terakhir diperbaharui: 24 Desember + +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: +Dari tingkat dasar sampai tingkat lanjut: Menguji seberapa jago Anda di JavaScript, asah pengetahuan Anda, atau untuk persiapan interview tentang pemrograman! :muscle: :rocket: Saya akan memperbaharui jawaban di bagian yang tertutup di bawah pertanyaan, sederhananya tinggal di klik saja yang nantinya jawaban akan muncul disana. Ini hanya untuk bersenang - senang saja, semoga berhasil! :heart: + +Feel free to reach out to me! 😊
+Jangan sungkan untuk terhubung dengan saya! 😊
+Instagram || Twitter || LinkedIn || Blog + +
+ +--- + +
Lihat 17 Terjemahan yang tersedia 🇪🇸🇮🇹🇩🇪 🇫🇷🇷🇺🇨🇳🇵🇹 +

+ +- [English](../en-EN/README.md) +- [العربية](../ar-AR/README_AR.md) +- [اللغة العامية - Egyptian Arabic](../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) +- [日本語](../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) +- [Українська мова](../ua-UA/README-ua_UA.md) +- [Tiếng Việt](../vi-VI/README-vi.md) +- [中文版本](../zh-CN/README-zh_CN.md) +- [Türkçe](../tr-TR/README-tr_TR.md) +- [ไทย](../th-TH/README-th_TH.md) +- [Indonesia](../id-ID/README.md) + +

+
+ +--- + +###### 1. Apa yang akan tampil? + +```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` + +
Jawaban +

+ +#### Jawaban: D + +Within the function, we first declare the `name` variable with the `var` keyword. This means that the variable gets hoisted (memory space is set up during the creation phase) with the default value of `undefined`, until we actually get to the line where we define the variable. We haven't defined the variable yet on the line where we try to log the `name` variable, so it still holds the value of `undefined`. + +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`. + +

+
+ +--- + +###### 2. Apa yang akan tampil? + +```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` + +
Jawaban +

+ +#### Jawaban: C + +Because of the event queue in JavaScript, the `setTimeout` callback function is called _after_ the loop has been executed. Since the variable `i` in the first loop was declared using the `var` keyword, this value was global. During the loop, we incremented the value of `i` by `1` each time, using the unary operator `++`. By the time the `setTimeout` callback function was invoked, `i` was equal to `3` in the first example. + +In the second loop, the variable `i` was declared using the `let` keyword: variables declared with the `let` (and `const`) keyword are block-scoped (a block is anything between `{ }`). During each iteration, `i` will have a new value, and each value is scoped inside the loop. + +

+
+ +--- + +###### 3. Apa yang akan tampil? + +```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` + +
Jawaban +

+ +#### Jawaban: B + +Note that the value of `diameter` is a regular function, whereas the value of `perimeter` is an arrow function. + +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 `undefined`. + +

+
+ +--- + +###### 4. Apa yang akan tampil? + +```javascript ++true; +!'Lydia'; +``` + +- A: `1` and `false` +- B: `false` and `NaN` +- C: `false` and `false` + +
Jawaban +

+ +#### Jawaban: A + +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`. + +

+
+ +--- + +###### 5. Which one is true? + +```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 + +
Jawaban +

+ +#### Jawaban: A + +In JavaScript, all object keys are strings (unless it's a Symbol). Even though we might not _type_ them as strings, they are always converted into strings under the hood. + +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. + +`mouse[bird.size]`: First it evaluates `bird.size`, which is `"small"`. `mouse["small"]` returns `true` + +However, with dot notation, this doesn't happen. `mouse` does not have a key called `bird`, which means that `mouse.bird` is `undefined`. Then, we ask for the `size` using dot notation: `mouse.bird.size`. Since `mouse.bird` is `undefined`, we're actually asking `undefined.size`. This isn't valid, and will throw an error similar to `Cannot read property "size" of undefined`. + +

+
+ +--- + +###### 6. Apa yang akan tampil? + +```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` + +
Jawaban +

+ +#### Jawaban: A + +In JavaScript, all objects interact by _reference_ when setting them equal to each other. + +First, variable `c` holds a value to an object. Later, we assign `d` with the same reference that `c` has to the object. + + + +When you change one object, you change all of them. + +

+
+ +--- + +###### 7. Apa yang akan tampil? + +```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` + +
Jawaban +

+ +#### Jawaban: 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`. + +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.` + +

+
+ +--- + +###### 8. Apa yang akan tampil? + +```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` + +
Jawaban +

+ +#### Jawaban: 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. + +

+
+ +--- + +###### 9. Apa yang akan tampil? + +```javascript +let greeting; +greetign = {}; // Typo! +console.log(greetign); +``` + +- A: `{}` +- B: `ReferenceError: greetign is not defined` +- C: `undefined` + +
Jawaban +

+ +#### Jawaban: 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). + +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. + +

+
+ +--- + +###### 10. What happens when we do this? + +```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` + +
Jawaban +

+ +#### Jawaban: A + +This is possible in JavaScript, because functions are objects! (Everything besides primitive types are objects) + +A function is a special type of object. The code you write yourself isn't the actual function. The function is an object with properties. This property is invocable. + +

+
+ +--- + +###### 11. Apa yang akan tampil? + +```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` + +
Jawaban +

+ +#### Jawaban: A + +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() { + return `${this.firstName} ${this.lastName}`; +}; +``` + +would have made `member.getFullName()` work. Why is this beneficial? Say that we added this method to the constructor itself. Maybe not every `Person` instance needed this method. This would waste a lot of memory space, since they would still have that property, which takes of memory space for each instance. Instead, if we only add it to the prototype, we just have it at one spot in memory, yet they all have access to it! + +

+
+ +--- + +###### 12. Apa yang akan tampil? + +```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` + +
Jawaban +

+ +#### Jawaban: A + +For `sarah`, we didn't use the `new` keyword. When using `new`, it refers to the new empty object we create. However, if you don't add `new` it 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 + +
Jawaban +

+ +#### Jawaban: 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 + +
Jawaban +

+ +#### Jawaban: 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. Apa yang akan tampil? + +```javascript +function sum(a, b) { + return a + b; +} + +sum(1, '2'); +``` + +- A: `NaN` +- B: `TypeError` +- C: `"12"` +- D: `3` + +
Jawaban +

+ +#### Jawaban: 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. Apa yang akan tampil? + +```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` + +
Jawaban +

+ +#### Jawaban: 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. Apa yang akan tampil? + +```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` + +
Jawaban +

+ +#### Jawaban: 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. Apa yang akan tampil? + +```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` + +
Jawaban +

+ +#### Jawaban: 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. Apa yang akan tampil? + +```javascript +function getAge(...args) { + console.log(typeof args); +} + +getAge(21); +``` + +- A: `"number"` +- B: `"array"` +- C: `"object"` +- D: `"NaN"` + +
Jawaban +

+ +#### Jawaban: 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. Apa yang akan tampil? + +```javascript +function getAge() { + 'use strict'; + age = 21; + console.log(age); +} + +getAge(); +``` + +- A: `21` +- B: `undefined` +- C: `ReferenceError` +- D: `TypeError` + +
Jawaban +

+ +#### Jawaban: 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 value of `sum`? + +```javascript +const sum = eval('10*10+5'); +``` + +- A: `105` +- B: `"105"` +- C: `TypeError` +- D: `"10*10+5"` + +
Jawaban +

+ +#### Jawaban: 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. + +
Jawaban +

+ +#### Jawaban: 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. Apa yang akan tampil? + +```javascript +var num = 8; +var num = 10; + +console.log(num); +``` + +- A: `8` +- B: `10` +- C: `SyntaxError` +- D: `ReferenceError` + +
Jawaban +

+ +#### Jawaban: 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. Apa yang akan tampil? + +```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` + +
Jawaban +

+ +#### Jawaban: 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. Apa yang akan tampil? + +```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` + +
Jawaban +

+ +#### Jawaban: 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 + +
Jawaban +

+ +#### Jawaban: A + +The base execution context is the global execution context: it's what's accessible everywhere in your code. + +

+
+ +--- + +###### 27. Apa yang akan tampil? + +```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` + +
Jawaban +

+ +#### Jawaban: C + +The `continue` statement skips an iteration if a certain condition returns `true`. + +

+
+ +--- + +###### 28. Apa yang akan tampil? + +```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` + +
Jawaban +

+ +#### Jawaban: 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. Apa yang akan tampil? + +```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` + +
Jawaban +

+ +#### Jawaban: 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. Apa yang akan tampil? + +```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` + +
Jawaban +

+ +#### Jawaban: 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. + +
Jawaban +

+ +#### Jawaban: 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` + +
Jawaban +

+ +#### Jawaban: 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. Apa yang akan tampil? + +```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` + +
Jawaban +

+ +#### Jawaban: 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. Apa yang akan tampil? + +```javascript +function sayHi() { + return (() => 0)(); +} + +console.log(typeof sayHi()); +``` + +- A: `"object"` +- B: `"number"` +- C: `"function"` +- D: `"undefined"` + +
Jawaban +

+ +#### Jawaban: B + +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`, and `symbol`. `"function"` is not a type, since functions are objects, it's of type `"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 + +
Jawaban +

+ +#### Jawaban: A + +There are only six falsy values: + +- `undefined` +- `null` +- `NaN` +- `0` +- `''` (empty string) +- `false` + +Function constructors, like `new Number` and `new Boolean` are truthy. + +

+
+ +--- + +###### 36. Apa yang akan tampil? + +```javascript +console.log(typeof typeof 1); +``` + +- A: `"number"` +- B: `"string"` +- C: `"object"` +- D: `"undefined"` + +
Jawaban +

+ +#### Jawaban: B + +`typeof 1` returns `"number"`. +`typeof "number"` returns `"string"` + +

+
+ +--- + +###### 37. Apa yang akan tampil? + +```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` + +
Jawaban +

+ +#### Jawaban: 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, 7 x empty, 11]` + +depending on where you run it (it's different for every browser, node, etc.) + +

+
+ +--- + +###### 38. Apa yang akan tampil? + +```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` + +
Jawaban +

+ +#### Jawaban: 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 + +
Jawaban +

+ +#### Jawaban: 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 object 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. Apa yang akan tampil? + +```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]` + +
Jawaban +

+ +#### Jawaban: 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. Apa yang akan tampil? + +```javascript +!!null; +!!''; +!!1; +``` + +- A: `false` `true` `false` +- B: `false` `false` `true` +- C: `false` `true` `true` +- D: `true` `true` `false` + +
Jawaban +

+ +#### Jawaban: 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` + +
Jawaban +

+ +#### Jawaban: 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"]]` + +
Jawaban +

+ +#### Jawaban: A + +A string is an iterable. The spread operator maps every character of an iterable to one element. + +

+
+ +--- + +###### 44. Apa yang akan tampil? + +```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` + +
Jawaban +

+ +#### Jawaban: 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"` + +
Jawaban +

+ +#### Jawaban: 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. Apa yang akan tampil? + +```javascript +let person = { name: 'Lydia' }; +const members = [person]; +person = null; + +console.log(members); +``` + +- A: `null` +- B: `[null]` +- C: `[{}]` +- D: `[{ name: "Lydia" }]` + +
Jawaban +

+ +#### Jawaban: 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. Apa yang akan tampil? + +```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]` + +
Jawaban +

+ +#### Jawaban: 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. Apa yang akan tampil? + +```javascript +console.log(3 + 4 + '5'); +``` + +- A: `"345"` +- B: `"75"` +- C: `12` +- D: `"12"` + +
Jawaban +

+ +#### Jawaban: 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` + +
Jawaban +

+ +#### Jawaban: 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. What's the 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 ]` + +
Jawaban +

+ +#### Jawaban: 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. Apa yang akan tampil? + +```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"` + +
Jawaban +

+ +#### Jawaban: 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. Apa yang akan tampil? + +```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!` + +
Jawaban +

+ +#### Jawaban: 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. Apa yang akan tampil? + +```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` + +
Jawaban +

+ +#### Jawaban: 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. Apa yang akan tampil? + +```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"` + +
Jawaban +

+ +#### Jawaban: 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 (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. Apa yang akan tampil? + +```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` + +
Jawaban +

+ +#### Jawaban: 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. Apa yang akan tampil? + +```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}` + +
Jawaban +

+ +#### Jawaban: 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. Apa yang akan tampil? + +```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` + +
Jawaban +

+ +#### Jawaban: 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. Apa yang akan tampil? + +```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` + +
Jawaban +

+ +#### Jawaban: 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. Apa yang akan tampil? + +```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]` + +
Jawaban +

+ +#### Jawaban: 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. Apa yang akan tampil? + +```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 }` + +
Jawaban +

+ +#### Jawaban: 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. Apa yang akan tampil? + +```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"]` + +
Jawaban +

+ +#### Jawaban: 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. Apa yang akan tampil? + +```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}"` + +
Jawaban +

+ +#### Jawaban: 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. Apa yang akan tampil? + +```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` + +
Jawaban +

+ +#### Jawaban: 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. Apa yang akan tampil? + +```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` + +
Jawaban +

+ +#### Jawaban: 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. Apa yang akan tampil? + +```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` + +
Jawaban +

+ +#### Jawaban: 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 + +
Jawaban +

+ +#### Jawaban: 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. Apa yang akan tampil? + +```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` + +
Jawaban +

+ +#### Jawaban: 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. Apa yang akan tampil? + +```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` + +
Jawaban +

+ +#### Jawaban: 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. Apa yang akan tampil? + +```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"`, + +
Jawaban +

+ +#### Jawaban: 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. Apa yang akan tampil? + +```javascript +console.log('🥑' + '💻'); +``` + +- A: `"🥑💻"` +- B: `257548` +- C: A string containing their code points +- D: Error + +
Jawaban +

+ +#### Jawaban: 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 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")` + +
Jawaban +

+ +#### Jawaban: 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. Apa yang akan tampil? + +```javascript +console.log(String.raw`Hello\nworld`); +``` + +- A: `Hello world!` +- B: `Hello`
     `world` +- C: `Hello\nworld` +- D: `Hello\n`
     `world` + +
Jawaban +

+ +#### Jawaban: 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. Apa yang akan tampil? + +```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` + +
Jawaban +

+ +#### Jawaban: 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. Apa yang akan tampil? + +```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` + +
Jawaban +

+ +#### Jawaban: 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. Apa yang akan tampil? + +```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` + +
Jawaban +

+ +#### Jawaban: 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)` returns 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. Apa yang akan tampil? + +```javascript +const { name: myName } = { name: 'Lydia' }; + +console.log(name); +``` + +- A: `"Lydia"` +- B: `"myName"` +- C: `undefined` +- D: `ReferenceError` + +
Jawaban +

+ +#### Jawaban: 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, a ReferenceError gets thrown. + +

+
+ +--- + +###### 77. Is this a pure function? + +```javascript +function sum(a, b) { + return a + b; +} +``` + +- A: Yes +- B: No + +
Jawaban +

+ +#### Jawaban: 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` + +
Jawaban +

+ +#### Jawaban: 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: "🍫"}` + +
Jawaban +

+ +#### Jawaban: 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]` + +
Jawaban +

+ +#### Jawaban: 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` + +
Jawaban +

+ +#### Jawaban: 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 `"😎"` + +
Jawaban +

+ +#### Jawaban: 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"` + +
Jawaban +

+ +#### Jawaban: 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` + +
Jawaban +

+ +#### Jawaban: 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. + +
Jawaban +

+ +#### Jawaban: 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` + +
Jawaban +

+ +#### Jawaban: 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. Apa yang akan tampil? + +```javascript +console.log('I want pizza'[0]); +``` + +- A: `"""` +- B: `"I"` +- C: `SyntaxError` +- D: `undefined` + +
Jawaban +

+ +#### Jawaban: 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. + +Note that this method is not supported in IE7 and below. In that case, use `.charAt()` + +

+
+ +--- + +###### 88. Apa yang akan tampil? + +```javascript +function sum(num1, num2 = num1) { + console.log(num1 + num2); +} + +sum(10); +``` + +- A: `NaN` +- B: `20` +- C: `ReferenceError` +- D: `undefined` + +
Jawaban +

+ +#### Jawaban: 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. Apa yang akan tampil? + +```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` + +
Jawaban +

+ +#### Jawaban: 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. Apa yang akan tampil? + +```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"` + +
Jawaban +

+ +#### Jawaban: C + +Classes are syntactical sugar for function constructors. The equivalent of the `Person` class as a function constructor would be: + +```javascript +function Person() { + 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. Apa yang akan tampil? + +```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` + +
Jawaban +

+ +#### Jawaban: 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. Apa yang akan tampil? + +```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` + +
Jawaban +

+ +#### Jawaban: 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. Apa yang akan tampil? + +```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` + +
Jawaban +

+ +#### Jawaban: 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. Apa yang akan tampil? + +```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` + +
Jawaban +

+ +#### Jawaban: 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. Apa yang akan tampil? + +```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` + +
Jawaban +

+ +#### Jawaban: 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. Apa yang akan tampil? + +```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` + +
Jawaban +

+ +#### Jawaban: 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. Apa yang akan tampil? + +```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 `[]` + +
Jawaban +

+ +#### Jawaban: 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. Apa yang akan tampil? + +```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 }` + +
Jawaban +

+ +#### Jawaban: 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 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 })` + +Since no value gets returned in this case, the function returns `undefined`. + +

+
+ +--- + +###### 99. Apa yang akan tampil? + +```javascript +const name = 'Lydia'; + +console.log(name()); +``` + +- A: `SyntaxError` +- B: `ReferenceError` +- C: `TypeError` +- D: `undefined` + +
Jawaban +

+ +#### Jawaban: 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` + +
Jawaban +

+ +#### Jawaban: 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` + +
Jawaban +

+ +#### Jawaban: 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 past 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` + +
Jawaban +

+ +#### Jawaban: 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 befoer 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` + +
Jawaban +

+ +#### Jawaban: 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` + +
Jawaban +

+ +#### Jawaban: 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` + +
Jawaban +

+ +#### Jawaban: 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` + +
Jawaban +

+ +#### Jawaban: 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 proprety 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` + +
Jawaban +

+ +#### Jawaban: 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` + +
Jawaban +

+ +#### Jawaban: 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. Apa yang akan tampil? + +```javascript +const food = ['🍕', '🍫', '🥑', '🍔']; +const info = { favoriteFood: food[0] }; + +info.favoriteFood = '🍝'; + +console.log(food); +``` + +- A: `['🍕', '🍫', '🥑', '🍔']` +- B: `['🍝', '🍫', '🥑', '🍔']` +- C: `['🍝', '🍕', '🍫', '🥑', '🍔']` +- D: `ReferenceError` + +
Jawaban +

+ +#### Jawaban: 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 act 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 + +
Jawaban +

+ +#### Jawaban: 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. Apa yang akan tampil? + +```javascript +let name = 'Lydia'; + +function getName() { + console.log(name); + let name = 'Sarah'; +} + +getName(); +``` + +- A: Lydia +- B: Sarah +- C: `undefined` +- D: `ReferenceError` + +
Jawaban +

+ +#### Jawaban: 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. Apa yang akan tampil? + +```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']` + +
Jawaban +

+ +#### Jawaban: 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. Apa yang akan tampil? + +```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` + +
Jawaban +

+ +#### Jawaban: 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` + +
Jawaban +

+ +#### Jawaban: 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). + +

+
+ +--- + +###### 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 + +
Jawaban +

+ +#### Jawaban: 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. Apa yang akan tampil? + +```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}` + +
Jawaban +

+ +#### Jawaban: 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])` + +
Jawaban +

+ +#### Jawaban: 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. Apa yang akan tampil? + +```javascript +let num = 1; +const list = ['🥳', '🤠', '🥰', '🤪']; + +console.log(list[(num += 1)]); +``` + +- A: `🤠` +- B: `🥰` +- C: `SyntaxError` +- D: `ReferenceError` + +
Jawaban +

+ +#### Jawaban: 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. Apa yang akan tampil? + +```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` + +
Jawaban +

+ +#### Jawaban: 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?.()`: `member` is not defined: `member.getLastName()` is nullish. The expression returns `undefined`. + +

+
+ +--- + +###### 120. Apa yang akan tampil? + +```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` + +
Jawaban +

+ +#### Jawaban: 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. Apa yang akan tampil? + +```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` + +
Jawaban +

+ +#### Jawaban: 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. Apa yang akan tampil? + +```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` + +
Jawaban +

+ +#### Jawaban: 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. Apa yang akan tampil? + +```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` + +
Jawaban +

+ +#### Jawaban: 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. Apa yang akan tampil? + +```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` + +
Jawaban +

+ +#### Jawaban: 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`. + +

+
+ +--- + +###### 125. Apa yang akan tampil? + +```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` + +
Jawaban +

+ +#### Jawaban: 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. Apa yang akan tampil? + +```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 + +
Jawaban +

+ +#### Jawaban: 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 `currentcy` in `USD` results in `$300.00`. + +

+
+ +--- + +###### 127. Apa yang akan tampil? + +```javascript +const spookyItems = ['👻', '🎃', '🕸']; +({ item: spookyItems[3] } = { item: '💀' }); + +console.log(spookyItems); +``` + +- A: `["👻", "🎃", "🕸"]` +- B: `["👻", "🎃", "🕸", "💀"]` +- C: `["👻", "🎃", "🕸", { item: "💀" }]` +- D: `["👻", "🎃", "🕸", "[object Object]"]` + +
Jawaban +

+ +#### Jawaban: 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. Apa yang akan tampil? + +```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` + +
Jawaban +

+ +#### Jawaban: 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. Apa yang akan tampil? + +```javascript +const randomValue = 21; + +function getInfo() { + console.log(typeof randomValue); + const randomValue = 'Lydia Hallie'; +} + +getInfo(); +``` + +- A: `"number"` +- B: `"string"` +- C: `undefined` +- D: `ReferenceError` + +
Jawaban +

+ +#### Jawaban: 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. + +

+
+ +--- + +###### 130. Apa yang akan tampil? + +```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!` + +
Jawaban +

+ +#### Jawaban: 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. Apa yang akan tampil? + +```javascript +const emojis = ['🥑', ['✨', '✨', ['🍕', '🍕']]]; + +console.log(emojis.flat(1)); +``` + +- A: `['🥑', ['✨', '✨', ['🍕', '🍕']]]` +- B: `['🥑', '✨', '✨', ['🍕', '🍕']]` +- C: `['🥑', ['✨', '✨', '🍕', '🍕']]` +- D: `['🥑', '✨', '✨', '🍕', '🍕']` + +
Jawaban +

+ +#### Jawaban: 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. Apa yang akan tampil? + +```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` + +
Jawaban +

+ +#### Jawaban: 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 the `counterTwo.increment()`, which sets the `count` to `3`. Then, we log the count on `counterOne`, which logs `3`. + + + +

+
+ +--- + +###### 133. Apa yang akan tampil? + +```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!` + +
Jawaban +

+ +#### Jawaban: 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.) + +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. + +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!`. + +The next line is the _asynchronous_ `setTimeout` function, from which the callback is sent to the Web API. + +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!` + +

+
+ +--- + +###### 134. How can we invoke `sum` in `index.js` from `sum.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 + +
Jawaban +

+ +#### Jawaban: 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. Apa yang akan tampil? + +```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 + +
Jawaban +

+ +#### Jawaban: C + +With a Proxy object, we can add custom behavior to an object that we pass to it as the second argument. In tis 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. + +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 })` + +
Jawaban +

+ +#### Jawaban: A + +With `Object.seal` we can prevent new properies 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" }` + +
Jawaban +

+ +#### Jawaban: 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. 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" }` + +
Jawaban +

+ +#### Jawaban: 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. + +

+
+ +--- + +###### 139. Apa yang akan tampil? + +```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` + +
Jawaban +

+ +#### Jawaban: 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`. + +

+
+ +--- + +###### 140. Apa yang akan tampil? + +```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` + +
Jawaban +

+ +#### Jawaban: 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! + +

+
+ +--- + +###### 141. Apa yang akan tampil? + +```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)` + +
Jawaban +

+ +#### Jawaban: 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. + +

+
+ +--- + +###### 142. Apa yang akan tampil? + +```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"]` + +
Jawaban +

+ +#### Jawaban: 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 `y`, `"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 `"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. + +After pushing `dancing` and `baking`, the value of `person.hobbies` is `["coding", "dancing", "baking"]` + +

+
+ +--- + +###### 143. Apa yang akan tampil? + +```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 + +
Jawaban +

+ +#### Jawaban: 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. 🦢"`. + +

+
+ +--- + +###### 144. 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 + +
Jawaban +

+ +#### Jawaban: 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 propeties on the `emojis` array can be modified, for example by pushing new values, splicing them, or setting the length of the array to 0. + +

+
+ +--- + +###### 145. 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]() { for (let x in this) yield* Object.values(this) }` +- D: `*[Symbol.iterator]() { for (let x in this) yield this }` + +
Jawaban +

+ +#### Jawaban: 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)`. + +

+
From 4b40fe890d0b16d3317d5d573e0d574284112a89 Mon Sep 17 00:00:00 2001 From: MrHanson Date: Mon, 6 Jan 2020 17:26:00 +0800 Subject: [PATCH 396/915] Translate 112-130 to Chinese --- zh-CN/README-zh_CN.md | 1165 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 1165 insertions(+) diff --git a/zh-CN/README-zh_CN.md b/zh-CN/README-zh_CN.md index 71529582..2c206597 100644 --- a/zh-CN/README-zh_CN.md +++ b/zh-CN/README-zh_CN.md @@ -3573,3 +3573,1168 @@ 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!` 被输出. + +

+
+ +--- + +###### 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. What's the output? + +```javascript +const emojis = ["🥑", ["✨", "✨", ["🍕", "🍕"]]]; + +console.log(emojis.flat(1)); +``` + +- A: `['🥑', ['✨', '✨', ['🍕', '🍕']]]` +- B: `['🥑', '✨', '✨', ['🍕', '🍕']]` +- C: `['🥑', ['✨', '✨', '🍕', '🍕']]` +- D: `['🥑', '✨', '✨', '🍕', '🍕']` + +
Answer +

+ +#### Answer: 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. What's the 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` + +
Answer +

+ +#### Answer: 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 the `counterTwo.increment()`, which sets the `count` to `3`. Then, we log the count on `counterOne`, which logs `3`. + + + +

+
+ +--- + +###### 133. What's the output? + +```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!` + +
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.) + +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. + +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!`. + +The next line is the _asynchronous_ `setTimeout` function, from which the callback is sent to the Web API. + +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!` + +

+
+ +--- + +###### 134. How can we invoke `sum` in `index.js` from `sum.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 + +
Answer +

+ +#### Answer: 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. What's the 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: Nothing gets logged + +
Answer +

+ +#### Answer: C + +With a Proxy object, we can add custom behavior to an object that we pass to it as the second argument. In tis 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. + +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 })` + +
Answer +

+ +#### Answer: A + +With `Object.seal` we can prevent new properies 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" }` + +
Answer +

+ +#### Answer: 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. 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" }` + +
Answer +

+ +#### Answer: 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. + +

+
+ +--- + +###### 139. What's the 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` + +
Answer +

+ +#### 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`. + +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`. + +

+
+ +--- + +###### 140. What's the 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` + +
Answer +

+ +#### 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! + +

+
+ +--- + +###### 141. What's the output? + +```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)` + +
Answer +

+ +#### Answer: 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. + +

+
+ +--- + +###### 142. What's the 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"]` + +
Answer +

+ +#### Answer: 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 `y`, `"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 `"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. + +After pushing `dancing` and `baking`, the value of `person.hobbies` is `["coding", "dancing", "baking"]` + +

+
+ +--- + +###### 143. What's the 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: Nothing, we didn't call any method + +
Answer +

+ +#### Answer: 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. 🦢"`. + +

+
+ +--- + +###### 144. 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 + +
Answer +

+ +#### Answer: 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 propeties on the `emojis` array can be modified, for example by pushing new values, splicing them, or setting the length of the array to 0. + +

+
+ +--- + +###### 145. 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]() { for (let x in this) yield* Object.values(this) }` +- D: `*[Symbol.iterator]() { for (let x in this) yield this }` + +
Answer +

+ +#### Answer: 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)`. + +

+
From 1c0a853a07110630124a38cafb2cb427c6f8d9b1 Mon Sep 17 00:00:00 2001 From: Agung Darmanto Date: Mon, 6 Jan 2020 20:34:07 +0700 Subject: [PATCH 397/915] Translated the question number 144 --- id-ID/README.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/id-ID/README.md b/id-ID/README.md index a5c0becb..7b3425cd 100644 --- a/id-ID/README.md +++ b/id-ID/README.md @@ -4695,7 +4695,7 @@ We create the variable `pet` which is an instance of the `Flamingo` class. When --- -###### 144. Which of the options result(s) in an error? +###### 144. Manakah dari pilihan di bawah ini yang salah? ```javascript const emojis = ['🎄', '🎅🏼', '🎁', '⭐']; @@ -4707,8 +4707,8 @@ const emojis = ['🎄', '🎅🏼', '🎁', '⭐']; ``` - A: 1 -- B: 1 and 2 -- C: 3 and 4 +- B: 1 dan 2 +- C: 3 dan 4 - D: 3
Jawaban @@ -4716,7 +4716,7 @@ const emojis = ['🎄', '🎅🏼', '🎁', '⭐']; #### Jawaban: 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 propeties on the `emojis` array can be modified, for example by pushing new values, splicing them, or setting the length of the array to 0. +Deklarasi `const` pada dasarnya berarti tidak dapat _mengubah_ nilai dari variable tersebut, karena bersifat _read-only (tidak dapat diubah)_. Bagaimanapun, nilainya tidak mutlak. Seperti array pada variable `emojis` dimana nilainya bisa diubah, contohnya untuk menambah nilai array baru, menghilangkan, atau mengubah properti `length` dari array menjadi 0.

From e03a76e49ee096536890f5d3fb73ec918867729b Mon Sep 17 00:00:00 2001 From: MrHanson Date: Mon, 6 Jan 2020 21:42:51 +0800 Subject: [PATCH 398/915] Update the lattest version in Chinese --- zh-CN/README-zh_CN.md | 176 +++++++++++++++++++++--------------------- 1 file changed, 88 insertions(+), 88 deletions(-) diff --git a/zh-CN/README-zh_CN.md b/zh-CN/README-zh_CN.md index 2c206597..17651b44 100644 --- a/zh-CN/README-zh_CN.md +++ b/zh-CN/README-zh_CN.md @@ -2188,8 +2188,8 @@ console.log("🥑" + "💻"); ```javascript function* startGame() { - const answer = yield "Do you love JavaScript?"; - if (answer !== "Yes") { + const 答案 = yield "Do you love JavaScript?"; + if (答案 !== "Yes") { return "Oh wow... Guess we're gone here"; } return "JavaScript loves you back ❤️"; @@ -2210,9 +2210,9 @@ console.log(/* 2 */); // JavaScript loves you back ❤️ #### 答案: C -`generator`函数在遇到`yield`关键字时会“暂停”其执行。 首先,我们需要让函数产生字符串`Do you love JavaScript?`,这可以通过调用`game.next().value`来完成。上述函数的第一行就有一个`yield`关键字,那么运行立即停止了,`yield`表达式本身没有返回值,或者说总是返回`undefined`, 这意味着此时变量 `answer` 为`undefined` +`generator`函数在遇到`yield`关键字时会“暂停”其执行。 首先,我们需要让函数产生字符串`Do you love JavaScript?`,这可以通过调用`game.next().value`来完成。上述函数的第一行就有一个`yield`关键字,那么运行立即停止了,`yield`表达式本身没有返回值,或者说总是返回`undefined`, 这意味着此时变量 `答案` 为`undefined` -`next`方法可以带一个参数,该参数会被当作上一个 `yield` 表达式的返回值。当我们调用`game.next("Yes").value`时,先前的 `yield` 的返回值将被替换为传递给`next()`函数的参数`"Yes"`。此时变量 `answer` 被赋值为 `"Yes"`,`if`语句返回`false`,所以`JavaScript loves you back ❤️`被打印。 +`next`方法可以带一个参数,该参数会被当作上一个 `yield` 表达式的返回值。当我们调用`game.next("Yes").value`时,先前的 `yield` 的返回值将被替换为传递给`next()`函数的参数`"Yes"`。此时变量 `答案` 被赋值为 `"Yes"`,`if`语句返回`false`,所以`JavaScript loves you back ❤️`被打印。

@@ -4184,7 +4184,7 @@ const myPromise = Promise.resolve("Woah some cool data"); --- -###### 131. What's the output? +###### 131. 输出什么? ```javascript const emojis = ["🥑", ["✨", "✨", ["🍕", "🍕"]]]; @@ -4197,19 +4197,19 @@ console.log(emojis.flat(1)); - C: `['🥑', ['✨', '✨', '🍕', '🍕']]` - D: `['🥑', '✨', '✨', '🍕', '🍕']` -
Answer +
答案

-#### Answer: B +#### 答案: 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 `['🥑', '✨', '✨', ['🍕', '🍕']]`. +通过方法 `flat`, 我们可以创建一个新的, 已被扁平化的数组。被扁平化的深度取决于我们传递的值。在这个case里,我们传递了值 `1` (并不必要,这是默认值),相当于只有第一层的数组才会被连接。即这个 case 里的 `['🥑']` and `['✨', '✨', ['🍕', '🍕']]`。连接这两个数组得到结果 `['🥑', '✨', '✨', ['🍕', '🍕']]`.

--- -###### 132. What's the output? +###### 132. 输出什么? ```javascript class Counter { @@ -4237,18 +4237,18 @@ console.log(counterOne.count); - C: `2` - D: `3` -
Answer +
答案

-#### Answer: D +#### 答案: 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`. +`counterOne` 是类 `Counter` 的一个实例。类 Counter 包含一个`count` 属性在它的构造函数里, 和一个 `increment` 方法。首先,我们通过 `counterOne.increment()` 调用方法 `increment` 两次。现在, `counterOne.count` 为 `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`. +然后,我们创建一个新的变量 `counterTwo` 并将 `counterOne` 的引用地址赋值给它。因为对象受引用地址的影响,我们刚刚创建了一个新的对象,其引用地址和 `counterOne` 的等价。因此它们指向同一块内存地址,任何对其的副作用都会影响 `counterTwo`。现在 `counterTwo.count` 为 `2`。 -We invoke the `counterTwo.increment()`, which sets the `count` to `3`. Then, we log the count on `counterOne`, which logs `3`. +我们调用 `counterTwo.increment()` 将 `count` 的值设为 `3`。然后,我们打印 `counterOne` 里的count,结果为 `3`。 @@ -4257,7 +4257,7 @@ We invoke the `counterTwo.increment()`, which sets the `count` to `3`. Then, we --- -###### 133. What's the output? +###### 133. 输出什么? ```javascript const myPromise = Promise.resolve(Promise.resolve("Promise!")); @@ -4284,27 +4284,27 @@ funcTwo(); - C: `Promise! Last line! Last line! Promise! Timeout! Timeout!` - D: `Last line! Promise! Promise! Last line! Timeout! Timeout!` -

Answer +
答案

-#### Answer: D +#### 答案: 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.) +首先,我们调用 `funcOne`。在函数 `funcOne` 的第一行,我们调用`myPromise` promise _异步操作_。当JS引擎在忙于执行 promise,它继续执行函数 `funcOne`。下一行 _异步操作_ `setTimeout`,其回调函数被 Web API 调用。 (详情请参考我关于event loop的文章.) -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. +promise 和 timeout 都是异步操作,函数继续执行当JS引擎忙于执行promise 和 处理 `setTimeout` 的回调。相当于 `Last line!` 首先被输出, 因为它不是异步操作。执行完 `funcOne` 的最后一行,promise 状态转变为 resolved,`Promise!` 被打印。然而,因为我们调用了 `funcTwo()`, 调用栈不为空,`setTimeout` 的回调仍不能入栈。 -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!`. +我们现在处于 `funcTwo`,先 _awaiting_ myPromise。通过 `await` 关键字, 我们暂停了函数的执行直到 promise 状态变为 resolved (或 rejected)。然后,我们输出 `res` 的 awaited 值(因为 promise 本身返回一个 promise)。 接着输出 `Promise!`。 -The next line is the _asynchronous_ `setTimeout` function, from which the callback is sent to the Web API. +下一行就是 _异步操作_ `setTimeout`,其回调函数被 Web API 调用。 -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!` +我们执行到函数 `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. How can we invoke `sum` in `index.js` from `sum.js?` +###### 134. 我们怎样才能在 `index.js` 中调用 `sum.js?` 中的 `sum`? ```javascript // sum.js @@ -4319,14 +4319,14 @@ 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 +- D: 默认导出不用 `*` 来导入,只能具名导出 -
Answer +
答案

-#### Answer: C +#### 答案: 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 @@ -4339,7 +4339,7 @@ import * as info from "./info"; console.log(info); ``` -The following would get logged: +将会输出以下内容: ```javascript { @@ -4349,20 +4349,20 @@ The following would get logged: } ``` -For the `sum` example, it means that the imported value `sum` looks like this: +以 `sum` 为例,相当于以下形式引入值 `sum`: ```javascript { default: function sum(x) { return x + x } } ``` -We can invoke this function, by calling `sum.default` +我们可以通过调用 `sum.default` 来调用该函数

--- -###### 135. What's the output? +###### 135. 输出什么? ```javascript const handler = { @@ -4379,27 +4379,27 @@ person.name; - A: `Added a new property!` - B: `Accessed a property!` - C: `Added a new property!` `Accessed a property!` -- D: Nothing gets logged +- D: 没有任何输出 -
Answer +
答案

-#### Answer: C +#### 答案: C -With a Proxy object, we can add custom behavior to an object that we pass to it as the second argument. In tis 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. +使用 Proxy 对象,我们可以给一个对象添加自定义行为。在这个 case,我们传递一个包含以下属性的对象 `handler` : `set` and `get`。每当我门 _设置_ 属性值时 `set` 被调用,每当我们 _获取_ 时 `get` 被调用。 -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. +第一个参数是一个空对象 `{}`,作为 `person` 的值。对于这个对象,自定义行为被定义在对象 `handler`。如果我们向对象 `person` 添加属性,`set` 将被调用。如果我们获取 `person` 的属性, `get` 将被调用。 -First, we added a new property `name` to the proxy object (`person.name = "Lydia"`). `set` gets invoked, and logs `"Added a new property!"`. +首先,我们向 proxy 对象(`person.name = "Lydia"`)添加一个属性 `name`。`set` 被调用并输出 `"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. +然后,我们获取 proxy 对象的一个属性,对象 handler 的属性 `get` 被调用。输出 `"Accessed a property!"`。

--- -###### 136. Which of the following will modify the `person` object? +###### 136. 以下哪一项会对对象 `person` 有副作用? ```javascript const person = { name: "Lydia Hallie" }; @@ -4412,21 +4412,21 @@ Object.seal(person); - C: `delete person.name` - D: `Object.assign(person, { age: 21 })` -
Answer +
答案

-#### Answer: A +#### 答案: A -With `Object.seal` we can prevent new properies from being _added_, or existing properties to be _removed_. +使用 `Object.seal` 我们可以防止新属性 _被添加_,或者存在属性 _被移除_. -However, you can still modify the value of existing properties. +然而,你仍然可以对存在属性进行更改。

--- -###### 137. Which of the following will modify the `person` object? +###### 137. 以下哪一项会对对象 `person` 有副作用? ```javascript const person = { @@ -4444,21 +4444,21 @@ Object.freeze(person); - C: `person.address.street = "101 Main St"` - D: `person.pet = { name: "Mara" }` -
Answer +
答案

-#### Answer: C +#### 答案: C -The `Object.freeze` method _freezes_ an object. No properties can be added, modified, or removed. +使用方法 `Object.freeze` 对一个对象进行 _冻结_。不能对属性进行添加,修改,删除。 -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. +然而,它仅 对对象进行 _浅_ 冻结,意味着只有 对象中的 _直接_ 属性被冻结。如果属性是另一个 object,像案例中的 `address`,`address` 中的属性没有被冻结,仍然可以被修改。

--- -###### 138. Which of the following will modify the `person` object? +###### 138. 以下哪一项会对对象 `person` 有副作用? ```javascript const person = { @@ -4476,21 +4476,21 @@ Object.freeze(person); - C: `person.address.street = "101 Main St"` - D: `person.pet = { name: "Mara" }` -
Answer +
答案

-#### Answer: C +#### 答案: C -The `Object.freeze` method _freezes_ an object. No properties can be added, modified, or removed. +使用方法 `Object.freeze` 对一个对象进行 _冻结_。不能对属性进行添加,修改,删除。 -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. +然而,它仅 对对象进行 _浅_ 冻结,意味着只有 对象中的 _直接_ 属性被冻结。如果属性是另一个 object,像案例中的 `address`,`address` 中的属性没有被冻结,仍然可以被修改。

--- -###### 139. What's the output? +###### 139. 输出什么? ```javascript const add = x => x + x; @@ -4508,21 +4508,21 @@ myFunc(3); - C: `2` `Error` and `3` `6` - D: `2` `4` and `3` `Error` -
Answer +
答案

-#### Answer: A +#### 答案: 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`. +首先我们不传递任何参数调用 `myFunc()`。因为我们没有传递参数,`num` 和 `value` 获取它们各自的默认值:num 为 `2`, 而 `value` 为函数 `add` 的返回值。对于函数 `add`,我们传递值为2的 `num` 作为参数。函数 `add` 返回 `4` 作为 `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`. +然后,我们调用 `myFunc(3)` 并传递值 `3` 参数 `num` 的值。我们没有给 `value` 传递值。因为我们没有给参数 `value` 传递值,它获取默认值:函数 `add` 的返回值。对于函数 `add`,我们传递值为3的 `num`给它。函数 `add` 返回 `6` 作为 `value` 的值。

--- -###### 140. What's the output? +###### 140. 输出什么? ```javascript class Counter { @@ -4548,19 +4548,19 @@ console.log(counter.#number) - C: `undefined` - D: `SyntaxError` -
Answer +
答案

-#### Answer: D +#### 答案: 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! +在 ES2020 中,通过 `#` 我们可以给 class 添加私有变量。在 class 的外部我们无法获取该值。当我们尝试输出 `counter.#number`,语法错误被抛出:我们无法在 class `Counter` 外部获取它!

--- -###### 141. What's the output? +###### 141. 选择哪一个? ```javascript const teams = [ @@ -4590,21 +4590,21 @@ obj.next(); // { value: "Lisa", done: false } - C: `return getMembers(teams[i].members)` - D: `return yield getMembers(teams[i].members)` -
Answer +
答案

-#### Answer: B +#### 答案: 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*`. +为了遍历 `teams` 数组中对象的属性 `members` 中的每一项,我们需要将 `teams[i].members` 传递给 Generator 函数 `getMembers`。Generator 函数返回一个 generator 对象。为了遍历这个 generator 对象中的每一项,我们需要使用 `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. +如果我们没有写 `yield`,`return yield` 或者 `return`,整个 Generator 函数不会第一时间 return 当我们调用 `next` 方法.

--- -###### 142. What's the output? +###### 142. 输出什么? ```javascript const person = { @@ -4629,27 +4629,27 @@ console.log(person.hobbies); - C: `["coding", "dancing", "baking"]` - D: `["coding", "running", "dancing", "baking"]` -
Answer +
答案

-#### Answer: C +#### 答案: C -The `addHobby` function receives two arguments, `hobby` and `hobbies` with the default value of the `hobbies` array on the `person` object. +函数 `addHobby` 接受两个参数,`hobby` 和有着对象 `person` 中数组 `hobbies` 默认值的 `hobbies`。 -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. +首相,我们调用函数 `addHobby`,并给 `hobby` 传递 `"running"` 以及给 `hobbies` 传递一个空数组。因为我们给 `hobbies` 传递了空数组,`"running"` 被添加到这个空数组。 -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. +然后,我们调用函数 `addHobby`,并给 `hobby` 传递 `"dancing"`。我们不向 `hobbies` 传递值,因此它获取其默认值 —— 对象 `person` 的 属性 `hobbies`。我们向数组 `person.hobbies` push `dancing`。 -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. +最后,我们调用函数 `addHobby`,并向 `hobby` 传递 值 `"bdaking"`,并且向 `hobbies` 传递 `person.hobbies`。我们向数组 `person.hobbies` push `dancing`。 -After pushing `dancing` and `baking`, the value of `person.hobbies` is `["coding", "dancing", "baking"]` +pushing `dancing` 和 `baking` 之后,`person.hobbies` 的值为 `["coding", "dancing", "baking"]`

--- -###### 143. What's the output? +###### 143. 输出什么? ```javascript class Bird { @@ -4673,19 +4673,19 @@ const pet = new Flamingo(); - C: `I'm a bird. 🦢` `I'm pink. 🌸` - D: Nothing, we didn't call any method -
Answer +
答案

-#### Answer: B +#### 答案: 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. 🦢"`. +我们创建了类 `Flamingo` 的实例 `pet`。当我们实例化这个实例,`Flamingo` 中的 `constructor` 被调用。首相,输出 `"I'm pink. 🌸"`, 之后我们调用`super()`。`super()` 调用父类的构造函数,`Bird`。`Bird` 的构造函数被调用,并输出 `"I'm a bird. 🦢"`。

--- -###### 144. Which of the options result(s) in an error? +###### 144. 哪一个选项会导致报错? ```javascript const emojis = ["🎄", "🎅🏼", "🎁", "⭐"]; @@ -4701,19 +4701,19 @@ const emojis = ["🎄", "🎅🏼", "🎁", "⭐"]; - C: 3 and 4 - D: 3 -
Answer +
答案

-#### Answer: D +#### 答案: 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 propeties on the `emojis` array can be modified, for example by pushing new values, splicing them, or setting the length of the array to 0. +`const` 关键字意味着我们不能 _重定义_ 变量中的值,它 _仅可读_。而然,值本身不可修改。数组 `emojis` 中的值可被修改,如 push 新的值, 拼接,又或者将数组的长度设置为0。

--- -###### 145. What do we need to add to the `person` object to get `["Lydia Hallie", 21]` as the output of `[...person]`? +###### 145. 我们需要向对象 `person` 添加什么,以致执行 `[...person]` 时获得形如 `["Lydia Hallie", 21]` 的输出? ```javascript const person = { @@ -4724,17 +4724,17 @@ const person = { [...person] // ["Lydia Hallie", 21] ``` -- A: Nothing, object are iterable by default +- 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 }` -
Answer +
答案

-#### Answer: C +#### 答案: 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)`. +对象默认并不是可迭代的。如果迭代规则被定义,则一个对象是可迭代的(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`。

From 0ded24dcb6c48d37f828bedbb5bf5d88a58641cc Mon Sep 17 00:00:00 2001 From: shoheihagiwara Date: Tue, 7 Jan 2020 21:43:45 +0900 Subject: [PATCH 399/915] Fix URLs for LinkedIn page and blog. --- README.md | 2 +- en-EN/README.md | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index d3d60814..1d9e5c4e 100644 --- a/README.md +++ b/README.md @@ -9,7 +9,7 @@ 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! 😊
- Instagram || Twitter || LinkedIn || Blog + Instagram || Twitter || LinkedIn || Blog
--- diff --git a/en-EN/README.md b/en-EN/README.md index ddf67054..437e80c8 100644 --- a/en-EN/README.md +++ b/en-EN/README.md @@ -9,7 +9,7 @@ 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! 😊
- Instagram || Twitter || LinkedIn || Blog + Instagram || Twitter || LinkedIn || Blog
--- @@ -4743,4 +4743,4 @@ const person = { 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)`.

- \ No newline at end of file + From 44446b8a068f5722e9431afd6fde0b9f739ccd89 Mon Sep 17 00:00:00 2001 From: Yuda Ferry Mahendra Date: Wed, 8 Jan 2020 14:04:33 +0700 Subject: [PATCH 400/915] translate pertanyaan nomor 1 --- id-ID/README.md | 17 ++++++----------- 1 file changed, 6 insertions(+), 11 deletions(-) diff --git a/id-ID/README.md b/id-ID/README.md index a5c0becb..2f010dd1 100644 --- a/id-ID/README.md +++ b/id-ID/README.md @@ -1,15 +1,11 @@ -
- -

Pertanyaan JavaScript

+

Pertannyaan JavaScript

---- + --- -Saya menerbitkan beberapa pilihan pertanyaan Javascript di akun Instagram Story [Instagram](https://www.instagram.com/theavocoder), yang mana diterbitkan disini juga! Terakhir diperbaharui: 24 Desember + Saya post pertanyaan pilihan ganda ke [Instagram](https://www.instagram.com/theavocoder) **stories** saya, yang saya post juga di sini ! update terakhir: December 24th -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: -Dari tingkat dasar sampai tingkat lanjut: Menguji seberapa jago Anda di JavaScript, asah pengetahuan Anda, atau untuk persiapan interview tentang pemrograman! :muscle: :rocket: Saya akan memperbaharui jawaban di bagian yang tertutup di bawah pertanyaan, sederhananya tinggal di klik saja yang nantinya jawaban akan muncul disana. Ini hanya untuk bersenang - senang saja, 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: -Feel free to reach out to me! 😊
Jangan sungkan untuk terhubung dengan saya! 😊
Instagram || Twitter || LinkedIn || Blog @@ -66,10 +62,9 @@ sayHi(); #### Jawaban: D -Within the function, we first declare the `name` variable with the `var` keyword. This means that the variable gets hoisted (memory space is set up during the creation phase) with the default value of `undefined`, until we actually get to the line where we define the variable. We haven't defined the variable yet on the line where we try to log the `name` variable, so it still holds the value of `undefined`. - -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`. +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` +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`.

From 017c5479ea14bf70a7ed5bd95e4c138a16c84f91 Mon Sep 17 00:00:00 2001 From: Yuda Ferry Mahendra Date: Wed, 8 Jan 2020 14:08:58 +0700 Subject: [PATCH 401/915] translate pertanyaan nomor 1 --- id-ID/README.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/id-ID/README.md b/id-ID/README.md index 2f010dd1..5e25228f 100644 --- a/id-ID/README.md +++ b/id-ID/README.md @@ -52,10 +52,10 @@ function sayHi() { sayHi(); ``` -- A: `Lydia` and `undefined` -- B: `Lydia` and `ReferenceError` -- C: `ReferenceError` and `21` -- D: `undefined` and `ReferenceError` +- A: `Lydia` dan `undefined` +- B: `Lydia` dan `ReferenceError` +- C: `ReferenceError` dan `21` +- D: `undefined` dan `ReferenceError`
Jawaban

From b02a4b33c4f9ee5f6168a84081fc3557058afff6 Mon Sep 17 00:00:00 2001 From: nobody <411298027@qq.com> Date: Wed, 8 Jan 2020 19:21:44 +0800 Subject: [PATCH 402/915] fix: zh_CN question 52 typo problem --- 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 443f5cd9..d2ecef8e 100644 --- a/zh-CN/README-zh_CN.md +++ b/zh-CN/README-zh_CN.md @@ -1553,7 +1553,7 @@ function sayHi() { const data = greeting(); console.log("It worked!", data); } catch (e) { - console.log("Oh no an error!", e); + console.log("Oh no an error:", e); } } From c8e8ec197a1a4fad45301d197e50d582f8e65f1f Mon Sep 17 00:00:00 2001 From: Askie Lin Date: Wed, 8 Jan 2020 19:39:37 +0800 Subject: [PATCH 403/915] [Feat] Create zh-TW version and contain questions 1-15 --- README.md | 3 +- zh-TW/README_zh-TW.md | 478 ++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 480 insertions(+), 1 deletion(-) create mode 100644 zh-TW/README_zh-TW.md diff --git a/README.md b/README.md index d3d60814..42e74ed5 100644 --- a/README.md +++ b/README.md @@ -30,7 +30,8 @@ * [Русский](./ru-RU/README.md) * [Українська мова](./ua-UA/README-ua_UA.md) * [Tiếng Việt](./vi-VI/README-vi.md) -* [中文版本](./zh-CN/README-zh_CN.md) +* [简体中文](./zh-CN/README-zh_CN.md) +* [繁體中文](./zh-TW/README_zh-TW.md) * [Türkçe](./tr-TR/README-tr_TR.md) * [ไทย](./th-TH/README-th_TH.md) diff --git a/zh-TW/README_zh-TW.md b/zh-TW/README_zh-TW.md new file mode 100644 index 00000000..d30a0b92 --- /dev/null +++ b/zh-TW/README_zh-TW.md @@ -0,0 +1,478 @@ +

+ +

JavaScript 進階題目列表

+ + --- + + 我會在我的 [Instagram](https://www.instagram.com/theavocoder) 上發布關於 JavaScript 的複選題,同時也會更新到這個 Repo 當中。更新日期: 2019 年 12 月 24 日 + + 從基礎到進階程度,測試你有多了解 JavaScript,不僅更新你的知識,更能幫助你的 coding 面試! +:muscle: :rocket: 我每週都會在這個 Repo 中更新新的題目。 + +答案在題目下方的摺疊區塊,點擊即可展開答案。祝你好運 :heart: + + 歡迎和我聯繫!😊
+ Instagram || Twitter || LinkedIn || Blog +
+ + +--- + +###### 1. 將會輸出什麽內容? + +```javascript +function sayHi() { + console.log(name) + console.log(age) + var name = 'Lydia' + let age = 21 +} + +sayHi() +``` + +- A: `Lydia` 和 `undefined` +- B: `Lydia` 和 `ReferenceError` +- C: `ReferenceError` 和 `21` +- D: `undefined` 和 `ReferenceError` + +
答案 +

+ +#### 答案: D + +在函式內部,我們首先透過 `var` 關鍵字宣告了 `name` 變數。這表示變數被提升了(記憶體位置在創建時期就被設置好了),直到程式執行到定義變數的那行之前,預設值都是 `undefined`。因為當我們印出 `name` 變數時,還沒有執行到定義變數的那一行程式碼,因此變數的值保持為 `undefined`。 + +透過 `let` 和 `const` 關鍵字宣告的變數也會提升,但是和 `var` 不同,它們不會被初始化,在我們初始化之前是不能訪問它們的,這個行為被稱之為暫時性死區。當我們嘗試在初始化之前訪問它們時,JavaScript 將會抛出一個 `ReferenceError` 錯誤。 + +

+
+ +--- + +###### 2. 將會輸出什麽內容? + +```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` 和 `0 1 2` +- B: `0 1 2` 和 `3 3 3` +- C: `3 3 3` 和 `0 1 2` + +
答案 +

+ +#### 答案: C + +由於 JavaScript 的事件佇列(Event Queue),`setTimeout` 的 `callback` 會在*遍歷結束後*才執行。因為在第一個迴圈中,遍歷 `i` 是透過 `var` 關鍵字宣告的,`var` 屬於 Function scope(需要用 `function() {}` 才能將值鎖在作用域裡面) +,所以 `for` 迴圈會造成變數外流,變成全域變數。在遍歷過程中,我們透過一元運算子 `++` 來遞增 `i` 的值。當 `setTimeout` 的 `callback` 執行的時候,`i` 的值等於 3。 + +在第二個迴圈中,遍歷 `i` 是透過 `let` 關鍵字宣告的:透過 `let` 和 `const` 關鍵字的變數擁有塊級作用域(指的是任何在 `{}` 中的内容)。在每次的遍歷過程中,`i` 都有一個新值,每次遍歷時 `i` 值的作用域都在迴圈内。 + +

+
+ +--- + +###### 3. 將會輸出什麽內容? + +```javascript +const shape = { + radius: 10, + diameter() { + return this.radius * 2 + }, + perimeter: () => 2 * Math.PI * this.radius +} + +shape.diameter() +shape.perimeter() +``` + +- A: `20` and `62.83185307179586` +- B: `20` and `NaN` +- C: `20` and `63` +- D: `NaN` and `63` + +
答案 +

+ +#### 答案: B + +注意 `diameter` 的值是一個一般的函式,但是 `perimeter` 的值是一個箭頭函式。 + +對於箭頭函式,`this` 關鍵字指向的是它當前周圍作用域,這個行為和一般函式不同。這表示當我們呼叫 `perimeter` 時,`this` 不是指向 `shape` 物件,而是它的周圍作用域(在範例中是 `window`)。 + +在 `window` 中沒有 `radius` 這個屬性,因此回傳 `undefined`。 + +

+
+ +--- + +###### 4. 將會輸出什麽內容? + +```javascript ++true; +!"Lydia"; +``` + +- A: `1` and `false` +- B: `false` and `NaN` +- C: `false` and `false` + +
答案 +

+ +#### 答案: A + +一元運算子加號 `+`,嘗試將 boolean 布林值型別轉為 number 數字型別。`true` 轉為 number 數字型別的話為 `1`,`false` 爲 `0`。 + +字串型別 `'Lydia'` 是一個真值,我們實際上問的題目是:「這個真值的相反會是什麼?」,真值的相反,將得到 `false`。 + +

+ +
+ +--- + +###### 5. 哪一個是正確的描述? + +```javascript +const bird = { + size: 'small' +} + +const mouse = { + name: 'Mickey', + small: true +} +``` + +- A: `mouse.bird.size`是無效的 +- B: `mouse[bird.size]`是無效的 +- C: `mouse[bird["size"]]`是無效的 +- D: 以上三個選項都是有效的 + +
答案 +

+ +#### 答案: A + +在 JavaScript 中,所有物件的 keys 都是字串型別(除非是 Symbol 物件)。儘管我們或許不會定義它們為字串,但它們在底層總會被轉換爲字串。 + +當我們使用中括號時([]),JavaScript 會解譯語句。它首先看到中括號的第一個開始處 `[` 並繼續往下直到找到結束的中括號 `]`。只有這樣,它才能計算語句的值。 + +`mouse[bird.size]`:首先計算 `bird.size`,這會得到 `small`。`mouse["small"]` 得到 `true`。 + +使用點的語法的時候,上面這一切都不會發生。`mouse` 沒有 `bird` 這個 key,這就表示 `mouse.bird` 是 `undefined`。然後當我們使用點語法 `mouse.bird.size` 時,因為 `mouse.bird` 是 `undefined`,這也就變成了我們實際的語句是 `undefined.size`,而此行為是無效的,並會抛出一個錯誤 `Cannot read property "size" of undefined`。 + +

+
+ +--- + + +###### 6. 將會輸出什麽內容? + +```javascript +let c = { greeting: 'Hey!' } +let d + +d = c +c.greeting = 'Hello' +console.log(d.greeting) +``` + +- A: `Hello` +- B: `undefined` +- C: `ReferenceError` +- D: `TypeError` + +
答案 +

+ +#### 答案: A + +在 JavaScript 中,當設定兩個物件彼此相等時,它們會經由*引用(reference)*進行互動。 + +首先,變數 `c` 的值是一個物件。接下来,我們將 `d` 分配了一個和 `c` 物件相同的引用。 + + + +因此當我們改變其中一個物件時,其實是改變了所有的物件的同一個引用的內容。 + +

+
+ +--- + +###### 7. 將會輸出什麽內容? + +```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` + +
答案 +

+ +#### 答案: C + +`new Number()` 是一個内建的函式建構子。它雖然看起來像是個 number,但它實際上並非真正的 number:它有一堆額外的功能,而且它是一個物件。 + +當我們使用 `==` 運算子的時候,它只會檢查兩者是否擁有有相同的*值*。因為它們的值都是 `3`,因此回傳 `true`。 + +然後,當我們使用 `===` 運算子時,兩者的值以及*型別*都必須是相同的。`new Number()` 是一個物件型別而不是 number(一般型別),因此回傳 `false`。 + +

+
+ +--- + +###### 8. 將會輸出什麽內容? + +```javascript +class Chameleon { + 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` + +
答案 +

+ +#### 答案: D + +`colorChange` 是一個靜態方法。靜態方法被設計爲只能被創造它們的建構子使用(也就是 `Chameleon` 中的 `constructor` ),並且不能傳遞給實例。因為 `freddie` 是一個實例,而靜態方法不能被實例使用,因此會抛出 `TypeError` 錯誤。 + +

+
+ +--- + +###### 9. 將會輸出什麽內容? + +```javascript +let greeting +greetign = {} // 手殘打錯變數名稱! +console.log(greetign) +``` + +- A: `{}` +- B: `ReferenceError: greetign is not defined` +- C: `undefined` + +
答案 +

+ +#### 答案: A + +程式碼印出了一個物件,這是因為我們在全域物件上創建了一個空物件!當我們將 `greeting` 寫錯成 `greetign` 時,JS 解譯器實際上將它視爲 `global.greetign = {}` (或者在瀏覽器中視為 `window.greetign = {}`)。 + +為了避免這個狀況,我們可以使用 `"use strict"`,來確保當你宣告變數時,必須賦值。 + +

+
+ +--- + +###### 10. 當我們這麼做時,會發生什麼事? + +```javascript +function bark() { + console.log('Woof!') +} + +bark.animal = 'dog' +``` + +- A: 正常運作! +- B: `SyntaxError`. 你不能透過這種方式在函式中新增屬性。 +- C: `undefined` +- D: `ReferenceError` + +
答案 +

+ +#### 答案: A + +這在 JavaScript 中是可以的,因爲函式是物件!(除了基本型別之外其他都是物件) + +函式是一個特殊的物件,函式是一個擁有屬性的物件,屬性也可被使用、呼叫的。 + +

+
+ +--- + +###### 11. 將會輸出什麽內容? + +```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` + +
答案 +

+ +#### 答案: A + +你可以為一般物件新增屬性,但建構函式(constructor)無法透過上面的方式來新增屬性。若你想一次性在所有實例上都新增某個屬性,要使用原型的方式。因此本例中,使用以下的方式: + +```js +Person.prototype.getFullName = function () { + return `${this.firstName} ${this.lastName}`; +} +``` + +這樣一來, `member.getFullName()` 就能有效。這樣做有什麼好處?假設我們真的能如題將這個方法新增到建構函式本身,並不是每個 `Person` 實例都需要這個方法,但每個實例卻仍然擁有該属性,代表著這將佔據每個實例的記憶體,造成大量的記憶體空間因此浪費掉了。相反,如果我們只將它新增在原型中,那麼它只存在記憶體中的一個位置,而所有實例都可以使用它! + +

+
+ +--- + +###### 12. 將會輸出什麽內容? + +```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` + +
答案 +

+ +#### 答案: A + +對 `sarah` 而言,我們沒有使用 `new` 關鍵字。當使用 `new` 時,`this` 引用我們建立的空物件。沒有使用 `new` 的時候,`this` 引用的是**全域物件**(global object)。 + +我們會說 `this.firstName` 等於 `"Sarah"`,而 `this.lastName` 等於 `"Smith"`。實際上我們做的是,定義了 `global.firstName = 'Sarah'` 和 `global.lastName = 'Smith'`。而 `sarah` 本身是 `undefined`,因為 `Person` 這個函式本身並沒有回傳值。 + +

+
+ +--- + +###### 13. 事件傳播的三個階段分別是? + +- A: Target > Capturing > Bubbling +- B: Bubbling > Target > Capturing +- C: Target > Bubbling > Capturing +- D: Capturing > Target > Bubbling + +
答案 +

+ +#### 答案: D + +先捕獲,再冒泡!在**捕獲**(capturing)階段中,事件從祖先元素向下傳播到目標元素。當事件到達**目標**(target)元素後,**冒泡**(bubbling)才開始。 + + + +

+
+ +--- + +###### 14. 所有物件都有原型。 + +- A: true +- B: false + +
答案 +

+ +#### 答案: B + +除了**基本物件**(base object,使用 `new` 關鍵字建立的物件)以外,所有物件都有原型。基本物件可以使用一些方法和属性,比如 `.toString`,這就是為什麼你可以使用內建的 JavaScript 方法!所有這類在原型上的方法都是可被使用的。雖然 JavaScript 不能直接在物件上找到這些方法,但 JavaScript 會沿著原型鍊找到它們,以便使用。 + +

+
+ +--- + +###### 15. 將會輸出什麽內容? + +```javascript +function sum(a, b) { + return a + b +} + +sum(1, '2') +``` + +- A: `NaN` +- B: `TypeError` +- C: `"12"` +- D: `3` + +
答案 +

+ +#### 答案: C + +JavaScript 是一個**動態型別語言**:我們不指定變數的型別。值可以在你不知道的情况下自動轉換成另一種型別,稱為**隱含式轉型**(implicit type coercion)。**Coercion** 是指將一種型別轉換成另一種型別。 + +在此範例中,JavaScript 將數字型別 `1` 轉換為字串型別,以便函式能回傳一個有意義的值。數字型別(`1`)和字串型別(`'2'`)相加的時候,該數字會被視為字串。我們也能連接不同的字串,比如 `"Hello" + "World"`,而此例是 `"1" + "2"`,它將回傳 `"12"`。 + +

+
\ No newline at end of file From f427846eaa30ab824ff418192ce3b5206113eb81 Mon Sep 17 00:00:00 2001 From: Do Trung Kien Date: Thu, 9 Jan 2020 15:46:51 +0700 Subject: [PATCH 404/915] translate next 10 question (102-111) into Vietnamese --- vi-VI/README-vi.md | 1513 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 1513 insertions(+) diff --git a/vi-VI/README-vi.md b/vi-VI/README-vi.md index 36ddfb77..02a8d87b 100644 --- a/vi-VI/README-vi.md +++ b/vi-VI/README-vi.md @@ -3220,3 +3220,1516 @@ 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!') + +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` và `I have resolved!`, `second` +- B: `second`, `I have resolved!` và `second`, `I have resolved!` +- C: `I have resolved!`, `second` và `second`, `I have resolved!` +- D: `second`, `I have resolved!` và `I have resolved!`, `second` + +
Đáp án +

+ +#### Đáp án: D + +Có thể tưởng tượng đơn giản cách promise thực thi như sau: _bây giờ tôi sẽ để tạm nó sang một bên vì nó tính toán mất thời gian. Chỉ khi nào nó được hoàn thành (resolved) hay bị hủy bỏ (rejected) hay khi call stack trở nên rỗng thì tôi sẽ lấy giá trị trả về ra._ + +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. + +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`. + +

+
+ +--- + +###### 103. Output là gì? + +```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 án +

+ +#### Đá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 đầ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ứ 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"`. + +

+
+ +--- + +###### 104. Output là gì? + +```javascript +Promise.resolve(5) +``` + +- A: `5` +- B: `Promise {: 5}` +- C: `Promise {: 5}` +- D: `Error` + +
Đáp án +

+ +#### Đáp án: C + +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`. + +

+
+ +--- + +###### 105. Output là gì? + +```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 án +

+ +#### Đá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. + +We set the default value for `person2` equal to the `person` object, and passed the `person` object as the value for `person1`. +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`. + +Điều đó có nghĩa là chúng cùng trỏ đến một object trong bộ nhớ, do đó chúng bằng nhau, và `They are the same!` được in ra. + +

+
+ +--- + +###### 106. Output là gì? + +```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 án +

+ +#### Đá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"]`). + +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`. + +

+
+ +--- + +###### 107. Ouput là gì? + +```javascript +console.log('❤️' === '❤️') +``` + +- A: `true` +- B: `false` + +
Đáp án +

+ +#### Đá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`. + +

+
+ +--- + +###### 108. Phép toán nào sau đây làm thay đổi mảng gốc? + +```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 án +

+ +#### Đá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. + +`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. + +

+
+ +--- + +###### 109. Output là gì? + +```javascript +const food = ['🍕', '🍫', '🥑', '🍔'] +const info = { favoriteFood: food[0] } + +info.favoriteFood = '🍝' + +console.log(food) +``` + +- A: `['🍕', '🍫', '🥑', '🍔']` +- B: `['🍝', '🍫', '🥑', '🍔']` +- C: `['🍝', '🍕', '🍫', '🥑', '🍔']` +- D: `ReferenceError` + +
Đáp án +

+ +#### Đáp án: A + +Trong Javascript tất cả các kiểu cơ bản (mọi thứ không phải object) đều tương tác bằng _giá trị_. Chúng ta set giá trị của thuộc tính `favoriteFood` trong object `info` bằng ký tự bánh pizza, `'🍕'`. Chuỗi trong javascript là một kiểu cơ bản, nên nó cũng sẽ tương tác bằng giá trị. + +Bản thân mảng `food` không hề thay đổi, do giá trị của `favoriteFood` chỉ là một bản _copy_ của giá trị đầu tiên trong mảng mà thôi, và không hề trỏ tới reference của `food[0]`. Do đó khi ghi ra, giá trị của mảng vẫn là giá trị ban đầu, `['🍕', '🍫', '🥑', '🍔']`. + +

+
+ +--- + +###### 110. Phép toán này dùng để làm gì? + +```javascript +JSON.parse() +``` + +- A: Parse JSON thành một giá trị JavaScript +- B: Parse một JavaScript object thành JSON +- C: Parse giá trị JavaScript bất kì thành JSON +- D: Parse JSON thành một JavaScript object + +
Đáp án +

+ +#### Đá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í 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 + +// 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] + +// 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' } +``` + +

+
+ +--- + +###### 111. Ouput là gì? + +```javascript +let name = 'Lydia' + +function getName() { + console.log(name) + let name = 'Sarah' +} + +getName() +``` + +- A: Lydia +- B: Sarah +- C: `undefined` +- D: `ReferenceError` + +
Đáp án +

+ +#### Đá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ộ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`. + +```javascript +let name = 'Lydia' + +function getName() { + console.log(name) +} + +getName() // Lydia +``` + +

+
+ +--- + +###### 112. What's the 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` and `a` +- B: `a` and `undefined` +- C: `['a', 'b', 'c']` and `a` +- D: `a` and `['a', 'b', 'c']` + +
Đáp án +

+ +#### Đáp án: 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. What's the 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` + +
Đáp án +

+ +#### Đáp án: 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` + +
Đáp án +

+ +#### Đáp án: 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). + +

+
+ +--- + +###### 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 + +
Đáp án +

+ +#### Đáp án: 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. What's the 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}` + +
Đáp án +

+ +#### Đáp án: 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])` + +
Đáp án +

+ +#### Đáp án: 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. What's the output? + +```javascript +let num = 1; +const list = ["🥳", "🤠", "🥰", "🤪"]; + +console.log(list[(num += 1)]); +``` + +- A: `🤠` +- B: `🥰` +- C: `SyntaxError` +- D: `ReferenceError` + +
Đáp án +

+ +#### Đáp án: 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. What's the 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` `undefined` +- C: `Mara` `null` `Lydia Hallie` `null` +- D: `null` `ReferenceError` `null` `ReferenceError` + +
Đáp án +

+ +#### Đáp án: 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?.()`: `member` is not defined: `member.getLastName()` is nullish. The expression returns `undefined`. + +

+
+ +--- + +###### 120. What's the 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` + +
Đáp án +

+ +#### Đáp án: 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. What's the 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` + +
Đáp án +

+ +#### Đáp án: 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. What's the 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` + +
Đáp án +

+ +#### Đáp án: 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. What's the 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` + +
Đáp án +

+ +#### Đáp án: 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. What's the 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` + +
Đáp án +

+ +#### Đáp án: 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`. + +

+
+ +--- + +###### 125. What's the 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` + +
Đáp án +

+ +#### Đáp án: 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. What's the 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 + +
Đáp án +

+ +#### Đáp án: 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 `currentcy` in `USD` results in `$300.00`. + +

+
+ +--- + +###### 127. What's the output? + +```javascript +const spookyItems = ["👻", "🎃", "🕸"]; +({ item: spookyItems[3] } = { item: "💀" }); + +console.log(spookyItems); +``` + +- A: `["👻", "🎃", "🕸"]` +- B: `["👻", "🎃", "🕸", "💀"]` +- C: `["👻", "🎃", "🕸", { item: "💀" }]` +- D: `["👻", "🎃", "🕸", "[object Object]"]` + +
Đáp án +

+ +#### Đáp án: 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. What's the 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` + +
Đáp án +

+ +#### Đáp án: 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. What's the output? + +```javascript +const randomValue = 21; + +function getInfo() { + console.log(typeof randomValue); + const randomValue = "Lydia Hallie"; +} + +getInfo(); +``` + +- A: `"number"` +- B: `"string"` +- C: `undefined` +- D: `ReferenceError` + +
Đáp án +

+ +#### Đáp án: 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. + +

+
+ +--- + +###### 130. What's the 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!` + +
Đáp án +

+ +#### Đáp án: 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. What's the output? + +```javascript +const emojis = ["🥑", ["✨", "✨", ["🍕", "🍕"]]]; + +console.log(emojis.flat(1)); +``` + +- A: `['🥑', ['✨', '✨', ['🍕', '🍕']]]` +- B: `['🥑', '✨', '✨', ['🍕', '🍕']]` +- C: `['🥑', ['✨', '✨', '🍕', '🍕']]` +- D: `['🥑', '✨', '✨', '🍕', '🍕']` + +
Đáp án +

+ +#### Đáp án: 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. What's the 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` + +
Đáp án +

+ +#### Đáp án: 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 the `counterTwo.increment()`, which sets the `count` to `3`. Then, we log the count on `counterOne`, which logs `3`. + + + +

+
+ +--- + +###### 133. What's the output? + +```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!` + +
Đáp án +

+ +#### Đáp án: 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.) + +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. + +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!`. + +The next line is the _asynchronous_ `setTimeout` function, from which the callback is sent to the Web API. + +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!` + +

+
+ +--- + +###### 134. How can we invoke `sum` in `index.js` from `sum.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 + +
Đáp án +

+ +#### Đáp án: 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. What's the 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: Nothing gets logged + +
Đáp án +

+ +#### Đáp án: C + +With a Proxy object, we can add custom behavior to an object that we pass to it as the second argument. In tis 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. + +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 })` + +
Đáp án +

+ +#### Đáp án: A + +With `Object.seal` we can prevent new properies 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" }` + +
Đáp án +

+ +#### Đáp án: 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. 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" }` + +
Đáp án +

+ +#### Đáp án: 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. + +

+
+ +--- + +###### 139. What's the 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` + +
Đáp án +

+ +#### Đáp án: 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`. + +

+
+ +--- + +###### 140. What's the 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` + +
Đáp án +

+ +#### Đáp án: 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! + +

+
+ +--- + +###### 141. What's the output? + +```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 án +

+ +#### Đáp án: 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. + +

+
+ +--- + +###### 142. What's the 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"]` + +
Đáp án +

+ +#### Đáp án: 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 `y`, `"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 `"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. + +After pushing `dancing` and `baking`, the value of `person.hobbies` is `["coding", "dancing", "baking"]` + +

+
+ +--- + +###### 143. What's the 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: Nothing, we didn't call any method + +
Đáp án +

+ +#### Đáp án: 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. 🦢"`. + +

+
+ +--- + +###### 144. 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 + +
Đáp án +

+ +#### Đáp án: 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 propeties on the `emojis` array can be modified, for example by pushing new values, splicing them, or setting the length of the array to 0. + +

+
+ +--- + +###### 145. 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]() { for (let x in this) yield* Object.values(this) }` +- D: `*[Symbol.iterator]() { for (let x in this) yield this }` + +
Đáp án +

+ +#### Đáp án: 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)`. + +

+
+ From 349df39a07bd72fe5321973887b625e64e1e169c Mon Sep 17 00:00:00 2001 From: Do Trung Kien Date: Fri, 10 Jan 2020 16:25:04 +0700 Subject: [PATCH 405/915] translate next 10 question (112-121) into Vietnamese --- vi-VI/README-vi.md | 74 ++++++++++++++++++++++++---------------------- 1 file changed, 39 insertions(+), 35 deletions(-) diff --git a/vi-VI/README-vi.md b/vi-VI/README-vi.md index 02a8d87b..69d0c095 100644 --- a/vi-VI/README-vi.md +++ b/vi-VI/README-vi.md @@ -3570,7 +3570,7 @@ getName() // Lydia --- -###### 112. What's the output? +###### 112. Output là gì? ```javascript function* generatorOne() { @@ -3598,16 +3598,16 @@ console.log(two.next().value) #### Đáp án: 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). +Với từ khóa `yield`, ta sẽ trả về các giá trị trong một `generator`. Với từ khóa `yield*`, ta có thể trả về giá trị từ một `engerator` khác, hoặc một `iterable object` (ví dụ mảng). -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']`. +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 ``` -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. +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' @@ -3621,7 +3621,7 @@ console.log(two.next().value) // undefined --- -###### 113. What's the output? +###### 113. Output là gì? ```javascript console.log(`${(x => x)('I love')} to program`) @@ -3637,14 +3637,14 @@ console.log(`${(x => x)('I love')} to program`) #### Đáp án: 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`. +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`.

--- -###### 114. What will happen? +###### 114. Điều gì sẽ xảy ra? ```javascript let config = { @@ -3656,24 +3656,24 @@ let config = { 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` +- A: Callback `setInterval` sẽ không được gọi +- B: Callback `setInterval` sẽ được gọi một lần duy nhất +- C: Callback `setInterval` vẫn sẽ được gọi mỗi giây một lần +- D: `config.alert()` không bao giờ được gọi bởi config là `null`
Đáp án

#### Đáp án: 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). +Thông thường khi ta set một object bằng `null`, thì object này sẽ được bộ dọn rác dọn đi do không còn gì reference đến nó nữa (_garbage collected_). Tuy nhiên, do callback trong `setInterval` là một arrow function (do đó nó sẽ gắn với object `config`), nên callback này vẫn sẽ giữ reference đến object `config`. Vì vẫn còn giữ reference, nên object sẽ không bị dọn đi. Do đó nó vẫn sẽ được gọi sau mỗi 1000ms (tức 1 giây).

--- -###### 115. Which method(s) will return the value `'Hello world!'`? +###### 115. Những hàm nào sẽ trả về `'Hello world!'`? ```javascript const myMap = new Map() @@ -3691,25 +3691,25 @@ myMap.get(() => 'greeting') - A: 1 - B: 2 -- C: 2 and 3 -- D: All of them +- C: 2 và 3 +- D: Tất cả
Đáp án

#### Đáp án: 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!' }`. +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 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. +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.

--- -###### 116. What's the output? +###### 116. Output là gì? ```javascript const person = { @@ -3739,18 +3739,18 @@ console.log(person) #### Đáp án: 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. +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`. -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 }`. +Đầ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 }`. -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 }`. +Sau đó, chúng ta gọi hàm `changeAgeAndName` tuy nhiên không đưa vào đối số nào cả. Do đó giá trị của `x` lúc này sẽ là giá trị mặc định, tức một bản _copy_ của object `{ ...person }`. Do nó chỉ là một bản copy (tức object mới), nên nó không ảnh hưởng gì tới giá trị của object `person` gốc, giá trị của `person` gốc sẽ vẫn là `{ name: "Lydia", age: 22 }`.

--- -###### 117. Which of the following options will return `6`? +###### 117. Phép tính nào dưới đây trả về `6`? ```javascript function sumValues(x, y, z) { @@ -3768,14 +3768,14 @@ function sumValues(x, y, z) { #### Đáp án: 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. +Với toán tử ba chấm (`spread operator`) `...`, chúng ta có thể unpack một iterable thành từng các phần tử riêng biệt. Hàm `sumValues` nhận vào 3 giá trị: `x`, `y` và `z`. `...[1, 2, 3]` sẽ trả về `1, 2, 3`, đưa vào `sumValues` sẽ cho ta kết quả là 6.

--- -###### 118. What's the output? +###### 118. Output là gì? ```javascript let num = 1; @@ -3794,14 +3794,14 @@ console.log(list[(num += 1)]); #### Đáp án: 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 🥰. +Với phép toán `+=`, Ta tăng giá trị của `num` lên `1`. `num` có giá trị khởi tạo là `1`, do đó `1 + 1` là `2`. Phần tử thứ hai của `list` là 🥰, do đó `console.log(list[2])` sẽ in ra 🥰.

--- -###### 119. What's the output? +###### 119. Output là gì? ```javascript const person = { @@ -3832,19 +3832,22 @@ console.log(member.getLastName?.()); #### Đáp án: 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`. +Với phép toán optional chaining `?.`, chúng ta sẽ không cần phải check xem giá trị phía sau nó có được phép truy cập hay có tồn tại hay không. Nếu ta cố lấy một thuộc tính của `undefined` hay `null` (_nullish_), biểu thức sẽ dừng lại và trả về `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?.()`: `member` is not defined: `member.getLastName()` is nullish. The expression returns `undefined`. +`person.pet?.name`: `person` có thuộc tính `pet`: do đó `person.pet` không phải là một nullish. Nó có một thuộc tính `name`, với giá trị `Mara`. + +`person.pet?.family?.name`: `person` có thuộc tính `pet`: do đó `person.pet` không phải là nullish. Tuy nhiên `pet` không có thuộc tính `family`, nên `person.pet.family` là nullish. Biểu thức sẽ trả về `undefined`. + +`person.getFullName?.()`: `person` có thuộc tính `getFullName`: do đó `person.getFullName()` không phải nullish và có thể gọi ra, trả về `Lydia Hallie`. + +`member.getLastName?.()`: `member` không được định nghĩa: do đó `member.getLastName()` là nullish. Biểu thức trả về `undefined`.

--- -###### 120. What's the output? +###### 120. Ouput là gì? ```javascript const groceries = ["banana", "apple", "peanuts"]; @@ -3866,14 +3869,14 @@ if (groceries.indexOf("banana")) { #### Đáp án: 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. +Ta đưa một điều kiện `groceries.indexOf("banana")` vào câu lệnh `if`. `groceries.indexOf("banana")` trả về `0`, là một giá trị `falsy`. Do đó điệu kiện `if` sẽ chạy vào khối `else` và in ra `We don't have to buy bananas!`.

--- -###### 121. What's the output? +###### 121. Ouput là gì? ```javascript const config = { @@ -3897,6 +3900,7 @@ console.log(config.language); #### Đáp án: 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. +Phương thức `language` là một `setter`. Setter không mang giá trị, nhiệm vụ của nó chỉ đơn giản là _thay đổi_ thuộc tính. Khi ta gọi một phương thức `setter` nó sẽ trả về `undefined`.

From a685fabe64c0011495a26dbb2e87b7e58b86b350 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Erdo=C4=9Fan=20Bava=C5=9F?= Date: Sat, 11 Jan 2020 13:04:37 +0300 Subject: [PATCH 406/915] Update README-tr_TR.md Fixed some typos --- tr-TR/README-tr_TR.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/tr-TR/README-tr_TR.md b/tr-TR/README-tr_TR.md index f09a2ccb..e273f228 100644 --- a/tr-TR/README-tr_TR.md +++ b/tr-TR/README-tr_TR.md @@ -1012,7 +1012,7 @@ sayHi.bind(person, 21); İkisinde de, `this` anahtar kelimesinin referans olmasını istediğimiz nesneyi geçebiliriz. Ancak, `.call` _anında çalıştırılır_! -`.bind.` fonksiyonun _kopyasını_ döndürür, ama konteksle bağlı şejilde. Anında çalıştırılmaz. +`.bind.` fonksiyonun _kopyasını_ döndürür, ama konteksle bağlı şekilde. Anında çalıştırılmaz.

@@ -1191,7 +1191,7 @@ JavaScript sadece primitif ve nesne tiplerine sahiptir. Primitif tipler, `boolean`, `null`, `undefined`, `bigint`, `number`, `string`, ve `symbol`. -Primitif ve nesneyi birbirinden ayıran, primitif tiplerin herhangi bir özelliğie ya da methoda sahip olmamasıdır; ancak, fark edeceğiniz üzere `'foo'.toUpperCase()` `'FOO'` olarak değer döndürür ve `TypeError` ile sonuçlanmaz. Bunun sebebi, string gibi primitif bir tip üzerinde özelliğe ya da methoda erişmeye çalıştığınızda, JavaScript sarıcı sınıflardan, "wrapper classes", birini kullanarak nesneyi dolaylı şekilde sarar, örneğin `String`, ve sonrasında ifade çalıştıktan sonra anında sarıcıyı ayırır. `null` ve `undefined` dışındaki tüm primitifler bu şekilde davranır. +Primitif ve nesneyi birbirinden ayıran, primitif tiplerin herhangi bir özelliğe ya da metoda sahip olmamasıdır; ancak, fark edeceğiniz üzere `'foo'.toUpperCase()` `'FOO'` olarak değer döndürür ve `TypeError` ile sonuçlanmaz. Bunun sebebi, string gibi primitif bir tip üzerinde özelliğe ya da methoda erişmeye çalıştığınızda, JavaScript sarıcı sınıflardan, "wrapper classes", birini kullanarak nesneyi dolaylı şekilde sarar, örneğin `String`, ve sonrasında ifade çalıştıktan sonra anında sarıcıyı ayırır. `null` ve `undefined` dışındaki tüm primitifler bu şekilde davranır.

@@ -1329,9 +1329,9 @@ console.log(gen.next().value); 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()` methodunu 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ı. +Ö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ı. -Sonra, `next()` methodunu kullanarak fonksiyonu tekrar çalıştırıyoruz. Fonksiyon önceki kaldığı yerden çalışmaya devam ediyor, `i` hala `10`'a eşit. Şimdi, fonksiyon sıraki `yield` anahtar kelimesi ile karşılaşıyor, ve `i * 2`'yi veriyor, yani fonksiyon `10 * 2` veriyor, ki o da `20`'dir. `10, 20` şeklinde sonuçlanıyor. +Sonra, `next()` metodunu kullanarak fonksiyonu tekrar çalıştırıyoruz. Fonksiyon önceki kaldığı yerden çalışmaya devam ediyor, `i` hala `10`'a eşit. Şimdi, fonksiyon sıraki `yield` anahtar kelimesi ile karşılaşıyor, ve `i * 2`'yi veriyor, yani fonksiyon `10 * 2` veriyor, ki o da `20`'dir. `10, 20` şeklinde sonuçlanıyor.

From b8b8512a226dd10fa94ce488573626225902309a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Erdo=C4=9Fan=20Bava=C5=9F?= Date: Sat, 11 Jan 2020 15:33:33 +0300 Subject: [PATCH 407/915] Update README-tr_TR.md Typos fixed and a question synced with en-EN --- tr-TR/README-tr_TR.md | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/tr-TR/README-tr_TR.md b/tr-TR/README-tr_TR.md index e273f228..6dfaca43 100644 --- a/tr-TR/README-tr_TR.md +++ b/tr-TR/README-tr_TR.md @@ -1966,7 +1966,7 @@ console.log(num2); const value = { number: 10 }; const multiply = (x = { ...value }) => { - console.log((x.number * 2)); + console.log((x.number *= 2)); }; multiply(); @@ -2866,7 +2866,7 @@ console.log(newList.push(5)) `.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 kullanmayo denedik. `newList` sayısal değer `4` olduğundan, `.push` methodunu kullanamayız: TypeError fırlatılır. +Sonra, `.push` methodunu `newList` üzerinde kullanmayı denedik. `newList` sayısal değer `4` olduğundan, `.push` methodunu kullanamayız: TypeError fırlatılır.

@@ -2916,9 +2916,9 @@ for (const [x, y] of Object.entries(person)) { } ``` -- A: `name` `Lydia` and `age` `21` -- B: `["name", "Lydia"]` and `["age", 21]` -- C: `["name", "age"]` and `undefined` +- A: `name` `Lydia` ve `age` `21` +- B: `["name", "Lydia"]` ve `["age", 21]` +- C: `["name", "age"]` ve `undefined` - D: `Error`
Cevap From 7a87b90e7331de5e3401d0bf2c7e1ad0bfafd9d3 Mon Sep 17 00:00:00 2001 From: Tarabass Date: Sat, 11 Jan 2020 15:58:14 +0100 Subject: [PATCH 408/915] Add README for dutch translation --- nl-NL/README.md | 4747 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 4747 insertions(+) create mode 100644 nl-NL/README.md diff --git a/nl-NL/README.md b/nl-NL/README.md new file mode 100644 index 00000000..739f2285 --- /dev/null +++ b/nl-NL/README.md @@ -0,0 +1,4747 @@ +
+ +

JavaScript Questions

+ + --- + + I post multiple choice JavaScript questions on my [Instagram](https://www.instagram.com/theavocoder) **stories**, which I'll also post here! Last updated: December 24th + + 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! 😊
+ Instagram || Twitter || LinkedIn || Blog +
+ +--- + +
See 17 Available Translations 🇪🇸🇮🇹🇩🇪 🇫🇷🇷🇺🇨🇳🇵🇹 +

+ +* [English](../en-EN/README.md) +* [العربية](../ar-AR/README_AR.md) +* [اللغة العامية - Egyptian Arabic](../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) +* [日本語](../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) +* [Українська мова](../ua-UA/README-ua_UA.md) +* [Tiếng Việt](../vi-VI/README-vi.md) +* [中文版本](../zh-CN/README-zh_CN.md) +* [Türkçe](../tr-TR/README-tr_TR.md) +* [ไทย](../th-TH/README-th_TH.md) + +

+
+ +--- + +###### 1. What's the output? + +```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` + +
Answer +

+ +#### Answer: D + +Within the function, we first declare the `name` variable with the `var` keyword. This means that the variable gets hoisted (memory space is set up during the creation phase) with the default value of `undefined`, until we actually get to the line where we define the variable. We haven't defined the variable yet on the line where we try to log the `name` variable, so it still holds the value of `undefined`. + +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`. + +

+
+ +--- + +###### 2. What's the 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` and `0 1 2` +- B: `0 1 2` and `3 3 3` +- C: `3 3 3` and `0 1 2` + +
Answer +

+ +#### Answer: C + +Because of the event queue in JavaScript, the `setTimeout` callback function is called _after_ the loop has been executed. Since the variable `i` in the first loop was declared using the `var` keyword, this value was global. During the loop, we incremented the value of `i` by `1` each time, using the unary operator `++`. By the time the `setTimeout` callback function was invoked, `i` was equal to `3` in the first example. + +In the second loop, the variable `i` was declared using the `let` keyword: variables declared with the `let` (and `const`) keyword are block-scoped (a block is anything between `{ }`). During each iteration, `i` will have a new value, and each value is scoped inside the loop. + +

+
+ +--- + +###### 3. What's the 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` and `62.83185307179586` +- B: `20` and `NaN` +- C: `20` and `63` +- D: `NaN` and `63` + +
Answer +

+ +#### Answer: B + +Note that the value of `diameter` is a regular function, whereas the value of `perimeter` is an arrow function. + +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 `undefined`. + +

+
+ +--- + +###### 4. What's the output? + +```javascript ++true; +!"Lydia"; +``` + +- A: `1` and `false` +- B: `false` and `NaN` +- C: `false` and `false` + +
Answer +

+ +#### Answer: A + +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`. + +

+
+ +--- + +###### 5. Which one is true? + +```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 + +
Answer +

+ +#### Answer: A + +In JavaScript, all object keys are strings (unless it's a Symbol). Even though we might not _type_ them as strings, they are always converted into strings under the hood. + +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. + +`mouse[bird.size]`: First it evaluates `bird.size`, which is `"small"`. `mouse["small"]` returns `true` + +However, with dot notation, this doesn't happen. `mouse` does not have a key called `bird`, which means that `mouse.bird` is `undefined`. Then, we ask for the `size` using dot notation: `mouse.bird.size`. Since `mouse.bird` is `undefined`, we're actually asking `undefined.size`. This isn't valid, and will throw an error similar to `Cannot read property "size" of undefined`. + +

+
+ +--- + + +###### 6. What's the 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` + +
Answer +

+ +#### Answer: A + +In JavaScript, all objects interact by _reference_ when setting them equal to each other. + +First, variable `c` holds a value to an object. Later, we assign `d` with the same reference that `c` has to the object. + + + +When you change one object, you change all of them. + +

+
+ +--- + +###### 7. What's the 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` + +
Answer +

+ +#### Answer: 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`. + +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.` + +

+
+ +--- + +###### 8. What's the 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` + +
Answer +

+ +#### 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. + +

+
+ +--- + +###### 9. What's the output? + +```javascript +let greeting; +greetign = {}; // Typo! +console.log(greetign); +``` + +- A: `{}` +- B: `ReferenceError: greetign is not defined` +- C: `undefined` + +
Answer +

+ +#### 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). + +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. + +

+
+ +--- + +###### 10. What happens when we do this? + +```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` + +
Answer +

+ +#### Answer: A + +This is possible in JavaScript, because functions are objects! (Everything besides primitive types are objects) + +A function is a special type of object. The code you write yourself isn't the actual function. The function is an object with properties. This property is invocable. + +

+
+ +--- + +###### 11. What's the 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` + +
Answer +

+ +#### Answer: A + +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() { + return `${this.firstName} ${this.lastName}`; +}; +``` + +would have made `member.getFullName()` work. Why is this beneficial? Say that we added this method to the constructor itself. Maybe not every `Person` instance needed this method. This would waste a lot of memory space, since they would still have that property, which takes of memory space for each instance. Instead, if we only add it to the prototype, we just have it at one spot in memory, yet they all have access to it! + +

+
+ +--- + +###### 12. What's the 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` + +
Answer +

+ +#### Answer: A + +For `sarah`, we didn't use the `new` keyword. When using `new`, it refers to the new empty object we create. However, if you don't add `new` it 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 + +
Answer +

+ +#### Answer: 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 + +
Answer +

+ +#### Answer: 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. What's the output? + +```javascript +function sum(a, b) { + return a + b; +} + +sum(1, "2"); +``` + +- A: `NaN` +- B: `TypeError` +- C: `"12"` +- D: `3` + +
Answer +

+ +#### Answer: 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. What's the 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` + +
Answer +

+ +#### Answer: 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. What's the 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` + +
Answer +

+ +#### Answer: 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. What's the 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` + +
Answer +

+ +#### Answer: 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. What's the output? + +```javascript +function getAge(...args) { + console.log(typeof args); +} + +getAge(21); +``` + +- A: `"number"` +- B: `"array"` +- C: `"object"` +- D: `"NaN"` + +
Answer +

+ +#### Answer: 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. What's the output? + +```javascript +function getAge() { + "use strict"; + age = 21; + console.log(age); +} + +getAge(); +``` + +- A: `21` +- B: `undefined` +- C: `ReferenceError` +- D: `TypeError` + +
Answer +

+ +#### Answer: 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 value of `sum`? + +```javascript +const sum = eval("10*10+5"); +``` + +- A: `105` +- B: `"105"` +- C: `TypeError` +- D: `"10*10+5"` + +
Answer +

+ +#### 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`. + +

+
+ +--- + +###### 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. + +
Answer +

+ +#### Answer: 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. What's the output? + +```javascript +var num = 8; +var num = 10; + +console.log(num); +``` + +- A: `8` +- B: `10` +- C: `SyntaxError` +- D: `ReferenceError` + +
Answer +

+ +#### Answer: 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. What's the 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` + +
Answer +

+ +#### Answer: 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. What's the 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` + +
Answer +

+ +#### Answer: 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 + +
Answer +

+ +#### Answer: A + +The base execution context is the global execution context: it's what's accessible everywhere in your code. + +

+
+ +--- + +###### 27. What's the 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` + +
Answer +

+ +#### Answer: C + +The `continue` statement skips an iteration if a certain condition returns `true`. + +

+
+ +--- + +###### 28. What's the 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` + +
Answer +

+ +#### 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! + +

+
+ +--- + +###### 29. What's the 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` + +
Answer +

+ +#### Answer: 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. What's the 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` + +
Answer +

+ +#### Answer: 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. + +
Answer +

+ +#### Answer: 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` + +
Answer +

+ +#### 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. + +

+
+ +--- + +###### 33. What's the 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` + +
Answer +

+ +#### Answer: 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. What's the output? + +```javascript +function sayHi() { + return (() => 0)(); +} + +console.log(typeof sayHi()); +``` + +- A: `"object"` +- B: `"number"` +- C: `"function"` +- D: `"undefined"` + +
Answer +

+ +#### Answer: B + +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`, and `symbol`. `"function"` is not a type, since functions are objects, it's of type `"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 + +
Answer +

+ +#### Answer: A + +There are only six falsy values: + +- `undefined` +- `null` +- `NaN` +- `0` +- `''` (empty string) +- `false` + +Function constructors, like `new Number` and `new Boolean` are truthy. + +

+
+ +--- + +###### 36. What's the output? + +```javascript +console.log(typeof typeof 1); +``` + +- A: `"number"` +- B: `"string"` +- C: `"object"` +- D: `"undefined"` + +
Answer +

+ +#### Answer: B + +`typeof 1` returns `"number"`. +`typeof "number"` returns `"string"` + +

+
+ +--- + +###### 37. What's the 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` + +
Answer +

+ +#### Answer: 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, 7 x empty, 11]` + +depending on where you run it (it's different for every browser, node, etc.) + +

+
+ +--- + +###### 38. What's the 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` + +
Answer +

+ +#### Answer: 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 + +
Answer +

+ +#### Answer: 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 object 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. What's the 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]` + +
Answer +

+ +#### Answer: 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. What's the output? + +```javascript +!!null; +!!""; +!!1; +``` + +- A: `false` `true` `false` +- B: `false` `false` `true` +- C: `false` `true` `true` +- D: `true` `true` `false` + +
Answer +

+ +#### Answer: 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` + +
Answer +

+ +#### Answer: 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"]]` + +
Answer +

+ +#### Answer: A + +A string is an iterable. The spread operator maps every character of an iterable to one element. + +

+
+ +--- + +###### 44. What's the 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` + +
Answer +

+ +#### Answer: 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"` + +
Answer +

+ +#### Answer: 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. What's the output? + +```javascript +let person = { name: "Lydia" }; +const members = [person]; +person = null; + +console.log(members); +``` + +- A: `null` +- B: `[null]` +- C: `[{}]` +- D: `[{ name: "Lydia" }]` + +
Answer +

+ +#### Answer: 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. What's the 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]` + +
Answer +

+ +#### Answer: 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. What's the output? + +```javascript +console.log(3 + 4 + "5"); +``` + +- A: `"345"` +- B: `"75"` +- C: `12` +- D: `"12"` + +
Answer +

+ +#### Answer: 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` + +
Answer +

+ +#### 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. + +`*` is not a valid number. It only parses `"7"` into the decimal `7`. `num` now holds the value of `7`. + +

+
+ +--- + +###### 50. What's the 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 ]` + +
Answer +

+ +#### Answer: 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. What's the 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"` + +
Answer +

+ +#### Answer: 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. What's the 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!` + +
Answer +

+ +#### Answer: 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. What's the 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` + +
Answer +

+ +#### 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"`. + +

+
+ +--- + +###### 54. What's the 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"` + +
Answer +

+ +#### Answer: 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 (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. What's the 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` + +
Answer +

+ +#### Answer: 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. What's the 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}` + +
Answer +

+ +#### Answer: 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. What's the 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` + +
Answer +

+ +#### Answer: 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. What's the 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` + +
Answer +

+ +#### 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 `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. What's the 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]` + +
Answer +

+ +#### Answer: 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. What's the 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 }` + +
Answer +

+ +#### Answer: 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. What's the 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"]` + +
Answer +

+ +#### Answer: 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. What's the 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}"` + +
Answer +

+ +#### Answer: 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. What's the 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` + +
Answer +

+ +#### 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. + +`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. What's the 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` + +
Answer +

+ +#### Answer: 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. What's the 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` + +
Answer +

+ +#### Answer: 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 + +
Answer +

+ +#### Answer: 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. What's the 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` + +
Answer +

+ +#### 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_. + +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. What's the 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` + +
Answer +

+ +#### Answer: 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. What's the 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"`, + +
Answer +

+ +#### Answer: 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. What's the output? + +```javascript +console.log("🥑" + "💻"); +``` + +- A: `"🥑💻"` +- B: `257548` +- C: A string containing their code points +- D: Error + +
Answer +

+ +#### Answer: 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 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")` + +
Answer +

+ +#### Answer: 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. What's the output? + +```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` 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. What's the 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` + +
Answer +

+ +#### Answer: 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. What's the 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` + +
Answer +

+ +#### Answer: 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. What's the 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` + +
Answer +

+ +#### Answer: 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)` returns 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. What's the output? + +```javascript +const { name: myName } = { name: "Lydia" }; + +console.log(name); +``` + +- A: `"Lydia"` +- B: `"myName"` +- C: `undefined` +- D: `ReferenceError` + +
Answer +

+ +#### 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, a ReferenceError gets thrown. + +

+
+ +--- + +###### 77. Is this a pure function? + +```javascript +function sum(a, b) { + return a + b; +} +``` + +- A: Yes +- B: No + +
Answer +

+ +#### Answer: 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` + +
Answer +

+ +#### Answer: 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: "🍫"}` + +
Answer +

+ +#### Answer: 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]` + +
Answer +

+ +#### Answer: 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` + +
Answer +

+ +#### Answer: 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 `"😎"` + +
Answer +

+ +#### Answer: 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"` + +
Answer +

+ +#### Answer: 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` + +
Answer +

+ +#### 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. + +

+
+ +--- + +###### 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. + +
Answer +

+ +#### Answer: 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` + +
Answer +

+ +#### 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`. + +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. What's the output? + +```javascript +console.log("I want pizza"[0]) +``` + +- A: `"""` +- B: `"I"` +- C: `SyntaxError` +- D: `undefined` + +
Answer +

+ +#### 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. + +Note that this method is not supported in IE7 and below. In that case, use `.charAt()` + +

+
+ +--- + +###### 88. What's the output? + +```javascript +function sum(num1, num2 = num1) { + console.log(num1 + num2) +} + +sum(10) +``` + +- A: `NaN` +- B: `20` +- C: `ReferenceError` +- D: `undefined` + +
Answer +

+ +#### Answer: 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. What's the 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` + +
Answer +

+ +#### 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"`. + +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. What's the 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"` + +
Answer +

+ +#### Answer: C + +Classes are syntactical sugar for function constructors. The equivalent of the `Person` class as a function constructor would be: + +```javascript +function Person() { + 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. What's the 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` + +
Answer +

+ +#### Answer: 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. What's the 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` + +
Answer +

+ +#### Answer: 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. What's the output? + +```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` + +
Answer +

+ +#### Answer: 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. What's the 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` + +
Answer +

+ +#### Answer: 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. What's the 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` + +
Answer +

+ +#### Answer: 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. What's the 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` + +
Answer +

+ +#### Answer: 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. What's the output? + +```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 `[]` + +
Answer +

+ +#### Answer: 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. What's the 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]]` 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 }` + +
Answer +

+ +#### Answer: 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 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 })``` + +Since no value gets returned in this case, the function returns `undefined`. + +

+
+ +--- + +###### 99. What's the output? + +```javascript +const name = "Lydia" + +console.log(name()) +``` + +- A: `SyntaxError` +- B: `ReferenceError` +- C: `TypeError` +- D: `undefined` + +
Answer +

+ +#### Answer: 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` + +
Answer +

+ +#### Answer: 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` + +
Answer +

+ +#### Answer: 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 past 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` + +
Answer +

+ +#### Answer: 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 befoer 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` + +
Answer +

+ +#### Answer: 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` + +
Answer +

+ +#### Answer: 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` + +
Answer +

+ +#### Answer: 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` + +
Answer +

+ +#### Answer: 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 proprety 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` + +
Answer +

+ +#### Answer: 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` + +
Answer +

+ +#### Answer: 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. What's the output? + +```javascript +const food = ['🍕', '🍫', '🥑', '🍔'] +const info = { favoriteFood: food[0] } + +info.favoriteFood = '🍝' + +console.log(food) +``` + +- A: `['🍕', '🍫', '🥑', '🍔']` +- B: `['🍝', '🍫', '🥑', '🍔']` +- C: `['🍝', '🍕', '🍫', '🥑', '🍔']` +- D: `ReferenceError` + +
Answer +

+ +#### Answer: 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 act 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 + +
Answer +

+ +#### Answer: 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. What's the output? + +```javascript +let name = 'Lydia' + +function getName() { + console.log(name) + let name = 'Sarah' +} + +getName() +``` + +- A: Lydia +- B: Sarah +- C: `undefined` +- D: `ReferenceError` + +
Answer +

+ +#### Answer: 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. What's the 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` and `a` +- B: `a` and `undefined` +- C: `['a', 'b', 'c']` and `a` +- D: `a` and `['a', 'b', 'c']` + +
Answer +

+ +#### Answer: 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. What's the 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` + +
Answer +

+ +#### Answer: 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` + +
Answer +

+ +#### 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). + +

+
+ +--- + +###### 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 + +
Answer +

+ +#### Answer: 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. What's the 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}` + +
Answer +

+ +#### Answer: 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])` + +
Answer +

+ +#### Answer: 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. What's the output? + +```javascript +let num = 1; +const list = ["🥳", "🤠", "🥰", "🤪"]; + +console.log(list[(num += 1)]); +``` + +- A: `🤠` +- B: `🥰` +- C: `SyntaxError` +- D: `ReferenceError` + +
Answer +

+ +#### 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 🥰. + +

+
+ +--- + +###### 119. What's the 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` `undefined` +- C: `Mara` `null` `Lydia Hallie` `null` +- D: `null` `ReferenceError` `null` `ReferenceError` + +
Answer +

+ +#### Answer: 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?.()`: `member` is not defined: `member.getLastName()` is nullish. The expression returns `undefined`. + +

+
+ +--- + +###### 120. What's the 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` + +
Answer +

+ +#### Answer: 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. What's the 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` + +
Answer +

+ +#### Answer: 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. What's the 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` + +
Answer +

+ +#### Answer: 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. What's the 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` + +
Answer +

+ +#### Answer: 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. What's the 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` + +
Answer +

+ +#### 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`. + +

+
+ +--- + +###### 125. What's the 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` + +
Answer +

+ +#### Answer: 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. What's the 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 + +
Answer +

+ +#### Answer: 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 `currentcy` in `USD` results in `$300.00`. + +

+
+ +--- + +###### 127. What's the output? + +```javascript +const spookyItems = ["👻", "🎃", "🕸"]; +({ item: spookyItems[3] } = { item: "💀" }); + +console.log(spookyItems); +``` + +- A: `["👻", "🎃", "🕸"]` +- B: `["👻", "🎃", "🕸", "💀"]` +- C: `["👻", "🎃", "🕸", { item: "💀" }]` +- D: `["👻", "🎃", "🕸", "[object Object]"]` + +
Answer +

+ +#### Answer: 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. What's the 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` + +
Answer +

+ +#### Answer: 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. What's the output? + +```javascript +const randomValue = 21; + +function getInfo() { + console.log(typeof randomValue); + const randomValue = "Lydia Hallie"; +} + +getInfo(); +``` + +- A: `"number"` +- B: `"string"` +- C: `undefined` +- D: `ReferenceError` + +
Answer +

+ +#### 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. + +

+
+ +--- + +###### 130. What's the 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!` + +
Answer +

+ +#### Answer: 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. What's the output? + +```javascript +const emojis = ["🥑", ["✨", "✨", ["🍕", "🍕"]]]; + +console.log(emojis.flat(1)); +``` + +- A: `['🥑', ['✨', '✨', ['🍕', '🍕']]]` +- B: `['🥑', '✨', '✨', ['🍕', '🍕']]` +- C: `['🥑', ['✨', '✨', '🍕', '🍕']]` +- D: `['🥑', '✨', '✨', '🍕', '🍕']` + +
Answer +

+ +#### Answer: 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. What's the 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` + +
Answer +

+ +#### Answer: 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 the `counterTwo.increment()`, which sets the `count` to `3`. Then, we log the count on `counterOne`, which logs `3`. + + + +

+
+ +--- + +###### 133. What's the output? + +```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!` + +
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.) + +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. + +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!`. + +The next line is the _asynchronous_ `setTimeout` function, from which the callback is sent to the Web API. + +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!` + +

+
+ +--- + +###### 134. How can we invoke `sum` in `index.js` from `sum.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 + +
Answer +

+ +#### Answer: 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. What's the 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: Nothing gets logged + +
Answer +

+ +#### Answer: C + +With a Proxy object, we can add custom behavior to an object that we pass to it as the second argument. In tis 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. + +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 })` + +
Answer +

+ +#### Answer: A + +With `Object.seal` we can prevent new properies 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" }` + +
Answer +

+ +#### Answer: 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. 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" }` + +
Answer +

+ +#### Answer: 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. + +

+
+ +--- + +###### 139. What's the 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` + +
Answer +

+ +#### 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`. + +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`. + +

+
+ +--- + +###### 140. What's the 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` + +
Answer +

+ +#### 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! + +

+
+ +--- + +###### 141. What's the output? + +```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)` + +
Answer +

+ +#### Answer: 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. + +

+
+ +--- + +###### 142. What's the 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"]` + +
Answer +

+ +#### Answer: 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 `y`, `"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 `"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. + +After pushing `dancing` and `baking`, the value of `person.hobbies` is `["coding", "dancing", "baking"]` + +

+
+ +--- + +###### 143. What's the 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: Nothing, we didn't call any method + +
Answer +

+ +#### Answer: 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. 🦢"`. + +

+
+ +--- + +###### 144. 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 + +
Answer +

+ +#### Answer: 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 propeties on the `emojis` array can be modified, for example by pushing new values, splicing them, or setting the length of the array to 0. + +

+
+ +--- + +###### 145. 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]() { for (let x in this) yield* Object.values(this) }` +- D: `*[Symbol.iterator]() { for (let x in this) yield this }` + +
Answer +

+ +#### Answer: 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)`. + +

+
\ No newline at end of file From 5889a6a320e3a8474cae936a7c07d0f13d7d63e0 Mon Sep 17 00:00:00 2001 From: Tarabass Date: Sat, 11 Jan 2020 15:58:36 +0100 Subject: [PATCH 409/915] Update main README --- README.md | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index d3d60814..b7c5d4b3 100644 --- a/README.md +++ b/README.md @@ -14,7 +14,7 @@ --- -
See 16 Available Translations 🇪🇸🇮🇹🇩🇪 🇫🇷🇷🇺🇨🇳🇵🇹 +
See 17 Available Translations 🇪🇸🇮🇹🇩🇪 🇫🇷🇷🇺🇨🇳🇵🇹

* [English](./en-EN/README.md) @@ -25,7 +25,8 @@ * [Español](./es-ES/README-ES.md) * [Français](./fr-FR/README_fr-FR.md) * [日本語](./ja-JA/README-ja_JA.md) -* [한국어](./ko-KR/README-ko_KR.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) * [Українська мова](./ua-UA/README-ua_UA.md) From ce3bc38324c75a737a60dd51f33ce8978bbd95d3 Mon Sep 17 00:00:00 2001 From: Tarabass Date: Sat, 11 Jan 2020 16:07:25 +0100 Subject: [PATCH 410/915] Update README for other languages --- ar-AR/README_AR.md | 3 ++- bs-BS/README-bs_BS.md | 3 ++- de-DE/README.md | 3 ++- en-EN/README.md | 3 ++- es-ES/README-ES.md | 3 ++- fr-FR/README_fr-FR.md | 3 ++- ja-JA/README-ja_JA.md | 3 ++- ko-KR/README-ko_KR.md | 3 ++- pt-BR/README_pt_BR.md | 3 ++- ru-RU/README.md | 3 ++- th-TH/README.md | 4 +++- tr-TR/README-tr_TR.md | 3 ++- ua-UA/README-ua_UA.md | 3 ++- vi-VI/README-vi.md | 3 ++- 14 files changed, 29 insertions(+), 14 deletions(-) diff --git a/ar-AR/README_AR.md b/ar-AR/README_AR.md index fb8ae229..8b33a246 100644 --- a/ar-AR/README_AR.md +++ b/ar-AR/README_AR.md @@ -22,7 +22,8 @@ * [Español](../es-ES/README-ES.md) * [Français](../fr-FR/README_fr-FR.md) * [日本語](../ja-JA/README-ja_JA.md) -* [한국어](../ko-KR/README-ko_KR.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) * [Українська мова](../ua-UA/README-ua_UA.md) diff --git a/bs-BS/README-bs_BS.md b/bs-BS/README-bs_BS.md index 29063aea..e040e6cb 100644 --- a/bs-BS/README-bs_BS.md +++ b/bs-BS/README-bs_BS.md @@ -20,7 +20,8 @@ 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) * [日本語](../ja-JA/README-ja_JA.md) -* [한국어](../ko-KR/README-ko_KR.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) * [Українська мова](../ua-UA/README-ua_UA.md) diff --git a/de-DE/README.md b/de-DE/README.md index b5e6ff78..a8e775de 100644 --- a/de-DE/README.md +++ b/de-DE/README.md @@ -15,7 +15,8 @@ Die Antworten sind unterhalb der Fragen versteckt. Du kannst einfach darauf klic * [Español](../es-ES/README-ES.md) * [Français](../fr-FR/README_fr-FR.md) * [日本語](../ja-JA/README-ja_JA.md) -* [한국어](../ko-KR/README-ko_KR.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) * [Українська мова](../ua-UA/README-ua_UA.md) diff --git a/en-EN/README.md b/en-EN/README.md index ddf67054..f75c09fb 100644 --- a/en-EN/README.md +++ b/en-EN/README.md @@ -25,7 +25,8 @@ * [Español](../es-ES/README-ES.md) * [Français](../fr-FR/README_fr-FR.md) * [日本語](../ja-JA/README-ja_JA.md) -* [한국어](../ko-KR/README-ko_KR.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) * [Українська мова](../ua-UA/README-ua_UA.md) diff --git a/es-ES/README-ES.md b/es-ES/README-ES.md index 585b8d00..a6247c9f 100644 --- a/es-ES/README-ES.md +++ b/es-ES/README-ES.md @@ -20,7 +20,8 @@ Lista de lenguajes disponibles: * [Español](../es-ES/README-ES.md) * [Français](../fr-FR/README_fr-FR.md) * [日本語](../ja-JA/README-ja_JA.md) -* [한국어](../ko-KR/README-ko_KR.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) * [Українська мова](../ua-UA/README-ua_UA.md) diff --git a/fr-FR/README_fr-FR.md b/fr-FR/README_fr-FR.md index 9af4c3b6..7b9b837c 100644 --- a/fr-FR/README_fr-FR.md +++ b/fr-FR/README_fr-FR.md @@ -14,7 +14,8 @@ Les réponses se trouvent dans les sections repliées en dessous des questions, * [Español](../es-ES/README-ES.md) * [Français](../fr-FR/README_fr-FR.md) * [日本語](../ja-JA/README-ja_JA.md) -* [한국어](../ko-KR/README-ko_KR.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) * [Українська мова](../ua-UA/README-ua_UA.md) diff --git a/ja-JA/README-ja_JA.md b/ja-JA/README-ja_JA.md index 4b081ae8..7d42eeeb 100644 --- a/ja-JA/README-ja_JA.md +++ b/ja-JA/README-ja_JA.md @@ -16,7 +16,8 @@ * [Español](../es-ES/README-ES.md) * [Français](../fr-FR/README_fr-FR.md) * [日本語](../ja-JA/README-ja_JA.md) -* [한국어](../ko-KR/README-ko_KR.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) * [Українська мова](../ua-UA/README-ua_UA.md) diff --git a/ko-KR/README-ko_KR.md b/ko-KR/README-ko_KR.md index 84ab3893..078de04a 100644 --- a/ko-KR/README-ko_KR.md +++ b/ko-KR/README-ko_KR.md @@ -18,7 +18,8 @@ JavaScript 에 관한 객관식 문제를 [Instagram](https://www.instagram.com/ * [Español](../es-ES/README-ES.md) * [Français](../fr-FR/README_fr-FR.md) * [日本語](../ja-JA/README-ja_JA.md) -* [한국어](../ko-KR/README-ko_KR.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) * [Українська мова](../ua-UA/README-ua_UA.md) diff --git a/pt-BR/README_pt_BR.md b/pt-BR/README_pt_BR.md index b9456327..e6fbb455 100644 --- a/pt-BR/README_pt_BR.md +++ b/pt-BR/README_pt_BR.md @@ -14,7 +14,8 @@ 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) * [日本語](../ja-JA/README-ja_JA.md) -* [한국어](../ko-KR/README-ko_KR.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) * [Українська мова](../ua-UA/README-ua_UA.md) diff --git a/ru-RU/README.md b/ru-RU/README.md index e709d4da..eb6be283 100644 --- a/ru-RU/README.md +++ b/ru-RU/README.md @@ -19,7 +19,8 @@ * [Español](../es-ES/README-ES.md) * [Français](../fr-FR/README_fr-FR.md) * [日本語](../ja-JA/README-ja_JA.md) -* [한국어](../ko-KR/README-ko_KR.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) * [Українська мова](../ua-UA/README-ua_UA.md) diff --git a/th-TH/README.md b/th-TH/README.md index c20e707a..d85eae8b 100644 --- a/th-TH/README.md +++ b/th-TH/README.md @@ -19,13 +19,15 @@ * [Español](../es-ES/README-ES.md) * [Français](../fr-FR/README_fr-FR.md) * [日本語](../ja-JA/README-ja_JA.md) -* [한국어](../ko-KR/README-ko_KR.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) * [Українська мова](../ua-UA/README-ua_UA.md) * [Tiếng Việt](../vi-VI/README-vi.md) * [中文版本](../zh-CN/README-zh_CN.md) * [Türkçe](../tr-TR/README-tr_TR.md) +* [ไทย](../th-TH/README-th_TH.md) --- diff --git a/tr-TR/README-tr_TR.md b/tr-TR/README-tr_TR.md index f09a2ccb..c2d0b5cb 100644 --- a/tr-TR/README-tr_TR.md +++ b/tr-TR/README-tr_TR.md @@ -20,7 +20,8 @@ Mevcut dillerin listesi: * [Español](../es-ES/README-ES.md) * [Français](../fr-FR/README_fr-FR.md) * [日本語](../ja-JA/README-ja_JA.md) -* [한국어](../ko-KR/README-ko_KR.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) * [Українська мова](../ua-UA/README-ua_UA.md) diff --git a/ua-UA/README-ua_UA.md b/ua-UA/README-ua_UA.md index 73677c00..5b0864b6 100644 --- a/ua-UA/README-ua_UA.md +++ b/ua-UA/README-ua_UA.md @@ -14,7 +14,8 @@ * [Español](../es-ES/README-ES.md) * [Français](../fr-FR/README_fr-FR.md) * [日本語](../ja-JA/README-ja_JA.md) -* [한국어](../ko-KR/README-ko_KR.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) * [Українська мова](../ua-UA/README-ua_UA.md) diff --git a/vi-VI/README-vi.md b/vi-VI/README-vi.md index 36ddfb77..e7018466 100644 --- a/vi-VI/README-vi.md +++ b/vi-VI/README-vi.md @@ -15,7 +15,8 @@ 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) * [日本語](../ja-JA/README-ja_JA.md) -* [한국어](../ko-KR/README-ko_KR.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) * [Українська мова](../ua-UA/README-ua_UA.md) From b8172103a7205d08f6f3e78fa5cf891cd62fcdcf Mon Sep 17 00:00:00 2001 From: Askie Lin Date: Sat, 11 Jan 2020 23:49:18 +0800 Subject: [PATCH 411/915] [Feat] Add questions 16-25 of zh-TW translation --- zh-TW/README_zh-TW.md | 298 +++++++++++++++++++++++++++++++++++++++++- 1 file changed, 292 insertions(+), 6 deletions(-) diff --git a/zh-TW/README_zh-TW.md b/zh-TW/README_zh-TW.md index d30a0b92..41ad8909 100644 --- a/zh-TW/README_zh-TW.md +++ b/zh-TW/README_zh-TW.md @@ -2,17 +2,17 @@

JavaScript 進階題目列表

- --- +--- - 我會在我的 [Instagram](https://www.instagram.com/theavocoder) 上發布關於 JavaScript 的複選題,同時也會更新到這個 Repo 當中。更新日期: 2019 年 12 月 24 日 +我會在我的 [Instagram](https://www.instagram.com/theavocoder) 上發布關於 JavaScript 的複選題,同時也會更新到這個 Repo 當中。更新日期: 2019 年 12 月 24 日 - 從基礎到進階程度,測試你有多了解 JavaScript,不僅更新你的知識,更能幫助你的 coding 面試! +從基礎到進階程度,測試你有多了解 JavaScript,不僅更新你的知識,更能幫助你的 coding 面試! :muscle: :rocket: 我每週都會在這個 Repo 中更新新的題目。 答案在題目下方的摺疊區塊,點擊即可展開答案。祝你好運 :heart: - 歡迎和我聯繫!😊
- Instagram || Twitter || LinkedIn || Blog +歡迎和我聯繫!😊
+Instagram || Twitter || LinkedIn || Blog
@@ -475,4 +475,290 @@ JavaScript 是一個**動態型別語言**:我們不指定變數的型別。 在此範例中,JavaScript 將數字型別 `1` 轉換為字串型別,以便函式能回傳一個有意義的值。數字型別(`1`)和字串型別(`'2'`)相加的時候,該數字會被視為字串。我們也能連接不同的字串,比如 `"Hello" + "World"`,而此例是 `"1" + "2"`,它將回傳 `"12"`。

- \ No newline at end of file + + +###### 16. 將會輸出什麽內容? + +```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` + +
答案 +

+ +#### 答案:C + +一元運算子 `++` 加在變數後方: + +1. 回傳值 (這個值是 `0`) +2. 新增值 (變數 `number` 的值現在是 `1`) + +一元運算子 `++` 加在變數前方: + +1. 新增值 (變數 `number` 的值現在是 `2`) +2. 回傳值 (這個值是 `2`) + +因此答案是 `0 2 2`. + +

+
+ +--- + +###### 17. 將會輸出什麽內容? + +```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` + +
答案 +

+ +#### 答案:B + +若你使用標籤樣板字面值(Tagged template literals),第一個參數的值永遠會是一個裝載字串的陣列,函式中的剩下的參數會取得表達式中傳進的變數(`person`、`age`)的值(`'Lydia'`、`21`)! + +

+
+ +--- + +###### 18. 將會輸出什麽內容? + +```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` + +
答案 +

+ +#### 答案:C + +驗證相等,一般型別只比較「值」,物件型別則是比較他們的「參考」。JavaScript 會確認不同物件的參考是否指向同一個記憶體位置。 + +題目中,我們比較的兩個物件擁有不同的記憶體位置:一個物件是作為參數傳遞的物件,它的記憶體位置與另一個拿來判斷是否相等的物件並不相同。 + +這就是 `{ age: 18 } === { age: 18 }` 與 `{ age: 18 } == { age: 18 }` 會回傳 `false` 的原因. + +

+
+ +--- + +###### 19. 將會輸出什麽內容? + +```javascript +function getAge(...args) { + console.log(typeof args); +} + +getAge(21); +``` + +- A: `"number"` +- B: `"array"` +- C: `"object"` +- D: `"NaN"` + +
答案 +

+ +#### 答案:C + +其餘參數(`...args`) 會蒐集傳進來剩下來未使用的參數,成為一個「陣列」。 陣列的型別是「物件」,所以透過 `typeof args` 將會回傳該值的型別,將是 `"object"`。 + +

+
+ +--- + +###### 20. 將會輸出什麽內容? + +```javascript +function getAge() { + 'use strict'; + age = 21; + console.log(age); +} + +getAge(); +``` + +- A: `21` +- B: `undefined` +- C: `ReferenceError` +- D: `TypeError` + +
答案 +

+ +#### 答案:C + +`"use strict"` 可以避免妳意外地宣告全區域變數。使用 `"use strict"` 時,我們若沒有宣告 `age` 這個變數,就直接賦值的話,會拋出 `ReferenceError`,若沒有使用 `"use strict"`,屬性 `age` 就會新增到全域物件上(瀏覽器上的全域物件是 `window`)。 + +

+
+ +--- + +###### 21. `sum` 的值會是? + +```javascript +const sum = eval('10*10+5'); +``` + +- A: `105` +- B: `"105"` +- C: `TypeError` +- D: `"10*10+5"` + +
答案 +

+ +#### 答案:A + +`eval` 會去執行傳進去的「字串」。如果該字串是一個表達式,如題目中的程式碼,那麼 `eval` 會自動執行該表達式 `10 * 10 + 5`,所以答案會是 `105`。 + +

+
+ +--- + +###### 22. cool_secret 這個資料儲存在瀏覽器,存活時間有多久? + +```javascript +sessionStorage.setItem('cool_secret', 123); +``` + +- A: 永遠都可以,資料不會不見。 +- B: 使用者關閉頁籤後,資料才會失效。 +- C: 使用者要關閉一整個瀏覽器,資料才會失效,單純關閉資料不會造成資料消失。 +- D: 使用者關閉電腦後。 + +
答案 +

+ +#### 答案:B + +儲存在 `sessionStorage` 的資料會在使用者「關閉頁籤」後消失。 + +若是使用 `localStorage` 來儲存資料的話,資料則會永遠存在瀏覽器端,直到觸發了 `localStorage.clear()` 才可以清除資料。 + +

+
+ +--- + +###### 23. 將會輸出什麽內容? + +```javascript +var num = 8; +var num = 10; + +console.log(num); +``` + +- A: `8` +- B: `10` +- C: `SyntaxError` +- D: `ReferenceError` + +
答案 +

+ +#### 答案:B + +使用 `var` 關鍵字重複宣告的變數,該值會以最新賦予的值作為它的「值」。這件事情在 `let` or `const` 不會發生,因為這兩個關鍵字所宣告的變數作用域是塊級作用域(block-scoped)。 + +

+
+ +--- + +###### 24. 將會輸出什麽內容? + +```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` + +
答案 +

+ +#### 答案:C + +除了 `Symbol` 以外的物件的 `key` 在底層都是字串類別,即使你建立該物件屬性時,並不是以字串來建立的,所以 `obj.hasOwnProperty('1')` 會回傳 `true`。不過 `set` 不是這樣的規則,在題目中的 `set` 並沒有字串 `'1'` 這個屬性名稱,所以 `set.has('1')` 會回傳 `false`,不過是有數字類別 `1` 的屬性值,`set.has(1)` 將會回傳 `true`。 + +

+
+ +--- + +###### 25. 將會輸出什麽內容? + +```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` + +
答案 +

+ +#### 答案:C + +若物件中的屬性有重複名稱者,第一個屬性會保持它的位置,但值會被最後一個重複屬性名稱的值給取代。 + +

+
+ +--- From 68b821f90761c863365920172e4dd2efd7b1c1e5 Mon Sep 17 00:00:00 2001 From: Askie Lin Date: Sat, 11 Jan 2020 23:55:38 +0800 Subject: [PATCH 412/915] [Fix] Correct answer's colon of Q1-Q15 in zh-TW version --- zh-TW/README_zh-TW.md | 31 ++++++++++++++++--------------- 1 file changed, 16 insertions(+), 15 deletions(-) diff --git a/zh-TW/README_zh-TW.md b/zh-TW/README_zh-TW.md index 41ad8909..baa9920d 100644 --- a/zh-TW/README_zh-TW.md +++ b/zh-TW/README_zh-TW.md @@ -13,6 +13,7 @@ 歡迎和我聯繫!😊
Instagram || Twitter || LinkedIn || Blog + @@ -39,7 +40,7 @@ sayHi()
答案

-#### 答案: D +#### 答案:D 在函式內部,我們首先透過 `var` 關鍵字宣告了 `name` 變數。這表示變數被提升了(記憶體位置在創建時期就被設置好了),直到程式執行到定義變數的那行之前,預設值都是 `undefined`。因為當我們印出 `name` 變數時,還沒有執行到定義變數的那一行程式碼,因此變數的值保持為 `undefined`。 @@ -69,7 +70,7 @@ for (let i = 0; i < 3; i++) {

答案

-#### 答案: C +#### 答案:C 由於 JavaScript 的事件佇列(Event Queue),`setTimeout` 的 `callback` 會在*遍歷結束後*才執行。因為在第一個迴圈中,遍歷 `i` 是透過 `var` 關鍵字宣告的,`var` 屬於 Function scope(需要用 `function() {}` 才能將值鎖在作用域裡面) ,所以 `for` 迴圈會造成變數外流,變成全域變數。在遍歷過程中,我們透過一元運算子 `++` 來遞增 `i` 的值。當 `setTimeout` 的 `callback` 執行的時候,`i` 的值等於 3。 @@ -104,7 +105,7 @@ shape.perimeter()

答案

-#### 答案: B +#### 答案 B 注意 `diameter` 的值是一個一般的函式,但是 `perimeter` 的值是一個箭頭函式。 @@ -131,7 +132,7 @@ shape.perimeter()

答案

-#### 答案: A +#### 答案:A 一元運算子加號 `+`,嘗試將 boolean 布林值型別轉為 number 數字型別。`true` 轉為 number 數字型別的話為 `1`,`false` 爲 `0`。 @@ -164,7 +165,7 @@ const mouse = {

答案

-#### 答案: A +#### 答案:A 在 JavaScript 中,所有物件的 keys 都是字串型別(除非是 Symbol 物件)。儘管我們或許不會定義它們為字串,但它們在底層總會被轉換爲字串。 @@ -199,7 +200,7 @@ console.log(d.greeting)

答案

-#### 答案: A +#### 答案:A 在 JavaScript 中,當設定兩個物件彼此相等時,它們會經由*引用(reference)*進行互動。 @@ -234,7 +235,7 @@ console.log(b === c)

答案

-#### 答案: C +#### 答案:C `new Number()` 是一個内建的函式建構子。它雖然看起來像是個 number,但它實際上並非真正的 number:它有一堆額外的功能,而且它是一個物件。 @@ -273,7 +274,7 @@ freddie.colorChange('orange')

答案

-#### 答案: D +#### 答案:D `colorChange` 是一個靜態方法。靜態方法被設計爲只能被創造它們的建構子使用(也就是 `Chameleon` 中的 `constructor` ),並且不能傳遞給實例。因為 `freddie` 是一個實例,而靜態方法不能被實例使用,因此會抛出 `TypeError` 錯誤。 @@ -297,7 +298,7 @@ console.log(greetign)

答案

-#### 答案: A +#### 答案:A 程式碼印出了一個物件,這是因為我們在全域物件上創建了一個空物件!當我們將 `greeting` 寫錯成 `greetign` 時,JS 解譯器實際上將它視爲 `global.greetign = {}` (或者在瀏覽器中視為 `window.greetign = {}`)。 @@ -326,7 +327,7 @@ bark.animal = 'dog'

答案

-#### 答案: A +#### 答案:A 這在 JavaScript 中是可以的,因爲函式是物件!(除了基本型別之外其他都是物件) @@ -361,7 +362,7 @@ console.log(member.getFullName());

答案

-#### 答案: A +#### 答案:A 你可以為一般物件新增屬性,但建構函式(constructor)無法透過上面的方式來新增屬性。若你想一次性在所有實例上都新增某個屬性,要使用原型的方式。因此本例中,使用以下的方式: @@ -401,7 +402,7 @@ console.log(sarah)

答案

-#### 答案: A +#### 答案:A 對 `sarah` 而言,我們沒有使用 `new` 關鍵字。當使用 `new` 時,`this` 引用我們建立的空物件。沒有使用 `new` 的時候,`this` 引用的是**全域物件**(global object)。 @@ -422,7 +423,7 @@ console.log(sarah)

答案

-#### 答案: D +#### 答案:D 先捕獲,再冒泡!在**捕獲**(capturing)階段中,事件從祖先元素向下傳播到目標元素。當事件到達**目標**(target)元素後,**冒泡**(bubbling)才開始。 @@ -441,7 +442,7 @@ console.log(sarah)

答案

-#### 答案: B +#### 答案:B 除了**基本物件**(base object,使用 `new` 關鍵字建立的物件)以外,所有物件都有原型。基本物件可以使用一些方法和属性,比如 `.toString`,這就是為什麼你可以使用內建的 JavaScript 方法!所有這類在原型上的方法都是可被使用的。雖然 JavaScript 不能直接在物件上找到這些方法,但 JavaScript 會沿著原型鍊找到它們,以便使用。 @@ -468,7 +469,7 @@ sum(1, '2')

答案

-#### 答案: C +#### 答案:C JavaScript 是一個**動態型別語言**:我們不指定變數的型別。值可以在你不知道的情况下自動轉換成另一種型別,稱為**隱含式轉型**(implicit type coercion)。**Coercion** 是指將一種型別轉換成另一種型別。 From 6a44db3f8b3b8595d5c1665bb9595381e741cfae Mon Sep 17 00:00:00 2001 From: Tarabass Date: Sat, 11 Jan 2020 19:34:43 +0100 Subject: [PATCH 413/915] Preface --- nl-NL/README.md | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/nl-NL/README.md b/nl-NL/README.md index 739f2285..16392c68 100644 --- a/nl-NL/README.md +++ b/nl-NL/README.md @@ -1,20 +1,20 @@

-

JavaScript Questions

+

JavaScript Vragen

--- - I post multiple choice JavaScript questions on my [Instagram](https://www.instagram.com/theavocoder) **stories**, which I'll also post here! Last updated: December 24th + Ik plaats JavaScript meerkeuzevragen op mijn [Instagram](https://www.instagram.com/theavocoder) **stories**, welke ik ook hier zal plaatsen! Laatste update: 24 december - 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: + 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: - Feel free to reach out to me! 😊
+ Voel je vrij om contact met mij op te nemen! 😊
Instagram || Twitter || LinkedIn || Blog
--- -
See 17 Available Translations 🇪🇸🇮🇹🇩🇪 🇫🇷🇷🇺🇨🇳🇵🇹 +
Zie alle 17 beschikbare vertalingen

* [English](../en-EN/README.md) From 26d86ac4c27a41486e7bcdc1d6be6f5a520f85a2 Mon Sep 17 00:00:00 2001 From: Tarabass Date: Sat, 11 Jan 2020 19:35:51 +0100 Subject: [PATCH 414/915] Question #1 --- nl-NL/README.md | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/nl-NL/README.md b/nl-NL/README.md index 16392c68..d60416be 100644 --- a/nl-NL/README.md +++ b/nl-NL/README.md @@ -40,7 +40,7 @@ --- -###### 1. What's the output? +###### 1. Wat is de uitkomst? ```javascript function sayHi() { @@ -53,19 +53,19 @@ function sayHi() { sayHi(); ``` -- A: `Lydia` and `undefined` -- B: `Lydia` and `ReferenceError` -- C: `ReferenceError` and `21` -- D: `undefined` and `ReferenceError` +- A: `Lydia` en `undefined` +- B: `Lydia` en `ReferenceError` +- C: `ReferenceError` en `21` +- D: `undefined` en `ReferenceError` -

Answer +
Antwoord

-#### Answer: D +#### Antwoord: D -Within the function, we first declare the `name` variable with the `var` keyword. This means that the variable gets hoisted (memory space is set up during the creation phase) with the default value of `undefined`, until we actually get to the line where we define the variable. We haven't defined the variable yet on the line where we try to log the `name` variable, so it still holds the value of `undefined`. +In de functie declareren we eerst de `name` variabele met het keyword `var`. Dit betekent dat de variabele gehoisted wordt (geheugen wordt vrijgemaakt tijdens de Creation Phase) met de waarde `undefined`, tot het niveau waar we de variabele daadwerkelijk definiëren. We hebben de variable nog niet gedefinieerd tot op de lijn waar we proberen de `name` variabele te loggen naar het console. De variabele is dus wel al aanwezig, maar de waarde is nog steeds `undefined`. -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`. +Variabelen die gedeclareerd worden met het keyword `let` (en `const`) worden ook gehoisted, maar worden niet, in tegenstelling tot `var`, geïnitialiseerd. Ze zijn niet toegankelijk totaan de lijn waarop ze gedeclareerd (geïnitialiseerd) worden. Dit wordt de "temporal dead zone" genoemd. Wanneer we de variabele proberen te benaderen voordat deze gedeclareerd is gooit JavaScript een `ReferenceError`.

From afa4a06e245cf26a9d65814ae0cb547e69f22416 Mon Sep 17 00:00:00 2001 From: Tarabass Date: Sat, 11 Jan 2020 20:24:37 +0100 Subject: [PATCH 415/915] Question #2 --- nl-NL/README.md | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/nl-NL/README.md b/nl-NL/README.md index d60416be..6192dfe3 100644 --- a/nl-NL/README.md +++ b/nl-NL/README.md @@ -72,7 +72,7 @@ Variabelen die gedeclareerd worden met het keyword `let` (en `const`) worden ook --- -###### 2. What's the output? +###### 2. Wat is de uitkomst? ```javascript for (var i = 0; i < 3; i++) { @@ -84,18 +84,18 @@ for (let i = 0; i < 3; i++) { } ``` -- A: `0 1 2` and `0 1 2` -- B: `0 1 2` and `3 3 3` -- C: `3 3 3` and `0 1 2` +- A: `0 1 2` en `0 1 2` +- B: `0 1 2` en `3 3 3` +- C: `3 3 3` en `0 1 2` -
Answer +
Antwoord

-#### Answer: C +#### Antwoord: C -Because of the event queue in JavaScript, the `setTimeout` callback function is called _after_ the loop has been executed. Since the variable `i` in the first loop was declared using the `var` keyword, this value was global. During the loop, we incremented the value of `i` by `1` each time, using the unary operator `++`. By the time the `setTimeout` callback function was invoked, `i` was equal to `3` in the first example. +Vanwege de Event Queue in JavaScript wordt de `setTimeout` callback functie aangeroepen _nadat_ de volledige loop is uitgevoerd. Omndat in de eerste loop de variabele `i` gedeclareerd wordt met het keyword `var`, wordt deze global gemaakt. Tijdens de loop verhogen we de waarde van `i` met `1` door middel van de unary operator `++`. Tegen de tijd dat de `setTimeout` callback functie wordt aangeroepen is de waarde van `i` al `3`, zoals te zien is in het eerste voorbeeld. -In the second loop, the variable `i` was declared using the `let` keyword: variables declared with the `let` (and `const`) keyword are block-scoped (a block is anything between `{ }`). During each iteration, `i` will have a new value, and each value is scoped inside the loop. +In de tweede loop wordt de variabele `i` gedeclareerd met het keyword `let`: variabelen die gedeclareerd worden met het keyword `let` (en `const`) zijn block-scoped (een scope is alles tussen `{ }`). Tijdens elke iteratie zal `i` een nieuwe waarde krijgen, en elke waarde is scoped (te gebruiken tussen `{ }`) in de loop.

From b241b0bdd4232ff1c8b10e8e4fb6b48235669b66 Mon Sep 17 00:00:00 2001 From: Tarabass Date: Sat, 11 Jan 2020 22:25:38 +0100 Subject: [PATCH 416/915] Question #3 --- nl-NL/README.md | 20 ++++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/nl-NL/README.md b/nl-NL/README.md index 6192dfe3..bc6fc3ba 100644 --- a/nl-NL/README.md +++ b/nl-NL/README.md @@ -102,7 +102,7 @@ In de tweede loop wordt de variabele `i` gedeclareerd met het keyword `let`: var --- -###### 3. What's the output? +###### 3. Wat is de uitkomst? ```javascript const shape = { @@ -117,21 +117,21 @@ 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` +- A: `20` en `62.83185307179586` +- B: `20` en `NaN` +- C: `20` en `63` +- D: `NaN` en `63` -
Answer +
Antwoord

-#### Answer: B +#### Antwoord: B -Note that the value of `diameter` is a regular function, whereas the value of `perimeter` is an arrow function. +Merk op dat de waarde van `diameter` een gewone functie is, waarbij de waarde van `perimeter` een zogenaamde arrow functie is. -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). +Bij arrow functies refereert het `this` keyword naar z'n huidige omliggende scope, zo niet bij gewone functie! Dat betekent dat wanneer we `perimeter` aanroepen het niet refereert naar het shape object, maar naar de omliggende scope (window bijvoorbeeld). -There is no value `radius` on that object, which returns `undefined`. +Er is geen propertie `radius` op dat object, daarom wordt `undefined` teruggegeven.

From 9be1ca8e33a14c3d62eb74e67b937b54c5683cde Mon Sep 17 00:00:00 2001 From: Tarabass Date: Sat, 11 Jan 2020 22:36:40 +0100 Subject: [PATCH 417/915] Question 4 --- nl-NL/README.md | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/nl-NL/README.md b/nl-NL/README.md index bc6fc3ba..93202b98 100644 --- a/nl-NL/README.md +++ b/nl-NL/README.md @@ -138,25 +138,25 @@ Er is geen propertie `radius` op dat object, daarom wordt `undefined` teruggegev --- -###### 4. What's the output? +###### 4. Wat is de uitkomst? ```javascript +true; !"Lydia"; ``` -- A: `1` and `false` -- B: `false` and `NaN` -- C: `false` and `false` +- A: `1` en `false` +- B: `false` en `NaN` +- C: `false` en `false` -
Answer +
Antwoord

-#### Answer: A +#### Antwoord: A -The unary plus tries to convert an operand to a number. `true` is `1`, and `false` is `0`. +De unaire plus probeert een operand naar een nummer te converteren. `true` is `1`, en `false` is `0`. -The string `'Lydia'` is a truthy value. What we're actually asking, is "is this truthy value falsy?". This returns `false`. +De string `'Lydia'` is een truthy waarde. Wat we eigenlijk vragen, is "is deze truthy waarde falsy?". Dit geeft `false` terug.

From 41a4cf389374ac374c7002f5cd254fae42795345 Mon Sep 17 00:00:00 2001 From: Tarabass Date: Sat, 11 Jan 2020 23:00:14 +0100 Subject: [PATCH 418/915] Question 5 --- nl-NL/README.md | 22 +++++++++++----------- 1 file changed, 11 insertions(+), 11 deletions(-) diff --git a/nl-NL/README.md b/nl-NL/README.md index 93202b98..71768862 100644 --- a/nl-NL/README.md +++ b/nl-NL/README.md @@ -163,7 +163,7 @@ De string `'Lydia'` is een truthy waarde. Wat we eigenlijk vragen, is "is deze t --- -###### 5. Which one is true? +###### 5. Welk antwoord is juist? ```javascript const bird = { @@ -176,23 +176,23 @@ const mouse = { }; ``` -- 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 +- A: `mouse.bird.size` is ongeldig +- B: `mouse[bird.size]` is ongeldig +- C: `mouse[bird["size"]]` is ongeldig +- D: Alle antwoorden zijn geldig -
Answer +
Antwoord

-#### Answer: A +#### Antwoord: A -In JavaScript, all object keys are strings (unless it's a Symbol). Even though we might not _type_ them as strings, they are always converted into strings under the hood. +In JavaScript zijn alle object keys strings (tenzij het een Symbol is). En ook al zijn ze niet van het _type_ string, onder de motorkap worden ze altijd geconverteerd naar een string. -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. +JavaScript interpreteert (of unboxed) statements. Wanneer we de bracket notatie gebruiken zal de interpreter de opening bracket `[` zien en net zolang doorgaan tot het een closing bracket `]` vindt. Alleen dan zal het de waarde bepalen van de declaratie. -`mouse[bird.size]`: First it evaluates `bird.size`, which is `"small"`. `mouse["small"]` returns `true` +`mouse[bird.size]`: Eerst wordt `bird.size` geëvalueerd, wat `"small"` teruggeeft. `mouse["small"]` geeft `true` terug. -However, with dot notation, this doesn't happen. `mouse` does not have a key called `bird`, which means that `mouse.bird` is `undefined`. Then, we ask for the `size` using dot notation: `mouse.bird.size`. Since `mouse.bird` is `undefined`, we're actually asking `undefined.size`. This isn't valid, and will throw an error similar to `Cannot read property "size" of undefined`. +Echter, met de dot notatie zal dit niet gebeuren. `mouse` heeft geen propertie genaamd `bird`, wat betekent dat `mouse.bird` `undefined` teruggeeft. Daarna vragen we de waarde op van `size` gebruikmakend van de dot notatie. Omdat `mouse.bird` `undefined` is vragen we eigenlijk de waarde op van `undefined.size`. Dit is ongeldig en zal een error gooien gelijk aan ``.

From a00b6bd37174ce88e4eac5fa3e171efc8a45c364 Mon Sep 17 00:00:00 2001 From: Tarabass Date: Sat, 11 Jan 2020 23:10:40 +0100 Subject: [PATCH 419/915] Question 6 --- nl-NL/README.md | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/nl-NL/README.md b/nl-NL/README.md index 71768862..c62f688b 100644 --- a/nl-NL/README.md +++ b/nl-NL/README.md @@ -200,7 +200,7 @@ Echter, met de dot notatie zal dit niet gebeuren. `mouse` heeft geen propertie g --- -###### 6. What's the output? +###### 6. Wat is de uitkomst? ```javascript let c = { greeting: "Hey!" }; @@ -217,18 +217,18 @@ console.log(d.greeting); - D: `ReferenceError` - E: `TypeError` -
Answer +
Antwoord

-#### Answer: A +#### Antwoord: A -In JavaScript, all objects interact by _reference_ when setting them equal to each other. +In JavaScript worden alle objecten verwerkt _by reference_, ook wanneer we de waarde van een variabele vullen met een ander object. -First, variable `c` holds a value to an object. Later, we assign `d` with the same reference that `c` has to the object. +In de eerste instantie verwijst de variabele `c` naar een object. Daarna wordt de waarde van de variabele `d` gezet met de waarde van `c`. Daardoor verwijst `d` naar hetzelfde object als `c`. -When you change one object, you change all of them. +Wanneer je één object veranderd, verander je ze allemaal.

From 728c6cbc897b7c2bb95adb308dadec68f3873f7e Mon Sep 17 00:00:00 2001 From: Tarabass Date: Sat, 11 Jan 2020 23:21:01 +0100 Subject: [PATCH 420/915] Question 7 --- nl-NL/README.md | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/nl-NL/README.md b/nl-NL/README.md index c62f688b..e73dbc3a 100644 --- a/nl-NL/README.md +++ b/nl-NL/README.md @@ -235,7 +235,7 @@ Wanneer je één object veranderd, verander je ze allemaal. --- -###### 7. What's the output? +###### 7. Wat is de uitkomst? ```javascript let a = 3; @@ -252,16 +252,16 @@ console.log(b === c); - C: `true` `false` `false` - D: `false` `true` `true` -
Answer +
Antwoord

-#### Answer: C +#### Antwoord: 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. +`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. -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`. +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. -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.` +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.

From d8c83e1d60c92548bca71990bc8ef8b0fce4392a Mon Sep 17 00:00:00 2001 From: Tarabass Date: Sun, 12 Jan 2020 14:33:30 +0100 Subject: [PATCH 421/915] Question 8 --- nl-NL/README.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/nl-NL/README.md b/nl-NL/README.md index e73dbc3a..bb3bc8e0 100644 --- a/nl-NL/README.md +++ b/nl-NL/README.md @@ -268,7 +268,7 @@ Echter, wanneer we de `===` operator gebruiken wordt er zowel op de _waarde_ als --- -###### 8. What's the output? +###### 8. Wat is de uitkomst? ```javascript class Chameleon { @@ -291,12 +291,12 @@ console.log(freddie.colorChange("orange")); - C: `green` - D: `TypeError` -
Answer +
Antwoord

-#### Answer: D +#### Antwoord: 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. +De `colorChange` functie is static. Static methods zijn alleen toegankelijk binnen de class waarin ze gedefinieerd worden, en zijn niet toegankelijk voor instanties van deze class. Omdat `freddie` een instantie is van `Cameleon` zijn static functies niet beschikbaar op deze instantie: een `TypeError` wordt gegooid.

From 3801d7222f7f689283f540960acd13e5ad585e1b Mon Sep 17 00:00:00 2001 From: Tarabass Date: Sun, 12 Jan 2020 15:11:24 +0100 Subject: [PATCH 422/915] Question 9 --- nl-NL/README.md | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/nl-NL/README.md b/nl-NL/README.md index bb3bc8e0..5e7149f3 100644 --- a/nl-NL/README.md +++ b/nl-NL/README.md @@ -303,7 +303,7 @@ De `colorChange` functie is static. Static methods zijn alleen toegankelijk binn --- -###### 9. What's the output? +###### 9. Wat is de uitkomst? ```javascript let greeting; @@ -315,14 +315,14 @@ console.log(greetign); - B: `ReferenceError: greetign is not defined` - C: `undefined` -
Answer +
Antwoord

-#### Answer: A +#### Antwoord: 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). +Het object wordt gelogd omdat we een leeg object hebben gedefinieerd op het global object! Wanneer we `greeting` verkeerd spellen als `greetign` ziet de JavaScript interpreter dit als `global.greetign = {}` (of `window.greetign = {}` in een browser). -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. +Om dit te voorkomen kunnen we gebruik maken van `"use strict"`. Dit vangt af dat de variabele gedeclareerd moet zijn voordat het een waarde krijgt.

From de4961d41f1f31b4b40ea8f3c2de51be312a8cb3 Mon Sep 17 00:00:00 2001 From: Tarabass Date: Sun, 12 Jan 2020 15:11:45 +0100 Subject: [PATCH 423/915] Question 10 --- nl-NL/README.md | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/nl-NL/README.md b/nl-NL/README.md index 5e7149f3..e288fa8a 100644 --- a/nl-NL/README.md +++ b/nl-NL/README.md @@ -339,19 +339,19 @@ function bark() { bark.animal = "dog"; ``` -- A: Nothing, this is totally fine! -- B: `SyntaxError`. You cannot add properties to a function this way. -- C: `"Woof"` gets logged. +- A: Niets, dit is helemaal goed! +- B: `SyntaxError`. Je kunt op deze manier geen properties toevoegen aan een functie. +- C: `"Woof"` wordt gelogd. - D: `ReferenceError` -
Answer +
Antwoord

-#### Answer: A +#### Antwoord: A -This is possible in JavaScript, because functions are objects! (Everything besides primitive types are objects) +Dit is mogelijk in JavaScript, omdat functies objecten zijn! (Alles behalve primitives zijn objecten) -A function is a special type of object. The code you write yourself isn't the actual function. The function is an object with properties. This property is invocable. +Een functie is een speciaal object. De code die je schrijft is niet de uiteindelijke functie. De functie is een object met properties. Deze properties zijn gewoon benaderbaar.

From f2403c4ab2d428bace3d9ed8def07ef930c1eefa Mon Sep 17 00:00:00 2001 From: Tarabass Date: Sun, 12 Jan 2020 15:12:10 +0100 Subject: [PATCH 424/915] Question 11 --- nl-NL/README.md | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/nl-NL/README.md b/nl-NL/README.md index e288fa8a..031c64c8 100644 --- a/nl-NL/README.md +++ b/nl-NL/README.md @@ -358,7 +358,7 @@ Een functie is een speciaal object. De code die je schrijft is niet de uiteindel --- -###### 11. What's the output? +###### 11. Wat is de uitkomst? ```javascript function Person(firstName, lastName) { @@ -379,12 +379,12 @@ console.log(member.getFullName()); - C: `Lydia Hallie` - D: `undefined` `undefined` -
Answer +
Antwoord

-#### Answer: A +#### Antwoord: A -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, +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() { @@ -392,7 +392,7 @@ Person.prototype.getFullName = function() { }; ``` -would have made `member.getFullName()` work. Why is this beneficial? Say that we added this method to the constructor itself. Maybe not every `Person` instance needed this method. This would waste a lot of memory space, since they would still have that property, which takes of memory space for each instance. Instead, if we only add it to the prototype, we just have it at one spot in memory, yet they all have access to it! +Zou `member.getFullName()` aanroepbaar maken. Waarom is dit voordelig? Zeg dat we deze methode toe zouden kunnen voegen aan de instantie van een object. Misschien hebben niet alle instanties van `Person` deze methode nodig. Dit zou een hoop plaats innemen in het geheugen omdat alle objecten toch deze propertie krijgen. In plaats daarvan kunnen we het alleen aan de prototype van een object toevoegen, en wordt het maar één keer in het geheugen geplaatst, terwijl alle instanties er toch bij kunnen!

From 23044a7d9a4b988b88bb458426a731dbed2d5b1b Mon Sep 17 00:00:00 2001 From: Tarabass Date: Sun, 12 Jan 2020 15:12:29 +0100 Subject: [PATCH 425/915] Question 12 --- nl-NL/README.md | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/nl-NL/README.md b/nl-NL/README.md index 031c64c8..6a3949f2 100644 --- a/nl-NL/README.md +++ b/nl-NL/README.md @@ -399,7 +399,7 @@ Zou `member.getFullName()` aanroepbaar maken. Waarom is dit voordelig? Zeg dat w --- -###### 12. What's the output? +###### 12. Wat is de uitkomst? ```javascript function Person(firstName, lastName) { @@ -414,19 +414,19 @@ 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` +- A: `Person {firstName: "Lydia", lastName: "Hallie"}` en `undefined` +- B: `Person {firstName: "Lydia", lastName: "Hallie"}` en `Person {firstName: "Sarah", lastName: "Smith"}` +- C: `Person {firstName: "Lydia", lastName: "Hallie"}` en `{}` +- D:`Person {firstName: "Lydia", lastName: "Hallie"}` en `ReferenceError` -
Answer +
Antwoord

-#### Answer: A +#### Antwoord: A -For `sarah`, we didn't use the `new` keyword. When using `new`, it refers to the new empty object we create. However, if you don't add `new` it refers to the **global object**! +Bij het declareren van `sarah` maakte we geen gebruik van het `new` keyword. Wanneer we `new` gebruiken refereert dit naar een nieuw object dat we aan willen maken. Als je geen gebruik maakt van `new` refereert het naar het **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. +We zeiden dat `this.firstName` gelijk is aan `"Sarah"` en `this.lastName` gelijk is aan `"Smith"`. Wat we eigenlijk deden is `global.firstName = 'Sarah'` en `global.lastName = 'Smith'` defineren. `sarah` zelf blijft `undefined` omdat we geen waarde teruggeven van de `Person` functie.

From dcde162aeec9577ebf77f35ccd7af4bab190ec16 Mon Sep 17 00:00:00 2001 From: Tarabass Date: Sun, 12 Jan 2020 15:12:47 +0100 Subject: [PATCH 426/915] Question 13 --- nl-NL/README.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/nl-NL/README.md b/nl-NL/README.md index 6a3949f2..dbcadd1b 100644 --- a/nl-NL/README.md +++ b/nl-NL/README.md @@ -433,19 +433,19 @@ We zeiden dat `this.firstName` gelijk is aan `"Sarah"` en `this.lastName` gelijk --- -###### 13. What are the three phases of event propagation? +###### 13. Wat zijn de drie fases van event propagation? - A: Target > Capturing > Bubbling - B: Bubbling > Target > Capturing - C: Target > Bubbling > Capturing - D: Capturing > Target > Bubbling -
Answer +
Antwoord

-#### Answer: D +#### Antwoord: 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. +Tijdens de **capturing** fase gaat het event door alle elementen in de boom naar beneden totaan het target element. Het komt dan bij het **target** element, en **bubbling** begint. From 24c8f75246d743771005d4dcd555dd97e1c74402 Mon Sep 17 00:00:00 2001 From: Tarabass Date: Sun, 12 Jan 2020 15:34:31 +0100 Subject: [PATCH 427/915] Question 14 --- nl-NL/README.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/nl-NL/README.md b/nl-NL/README.md index dbcadd1b..de7ae169 100644 --- a/nl-NL/README.md +++ b/nl-NL/README.md @@ -454,17 +454,17 @@ Tijdens de **capturing** fase gaat het event door alle elementen in de boom naar --- -###### 14. All object have prototypes. +###### 14. Alle objecten bevatten prototypes. - A: true - B: false -

Answer +
Antwoord

-#### Answer: B +#### Antwoord: 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. +Alle objecten bevatten een prototype, behalve het **base object**. Het base object is het object aangemaakt door de gebruiker, of een object dat is aangemaakt gebruikmakend van het `new` keyword. Het base object heeft toegang tot sommige methodes en properties, zoals `.toString`. Dit is de reden waarom je gebruik kan maken van ingebouwde JavaScript methodes! Al deze methodes zijn beschikbaar op het prototype. Wanneer JavaScript de methode niet direct kan vinden op het hoofd object zal het door de prototype chain naar beneden zoeken totdat het gevonden worden. Dit maakt het beschikbaar voor jou.

From 78ec040bd30d4c3a1cb23c72a59aebcefccd58d3 Mon Sep 17 00:00:00 2001 From: Tarabass Date: Sun, 12 Jan 2020 15:34:50 +0100 Subject: [PATCH 428/915] Question 15 --- nl-NL/README.md | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/nl-NL/README.md b/nl-NL/README.md index de7ae169..57363163 100644 --- a/nl-NL/README.md +++ b/nl-NL/README.md @@ -471,7 +471,7 @@ Alle objecten bevatten een prototype, behalve het **base object**. Het base obje --- -###### 15. What's the output? +###### 15. Wat is de uitkomst? ```javascript function sum(a, b) { @@ -486,14 +486,14 @@ sum(1, "2"); - C: `"12"` - D: `3` -
Answer +
Antwoord

-#### Answer: C +#### Antwoord: 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. +JavaScript is een **dynamically typed language**: we specificeren niet van welk type variabelen zijn. Waarden kunnen automatisch worden geconverteerd naar andere typen zonder dat je het weet. Dit wordt _implicit type coercion_ genoemd. **Coercion** is converteren van het ene type naar het andere type. -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"`. +In dit voorbeeld wordt het nummer `1` door JavaScript geconverteerd naar een string, dit om de functie logisch te maken, en de waarde teruggeven. Tijdens het optellen van het numerieke type (`1`) en een string (`'2'`) wordt het nummer gezien als een string. We kunnen strings aaneenschakelen zoals `"Hello" + "World"`. Wat er dus gebeurt hier is `"1" + "2"` wat `"12"` teruggeeft.

From 49ab09b07c0a3b7b4769fb87621ceca7b1f1b481 Mon Sep 17 00:00:00 2001 From: Tarabass Date: Sun, 12 Jan 2020 15:35:08 +0100 Subject: [PATCH 429/915] Question 16 --- nl-NL/README.md | 20 ++++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/nl-NL/README.md b/nl-NL/README.md index 57363163..8e972a60 100644 --- a/nl-NL/README.md +++ b/nl-NL/README.md @@ -500,7 +500,7 @@ In dit voorbeeld wordt het nummer `1` door JavaScript geconverteerd naar een str --- -###### 16. What's the output? +###### 16. Wat is de uitkomst? ```javascript let number = 0; @@ -514,22 +514,22 @@ console.log(number); - C: `0` `2` `2` - D: `0` `1` `2` -
Answer +
Antwoord

-#### Answer: C +#### Antwoord: C -The **postfix** unary operator `++`: +De **postfix** unary operator `++`: -1. Returns the value (this returns `0`) -2. Increments the value (number is now `1`) +1. Geeft de waarde terug (in dit geval `0`) +2. Vermeerderd de waarde (number is nu `1`) -The **prefix** unary operator `++`: +De **prefix** unary operator `++`: -1. Increments the value (number is now `2`) -2. Returns the value (this returns `2`) +1. Vermeerderd de waarde (number is nu `2`) +2. Geeft de waarde terug (in dit geval `2`) -This returns `0 2 2`. +Dit geeft `0 2 2` terug.

From cd32c0026d3f039a3528fd218a5c75d21fccbd50 Mon Sep 17 00:00:00 2001 From: Tarabass Date: Sun, 12 Jan 2020 15:35:53 +0100 Subject: [PATCH 430/915] Question 17 --- nl-NL/README.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/nl-NL/README.md b/nl-NL/README.md index 8e972a60..13ce8626 100644 --- a/nl-NL/README.md +++ b/nl-NL/README.md @@ -536,7 +536,7 @@ Dit geeft `0 2 2` terug. --- -###### 17. What's the output? +###### 17. Wat is de uitkomst? ```javascript function getPersonInfo(one, two, three) { @@ -555,12 +555,12 @@ getPersonInfo`${person} is ${age} years old`; - B: `["", " is ", " years old"]` `"Lydia"` `21` - C: `"Lydia"` `["", " is ", " years old"]` `21` -
Answer +
Antwoord

-#### Answer: B +#### Antwoord: 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! +Als je gebruik maakt van taggedd template literals is de waarde van het eerste argument altijd een array van de meegegeven string waarden. De overgebleven argumenten krijgen de waarde van de doorgegeven expressies!

From 844cfe51f22b837c17b8bf3fadf284c690265afb Mon Sep 17 00:00:00 2001 From: Tarabass Date: Sun, 12 Jan 2020 16:32:36 +0100 Subject: [PATCH 431/915] Prepare questions so only answers need translation --- nl-NL/README.md | 1170 +++++++++++++++++++++++------------------------ 1 file changed, 585 insertions(+), 585 deletions(-) diff --git a/nl-NL/README.md b/nl-NL/README.md index 13ce8626..baf8f12c 100644 --- a/nl-NL/README.md +++ b/nl-NL/README.md @@ -567,7 +567,7 @@ Als je gebruik maakt van taggedd template literals is de waarde van het eerste a --- -###### 18. What's the output? +###### 18. Wat is de uitkomst? ```javascript function checkAge(data) { @@ -587,23 +587,23 @@ checkAge({ age: 18 }); - B: `You are still an adult.` - C: `Hmm.. You don't have an age I guess` -
Answer +
Antwoord

-#### Answer: C +#### Antwoord: 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`. +This is why both `{ age: 18 } === { age: 18 }` en `{ age: 18 } == { age: 18 }` return `false`.

--- -###### 19. What's the output? +###### 19. Wat is de uitkomst? ```javascript function getAge(...args) { @@ -618,10 +618,10 @@ getAge(21); - C: `"object"` - D: `"NaN"` -
Answer +
Antwoord

-#### Answer: C +#### Antwoord: C The rest parameter (`...args`.) lets us "collect" all remaining arguments into an array. An array is an object, so `typeof args` returns `"object"` @@ -630,7 +630,7 @@ The rest parameter (`...args`.) lets us "collect" all remaining arguments into a --- -###### 20. What's the output? +###### 20. Wat is de uitkomst? ```javascript function getAge() { @@ -647,19 +647,19 @@ getAge(); - C: `ReferenceError` - D: `TypeError` -

Answer +
Antwoord

-#### Answer: C +#### Antwoord: 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. +With `"use strict"`, you can make sure that you don't accidentally declare global variables. We never declared the variable `age`, en 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 value of `sum`? +###### 21. Wat is de waarde van `sum`? ```javascript const sum = eval("10*10+5"); @@ -670,10 +670,10 @@ const sum = eval("10*10+5"); - C: `TypeError` - D: `"10*10+5"` -
Answer +
Antwoord

-#### Answer: A +#### Antwoord: 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`. @@ -682,21 +682,21 @@ const sum = eval("10*10+5"); --- -###### 22. How long is cool_secret accessible? +###### 22. Hoe lang is cool_secret benaderbaar? ```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. +- A: Voor altijd, de data gaat niet verloren. +- B: Wanneer de gebruiker de tab sluit. +- C: Wanneer de gebruiker de gehele browser sluit, niet alleen de tab. +- D: Wanneer de gebruiker zijn computer afsluit. -

Answer +
Antwoord

-#### Answer: B +#### Antwoord: B The data stored in `sessionStorage` is removed after closing the _tab_. @@ -707,7 +707,7 @@ If you used `localStorage`, the data would've been there forever, unless for exa --- -###### 23. What's the output? +###### 23. Wat is de uitkomst? ```javascript var num = 8; @@ -721,10 +721,10 @@ console.log(num); - C: `SyntaxError` - D: `ReferenceError` -

Answer +
Antwoord

-#### Answer: B +#### Antwoord: B With the `var` keyword, you can declare multiple variables with the same name. The variable will then hold the latest value. @@ -735,7 +735,7 @@ You cannot do this with `let` or `const` since they're block-scoped. --- -###### 24. What's the output? +###### 24. Wat is de uitkomst? ```javascript const obj = { 1: "a", 2: "b", 3: "c" }; @@ -752,10 +752,10 @@ set.has(1); - C: `true` `true` `false` `true` - D: `true` `true` `true` `true` -

Answer +
Antwoord

-#### Answer: C +#### Antwoord: 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. @@ -766,7 +766,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? +###### 25. Wat is de uitkomst? ```javascript const obj = { a: "one", b: "two", a: "three" }; @@ -778,10 +778,10 @@ console.log(obj); - C: `{ a: "three", b: "two" }` - D: `SyntaxError` -

Answer +
Antwoord

-#### Answer: C +#### Antwoord: 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. @@ -790,16 +790,16 @@ If you have two keys with the same name, the key will be replaced. It will still --- -###### 26. The JavaScript global execution context creates two things for you: the global object, and the "this" keyword. +###### 26. De JavaScript global execution context maakt twee dingen aan voor je: het globale object, en het "this" keyword. - A: true - B: false -- C: it depends +- C: het hangt er vanaf -

Answer +
Antwoord

-#### Answer: A +#### Antwoord: A The base execution context is the global execution context: it's what's accessible everywhere in your code. @@ -808,7 +808,7 @@ The base execution context is the global execution context: it's what's accessib --- -###### 27. What's the output? +###### 27. Wat is de uitkomst? ```javascript for (let i = 1; i < 5; i++) { @@ -822,10 +822,10 @@ for (let i = 1; i < 5; i++) { - C: `1` `2` `4` - D: `1` `3` `4` -

Answer +
Antwoord

-#### Answer: C +#### Antwoord: C The `continue` statement skips an iteration if a certain condition returns `true`. @@ -834,7 +834,7 @@ The `continue` statement skips an iteration if a certain condition returns `true --- -###### 28. What's the output? +###### 28. Wat is de uitkomst? ```javascript String.prototype.giveLydiaPizza = () => { @@ -851,10 +851,10 @@ name.giveLydiaPizza(); - C: `SyntaxError` - D: `undefined` -

Answer +
Antwoord

-#### Answer: A +#### Antwoord: 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! @@ -863,7 +863,7 @@ name.giveLydiaPizza(); --- -###### 29. What's the output? +###### 29. Wat is de uitkomst? ```javascript const a = {}; @@ -881,10 +881,10 @@ console.log(a[b]); - C: `undefined` - D: `ReferenceError` -

Answer +
Antwoord

-#### Answer: B +#### Antwoord: 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`. @@ -897,7 +897,7 @@ Then, we log `a[b]`, which is actually `a["object Object"]`. We just set that to --- -###### 30. What's the output? +###### 30. Wat is de uitkomst? ```javascript const foo = () => console.log("First"); @@ -914,24 +914,24 @@ baz(); - C: `Second` `First` `Third` - D: `Second` `Third` `First` -

Answer +
Antwoord

-#### Answer: B +#### Antwoord: B -We have a `setTimeout` function and invoked it first. Yet, it was logged last. +We have a `setTimeout` function en 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. +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, en 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. +Now, `foo` gets invoked, en `"First"` is being logged. -`foo` is popped off the stack, and `baz` gets invoked. `"Third"` gets logged. +`foo` is popped off the stack, en `baz` gets invoked. `"Third"` gets logged. @@ -939,18 +939,18 @@ The WebAPI can't just add stuff to the stack whenever it's ready. Instead, it pu -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. +This is where an event loop starts to work. An **event loop** looks at the stack en task queue. If the stack is empty, it takes the first thing on the queue en pushes it onto the stack. -`bar` gets invoked, `"Second"` gets logged, and it's popped off the stack. +`bar` gets invoked, `"Second"` gets logged, en it's popped off the stack.

--- -###### 31. What is the event.target when clicking the button? +###### 31. Wat is de event.target wanneer geklikt wordt op de knop? ```html
@@ -962,15 +962,15 @@ This is where an event loop starts to work. An **event loop** looks at the stack
``` -- A: Outer `div` -- B: Inner `div` +- A: Buitenste `div` +- B: Binnenste `div` - C: `button` -- D: An array of all nested elements. +- D: Een array van alle geneste elementen. -
Answer +
Antwoord

-#### Answer: C +#### Antwoord: C The deepest nested element that caused the event is the target of the event. You can stop bubbling by `event.stopPropagation` @@ -979,7 +979,7 @@ The deepest nested element that caused the event is the target of the event. You --- -###### 32. When you click the paragraph, what's the logged output? +###### 32. Wat wordt er gelogd wanneer je op de paragraaf klikt? ```html

@@ -994,19 +994,19 @@ The deepest nested element that caused the event is the target of the event. You - C: `p` - D: `div` -
Answer +
Antwoord

-#### Answer: A +#### Antwoord: 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` en `div`. During event propagation, there are 3 phases: capturing, target, en 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. What's the output? +###### 33. Wat is de uitkomst? ```javascript const person = { name: "Lydia" }; @@ -1024,10 +1024,10 @@ console.log(sayHi.bind(person, 21)); - C: `Lydia is 21` `Lydia is 21` - D: `Lydia is 21` `function` -
Answer +
Antwoord

-#### Answer: D +#### Antwoord: D With both, we can pass the object to which we want the `this` keyword to refer to. However, `.call` is also _executed immediately_! @@ -1038,7 +1038,7 @@ With both, we can pass the object to which we want the `this` keyword to refer t --- -###### 34. What's the output? +###### 34. Wat is de uitkomst? ```javascript function sayHi() { @@ -1053,20 +1053,20 @@ console.log(typeof sayHi()); - C: `"function"` - D: `"undefined"` -

Answer +
Antwoord

-#### Answer: B +#### Antwoord: B 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`, and `symbol`. `"function"` is not a type, since functions are objects, it's of type `"object"`. +FYI: there are only 7 built-in types: `null`, `undefined`, `boolean`, `number`, `string`, `object`, en `symbol`. `"function"` is not a type, since functions are objects, it's of type `"object"`.

--- -###### 35. Which of these values are falsy? +###### 35. Welke van deze waarden zijn falsy? ```javascript 0; @@ -1080,12 +1080,12 @@ 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: Ze zijn allemaal falsy -
Answer +
Antwoord

-#### Answer: A +#### Antwoord: A There are only six falsy values: @@ -1096,14 +1096,14 @@ There are only six falsy values: - `''` (empty string) - `false` -Function constructors, like `new Number` and `new Boolean` are truthy. +Function constructors, like `new Number` en `new Boolean` are truthy.

--- -###### 36. What's the output? +###### 36. Wat is de uitkomst? ```javascript console.log(typeof typeof 1); @@ -1114,10 +1114,10 @@ console.log(typeof typeof 1); - C: `"object"` - D: `"undefined"` -
Answer +
Antwoord

-#### Answer: B +#### Antwoord: B `typeof 1` returns `"number"`. `typeof "number"` returns `"string"` @@ -1127,7 +1127,7 @@ console.log(typeof typeof 1); --- -###### 37. What's the output? +###### 37. Wat is de uitkomst? ```javascript const numbers = [1, 2, 3]; @@ -1140,10 +1140,10 @@ console.log(numbers); - C: `[1, 2, 3, 7 x empty, 11]` - D: `SyntaxError` -

Answer +
Antwoord

-#### Answer: C +#### Antwoord: 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: @@ -1156,7 +1156,7 @@ depending on where you run it (it's different for every browser, node, etc.) --- -###### 38. What's the output? +###### 38. Wat is de uitkomst? ```javascript (() => { @@ -1177,46 +1177,46 @@ depending on where you run it (it's different for every browser, node, etc.) - C: `1` `1` `2` - D: `1` `undefined` `undefined` -

Answer +
Antwoord

-#### Answer: A +#### Antwoord: 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`. +Later, we set this block-scoped variable equal to `1`, en 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`. +Outside of the `catch` block, `x` is still `undefined`, en `y` is `2`. When we want to `console.log(x)` outside of the `catch` block, it returns `undefined`, en `y` returns `2`.

--- -###### 39. Everything in JavaScript is either a... +###### 39. Alles in JavaScript is of een... -- A: primitive or object -- B: function or object -- C: trick question! only objects -- D: number or object +- A: primitieve of een object +- B: functie of een object +- C: lastige vraag! alleen objecten +- D: nummer of een object -
Answer +
Antwoord

-#### Answer: A +#### Antwoord: A -JavaScript only has primitive types and objects. +JavaScript only has primitive types en objects. -Primitive types are `boolean`, `null`, `undefined`, `bigint`, `number`, `string`, and `symbol`. +Primitive types are `boolean`, `null`, `undefined`, `bigint`, `number`, `string`, en `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 object 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'` en 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 object using one of the wrapper classes, i.e. `String`, en then immediately discard the wrapper after the expression evaluates. All primitives except for `null` en `undefined` exhibit this behaviour.

--- -###### 40. What's the output? +###### 40. Wat is de uitkomst? ```javascript [[0, 1], [2, 3]].reduce( @@ -1232,21 +1232,21 @@ What differentiates a primitive from an object is that primitives do not have an - C: `[1, 2, 0, 1, 2, 3]` - D: `[1, 2, 6]` -
Answer +
Antwoord

-#### Answer: C +#### Antwoord: 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]`. +`[1, 2]` is our initial value. This is the value we start with, en the value of the very first `acc`. During the first round, `acc` is `[1,2]`, en `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]` +Then, `[1, 2, 0, 1]` is `acc` en `[2, 3]` is `cur`. We concatenate them, en get `[1, 2, 0, 1, 2, 3]`

--- -###### 41. What's the output? +###### 41. Wat is de uitkomst? ```javascript !!null; @@ -1259,10 +1259,10 @@ Then, `[1, 2, 0, 1]` is `acc` and `[2, 3]` is `cur`. We concatenate them, and ge - C: `false` `true` `true` - D: `true` `true` `false` -
Answer +
Antwoord

-#### Answer: B +#### Antwoord: B `null` is falsy. `!null` returns `true`. `!true` returns `false`. @@ -1275,21 +1275,21 @@ 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? +###### 42. Wat geeft de `setInterval` methode terug in de browser? ```javascript setInterval(() => console.log("Hi"), 1000); ``` -- A: a unique id -- B: the amount of milliseconds specified -- C: the passed function +- A: een uniek id +- B: het aantal opgegeven milliseconden +- C: de doorgegeven functie - D: `undefined` -

Answer +
Antwoord

-#### Answer: A +#### Antwoord: A It returns a unique id. This id can be used to clear that interval with the `clearInterval()` function. @@ -1298,7 +1298,7 @@ It returns a unique id. This id can be used to clear that interval with the `cle --- -###### 43. What does this return? +###### 43. Wat geeft dit terug? ```javascript [..."Lydia"]; @@ -1309,10 +1309,10 @@ It returns a unique id. This id can be used to clear that interval with the `cle - C: `[[], "Lydia"]` - D: `[["L", "y", "d", "i", "a"]]` -

Answer +
Antwoord

-#### Answer: A +#### Antwoord: A A string is an iterable. The spread operator maps every character of an iterable to one element. @@ -1321,7 +1321,7 @@ A string is an iterable. The spread operator maps every character of an iterable --- -###### 44. What's the output? +###### 44. Wat is de uitkomst? ```javascript function* generator(i) { @@ -1338,25 +1338,25 @@ console.log(gen.next().value); - A: `[0, 10], [10, 20]` - B: `20, 20` - C: `10, 20` -- D: `0, 10 and 10, 20` +- D: `0, 10 en 10, 20` -

Answer +
Antwoord

-#### Answer: C +#### Antwoord: 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. +Regular functions cannot be stopped mid-way after invocation. However, a generator function can be "stopped" midway, en 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. +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", en `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`. +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, en 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? +###### 45. Wat geeft dit terug? ```javascript const firstPromise = new Promise((res, rej) => { @@ -1375,19 +1375,19 @@ Promise.race([firstPromise, secondPromise]).then(res => console.log(res)); - C: `"two" "one"` - D: `"one" "two"` -
Answer +
Antwoord

-#### Answer: B +#### Antwoord: 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. +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`), en 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. What's the output? +###### 46. Wat is de uitkomst? ```javascript let person = { name: "Lydia" }; @@ -1402,10 +1402,10 @@ console.log(members); - C: `[{}]` - D: `[{ name: "Lydia" }]` -
Answer +
Antwoord

-#### Answer: D +#### Antwoord: D First, we declare a variable `person` with the value of an object that has a `name` property. @@ -1419,14 +1419,14 @@ 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. +We are only modifying the value of the `person` variable, en 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. What's the output? +###### 47. Wat is de uitkomst? ```javascript const person = { @@ -1444,19 +1444,19 @@ for (const item in person) { - C: `"Lydia", 21` - D: `["name", "Lydia"], ["age", 21]` -
Answer +
Antwoord

-#### Answer: B +#### Antwoord: 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. +With a `for-in` loop, we can iterate through object keys, in this case `name` en `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`, en gets logged. Then, `item` is equal to `age`, which gets logged.

--- -###### 48. What's the output? +###### 48. Wat is de uitkomst? ```javascript console.log(3 + 4 + "5"); @@ -1467,10 +1467,10 @@ console.log(3 + 4 + "5"); - C: `12` - D: `"12"` -
Answer +
Antwoord

-#### Answer: B +#### Antwoord: 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. @@ -1483,7 +1483,7 @@ Operator associativity is the order in which the compiler evaluates the expressi --- -###### 49. What's the value of `num`? +###### 49. Wat is de waarde van `num`? ```javascript const num = parseInt("7*6", 10); @@ -1494,12 +1494,12 @@ const num = parseInt("7*6", 10); - C: `7` - D: `NaN` -

Answer +
Antwoord

-#### Answer: C +#### Antwoord: 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 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 en ignores the following characters. `*` is not a valid number. It only parses `"7"` into the decimal `7`. `num` now holds the value of `7`. @@ -1508,7 +1508,7 @@ Only the first numbers in the string is returned. Based on the _radix_ (the seco --- -###### 50. What's the output`? +###### 50. Wat is de uitkomst? ```javascript [1, 2, 3].map(num => { @@ -1522,12 +1522,12 @@ Only the first numbers in the string is returned. Based on the _radix_ (the seco - C: `[undefined, undefined, undefined]` - D: `[ 3 x empty ]` -

Answer +
Antwoord

-#### Answer: C +#### Antwoord: 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. +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 en 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`. @@ -1536,7 +1536,7 @@ However, we don’t return a value. When we don’t return a value from the func --- -###### 51. What's the output? +###### 51. Wat is de uitkomst? ```javascript function getInfo(member, year) { @@ -1557,10 +1557,10 @@ console.log(person, birthYear); - C: `{ name: "Lydia" }, "1998"` - D: `{ name: "Sarah" }, "1997"` -

Answer +
Antwoord

-#### Answer: A +#### Antwoord: 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). @@ -1573,7 +1573,7 @@ The value of `person` is an object. The argument `member` has a (copied) referen --- -###### 52. What's the output? +###### 52. Wat is de uitkomst? ```javascript function greeting() { @@ -1597,10 +1597,10 @@ sayHi(); - C: `SyntaxError: can only throw Error objects` - D: `Oh no an error: Hello world!` -

Answer +
Antwoord

-#### Answer: D +#### Antwoord: 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'`. @@ -1611,7 +1611,7 @@ With the `catch` statement, we can specify what to do if an exception is thrown --- -###### 53. What's the output? +###### 53. Wat is de uitkomst? ```javascript function Car() { @@ -1628,10 +1628,10 @@ console.log(myCar.make); - C: `ReferenceError` - D: `TypeError` -

Answer +
Antwoord

-#### Answer: B +#### Antwoord: 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"`. @@ -1640,7 +1640,7 @@ When you return a property, the value of the property is equal to the _returned_ --- -###### 54. What's the output? +###### 54. Wat is de uitkomst? ```javascript (() => { @@ -1656,10 +1656,10 @@ console.log(typeof y); - C: `"object", "number"` - D: `"number", "undefined"` -

Answer +
Antwoord

-#### Answer: A +#### Antwoord: A `let x = y = 10;` is actually shorthand for: @@ -1672,14 +1672,14 @@ When we set `y` equal to `10`, we actually add a property `y` to the global obje 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 (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"`. +However, we created a global variable `y` when setting `y` equal to `10`. This value is accessible anywhere in our code. `y` is defined, en holds a value of type `"number"`. `console.log(typeof y)` returns `"number"`.

--- -###### 55. What's the output? +###### 55. Wat is de uitkomst? ```javascript class Dog { @@ -1706,10 +1706,10 @@ pet.bark(); - C: `"Woof I am Mara"`, `undefined` - D: `TypeError`, `TypeError` -
Answer +
Antwoord

-#### Answer: A +#### Antwoord: 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. @@ -1720,7 +1720,7 @@ When we try to invoke something that is not a function, a `TypeError` is thrown. --- -###### 56. What's the output? +###### 56. Wat is de uitkomst? ```javascript const set = new Set([1, 1, 2, 3, 4]); @@ -1733,10 +1733,10 @@ console.log(set); - C: `{1, 1, 2, 3, 4}` - D: `{1, 2, 3, 4}` -

Answer +
Antwoord

-#### Answer: D +#### Antwoord: D The `Set` object is a collection of _unique_ values: a value can only occur once in a set. @@ -1747,7 +1747,7 @@ We passed the iterable `[1, 1, 2, 3, 4]` with a duplicate value `1`. Since we ca --- -###### 57. What's the output? +###### 57. Wat is de uitkomst? ```javascript // counter.js @@ -1769,21 +1769,21 @@ console.log(myCounter); - C: `Error` - D: `NaN` -

Answer +
Antwoord

-#### Answer: C +#### Antwoord: 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. +When we try to increment the value of `myCounter`, it throws an error: `myCounter` is read-only en cannot be modified.

--- -###### 58. What's the output? +###### 58. Wat is de uitkomst? ```javascript const name = "Lydia"; @@ -1798,10 +1798,10 @@ console.log(delete age); - C: `true`, `true` - D: `undefined`, `undefined` -
Answer +
Antwoord

-#### Answer: A +#### Antwoord: 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. @@ -1812,7 +1812,7 @@ The `name` variable was declared with a `const` keyword, so its deletion is not --- -###### 59. What's the output? +###### 59. Wat is de uitkomst? ```javascript const numbers = [1, 2, 3, 4, 5]; @@ -1826,10 +1826,10 @@ console.log(y); - C: `1` - D: `[1]` -

Answer +
Antwoord

-#### Answer: C +#### Antwoord: C We can unpack values from arrays or properties from objects through destructuring. For example: @@ -1839,7 +1839,7 @@ We can unpack values from arrays or properties from objects through destructurin -The value of `a` is now `1`, and the value of `b` is now `2`. What we actually did in the question, is: +The value of `a` is now `1`, en the value of `b` is now `2`. What we actually did in the question, is: ```javascript [y] = [1, 2, 3, 4, 5]; @@ -1854,7 +1854,7 @@ This means that the value of `y` is equal to the first value in the array, which --- -###### 60. What's the output? +###### 60. Wat is de uitkomst? ```javascript const user = { name: "Lydia", age: 21 }; @@ -1868,19 +1868,19 @@ console.log(admin); - C: `{ admin: true, user: ["Lydia", 21] }` - D: `{ admin: true }` -

Answer +
Antwoord

-#### Answer: B +#### Antwoord: 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 }`. +It's possible to combine objects using the spread operator `...`. It lets you create copies of the key/value pairs of one object, en add them to another object. In this case, we create copies of the `user` object, en 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. What's the output? +###### 61. Wat is de uitkomst? ```javascript const person = { name: "Lydia" }; @@ -1896,21 +1896,21 @@ console.log(Object.keys(person)); - C: `{ name: "Lydia"}`, `["name", "age"]` - D: `{ name: "Lydia"}`, `["age"]` -
Answer +
Antwoord

-#### Answer: B +#### Antwoord: 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. +Properties added using the `defineProperty` method are immutable by default. You can override this behavior using the `writable`, `configurable` en `enumerable` properties. This way, the `defineProperty` method gives you a lot more control over the properties you're adding to an object.

--- -###### 62. What's the output? +###### 62. Wat is de uitkomst? ```javascript const settings = { @@ -1928,14 +1928,14 @@ console.log(data); - C: `"["level", "health"]"` - D: `"{"username": "lydiahallie", "level":19, "health":90}"` -
Answer +
Antwoord

-#### Answer: A +#### Antwoord: 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. +The second argument of `JSON.stringify` is the _replacer_. The replacer can either be a function or an array, en lets you control what en 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 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"` en `"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. @@ -1944,7 +1944,7 @@ If the replacer is a _function_, this function gets called on every property in --- -###### 63. What's the output? +###### 63. Wat is de uitkomst? ```javascript let num = 10; @@ -1964,12 +1964,12 @@ console.log(num2); - C: `11`, `11` - D: `11`, `12` -

Answer +
Antwoord

-#### Answer: A +#### Antwoord: 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`, en 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`. @@ -1978,7 +1978,7 @@ The unary operator `++` _first returns_ the value of the operand, _then incremen --- -###### 64. What's the output? +###### 64. Wat is de uitkomst? ```javascript const value = { number: 10 }; @@ -1998,16 +1998,16 @@ multiply(value); - C: `20`, `20`, `20`, `40` - D: `NaN`, `NaN`, `20`, `40` -

Answer +
Antwoord

-#### Answer: C +#### Antwoord: 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 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`, en 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`. @@ -2016,39 +2016,39 @@ The fourth time, we pass the `value` object again. `x.number` was previously mod --- -###### 65. What's the output? +###### 65. Wat is de uitkomst? ```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` +- A: `1` `2` en `3` `3` en `6` `4` +- B: `1` `2` en `2` `3` en `3` `4` +- C: `1` `undefined` en `2` `undefined` en `3` `undefined` en `4` `undefined` +- D: `1` `2` en `undefined` `3` en `undefined` `4` -

Answer +
Antwoord

-#### Answer: D +#### Antwoord: 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. +In this example, we are not returning any values, we are simply logging the values of the accumulator en 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. +On the first call, the accumulator (`x`) is `1`, en the current value (`y`) is `2`. We don't return from the callback function, we log the accumulator en current value: `1` en `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. +If you don't return a value from a function, it returns `undefined`. On the next call, the accumulator is `undefined`, en the current value is `3`. `undefined` en `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. +On the fourth call, we again don't return from the callback function. The accumulator is again `undefined`, en the current value is `4`. `undefined` en `4` get logged.

--- -###### 66. With which constructor can we successfully extend the `Dog` class? +###### 66. Met welke constructor kunnen we succesvol de `Dog` class extenden? ```javascript class Dog { @@ -2086,22 +2086,22 @@ class Labrador extends Dog { - C: 3 - D: 4 -
Answer +
Antwoord

-#### Answer: B +#### Antwoord: 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. +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 en 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. +The `Labrador` class receives two arguments, `name` since it extends `Dog`, en `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. What's the output? +###### 67. Wat is de uitkomst? ```javascript // index.js @@ -2119,21 +2119,21 @@ export const sum = (a, b) => a + b; - C: `running sum.js`, `3`, `running index.js` - D: `running index.js`, `undefined`, `running sum.js` -
Answer +
Antwoord

-#### Answer: B +#### Antwoord: 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 en `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. What's the output? +###### 68. Wat is de uitkomst? ```javascript console.log(Number(2) === Number(2)) @@ -2146,19 +2146,19 @@ console.log(Symbol('foo') === Symbol('foo')) - C: `true`, `false`, `true` - D: `true`, `true`, `true` -
Answer +
Antwoord

-#### Answer: A +#### Antwoord: 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')`, en the second `Symbol('foo')`. These two values are unique en not equal to each other, `Symbol('foo') === Symbol('foo')` returns `false`.

--- -###### 69. What's the output? +###### 69. Wat is de uitkomst? ```javascript const name = "Lydia Hallie" @@ -2171,10 +2171,10 @@ console.log(name.padStart(2)) - C: `" Lydia Hallie"`, `"Lydia Hallie"` (`"[1x whitespace]Lydia Hallie"`, `"Lydia Hallie"`) - D: `"Lydia Hallie"`, `"Lyd"`, -
Answer +
Antwoord

-#### Answer: C +#### Antwoord: 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. @@ -2185,7 +2185,7 @@ If the argument passed to the `padStart` method is smaller than the length of th --- -###### 70. What's the output? +###### 70. Wat is de uitkomst? ```javascript console.log("🥑" + "💻"); @@ -2193,13 +2193,13 @@ console.log("🥑" + "💻"); - A: `"🥑💻"` - B: `257548` -- C: A string containing their code points +- C: Een string die hun code points bevat - D: Error -

Answer +
Antwoord

-#### Answer: A +#### Antwoord: A With the `+` operator, you can concatenate strings. In this case, we are concatenating the string `"🥑"` with the string `"💻"`, resulting in `"🥑💻"`. @@ -2208,7 +2208,7 @@ With the `+` operator, you can concatenate strings. In this case, we are concate --- -###### 71. How can we log the values that are commented out after the console.log statement? +###### 71. Hoe kunnen we de waarden loggen die uitgecommentarieerd zijn achter de console.log statement? ```javascript function* startGame() { @@ -2224,28 +2224,28 @@ 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")` +- A: `game.next("Yes").value` en `game.next().value` +- B: `game.next.value("Yes")` en `game.next.value()` +- C: `game.next().value` en `game.next("Yes").value` +- D: `game.next.value()` en `game.next.value("Yes")` -

Answer +
Antwoord

-#### Answer: C +#### Antwoord: 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. +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`, en `JavaScript loves you back ❤️` gets logged.

--- -###### 72. What's the output? +###### 72. Wat is de uitkomst? ```javascript console.log(String.raw`Hello\nworld`); @@ -2256,10 +2256,10 @@ console.log(String.raw`Hello\nworld`); - C: `Hello\nworld` - D: `Hello\n`
     `world` -
Answer +
Antwoord

-#### Answer: C +#### Antwoord: 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: @@ -2269,7 +2269,7 @@ Which would result in: `"C:DocumentsProjects able.html"` -With `String.raw`, it would simply ignore the escape and print: +With `String.raw`, it would simply ignore the escape en print: `C:\Documents\Projects\table.html` @@ -2280,7 +2280,7 @@ In this case, the string is `Hello\nworld`, which gets logged. --- -###### 73. What's the output? +###### 73. Wat is de uitkomst? ```javascript async function getData() { @@ -2296,10 +2296,10 @@ console.log(data); - C: `Promise {}` - D: `undefined` -

Answer +
Antwoord

-#### Answer: C +#### Antwoord: 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. @@ -2314,7 +2314,7 @@ This would've logged `"I made it!"` --- -###### 74. What's the output? +###### 74. Wat is de uitkomst? ```javascript function addToList(item, list) { @@ -2330,12 +2330,12 @@ console.log(result); - C: `true` - D: `undefined` -

Answer +
Antwoord

-#### Answer: B +#### Antwoord: 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 returns the _length_ of the new array! Previously, the array contained one element (the string `"banana"`) en had a length of `1`. After adding the string `"apple"` to the array, the array contains two elements, en 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. @@ -2344,7 +2344,7 @@ The `push` method modifies the original array. If you wanted to return the _arra --- -###### 75. What's the output? +###### 75. Wat is de uitkomst? ```javascript const box = { x: 10, y: 20 }; @@ -2362,23 +2362,23 @@ console.log(shape); - C: `{ x: 100 }` - D: `ReferenceError` -

Answer +
Antwoord

-#### Answer: B +#### Antwoord: 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)` returns true, since the variable `shape` has a reference to a frozen object. +When we create the variable `shape` en 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. -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. +Since `shape` is frozen, en since the value of `x` is not an object, we cannot modify the property `x`. `x` is still equal to `10`, en `{ x: 10, y: 20 }` gets logged.

--- -###### 76. What's the output? +###### 76. Wat is de uitkomst? ```javascript const { name: myName } = { name: "Lydia" }; @@ -2391,10 +2391,10 @@ console.log(name); - C: `undefined` - D: `ReferenceError` -
Answer +
Antwoord

-#### Answer: D +#### Antwoord: 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`. @@ -2407,7 +2407,7 @@ Since we try to log `name`, a variable that is not defined, a ReferenceError get --- -###### 77. Is this a pure function? +###### 77. Is dit een pure function? ```javascript function sum(a, b) { @@ -2415,24 +2415,24 @@ function sum(a, b) { } ``` -- A: Yes -- B: No +- A: Ja +- B: Nee -

Answer +
Antwoord

-#### Answer: A +#### Antwoord: 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. +The `sum` function always returns the same result. If we pass `1` en `2`, it will _always_ return `3` without side effects. If we pass `5` en `10`, it will _always_ return `15`, en so on. This is the definition of a pure function.

--- -###### 78. What is the output? +###### 78. Wat is de uitkomst? ```javascript const add = () => { @@ -2459,27 +2459,27 @@ console.log(addFunction(5 * 2)); - C: `Calculated! 20` `From cache! 20` `From cache! 20` - D: `Calculated! 20` `From cache! 20` `Error` -
Answer +
Antwoord

-#### Answer: C +#### Antwoord: 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. +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 en 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 }`. +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`, en the else block gets executed: `Calculated! 20` gets logged, en 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 second time, the `cache` object contains the value that gets returned for `10`. The condition of the if-statement `num in cache` returns `true`, en `'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. +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`, en `'From cache! 20'` gets logged.

--- -###### 79. What is the output? +###### 79. Wat is de uitkomst? ```javascript const myLifeSummedUp = ["☕", "💻", "🍷", "🍫"] @@ -2493,15 +2493,15 @@ for (let item of myLifeSummedUp) { } ``` -- 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: `0` `1` `2` `3` en `"☕"` ` "💻"` `"🍷"` `"🍫"` +- B: `"☕"` ` "💻"` `"🍷"` `"🍫"` en `"☕"` ` "💻"` `"🍷"` `"🍫"` +- C: `"☕"` ` "💻"` `"🍷"` `"🍫"` en `0` `1` `2` `3` +- D: `0` `1` `2` `3` en `{0: "☕", 1: "💻", 2: "🍷", 3: "🍫"}` -
Answer +
Antwoord

-#### Answer: A +#### Antwoord: 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: @@ -2516,7 +2516,7 @@ With a _for-of_ loop, we can iterate over **iterables**. An array is an iterable --- -###### 80. What is the output? +###### 80. Wat is de uitkomst? ```javascript const list = [1 + 2, 1 * 2, 1 / 2] @@ -2528,21 +2528,21 @@ console.log(list) - C: `[3, 2, 0.5]` - D: `[1, 1, 1]` -

Answer +
Antwoord

-#### Answer: C +#### Antwoord: 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. +Array elements can hold any value. Numbers, strings, objects, other arrays, null, boolean values, undefined, en other expressions such as dates, functions, en calculations. -The element will be equal to the returned value. `1 + 2` returns `3`, `1 * 2` returns `2`, and `1 / 2` returns `0.5`. +The element will be equal to the returned value. `1 + 2` returns `3`, `1 * 2` returns `2`, en `1 / 2` returns `0.5`.

--- -###### 81. What is the output? +###### 81. Wat is de uitkomst? ```javascript function sayHi(name) { @@ -2557,10 +2557,10 @@ console.log(sayHi()) - C: `Hi there, null` - D: `ReferenceError` -
Answer +
Antwoord

-#### Answer: B +#### Antwoord: 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. @@ -2575,7 +2575,7 @@ In this case, if we didn't pass a value or if we passed `undefined`, `name` woul --- -###### 82. What is the output? +###### 82. Wat is de uitkomst? ```javascript var status = "😎" @@ -2595,15 +2595,15 @@ setTimeout(() => { }, 0) ``` -- A: `"🥑"` and `"😍"` -- B: `"🥑"` and `"😎"` -- C: `"😍"` and `"😎"` -- D: `"😎"` and `"😎"` +- A: `"🥑"` en `"😍"` +- B: `"🥑"` en `"😎"` +- C: `"😍"` en `"😎"` +- D: `"😎"` en `"😎"` -

Answer +
Antwoord

-#### Answer: B +#### Antwoord: 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 `"🥑"`. @@ -2615,7 +2615,7 @@ With the `call` method, we can change the object to which the `this` keyword ref --- -###### 83. What is the output? +###### 83. Wat is de uitkomst? ```javascript const person = { @@ -2634,10 +2634,10 @@ console.log(person) - C: `{ name: "Lydia", age: 21, city: undefined }` - D: `"Amsterdam"` -

Answer +
Antwoord

-#### Answer: A +#### Antwoord: 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`. @@ -2652,7 +2652,7 @@ When logging the `person` object, the unmodified object gets returned. --- -###### 84. What is the output? +###### 84. Wat is de uitkomst? ```javascript function checkAge(age) { @@ -2673,19 +2673,19 @@ console.log(checkAge(21)) - C: `ReferenceError` - D: `undefined` -

Answer +
Antwoord

-#### Answer: C +#### Antwoord: 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` en `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? +###### 85. Welke informatie zal worden gelogd? ```javascript fetch('https://www.website.com/api/user/1') @@ -2693,15 +2693,15 @@ fetch('https://www.website.com/api/user/1') .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. +- A: Het resultaat van de `fetch` methode. +- B: Het resultaat van de tweede aanroep van de `fetch` methode. +- C: Het resultaat van de callback in de vorige `.then()`. +- D: Het zal altijd undefined zijn. -
Answer +
Antwoord

-#### Answer: C +#### Antwoord: 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. @@ -2710,7 +2710,7 @@ The value of `res` in the second `.then` is equal to the returned value of the p --- -###### 86. Which option is a way to set `hasName` equal to `true`, provided you cannot pass `true` as an argument? +###### 86. Welke optie is een manier om `hasName` te vullen met de boolean waarde `true`, terwijl je geen `true` mee kan geven als argument? ```javascript function getName(name) { @@ -2723,10 +2723,10 @@ function getName(name) { - C: `new Boolean(name)` - D: `name.length` -

Answer +
Antwoord

-#### Answer: A +#### Antwoord: 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`. @@ -2741,7 +2741,7 @@ By setting `hasName` equal to `name`, you set `hasName` equal to whatever value --- -###### 87. What's the output? +###### 87. Wat is de uitkomst? ```javascript console.log("I want pizza"[0]) @@ -2752,21 +2752,21 @@ console.log("I want pizza"[0]) - C: `SyntaxError` - D: `undefined` -

Answer +
Antwoord

-#### Answer: B +#### Antwoord: 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 an character on a specific index in a string, you can use bracket notation. The first character in the string has index 0, en so on. In this case we want to get the element which index is 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 en below. In that case, use `.charAt()`

--- -###### 88. What's the output? +###### 88. Wat is de uitkomst? ```javascript function sum(num1, num2 = num1) { @@ -2781,12 +2781,12 @@ sum(10) - C: `ReferenceError` - D: `undefined` -
Answer +
Antwoord

-#### Answer: B +#### Antwoord: 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, en 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. @@ -2795,7 +2795,7 @@ If you're trying to set a default parameter's value equal to a parameter which i --- -###### 89. What's the output? +###### 89. Wat is de uitkomst? ```javascript // module.js @@ -2811,23 +2811,23 @@ 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` +- D: Globale object of `module.js` -

Answer +
Antwoord

-#### Answer: A +#### Antwoord: 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, en a named export. The default export is a function which returns the string `"Hello World"`, en 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 en their corresponding values.

--- -###### 90. What's the output? +###### 90. Wat is de uitkomst? ```javascript class Person { @@ -2845,10 +2845,10 @@ console.log(typeof member) - C: `"object"` - D: `"string"` -
Answer +
Antwoord

-#### Answer: C +#### Antwoord: C Classes are syntactical sugar for function constructors. The equivalent of the `Person` class as a function constructor would be: @@ -2865,7 +2865,7 @@ Calling a function constructor with `new` results in the creation of an instance --- -###### 91. What's the output? +###### 91. Wat is de uitkomst? ```javascript let newList = [1, 2, 3].push(4) @@ -2878,10 +2878,10 @@ console.log(newList.push(5)) - C: `[1, 2, 3, 4]` - D: `Error` -

Answer +
Antwoord

-#### Answer: D +#### Antwoord: 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`. @@ -2892,7 +2892,7 @@ Then, we try to use the `.push` method on `newList`. Since `newList` is the nume --- -###### 92. What's the output? +###### 92. Wat is de uitkomst? ```javascript function giveLydiaPizza() { @@ -2910,10 +2910,10 @@ console.log(giveLydiaChocolate.prototype) - C: `{ constructor: ...}` `{}` - D: `{ constructor: ...}` `undefined` -

Answer +
Antwoord

-#### Answer: D +#### Antwoord: 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`. @@ -2922,7 +2922,7 @@ Regular functions, such as the `giveLydiaPizza` function, have a `prototype` pro --- -###### 93. What's the output? +###### 93. Wat is de uitkomst? ```javascript const person = { @@ -2935,31 +2935,31 @@ for (const [x, y] of Object.entries(person)) { } ``` -- A: `name` `Lydia` and `age` `21` -- B: `["name", "Lydia"]` and `["age", 21]` -- C: `["name", "age"]` and `undefined` +- A: `name` `Lydia` en `age` `21` +- B: `["name", "Lydia"]` en `["age", 21]` +- C: `["name", "age"]` en `undefined` - D: `Error` -

Answer +
Antwoord

-#### Answer: A +#### Antwoord: A -`Object.entries(person)` returns an array of nested arrays, containing the keys and objects: +`Object.entries(person)` returns an array of nested arrays, containing the keys en 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. +The first subarray is `[ "name", "Lydia" ]`, with `x` equal to `"name"`, en `y` equal to `"Lydia"`, which get logged. +The second subarray is `[ "age", 21 ]`, with `x` equal to `"age"`, en `y` equal to `21`, which get logged.

--- -###### 94. What's the output? +###### 94. Wat is de uitkomst? ```javascript function getItems(fruitList, ...args, favoriteFruit) { @@ -2974,12 +2974,12 @@ getItems(["banana", "apple"], "pear", "orange") - C: `["banana", "apple", ["pear"], "orange"]` - D: `SyntaxError` -
Answer +
Antwoord

-#### Answer: D +#### Antwoord: 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, **en can only be the last parameter**! In this example, the rest parameter was the second parameter. This is not possible, en will throw a syntax error. ```javascript function getItems(fruitList, favoriteFruit, ...args) { @@ -2995,7 +2995,7 @@ The above example works. This returns the array `[ 'banana', 'apple', 'orange', --- -###### 95. What's the output? +###### 95. Wat is de uitkomst? ```javascript function nums(a, b) { @@ -3012,19 +3012,19 @@ 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` +- A: `a is bigger`, `6` en `b is bigger`, `3` +- B: `a is bigger`, `undefined` en `b is bigger`, `undefined` +- C: `undefined` en `undefined` - D: `SyntaxError` -

Answer +
Antwoord

-#### Answer: B +#### Antwoord: 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: +Here, we wrote a `return` statement, en 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; @@ -3038,7 +3038,7 @@ This means that `a + b` is never reached, since a function stops running after t --- -###### 96. What's the output? +###### 96. Wat is de uitkomst? ```javascript class Person { @@ -3062,10 +3062,10 @@ console.log(member.name) - C: `Error: cannot redeclare Person` - D: `SyntaxError` -

Answer +
Antwoord

-#### Answer: B +#### Antwoord: 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"`. @@ -3074,7 +3074,7 @@ We can set classes equal to other classes/function constructors. In this case, w --- -###### 97. What's the output? +###### 97. Wat is de uitkomst? ```javascript const info = { @@ -3085,17 +3085,17 @@ 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 `[]` +- A: `{Symbol('a'): 'b'}` en `["{Symbol('a')"]` +- B: `{}` en `[]` +- C: `{ a: "b" }` en `["a"]` +- D: `{Symbol('a'): 'b'}` en `[]` -

Answer +
Antwoord

-#### Answer: D +#### Antwoord: 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. +A Symbol is not _enumerable_. The Object.keys method returns all _enumerable_ key properties on an object. The Symbol won't be visible, en 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). @@ -3104,7 +3104,7 @@ This is one of the many qualities of a symbol: besides representing an entirely --- -###### 98. What's the output? +###### 98. Wat is de uitkomst? ```javascript const getList = ([x, ...y]) => [x, y] @@ -3117,21 +3117,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: `[1, [2, 3, 4]]` en `undefined` +- B: `[1, [2, 3, 4]]` en `{ name: "Lydia", age: 21 }` +- C: `[1, 2, 3, 4]` en `{ name: "Lydia", age: 21 }` +- D: `Error` en `{ name: "Lydia", age: 21 }` -

Answer +
Antwoord

-#### Answer: A +#### Antwoord: 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. + With the rest parameter `...y`, we put all "remaining" arguments in an array. The remaining arguments are `2`, `3` en `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: @@ -3144,7 +3144,7 @@ Since no value gets returned in this case, the function returns `undefined`. --- -###### 99. What's the output? +###### 99. Wat is de uitkomst? ```javascript const name = "Lydia" @@ -3157,10 +3157,10 @@ console.log(name()) - C: `TypeError` - D: `undefined` -

Answer +
Antwoord

-#### Answer: C +#### Antwoord: C The variable `name` holds the value of a string, which is not a function, thus cannot invoke. @@ -3174,7 +3174,7 @@ ReferenceErrors get thrown when JavaScript isn't able to find a reference to a v --- -###### 100. What's the value of output? +###### 100. Wat is de waarde van output? ```javascript // 🎉✨ This is my 100th question! ✨🎉 @@ -3188,10 +3188,10 @@ 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` -

Answer +
Antwoord

-#### Answer: B +#### Antwoord: 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. @@ -3202,7 +3202,7 @@ You should${'' && `n't`} see a therapist after so much JavaScript lol` --- -###### 101. What's the value of output? +###### 101. Wat is de waarde van output? ```javascript const one = (false || {} || null) @@ -3217,14 +3217,14 @@ console.log(one, two, three) - C: `{}` `""` `[]` - D: `null` `null` `true` -

Answer +
Antwoord

-#### Answer: C +#### Antwoord: 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 `{}`. +`(false || {} || null)`: the empty object `{}` is a truthy value. This is the first (en only) truthy value, which gets returned. `one` is equal to `{}`. `(null || false || "")`: all operands are falsy values. This means that the past operand, `""` gets returned. `two` is equal to `""`. @@ -3235,7 +3235,7 @@ With the `||` operator, we can return the first truthy operand. If all values ar --- -###### 102. What's the value of output? +###### 102. Wat is de waarde van output? ```javascript const myPromise = () => Promise.resolve('I have resolved!') @@ -3254,32 +3254,32 @@ 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` +- A: `I have resolved!`, `second` en `I have resolved!`, `second` +- B: `second`, `I have resolved!` en `second`, `I have resolved!` +- C: `I have resolved!`, `second` en `second`, `I have resolved!` +- D: `second`, `I have resolved!` en `I have resolved!`, `second` -

Answer +
Antwoord

-#### Answer: D +#### Antwoord: 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._ +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), en 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` en the `await` keyword in an `async` function. Although we can get a promise's value with both `.then` en `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 befoer 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`, en only once that happened, we moved to the next line: `second` got logged.

--- -###### 103. What's the value of output? +###### 103. Wat is de waarde van output? ```javascript const set = new Set() @@ -3298,16 +3298,16 @@ for (let item of set) { - C: `3`, `Lydia2`, `[object Object]2` - D: `"12"`, `Lydia2`, `[object Object]2` -
Answer +
Antwoord

-#### Answer: C +#### Antwoord: 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"`. +However, the second one is a string `"Lydia"`. `"Lydia"` is a string en `2` is a number: `2` gets coerced into a string. `"Lydia"` en `"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"`. @@ -3316,7 +3316,7 @@ However, the second one is a string `"Lydia"`. `"Lydia"` is a string and `2` is --- -###### 104. What's its value? +###### 104. Wat is de waarde? ```javascript Promise.resolve(5) @@ -3327,10 +3327,10 @@ Promise.resolve(5) - C: `Promise {: 5}` - D: `Error` -

Answer +
Antwoord

-#### Answer: C +#### Antwoord: 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. @@ -3341,7 +3341,7 @@ In this case, we just passed the numerical value `5`. It returns a resolved prom --- -###### 105. What's its value? +###### 105. Wat is de waarde? ```javascript function compareMembers(person1, person2 = person) { @@ -3362,25 +3362,25 @@ compareMembers(person) - C: `ReferenceError` - D: `SyntaxError` -

Answer +
Antwoord

-#### Answer: B +#### Antwoord: 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`. +We set the default value for `person2` equal to the `person` object, en 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, en `They are the same!` gets logged.

--- -###### 106. What's its value? +###### 106. Wat is de waarde? ```javascript const colorConfig = { @@ -3401,23 +3401,23 @@ console.log(colorConfig.colors[1]) - C: `undefined` - D: `TypeError` -
Answer +
Antwoord

-#### Answer: D +#### Antwoord: 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 proprety 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. +JavaScript interprets (or unboxes) statements. When we use bracket notation, it sees the first opening bracket `[` en 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? +###### 107. Wat is de waarde? ```javascript console.log('❤️' === '❤️') @@ -3426,10 +3426,10 @@ console.log('❤️' === '❤️') - A: `true` - B: `false` -
Answer +
Antwoord

-#### Answer: A +#### Antwoord: 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. @@ -3438,7 +3438,7 @@ Under the hood, emojis are unicodes. The unicodes for the heart emoji is `"U+276 --- -###### 108. Which of these methods modifies the original array? +###### 108. Welke van onderstaande methoden passen de originele array aan? ```javascript const emojis = ['✨', '🥑', '😍'] @@ -3456,21 +3456,21 @@ emojis.splice(1, 2, '✨') - C: `map` `slice` `splice` - D: `splice` -

Answer +
Antwoord

-#### Answer: D +#### Antwoord: 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. +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 `'🥑'` en `'😍'`) en added the ✨ emoji instead. -`map`, `filter` and `slice` return a new array, `find` returns an element, and `reduce` returns a reduced value. +`map`, `filter` en `slice` return a new array, `find` returns an element, en `reduce` returns a reduced value.

--- -###### 109. What's the output? +###### 109. Wat is de uitkomst? ```javascript const food = ['🍕', '🍫', '🥑', '🍔'] @@ -3486,37 +3486,37 @@ console.log(food) - C: `['🍝', '🍕', '🍫', '🥑', '🍔']` - D: `ReferenceError` -
Answer +
Antwoord

-#### Answer: A +#### Antwoord: 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 act 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) +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, en 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, `['🍕', '🍫', '🥑', '🍔']`. +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, en 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? +###### 110. Wat doet onderstaande methode? ```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: Ontleedt JSON naar een JavaScript waarde +- B: Ontleedt een JavaScript object naar JSON +- C: Ontleedt elke JavaScript waarde naar JSON +- D: Ontleedt JSON alleen naar een JavaScript object -
Answer +
Antwoord

-#### Answer: A +#### Antwoord: A With the `JSON.parse()` method, we can parse JSON string to a JavaScript value. @@ -3539,7 +3539,7 @@ JSON.parse(jsonArray) // { name: 'Lydia' } --- -###### 111. What's the output? +###### 111. Wat is de uitkomst? ```javascript let name = 'Lydia' @@ -3557,14 +3557,14 @@ getName() - C: `undefined` - D: `ReferenceError` -

Answer +
Antwoord

-#### Answer: D +#### Antwoord: 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'`. +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, en 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`. +Variables with the `let` keyword (en `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`. @@ -3583,7 +3583,7 @@ getName() // Lydia --- -###### 112. What's the output? +###### 112. Wat is de uitkomst? ```javascript function* generatorOne() { @@ -3601,15 +3601,15 @@ 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']` +- A: `a` en `a` +- B: `a` en `undefined` +- C: `['a', 'b', 'c']` en `a` +- D: `a` en `['a', 'b', 'c']` -

Answer +
Antwoord

-#### Answer: C +#### Antwoord: 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). @@ -3634,7 +3634,7 @@ console.log(two.next().value) // undefined --- -###### 113. What's the output? +###### 113. Wat is de uitkomst? ```javascript console.log(`${(x => x)('I love')} to program`) @@ -3645,10 +3645,10 @@ console.log(`${(x => x)('I love')} to program`) - C: `${(x => x)('I love') to program` - D: `TypeError` -

Answer +
Antwoord

-#### Answer: A +#### Antwoord: 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`. @@ -3657,7 +3657,7 @@ Expressions within template literals are evaluated first. This means that the st --- -###### 114. What will happen? +###### 114. Wat zal er gebeuren? ```javascript let config = { @@ -3669,15 +3669,15 @@ let config = { 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` +- A: De `setInterval` callback zal niet worden aangeroepen +- B: De `setInterval` callback zal één keer aangeroepen worden +- C: De `setInterval` callback zal nog steeds elke seconde aangeroepen worden +- D: We roepen `config.alert()` nooit aan, config is `null` -

Answer +
Antwoord

-#### Answer: C +#### Antwoord: 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). @@ -3686,7 +3686,7 @@ Normally when we set objects equal to `null`, those objects get _garbage collect --- -###### 115. Which method(s) will return the value `'Hello world!'`? +###### 115. Welke methode(n) zal de waarde `'Hello world!'` teruggeven? ```javascript const myMap = new Map() @@ -3704,15 +3704,15 @@ myMap.get(() => 'greeting') - A: 1 - B: 2 -- C: 2 and 3 -- D: All of them +- C: 2 en 3 +- D: Allemaal -

Answer +
Antwoord

-#### Answer: B +#### Antwoord: 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!' }`. +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, en the value will be the second argument passed to the `set` function. The key is the _function_ `() => 'greeting'` in this case, en 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. @@ -3722,7 +3722,7 @@ When adding a key/value pair using the `set` method, the key will be the value o --- -###### 116. What's the output? +###### 116. Wat is de uitkomst? ```javascript const person = { @@ -3747,14 +3747,14 @@ console.log(person) - C: `{name: "Lydia", age: 22}` - D: `{name: "Lydia", age: 23}` -

Answer +
Antwoord

-#### Answer: C +#### Antwoord: 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. +Both the `changeAge` en `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 }`. +First, we invoke the `changeAge` function en 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 }`. @@ -3763,7 +3763,7 @@ Then, we invoke the `changeAgeAndName` function, however we don't pass a paramet --- -###### 117. Which of the following options will return `6`? +###### 117. Welke van onderstaande opties zal `6` teruggeven? ```javascript function sumValues(x, y, z) { @@ -3776,19 +3776,19 @@ function sumValues(x, y, z) { - C: `sumValues(...[1, 2, 3])` - D: `sumValues([1, 2, 3])` -

Answer +
Antwoord

-#### Answer: C +#### Antwoord: 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. +With the spread operator `...`, we can _spread_ iterables to individual elements. The `sumValues` function receives three arguments: `x`, `y` en `z`. `...[1, 2, 3]` will result in `1, 2, 3`, which we pass to the `sumValues` function.

--- -###### 118. What's the output? +###### 118. Wat is de uitkomst? ```javascript let num = 1; @@ -3802,10 +3802,10 @@ console.log(list[(num += 1)]); - C: `SyntaxError` - D: `ReferenceError` -
Answer +
Antwoord

-#### Answer: B +#### Antwoord: 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 🥰. @@ -3814,7 +3814,7 @@ With the `+=` operand, we're incrementing the value of `num` by `1`. `num` had t --- -###### 119. What's the output? +###### 119. Wat is de uitkomst? ```javascript const person = { @@ -3840,16 +3840,16 @@ console.log(member.getLastName?.()); - C: `Mara` `null` `Lydia Hallie` `null` - D: `null` `ReferenceError` `null` `ReferenceError` -

Answer +
Antwoord

-#### Answer: B +#### Antwoord: 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`. +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 en 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?.name`: `person` has a property named `pet`: `person.pet` is not nullish. It has a property called `name`, en 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`. +`person.getFullName?.()`: `person` has a property named `getFullName`: `person.getFullName()` is not nullish en can get invoked, which returns `Lydia Hallie`. `member.getLastName?.()`: `member` is not defined: `member.getLastName()` is nullish. The expression returns `undefined`.

@@ -3857,7 +3857,7 @@ With the optional chaining operator `?.`, we no longer have to explicitly check --- -###### 120. What's the output? +###### 120. Wat is de uitkomst? ```javascript const groceries = ["banana", "apple", "peanuts"]; @@ -3874,19 +3874,19 @@ if (groceries.indexOf("banana")) { - C: `undefined` - D: `1` -
Answer +
Antwoord

-#### Answer: B +#### Antwoord: 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. +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, en `We don't have to buy bananas!` gets logged.

--- -###### 121. What's the output? +###### 121. Wat is de uitkomst? ```javascript const config = { @@ -3904,10 +3904,10 @@ console.log(config.language); - C: `[]` - D: `undefined` -
Answer +
Antwoord

-#### Answer: D +#### Antwoord: 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. @@ -3916,7 +3916,7 @@ The `language` method is a `setter`. Setters don't hold an actual value, their p --- -###### 122. What's the output? +###### 122. Wat is de uitkomst? ```javascript const name = "Lydia Hallie"; @@ -3930,12 +3930,12 @@ console.log(!typeof name === "string"); - C: `false` `false` - D: `true` `true` -

Answer +
Antwoord

-#### Answer: C +#### Antwoord: 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`. +`typeof name` returns `"string"`. The string `"string"` is a truthy value, so `!typeof name` returns the boolean value `false`. `false === "object"` en `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`) @@ -3944,7 +3944,7 @@ console.log(!typeof name === "string"); --- -###### 123. What's the output? +###### 123. Wat is de uitkomst? ```javascript const add = x => y => z => { @@ -3960,19 +3960,19 @@ add(4)(5)(6); - C: `4` `function` `function` - D: `undefined` `undefined` `6` -

Answer +
Antwoord

-#### Answer: A +#### Antwoord: 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`. +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` en `z` within the last arrow function, the JS engine goes up the scope chain in order to find the values for `x` en `y` accordingly. This returns `4` `5` `6`.

--- -###### 124. What's the output? +###### 124. Wat is de uitkomst? ```javascript async function* range(start, end) { @@ -3994,10 +3994,10 @@ async function* range(start, end) { - C: `1` `2` `3` - D: `undefined` `undefined` `undefined` -
Answer +
Antwoord

-#### Answer: C +#### Antwoord: 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`. @@ -4006,7 +4006,7 @@ The generator function `range` returns an async object with promises for each it --- -###### 125. What's the output? +###### 125. Wat is de uitkomst? ```javascript const myFunc = ({ x, y, z }) => { @@ -4021,19 +4021,19 @@ myFunc(1, 2, 3); - C: `{ 1: undefined }` `undefined` `undefined` - D: `undefined` `undefined` `undefined` -

Answer +
Antwoord

-#### Answer: D +#### Antwoord: 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`. +`myFunc` expects an object with properties `x`, `y` en `z` as its argument. Since we're only passing three separate numeric values (1, 2, 3) instead of one object with properties `x`, `y` en `z` ({x: 1, y: 2, z: 3}), `x`, `y` en `z` have their default value of `undefined`.

--- -###### 126. What's the output? +###### 126. Wat is de uitkomst? ```javascript function getFine(speed, amount) { @@ -4047,21 +4047,21 @@ function getFine(speed, amount) { { style: 'currency', currency: 'USD' } }).format(amount) - return `The driver drove ${formattedSpeed} and has to pay ${formattedAmount}` + return `The driver drove ${formattedSpeed} en 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 +- A: The driver drove 130 en has to pay 300 +- B: The driver drove 130 mph en has to pay \$300.00 +- C: The driver drove undefined en has to pay undefined +- D: The driver drove 130.00 en has to pay 300.00 -
Answer +
Antwoord

-#### Answer: B +#### Antwoord: 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 `currentcy` in `USD` results in `$300.00`. @@ -4070,7 +4070,7 @@ With the `Intl.NumberFormat` method, we can format numeric values to any locale. --- -###### 127. What's the output? +###### 127. Wat is de uitkomst? ```javascript const spookyItems = ["👻", "🎃", "🕸"]; @@ -4084,19 +4084,19 @@ console.log(spookyItems); - C: `["👻", "🎃", "🕸", { item: "💀" }]` - D: `["👻", "🎃", "🕸", "[object Object]"]` -

Answer +
Antwoord

-#### Answer: B +#### Antwoord: 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. +By destructuring objects, we can unpack values from the right-hand object, en 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. What's the output? +###### 128. Wat is de uitkomst? ```javascript const name = "Lydia Hallie"; @@ -4114,12 +4114,12 @@ console.log(isNaN(age)); - C: `false` `false` `true` `false` - D: `false` `true` `false` `true` -
Answer +
Antwoord

-#### Answer: C +#### Antwoord: 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 `Number.isNaN` method, you can check if the value you pass is a _numeric value_ en 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`. @@ -4128,7 +4128,7 @@ With the `isNaN` method, you can check if the value you pass is not a number. `n --- -###### 129. What's the output? +###### 129. Wat is de uitkomst? ```javascript const randomValue = 21; @@ -4146,10 +4146,10 @@ getInfo(); - C: `undefined` - D: `ReferenceError` -

Answer +
Antwoord

-#### Answer: D +#### Antwoord: 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. @@ -4158,7 +4158,7 @@ Variables declared with the `const` keyword are not referencable before their in --- -###### 130. What's the output? +###### 130. Wat is de uitkomst? ```javascript const myPromise = Promise.resolve("Woah some cool data"); @@ -4179,10 +4179,10 @@ const myPromise = Promise.resolve("Woah some cool data"); - C: `Woah some cool data` `Oh finally!` - D: `Oops didn't work` `Oh finally!` -

Answer +
Antwoord

-#### Answer: C +#### Antwoord: 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. @@ -4191,7 +4191,7 @@ In the `try` block, we're logging the awaited value of the `myPromise` variable: --- -###### 131. What's the output? +###### 131. Wat is de uitkomst? ```javascript const emojis = ["🥑", ["✨", "✨", ["🍕", "🍕"]]]; @@ -4204,19 +4204,19 @@ console.log(emojis.flat(1)); - C: `['🥑', ['✨', '✨', '🍕', '🍕']]` - D: `['🥑', '✨', '✨', '🍕', '🍕']` -

Answer +
Antwoord

-#### Answer: B +#### Antwoord: 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 `['🥑', '✨', '✨', ['🍕', '🍕']]`. +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. `['🥑']` en `['✨', '✨', ['🍕', '🍕']]` in this case. Concatenating these two arrays results in `['🥑', '✨', '✨', ['🍕', '🍕']]`.

--- -###### 132. What's the output? +###### 132. Wat is de uitkomst? ```javascript class Counter { @@ -4244,16 +4244,16 @@ console.log(counterOne.count); - C: `2` - D: `3` -
Answer +
Antwoord

-#### Answer: D +#### Antwoord: 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`. +`counterOne` is an instance of the `Counter` class. The counter class contains a `count` property on its constructor, en 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`. +Then, we create a new variable `counterTwo`, en 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`. @@ -4264,7 +4264,7 @@ We invoke the `counterTwo.increment()`, which sets the `count` to `3`. Then, we --- -###### 133. What's the output? +###### 133. Wat is de uitkomst? ```javascript const myPromise = Promise.resolve(Promise.resolve("Promise!")); @@ -4291,27 +4291,27 @@ funcTwo(); - C: `Promise! Last line! Last line! Promise! Timeout! Timeout!` - D: `Last line! Promise! Promise! Last line! Timeout! Timeout!` -

Answer +
Antwoord

-#### Answer: D +#### Antwoord: 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.) -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. +Both the promise en the timeout are asynchronous operations, the function keeps on running while it's busy completing the promise en 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, en `Promise!` gets logged. However, since we're invoking `funcTwo()`, the call stack isn't empty, en the callback of the `setTimeout` function cannot get added to the callstack yet. 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!`. The next line is the _asynchronous_ `setTimeout` function, from which the callback is sent to the Web API. -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!` +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`, en `() => console.log("Timeout!")` from `funcTwo`) get added to the call stack one by one. The first callback logs `Timeout!`, en gets popped off the stack. Then, the second callback logs `Timeout!`, en gets popped off the stack. This logs `Last line! Promise! Promise! Last line! Timeout! Timeout!`

--- -###### 134. How can we invoke `sum` in `index.js` from `sum.js?` +###### 134. Hoe kunnen we `sum` uit `sum.js` aanroepen in `index.js`?` ```javascript // sum.js @@ -4326,14 +4326,14 @@ 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 +- D: Default wordt niet geïmporteerd met `*`, alleen named exports -
Answer +
Antwoord

-#### Answer: C +#### Antwoord: C -With the asterisk `*`, we import all exported values from that file, both default and named. If we had the following file: +With the asterisk `*`, we import all exported values from that file, both default en named. If we had the following file: ```javascript // info.js @@ -4369,7 +4369,7 @@ We can invoke this function, by calling `sum.default` --- -###### 135. What's the output? +###### 135. Wat is de uitkomst? ```javascript const handler = { @@ -4386,18 +4386,18 @@ person.name; - A: `Added a new property!` - B: `Accessed a property!` - C: `Added a new property!` `Accessed a property!` -- D: Nothing gets logged +- D: Niets wordt gelogd -

Answer +
Antwoord

-#### Answer: C +#### Antwoord: C -With a Proxy object, we can add custom behavior to an object that we pass to it as the second argument. In tis 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 tis case, we pass the `handler` object which contained to properties: `set` en `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!"`. +First, we added a new property `name` to the proxy object (`person.name = "Lydia"`). `set` gets invoked, en 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. @@ -4406,7 +4406,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? +###### 136. Welke van onderstaande zal het `person` object aanpassen? ```javascript const person = { name: "Lydia Hallie" }; @@ -4419,10 +4419,10 @@ Object.seal(person); - C: `delete person.name` - D: `Object.assign(person, { age: 21 })` -

Answer +
Antwoord

-#### Answer: A +#### Antwoord: A With `Object.seal` we can prevent new properies from being _added_, or existing properties to be _removed_. @@ -4433,7 +4433,7 @@ However, you can still modify the value of existing properties. --- -###### 137. Which of the following will modify the `person` object? +###### 137. Welke van onderstaande zal het `person` object aanpassen? ```javascript const person = { @@ -4451,21 +4451,21 @@ Object.freeze(person); - C: `person.address.street = "101 Main St"` - D: `person.pet = { name: "Mara" }` -

Answer +
Antwoord

-#### Answer: C +#### Antwoord: 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. +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, en can be modified.

--- -###### 138. Which of the following will modify the `person` object? +###### 138. Welke van onderstaande zal het `person` object aanpassen? ```javascript const person = { @@ -4483,21 +4483,21 @@ Object.freeze(person); - C: `person.address.street = "101 Main St"` - D: `person.pet = { name: "Mara" }` -
Answer +
Antwoord

-#### Answer: C +#### Antwoord: 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. +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, en can be modified.

--- -###### 139. What's the output? +###### 139. Wat is de uitkomst? ```javascript const add = x => x + x; @@ -4510,26 +4510,26 @@ 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: `2` `4` en `3` `6` +- B: `2` `NaN` en `3` `NaN` +- C: `2` `Error` en `3` `6` +- D: `2` `4` en `3` `Error` -
Answer +
Antwoord

-#### Answer: A +#### Antwoord: 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` en `value` got their default values: num is `2`, en `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`. +Then, we invoked `myFunc(3)` en 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`.

--- -###### 140. What's the output? +###### 140. Wat is de uitkomst? ```javascript class Counter { @@ -4555,10 +4555,10 @@ console.log(counter.#number) - C: `undefined` - D: `SyntaxError` -
Answer +
Antwoord

-#### Answer: D +#### Antwoord: 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! @@ -4567,7 +4567,7 @@ In ES2020, we can add private variables in classes by using the `#`. We cannot a --- -###### 141. What's the output? +###### 141. Wat is de uitkomst? ```javascript const teams = [ @@ -4597,10 +4597,10 @@ obj.next(); // { value: "Lisa", done: false } - C: `return getMembers(teams[i].members)` - D: `return yield getMembers(teams[i].members)` -

Answer +
Antwoord

-#### Answer: B +#### Antwoord: 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*`. @@ -4611,7 +4611,7 @@ If we would've written `yield`, `return yield`, or `return`, the entire generato --- -###### 142. What's the output? +###### 142. Wat is de uitkomst? ```javascript const person = { @@ -4636,27 +4636,27 @@ console.log(person.hobbies); - C: `["coding", "dancing", "baking"]` - D: `["coding", "running", "dancing", "baking"]` -

Answer +
Antwoord

-#### Answer: C +#### Antwoord: C -The `addHobby` function receives two arguments, `hobby` and `hobbies` with the default value of the `hobbies` array on the `person` object. +The `addHobby` function receives two arguments, `hobby` en `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, en pass `"running"` as the value for `hobby` en 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. -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. +Then, we invoke the `addHobby` function, en 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, en pass `"bdaking"` as the value for `hobby`, en 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"]` +After pushing `dancing` en `baking`, the value of `person.hobbies` is `["coding", "dancing", "baking"]`

--- -###### 143. What's the output? +###### 143. Wat is de uitkomst? ```javascript class Bird { @@ -4678,21 +4678,21 @@ 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 +- D: Niets, we hebben geen methode aangeroepen -
Answer +
Antwoord

-#### Answer: B +#### Antwoord: 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. 🦢"`. +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, en logs `"I'm a bird. 🦢"`.

--- -###### 144. Which of the options result(s) in an error? +###### 144. Welke van onderstaande opties zal resulteren in een error? ```javascript const emojis = ["🎄", "🎅🏼", "🎁", "⭐"]; @@ -4704,14 +4704,14 @@ const emojis = ["🎄", "🎅🏼", "🎁", "⭐"]; ``` - A: 1 -- B: 1 and 2 -- C: 3 and 4 +- B: 1 en 2 +- C: 3 en 4 - D: 3 -
Answer +
Antwoord

-#### Answer: D +#### Antwoord: 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 propeties on the `emojis` array can be modified, for example by pushing new values, splicing them, or setting the length of the array to 0. @@ -4720,7 +4720,7 @@ The `const` keyword simply means we cannot _redeclare_ the value of that variabl --- -###### 145. What do we need to add to the `person` object to get `["Lydia Hallie", 21]` as the output of `[...person]`? +###### 145. Wat moeten we aan het `person` object toevoegen om `["Lydia Hallie", 21]` als uitkomst te krijgen van `[...person]`? ```javascript const person = { @@ -4731,15 +4731,15 @@ const person = { [...person] // ["Lydia Hallie", 21] ``` -- A: Nothing, object are iterable by default +- A: Niets, objecten zijn standaard iterabel - 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 }` -

Answer +
Antwoord

-#### Answer: C +#### Antwoord: 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)`. From e2b7476866e3ae430f3530c2a0e6ba2fdcb35489 Mon Sep 17 00:00:00 2001 From: Tarabass Date: Sun, 12 Jan 2020 16:56:29 +0100 Subject: [PATCH 432/915] Question 18 --- nl-NL/README.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/nl-NL/README.md b/nl-NL/README.md index baf8f12c..08e7c465 100644 --- a/nl-NL/README.md +++ b/nl-NL/README.md @@ -592,11 +592,11 @@ checkAge({ age: 18 }); #### Antwoord: 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. +Wanneer we waarden vergelijken worden primitieven vergelijken _by value_, terwijl objecten vergelijken worden _by reference_. JavaScript bekijkt of de objecten een referentie hebben naar dezelfde lokatie in het geheugen. -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. +De twee objecten die we vergelijken hebben dat niet: het object die we doorgeven als een parameter refereert naar een andere lokatie in het geheugen dan het object waarmee we vergelijken. -This is why both `{ age: 18 } === { age: 18 }` en `{ age: 18 } == { age: 18 }` return `false`. +Dit is waarom `{ age: 18 } === { age: 18 }` en `{ age: 18 } == { age: 18 }` allebei `false` teruggeven.

From 08059009fe8947104672f30837fa37799acb901f Mon Sep 17 00:00:00 2001 From: Tarabass Date: Sun, 12 Jan 2020 17:16:10 +0100 Subject: [PATCH 433/915] Question 19 --- nl-NL/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/nl-NL/README.md b/nl-NL/README.md index 08e7c465..8bfe5e87 100644 --- a/nl-NL/README.md +++ b/nl-NL/README.md @@ -623,7 +623,7 @@ getAge(21); #### Antwoord: C -The rest parameter (`...args`.) lets us "collect" all remaining arguments into an array. An array is an object, so `typeof args` returns `"object"` +De rest parameter (`...args`.) laat ons alle overgebleven argumenten "verzamelen" in een array. Een array is een object, dus `typeof args` geeft `"object"` terug.

From b0b2419bf482012d9f333db96ebe99e39c2eb031 Mon Sep 17 00:00:00 2001 From: Tarabass Date: Sun, 12 Jan 2020 17:16:29 +0100 Subject: [PATCH 434/915] Question 20 --- nl-NL/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/nl-NL/README.md b/nl-NL/README.md index 8bfe5e87..b556ad7d 100644 --- a/nl-NL/README.md +++ b/nl-NL/README.md @@ -652,7 +652,7 @@ getAge(); #### Antwoord: C -With `"use strict"`, you can make sure that you don't accidentally declare global variables. We never declared the variable `age`, en 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. +Door gebruik te maken van `"use strict"` kun je er zeker van zijn dat je niet perongeluk globale variabelen declareert. We hebben de variabele `age` nooit gedeclareerd, en omdat we `"use strict"` gebruiken zal dit een reference error gooien. Als we geen gebruik hadden gemaakt van `"use strict"` had het wel gewerkt, omdat de propertie `age` dan was toegevoegd aan het globale object.

From fc9327070ea518cb7c31623e2e04e56bf81053cc Mon Sep 17 00:00:00 2001 From: Tarabass Date: Sun, 12 Jan 2020 17:16:42 +0100 Subject: [PATCH 435/915] Question 21 --- nl-NL/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/nl-NL/README.md b/nl-NL/README.md index b556ad7d..9a1d4a9b 100644 --- a/nl-NL/README.md +++ b/nl-NL/README.md @@ -675,7 +675,7 @@ const sum = eval("10*10+5"); #### Antwoord: 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` voert code uit dat is meegegeven als string. Als het een expressie is, zoals in dit geval, zal het de expressie uitvoeren. De expressie is `10 * 10 + 5`. Dit geeft het getal `105` terug.

From 9e31f6d4b00d2fab5629ac691741a47210532242 Mon Sep 17 00:00:00 2001 From: Tarabass Date: Sun, 12 Jan 2020 17:16:51 +0100 Subject: [PATCH 436/915] Question 22 --- nl-NL/README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/nl-NL/README.md b/nl-NL/README.md index 9a1d4a9b..0d9ebaab 100644 --- a/nl-NL/README.md +++ b/nl-NL/README.md @@ -698,9 +698,9 @@ sessionStorage.setItem("cool_secret", 123); #### Antwoord: B -The data stored in `sessionStorage` is removed after closing the _tab_. +De data opgeslagen in `sessionStorage` wordt verwijderd na het sluiten van de _tab_. -If you used `localStorage`, the data would've been there forever, unless for example `localStorage.clear()` is invoked. +Als je `localStorage` had gebruikt was de data wel voor altijd opgeslagen, zolang bijvoorbeeld `localStorage.clear()` wordt aangeroepen.

From 25047d71966583dc74c8e8b0bb5d06a4515bd898 Mon Sep 17 00:00:00 2001 From: Tarabass Date: Sun, 12 Jan 2020 17:17:01 +0100 Subject: [PATCH 437/915] Question 23 --- nl-NL/README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/nl-NL/README.md b/nl-NL/README.md index 0d9ebaab..b40bc362 100644 --- a/nl-NL/README.md +++ b/nl-NL/README.md @@ -726,9 +726,9 @@ console.log(num); #### Antwoord: B -With the `var` keyword, you can declare multiple variables with the same name. The variable will then hold the latest value. +Met het `var` keyword kun je meerdere variabelen met dezelfde naam declareren. De variabele zal dan de laatst gezette waarde bevatten. -You cannot do this with `let` or `const` since they're block-scoped. +Je kunt dit niet doen met `let` of `const`, omdat deze block-scoped zijn.

From 2ec0d1ff06b3533f8f0b2f2efe847f5ac1b5f714 Mon Sep 17 00:00:00 2001 From: Tarabass Date: Sun, 12 Jan 2020 17:17:15 +0100 Subject: [PATCH 438/915] Question 24 --- nl-NL/README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/nl-NL/README.md b/nl-NL/README.md index b40bc362..e1801322 100644 --- a/nl-NL/README.md +++ b/nl-NL/README.md @@ -757,9 +757,9 @@ set.has(1); #### Antwoord: 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. +Alle object keys (Symbols uitgesloten) zijn onder de motorkap strings, zelfs als je het zelf niet een string gemaakt hebt. Dat is waarom `obj.hasOwnProperty('1')` ook `true` teruggeeft. -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`. +Dit werkt niet op deze manier voor een set. Er is geen `'1'` in onze set: `set.has('1')` geeft `false` terug. Het heeft de numerieke waarde `1`, `set.has(1)` geeft `true` terug.

From 70766f34e74ba0e1667e574fb977d268831b6264 Mon Sep 17 00:00:00 2001 From: Tarabass Date: Sun, 12 Jan 2020 17:17:27 +0100 Subject: [PATCH 439/915] Question 25 --- nl-NL/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/nl-NL/README.md b/nl-NL/README.md index e1801322..94179d5b 100644 --- a/nl-NL/README.md +++ b/nl-NL/README.md @@ -783,7 +783,7 @@ console.log(obj); #### Antwoord: 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. +Als je twee properties met dezelfde naam hebt zal de waarde van de al bestaande propertie overschreven worden. Het zal dan ook in de eerste positie blijven, maar met de laatste waarde.

From b0623c0f7b2bb01f42d2ad429d1345d0c28106a5 Mon Sep 17 00:00:00 2001 From: Tarabass Date: Sun, 12 Jan 2020 17:17:37 +0100 Subject: [PATCH 440/915] Question 26 --- nl-NL/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/nl-NL/README.md b/nl-NL/README.md index 94179d5b..e74850cd 100644 --- a/nl-NL/README.md +++ b/nl-NL/README.md @@ -801,7 +801,7 @@ Als je twee properties met dezelfde naam hebt zal de waarde van de al bestaande #### Antwoord: A -The base execution context is the global execution context: it's what's accessible everywhere in your code. +De base execution context is de global execution context: dit is benaderbaar overal in je code.

From 2b2f9042b2fbdcfee571d024e164092b266d55e2 Mon Sep 17 00:00:00 2001 From: Tarabass Date: Sun, 12 Jan 2020 17:17:49 +0100 Subject: [PATCH 441/915] Question 27 --- nl-NL/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/nl-NL/README.md b/nl-NL/README.md index e74850cd..925357d9 100644 --- a/nl-NL/README.md +++ b/nl-NL/README.md @@ -827,7 +827,7 @@ for (let i = 1; i < 5; i++) { #### Antwoord: C -The `continue` statement skips an iteration if a certain condition returns `true`. +De `continue` statement slaat een iteratie over als een bepaalde conditie `true` teruggeeft.

From 0ce13fe2fad265bf5285ac38d9faf8c872e176f6 Mon Sep 17 00:00:00 2001 From: Tarabass Date: Mon, 13 Jan 2020 13:24:21 +0100 Subject: [PATCH 442/915] Question 28 --- nl-NL/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/nl-NL/README.md b/nl-NL/README.md index 925357d9..18bafcaa 100644 --- a/nl-NL/README.md +++ b/nl-NL/README.md @@ -856,7 +856,7 @@ name.giveLydiaPizza(); #### Antwoord: 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 een built-in constructor waaraan we properties kunnen toevoegen. Primitieve strings worden automatisch geconverteerd naar een string object, gegenereerd door de string prototype functie. Daarom hebben alle strings (string objecten) toegang tot de methode!

From 12d7b1757381cecb9f9f0293dcd2b0b146b33606 Mon Sep 17 00:00:00 2001 From: Tarabass Date: Mon, 13 Jan 2020 13:38:48 +0100 Subject: [PATCH 443/915] Question 29 --- nl-NL/README.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/nl-NL/README.md b/nl-NL/README.md index 18bafcaa..d17bbc58 100644 --- a/nl-NL/README.md +++ b/nl-NL/README.md @@ -886,11 +886,11 @@ console.log(a[b]); #### Antwoord: 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`. +Object keys worden automatisch geconverteerd naar strings. We proberen een object aan een propertie toe te wijzen van object `a`, met de waarde `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`. +Maar als we een object converteren naar een string krijgen we `"[object Object]"` terug. Wat we hier dus schrijven is `a["object Object"] = 123`. Dan kunnen we hetzelfde nog een keer proberen. `c` is een ander object dat converteren naar een string. En dan, `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`. +Dan loggen we `a[b]`, waar eigenlijk `a["object Object"]` staat. We overschrijven dat met `456`, en dit is ook wat gelogd wordt.

From 793172fe5868a8d03148d3b62d05070b99df1541 Mon Sep 17 00:00:00 2001 From: Tarabass Date: Mon, 13 Jan 2020 14:01:55 +0100 Subject: [PATCH 444/915] Question 30 --- nl-NL/README.md | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/nl-NL/README.md b/nl-NL/README.md index d17bbc58..6c456257 100644 --- a/nl-NL/README.md +++ b/nl-NL/README.md @@ -919,31 +919,31 @@ baz(); #### Antwoord: B -We have a `setTimeout` function en invoked it first. Yet, it was logged last. +We hebben een `setTimeout` functie en roepen het als eerste aan. Toch wordt het als laatste gelogd. -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, en for example the DOM. +Dit komt doordat we in browsers niet alleen een runtime engine hebben, maar ook iets dat een `WebAPI` genoemd wordt. De `WebAPI` geeft ons een `setTimeout` functie, en bijvoorbeeld ook de DOM. -After the _callback_ is pushed to the WebAPI, the `setTimeout` function itself (but not the callback!) is popped off the stack. +Nadat de _calback_ naar de WebAPI is gestuurd wordt de `setTimeout` functie zelf (niet de callback functie) van de stack gegooid. -Now, `foo` gets invoked, en `"First"` is being logged. +Dan wordt `foo` uitgevoerd en `"First"` wordt gelogd. -`foo` is popped off the stack, en `baz` gets invoked. `"Third"` gets logged. +`foo` wordt van de stack gegooid en `baz` wordt uitgevoerd. `"Third"` wordt gelogd. -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_. +De WebAPI kan niet zomaar dingen toevoegen aan de stack. In plaats daarvan wordt de callback functie op de zogenaamde _queue_ gezet. -This is where an event loop starts to work. An **event loop** looks at the stack en task queue. If the stack is empty, it takes the first thing on the queue en pushes it onto the 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. -`bar` gets invoked, `"Second"` gets logged, en it's popped off the stack. +`bar` wordt uitgevoerd, `"Second"` wordt gelogd, en het verdwijnt van de stack.

From 35175e8e232ff99a4ff32a78f0da19ccc0d334ca Mon Sep 17 00:00:00 2001 From: Tarabass Date: Mon, 13 Jan 2020 14:05:37 +0100 Subject: [PATCH 445/915] Question 31 --- nl-NL/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/nl-NL/README.md b/nl-NL/README.md index 6c456257..8ab0042d 100644 --- a/nl-NL/README.md +++ b/nl-NL/README.md @@ -972,7 +972,7 @@ Dit is waar de event loop zijn intrede doet. Een ***event loop* naar de stack en #### Antwoord: C -The deepest nested element that caused the event is the target of the event. You can stop bubbling by `event.stopPropagation` +Het diepst geneste element dat het event afvuurt is de target van het event. Je kunt bubbling stoppen met `event.stopPropagation`.

From f6d1654533e95410f1a515dfd75b6eda16c8fa99 Mon Sep 17 00:00:00 2001 From: jtakalai Date: Mon, 13 Jan 2020 16:18:16 +0200 Subject: [PATCH 446/915] fix answer to q 145 current line would return two times the wanted result, once for each prop. --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index d3d60814..0336e02a 100644 --- a/README.md +++ b/README.md @@ -4732,7 +4732,7 @@ const person = { - A: Nothing, object are iterable by default - 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 }`
Answer From 3b5e707344c03b5ffdd2943be6fdffda4a031e28 Mon Sep 17 00:00:00 2001 From: Ana Carolina Hernandes Date: Mon, 13 Jan 2020 15:47:02 -0300 Subject: [PATCH 447/915] correcting translation of question 37 --- README.md | 2 +- pt-BR/README_pt_BR.md | 8 ++++---- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/README.md b/README.md index d3d60814..4e8af3c9 100644 --- a/README.md +++ b/README.md @@ -9,7 +9,7 @@ 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! 😊
- Instagram || Twitter || LinkedIn || Blog + Instagram || Twitter || LinkedIn || Blog
--- diff --git a/pt-BR/README_pt_BR.md b/pt-BR/README_pt_BR.md index b9456327..23577533 100644 --- a/pt-BR/README_pt_BR.md +++ b/pt-BR/README_pt_BR.md @@ -1131,16 +1131,16 @@ console.log(numbers); - C: `[1, 2, 3, 7 x empty, 11]` - D: `SyntaxError` -
Answer +
Resposta

-#### Answer: C +#### Resposta: 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: +Quando você define um valor para um elemento em um array que excede o tamanho do próprio array, o JavaScript cria algo chamado "empty slots" (espaços vazios). Na verdade, esses espaços vazios tem o valor de `undefined`, mas você verá algo como: `[1, 2, 3, 7 x empty, 11]` -depending on where you run it (it's different for every browser, node, etc.) +dependendo de onde você o executa, pois é diferente para cada navegador, node etc.

From 783ec01333c8a23e228e1df4f1279258619bde4b Mon Sep 17 00:00:00 2001 From: Tarabass Date: Mon, 13 Jan 2020 22:20:40 +0100 Subject: [PATCH 448/915] Question 32 --- nl-NL/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/nl-NL/README.md b/nl-NL/README.md index 8ab0042d..ba0e5f89 100644 --- a/nl-NL/README.md +++ b/nl-NL/README.md @@ -999,7 +999,7 @@ Het diepst geneste element dat het event afvuurt is de target van het event. Je #### Antwoord: A -If we click `p`, we see two logs: `p` en `div`. During event propagation, there are 3 phases: capturing, target, en 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. +Als we op `p` klikken zien we twee logs: `p` en `div`. Tijdens de event propagation zijn er 3 fases: capturing, target, en bubbling. Standaard worden event handlers uitgevoerd in de bubbling fase (tenzij je `useCapture` op `true` zet). Bubbling begint bij het diepst geneste element omhoog.

From cb0eb9095e183eb1c8ead01d40e82f943225d434 Mon Sep 17 00:00:00 2001 From: Tarabass Date: Mon, 13 Jan 2020 22:20:59 +0100 Subject: [PATCH 449/915] Question 33 --- nl-NL/README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/nl-NL/README.md b/nl-NL/README.md index ba0e5f89..7530a37f 100644 --- a/nl-NL/README.md +++ b/nl-NL/README.md @@ -1029,9 +1029,9 @@ console.log(sayHi.bind(person, 21)); #### Antwoord: D -With both, we can pass the object to which we want the `this` keyword to refer to. However, `.call` is also _executed immediately_! +Op beide manieren kunnen we een object doorgeven waarnaar het `this` keyword verwijst. Echter, `.call` wordt _direct uitgevoerd_! -`.bind.` returns a _copy_ of the function, but with a bound context! It is not executed immediately. +`.bind` geeft een _kopie_ terug van de functie, maar met een bound context! Het wordt niet direct uitgevoerd!

From cf9648fb98db536c8b149bfc76ea9b4411e9b305 Mon Sep 17 00:00:00 2001 From: Tarabass Date: Mon, 13 Jan 2020 22:21:16 +0100 Subject: [PATCH 450/915] Question 34 --- nl-NL/README.md | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/nl-NL/README.md b/nl-NL/README.md index 7530a37f..9092b806 100644 --- a/nl-NL/README.md +++ b/nl-NL/README.md @@ -1058,9 +1058,10 @@ console.log(typeof sayHi()); #### Antwoord: B -The `sayHi` function returns the returned value of the immediately invoked function (IIFE). This function returned `0`, which is type `"number"`. +De `sayHi` functie geeft de waarde terug van de direct aangeroepen functie (IIFE). Deze functie geeft `0` terug, die het type `number` heeft. + +FYI: er zijn slechts 7 ingebouwde types: `null`, `undefined`, `boolean`, `number`, `string`, `object`, en `symbol`. `"function"` is geen type omdat functies objecten zijn, en dus van het type `"object"`. -FYI: there are only 7 built-in types: `null`, `undefined`, `boolean`, `number`, `string`, `object`, en `symbol`. `"function"` is not a type, since functions are objects, it's of type `"object"`.

From 1df4120e094d3efa3720556b81c8672506523c56 Mon Sep 17 00:00:00 2001 From: Tarabass Date: Mon, 13 Jan 2020 22:21:35 +0100 Subject: [PATCH 451/915] Question 35 --- nl-NL/README.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/nl-NL/README.md b/nl-NL/README.md index 9092b806..861c3ab1 100644 --- a/nl-NL/README.md +++ b/nl-NL/README.md @@ -1088,16 +1088,16 @@ undefined; #### Antwoord: A -There are only six falsy values: +Er zijn slechts zes falsy waarden: - `undefined` - `null` - `NaN` - `0` -- `''` (empty string) +- `''` (lege string) - `false` -Function constructors, like `new Number` en `new Boolean` are truthy. +Functie constructors, zoals `new Number` en `new Boolean`, zijn truthy.

From 11b6c54bb5ec53e531e54f314372a27448bae7fb Mon Sep 17 00:00:00 2001 From: Tarabass Date: Mon, 13 Jan 2020 22:21:55 +0100 Subject: [PATCH 452/915] Question 36 --- nl-NL/README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/nl-NL/README.md b/nl-NL/README.md index 861c3ab1..c2911322 100644 --- a/nl-NL/README.md +++ b/nl-NL/README.md @@ -1120,8 +1120,8 @@ console.log(typeof typeof 1); #### Antwoord: B -`typeof 1` returns `"number"`. -`typeof "number"` returns `"string"` +`typeof 1` geeft `"number"` terug. +`typeof "number"` geeft `"string"` terug.

From cb310e8b99a344e27038c8c0d42249f1bca3a646 Mon Sep 17 00:00:00 2001 From: Tarabass Date: Mon, 13 Jan 2020 22:22:49 +0100 Subject: [PATCH 453/915] Question 37 --- nl-NL/README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/nl-NL/README.md b/nl-NL/README.md index c2911322..0b5344ee 100644 --- a/nl-NL/README.md +++ b/nl-NL/README.md @@ -1146,11 +1146,11 @@ console.log(numbers); #### Antwoord: 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: +Wanneer je een element van een array een waarde geeft die buiten de lengte van de array ligt zal JavaScript voor de tussenliggende elementen zogenaamde "empty slots" aanmaken. Deze hebben eigenlijk de waarde `undefined`, maar je zult zoiets zien als: `[1, 2, 3, 7 x empty, 11]` -depending on where you run it (it's different for every browser, node, etc.) +afhankelijk van waar je de code uitvoert (het verschilt in alle browsers, node, etc.)

From 61adf9a18426bab3737bfa88f8d3e17c7f731796 Mon Sep 17 00:00:00 2001 From: Tarabass Date: Mon, 13 Jan 2020 22:23:07 +0100 Subject: [PATCH 454/915] Question 38 --- nl-NL/README.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/nl-NL/README.md b/nl-NL/README.md index 0b5344ee..b63eeb85 100644 --- a/nl-NL/README.md +++ b/nl-NL/README.md @@ -1183,11 +1183,11 @@ afhankelijk van waar je de code uitvoert (het verschilt in alle browsers, node, #### Antwoord: 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. +Het `catch` block krijgt het argument `x` mee. Dit is niet dezelfde `x` als de variabele zoals bovenaan gedefinieerd. De meegegeven `x` is block-scoped. -Later, we set this block-scoped variable equal to `1`, en set the value of the variable `y`. Now, we log the block-scoped variable `x`, which is equal to `1`. +Later vullen we deze block-scoped variabele met `1`, en zetten de waarde van de variabele `y`. Dan loggen we de block-scoped variabele `x`, die op dat moment `1` bevat. -Outside of the `catch` block, `x` is still `undefined`, en `y` is `2`. When we want to `console.log(x)` outside of the `catch` block, it returns `undefined`, en `y` returns `2`. +Buiten het `catch` block is de variable `x` nog steeds `undefined`, `y` is echter `2`. Wanneer we beide variabelen buiten de try...catch statement loggen zal `x` `undefined` teruggeven en `y` `2`.

From 5b9d2ef33f153404cd78cce3ff34c52886bba86c Mon Sep 17 00:00:00 2001 From: Tarabass Date: Mon, 13 Jan 2020 22:23:23 +0100 Subject: [PATCH 455/915] Question 39 --- nl-NL/README.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/nl-NL/README.md b/nl-NL/README.md index b63eeb85..f4e2725c 100644 --- a/nl-NL/README.md +++ b/nl-NL/README.md @@ -1206,11 +1206,11 @@ Buiten het `catch` block is de variable `x` nog steeds `undefined`, `y` is echte #### Antwoord: A -JavaScript only has primitive types en objects. +JavaScript bestaat alleen uit primitieve types en objecten. -Primitive types are `boolean`, `null`, `undefined`, `bigint`, `number`, `string`, en `symbol`. +Primitieve types zijn `boolean`, `null`, `undefined`, `bigint`, `number`, `string`, en `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'` en 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 object using one of the wrapper classes, i.e. `String`, en then immediately discard the wrapper after the expression evaluates. All primitives except for `null` en `undefined` exhibit this behaviour. +Wat primitieven onderscheidt van objecten is dat primitieven geen properties of methodes bevatten. Echter, je zal opmerken dan `'foo'.toUpperCase()` resulteert in `'FOO'` en geen `TypeError` gooit. Dit komt doordat wanneer je een propertie of een methode benadert van een primitieve zoals een string, JavaScript impliciet het object wrapped gebruikmakend van één van de wrapper classen, in dit geval `String`, en daarna direct de wrapper weghaalt als de expressie heeft geresulteerd in een waarde. Alle primitieven vertonen dit gedrag, met uitzondering van `null` en `undefined`.

From c6ff53854a85bf86fb5a3e4750aaf41758c24170 Mon Sep 17 00:00:00 2001 From: Do Trung Kien Date: Tue, 14 Jan 2020 08:40:06 +0700 Subject: [PATCH 456/915] translate next 10 question (122-131) into Vietnamese --- vi-VI/README-vi.md | 46 ++++++++++++++++++++++------------------------ 1 file changed, 22 insertions(+), 24 deletions(-) diff --git a/vi-VI/README-vi.md b/vi-VI/README-vi.md index 69d0c095..94f46d16 100644 --- a/vi-VI/README-vi.md +++ b/vi-VI/README-vi.md @@ -3899,7 +3899,6 @@ console.log(config.language); #### Đáp án: 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. Phương thức `language` là một `setter`. Setter không mang giá trị, nhiệm vụ của nó chỉ đơn giản là _thay đổi_ thuộc tính. Khi ta gọi một phương thức `setter` nó sẽ trả về `undefined`.

@@ -3907,7 +3906,7 @@ Phương thức `language` là một `setter`. Setter không mang giá trị, nh --- -###### 122. What's the output? +###### 122. Output là gì? ```javascript const name = "Lydia Hallie"; @@ -3926,16 +3925,16 @@ console.log(!typeof name === "string"); #### Đáp án: 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`. +`typeof name` trả về `"string"`. Chuỗi `"string"` là một giá trị `truthy`, do đó `!typeof name` sẽ trả về một giá trị bool là `false`. Do đó `false === "object"` và `false === "string"` đều trả về`false`. -(If we wanted to check whether the type was (un)equal to a certain type, we should've written `!==` instead of `!typeof`) +(Nếu chúng ta muốn check xem một kiểu dữ liệu không phải là một kiểu nào đó, chúng ta nên viết `!==` thay vì `!typeof`)

--- -###### 123. What's the output? +###### 123. Output là gì? ```javascript const add = x => y => z => { @@ -3956,14 +3955,14 @@ add(4)(5)(6); #### Đáp án: 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`. +Hàm `add` trả về một arrow function, arrow function này lại trả về một arrow function khác, arrow function này lại trả về một arrow function khác nữa. Hàm đầu tiên nhận vào một tham số `x` với giá trị là 4 `4`. Chúng ta gọi hàm thứ hai, nhận vào giá trị của `y` là `5`. Sau đó chúng ta gọi hàm thứ 3, nhận vào giá trị của `z` là `6`. Sau đó ta truy cập các giá trị của `x`, `y` và `z` bên trong arrow function cuối cùng, khi này JS engine sẽ lần ngược lại scope chain để tìm các giá trị `x` và `y` tương ứng. Do đó cuối cùng nó sẽ trả về `4` `5` `6`.

--- -###### 124. What's the output? +###### 124. Output là gì? ```javascript async function* range(start, end) { @@ -3990,14 +3989,14 @@ async function* range(start, end) { #### Đáp án: 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`. +Generator `range` trả về một async object với các promise tương ứng với mỗi phần tử ta đưa vào: `Promise{1}`, `Promise{2}`, `Promise{3}`. Ta set giá trị `gen` bằng với một async object để thực hiện vòng lặp `for await ... of` sau đó. Tiếp đó ta lại set giá trị của `item` bằng với giá trị trả về của mỗi promise: đầu tiên là `Promise{1}`, sau đó `Promise{2}`, sau đó `Promise{3}`. Do chúng ta sử dụng cú pháp `async/await` nên sẽ trả về giá trị đã được resolve của promise `item`, do đó lần lượt `1`, `2`, và `3` được in ra.

--- -###### 125. What's the output? +###### 125. Output là gì? ```javascript const myFunc = ({ x, y, z }) => { @@ -4017,14 +4016,14 @@ myFunc(1, 2, 3); #### Đáp án: 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`. +`myFunc` nhận vào một object có các thuộc tính `x`, `y` và `z` làm đối số của nó. Do chúng ta đưa vào 3 số riêng biệt (1, 2, 3) chứ không phải một object với các thuộc tính `x`, `y`, `z` như ({x: 1, y: 2, z: 3}), nên `x`, `y`, `z` đều có giá trị là `undefined`.

--- -###### 126. What's the output? +###### 126. Output là gì? ```javascript function getFine(speed, amount) { @@ -4054,14 +4053,14 @@ console.log(getFine(130, 300)) #### Đáp án: 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 `currentcy` in `USD` results in `$300.00`. +Với phương thức `Intl.NumberFormat`, chúng ta có thể format bất cứ số nào theo định dạng ta mong muốn. Ở đây ta format giá trị `130` theo định dạng `en-US`, kiểu `unit`, đơn vị là `mile-per-hour`, và nó sẽ trả về `130 mph`. Tiếp theo số `300` sẽ được format theo định dạng `en-US`, kiểu `currentcy`, đơn vị `USD`, và kết quả là `$300.00`.

--- -###### 127. What's the output? +###### 127. Output là gì? ```javascript const spookyItems = ["👻", "🎃", "🕸"]; @@ -4080,14 +4079,14 @@ console.log(spookyItems); #### Đáp án: 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. +Khi tiến hành cú pháp destructuring object, chúng ta có thể unpack các giá trị ở phía phải của một object, và đưa giá trị đã được unpack đó làm giá trị của thuộc tính tương ứng của object phía trái. Trong trường hợp này, ta đã gán giá trị "💀" cho `spookyItems[3]`. Có nghĩa là mảng `spookyItems` đã bị thay đổi, chúng ta đã thêm vào nó một phần tử "💀". Do đó khi in ra thì kết quả sẽ là `["👻", "🎃", "🕸", "💀"]` .

--- -###### 128. What's the output? +###### 128. Output là gì? ```javascript const name = "Lydia Hallie"; @@ -4110,16 +4109,15 @@ console.log(isNaN(age)); #### Đáp án: 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`. +Với phương thức `Number.isNaN`, ta có thể check một giá trị có phải là _dạng số_ và bằng `NaN` hay không. `name` không phải là một số, do đó `Number.isNaN(name)` sẽ trả về `false`. `age` là một số, nhưng không bằng `NaN`, do đó `Number.isNaN(age)` cũng trả về `false`. +Với phương thức `isNaN`, ta đơn thuần chỉ check xem giá trị đưa vào không phải là _dạng số_ hay không. `name` không phải là dạng số, nên `isNaN(name)` trả về `true`. `age` là số, nên `isNaN(age)` trả về `false`.

--- -###### 129. What's the output? +###### 129. Output là gì? ```javascript const randomValue = 21; @@ -4142,14 +4140,14 @@ getInfo(); #### Đáp án: 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. +Một biến được khai báo với từ khóa `const` sẽ không thể truy cập trước khi nó được khởi tạo: nó gọi là _temporal dead zone_. Trong hàm `getInfo`, giá trị `randomValue` sẽ được tìm kiếm đầu tiên trong scope của hàm `getInfo`. Tại dòng ta muốn lấy ra `typeof randomValue`, giá trị `randomValue` chưa được khởi tạo, do đó một `ReferenceError` sẽ được throw ra! Lưu ý nhỏ là Javascript engine sẽ không tìm kiếm ở scope khác nữa do `randomValue` đã được khai báo bên trong hàm `getInfo`.

--- -###### 130. What's the output? +###### 130. Ouput là gì? ```javascript const myPromise = Promise.resolve("Woah some cool data"); @@ -4175,14 +4173,14 @@ const myPromise = Promise.resolve("Woah some cool data"); #### Đáp án: 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. +Trong khối `try`, ta in ra giá trị của biến `myPromise`: `"Woah some cool data"`. Do không có lỗi gì xảy ra ở đây cả, nên các lệnh trong khối `catch` sẽ không được chạy. Tuy nhiên các lệnh trong khối `finally` thì sẽ _luôn luôn_ chạy, nên `"Oh finally!"` sẽ được in ra.

--- -###### 131. What's the output? +###### 131. Output là gì? ```javascript const emojis = ["🥑", ["✨", "✨", ["🍕", "🍕"]]]; @@ -4200,7 +4198,7 @@ console.log(emojis.flat(1)); #### Đáp án: 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 `['🥑', '✨', '✨', ['🍕', '🍕']]`. +Với phương thức `flat`, ta có thể tạo một mảng mới với các phần tử đã được `flattened` (làm phẳng). Độ sâu của mảng đã làm phẳng sẽ phụ thuộc vào giá trị ta đưa vào. Trong trường hợp này ta đưa vào là `1` (thực ra đây là giá trị default, ta không đưa vào cũng không sao), có nghĩa là chỉ những phần tử ở độ sâu 1 sẽ được làm phẳng. Chúng là`['🥑']` và `['✨', '✨', ['🍕', '🍕']]` trong trường hợp này. Nối lại ta sẽ có mảng mới `['🥑', '✨', '✨', ['🍕', '🍕']]`.

From e4c562e8c35f6a5aa2568eb10975ce2f9071edd0 Mon Sep 17 00:00:00 2001 From: Emanoel Lucas Date: Mon, 13 Jan 2020 23:13:46 -0300 Subject: [PATCH 457/915] translation of question 44 to brazilian portuguese --- pt-BR/README_pt_BR.md | 34 ++++++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) diff --git a/pt-BR/README_pt_BR.md b/pt-BR/README_pt_BR.md index b9456327..f83790dc 100644 --- a/pt-BR/README_pt_BR.md +++ b/pt-BR/README_pt_BR.md @@ -1309,3 +1309,37 @@ Strings são iteráveis. O operador do spread `...` mapeia todo caractére de um

+ +--- + +###### 44. Qual é a saída? + +```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 e 10, 20` + +
Resposta +

+ +#### Resposta: C + +Funções regulares não podem ser paradas no meio do caminho (antes de sua finalização). No entando, uma função geradora pode ser "parada" no meio do caminho, e depois continuar de onde parou. Toda vez que uma função geradora encontra uma palavra-chave 'yield', a função produz o valor especificado depois dela. Note que a função gerador, nesse caso, não _retorna_ o valor, mas sim _produz_ o valor. + +Primeiro, inicializamos a função geradora com `i` igual a `10`. Invocamos a função geradora usando o método `next()`. Na primeira vez que invocamos a função geradora, `i` é igual a `10`. Ela encontra o primeiro a primeira palavra-chave `yield`: ela retorna o valor de `i`. A geradora agora está "parada", e `10` é registrado. + +Então, incovamos a função novamente com o método `next()`. Ela continua de onde parou anteriormente, ainda com `i` igual a `10`. Agora, ela encontra a próxima palavra-chave `yield`, e produz `i * 2`. `i` é igual a `10`, então ela retorna `10 * 2`, que é `20`. Isso resulta em `10, 20`. +

+
From 2b9bc36e8c568d313eba6bc86def237f74d971a3 Mon Sep 17 00:00:00 2001 From: Do Trung Kien Date: Tue, 14 Jan 2020 09:36:34 +0700 Subject: [PATCH 458/915] translate next 10 question (132-141) into Vietnamese --- vi-VI/README-vi.md | 75 +++++++++++++++++++++++----------------------- 1 file changed, 38 insertions(+), 37 deletions(-) diff --git a/vi-VI/README-vi.md b/vi-VI/README-vi.md index 94f46d16..5cae7f31 100644 --- a/vi-VI/README-vi.md +++ b/vi-VI/README-vi.md @@ -4205,7 +4205,7 @@ Với phương thức `flat`, ta có thể tạo một mảng mới với các p --- -###### 132. What's the output? +###### 132. Output là gì? ```javascript class Counter { @@ -4238,13 +4238,13 @@ console.log(counterOne.count); #### Đáp án: 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`. +`counterOne` là một instance của class `Counter`. Trong counter class có thuộc tính `count` bên trong constructor, và một phương thức `increment`. Đầu tiên chúng ta gọi phương thức `increment` hai lần bằng `counterOne.increment()`. Nên hiện tại giá trị của `counterOne.count` là `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`. +Sau đó chúng ta có thêm một biến mới là `counterTwo`, và set cho nó giá trị bằng với `counterOne`. Do object được tương tác bằng reference, nên việc này tương ứng với ta đã tạo thêm một reference đến bộ nhớ mà biến `counterOne` đã trỏ vào. Do chúng có chung bộ nhớ, bất cứ thay đổi nào trên `counterTwo` cũng sẽ thay đổi trên `counterOne`. Lúc này `counterTwo.count` cũng sẽ là `2`. -We invoke the `counterTwo.increment()`, which sets the `count` to `3`. Then, we log the count on `counterOne`, which logs `3`. +Ta gọi hàm `counterTwo.increment()` để tăng `count` lên `3`. Sau đó chúng ta in ra `count` ở `counterOne`, kết quả là `3`. @@ -4253,7 +4253,7 @@ We invoke the `counterTwo.increment()`, which sets the `count` to `3`. Then, we --- -###### 133. What's the output? +###### 133. Output là gì? ```javascript const myPromise = Promise.resolve(Promise.resolve("Promise!")); @@ -4285,22 +4285,22 @@ funcTwo(); #### Đáp án: 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.) +Đầu tiên chúng ta gọi `funcOne`. Trong dòng đầu tiên của `funcOne`, chúng ta gọi `myPromise`, đây là một hàm _bất đồng bộ_. Trong khi chờ promise này hoàn thành, nó sẽ tiếp tục thực thi các dòng khác trong `funcOne`. Dòng tiếp theo là cũng là một hàm _bất đồng bộ_ `setTimeout`, phần callback của nó sẽ được gửi tới Web API (các bạn có thể tham khảo câu hỏi trước đó để hiểu về callstack và Web API). -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. +Do cả promise và timeout đều là những hàm xử lý bất đồng bộ, nên trong khi chờ chúng hoàn thành thì các dòng tiếp theo vẫn tiếp tục được thực thi. Có nghĩa là `Last line!` sẽ được in ra đầu tiên, do nó là một hàm chạy _đồng bộ_. Và đây cũng là dòng cuối cùng của hàm `funcOne`, khi này promise sẽ được resolve, trả về `Promise!`. Tuy nhiên do ta tiếp tục gọi hàm `funcTwo()`, call stack của ta vẫn chưa rỗng, nên callback của `setTimeout` vẫn chưa thể được đưa vào callstack (vẫn đang năm ở Web API). -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!`. +Trong hàm `funcTwo` đầu tiên ta sẽ _awaiting_ myPromise. Với từ khóa `await`, Ta sẽ tạm dừng thực thi cho tới khi n ào promise được resolved (hay rejected). Khi này ta sẽ in ra giá trị của `res` (do bản thân hàm promise lại trả về một promise). Nó sẽ in ra `Promise!`. -The next line is the _asynchronous_ `setTimeout` function, from which the callback is sent to the Web API. +Dòng tiếp theo lại là một hàm _bất đồng bộ_ `setTimeout`, callback khi này tiếp tục được gửi tới Web API. -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!` +Ta tiếp tục thực thi dòng cuối cùng của `funcTwo`, trả về `Last line!`. Khi này `funcTwo` đã làm rỗng call stack. Các callback khi nãy (`() => console.log("Timeout!")` từ `funcOne`, và `() => console.log("Timeout!")` từ `funcTwo`) lần lượt được đưa vào trong call stack. Callback đầu tiên in ra `Timeout!`. Callback thứ hai in ra `Timeout!`. Kết quả cuối cùng sẽ là `Last line! Promise! Promise! Last line! Timeout! Timeout!`

--- -###### 134. How can we invoke `sum` in `index.js` from `sum.js?` +###### 134. Làm thế nào có thể gọi hàm `sum` trong `index.js` từ `sum.js?` ```javascript // sum.js @@ -4322,7 +4322,7 @@ import * as sum from "./sum"; #### Đáp án: C -With the asterisk `*`, we import all exported values from that file, both default and named. If we had the following file: +Với dấu hoa thị `*`, ta sẽ import tất cả những gì đã được export ra bởi file đó, cả default lẫn những hàm có tên. Nếu ta có một dòng như sau: ```javascript // info.js @@ -4335,7 +4335,7 @@ import * as info from "./info"; console.log(info); ``` -The following would get logged: +Thì kết quả sẽ là: ```javascript { @@ -4345,20 +4345,20 @@ The following would get logged: } ``` -For the `sum` example, it means that the imported value `sum` looks like this: +Trong ví dụ hàm `sum`, nó giống với chúng ta đã import hàm `sum` như thế này: ```javascript { default: function sum(x) { return x + x } } ``` -We can invoke this function, by calling `sum.default` +Ta có thể gọi hàm này bằng cách sử dụng `sum.default`

--- -###### 135. What's the output? +###### 135. Output là gì? ```javascript const handler = { @@ -4382,20 +4382,20 @@ person.name; #### Đáp án: C -With a Proxy object, we can add custom behavior to an object that we pass to it as the second argument. In tis 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. +Với Proxy object, ta có thể add thêm được các hành vi (behavior) cho object bằng cách đưa nó vào làm đối số thứ hai. Trong trường hợp này, chúng ta đưa vào object `handler` có hai thuộc tính: `set` và `get`. `set` sẽ được gọi mỗi khi ta _thay đổi_ giá trị của thuộc tính, `get` sẽ được gọi mỗi khi ta _truy cập_ giá trị của thuộc tính. -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. +Giá trị của `person` sẽ là đối số đầu tiên đưa vào, là một object rỗng `{}`. Hành vi của `person` là đối số thứ hai, tức `handler`. Do đó môi khi ta thêm thuộc tính của obejct `person`, `set` sẽ được gọi. Nếu ta truy cập thuộc tính của `person` thì `get` sẽ được gọi. -First, we added a new property `name` to the proxy object (`person.name = "Lydia"`). `set` gets invoked, and logs `"Added a new property!"`. +Đầu tiên ra thêm vào thuộc tính `name` cho proxy object (`person.name = "Lydia"`). `set` được gọi và in ra `"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. +Sau đó chúng truy cập thuộc tính này, `get` được gọi và in ra `"Accessed a property!"`.

--- -###### 136. Which of the following will modify the `person` object? +###### 136. Cách nào sau đây sẽ thay đổi object `person`? ```javascript const person = { name: "Lydia Hallie" }; @@ -4413,16 +4413,16 @@ Object.seal(person); #### Đáp án: A -With `Object.seal` we can prevent new properies from being _added_, or existing properties to be _removed_. +Với `Object.seal` ta có thể ngăn _thêm vào_ các thuộc tính mới, hay _xóa đi_ các thuộc tính cũ. -However, you can still modify the value of existing properties. +Tuy nhiên ta vẫn có thể _thay đổi_ các thuộc tính cũ.

--- -###### 137. Which of the following will modify the `person` object? +###### 137. Cách nào sau đây có thể thay đổi object `person`? ```javascript const person = { @@ -4445,16 +4445,16 @@ Object.freeze(person); #### Đáp án: C -The `Object.freeze` method _freezes_ an object. No properties can be added, modified, or removed. +Phương thức `Object.freeze` sẽ _đóng băng_ object. Ta không thể thêm/sửa/xóa bất kì thuộc tính nào. -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. +Tuy nhiên trên thực tế đây chỉ là đóng băng _nông_ (_shallowly_) object, có nghĩa là nó chỉ đóng băng các thuộc tính _trực tiếp_ của object mà thôi. Nếu thuộc tính lại là một object khác, như `address` trong trường hợp này, thuộc tính bên trong của `address` sẽ không bị đóng băng, và ta vẫn có thể chỉnh sửa như bình thường.

--- -###### 138. Which of the following will modify the `person` object? +###### 138. Cách nào sau đây có thể thay đổi object `person`? ```javascript const person = { @@ -4477,16 +4477,16 @@ Object.freeze(person); #### Đáp án: C -The `Object.freeze` method _freezes_ an object. No properties can be added, modified, or removed. +Phương thức `Object.freeze` sẽ _đóng băng_ object. Ta không thể thêm/sửa/xóa bất kì thuộc tính nào. -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. +Tuy nhiên trên thực tế đây chỉ là đóng băng _nông_ (_shallowly_) object, có nghĩa là nó chỉ đóng băng các thuộc tính _trực tiếp_ của object mà thôi. Nếu thuộc tính lại là một object khác, như `address` trong trường hợp này, thuộc tính bên trong của `address` sẽ không bị đóng băng, và ta vẫn có thể chỉnh sửa như bình thường.

--- -###### 139. What's the output? +###### 139. Output là gì? ```javascript const add = x => x + x; @@ -4509,16 +4509,16 @@ myFunc(3); #### Đáp án: 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`. +Đầu tiên, ta gọi hàm `myFunc()` nhưng không đưa vào đối số nào. Do đó `num` và `value` sẽ nhận các giá trị mặc định: `num` là `2`, và `value` sẽ là giá trị trả về của hàm `add`. Với hàm `add`, ta đưa `num` vào làm đối số, tức `2`. `add` trả về `4`, đây sẽ là giá trị của `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`. +Sau đó ta gọi hàm `myFunc(3)`, khi này `3` sẽ là giá trị của `num`. Ta không đưa vào giá trị cho `value`. Lúc này `value` tiếp tục nhận giá trị mặc định: giá trị trả về của hàm `add`. Trong `add`, ta đưa vào `num`, khi này là `3`. `add` sẽ trả về `6`, đây sẽ là giá trị của `value`.

--- -###### 140. What's the output? +###### 140. Output là gì? ```javascript class Counter { @@ -4549,14 +4549,14 @@ console.log(counter.#number) #### Đáp án: 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! +Với cú pháp ES2020, ta có thể thêm các thuộc tính private vào class bằng cách sử dụng `#`. Ta không thể truy cập được biến này bên ngoài class. Khi ta in ra `counter.#number`, một SyntaxError sẽ được throw: ta không thể truy cập từ phía ngoài class `Counter`!

--- -###### 141. What's the output? +###### 141. Câu lệnh còn thiếu là gì? ```javascript const teams = [ @@ -4591,13 +4591,14 @@ obj.next(); // { value: "Lisa", done: false } #### Đáp án: 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*`. +Ta duyệt và in ra giá trị của từng member bên trong `members`, mà `members` lại nằm bên trong mảng `teams`, ta cần đưa vào đối số `teams[i].members` cho hàm generator `getMembers` trong phần code thiếu. Hàm generator sẽ trả về một generator object. Để duyệt qua từng phần tử của một generator object, ta dùng từ khóa `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. +Nếu ta dùng `yield`, `return yield`, hay `return`, toàn bộ generator sẽ được trả về trong lần đầu tiên chúng ta gọi phương thức `next`.

+ --- ###### 142. What's the output? From 38ba0f608c73cb1983c7c65a799cf20423d14fd2 Mon Sep 17 00:00:00 2001 From: Do Trung Kien Date: Tue, 14 Jan 2020 10:18:44 +0700 Subject: [PATCH 459/915] translate next questions (142-145) into Vietnamese --- vi-VI/README-vi.md | 26 ++++++++++++++------------ 1 file changed, 14 insertions(+), 12 deletions(-) diff --git a/vi-VI/README-vi.md b/vi-VI/README-vi.md index 5cae7f31..eed28920 100644 --- a/vi-VI/README-vi.md +++ b/vi-VI/README-vi.md @@ -4601,7 +4601,7 @@ Nếu ta dùng `yield`, `return yield`, hay `return`, toàn bộ generator sẽ --- -###### 142. What's the output? +###### 142. Output là gì? ```javascript const person = { @@ -4631,22 +4631,22 @@ console.log(person.hobbies); #### Đáp án: C -The `addHobby` function receives two arguments, `hobby` and `hobbies` with the default value of the `hobbies` array on the `person` object. +Hàm `addHobby` nhận vào hai đối số, `hobby`, và `hobbies` với giá trị default là mảng `hobbies` của object `person`. -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. +Đầu tiên chúng ta gọi hàm `addHobby` và đưa vào `"running"` làm giá trị cho `hobby`, và một mảng rỗng cho `hobbies`. Do chúng ta đưa vào một mảng rỗng cho `hobbies`, `"running"` sẽ được add vào một mảng rỗng. -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. +Sau đó chúng ta tiếp tục gọi hàm `addHobby`, đưa `"dancing"` vào làm giá trị cho `hobby`. Chúng ta không hề đưa vào giá trị nào cho `hobbies`, do đó nó sẽ sử dụng giá trị mặc định, tức mảng `hobbies` trong thuộc tính của object `person`. Có nghĩa là ta đã thêm `dancing` vào trong mảng `person.hobbies`. -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. +Cuối cùng chúng ta lại gọi `addHobby`, đưa `"baking"` vào làm giá trị cho `hobby`, và mảng `person.hobbies` làm giá trị cho `hobbies`. Có nghĩa là ta đã thêm `baking` vào trong mảng `person.hobbies`. -After pushing `dancing` and `baking`, the value of `person.hobbies` is `["coding", "dancing", "baking"]` +Sau khi thêm `dancing` và `baking`, giá trị của `person.hobbies` là `["coding", "dancing", "baking"]`

--- -###### 143. What's the output? +###### 143. Output là gì? ```javascript class Bird { @@ -4675,14 +4675,14 @@ const pet = new Flamingo(); #### Đáp án: 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. 🦢"`. +Chúng ta tạo ra biến `pet` là một instance của clas `Flamingo`. Khi ta tạo ra instance, `constructor` bên trong `Flamingo` sẽ được gọi. Đầu tiên, `"I'm pink. 🌸"` được in ra, sau đó chúng ta gọi `super()`. `super()` sẽ gọi constructor ở class cha, tức `Bird`. Hàm constructor trong `Bird` được gọi và in ra `"I'm a bird. 🦢"`.

--- -###### 144. Which of the options result(s) in an error? +###### 144. Câu lệnh nào sẽ bị lỗi? ```javascript const emojis = ["🎄", "🎅🏼", "🎁", "⭐"]; @@ -4703,14 +4703,14 @@ const emojis = ["🎄", "🎅🏼", "🎁", "⭐"]; #### Đáp án: 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 propeties on the `emojis` array can be modified, for example by pushing new values, splicing them, or setting the length of the array to 0. +Từ khóa `const` làm cho ta không thể _định nghĩa lại_ giá trị của biến, nó là _read-only_. Tuy nhiên giá trị của bên trong nó thì không phải là bất biến. Các thuộc tính bên trong mảng `emojis` vẫn có thể được sửa đổi, ví dụ thêm phần tử, cắt, hoặc là đưa độ dài mảng về 0.

--- -###### 145. What do we need to add to the `person` object to get `["Lydia Hallie", 21]` as the output of `[...person]`? +###### 145. Ta cần thêm gì vào object `person` để khi gọi `[...person]` sẽ cho kết quả là `["Lydia Hallie", 21]`? ```javascript const person = { @@ -4731,7 +4731,9 @@ const person = { #### Đáp án: 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)`. +Mặc định ta không thể duyệt qua được object. Trừ phi nó được cài đặt iterator protocol. Ta có thể cài đặt bằng cách thêm vào một iterator symbol `[Symbol.iterator]`, biến nó trở thành generator object (object có thể duyệt được), ví dụ `*[Symbol.iterator]() {}`. + +Để generator này trả về được mảng các giá trị của các thuộc tính của object `person`, tức `Object.values` của object `person`, ta sẽ sử dụng cấu trúc `yield* Object.values(this)`.

From e5956734e3c746b51604d7c9d2f100a6464be9a1 Mon Sep 17 00:00:00 2001 From: Do Trung Kien Date: Tue, 14 Jan 2020 10:49:19 +0700 Subject: [PATCH 460/915] fix typo --- vi-VI/README-vi.md | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/vi-VI/README-vi.md b/vi-VI/README-vi.md index eed28920..fbff9dc5 100644 --- a/vi-VI/README-vi.md +++ b/vi-VI/README-vi.md @@ -3357,7 +3357,6 @@ compareMembers(person) 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. -We set the default value for `person2` equal to the `person` object, and passed the `person` object as the value for `person1`. 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`. Điều đó có nghĩa là chúng cùng trỏ đến một object trong bộ nhớ, do đó chúng bằng nhau, và `They are the same!` được in ra. @@ -3551,7 +3550,7 @@ getName() 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`. @@ -4205,7 +4204,7 @@ Với phương thức `flat`, ta có thể tạo một mảng mới với các p --- -###### 132. Output là gì? +###### 132. Output là gì? ```javascript class Counter { From 3333a36fb2db55bce7e8bd7a9043a912400b56d0 Mon Sep 17 00:00:00 2001 From: Tarabass Date: Wed, 15 Jan 2020 21:04:23 +0100 Subject: [PATCH 461/915] Question 40 --- nl-NL/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/nl-NL/README.md b/nl-NL/README.md index f4e2725c..64b0bbf0 100644 --- a/nl-NL/README.md +++ b/nl-NL/README.md @@ -1240,7 +1240,7 @@ Wat primitieven onderscheidt van objecten is dat primitieven geen properties of `[1, 2]` is our initial value. This is the value we start with, en the value of the very first `acc`. During the first round, `acc` is `[1,2]`, en `cur` is `[0, 1]`. We concatenate them, which results in `[1, 2, 0, 1]`. -Then, `[1, 2, 0, 1]` is `acc` en `[2, 3]` is `cur`. We concatenate them, en get `[1, 2, 0, 1, 2, 3]` +Tijdens de volgende iteratie `acc` is `[1, 2, 0, 1]` en `cur` is `[2, 3]`. Deze worden wederom geconcateneerd en resulteerd in `[1, 2, 0, 1, 2, 3]`.

From cd31ed0d1d1035476f3ded6a9f09e161e4521664 Mon Sep 17 00:00:00 2001 From: Tarabass Date: Wed, 15 Jan 2020 21:06:37 +0100 Subject: [PATCH 462/915] Question 41 --- nl-NL/README.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/nl-NL/README.md b/nl-NL/README.md index 64b0bbf0..ebb7219d 100644 --- a/nl-NL/README.md +++ b/nl-NL/README.md @@ -1238,7 +1238,7 @@ Wat primitieven onderscheidt van objecten is dat primitieven geen properties of #### Antwoord: C -`[1, 2]` is our initial value. This is the value we start with, en the value of the very first `acc`. During the first round, `acc` is `[1,2]`, en `cur` is `[0, 1]`. We concatenate them, which results in `[1, 2, 0, 1]`. +`[1, 2]` is onze initiële waarde. Dit is de waarde waarmee we starten, en de waarde van de allereerste `acc`. Tijdens de eerste iteratie, `acc` is `[1, 2]` en `cur` is `[0, 1]`. Deze waarden concateneren we, wat resulteerd in `[1, 2, 0, 1]`. Tijdens de volgende iteratie `acc` is `[1, 2, 0, 1]` en `cur` is `[2, 3]`. Deze worden wederom geconcateneerd en resulteerd in `[1, 2, 0, 1, 2, 3]`. @@ -1265,11 +1265,11 @@ Tijdens de volgende iteratie `acc` is `[1, 2, 0, 1]` en `cur` is `[2, 3]`. Deze #### Antwoord: B -`null` is falsy. `!null` returns `true`. `!true` returns `false`. +`null` is falsy. `!null` geeft `true` terug. `!true` geeft `false` terug. -`""` is falsy. `!""` returns `true`. `!true` returns `false`. +`""` is falsy. `!""` geeft `true` terug. `!true` geeft `false` terug. -`1` is truthy. `!1` returns `false`. `!false` returns `true`. +`1` is truthy. `!1` geeft `false` terug. `!false` geeft `true` terug.

From 6425381931cee5a959af253bd66234d52eaf9a47 Mon Sep 17 00:00:00 2001 From: Tarabass Date: Wed, 15 Jan 2020 21:08:57 +0100 Subject: [PATCH 463/915] Question 42 --- nl-NL/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/nl-NL/README.md b/nl-NL/README.md index ebb7219d..f521c6a8 100644 --- a/nl-NL/README.md +++ b/nl-NL/README.md @@ -1292,7 +1292,7 @@ setInterval(() => console.log("Hi"), 1000); #### Antwoord: A -It returns a unique id. This id can be used to clear that interval with the `clearInterval()` function. +Het geeft een uniek id terug. Dit id kan gebruikt worden om de interval te stoppen door het mee te geven aan de `clearInterval()` functie.

From 6eed4f3202cc9534ff0fe93612331f448b97bc5f Mon Sep 17 00:00:00 2001 From: Tarabass Date: Wed, 15 Jan 2020 21:15:31 +0100 Subject: [PATCH 464/915] Question 43 --- nl-NL/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/nl-NL/README.md b/nl-NL/README.md index f521c6a8..8adab314 100644 --- a/nl-NL/README.md +++ b/nl-NL/README.md @@ -1315,7 +1315,7 @@ Het geeft een uniek id terug. Dit id kan gebruikt worden om de interval te stopp #### Antwoord: A -A string is an iterable. The spread operator maps every character of an iterable to one element. +Een string is een iterable. The spread operator arrangeert elk karakter van een iterable naar één element.

From 4c41e2d6ce571edf51f2d87e1a6a9bf3f071ff16 Mon Sep 17 00:00:00 2001 From: Tarabass Date: Wed, 15 Jan 2020 21:28:21 +0100 Subject: [PATCH 465/915] Question 44 --- nl-NL/README.md | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/nl-NL/README.md b/nl-NL/README.md index 8adab314..d3571473 100644 --- a/nl-NL/README.md +++ b/nl-NL/README.md @@ -1345,12 +1345,11 @@ 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_. -Regular functions cannot be stopped mid-way after invocation. However, a generator function can be "stopped" midway, en 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. +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. -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", en `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, en yields `i * 2`. `i` is equal to `10`, so it returns `10 * 2`, which is `20`. This results in `10, 20`. +Dan roepen we de functie nog een keer aan met de `next()` methode. Het gaat verder waar het eerder gebleven is, waarbij `i` nog steeds gelijk is aan `10`. Nu wordt de volgende `yield` aangetroffen, en levert `i * 2` op. `i` is gelijk aan `10`, dus het levert `10 * 2` op, wat gelijk is aan `20`. Het resultaat is dus `10, 20`.

From c25b1050009fc32fa068946974d02debd9ed3b17 Mon Sep 17 00:00:00 2001 From: Tarabass Date: Wed, 15 Jan 2020 21:45:36 +0100 Subject: [PATCH 466/915] Question 45 --- nl-NL/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/nl-NL/README.md b/nl-NL/README.md index d3571473..6fcdbb72 100644 --- a/nl-NL/README.md +++ b/nl-NL/README.md @@ -1380,7 +1380,7 @@ Promise.race([firstPromise, secondPromise]).then(res => console.log(res)); #### Antwoord: 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`), en 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. +Wanneer we meerdere promises meegeven aan de `Promise.race` methode zal het de _eerste_ promise resolven/rejecten. Aan de `setTimeout` methodes geven we een timer mee: 500ms voor de eerste promise (`firstPromise`) en 100ms voor de tweede promise (`secondPromise`). Dit betekent dat de `secondPromise` als eerste resolved met de waarde `'two'`. `res` bevat nu de waarde `'two'`, wat dus gelogd wordt.

From 72ba7e5957084999286b1389854cfc314a7c6ac1 Mon Sep 17 00:00:00 2001 From: Tarabass Date: Wed, 15 Jan 2020 21:57:28 +0100 Subject: [PATCH 467/915] Question 46 --- nl-NL/README.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/nl-NL/README.md b/nl-NL/README.md index 6fcdbb72..4c199792 100644 --- a/nl-NL/README.md +++ b/nl-NL/README.md @@ -1407,19 +1407,19 @@ console.log(members); #### Antwoord: D -First, we declare a variable `person` with the value of an object that has a `name` property. +Allereerst declareren we een variabele `person` met de waarde van een object met een propertie `name`. -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!) +Dan declareren we een variabele genaamd `members`. We vullen het eerste element van die array met de waarde van de variabele `person`. Objecten interacteren _by reference_. Wanneer je de ene referentie van een variabele toewijst aan een andere variabele, maak je een _kopie_ van die referentie (let op dat ze niet _dezelfde_ referentie hebben!). -Then, we set the variable `person` equal to `null`. +Dan zetten we de variabele `person` gelijk aan `null`. -We are only modifying the value of the `person` variable, en 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. +We passaen alleen de waarde aan van de `person` variabele en niet van het eerste element in de array, omdat dat element een andere referentie heeft (gekopieerd) naar dat object. Het eerste element behoudt nog steeds een referentie naar het eerste object. Wanneer we de array `members` loggen heeft het eerste element nog steeds de waarde van het object, wat dus gelogd wordt.

From 2aaa6cd1df118c8f859cfc5580eee1935535bab4 Mon Sep 17 00:00:00 2001 From: Tarabass Date: Wed, 15 Jan 2020 22:01:49 +0100 Subject: [PATCH 468/915] Question 47 --- nl-NL/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/nl-NL/README.md b/nl-NL/README.md index 4c199792..02aad161 100644 --- a/nl-NL/README.md +++ b/nl-NL/README.md @@ -1449,7 +1449,7 @@ for (const item in person) { #### Antwoord: B -With a `for-in` loop, we can iterate through object keys, in this case `name` en `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`, en gets logged. Then, `item` is equal to `age`, which gets logged. +Met een `for-in` loop kunnen we itereren over object keys, in dit geval `name` en `age`. Onder de motorkap zijn object keys strings (als het geen Symbols zijn). Bij elke iteratie is de waarde van `item` gelijk aan de huidige key waarover wordt geïtereerd. Bj de eerste iteratie is `item` gelijk aan `name` en wordt gelogd. Bij de tweede iteratie is `item` gelijk aan `age` en wordt gelogd.

From 7c2ea2a6ff8c748e5313b6b1d62657db3e1737e8 Mon Sep 17 00:00:00 2001 From: Tarabass Date: Wed, 15 Jan 2020 22:11:17 +0100 Subject: [PATCH 469/915] Question 48 --- nl-NL/README.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/nl-NL/README.md b/nl-NL/README.md index 02aad161..14a5bc02 100644 --- a/nl-NL/README.md +++ b/nl-NL/README.md @@ -1472,11 +1472,11 @@ console.log(3 + 4 + "5"); #### Antwoord: 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. +Operator associativiteit is de volgorde waarin de compiler de expressies evalueerd, of van links naar recht of van rechts naar links. Dat gebeurt alleen als alle operators _dezelfde_ prioriteit hebben. In dit geval hebben we maar één type operator: `+`. In beginsel, de associativiteit is van links naar rechts. -`3 + 4` gets evaluated first. This results in the number `7`. +`3 + 4` wordt eerst geëvalueerd. Dit levert het getal `7` op. -`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"`. +`7 + '5'` resulteert in `"75"` door coersion. JavaScript converteert het getal `7` naar een string, zo ook te zien bij vraag 15. We kunnen twee stringen concateneren door gebruik te maken van de `+` operator. `"7" + "5"` resulteert in `"75"`.

From 06e23339443f96d43f73b706d75c111721c33e64 Mon Sep 17 00:00:00 2001 From: Tarabass Date: Wed, 15 Jan 2020 22:20:32 +0100 Subject: [PATCH 470/915] Question 49 --- nl-NL/README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/nl-NL/README.md b/nl-NL/README.md index 14a5bc02..5f427d03 100644 --- a/nl-NL/README.md +++ b/nl-NL/README.md @@ -1499,9 +1499,9 @@ const num = parseInt("7*6", 10); #### Antwoord: 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 en ignores the following characters. +Alleen het eerste getal in de string wordt geretourneerd. Gebaseerd op de _radix_ (het tweede argument om te speciferen naar welk type nummer we het willen parsen: base 10, hexadecimal, octal, binary, etc.), de `parseInt` methode checkt of de karakters in de string geldig zijn. Zodra het een karakter tegenkomt dat niet een geldig getal is in het eerste argument stopt het parsen en worden opvolgende karakters genegeerd. -`*` is not a valid number. It only parses `"7"` into the decimal `7`. `num` now holds the value of `7`. +`*` is geen geldig getal. Alleen `"7"` wordt geparsed naar een decimal `7`. `num` bevat nu de waarde `7`.

From 8c6520fcf14f970ca2e2230064ceff427330f64b Mon Sep 17 00:00:00 2001 From: Mikhail Kryukov <17042755+daniil-gorbunov@users.noreply.github.com> Date: Thu, 16 Jan 2020 00:00:00 -0800 Subject: [PATCH 471/915] Duplicate question #138 was removed --- README.md | 46 +++++++--------------------------------------- 1 file changed, 7 insertions(+), 39 deletions(-) diff --git a/README.md b/README.md index 4e8af3c9..8a26d70d 100644 --- a/README.md +++ b/README.md @@ -4464,39 +4464,7 @@ However, it only _shallowly_ freezes the object, meaning that only _direct_ prop --- -###### 138. 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" }` - -
Answer -

- -#### Answer: 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. - -

-
- ---- - -###### 139. What's the output? +###### 138. What's the output? ```javascript const add = x => x + x; @@ -4528,7 +4496,7 @@ Then, we invoked `myFunc(3)` and passed the value `3` as the value for the argum --- -###### 140. What's the output? +###### 139. What's the output? ```javascript class Counter { @@ -4566,7 +4534,7 @@ In ES2020, we can add private variables in classes by using the `#`. We cannot a --- -###### 141. What's the output? +###### 140. What's the output? ```javascript const teams = [ @@ -4610,7 +4578,7 @@ If we would've written `yield`, `return yield`, or `return`, the entire generato --- -###### 142. What's the output? +###### 141. What's the output? ```javascript const person = { @@ -4655,7 +4623,7 @@ After pushing `dancing` and `baking`, the value of `person.hobbies` is `["coding --- -###### 143. What's the output? +###### 142. What's the output? ```javascript class Bird { @@ -4691,7 +4659,7 @@ We create the variable `pet` which is an instance of the `Flamingo` class. When --- -###### 144. Which of the options result(s) in an error? +###### 143. Which of the options result(s) in an error? ```javascript const emojis = ["🎄", "🎅🏼", "🎁", "⭐"]; @@ -4719,7 +4687,7 @@ The `const` keyword simply means we cannot _redeclare_ the value of that variabl --- -###### 145. What do we need to add to the `person` object to get `["Lydia Hallie", 21]` as the output of `[...person]`? +###### 144. What do we need to add to the `person` object to get `["Lydia Hallie", 21]` as the output of `[...person]`? ```javascript const person = { From 1f4e20d1a0324b3527208f9a291d2b939ef73484 Mon Sep 17 00:00:00 2001 From: Daniil Gorbunov Date: Thu, 16 Jan 2020 11:00:45 -0800 Subject: [PATCH 472/915] Duplicate question #138 was removed in translations --- en-EN/README.md | 46 +++++++--------------------------------------- vi-VI/README-vi.md | 46 +++++++--------------------------------------- 2 files changed, 14 insertions(+), 78 deletions(-) diff --git a/en-EN/README.md b/en-EN/README.md index ddf67054..b75f7289 100644 --- a/en-EN/README.md +++ b/en-EN/README.md @@ -4464,39 +4464,7 @@ However, it only _shallowly_ freezes the object, meaning that only _direct_ prop --- -###### 138. 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" }` - -
Answer -

- -#### Answer: 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. - -

-
- ---- - -###### 139. What's the output? +###### 138. What's the output? ```javascript const add = x => x + x; @@ -4528,7 +4496,7 @@ Then, we invoked `myFunc(3)` and passed the value `3` as the value for the argum --- -###### 140. What's the output? +###### 139. What's the output? ```javascript class Counter { @@ -4566,7 +4534,7 @@ In ES2020, we can add private variables in classes by using the `#`. We cannot a --- -###### 141. What's the output? +###### 140. What's the output? ```javascript const teams = [ @@ -4610,7 +4578,7 @@ If we would've written `yield`, `return yield`, or `return`, the entire generato --- -###### 142. What's the output? +###### 141. What's the output? ```javascript const person = { @@ -4655,7 +4623,7 @@ After pushing `dancing` and `baking`, the value of `person.hobbies` is `["coding --- -###### 143. What's the output? +###### 142. What's the output? ```javascript class Bird { @@ -4691,7 +4659,7 @@ We create the variable `pet` which is an instance of the `Flamingo` class. When --- -###### 144. Which of the options result(s) in an error? +###### 143. Which of the options result(s) in an error? ```javascript const emojis = ["🎄", "🎅🏼", "🎁", "⭐"]; @@ -4719,7 +4687,7 @@ The `const` keyword simply means we cannot _redeclare_ the value of that variabl --- -###### 145. What do we need to add to the `person` object to get `["Lydia Hallie", 21]` as the output of `[...person]`? +###### 144. What do we need to add to the `person` object to get `["Lydia Hallie", 21]` as the output of `[...person]`? ```javascript const person = { diff --git a/vi-VI/README-vi.md b/vi-VI/README-vi.md index fbff9dc5..55f44b4f 100644 --- a/vi-VI/README-vi.md +++ b/vi-VI/README-vi.md @@ -4453,39 +4453,7 @@ Tuy nhiên trên thực tế đây chỉ là đóng băng _nông_ (_shallowly_) --- -###### 138. Cách nào sau đây có thể thay đổi object `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 án -

- -#### Đáp án: C - -Phương thức `Object.freeze` sẽ _đóng băng_ object. Ta không thể thêm/sửa/xóa bất kì thuộc tính nào. - -Tuy nhiên trên thực tế đây chỉ là đóng băng _nông_ (_shallowly_) object, có nghĩa là nó chỉ đóng băng các thuộc tính _trực tiếp_ của object mà thôi. Nếu thuộc tính lại là một object khác, như `address` trong trường hợp này, thuộc tính bên trong của `address` sẽ không bị đóng băng, và ta vẫn có thể chỉnh sửa như bình thường. - -

-
- ---- - -###### 139. Output là gì? +###### 138. Output là gì? ```javascript const add = x => x + x; @@ -4517,7 +4485,7 @@ Sau đó ta gọi hàm `myFunc(3)`, khi này `3` sẽ là giá trị của `num` --- -###### 140. Output là gì? +###### 139. Output là gì? ```javascript class Counter { @@ -4555,7 +4523,7 @@ Với cú pháp ES2020, ta có thể thêm các thuộc tính private vào class --- -###### 141. Câu lệnh còn thiếu là gì? +###### 140. Câu lệnh còn thiếu là gì? ```javascript const teams = [ @@ -4600,7 +4568,7 @@ Nếu ta dùng `yield`, `return yield`, hay `return`, toàn bộ generator sẽ --- -###### 142. Output là gì? +###### 141. Output là gì? ```javascript const person = { @@ -4645,7 +4613,7 @@ Sau khi thêm `dancing` và `baking`, giá trị của `person.hobbies` là `["c --- -###### 143. Output là gì? +###### 142. Output là gì? ```javascript class Bird { @@ -4681,7 +4649,7 @@ Chúng ta tạo ra biến `pet` là một instance của clas `Flamingo`. Khi ta --- -###### 144. Câu lệnh nào sẽ bị lỗi? +###### 143. Câu lệnh nào sẽ bị lỗi? ```javascript const emojis = ["🎄", "🎅🏼", "🎁", "⭐"]; @@ -4709,7 +4677,7 @@ Từ khóa `const` làm cho ta không thể _định nghĩa lại_ giá trị c --- -###### 145. Ta cần thêm gì vào object `person` để khi gọi `[...person]` sẽ cho kết quả là `["Lydia Hallie", 21]`? +###### 144. Ta cần thêm gì vào object `person` để khi gọi `[...person]` sẽ cho kết quả là `["Lydia Hallie", 21]`? ```javascript const person = { From 8656a9afcd97ca7f39db2d7592c1e4cdac706df8 Mon Sep 17 00:00:00 2001 From: Tarabass Date: Thu, 16 Jan 2020 20:33:27 +0100 Subject: [PATCH 473/915] Question 50 --- nl-NL/README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/nl-NL/README.md b/nl-NL/README.md index 5f427d03..ff495066 100644 --- a/nl-NL/README.md +++ b/nl-NL/README.md @@ -1527,9 +1527,9 @@ Alleen het eerste getal in de string wordt geretourneerd. Gebaseerd op de _radix #### Antwoord: 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 en inserts the values returned from the function. +Wanneer je iterate over een array gebruik makend van de `map()` methode is de waarde van `num` gelijk aan het huidige element dat verwerkt wordt. In dit geval zijn de elementen getallen en de conditie van de if statement `typeof num === "number"` geeft `true` terug. De `map()` methode maakt een nieuwe array aan met als inhoud het resultaat van het aanroepen van de meegegeven functie op elk van de elementen uit de originele array. -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`. +Echter geven wij nooit een waarde terug. Wanneer we geen waarde toevoegen in de functie zal de functie `undefined` teruggeven. De functie wordt voor elk element in de originele array aangeroepen en voor elk element geven we `undefined` terug.

From f9940f9b45b34631c749396a788d02d0706a09a4 Mon Sep 17 00:00:00 2001 From: Tarabass Date: Thu, 16 Jan 2020 20:46:55 +0100 Subject: [PATCH 474/915] Question 51 --- nl-NL/README.md | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/nl-NL/README.md b/nl-NL/README.md index ff495066..8a33053d 100644 --- a/nl-NL/README.md +++ b/nl-NL/README.md @@ -1561,12 +1561,11 @@ 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). -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). +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"`. -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"` +De waarde van `person` is een object. Het argument `member` heeft een (gekopieerde) referentie naar _hetzelfde_ object. Wanneer we een propertie veranderen van het object waar `member` een referentie naartoe heeft zal de waarde van `person` ook veranderen, omdat beide een referentie hebben naar hetzelfde object. De propertie `name` van `person` is nu gelijk aan `"Lydia"`.

From fc104358acc9a67bdae3dbd783e89d95fdfcfab7 Mon Sep 17 00:00:00 2001 From: Tarabass Date: Thu, 16 Jan 2020 20:54:34 +0100 Subject: [PATCH 475/915] Question 52 --- nl-NL/README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/nl-NL/README.md b/nl-NL/README.md index 8a33053d..8820768c 100644 --- a/nl-NL/README.md +++ b/nl-NL/README.md @@ -1601,9 +1601,9 @@ sayHi(); #### Antwoord: 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'`. +Met de `throw` statement kunnen we custom errors gooien. Een exceptie kan een string, een number, een boolean of een object zijn. In dit geval onze exceptie is aan string met de waarde `'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'`. +Met de `catch` statement kunnen we specificeren wat er moet gebeuren als er een exceptie is gegooid in het `try` blok. Een exceptie is gegooid: de string `'Hello world'`. `e` is nu gelijk aan deze string en wordt dus gelogd. Dat resulteert in `'Oh an error: Hello world'`.

From b199868d6812e870566f3c317552f91871200c58 Mon Sep 17 00:00:00 2001 From: Tarabass Date: Thu, 16 Jan 2020 20:57:36 +0100 Subject: [PATCH 476/915] Question 53 --- nl-NL/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/nl-NL/README.md b/nl-NL/README.md index 8820768c..97c9899f 100644 --- a/nl-NL/README.md +++ b/nl-NL/README.md @@ -1632,7 +1632,7 @@ console.log(myCar.make); #### Antwoord: 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"`. +Wanneer je een propertie teruggeeft zal de waarde van de propertie gelijk zijn aan de _geretourneerde_ waarde, niet de waarde die gezet wordt in de constructor. We geven de string `"Maserati"` terug, dus `myCar.make` is gelijk aan `"Maserati"`.

From b4453b73a6b3c49e04ad537d50c6b94939855ddd Mon Sep 17 00:00:00 2001 From: Tarabass Date: Thu, 16 Jan 2020 21:12:26 +0100 Subject: [PATCH 477/915] Question 54 --- nl-NL/README.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/nl-NL/README.md b/nl-NL/README.md index 97c9899f..b7c33861 100644 --- a/nl-NL/README.md +++ b/nl-NL/README.md @@ -1660,18 +1660,18 @@ console.log(typeof y); #### Antwoord: A -`let x = y = 10;` is actually shorthand for: +`let x = y = 10;` is een verkorte versie van: ```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`. +Wanneer we de waarde van `y` vullen met `10` voegen we eigenlijk een propertie `y` toe aan het globale object (`window` in de browser, `global` in Node). In de browser is `window.y` nu gelijk aan `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 (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"`. +Daarna declareren we de variabele `x` met de waarde van `y`, wat 10 is. Variabelen die gedeclareerd worden met het keyword `let` zijn _block scoped_, ze zijn alleen gedefinieerd binnen het blok waarin ze gedeclareerd zijn. In dit geval de direct aangeroepen functie (IIFE). Wanneer we de operator `typeof` gebruiken is `x` dus niet gedefinieerd; we proberen `x` te benaderen buiten de scope waarin het gedeclareerd is. Dat betekent dat `x` niet gedefinieerd is. variabelen die nog geen waarde toegewezen hebben gekregen zijn van het type `"undefined"`. `console.log(typeof x)` geeft `"undefined"` terug. -However, we created a global variable `y` when setting `y` equal to `10`. This value is accessible anywhere in our code. `y` is defined, en holds a value of type `"number"`. `console.log(typeof y)` returns `"number"`. +Echter, we hebben een globale variabele `y` aangemaakt toen we 'y' vulde met `10`. Deze waarde is overal toegankelijk in onze code. `y` is gedefinieerd en bevat de waarde `"number"`. `console.log(typeof y)` geeft `"number"` terug.

From bbf5149bcdf271c568bb84febe128b0792ad3b0e Mon Sep 17 00:00:00 2001 From: Tarabass Date: Thu, 16 Jan 2020 21:17:34 +0100 Subject: [PATCH 478/915] Question 55 --- nl-NL/README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/nl-NL/README.md b/nl-NL/README.md index b7c33861..2ff51dc4 100644 --- a/nl-NL/README.md +++ b/nl-NL/README.md @@ -1710,9 +1710,9 @@ pet.bark(); #### Antwoord: 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. +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`. -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`. +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.

From 93722b56c4231a7424ac6376a2fbe0a29485a250 Mon Sep 17 00:00:00 2001 From: Tarabass Date: Thu, 16 Jan 2020 21:21:09 +0100 Subject: [PATCH 479/915] Question 56 --- nl-NL/README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/nl-NL/README.md b/nl-NL/README.md index 2ff51dc4..835dace0 100644 --- a/nl-NL/README.md +++ b/nl-NL/README.md @@ -1737,9 +1737,9 @@ console.log(set); #### Antwoord: D -The `Set` object is a collection of _unique_ values: a value can only occur once in a set. +Het `Set` object is een collectie van _unieke_ waarden: een waarde kan maar één keer voorkomen in een 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}`. +We geven de array `[1, 1, 2, 3, 4]` mee met de dubbele waarde `1`. Omdat we niet twee keer dezelfde waarde kunnen hebben in een set zal één van deze dubbele waarden verwijderd worden. Dit resulteert in `{1, 2, 3, 4}`.

From 4fe4ba813bed7ca9e2198ebe63e662890d131ba6 Mon Sep 17 00:00:00 2001 From: Tarabass Date: Thu, 16 Jan 2020 21:36:39 +0100 Subject: [PATCH 480/915] Question 57 --- nl-NL/README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/nl-NL/README.md b/nl-NL/README.md index 835dace0..4594adad 100644 --- a/nl-NL/README.md +++ b/nl-NL/README.md @@ -1773,9 +1773,9 @@ console.log(myCounter); #### Antwoord: C -An imported module is _read-only_: you cannot modify the imported module. Only the module that exports them can change its value. +Een geïmporteerde module is _readonly_: je kunt de geïmporteerde module niet aanpassen. Alleen de module die de exports doet kan de waarde aanpassen. -When we try to increment the value of `myCounter`, it throws an error: `myCounter` is read-only en cannot be modified. +Wanneer we de waarde van `myCounter` aanpassen zal dit een error gooien: `myCounter` is read-only en cannot be modified.

From aa22c0a3bf268ba80220dd54a57aa42336951001 Mon Sep 17 00:00:00 2001 From: Tarabass Date: Thu, 16 Jan 2020 21:42:56 +0100 Subject: [PATCH 481/915] Question 58 --- nl-NL/README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/nl-NL/README.md b/nl-NL/README.md index 4594adad..6689c813 100644 --- a/nl-NL/README.md +++ b/nl-NL/README.md @@ -1802,9 +1802,9 @@ console.log(delete age); #### Antwoord: 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. +De `delete` operatot geeft een boolean waarde terug: `true` bij een succesvolle verwijdering, anders zal het `false` teruggeven. Echter, variabelen die gedeclareerd worden met de keywords `var`, `const` en `let` kunnen niet verwijderd worden met de `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`. +De variabele `name` werd gedeclareerd met het keyword `const`, dus het verwijderen is niet succesvol: `false` wordt teruggegeven. Wanneer we `age` de waarde `21` geven voegen we eigenlijk een propertie `age` toe aan het globale object. Properties van objecten kunnen prima verwijderd worden op deze manier, ook van het globale object, dus `delete age` geeft `true` terug.

From cc3e761692a7f97fa0c8c208499783392afa2035 Mon Sep 17 00:00:00 2001 From: Tarabass Date: Thu, 16 Jan 2020 21:47:03 +0100 Subject: [PATCH 482/915] Question 59 --- nl-NL/README.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/nl-NL/README.md b/nl-NL/README.md index 6689c813..3d82fd11 100644 --- a/nl-NL/README.md +++ b/nl-NL/README.md @@ -1830,7 +1830,7 @@ console.log(y); #### Antwoord: C -We can unpack values from arrays or properties from objects through destructuring. For example: +We kunnen waarden van arrays en objecten uitpakken door `destructuring`. Voorbeeld: ```javascript [a, b] = [1, 2]; @@ -1838,7 +1838,7 @@ We can unpack values from arrays or properties from objects through destructurin -The value of `a` is now `1`, en the value of `b` is now `2`. What we actually did in the question, is: +De waarde van `a` is nu `1` en de waarde van `b` is nu `2`. Wat we dus eigenlijk deden in de vraag is: ```javascript [y] = [1, 2, 3, 4, 5]; @@ -1846,7 +1846,7 @@ The value of `a` is now `1`, en the value of `b` is now `2`. What we actually di -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. +Dat betekent dat de waarde van `y` gelijk is aan de eerste waarde van de array, het getal `1`. Wanneer we `y` loggen, geeft dit `1` terug.

From c44c2c7e299272c65206e80dcd19bd403191e71d Mon Sep 17 00:00:00 2001 From: Tarabass Date: Fri, 17 Jan 2020 22:08:06 +0100 Subject: [PATCH 483/915] Question 60 --- nl-NL/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/nl-NL/README.md b/nl-NL/README.md index 3d82fd11..ec1c1cf7 100644 --- a/nl-NL/README.md +++ b/nl-NL/README.md @@ -1872,7 +1872,7 @@ console.log(admin); #### Antwoord: B -It's possible to combine objects using the spread operator `...`. It lets you create copies of the key/value pairs of one object, en add them to another object. In this case, we create copies of the `user` object, en 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 }`. +Het is mogelijk om objecten samen te voegen door gebruik te maken van de spread operator `...`. Het geeft je de mogelijkheid om key/value pairs van het ene object te kopiëren naar een ander object. In dit geval maken we een kopie van het `user` object en voegen het samen met het `admin` object. Het `admin` object bevat nu de gekopieerde key/value pairs, wat resulteert in `{ admin: true, name: "Lydia", age: 21 }`.

From 2cd4a12191a9d94db6d7414e8558d6c2c80acfc7 Mon Sep 17 00:00:00 2001 From: Tarabass Date: Fri, 17 Jan 2020 22:08:31 +0100 Subject: [PATCH 484/915] Question 61 --- nl-NL/README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/nl-NL/README.md b/nl-NL/README.md index ec1c1cf7..1c7f684c 100644 --- a/nl-NL/README.md +++ b/nl-NL/README.md @@ -1900,9 +1900,9 @@ console.log(Object.keys(person)); #### Antwoord: 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"`. +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 added using the `defineProperty` method are immutable by default. You can override this behavior using the `writable`, `configurable` en `enumerable` properties. This way, the `defineProperty` method gives you a lot more control over the properties you're adding to an object. +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.

From 29f3949959e7f345edbf09f3c8091d2a72908c90 Mon Sep 17 00:00:00 2001 From: Tarabass Date: Fri, 17 Jan 2020 22:08:50 +0100 Subject: [PATCH 485/915] Question 62 --- nl-NL/README.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/nl-NL/README.md b/nl-NL/README.md index 1c7f684c..1f58f0b8 100644 --- a/nl-NL/README.md +++ b/nl-NL/README.md @@ -1932,11 +1932,11 @@ console.log(data); #### Antwoord: A -The second argument of `JSON.stringify` is the _replacer_. The replacer can either be a function or an array, en lets you control what en how the values should be stringified. +Het tweede argument van `JSON.stringify` is de _replacer_. De replacer kan óf een functie zijn óf een array, en geeft je controle over wat en hoe de waarden gestringified worden. -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"` en `"health"` are included, `"username"` is excluded. `data` is now equal to `"{"level":19, "health":90}"`. +Als de replacer een _array_ is zullen alleen de propertie namen die in de array zitten toegevoegd worden aan de JSON string. In dit geval worden alleen de properties `"level"` en `"health"` toegevoegd, `"username"` niet. `data` is nu gelijk aan `"{"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. +Als de replacer een _functie_ is zal die functie worden aangeroepen over elke propertie in het object dat je omzet naar een string. De waarde die teruggegeven wordt door die functie zal de waarde zijn van die propertie wanneer het wordt toegevoegd aan de JSON string. Als de waarde `undefined` is zal de property niet worden toegevoegd aan de JSON string.

From ee092b20a10af9dc6f4aa997fee9535b957ec7df Mon Sep 17 00:00:00 2001 From: Tarabass Date: Fri, 17 Jan 2020 22:09:09 +0100 Subject: [PATCH 486/915] Question 63 --- nl-NL/README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/nl-NL/README.md b/nl-NL/README.md index 1f58f0b8..5312ce82 100644 --- a/nl-NL/README.md +++ b/nl-NL/README.md @@ -1968,9 +1968,9 @@ console.log(num2); #### Antwoord: 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`, en only increments the value of `num` afterwards. +De unary operator `++` geeft eerst de waarde van de variabele terug, en pas daarna de waarde verhogen van de variabele. De waarde van `num1` is `10` omdat de `increaseNumber` functie eerst de waarde van `num` teruggeeft, wat `10` is, en pas daarna de waarde van `num` verhogen met 1. -`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` omdat we `num1` meegeven aan de functie `increasePassedNumber`. `number` is gelijk aan `10` (de waarde van ` num1`). Nogmaals, de unary operator `++` zal _eerst_ de huidige waarde van de variabele teruggeven en pas _daarna_ de waarde verhogen. De waarde van `number` is `10`, dus de waarde van `num2` is ook `10`.

From 8a1e5c1369106156bbd36a393d58ef890ebfd3d0 Mon Sep 17 00:00:00 2001 From: Tarabass Date: Fri, 17 Jan 2020 22:09:26 +0100 Subject: [PATCH 487/915] Question 64 --- nl-NL/README.md | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/nl-NL/README.md b/nl-NL/README.md index 5312ce82..c3e849c1 100644 --- a/nl-NL/README.md +++ b/nl-NL/README.md @@ -2002,13 +2002,14 @@ multiply(value); #### Antwoord: 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 }`. +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 }`. -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`. +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. -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`, en log the multiplied value `20`. +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`. -The fourth time, we pass the `value` object again. `x.number` was previously modified to `20`, so `x.number *= 2` logs `40`. +De vierde keer geven we weer het `value` object mee. `x.number` was al aangepast naar `20`, en `x.number *= 2` logt `40`.

From 996ce973678b97aa6ff1a2c8df6d38b636d2a259 Mon Sep 17 00:00:00 2001 From: Tarabass Date: Sun, 19 Jan 2020 14:20:08 +0100 Subject: [PATCH 488/915] Question 65 --- nl-NL/README.md | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-) diff --git a/nl-NL/README.md b/nl-NL/README.md index c3e849c1..7a266422 100644 --- a/nl-NL/README.md +++ b/nl-NL/README.md @@ -2032,17 +2032,18 @@ De vierde keer geven we weer het `value` object mee. `x.number` was al aangepast #### Antwoord: 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. +Het eerste argument van de `reduce` methode is de _accumulator_, in dit geval `x`. Het tweede argument is de _huidige waarde_, `y`. Met de `reduce` methode voeren we een functie uit op elk element in de array, wat uiteindelijk zal resulteren in een enkele waarde. -In this example, we are not returning any values, we are simply logging the values of the accumulator en the current value. +In dit voorbeeld geven we geen waarde terug. We loggen enkel the waarden van de accumulator en de huidige waarde. -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. +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. -On the first call, the accumulator (`x`) is `1`, en the current value (`y`) is `2`. We don't return from the callback function, we log the accumulator en current value: `1` en `2` get logged. +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. -If you don't return a value from a function, it returns `undefined`. On the next call, the accumulator is `undefined`, en the current value is `3`. `undefined` en `3` get logged. +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. -On the fourth call, we again don't return from the callback function. The accumulator is again `undefined`, en the current value is `4`. `undefined` en `4` get logged.

From ab0986575b9183bc4e4cfb39ed0648cabad0e363 Mon Sep 17 00:00:00 2001 From: Tarabass Date: Sun, 19 Jan 2020 14:39:37 +0100 Subject: [PATCH 489/915] Question 66 --- nl-NL/README.md | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/nl-NL/README.md b/nl-NL/README.md index 7a266422..f834b6df 100644 --- a/nl-NL/README.md +++ b/nl-NL/README.md @@ -2092,11 +2092,12 @@ class Labrador extends Dog { #### Antwoord: 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 en 4 would throw a reference error. +In de afgeleide class kun je het `this` keyword niet benaderen totdat je `super` hebt aangeroepen. Als je toch probeert zal dit een _ReferenceError_ gegooid worden: 1 en 4 zouden een reference error gooien. -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`. +Met het `super` keyword roepen we de parent class zijn contructor aan met het meegegeven argument. De parent class' contructor verwacht het argument `name`, dus we moeten `name` meegeven aan `super`. + +De `Labrador` class verwacht twee argumenten, `name` omdat het een afgeleide is van `Dog`, en `size` als een propertie van de `Labrador` class zelf. Ze zullen allebei meegegeven moeten worden aan de contructor van `Labrador`, wat op de juiste manier gebeurt bij constructor 2. -The `Labrador` class receives two arguments, `name` since it extends `Dog`, en `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.

From b958ac50bc27d0d5c9ed95f0a0bbfb6423f87be2 Mon Sep 17 00:00:00 2001 From: Tarabass Date: Sun, 19 Jan 2020 14:50:12 +0100 Subject: [PATCH 490/915] Question 67 --- nl-NL/README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/nl-NL/README.md b/nl-NL/README.md index f834b6df..c0650ebb 100644 --- a/nl-NL/README.md +++ b/nl-NL/README.md @@ -2126,9 +2126,9 @@ export const sum = (a, b) => a + b; #### Antwoord: 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_. +Met het `import` keyword worden alle geïmporteerde modules _pre-parsed_. Dat betekent dat de geïmporteerde modules _als eerste_ uitgevoerd zal worden en de code waarin de module geïmporteerde wordt _als tweede_. -This is a difference between `require()` in CommonJS en `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. +Dit is een verschil tussen `require()` in CommonJS en `import`! Met `require()` kun je dependencies inladen tijdens dat de code uitgevoerd wordt. Als we `require` gebruikt hadden in plaats van `import` zou er `running index.js`, `running sum.js`, `3` gelogt worden in het console.

From de1b7f144eb93f8c866093ed4ab4977761a66c26 Mon Sep 17 00:00:00 2001 From: Tarabass Date: Sun, 19 Jan 2020 14:55:20 +0100 Subject: [PATCH 491/915] Question 668 --- nl-NL/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/nl-NL/README.md b/nl-NL/README.md index c0650ebb..66b7f279 100644 --- a/nl-NL/README.md +++ b/nl-NL/README.md @@ -2153,7 +2153,7 @@ console.log(Symbol('foo') === Symbol('foo')) #### Antwoord: 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')`, en the second `Symbol('foo')`. These two values are unique en not equal to each other, `Symbol('foo') === Symbol('foo')` returns `false`. +Elk Symbol is volledig uniek. Het doel van het argument dat meegegeven wordt aan de Symbol is om de Symbol een omschrijving te geven. De waarde van de Symbol is niet afhankelijk van het doorgegeven argument. Als we de waarden vergelijken creëeren we compleet nieuwe Symbols: de eerste `Symbol('foo')` en de tweede `Symbol('foo')`. Deze twee waarden zijn uniek en niet gelijk aan elkaar, `Symbol('foo') === Symbol('foo')` geeft `false` terug.

From 6fcea3a34949e89eca8345757949288bd5e450a5 Mon Sep 17 00:00:00 2001 From: Tarabass Date: Sun, 19 Jan 2020 15:00:04 +0100 Subject: [PATCH 492/915] Question 69 --- nl-NL/README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/nl-NL/README.md b/nl-NL/README.md index 66b7f279..d66cae8c 100644 --- a/nl-NL/README.md +++ b/nl-NL/README.md @@ -2178,9 +2178,9 @@ console.log(name.padStart(2)) #### Antwoord: 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. +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. -If the argument passed to the `padStart` method is smaller than the length of the array, no padding will be added. +Als het argument dat we meegeven aan de `padStart` methode kleiner is dan de lengte van de string zullen er geen spaties worden toegevoegd.

From 2418528155d8710b93d8c6da1a15b5f150f7bd41 Mon Sep 17 00:00:00 2001 From: Tarabass Date: Sun, 19 Jan 2020 15:01:27 +0100 Subject: [PATCH 493/915] Question 70 --- nl-NL/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/nl-NL/README.md b/nl-NL/README.md index d66cae8c..102026c4 100644 --- a/nl-NL/README.md +++ b/nl-NL/README.md @@ -2203,7 +2203,7 @@ console.log("🥑" + "💻"); #### Antwoord: A -With the `+` operator, you can concatenate strings. In this case, we are concatenating the string `"🥑"` with the string `"💻"`, resulting in `"🥑💻"`. +Met de `+` operator kun je strings concateneren. In dit geval concateneren we de string `"🥑"` met de string `"💻"`, wat `"🥑💻"` oplevert.

From 386b1c9e1805aa335f72cc05ca1d80b8da9a2fb9 Mon Sep 17 00:00:00 2001 From: Emanoel Lucas Date: Sun, 19 Jan 2020 20:10:47 -0300 Subject: [PATCH 494/915] Translation of question 51 to brazilian Portguese --- pt-BR/README_pt_BR.md | 37 +++++++++++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) diff --git a/pt-BR/README_pt_BR.md b/pt-BR/README_pt_BR.md index 4f27be1f..55490e25 100644 --- a/pt-BR/README_pt_BR.md +++ b/pt-BR/README_pt_BR.md @@ -1525,3 +1525,40 @@ Entretanto, não se retorna o valor. Quando não se retorna um valor para a fun --- + +###### 51. Qual é a saída? + +```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"` + +
Resposta +

+ +#### Resposta: A +Argumentos são passados por _valor_, a não ser que seus valores sejam um objeto: nesse caso, são passados por _referência_. `birthYear` é passado por valor, já que é uma string, não um objeto. Quando passamos argumentos por valor, uma _cópia_ desse valor é criada (veja a questão 46). + +A variável `birthYear` tem comporta o valor `"1997"`. O argumento `year` também tem o valor `"1997"`, mas não é o mesmo valor para o qual `birthYear` tem uma aponta. Quando atualizamos o valor de `year` "setando" (configurando) `year` para `"1998"`, estamos atualizando apenas o valor de `year`, isto é, apenas dentro da função. `birthYear` ainda é igual a `"1997"`. + +O valor de `person` é um objeto. O argumento `member` tem uma referência (copiada) para o _mesmo_ objeto. Quando modificamos uma propriedade do objeto `member`, o valor de `person` também será modificando, já que eles têm uma referência (apontam) para o mesmo objeto. Portanto, agora a propriedade `name` é igual ao valor `"Lydia"`. + +

+
+ +--- + From ba580ebcc427a3fc37988fd42de986abbb81bd71 Mon Sep 17 00:00:00 2001 From: Emanoel Lucas Date: Sun, 19 Jan 2020 20:20:10 -0300 Subject: [PATCH 495/915] Translation of question 52 to brazilian Portuguese. --- pt-BR/README_pt_BR.md | 36 ++++++++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) diff --git a/pt-BR/README_pt_BR.md b/pt-BR/README_pt_BR.md index 55490e25..71babf82 100644 --- a/pt-BR/README_pt_BR.md +++ b/pt-BR/README_pt_BR.md @@ -1562,3 +1562,39 @@ O valor de `person` é um objeto. O argumento `member` tem uma referência (copi --- +###### 52. Qual é a saída? + +```javascript +function cumprimento() { + throw "Olá, Mundo!"; +} + +function falaOi() { + try { + const data = cumprimento(); + console.log("Funcionou!", data); + } catch (e) { + console.log("Oh no, um erro: ", e); + } +} + +falaOi(); +``` + +- A: `Funcionou! Olá, Mundo!` +- B: `Oh no, um erro: undefined` +- C: `SyntaxError: can only throw Error objects` +- D: `Oh no, um erro: Olá, Mundo!` + +
Resposta +

+ +#### Resposta: D + +Com a declração `throw`, podemos criar erros customizados. Com essa declaração, você pode lançar exceções. Uma exceção pode ser uma string, a number, a boolean or an object. Nesse caso, nossa exceção é a string `'Olá, Mundo!'`. + +Com a declaração `catch`, podemos especificar o que fazer se uma exceção é lançada no bloco `try`. Uma exceção é lançada: a string `'Olá, Mundo!'`. `e` agora é igual a essa string, a qual mostramos. Isso resulta em `Oh no, um erro: Olá, Mundo!'`. +

+
+ +--- From 8b28defefe7086e093ec9bee232821d8c0e6c6fe Mon Sep 17 00:00:00 2001 From: Emanoel Lucas Date: Sun, 19 Jan 2020 20:26:01 -0300 Subject: [PATCH 496/915] Translation of question 53 to brzilian Portuguese. --- pt-BR/README_pt_BR.md | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) diff --git a/pt-BR/README_pt_BR.md b/pt-BR/README_pt_BR.md index 71babf82..3bea057c 100644 --- a/pt-BR/README_pt_BR.md +++ b/pt-BR/README_pt_BR.md @@ -1598,3 +1598,32 @@ Com a declaração `catch`, podemos especificar o que fazer se uma exceção é --- + + +###### 53. Qual é a saída? + +```javascript +function Carro() { + this.make = "Lamborghini"; + return { make: "Maserati" }; +} + +const meuCarro = new Carro(); +console.log(meuCarro.make); +``` + +- A: `"Lamborghini"` +- B: `"Maserati"` +- C: `ReferenceError` +- D: `TypeError` + +
Resposta +

+ +#### Resposta: B +Quando você retorna uma propriedade, o valor da propriedade é igual ao valor _retornado_, não o valor setado (configurado) no construtor da função. Retornamos a string `"Maserati"`, então `meuCarro.make` é igual a `"Maserati"`. + +

+
+ +--- \ No newline at end of file From 811e65eb5418b97b1bd0b47c898bda23bc631e2e Mon Sep 17 00:00:00 2001 From: Emanoel Lucas Date: Sun, 19 Jan 2020 20:46:25 -0300 Subject: [PATCH 497/915] Translation of question 44 to brazilian Portuguese --- pt-BR/README_pt_BR.md | 43 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 43 insertions(+) diff --git a/pt-BR/README_pt_BR.md b/pt-BR/README_pt_BR.md index 3bea057c..47d87359 100644 --- a/pt-BR/README_pt_BR.md +++ b/pt-BR/README_pt_BR.md @@ -1626,4 +1626,47 @@ Quando você retorna uma propriedade, o valor da propriedade é igual ao valor _

+--- + + + +###### 54. Qual é a saída? + +```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"` + +
Resposta +

+ +#### Reposta: A + +`let x = y = 10;` é, na verdade, uma maneira sucinta de fazer o mesmo que: + +```javascript +y = 10; +let x = y; +``` +Quando setamos `y` para `10`, na verdade adicionamos uma propriedade `y` ao objeto global (`window` no browser, `global` no Node). Em um browser,`window.y` agora é igual a`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 (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"`. + + +Então declaramos uma variável `x` com o valor de `y`, que é `10`. Variáveis declaradas com a palavra-chave`let` têm escopo de bloco, elas estão definidas apenas dentro do bloco no qual estão declaradas; a função imediatamene invocada (do inglês, immediately-invoked), (IIFE), nesse caso. Quando usamos o operador `typeof`, o operador `x` não está definido: estamos tentando acessar `x` fora do bloco no qual ele está declarado. Isso significa que `x` não está definido. Variáveis às quais não se atribui nenhum valor ou não foram declaradas são do tipo `"undefined"`. `console.log(typeof x)` retorna `"undefined"`. + + +No entanto, criamos uma variável global `y` quando seetamos `y` para `10`. Esse valor é acessível em qualquer lugar do nosso código. `y` está definido, e comporta o valor de tipo `"number"`. `console.log(typeof y)` retorna `"number"`. +

+
+ --- \ No newline at end of file From a6432489838f0e93a5fe5eaf5f1934dda7fb9a6e Mon Sep 17 00:00:00 2001 From: Emanoel Lucas Date: Sun, 19 Jan 2020 21:11:48 -0300 Subject: [PATCH 498/915] Question 61 translated --- pt-BR/README_pt_BR.md | 281 ++++++++++++++++++++++++++++++++++++------ 1 file changed, 246 insertions(+), 35 deletions(-) diff --git a/pt-BR/README_pt_BR.md b/pt-BR/README_pt_BR.md index 47d87359..c6a9ddd6 100644 --- a/pt-BR/README_pt_BR.md +++ b/pt-BR/README_pt_BR.md @@ -1533,12 +1533,9 @@ function getInfo(member, year) { member.name = "Lydia"; year = "1998"; } - const person = { name: "Sarah" }; const birthYear = "1997"; - getInfo(person, birthYear); - console.log(person, birthYear); ``` @@ -1551,11 +1548,12 @@ console.log(person, birthYear);

#### Resposta: A -Argumentos são passados por _valor_, a não ser que seus valores sejam um objeto: nesse caso, são passados por _referência_. `birthYear` é passado por valor, já que é uma string, não um objeto. Quando passamos argumentos por valor, uma _cópia_ desse valor é criada (veja a questão 46). -A variável `birthYear` tem comporta o valor `"1997"`. O argumento `year` também tem o valor `"1997"`, mas não é o mesmo valor para o qual `birthYear` tem uma aponta. Quando atualizamos o valor de `year` "setando" (configurando) `year` para `"1998"`, estamos atualizando apenas o valor de `year`, isto é, apenas dentro da função. `birthYear` ainda é igual a `"1997"`. +Os argumentos são passados ​​por _valor_. Porém, se seu valor for um objeto, eles são passados ​​por _referência_. `birthYear` é passado por valor, já que é uma string, não um objeto. Quando passamos argumentos por valor, uma _cópia_ desse valor é criada (consulte a pergunta 46). -O valor de `person` é um objeto. O argumento `member` tem uma referência (copiada) para o _mesmo_ objeto. Quando modificamos uma propriedade do objeto `member`, o valor de `person` também será modificando, já que eles têm uma referência (apontam) para o mesmo objeto. Portanto, agora a propriedade `name` é igual ao valor `"Lydia"`. +A variável `birthYear` tem uma referência ao valor `"1997"`. O argumento `year` também tem uma referência ao valor `"1997"`, mas não é o mesmo valor de referência de `birthYear`. Quando atualizamos o valor de `year`, definindo ` year` igual a `"1998"`, estamos apenas atualizando o valor de `year`. `birthYear` ainda é igual a `"1997"`. + +O valor de `person` é um objeto. O argumento `member` possui uma referência (copiada) do _mesmo_ objeto . Quando modificamos uma propriedade do objeto que `member` tem referência, o valor de `person` também será modificado, pois ambos tem referência ao mesmo objeto. A propriedade `name` de `person` agora é igual ao valor `"Lydia"`.

@@ -1565,51 +1563,48 @@ O valor de `person` é um objeto. O argumento `member` tem uma referência (copi ###### 52. Qual é a saída? ```javascript -function cumprimento() { - throw "Olá, Mundo!"; +function greeting() { + throw "Hello world!"; } - -function falaOi() { +function sayHi() { try { - const data = cumprimento(); - console.log("Funcionou!", data); + const data = greeting(); + console.log("It worked!", data); } catch (e) { - console.log("Oh no, um erro: ", e); + console.log("Oh no an error:", e); } } - -falaOi(); +sayHi(); ``` -- A: `Funcionou! Olá, Mundo!` -- B: `Oh no, um erro: undefined` +- A: `It worked! Hello world!` +- B: `Oh no an error: undefined` - C: `SyntaxError: can only throw Error objects` -- D: `Oh no, um erro: Olá, Mundo!` +- D: `Oh no an error: Hello world!`
Resposta

#### Resposta: D -Com a declração `throw`, podemos criar erros customizados. Com essa declaração, você pode lançar exceções. Uma exceção pode ser uma string, a number, a boolean or an object. Nesse caso, nossa exceção é a string `'Olá, Mundo!'`. +Com a declaração `throw`, podemos criar erros personalizados. Com esta declaração, você pode lançar exceções. Uma exceção pode ser uma string, um número, um booleano ou um objeto. Nesse caso, nossa exceção é a string `'Hello world!'`. + +Com a declaração `catch`, podemos especificar o que fazer se uma exceção for lançada no bloco `try`. Uma exceção foi lançada: a string `'Hello world'`. `e` agora é igual a essa string que registramos. Isso resulta em `'Oh no an error: Hello world!'`. -Com a declaração `catch`, podemos especificar o que fazer se uma exceção é lançada no bloco `try`. Uma exceção é lançada: a string `'Olá, Mundo!'`. `e` agora é igual a essa string, a qual mostramos. Isso resulta em `Oh no, um erro: Olá, Mundo!'`.

--- - ###### 53. Qual é a saída? ```javascript -function Carro() { +function Car() { this.make = "Lamborghini"; return { make: "Maserati" }; } - -const meuCarro = new Carro(); -console.log(meuCarro.make); +const myCar = new Car(); +console.log(myCar.make); ``` - A: `"Lamborghini"` @@ -1621,22 +1616,20 @@ console.log(meuCarro.make);

#### Resposta: B -Quando você retorna uma propriedade, o valor da propriedade é igual ao valor _retornado_, não o valor setado (configurado) no construtor da função. Retornamos a string `"Maserati"`, então `meuCarro.make` é igual a `"Maserati"`. + +Quando você retorna uma propriedade, o valor da propriedade é igual ao valor _retornado_, não ao valor _definido_ na função do construtor. Retornamos a string `"Maserati"`, então `myCar.make` é igual a `"Maserati"`.

--- - - ###### 54. Qual é a saída? ```javascript (() => { let x = (y = 10); })(); - console.log(typeof x); console.log(typeof y); ``` @@ -1649,23 +1642,241 @@ console.log(typeof y);
Resposta

-#### Reposta: A +#### Resposta: A -`let x = y = 10;` é, na verdade, uma maneira sucinta de fazer o mesmo que: +`let x = y = 10;` é na realidade uma abreviação de: ```javascript y = 10; let x = y; ``` -Quando setamos `y` para `10`, na verdade adicionamos uma propriedade `y` ao objeto global (`window` no browser, `global` no Node). Em um browser,`window.y` agora é igual a`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 (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"`. +Quando definimos `y` igual a `10`, adicionamos na verdade uma propriedade `y` ao objeto global (`window` no navegador, `global` no Node). Em um navegador, `window.y` agora é igual a `10`. + +Então, declaramos uma variável `x` com o valor de `y`, que é `10`. As variáveis ​​declaradas com `let` tem _escopo definido no bloco_ ou seja, são definidas apenas dentro do bloco em que são declaradas, neste caso, _immediately-invoked function_ (IIFE). Quando usamos o operador `typeof`, o operando `x` não está definido: estamos tentando acessar `x` fora do bloco em que está declarado. Isso significa que `x` não está definido. Os valores que não foram atribuídos ou declarados a um valor são do tipo `"undefined"`. `console.log(typeof x)` retorna `"undefined"`. + +No entanto, criamos uma variável global `y` ao definir `y` igual a `10`. Este valor está acessível em qualquer lugar do nosso código. `y` é definido e mantém um valor do tipo `"number"`. `console.log(typeof y)` retorna `"number"`. + +

+
+ +--- + +###### 55. Qual é a saída? + +```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` + +
Resposta +

+ +#### Resposta: A + +Podemos excluir propriedades de objetos usando `delete`, também no prototype. Ao excluir uma propriedade no prototype, ela não está mais disponível na cadeia de prototypes. Nesse caso, a função `bark` não está mais disponível no prototype depois de `delete Dog.prototype.bark`, mas ainda tentamos acessá-lo. + +Quando tentamos invocar algo que não é uma função, um `TypeError` é lançado. Neste caso, `TypeError: pet.bark is not a function`, uma vez que `pet.bark` é `undefined`. + +

+
+ +--- + +###### 56. Qual é a saída? + +```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}` + +
Resposta +

+ +#### Resposta: D + +O objeto `Set` é uma coleção de valores _exclusivos_ : um valor pode ocorrer apenas uma vez. + +Passamos o iterável `[1, 1, 2, 3, 4]` com um valor `1` duplicado. Como não podemos ter dois dos mesmos valores em um conjunto, um deles é removido. Isso resulta em `{1, 2, 3, 4}`. + +

+
+ +--- + +###### 57. Qual é a saída? + +```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` + +
Resposta +

+ +#### Resposta: C + +Um módulo importado é _somente leitura_: você não pode modificar o módulo importado. Somente o módulo que os exporta pode alterar seu valor. + +Quando tentamos aumentar o valor de `myCounter`, recebemos um erro: `myCounter` é somente leitura e não pode ser modificado. + +

+
+ +--- + +###### 58. Qual é a saída? + +```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` + +
Resposta +

+ +#### Resposta: A + +O operador `delete` retorna um valor booleano: `true` em uma exclusão bem-sucedida, caso contrário, ele retorna `false`. No entanto, variáveis declaradas com `var`, `const` ou `let` não podem ser excluídas usando o operador `delete`. + +A variável `name` foi declarada com `const`, portanto sua exclusão não é bem-sucedida: `false` é retornado. Quando definimos `age` igual a `21`, na verdade adicionamos uma propriedade chamada `age` para o objeto global. Dessa forma, você pode excluir propriedades dos objetos, portanto `delete age` returns `true`. + +

+
+ +--- + +###### 59. Qual é a saída? + +```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]` + +
Resposta +

+ +#### Resposta: C + +Podemos descompactar valores de matrizes ou propriedades de objetos através da desestruturação. Por exemplo: + +```javascript +[a, b] = [1, 2]; +``` + + +O valor de `a` agora é `1` e o valor de `b` agora é `2`. O que realmente fizemos na pergunta é: -Então declaramos uma variável `x` com o valor de `y`, que é `10`. Variáveis declaradas com a palavra-chave`let` têm escopo de bloco, elas estão definidas apenas dentro do bloco no qual estão declaradas; a função imediatamene invocada (do inglês, immediately-invoked), (IIFE), nesse caso. Quando usamos o operador `typeof`, o operador `x` não está definido: estamos tentando acessar `x` fora do bloco no qual ele está declarado. Isso significa que `x` não está definido. Variáveis às quais não se atribui nenhum valor ou não foram declaradas são do tipo `"undefined"`. `console.log(typeof x)` retorna `"undefined"`. +```javascript +[y] = [1, 2, 3, 4, 5]; +``` + + + +Isso significa que o valor de `y` é igual ao primeiro valor no array, que é o número `1`. Quando registramos no console `y`, `1` é retornado. + +

+
+ +--- + +###### 60. Qual é a saída? + +```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 }` + +
Resposta +

+ +#### Resposta: B -No entanto, criamos uma variável global `y` quando seetamos `y` para `10`. Esse valor é acessível em qualquer lugar do nosso código. `y` está definido, e comporta o valor de tipo `"number"`. `console.log(typeof y)` retorna `"number"`. +É 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 }`. + +

+
+ +--- + +###### 61. Qual é saída? + +```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"]` + +
Resposta +

+ +#### 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 sobrescrever 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.

From bc1a4bb9cb4e989de3294c32f39b70f4dbe24463 Mon Sep 17 00:00:00 2001 From: Emanoel Lucas Date: Sun, 19 Jan 2020 21:20:03 -0300 Subject: [PATCH 499/915] Question 62 --- pt-BR/README_pt_BR.md | 35 ++++++++++++++++++++++++++++++++++- 1 file changed, 34 insertions(+), 1 deletion(-) diff --git a/pt-BR/README_pt_BR.md b/pt-BR/README_pt_BR.md index c6a9ddd6..5b723efb 100644 --- a/pt-BR/README_pt_BR.md +++ b/pt-BR/README_pt_BR.md @@ -1875,9 +1875,42 @@ 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 sobrescrever 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.

+--- + +###### 62. Qual é a saída? + +```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}"` + +
Resposta +

+ +#### Answer: A + +O segundo argumento de `JSON.stringify` é o _substituo_. O substituto pode ser uma função ou um array, e deixa você controlar o que deve ser "stringfied", isto é, ser usado pelo método `JSON.stringfy`. + +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. +

+
+ --- \ No newline at end of file From 9fd7c0ab7f25ed67ff1036a972094065165261e7 Mon Sep 17 00:00:00 2001 From: Askie Lin Date: Wed, 22 Jan 2020 23:47:46 +0800 Subject: [PATCH 500/915] [Feat] Add questions 26-30 of zh-TW translation --- zh-TW/README_zh-TW.md | 161 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 161 insertions(+) diff --git a/zh-TW/README_zh-TW.md b/zh-TW/README_zh-TW.md index baa9920d..2c9f600c 100644 --- a/zh-TW/README_zh-TW.md +++ b/zh-TW/README_zh-TW.md @@ -763,3 +763,164 @@ console.log(obj); --- + +###### 26. JavaScript 在全域執行環境為你做了兩件事:全域物件和 this 關鍵字。 + +- A: true +- B: false +- C: it depends + +
答案 +

+ +#### 答案: A + +基本执行上下文是全局执行上下文:它是代码中随处可访问的内容。 +基底的執行環境是全域的:代表它在程式碼中,可被隨處使用。 + +

+
+ +--- + +###### 27. 將會輸出什麽內容? + +```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` + +
答案 +

+ +#### 答案: C + +當 `if` 條件成立時會回傳 `true`,執行 `continue` 語句,代表忽略本次迭代(`console.log(i)`)。 + +

+
+ +--- + +###### 28. 將會輸出什麽內容? + +```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` + +
答案 +

+ +#### 答案: A + +`String` 是內建的建構函式,我們可以向它新增属性。我只是在它的原型中加上一個方法。基本型別字串被自動轉換成字串物件,由字串原型函式生成。因此,所有 string(string 物件)都可以使用 `giveLydiaPizza` 方法! + +

+
+ +--- + +###### 29. 將會輸出什麽內容? + +```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` + +
答案 +

+ +#### 答案: B + +物件的 key 自動轉為字串型別。我們正嘗試將物件 `b` 的 key 設為物件 `a` 的 key,其值爲 `123`。 + +然而,當物件「字串化」,它會變成 `"[object Object]"`。所以這裡的意思是,`a["[object Object]"] = 123`。然後,我們又再做了一次一樣的事情,`c` 也是隱式的物件字串化,所以,`a["[object Object]"] = 456`。 + +最後,我們輸出 `a[b]`,也就是 `a["[object Object]"]`。之前剛賦值爲 `456`,將回傳 `456`。 + +

+
+ +--- + +###### 30. 將會輸出什麽內容? + +```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` + +
答案 +

+ +#### 答案: B + +我們有一個 `setTimeout` 函式,首先呼叫它。然而,它的執行順序是最後執行的。 + +因為在瀏覽器中,我們除了有執行引擎,還有一個 `WebAPI`。`WebAPI` 提供了 `setTimeout` 函式,也包含其他的,例如 DOM。 + +在『callback』推送到 `WebAPI` 後,`setTimeout` 函式本身(不是回呼函式)將從堆疊(`stack`)中彈出。 + + + +現在,`foo` 被呼叫,印出 `"First"`。 + + + +`foo` 從堆疊中彈出,`baz` 被呼叫,印出 `"Third"`。 + + + +WebAPI 不能隨時向堆疊内新增内容。相反,它會將回呼函式彈到名爲『`queue`』的地方。 + + + +這就是事件迴圈(`Event Loop`)的流程,了解**事件迴圈**堆疊與任務佇列的運作模式。如果堆疊是空的,它接受任務佇列上的第一个元素,推入堆疊中。 + + + +`bar` 被呼叫,印出 `"Second"`,然後它被彈出堆疊。 + +

+
+ +--- From 2de8f6dfcb831693e8dcccd8a31a5f745b78727b Mon Sep 17 00:00:00 2001 From: Tarabass Date: Sun, 26 Jan 2020 11:21:45 +0100 Subject: [PATCH 501/915] Question 71 --- nl-NL/README.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/nl-NL/README.md b/nl-NL/README.md index 102026c4..9732c133 100644 --- a/nl-NL/README.md +++ b/nl-NL/README.md @@ -2236,11 +2236,11 @@ console.log(/* 2 */); // JavaScript loves you back ❤️ #### Antwoord: 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`. +Een generator functie "pauzeert" tijdens de uitvoering wanneer het het keyword `yield` tegenkomt. Allereerst laten we de functie de string "Do you love JavaScript?" opleveren. Dat kunnen we doen door `game.next().value` te gebruiken. -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!_ +Elke lijn van de functie wordt uitgevoerd totaan het eerste `yield` keyword. Er is een `yield` aanwezig op de eerste lijn van de functie: de uitvoering stopt bij de eerste `yield`! _Dat betekent dat de variabele `answer` nog niet gedefinieerd is!_ -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`, en `JavaScript loves you back ❤️` gets logged. +Wanneer we `game.next("Yes").value` aanroepen wordt de vorige `yield` vervangen met de waarde van de parameters die zijn meegegeven aan de `next()` functie, `"Yes"` in dit geval. De waarde van de variabele `answer` is nu gelijk aan `"Yes"`. De conditie van de if-statement geeft `false` terug en `JavaScript loves you back ❤️` wordt gelogd.

From 38c85d5ed3c95b5745193e28e947add40965a0f9 Mon Sep 17 00:00:00 2001 From: Tarabass Date: Sun, 26 Jan 2020 11:31:10 +0100 Subject: [PATCH 502/915] Question 72 --- nl-NL/README.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/nl-NL/README.md b/nl-NL/README.md index 9732c133..a0681c87 100644 --- a/nl-NL/README.md +++ b/nl-NL/README.md @@ -2263,19 +2263,19 @@ console.log(String.raw`Hello\nworld`); #### Antwoord: 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: +`String.raw` geeft een string terug waarbij de escapes (`\n`, `\v`, `\t` etc.) genegeerd worden! Backslashes kunnen een probleem zijn omdat je kunt eindigen met zoiets als: `` const path = `C:\Documents\Projects\table.html` `` -Which would result in: +Wat resulteert in: `"C:DocumentsProjects able.html"` -With `String.raw`, it would simply ignore the escape en print: +Met `String.raw` worden de escapes simpelweg genegeerd: `C:\Documents\Projects\table.html` -In this case, the string is `Hello\nworld`, which gets logged. +In dit geval wordt `Hello\nworld` gelogd.

From 3cd647f415ecaca60ef87d54f607262340145b0d Mon Sep 17 00:00:00 2001 From: Tarabass Date: Sun, 26 Jan 2020 11:37:10 +0100 Subject: [PATCH 503/915] Question 73 --- nl-NL/README.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/nl-NL/README.md b/nl-NL/README.md index a0681c87..6340ecd2 100644 --- a/nl-NL/README.md +++ b/nl-NL/README.md @@ -2303,13 +2303,13 @@ console.log(data); #### Antwoord: 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. +Een asynchrone functie geeft altijd een promise terug. De `await` moet nog steeds wachten op de oplossing van de promise: een wachtende promise wordt teruggegeven wanneer we `getData()` aanroepen om daarmee `data` te vullen. -If we wanted to get access to the resolved value `"I made it"`, we could have used the `.then()` method on `data`: +Als we de teruggegeven waarde van de promise `"I made it"` willen benaderen zouden we de `then()` method kunnen gebruiken op `data`: `data.then(res => console.log(res))` -This would've logged `"I made it!"` +Dit zou wel `"I made it!"` loggen.

From 52e9acff099162fe583ecd8d12c3560a2e816157 Mon Sep 17 00:00:00 2001 From: Tarabass Date: Sun, 26 Jan 2020 11:48:03 +0100 Subject: [PATCH 504/915] Question 74 --- nl-NL/README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/nl-NL/README.md b/nl-NL/README.md index 6340ecd2..61180462 100644 --- a/nl-NL/README.md +++ b/nl-NL/README.md @@ -2337,9 +2337,9 @@ console.log(result); #### Antwoord: B -The `.push()` method returns the _length_ of the new array! Previously, the array contained one element (the string `"banana"`) en had a length of `1`. After adding the string `"apple"` to the array, the array contains two elements, en has a length of `2`. This gets returned from the `addToList` function. +De `push()` methode geeft de _Lengte_ terug van de nieuwe array! In eerste instantie bevatte de array één element (de string `"banana"`) en had een lengte van `1`. Nadat de string `"apple"` toegevoegd wordt aan de array bevat de array twee elementen en heeft een lengte van `2`. Dit wordt dan ook teruggegeven door de `addToList` functie. -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. +De `push()` methode past de originele array aan. Als je de _array_ zelf terug zou willen geven in plaats van de _lengte van de array_ zou je de `list` moeten teruggeven nadat de `item` toegevoegd is.

From e54b8a9df2a2f265a104e439390b4b523fc34328 Mon Sep 17 00:00:00 2001 From: Tarabass Date: Sun, 26 Jan 2020 11:53:50 +0100 Subject: [PATCH 505/915] Question 75 --- nl-NL/README.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/nl-NL/README.md b/nl-NL/README.md index 61180462..c680bd7d 100644 --- a/nl-NL/README.md +++ b/nl-NL/README.md @@ -2369,11 +2369,11 @@ console.log(shape); #### Antwoord: B -`Object.freeze` makes it impossible to add, remove, or modify properties of an object (unless the property's value is another object). +`Object.freeze` maakt het onmogelijk om properties van een object toe te voegen, te verwijderen of aan te passen (tenzij de waarde van de propertie zelf een object is). -When we create the variable `shape` en 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. +Wanneer we de variabele `shape` aanmaken en hieraan het bevroren object `box` toewijzen zal de referentie naar het bevroren object blijven bestaan. Je kunt checken of een object bevroren is door `Object.isFrozen` te gebruiken. In dit geval geeft `Object.isFrozen(shape)` true terug omdat de referentie naar het bevroren object `box` is blijven bestaan. -Since `shape` is frozen, en since the value of `x` is not an object, we cannot modify the property `x`. `x` is still equal to `10`, en `{ x: 10, y: 20 }` gets logged. +Omdat `shape` bevroren is en omdat de waarde van `x` geen object is kunnen we de propertie `x` niet aanpassen. `x` is nog steeds gelijk aan `10` en `{ x: 10, y: 20 }` wordt gelogd.

From 857e586a525d5c26844d452d3a59307226ef812a Mon Sep 17 00:00:00 2001 From: Tarabass Date: Sun, 26 Jan 2020 11:57:48 +0100 Subject: [PATCH 506/915] Question 76 --- nl-NL/README.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/nl-NL/README.md b/nl-NL/README.md index c680bd7d..c957124d 100644 --- a/nl-NL/README.md +++ b/nl-NL/README.md @@ -2398,11 +2398,11 @@ console.log(name); #### Antwoord: 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`. +Wanneer we de propertie `name` opvragen van het object aan de rechterkant wijzen we de waarde `"Lydia"` toe aan de variabele met de naam `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. +Met `{ name: myName }` zeggen we in JavaScript dat we een nieuwe variabele aan willen maken met de naam `myName` met de waarde van de `name` propertie van het object aan de rechterkant. -Since we try to log `name`, a variable that is not defined, a ReferenceError gets thrown. +Omdat we proberen `name` te loggen, een variabele die niet gedefinieerd is, wordt er een ReferenceError gegooid.

From 4d188b6ffa355f67fbeb8a79f4d85f27ac818248 Mon Sep 17 00:00:00 2001 From: Tarabass Date: Sun, 26 Jan 2020 12:00:46 +0100 Subject: [PATCH 507/915] Question 77 --- nl-NL/README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/nl-NL/README.md b/nl-NL/README.md index c957124d..790903c3 100644 --- a/nl-NL/README.md +++ b/nl-NL/README.md @@ -2425,9 +2425,9 @@ function sum(a, b) { #### Antwoord: A -A pure function is a function that _always_ returns the same result, if the same arguments are passed. +Een `pure function` is een functie die _altijd_ dezelfde waarde teruggeeft, zolang hetzelfde argument wordt meegegeven. -The `sum` function always returns the same result. If we pass `1` en `2`, it will _always_ return `3` without side effects. If we pass `5` en `10`, it will _always_ return `15`, en so on. This is the definition of a pure function. +De `sum` functie geeft altijd dezelfde waarde terug. Als we `1` en `2` meegeven zal het _altijd_ `3` teruggeven. Als we de waarde `5` en `10` meegeven zal het _altijd_ `15` teruggeven. Dit is de definitie van een `pure function`.

From cd7f11d6849ac97bd2259d19986d002c91bfd16b Mon Sep 17 00:00:00 2001 From: Tarabass Date: Sun, 26 Jan 2020 12:18:36 +0100 Subject: [PATCH 508/915] Question 78 --- nl-NL/README.md | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/nl-NL/README.md b/nl-NL/README.md index 790903c3..9acf703c 100644 --- a/nl-NL/README.md +++ b/nl-NL/README.md @@ -2466,15 +2466,15 @@ console.log(addFunction(5 * 2)); #### Antwoord: 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. +De `add` functie is een _memoized_ functie. Met memoization kunnen we het resultaat van een functie cachen om de uitvoering ervan te versnellen. In dit geval maken we een `cache` object aan waarin we de waarde van dat de vorige keer werd teruggegeven opslaan. -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 en store it afterwards. +Als we de functie `addFunction` aanroepen met hetzelfde argument wordt eerst gecheckt of de waarde al in de cache voorkomt. Als dat het geval is wordt de opgeslagen waarde teruggegeven, waardoor de functie niet helemaal hoeft te worden uitgevoerd. Anders, als de waarde nog niet is opgeslagen in de cache, zal het de waarde berekenen en daarna opslaan in de cache. -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`, en the else block gets executed: `Calculated! 20` gets logged, en the value of the result gets added to the cache object. `cache` now looks like `{ 10: 20 }`. +We roepen de functie `addFunction` drie keer aan met dezelfde waarde: Tijdens de eerste aanroep is de waarde van de functie `num` wanneer het gelijk is aan `10` nog niet opgslagen in de cache. De conditie van de if-statement `num in cache` geeft `false` terug waardoor we in de else-statement komen: `Calculated! 20` wordt gelogd en de waarde van het resultaat wordt opgeslagen in het cache object. `cache` ziet er nu uit als `{ 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`, en `'From cache! 20'` gets logged. +De tweede keer bevat het object `cache` de waarde dat teruggegeven wordt wanneer `10` wordt meegegeven. De conditie van de if-statement `num in cache` geeft `true` terug en `'From cache! 20'` wordt gelogd. -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`, en `'From cache! 20'` gets logged. +De derde keer geven we `5 * 2` mee aan de functie wat `10` oplevert. Het `cache` object bevat de waarde dat teruggegeven gaat worden voor `10`. De conditie van de if-statement `num in cache` geeft `true` terug en `'From cache! 20'` wordt gelogd.

From 2f13529abbc24048702fc42b13a0f963a44d52c1 Mon Sep 17 00:00:00 2001 From: Tarabass Date: Sun, 26 Jan 2020 12:22:41 +0100 Subject: [PATCH 509/915] Question 79 --- nl-NL/README.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/nl-NL/README.md b/nl-NL/README.md index 9acf703c..8869d654 100644 --- a/nl-NL/README.md +++ b/nl-NL/README.md @@ -2505,13 +2505,13 @@ for (let item of myLifeSummedUp) { #### Antwoord: 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: +Met de _for-in_ loop kunnen we itereren over de **enumerable** properties. In een array zijn de "keys" van de array elementen enumarable, wat eigenlijk hun indexen zijn. Je kunt een array zien als: `{0: "☕", 1: "💻", 2: "🍷", 3: "🍫"}` -Where the keys are the enumerable properties. `0` `1` `2` `3` get logged. +Waar de keys de enumarable properties zijn. `0` `1` `2` `3` worden gelogd. -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. +Met de _for-of_ loop kunnen we itereren over **iterables**. Een array is een iterable. Wanneer we itereren over een array is de waarde van de variabele "item" gelijk aan het huidige element, `"☕"` ` "💻"` `"🍷"` `"🍫"` wordt gelogd.

From 76d4c47981810740517a55339124940f3472d964 Mon Sep 17 00:00:00 2001 From: Tarabass Date: Mon, 3 Feb 2020 20:46:13 +0100 Subject: [PATCH 510/915] Question 80 --- nl-NL/README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/nl-NL/README.md b/nl-NL/README.md index 8869d654..344d7534 100644 --- a/nl-NL/README.md +++ b/nl-NL/README.md @@ -2535,9 +2535,9 @@ console.log(list) #### Antwoord: C -Array elements can hold any value. Numbers, strings, objects, other arrays, null, boolean values, undefined, en other expressions such as dates, functions, en calculations. +Array elementen kunnen elke waarde bevatten. Nummers, strings, objecten, andere arrays, null, boolean waarden, undefined en andere expressies zoals datums, functies en berekeningen. -The element will be equal to the returned value. `1 + 2` returns `3`, `1 * 2` returns `2`, en `1 / 2` returns `0.5`. +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.

From 2172f0773b7ce79a4d6fe7b66d2be37dc1394973 Mon Sep 17 00:00:00 2001 From: Tarabass Date: Mon, 3 Feb 2020 20:55:41 +0100 Subject: [PATCH 511/915] Question 81 --- nl-NL/README.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/nl-NL/README.md b/nl-NL/README.md index 344d7534..265320a0 100644 --- a/nl-NL/README.md +++ b/nl-NL/README.md @@ -2564,13 +2564,13 @@ console.log(sayHi()) #### Antwoord: 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. +Argumenten hebben standaard de waarde `undefined`, tenzij de waarde wordt meegegeven aan de functie. In dit geval hebben we geen waarde meegegeven voor het argument `name`. `name` is gelijk aan `undefined` wat gelogd wordt. -In ES6, we can overwrite this default `undefined` value with default parameters. For example: +In ES6 kunnen we argumenten een standaard waarde geven. Als voorbeeld: `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` +In dit geval zal de waarde van het argument `name`, als we geen waarde meegeven aan de functie, standaard `Lydia` bevatten.

From c5c7f1f4dd7518049c04f93953c1ab58cb291ffc Mon Sep 17 00:00:00 2001 From: Tarabass Date: Mon, 3 Feb 2020 21:11:08 +0100 Subject: [PATCH 512/915] Question 82 --- nl-NL/README.md | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/nl-NL/README.md b/nl-NL/README.md index 265320a0..52cd9d64 100644 --- a/nl-NL/README.md +++ b/nl-NL/README.md @@ -2607,10 +2607,9 @@ setTimeout(() => { #### Antwoord: 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. +De waarde van het keyword `this` hangt af van in welke scope je het gebruikt. In een **methode**, zoals de `getStatus` methode, het `this` keyword verwijst naar _het object waartoe de methode behoort_. De methode behoort toe aan het `data` object, dus `this` verwijst naar het `data` object. Wanneer we `this.status` loggen wordt de `status` propertie van het `data` object gelogd, wat `"🥑"` is. +Met de `call` methode kunnen we het object veranderen waarnaar het keyword `this` verwijst. In **functies** refereert het keyword `this` naar _het object waartoe de function behoort_. We declareren de `setTimeout` functie op het _globale object_, dus binnen de `setTimeout` functie refereert het keyword `this` naar het _globale object_. Op het globale object bestaat de variabele genaamd _status_ met de waarde `"😎"`. Wanneer we `this.status` loggen wordt `"😎"` gelogd.

From cc0708cd1cc25ca631a39135c1a74cc2820e349e Mon Sep 17 00:00:00 2001 From: Tarabass Date: Mon, 3 Feb 2020 21:19:58 +0100 Subject: [PATCH 513/915] Question 83 --- nl-NL/README.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/nl-NL/README.md b/nl-NL/README.md index 52cd9d64..32ec792a 100644 --- a/nl-NL/README.md +++ b/nl-NL/README.md @@ -2640,13 +2640,13 @@ console.log(person) #### Antwoord: 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 vullen de variabele `city` met de waarde van de propertie `city` op het object `person`. Er is echter geen propertie `city` op dit object, dus de variabele `city` krijgt de waarde `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. +Let op dat we _niet_ refereren naar het object `person` zelf! We vullen de waarde van de variabele `city` enkel met de waarde van de propertie `city` op het `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. +Daarna zetten we de waarde van `city` gelijk aan de string `"Amsterdam"`. Dit verandert niets aan het object `person`: we hebben geen referentie naar dat object. -When logging the `person` object, the unmodified object gets returned. +Wanneer we het object `person` loggen, wordt het onaangepaste object gelogd.

From d5092fe5715e04b3e98db639b4309700031bb369 Mon Sep 17 00:00:00 2001 From: Tarabass Date: Mon, 3 Feb 2020 21:32:34 +0100 Subject: [PATCH 514/915] Question 84 --- nl-NL/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/nl-NL/README.md b/nl-NL/README.md index 32ec792a..7d8ee1b8 100644 --- a/nl-NL/README.md +++ b/nl-NL/README.md @@ -2679,7 +2679,7 @@ console.log(checkAge(21)) #### Antwoord: C -Variables with the `const` en `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. +Variabelen gedeclareerd met de keywords `const` en `let` zijn _block-scoped_. Een block is alles tussen accolades (`{ }`). In dit geval de accolades van de if/else statements. Je kunt niet refereren naar een variabele buiten het block waarin het gedeclareerd is. Een ReferenceError wordt gegooid.

From fee30f63d189833dfd4e0aa8865a17a349db1c1c Mon Sep 17 00:00:00 2001 From: Tarabass Date: Mon, 3 Feb 2020 21:38:03 +0100 Subject: [PATCH 515/915] Question 85 --- nl-NL/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/nl-NL/README.md b/nl-NL/README.md index 7d8ee1b8..7823161f 100644 --- a/nl-NL/README.md +++ b/nl-NL/README.md @@ -2704,7 +2704,7 @@ fetch('https://www.website.com/api/user/1') #### Antwoord: 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. +De waarde van `res` in de tweede `.then` is gelijk aan de geretourneerde waarde in de vorige `.then`. Je kunt `.then`s zoals dit blijven `chainen`, waarbij de waarde wordt meegegeven aan de volgende `handler`.

From 4adaf11a8608e37d360e59dae4f199eebfb5b80a Mon Sep 17 00:00:00 2001 From: Tarabass Date: Mon, 3 Feb 2020 21:47:00 +0100 Subject: [PATCH 516/915] Question 86 --- nl-NL/README.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/nl-NL/README.md b/nl-NL/README.md index 7823161f..0d3d3857 100644 --- a/nl-NL/README.md +++ b/nl-NL/README.md @@ -2729,13 +2729,13 @@ function getName(name) { #### Antwoord: 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`. +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. -By setting `hasName` equal to `name`, you set `hasName` equal to whatever value you passed to the `getName` function, not the boolean value `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)` returns an object wrapper, not the boolean value itself. +`new Boolean(true)` geeft een object wrapper terug, niet de boolean waarde zelf. -`name.length` returns the length of the passed argument, not whether it's `true`. +`name.length` geeft de lengte terug van de meegegeven waarde, niet of het `true` is.

From 270ee03261c5dbeb9e3d25f1330acc3cc5aa83c1 Mon Sep 17 00:00:00 2001 From: Tarabass Date: Mon, 3 Feb 2020 21:52:13 +0100 Subject: [PATCH 517/915] Question 87 --- nl-NL/README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/nl-NL/README.md b/nl-NL/README.md index 0d3d3857..fb44484b 100644 --- a/nl-NL/README.md +++ b/nl-NL/README.md @@ -2758,9 +2758,9 @@ console.log("I want pizza"[0]) #### Antwoord: 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, en so on. In this case we want to get the element which index is 0, the character `"I'`, which gets logged. +Om een karakter van een string op een specifieke index te krijgen kun je blokhaken gebruiken. Het eerste karakter in de string heeft de index 0. In dit geval willen we het element hebben met de index 0, het karakter `"I"`, wat gelogd wordt. -Note that this method is not supported in IE7 en below. In that case, use `.charAt()` +Let op dat deze methode niet ondersteund wordt in IE7 en daaronder. In dat geval maak je gebruik van `.charAt()`.

From a2b159d7fbf8b0cc893fb70b0b1e3eed8550fb43 Mon Sep 17 00:00:00 2001 From: Tarabass Date: Mon, 3 Feb 2020 21:59:57 +0100 Subject: [PATCH 518/915] Question 88 --- nl-NL/README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/nl-NL/README.md b/nl-NL/README.md index fb44484b..40fae83b 100644 --- a/nl-NL/README.md +++ b/nl-NL/README.md @@ -2787,9 +2787,9 @@ sum(10) #### Antwoord: 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, en 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`. +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. -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. +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.

From e708444464b7c152b7b3f8ca434373bc09eb1878 Mon Sep 17 00:00:00 2001 From: Tarabass Date: Mon, 3 Feb 2020 22:07:44 +0100 Subject: [PATCH 519/915] Question 89 --- nl-NL/README.md | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/nl-NL/README.md b/nl-NL/README.md index 40fae83b..249662fd 100644 --- a/nl-NL/README.md +++ b/nl-NL/README.md @@ -2818,10 +2818,9 @@ 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. -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, en a named export. The default export is a function which returns the string `"Hello World"`, en 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 en their corresponding values. +Het object `data` bevat een propertie `default` voor de standaard export. Andere properties hebben de naam van de benoemde exports en hun corresponderende waarden.

From 20bb758282f290f6ffe0cddb91d6255960fc7c2f Mon Sep 17 00:00:00 2001 From: Tarabass Date: Mon, 3 Feb 2020 22:13:00 +0100 Subject: [PATCH 520/915] Question 90 --- nl-NL/README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/nl-NL/README.md b/nl-NL/README.md index 249662fd..6aebb58c 100644 --- a/nl-NL/README.md +++ b/nl-NL/README.md @@ -2850,7 +2850,7 @@ console.log(typeof member) #### Antwoord: C -Classes are syntactical sugar for function constructors. The equivalent of the `Person` class as a function constructor would be: +Classes zijn een syntactisch sausje voor functie constructors. Het equivalent van de class `Person` als een functie constructor zou zijn: ```javascript function Person() { @@ -2858,7 +2858,7 @@ function Person() { } ``` -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"`. +Het aanroepen van de functie contructor met `new` resulteert in het creëeren van een instantie van `Person`. Het keyword `typeof` geeft voor een instantie `"object"` terug. `typeof member` geeft `"object"` terug.

From c5c99692d4803e3624087b306cb1004a8ea31460 Mon Sep 17 00:00:00 2001 From: Luan AP Date: Tue, 4 Feb 2020 15:10:28 -0300 Subject: [PATCH 521/915] Adjusted grammar problem --- 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 5b723efb..5640d727 100644 --- a/pt-BR/README_pt_BR.md +++ b/pt-BR/README_pt_BR.md @@ -780,7 +780,7 @@ Se temos duas chaves com o mesmo nome, a última irá substituir a primeira. Ain --- -###### 26. O contexto global de execução do JavaScrit cria duas coisas para você: O objeto global, e a palavra-chave `this`. +###### 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 @@ -1913,4 +1913,4 @@ Se o substituto (replacer) for uma _função_, essa função é chamada em c ada

---- \ No newline at end of file +--- From 97266815fa95825153713e1183861976a4268199 Mon Sep 17 00:00:00 2001 From: Tarabass Date: Tue, 4 Feb 2020 21:11:09 +0100 Subject: [PATCH 522/915] Question 91 --- nl-NL/README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/nl-NL/README.md b/nl-NL/README.md index 6aebb58c..b8d88073 100644 --- a/nl-NL/README.md +++ b/nl-NL/README.md @@ -2883,9 +2883,9 @@ console.log(newList.push(5)) #### Antwoord: 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`. +De `.push` methode retourneert de _nieuwe lengte_ van de array, niet de array zelf! Door `newList` te vullen met `[1, 2, 3].push(4)`, zetten we `newList` gelijk aan de nieuwe lengte van de 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. +Dan gebruiken we de `.push` methode op `newList`. Omdat `newList` nu de numerieke waarde `4` bevat, kunnen we de `.push` methode niet gebruiker: een TypeError wordt gegooid.

From bdcf9930a1d93be1e66a995271b46aacf0c3219a Mon Sep 17 00:00:00 2001 From: Tarabass Date: Tue, 4 Feb 2020 21:15:44 +0100 Subject: [PATCH 523/915] Question 92 --- nl-NL/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/nl-NL/README.md b/nl-NL/README.md index b8d88073..64929ef8 100644 --- a/nl-NL/README.md +++ b/nl-NL/README.md @@ -2915,7 +2915,7 @@ console.log(giveLydiaChocolate.prototype) #### Antwoord: 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`. +Reguliere functies zoals de `giveLydiaPizza` functie hebben een `prototype` propertie, wat een object is (prototype object) met een `constructor` propertie. Arrow functies zoals de `giveLydiaChocolate` functie hebben geen `prototype` functie. `undefined` wordt geretourneerd wanneer we proberen om de `prototype` propertie te benaderen door gebruik te maken van `giveLydiaChocolate.prototype`.

From 59f2d52a674065212368d57c0a8bb8358f2305fb Mon Sep 17 00:00:00 2001 From: Tarabass Date: Tue, 4 Feb 2020 21:23:13 +0100 Subject: [PATCH 524/915] Question 92 --- nl-NL/README.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/nl-NL/README.md b/nl-NL/README.md index 64929ef8..6084207a 100644 --- a/nl-NL/README.md +++ b/nl-NL/README.md @@ -2945,14 +2945,14 @@ for (const [x, y] of Object.entries(person)) { #### Antwoord: A -`Object.entries(person)` returns an array of nested arrays, containing the keys en objects: +`Object.entries(person)` retourneert een array van geneste arrays, welke de keys en objecten bevat: `[ [ '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. +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. -The first subarray is `[ "name", "Lydia" ]`, with `x` equal to `"name"`, en `y` equal to `"Lydia"`, which get logged. -The second subarray is `[ "age", 21 ]`, with `x` equal to `"age"`, en `y` equal to `21`, which get logged. +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"`.

From abfc0bf85f6db6db4afa7fabebc7122f8a91d506 Mon Sep 17 00:00:00 2001 From: Tarabass Date: Tue, 4 Feb 2020 21:27:14 +0100 Subject: [PATCH 525/915] Question 94 --- nl-NL/README.md | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/nl-NL/README.md b/nl-NL/README.md index 6084207a..8d6d6fec 100644 --- a/nl-NL/README.md +++ b/nl-NL/README.md @@ -2979,7 +2979,7 @@ getItems(["banana", "apple"], "pear", "orange") #### Antwoord: D -`...args` is a rest parameter. The rest parameter's value is an array containing all remaining arguments, **en can only be the last parameter**! In this example, the rest parameter was the second parameter. This is not possible, en will throw a syntax error. +`...args` is een rest parameter. De waarde van een rest parameter is een array die alle overgebleven argumenten bevat, en om die reden **alleen de laatste parameter kan zijn**! In dit voorbeeld is de rest parameter niet de laatste parameter, wat niet mogelijk is. Er wordt een syntax error gegooid. ```javascript function getItems(fruitList, favoriteFruit, ...args) { @@ -2989,7 +2989,8 @@ function getItems(fruitList, favoriteFruit, ...args) { getItems(["banana", "apple"], "pear", "orange") ``` -The above example works. This returns the array `[ 'banana', 'apple', 'orange', 'pear' ]` +Het bovenstaande voorbeeld werkt. Dit geeft de array `[ 'banana', 'apple', 'orange', 'pear' ]` terug. +

From 4f25cfd76f618052368caa570fe02f1fb0b8e970 Mon Sep 17 00:00:00 2001 From: Tarabass Date: Tue, 4 Feb 2020 21:38:46 +0100 Subject: [PATCH 526/915] Question 95 --- nl-NL/README.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/nl-NL/README.md b/nl-NL/README.md index 8d6d6fec..fa8f0c2b 100644 --- a/nl-NL/README.md +++ b/nl-NL/README.md @@ -3023,16 +3023,16 @@ console.log(nums(1, 2)) #### Antwoord: 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 _hoeven_ we geen puntkomma's te schrijven, alhoewel de JavaScript engine ze toch zal toevoegen na statements. Dit wordt **Automatic Semicolon Insertion** genoemd. Een statement kan bijvoorbeeld een variabele zijn of een keyword zoals `throw`, `return`, `break`, etc. -Here, we wrote a `return` statement, en 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: +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 ``` -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! +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!

From c948c0721bd5536bcffd68dfa874dc87c4e3a215 Mon Sep 17 00:00:00 2001 From: Tarabass Date: Tue, 4 Feb 2020 21:44:14 +0100 Subject: [PATCH 527/915] Question 96 --- nl-NL/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/nl-NL/README.md b/nl-NL/README.md index fa8f0c2b..e511cb5e 100644 --- a/nl-NL/README.md +++ b/nl-NL/README.md @@ -3068,7 +3068,7 @@ console.log(member.name) #### Antwoord: 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"`. +We kunnen classes gelijk zetten tot andere classes/functie constructors. In dit geval zettten we `Person` gelijk aan `AnotherPerson`. De naam op deze constructor is `Sarah`, dus de propertie naam van de nieuwe `Person` instantie `member` is `"Sarah"`.

From 3b2b0b303c32ada0db5e95177e946d74be97d7af Mon Sep 17 00:00:00 2001 From: Tarabass Date: Wed, 5 Feb 2020 20:31:36 +0100 Subject: [PATCH 528/915] Question 97 --- nl-NL/README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/nl-NL/README.md b/nl-NL/README.md index e511cb5e..27f907c8 100644 --- a/nl-NL/README.md +++ b/nl-NL/README.md @@ -3096,9 +3096,9 @@ console.log(Object.keys(info)) #### Antwoord: D -A Symbol is not _enumerable_. The Object.keys method returns all _enumerable_ key properties on an object. The Symbol won't be visible, en an empty array is returned. When logging the entire object, all properties will be visible, even non-enumerable ones. +Een Symbol is geen _enumerable_. De Object.keys methode retourneert alle _enumerable_ key properties van een object. De Symbol zal niet zichtbaar zijn en een lege array zal geretourneerd worden. Wanneer we het hele object loggen zullen alle properties zichtbaar zijn, zelfs de niet enumarables. -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). +Dit is één van de goeie eigenschappen van een Symbol: naast dat het een compleet unieke waarde representeert (wat voorkomt dat namen op objecten per ongeluk conflecteren, bijvoorbeeld wanneer je werkt met 2 libraries die properties willen toevoegen aan één en hetzelfde object) kun je properties op objecten op deze manier ook verbergen (natuurlijk niet compleet verbergen. Je kunt de Symbolen altijd benaderen gebruikmakend van de `Object.getOwnPropertySymbols()` methode).

From b793d05d12b920880fe37abec331879e0349e715 Mon Sep 17 00:00:00 2001 From: Tarabass Date: Wed, 5 Feb 2020 21:22:12 +0100 Subject: [PATCH 529/915] Question 98 --- nl-NL/README.md | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/nl-NL/README.md b/nl-NL/README.md index 27f907c8..7da06027 100644 --- a/nl-NL/README.md +++ b/nl-NL/README.md @@ -3128,17 +3128,17 @@ console.log(getUser(user)) #### Antwoord: 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: +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]` - With the rest parameter `...y`, we put all "remaining" arguments in an array. The remaining arguments are `2`, `3` en `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: +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 })``` -Since no value gets returned in this case, the function returns `undefined`. +Omdat er geen waarde geretourneerd wordt in dit geval zal de functie `undefined` retourneren.

From 8748b0f7d4fe91844f7121527706406e23e23f91 Mon Sep 17 00:00:00 2001 From: Tarabass Date: Wed, 5 Feb 2020 21:30:39 +0100 Subject: [PATCH 530/915] Question 99 --- nl-NL/README.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/nl-NL/README.md b/nl-NL/README.md index 7da06027..b551de1a 100644 --- a/nl-NL/README.md +++ b/nl-NL/README.md @@ -3163,12 +3163,12 @@ console.log(name()) #### Antwoord: C -The variable `name` holds the value of a string, which is not a function, thus cannot invoke. +De variabele `name` bevat de waarde van een string wat geen functie is, en dus niet aangeroepen kan worden. -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! +TypeErrors worden gegooid als een waarde niet van het verwachtte type is. JavaScript verwacht dat `name` een functie is omdat we het proberen aan te roepen. Omdat het een string is zal er een TypeError gegooid worden: `name` is geen functie! -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. +SyntaxErrors worden gegooid wanneer je iets hebt geschreven wat geen valide JavaScript is. Als je bijvoorbeeld het woord `return` als `retrun` hebt geschreven. +ReferenceErrors worden gegooid wanneer JavaScript niet in staat is een referentie te vinden naar een waarde die je probeert te beanderen.

From 7befce67bad3eba05043ed86591abfee3d8b9108 Mon Sep 17 00:00:00 2001 From: Tarabass Date: Wed, 5 Feb 2020 21:37:50 +0100 Subject: [PATCH 531/915] Question 100 --- nl-NL/README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/nl-NL/README.md b/nl-NL/README.md index b551de1a..133f50f4 100644 --- a/nl-NL/README.md +++ b/nl-NL/README.md @@ -3194,9 +3194,9 @@ You should${'' && `n't`} see a therapist after so much JavaScript lol` #### Antwoord: 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 een truthy waarde. Met de `&&` operator wordt de rechter waarde geretourneerd wanneer de linker waarde een truthy waarde bevat. In dit geval is de linker waarde `[]` een truthy waarde, daarom wordt `"Im'` geretourneerd. -`""` is a falsy value. If the left-hand value is falsy, nothing gets returned. `n't` doesn't get returned. +`""` is een falsy waarde. Als de linker waarde falsy is wordt er niets geretourneerd. `n't` wordt niet geretourneerd.

From 56b779a6be315758e930f9b296da5484e756fe1b Mon Sep 17 00:00:00 2001 From: Tarabass Date: Thu, 6 Feb 2020 20:50:25 +0100 Subject: [PATCH 532/915] Question 101 --- nl-NL/README.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/nl-NL/README.md b/nl-NL/README.md index 133f50f4..6fe2f5ab 100644 --- a/nl-NL/README.md +++ b/nl-NL/README.md @@ -3223,13 +3223,13 @@ console.log(one, two, three) #### Antwoord: C -With the `||` operator, we can return the first truthy operand. If all values are falsy, the last operand gets returned. +Met de `||` (or) operator kunnen we de eerste truthy waarde retourneren. Als alle waarden falsy zijn wordt de laatste waarde geretourneerd. -`(false || {} || null)`: the empty object `{}` is a truthy value. This is the first (en only) truthy value, which gets returned. `one` is equal to `{}`. +`(false || {} || null)`: het lege object `{}` is een truthy waarde. Dit is de eerste (en enige) truthy waarde en zal worden geretourneerd. `one` is gelijk aan `{}`. -`(null || false || "")`: all operands are falsy values. This means that the past operand, `""` gets returned. `two` is equal to `""`. +`(null || false || "")`: alle waarden zijn falsy waarden. Dit betekent dat de laatste waarde, `""`, wordt geretourneerd. `two` is gelijk aan `""`. -`([] || 0 || "")`: the empty array`[]` is a truthy value. This is the first truthy value, which gets returned. `three` is equal to `[]`. +`([] || 0 || "")`: de lege array `[]` is een truthy waarde. Dit is de eerste truthy waarde en wordt geretourneerd. `three` is gelijk aan `[]`.

From 618fd63820241bb8d0494c1ab7db0501b8a0b7f8 Mon Sep 17 00:00:00 2001 From: Tarabass Date: Thu, 6 Feb 2020 20:58:55 +0100 Subject: [PATCH 533/915] Fix typo in question 101 --- README.md | 2 +- en-EN/README.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index d3d60814..cdfc1cf3 100644 --- a/README.md +++ b/README.md @@ -3225,7 +3225,7 @@ With the `||` operator, we can return the first truthy operand. If all values ar `(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 past operand, `""` gets returned. `two` 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 `[]`. diff --git a/en-EN/README.md b/en-EN/README.md index ddf67054..727df465 100644 --- a/en-EN/README.md +++ b/en-EN/README.md @@ -3225,7 +3225,7 @@ With the `||` operator, we can return the first truthy operand. If all values ar `(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 past operand, `""` gets returned. `two` 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 `[]`. From 84159ff69baad20e42e799781b2acff6b90a7a3c Mon Sep 17 00:00:00 2001 From: Tarabass Date: Thu, 6 Feb 2020 21:27:01 +0100 Subject: [PATCH 534/915] Question 102 --- nl-NL/README.md | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/nl-NL/README.md b/nl-NL/README.md index 6fe2f5ab..542a7f78 100644 --- a/nl-NL/README.md +++ b/nl-NL/README.md @@ -3265,15 +3265,15 @@ secondFunction() #### Antwoord: 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), en when the call stack is empty, I want to use this value._ +Met een promise zeggen we eigenlijk _Ik wil deze functie uitvoeren, maar voor nu zet ik hem even weg omdat de uitvoer even kan duren. Alleen wanneer een bepaalde waarde is opgelost (of afgewezen), en wanneer de call stack leeg is, wil ik deze waarde gebruiken._ -We can get this value with both `.then` en the `await` keyword in an `async` function. Although we can get a promise's value with both `.then` en `await`, they work a bit differently. +We kunnen deze waarde verkrijgen met `.then` en het keyword `await` is een `async` function. Ook al kunnen we de teruggegeven waarde verkrijgen met zowel `.then` als `await`, toch werken ze allebei anders. -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 de functie `firstFunction` zetten we de myPromise functie (soort van) even aan de kant terwijl het wordt uitgevoerd en voeren we de rest van de code uit, wat `console.log('second')` is in dit geval. Daarna wordt de promise opgelost en zal de string `I have resolved` worden geretourneerd, wat gelogd zal worden nadat het zag dat de callstack leeg was. -With the await keyword in `secondFunction`, we literally pause the execution of an async function until the value has been resolved befoer moving to the next line. +Met de keyword `await` in de functie `secondFunction` pauzeren we letterlijk de executie van een async functie totdat de promise is opgelost voordat de rest van de functie wordt uitgevoerd. -This means that it waited for the `myPromise` to resolve with the value `I have resolved`, en only once that happened, we moved to the next line: `second` got logged. +Dit betekent dat het wacht tot de `myPromise` is opgelost met de waarde `I have resolved`, en alleen als dat gebeurt gaan we naar de volgende regel: `second` wordt gelogd.

From a5e78ece9406012f9dface558fb6e9cef1bb687d Mon Sep 17 00:00:00 2001 From: Tarabass Date: Thu, 6 Feb 2020 21:35:55 +0100 Subject: [PATCH 535/915] Question 103 --- nl-NL/README.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/nl-NL/README.md b/nl-NL/README.md index 542a7f78..482497ac 100644 --- a/nl-NL/README.md +++ b/nl-NL/README.md @@ -3304,13 +3304,13 @@ for (let item of set) { #### Antwoord: 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. +De `+` operator wordt niet alleen gebruikt voor het optellen van numerieke waarden, maar wordt ook gebruikt om strings te concateneren. Zodra de JavaScript engine ziet dat één van de waarden niet een numerieke waarde bevat, wordt het getal omgezet naar een string. -The first one is `1`, which is a numerical value. `1 + 2` returns the number 3. +De eerste is een `1`, wat een numerieke waarde is. `1 + 2` retourneert het getal 3. -However, the second one is a string `"Lydia"`. `"Lydia"` is a string en `2` is a number: `2` gets coerced into a string. `"Lydia"` en `"2"` get concatenated, which results in the string `"Lydia2"`. +Echter, de tweede is de string `"Lydia"`. `"Lydia"` is een string en `2` is een getal: `2` wordt omgezet naar een string. `"Lydia"` en `"2"` worden geconcateneerd wat resulteert in de 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"`. +`{ name: "Lydia" }` is een object. Een getal noch een object is een string, dus beide worden gestringified. Wanneer we een regulier object stringifiën levert dit `"[object Object]"` op. `"[object Object]"` geconcateneerd met `"2"` wordt `"[object Object]2"`.

From 0f48ab8b95c4e4d8b42dbc8c40f80d59de997d17 Mon Sep 17 00:00:00 2001 From: Tarabass Date: Thu, 6 Feb 2020 21:44:36 +0100 Subject: [PATCH 536/915] Question 104 --- nl-NL/README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/nl-NL/README.md b/nl-NL/README.md index 482497ac..9966bd9e 100644 --- a/nl-NL/README.md +++ b/nl-NL/README.md @@ -3333,9 +3333,9 @@ Promise.resolve(5) #### Antwoord: 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. +We kunnen elk type of waarde meegeven aan `Promise.resolve`, zowel een promise als een niet-promise. De methode zelf retourneert een promise met een opgeloste waarde. Als je een reguliere functie meegeeft zal het een opgeloste promise zijn met een reguliere waarde. Als je een promise meegeeft zal het een opgeloste promise zijn met een opgeloste waarde, of de doorgegeven promise. -In this case, we just passed the numerical value `5`. It returns a resolved promise with the value `5`. +In dit geval geven we alleen de numerieke waarde `5` mee. Het geeft de opgeloste promise terug met de waarde `5`.

From f1a99c9d71133ea2e0b553b3ac0ae16616c0b78c Mon Sep 17 00:00:00 2001 From: Tarabass Date: Thu, 6 Feb 2020 21:50:41 +0100 Subject: [PATCH 537/915] Question 105 --- nl-NL/README.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/nl-NL/README.md b/nl-NL/README.md index 9966bd9e..ecb7288c 100644 --- a/nl-NL/README.md +++ b/nl-NL/README.md @@ -3368,13 +3368,13 @@ compareMembers(person) #### Antwoord: B -Objects are passed by reference. When we check objects for strict equality (`===`), we're comparing their references. +Objecten worden doorgegeven _by reference_. Wanneer we objecten vergelijken op type en gelijkenis (`===`), vergelijken we hun referenties. -We set the default value for `person2` equal to the `person` object, en passed the `person` object as the value for `person1`. +We zetten de standaard waarde voor `person2` gelijk aan het object `person` en geven het object `person` door als de waarde voor het argument `person1`. -This means that both values have a reference to the same spot in memory, thus they are equal. +Dit betekent dat beide waarden een referentie hebben naar dezelfde plek in het geheugen, dus zijn ze gelijk. -The code block in the `else` statement gets run, en `They are the same!` gets logged. +De code in de `else` statement wordt uitgevoerd en `They are the same!` wordt gelogd.

From e375bdf18d8c91d69ca055665fbc57fbc14e9fdd Mon Sep 17 00:00:00 2001 From: Tarabass Date: Thu, 6 Feb 2020 22:11:58 +0100 Subject: [PATCH 538/915] Question 106 --- nl-NL/README.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/nl-NL/README.md b/nl-NL/README.md index ecb7288c..b74273dd 100644 --- a/nl-NL/README.md +++ b/nl-NL/README.md @@ -3407,11 +3407,11 @@ console.log(colorConfig.colors[1]) #### Antwoord: 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 kunnen we properties van een object op twee manieren benaderen: blokhaken of met een punt notitie. In dit voorbeeld gebruiken we de punt notatie (`colorConfig.colors`) in plaats van blokhaken (`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 `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`. +Met de punt notatie zal JavaScript proberen om de propertie van een object te vinden met exact dezelfde naam. In dit voorbeeld probeert JavaScript een propertie te vinden met de naam `colors` uit het `colorConfig` object. Er is geen property genaamd `colors` dus wordt `undefined` geretourneerd. Dan proberen we de waarde van het eerste element te benaderen door gebruik te maken van `[1]`. We kunnen dit niet doen op een waarde die `undefined` is, dus wordt er een `TypeError` gegooid: `Cannot read property '1' of undefined`. -JavaScript interprets (or unboxes) statements. When we use bracket notation, it sees the first opening bracket `[` en 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 interpreteert (of beter gezegd unboxed) statements. Wanneer we blokhaken gebruiken ziet het de eerste blokhaak `[` en blijft doorgaan totdat het de tweede blokhaak `]` vindt. Alleen dan zal het het statement evalueren. Als we `colorConfig[colors[1]]` hadden gebruikt zou het de waarde van de `red` propertie teruggeven van het `colorConfig` object.

From a915f578ed4298319c6a0a87b4a9683b7bd864b4 Mon Sep 17 00:00:00 2001 From: Tarabass Date: Thu, 6 Feb 2020 22:15:38 +0100 Subject: [PATCH 539/915] Question 107 --- nl-NL/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/nl-NL/README.md b/nl-NL/README.md index b74273dd..4df94c2d 100644 --- a/nl-NL/README.md +++ b/nl-NL/README.md @@ -3432,7 +3432,7 @@ console.log('❤️' === '❤️') #### Antwoord: 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. +Onder de motorkap zijn emojis unicodes. De unicodes voor het hart zijn `"U+2764 U+FE0F"`. Deze zijn altijd hetzelfde voor dezelfde emojis. We vergelijken twee gelijke string met elkaar, wat true retourneert.

From 175517b8fa2e83851bd9d16d3f58a8c6eac4de1b Mon Sep 17 00:00:00 2001 From: Tarabass Date: Thu, 6 Feb 2020 22:22:25 +0100 Subject: [PATCH 540/915] Question 108 --- nl-NL/README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/nl-NL/README.md b/nl-NL/README.md index 4df94c2d..b227182f 100644 --- a/nl-NL/README.md +++ b/nl-NL/README.md @@ -3462,9 +3462,9 @@ emojis.splice(1, 2, '✨') #### Antwoord: 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 `'🥑'` en `'😍'`) en added the ✨ emoji instead. +Met de `splice` methode passen we de originele array aan door elementen te verwijderen, te vervangen of toe te voegen. In dit geval hebben we 2 elementen verwijderd vanaf index 1 (we hebben `'🥑'` en `'😍'` verwijderd) en hebben in plaats daarvan ✨ toegevoegd. -`map`, `filter` en `slice` return a new array, `find` returns an element, en `reduce` returns a reduced value. +`map`, `filter` en `slice` geven een nieuwe array terug, `find` geeft een element terug en `reduce` geeft een gereduceerde waarde terug.

From 59068db52d84ce5b4b4f11531f593f354bfa321e Mon Sep 17 00:00:00 2001 From: Tarabass Date: Thu, 13 Feb 2020 20:57:42 +0100 Subject: [PATCH 541/915] Question 109 --- nl-NL/README.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/nl-NL/README.md b/nl-NL/README.md index b227182f..d20bc6d1 100644 --- a/nl-NL/README.md +++ b/nl-NL/README.md @@ -3471,7 +3471,7 @@ Met de `splice` methode passen we de originele array aan door elementen te verwi --- -###### 109. Wat is de uitkomst? +###### 109. Wat is de uitkomst? ```javascript const food = ['🍕', '🍫', '🥑', '🍔'] @@ -3492,11 +3492,11 @@ console.log(food) #### Antwoord: 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 act by reference +We zetten de waarde van de property `favoriteFood` op het object `info` gelijk aan de string met de pizza emoji, `'🍕'`. Een string is een primitief data type. In JavaScript zijn primitieve data types _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, en 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) +In JavaScript interacteren primitieve data types (alles dat geen object is) _by value_. In dit geval zetten we de waarde van de property `favoriteFood` op het object `info` gelijk aan de waarde van het eerste element in de `food` array, de string met de pizza emoji in dit geval (`'🍕'`). Een string is een primitief data type en interacteert _by value_ (neem een kijkje op mijn [blogpost](https://www.theavocoder.com/complete-javascript/2018/12/21/by-value-vs-by-reference) als je geïntereseerd bent om hierover meer te leren). -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, en 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, `['🍕', '🍫', '🥑', '🍔']`. +Daarna veranderen we de waarde van de property `favoriteFood` op het object `info`. De `food` array is niet veranderd omdat de waarde van `favoriteFood` een _kopie_ bevat van de waarde van het eerste element van de array, en geen referentie heeft naar dezelfde plek in het geheugen van de element in `food[0]`. Wanneer we food loggen is het nog steeds dezelfde array, `['🍕', '🍫', '🥑', '🍔']`.

From 5689f0618633de9a8bfed6704a24c63584f553bf Mon Sep 17 00:00:00 2001 From: Tarabass Date: Thu, 13 Feb 2020 21:01:51 +0100 Subject: [PATCH 542/915] Question 110 --- nl-NL/README.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/nl-NL/README.md b/nl-NL/README.md index d20bc6d1..3b65605e 100644 --- a/nl-NL/README.md +++ b/nl-NL/README.md @@ -3519,18 +3519,18 @@ JSON.parse() #### Antwoord: A -With the `JSON.parse()` method, we can parse JSON string to a JavaScript value. +Met de `JSON.parse()` methode kunnen we een JSON string parsen naar een JavaScript waarde. ```javascript -// Stringifying a number into valid JSON, then parsing the JSON string to a JavaScript value: +// 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 -// Stringifying an array value into valid JSON, then parsing the JSON string to a JavaScript value: +// 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] -// Stringifying an object into valid JSON, then parsing the JSON string to a JavaScript value: +// 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' } ``` From 7bdaa6ed6438553d949726941c1aca6c28a5c0d2 Mon Sep 17 00:00:00 2001 From: Tarabass Date: Thu, 13 Feb 2020 21:17:24 +0100 Subject: [PATCH 543/915] Question 111 --- nl-NL/README.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/nl-NL/README.md b/nl-NL/README.md index 3b65605e..4bcc9514 100644 --- a/nl-NL/README.md +++ b/nl-NL/README.md @@ -3563,11 +3563,11 @@ getName() #### Antwoord: 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, en with the value of `'Sarah'`. +Elke functie heeft zijn eigen _execution context_ (of _scope_). De `getName` functie zoekt eerst binnen zijn eigen context (scope) om te kijken of het de variabele `name` bevat, die we proberen te benaderen. In dit geval bevat de `getName` functie zijn eigen `name` variabele: we declareren de variabele `name` met het keyword `let` en met de waarde `'Sarah'`. -Variables with the `let` keyword (en `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`. +Variabelen gedeclareerd met het keyword `let` (en `const`) worden gehoisted, maar worden niet, zoals met het keyword `var`, geïnitialiseerd. Ze zijn niet benaderbaar voor de lijn waar we ze declareren (initialiseren). Dit wordt de "temporal dead zone" genoemd. Wanneer we de variabelen proberen te benaderen voordat ze gedeclareerd zijn zal JavaScript een `ReferenceError` gooien. -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`. +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' From da5733e817554c226f18319c4590204330ce9c38 Mon Sep 17 00:00:00 2001 From: Tarabass Date: Thu, 13 Feb 2020 21:39:51 +0100 Subject: [PATCH 544/915] Question 112 --- nl-NL/README.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/nl-NL/README.md b/nl-NL/README.md index 4bcc9514..fe2e1610 100644 --- a/nl-NL/README.md +++ b/nl-NL/README.md @@ -3612,16 +3612,16 @@ console.log(two.next().value) #### Antwoord: 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). +Met het keyword `yield` , we `yield` waarden in een generator functie. Met het keyword `yield*`, we `yield` waarden van een andere generator functie, of iterabel object (bijvoorbeeld een 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']`. +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 ``` -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. +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' From 92efe70c657c12fe1194ae4bc953576476d179cb Mon Sep 17 00:00:00 2001 From: Tarabass Date: Thu, 13 Feb 2020 21:45:23 +0100 Subject: [PATCH 545/915] Question 113 --- nl-NL/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/nl-NL/README.md b/nl-NL/README.md index fe2e1610..83bc8ce2 100644 --- a/nl-NL/README.md +++ b/nl-NL/README.md @@ -3651,7 +3651,7 @@ console.log(`${(x => x)('I love')} to program`) #### Antwoord: 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`. +Expressies binnen template literals worden eerste geëvalueerd. Dit betekent dat de string de geretourneerde waarde zal bevatten van de expressie, de direct aangeroepen functie `(x => x)('I love')` in dit geval. We geven de waarde `'I love'` mee als een argument aan de arrow functie `x => x`. `x` is gelijk aan `'I love'`, wat geretourneerd zal worden. Dit resulteert in `I love to program`.

From 9ad2c8cf71f82318cfaa7b5147559a575af38641 Mon Sep 17 00:00:00 2001 From: Tarabass Date: Thu, 13 Feb 2020 21:53:45 +0100 Subject: [PATCH 546/915] Question 114 --- nl-NL/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/nl-NL/README.md b/nl-NL/README.md index 83bc8ce2..2ae71cbf 100644 --- a/nl-NL/README.md +++ b/nl-NL/README.md @@ -3680,7 +3680,7 @@ config = null #### Antwoord: 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). +Normaal als we objecten gelijk maken aan `null` worden deze objecten opgeruimd door de _garbage collector_, omdat er geen referentie meer is naar het object. Echter, omdat de callback functie binnen `setInterval` een arrow functie is (en dus verbonden is aan het `config` object) zal de callback functie nog steeds een referentie behouden naar het `config` object. Zolang er een referentie is zal de _garbage collector_ het object niet opruimen. Omdat het niet opgeruimd wordt door de _garbage collector_ zal de `setInterval` callback functie nog steeds iedere 1000ms (1s) aangeroepen worden.

From 659a7753014c3d26806cb3b046796276a245bd2e Mon Sep 17 00:00:00 2001 From: Tarabass Date: Thu, 13 Feb 2020 22:13:08 +0100 Subject: [PATCH 547/915] Question 115 --- nl-NL/README.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/nl-NL/README.md b/nl-NL/README.md index 2ae71cbf..6a2174fd 100644 --- a/nl-NL/README.md +++ b/nl-NL/README.md @@ -3713,10 +3713,10 @@ myMap.get(() => 'greeting') #### Antwoord: 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, en the value will be the second argument passed to the `set` function. The key is the _function_ `() => 'greeting'` in this case, en the value `'Hello world'`. `myMap` is now `{ () => 'greeting' => 'Hello world!' }`. +Als een **key/value** paar wordt toegevoegd gebruikmakend van de `set` methode zal de **key** de waarde zijn van het eerste argument dat zal worden meegegeven aan de `set` functie, en de **value** zal het tweede argument zijn die wordt meegegeven aan de `set` functie. De **key** is de _functie_ `() => 'greeting'` in dit geval, en de waarde `'Hello world'`. `myMap` is nu `{ () => '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. +1 is verkeerd omdat de **key** niet `'greeting'` is, maar `() => 'greeting'`. +3 is verkeerd omdat we een nieuwe functie creëeren door het mee te geven als een parameter aan de `get` methode. Object interacteert _by reference_. Een functie is een object, dit is ook waarom twee functies nooit strict gelijk zijn. Zelfs niet als ze identiek zijn: ze hebben een referentie naar een andere plek in het geheugen.

From 0e43ea5c0903f43d1a035254c24553b69d7f0259 Mon Sep 17 00:00:00 2001 From: Tarabass Date: Fri, 14 Feb 2020 20:52:32 +0100 Subject: [PATCH 548/915] Question 116 --- nl-NL/README.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/nl-NL/README.md b/nl-NL/README.md index 6a2174fd..daf826cd 100644 --- a/nl-NL/README.md +++ b/nl-NL/README.md @@ -3753,11 +3753,11 @@ console.log(person) #### Antwoord: C -Both the `changeAge` en `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. +De functies `changeAge` en `changeAgeAndName` hebben beiden een standaard parameter, namelijk het _nieuw_ aangemaakte object `{ ...person }`. Dit object bevat kopieën van alle key/value paren in het `person` object. -First, we invoke the `changeAge` function en 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 }`. +Als eerste roepen we de `changeAge` functie aan en geven het object `person` mee als argument. Deze functie verhoogt de waarde van de propertie `age` met 1. `person` is nu `{ 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 }`. +Dan roepen we de functie `changeAgeAndName` aan, echter geven we geen parameter mee. In plaats daarvan is de waarde van `x` gelijk aan een _nieuw_ object: `{ ...person }`. Omdat het een nieuw object is heeft het geen effect op de waarden van de properties van het object `person`. `person` is nog steeds gelijk aan `{ name: "Lydia", age: 22 }`.

From b4e450b51122d45eddd4052b936c1812fbdd8791 Mon Sep 17 00:00:00 2001 From: Tarabass Date: Fri, 14 Feb 2020 20:55:01 +0100 Subject: [PATCH 549/915] Question 117 --- nl-NL/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/nl-NL/README.md b/nl-NL/README.md index daf826cd..05266136 100644 --- a/nl-NL/README.md +++ b/nl-NL/README.md @@ -3782,7 +3782,7 @@ function sumValues(x, y, z) { #### Antwoord: C -With the spread operator `...`, we can _spread_ iterables to individual elements. The `sumValues` function receives three arguments: `x`, `y` en `z`. `...[1, 2, 3]` will result in `1, 2, 3`, which we pass to the `sumValues` function. +Met de spread operator `...` kunnen we iterabelen _ontplooien_ tot individuele elementen. De `sumValues` functie krijgt drie argumenten mee: `x`, `y` en `z`. `...[1, 2, 3]` zal resulteren in `1, 2, 3`, wat we meegeven aan de functie `sumValues`.

From 3def5c55bca6048f483b0b4a2aff49f9b295e683 Mon Sep 17 00:00:00 2001 From: Tarabass Date: Fri, 14 Feb 2020 20:57:53 +0100 Subject: [PATCH 550/915] Question 118 --- nl-NL/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/nl-NL/README.md b/nl-NL/README.md index 05266136..723323f3 100644 --- a/nl-NL/README.md +++ b/nl-NL/README.md @@ -3808,7 +3808,7 @@ console.log(list[(num += 1)]); #### Antwoord: 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 🥰. +Met de `+=` operator verhogen we de waarde van `num` met `1`. `num` heeft een initiële waarde van `1`, dus `1 + 1` is `2`. Het element met de index 2 in de `list` array is 🥰, `console.log(list[2])` logt 🥰.

From 40ec2aab783fed7e58f9fcd2bc4b3e58156cadb0 Mon Sep 17 00:00:00 2001 From: Tarabass Date: Fri, 14 Feb 2020 21:12:18 +0100 Subject: [PATCH 551/915] Question 119 --- nl-NL/README.md | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/nl-NL/README.md b/nl-NL/README.md index 723323f3..e59e644c 100644 --- a/nl-NL/README.md +++ b/nl-NL/README.md @@ -3846,12 +3846,12 @@ console.log(member.getLastName?.()); #### Antwoord: 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 en returns `undefined`. +Met de _optional chaining operator_ `?.` hoeven we niet langer expliciet te checken of een dieper geneste waarde valide is, of niet. Als we een propertie proberen te benaderen op een `undefined` of `null` waarde (_nullish_) zal de expressie stoppen en `undefined` retourneren. -`person.pet?.name`: `person` has a property named `pet`: `person.pet` is not nullish. It has a property called `name`, en 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 en can get invoked, which returns `Lydia Hallie`. -`member.getLastName?.()`: `member` is not defined: `member.getLastName()` is nullish. The expression returns `undefined`. +`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. +`member.getLastName?.()`: `member` is niet gedefinieerd: `member.getLastName()` is _nullish_. The expressie geeft `undefined` terug.

From 5a878d5a006f750902fa7e49ed42bfac3678feda Mon Sep 17 00:00:00 2001 From: Tarabass Date: Fri, 14 Feb 2020 21:24:18 +0100 Subject: [PATCH 552/915] Question 120 --- nl-NL/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/nl-NL/README.md b/nl-NL/README.md index e59e644c..fa8132c2 100644 --- a/nl-NL/README.md +++ b/nl-NL/README.md @@ -3880,7 +3880,7 @@ if (groceries.indexOf("banana")) { #### Antwoord: 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, en `We don't have to buy bananas!` gets logged. +We geven de conditie `groceries.indexOf("banana")` mee aan de if-statement. `groceries.indexOf("banana")` geeft `0` terug, wat een _falsy_ waarde is.Omdat de conditie in de if-statement _falsy_ is wordt de code in de else-statement uitgevoerd, en `We don't have to buy bananas!` wordt gelogd.

From 635dd3ab8d260b21512e7b94d9aa205675cf1cd5 Mon Sep 17 00:00:00 2001 From: Tarabass Date: Fri, 14 Feb 2020 21:27:02 +0100 Subject: [PATCH 553/915] Question 121 --- nl-NL/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/nl-NL/README.md b/nl-NL/README.md index fa8132c2..c5fe6b3c 100644 --- a/nl-NL/README.md +++ b/nl-NL/README.md @@ -3910,7 +3910,7 @@ console.log(config.language); #### Antwoord: 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. +De `language` methode is een `setter`. Setters hebben geen werkelijke waarde. Hun doel is om properties te _wijzigen_. Wanneer een `setter` methode wordt aangeroepen wordt `undefined` geretourneerd.

From 1614a86b336fca43bfc5112c3318dc244ede6e35 Mon Sep 17 00:00:00 2001 From: Tarabass Date: Fri, 14 Feb 2020 21:30:14 +0100 Subject: [PATCH 554/915] Question 122 --- nl-NL/README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/nl-NL/README.md b/nl-NL/README.md index c5fe6b3c..dadb8904 100644 --- a/nl-NL/README.md +++ b/nl-NL/README.md @@ -3936,9 +3936,9 @@ console.log(!typeof name === "string"); #### Antwoord: C -`typeof name` returns `"string"`. The string `"string"` is a truthy value, so `!typeof name` returns the boolean value `false`. `false === "object"` en `false === "string"` both return`false`. +`typeof name` retourneert `"string"`. De string `"string"` is een _truthy_ waarde, dus `!typeof name` retourneert de boolean waarde `false`. `false === "object"` en `false === "string"` retourneren beiden `false`. -(If we wanted to check whether the type was (un)equal to a certain type, we should've written `!==` instead of `!typeof`) +(Als we wilden checken of het type (on)gelijk is aan een bepaald type, zouden we `!==` moeten gebruiken in plaats van `!typeof`)

From 6f851f11b020f2ba93358955d0506e3978a039b2 Mon Sep 17 00:00:00 2001 From: Tarabass Date: Fri, 14 Feb 2020 21:36:19 +0100 Subject: [PATCH 555/915] Question 123 --- nl-NL/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/nl-NL/README.md b/nl-NL/README.md index dadb8904..d82c7067 100644 --- a/nl-NL/README.md +++ b/nl-NL/README.md @@ -3966,7 +3966,7 @@ add(4)(5)(6); #### Antwoord: 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` en `z` within the last arrow function, the JS engine goes up the scope chain in order to find the values for `x` en `y` accordingly. This returns `4` `5` `6`. +De `add` functie retourneert een arrow functie, die een arrow functie retourneert, die ook weer een arrow functie retourneert. De eerste functie krijgt een argument `x` mee met de waarde `4`. We roepen de tweede functie aan, welke een argument `y` meekrijgt met de waarde `5`. Dan roepen we de derde functie aan en die krijgt het argument `z` meet met de waarde `6`. Wanneer we de waarden proberen op te vragen van `x`, `y` en `z` ind e laatste arrow functie de JavaScript engine gaat omhoog in de _scope chain_ om de waarden van `x` en `y` te vinden. Dit retourneert `4` `5` `6`.

From acaa13046040783280e7ca67846f8bf9c053baaf Mon Sep 17 00:00:00 2001 From: Tarabass Date: Sat, 15 Feb 2020 20:25:40 +0100 Subject: [PATCH 556/915] Question 124 --- nl-NL/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/nl-NL/README.md b/nl-NL/README.md index d82c7067..81f37242 100644 --- a/nl-NL/README.md +++ b/nl-NL/README.md @@ -4000,7 +4000,7 @@ async function* range(start, end) { #### Antwoord: 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`. +De generator functie `range` retourneert een async object met promises voor elk item in de range die we meegeven: `Promise{1}`, `Promise{2}`, `Promise{3}`. We zetten de variabele `gen` gelijk aan het async object, waarnaar we eroverheen iteraten gebruikmakend van een `for await ... of` loop. We zetten de variabele `item` gelijk aan de promises die geretourneerd worden: eerst `Promise{1}`, dan `Promise{2}` en dan `Promise{3}`. Omdat we de waarde van `item` _awaiten_, de opgeloste promise, worden de opgeloste _waarden_ van de promises geretourneerd: `1`, `2` en `3`.

From f781a10cc93698c61913a7bac99c6a2f41ddd286 Mon Sep 17 00:00:00 2001 From: Tarabass Date: Sat, 15 Feb 2020 20:29:51 +0100 Subject: [PATCH 557/915] Question 125 --- nl-NL/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/nl-NL/README.md b/nl-NL/README.md index 81f37242..9971c9b3 100644 --- a/nl-NL/README.md +++ b/nl-NL/README.md @@ -4027,7 +4027,7 @@ myFunc(1, 2, 3); #### Antwoord: D -`myFunc` expects an object with properties `x`, `y` en `z` as its argument. Since we're only passing three separate numeric values (1, 2, 3) instead of one object with properties `x`, `y` en `z` ({x: 1, y: 2, z: 3}), `x`, `y` en `z` have their default value of `undefined`. +De functie `myFunc` verwacht een object met de properties `x`, `y` en `z` als haar argument. Omdat we maar drie separate numerieke waarden (1, 2, 3) meegeven in plaats van één object met de properties `x`, `y` en `z` ({x: 1, y: 2, z: 3}), hebben `x`, `y` en `z` hun default waarde `undefined`.

From edc18c1ecd0fa0e0991d84a28399fe3b47ca8cb0 Mon Sep 17 00:00:00 2001 From: Tarabass Date: Sun, 16 Feb 2020 10:56:58 +0100 Subject: [PATCH 558/915] Question 126 --- nl-NL/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/nl-NL/README.md b/nl-NL/README.md index 9971c9b3..1168b250 100644 --- a/nl-NL/README.md +++ b/nl-NL/README.md @@ -4064,7 +4064,7 @@ console.log(getFine(130, 300)) #### Antwoord: 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 `currentcy` in `USD` results in `$300.00`. +Met de `Intl.NumberFormat` methode kunnen we numerieke waarden formatteren naar elke lokale format. We formatteren de numerieke waarde `130` naar de lokale waarde van `en-US` als een `unit` in `mile-per-hour`, wat resulteert in `130 mph`. De numerieke waarde `300` naar de lokale waarde van `en-US` als een `currency` in `USD`, wat resulteert in `€300.00`.

From 3ede4a588203dba64046f99a674dae62fac6625d Mon Sep 17 00:00:00 2001 From: Tarabass Date: Sun, 16 Feb 2020 11:16:34 +0100 Subject: [PATCH 559/915] Question 127 --- nl-NL/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/nl-NL/README.md b/nl-NL/README.md index 1168b250..526250ec 100644 --- a/nl-NL/README.md +++ b/nl-NL/README.md @@ -4090,7 +4090,7 @@ console.log(spookyItems); #### Antwoord: B -By destructuring objects, we can unpack values from the right-hand object, en 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. +Door objecten te destructureren (_destructuring_) kunnen we de values van een object uitpakken en een uitgepakte waarde toewijzen aan de key van dezelfde property. In dit geval wijzen we de waarde "💀" toe aan `spookyItems[3]`. Dit betekent dat we de array `spookyItems` aanpassen, we voegen namelijk "💀" toe. Wanneer we de array `spookyItems` loggen wordt `["👻", "🎃", "🕸", "💀"]` gelogd.

From f205fda7abd6d145d888d916b687c4ca42f57adc Mon Sep 17 00:00:00 2001 From: Tarabass Date: Sun, 16 Feb 2020 11:29:14 +0100 Subject: [PATCH 560/915] Question 128 --- nl-NL/README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/nl-NL/README.md b/nl-NL/README.md index 526250ec..322c15c8 100644 --- a/nl-NL/README.md +++ b/nl-NL/README.md @@ -4120,9 +4120,9 @@ console.log(isNaN(age)); #### Antwoord: C -With the `Number.isNaN` method, you can check if the value you pass is a _numeric value_ en 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`. +Met de `Number.isNaN` methode kunnen je checken of de waarde die je meegeeft een _numerieke waarde_ is en gelijk is aan `NaN`. `name` is niet een numerieke waarde en `Number.isNaN(name)` zal `false` teruggeven. `age` is een numerieke waarde, maar is niet gelijk aan `NaN`. `Number.isNaN(age)` zal `false` teruggeven. -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`. +Met de `isNaN` methode kun je checken of een waarde die je meegeeft geen numerieke waarde is. `name` is geen numerieke waarde, dus `isNaN(name)` geeft `true` terug. `age` is wel een numerieke waarde, dus `isNaN(age)` geeft `false` terug.

From 98d2324f88b57eb833328a0ca12b6fe23e1dcb6a Mon Sep 17 00:00:00 2001 From: Tarabass Date: Sun, 16 Feb 2020 11:32:21 +0100 Subject: [PATCH 561/915] Question 130 --- nl-NL/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/nl-NL/README.md b/nl-NL/README.md index 322c15c8..0eb93ee5 100644 --- a/nl-NL/README.md +++ b/nl-NL/README.md @@ -4185,7 +4185,7 @@ const myPromise = Promise.resolve("Woah some cool data"); #### Antwoord: 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. +In de `try` statement loggen we de _awaited_ waarde van de `myPromise` variabele: `"Woah some cool data"`. Omdat er geen errors gegooid worden in de `try` statement komt de code niet in de `catch`. De code in de `finally` statement wordt _altijd_ uitgevoerd, `"Oh finally!"` wordt gelogd.

From 5beceaccb5f8ecaa64bb10db7e63d803a0dcca23 Mon Sep 17 00:00:00 2001 From: Tarabass Date: Sun, 16 Feb 2020 11:35:46 +0100 Subject: [PATCH 562/915] Question 131 --- nl-NL/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/nl-NL/README.md b/nl-NL/README.md index 0eb93ee5..d4421b0b 100644 --- a/nl-NL/README.md +++ b/nl-NL/README.md @@ -4210,7 +4210,7 @@ console.log(emojis.flat(1)); #### Antwoord: 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. `['🥑']` en `['✨', '✨', ['🍕', '🍕']]` in this case. Concatenating these two arrays results in `['🥑', '✨', '✨', ['🍕', '🍕']]`. +Met de `flat` methode kunnen we een nieuwe platgemaakte array maken. De diepte van de platgemaakte array hangt af van de waarde die we meegeven. In dit geval geven we de waarde `1` mee (wat eigenlijk niet had gehoeven omdat dit de standaard waarde is), wat betekent dat alleen de arrays van het eerste niveau geconcateneerd worden. `['🥑']` en `['✨', '✨', ['🍕', '🍕']]` in dit geval. Het concateneren van deze twee arrays resulteert in `['🥑', '✨', '✨', ['🍕', '🍕']]`.

From eab72c2de9201a8d2575d6f373fb72d65c9097d9 Mon Sep 17 00:00:00 2001 From: Tarabass Date: Sun, 16 Feb 2020 11:41:55 +0100 Subject: [PATCH 563/915] Question 132 --- nl-NL/README.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/nl-NL/README.md b/nl-NL/README.md index d4421b0b..df2cb6e7 100644 --- a/nl-NL/README.md +++ b/nl-NL/README.md @@ -4217,7 +4217,7 @@ Met de `flat` methode kunnen we een nieuwe platgemaakte array maken. De diepte v --- -###### 132. Wat is de uitkomst? +###### 132. Wat is de uitkomst? ```javascript class Counter { @@ -4250,13 +4250,13 @@ console.log(counterOne.count); #### Antwoord: D -`counterOne` is an instance of the `Counter` class. The counter class contains a `count` property on its constructor, en an `increment` method. First, we invoked the `increment` method twice by calling `counterOne.increment()`. Currently, `counterOne.count` is `2`. +`counterOne` is een instantie van de `Counter` class. De counter class bevat een `count` propertie op de constructor en een `increment` methode.Eerst roepen we de `increment` methode twee keer aan door `counterOne.increment()` aan te roepen. Op dat moment is `counterOne.count` gelijk aan `2`. -Then, we create a new variable `counterTwo`, en 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`. +Dan maken we de variabele `counterTwo` aan en maken het gelijk aan `counterOne`. Omdat object interacteren _by reference_ creëeren we enkel een referentie naar dezelfde plek in het geheugen waarnaar `counterOne` verwijst. Omdat dit dezelfde plek in het geheugen is worden alle veranderingen op het object `counterTwo` ook doorgevoerd op `counterOne`. Op dat moment is `counterTwo.count` ook `2`. -We invoke the `counterTwo.increment()`, which sets the `count` to `3`. Then, we log the count on `counterOne`, which logs `3`. +We roepen `counterTwo.increment()` aan, wat `count` gelijk maakt aan `3`. Als we de `count` op `counterOne` loggen is die `3`. From 735b2813540b9c7facc7bd7e5f1634b3ae0f5a36 Mon Sep 17 00:00:00 2001 From: Tarabass Date: Sun, 16 Feb 2020 12:03:20 +0100 Subject: [PATCH 564/915] Question 133 --- nl-NL/README.md | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/nl-NL/README.md b/nl-NL/README.md index df2cb6e7..e98d1678 100644 --- a/nl-NL/README.md +++ b/nl-NL/README.md @@ -4297,15 +4297,15 @@ funcTwo(); #### Antwoord: 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.) +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. -Both the promise en the timeout are asynchronous operations, the function keeps on running while it's busy completing the promise en 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, en `Promise!` gets logged. However, since we're invoking `funcTwo()`, the call stack isn't empty, en the callback of the `setTimeout` function cannot get added to the callstack yet. +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. -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!`. +In `funcTwo` wachten we eerst op de promise `myPromise`. Met het keyword `await` pauzeren we de executie van de functie totdat de promise iets teruggeeft (of afwijst). Dan loggen we de _awaited_ waarde van `res` (omdat de promise zelf een promise retourneert). Dit logt `Promise!`. -The next line is the _asynchronous_ `setTimeout` function, from which the callback is sent to the Web API. +De volgende regel is de _asynchrone_ `setTimeout` functie waarvan de callback functie naar de Web API gestuurd wordt. -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`, en `() => console.log("Timeout!")` from `funcTwo`) get added to the call stack one by one. The first callback logs `Timeout!`, en gets popped off the stack. Then, the second callback logs `Timeout!`, en gets popped off the stack. This logs `Last line! Promise! Promise! Last line! Timeout! Timeout!` +We komen op de laatste regel van `funcTwo` wat `Last line!` logt naar het console. Omdat `funcTwo` van de callstack gaat is de callstack leeg. De callback functies die in de wachtrij stonden (`() => console.log("Timeout!")` van `funcOne` en `() => console.log("Timeout!")` van `funcTwo`) worden nu één voor één toegevoegd aan de callstack. De eerste callback functie logt `Timeout!` en wordt verwijderd van de callstack. De tweede callback functie logt dan `Timeout!` en wordt verwijderd van de callstack. Dit logt `Last line! Promise! Promise! Last line! Timeout! Timeout!`.

From 4762804e827c61300302f2c3f5a18fd3e4289b2e Mon Sep 17 00:00:00 2001 From: Tarabass Date: Sun, 16 Feb 2020 12:06:14 +0100 Subject: [PATCH 565/915] Question 134 --- nl-NL/README.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/nl-NL/README.md b/nl-NL/README.md index e98d1678..53873ee5 100644 --- a/nl-NL/README.md +++ b/nl-NL/README.md @@ -4334,7 +4334,7 @@ import * as sum from "./sum"; #### Antwoord: C -With the asterisk `*`, we import all exported values from that file, both default en named. If we had the following file: +Met het sterretje `*` importeren we alle geëxporteerde waarden van een bestand, zowel de default als de benaamde. Als we het volgende bestand hadden: ```javascript // info.js @@ -4347,7 +4347,7 @@ import * as info from "./info"; console.log(info); ``` -The following would get logged: +Het volgende zou gelogd worden: ```javascript { @@ -4357,13 +4357,13 @@ The following would get logged: } ``` -For the `sum` example, it means that the imported value `sum` looks like this: +Voor het `sum` voorbeeld betekent dit dat de geïmporteerde waarde `sum` eruit ziet als: ```javascript { default: function sum(x) { return x + x } } ``` -We can invoke this function, by calling `sum.default` +We kunnen deze functie aanvoeren door `sum.default` aan te roepen.

From a1e69d1b39e67e3ab4b89ac55c312054a81864ca Mon Sep 17 00:00:00 2001 From: Tarabass Date: Sun, 16 Feb 2020 12:16:33 +0100 Subject: [PATCH 566/915] Question 135 --- nl-NL/README.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/nl-NL/README.md b/nl-NL/README.md index 53873ee5..882bbe97 100644 --- a/nl-NL/README.md +++ b/nl-NL/README.md @@ -4394,13 +4394,13 @@ person.name; #### Antwoord: C -With a Proxy object, we can add custom behavior to an object that we pass to it as the second argument. In tis case, we pass the `handler` object which contained to properties: `set` en `get`. `set` gets invoked whenever we _set_ property values, `get` gets invoked whenever we _get_ (access) property values. +Met het Proxy object kunnen we functionaliteit toevoegen aan een object als we dit meegeven als tweede argument. In dit geval geven we het object `handler` mee wat de volgende properties bevat: `set` en `get`. `set` wordt aangeroepen elke keer als we een waarde van een propertie _zetten_. `get` wordt aangeroepen elke keer als we een propertie waarde opvragen. -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. +Het eerste argument is een leeg object `{}` wat de waarde is van `person`. Aan dit object wordt de functionaliteit toegevoegd die gespecificeerd is in het object `handler`. Als we een propertie toevoegen aan het object `person` wordt `set` uitgevoerd. Als we een propertie benaderen op het object `person` wordt `get` uitgevoerd. -First, we added a new property `name` to the proxy object (`person.name = "Lydia"`). `set` gets invoked, en logs `"Added a new property!"`. +Als eerste voegen we de propertie `name` toe aan het proxy object (`person.name = "Lydia"`). `set` wordt aangeroepen en `"Added a new property!"` wordt gelogd. -Then, we access a property value on the proxy object, the `get` property on the handler object got invoked. `"Accessed a property!"` gets logged. +Dan vragen we de waarde van een propertie op het proxy object op en `get` van het `handler` object wordt aangeroepen. `"Accessed a property!"` wordt gelogd.

From 7f2bc689dfba97aea796f650953f25b80d97070b Mon Sep 17 00:00:00 2001 From: Tarabass Date: Sun, 16 Feb 2020 12:17:55 +0100 Subject: [PATCH 567/915] Question 136 --- nl-NL/README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/nl-NL/README.md b/nl-NL/README.md index 882bbe97..b79e556a 100644 --- a/nl-NL/README.md +++ b/nl-NL/README.md @@ -4425,9 +4425,9 @@ Object.seal(person); #### Antwoord: A -With `Object.seal` we can prevent new properies from being _added_, or existing properties to be _removed_. +Met `Object.seal` kunnen we voorkomen dat nieuwe properties kunnen worden _toegevoegd_ of bestaande properties worden _verwijderd_. -However, you can still modify the value of existing properties. +Echter kunnen van de bestaande properties nog steeds aanpassen.

From 04296b4c4a2c6bde7fdf1ad647119d9b1a197079 Mon Sep 17 00:00:00 2001 From: Tarabass Date: Sun, 16 Feb 2020 12:20:43 +0100 Subject: [PATCH 568/915] Question 137 --- nl-NL/README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/nl-NL/README.md b/nl-NL/README.md index b79e556a..f2685d1e 100644 --- a/nl-NL/README.md +++ b/nl-NL/README.md @@ -4457,9 +4457,9 @@ Object.freeze(person); #### Antwoord: C -The `Object.freeze` method _freezes_ an object. No properties can be added, modified, or removed. +De `Object.freeze` methode _bevriest_ een object. Geen enkele propertie van worden toegevoegd, aangepast worden of worden verwijderd. -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, en can be modified. +Echter wordt het object enkel _oppervlakkig_ bevroren wat betekent dat alleen _directe_ properties bevroren zijn. Als de propertie een ander object is, zoals `address` in dit geval, zijn de properties van dat object niet bevroren en kunnen wel worden aangepast.

From d6122efa987f931f25c75516ff2f3c0d9586d09f Mon Sep 17 00:00:00 2001 From: Tarabass Date: Sun, 16 Feb 2020 12:27:03 +0100 Subject: [PATCH 569/915] Question 138 --- nl-NL/README.md | 40 ++++------------------------------------ 1 file changed, 4 insertions(+), 36 deletions(-) diff --git a/nl-NL/README.md b/nl-NL/README.md index f2685d1e..254c0e93 100644 --- a/nl-NL/README.md +++ b/nl-NL/README.md @@ -4457,7 +4457,7 @@ Object.freeze(person); #### Antwoord: C -De `Object.freeze` methode _bevriest_ een object. Geen enkele propertie van worden toegevoegd, aangepast worden of worden verwijderd. +De `Object.freeze` methode _bevriest_ een object. Geen enkele propertie van worden toegevoegd, aangepast worden of worden verwijderd. Echter wordt het object enkel _oppervlakkig_ bevroren wat betekent dat alleen _directe_ properties bevroren zijn. Als de propertie een ander object is, zoals `address` in dit geval, zijn de properties van dat object niet bevroren en kunnen wel worden aangepast. @@ -4466,39 +4466,7 @@ Echter wordt het object enkel _oppervlakkig_ bevroren wat betekent dat alleen _d --- -###### 138. Welke van onderstaande zal het `person` object aanpassen? - -```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" }` - -
Antwoord -

- -#### Antwoord: 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, en can be modified. - -

-
- ---- - -###### 139. Wat is de uitkomst? +###### 138. Wat is de uitkomst? ```javascript const add = x => x + x; @@ -4521,9 +4489,9 @@ myFunc(3); #### Antwoord: A -First, we invoked `myFunc()` without passing any arguments. Since we didn't pass arguments, `num` en `value` got their default values: num is `2`, en `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`. +Eerst roepen we de functie `myFunc()` aan zonder argumenten mee te geven. Omdat we geen argumenten meegeven, `num` en `value` behouden hun standaard waarde: num is `2`, en `value` de geretourneerde waarde van de functie `add`. Aan de functie `add` geven we `num` als argument mee, wat de waarde `2` heeft. `add` retourneert `4` wat de waarde is van `value`. -Then, we invoked `myFunc(3)` en 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`. +Daarna roepen we de functie `myFunc(3)` aan het geven `3` meet als de waarde voor het argument `num`. We geven het argument `value` niet mee. Omdat we geen waarde meegeven voor het argument `value` krijgt het de standaard waarde: het retourneert de waarde van de `add` functie. Aan de functie `add` geven we `num` mee, wat de waarde `3` bevat. `add` retourneert `6` wat op dat moment de waarde is van `value`.

From b0fb3e655b35cf21a626cd1086c5b7fe43c549f7 Mon Sep 17 00:00:00 2001 From: Tarabass Date: Sun, 16 Feb 2020 12:29:11 +0100 Subject: [PATCH 570/915] Question 139 --- nl-NL/README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/nl-NL/README.md b/nl-NL/README.md index 254c0e93..67de1ebb 100644 --- a/nl-NL/README.md +++ b/nl-NL/README.md @@ -4498,7 +4498,7 @@ Daarna roepen we de functie `myFunc(3)` aan het geven `3` meet als de waarde voo --- -###### 140. Wat is de uitkomst? +###### 139. Wat is de uitkomst? ```javascript class Counter { @@ -4529,7 +4529,7 @@ console.log(counter.#number) #### Antwoord: 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 kunnen we private variabelen toevoegen aan classes door gebruik te maken van `#`. We kunnen deze variabelen niet benaderen van buitenaf. Wanneer we `counter.#number` proberen te loggen wordt er een SuntaxError gegooid: we cannot acccess it outside the `Counter` class!

From 8798f41b0b42f8332e55b686012cd93acae04c60 Mon Sep 17 00:00:00 2001 From: Tarabass Date: Sun, 16 Feb 2020 12:33:40 +0100 Subject: [PATCH 571/915] Question 140 --- nl-NL/README.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/nl-NL/README.md b/nl-NL/README.md index 67de1ebb..259b4fad 100644 --- a/nl-NL/README.md +++ b/nl-NL/README.md @@ -4536,7 +4536,7 @@ In ES2020 kunnen we private variabelen toevoegen aan classes door gebruik te mak --- -###### 141. Wat is de uitkomst? +###### 140. Wat is de uitkomst? ```javascript const teams = [ @@ -4571,9 +4571,9 @@ obj.next(); // { value: "Lisa", done: false } #### Antwoord: 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*`. +Om te kunnen itereren over de `members` in elk element in de array `teams` moeten we `teams[i].members` meegeven aan de `getMembers` generator functie. De generator functie retourneert een generator object. Om te kunnen itereren over elk element in het generator object moeten we `yield*` gebruiken. -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. +Als we `yield`, `return yield`, of `return` hadden geschreven zou de gehele generator functie geretourneerd worden tijdens de eerste keer dat we de `next` methode aanriepen.

From 26f6a5f5115ef6ff103214702d39241d06d9ea26 Mon Sep 17 00:00:00 2001 From: Tarabass Date: Sun, 16 Feb 2020 12:40:51 +0100 Subject: [PATCH 572/915] Question 141 --- nl-NL/README.md | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/nl-NL/README.md b/nl-NL/README.md index 259b4fad..f207b04c 100644 --- a/nl-NL/README.md +++ b/nl-NL/README.md @@ -4580,7 +4580,7 @@ Als we `yield`, `return yield`, of `return` hadden geschreven zou de gehele gene --- -###### 142. Wat is de uitkomst? +###### 141. Wat is de uitkomst? ```javascript const person = { @@ -4610,15 +4610,15 @@ console.log(person.hobbies); #### Antwoord: C -The `addHobby` function receives two arguments, `hobby` en `hobbies` with the default value of the `hobbies` array on the `person` object. +De functie `addHobby` ontvangt twee arguemnten, `hobby` en `hobbies` met als standaard waarde de waarde van de array `hobbies` op het object `person`. -First, we invoke the `addHobby` function, en pass `"running"` as the value for `hobby` en 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. +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. -Then, we invoke the `addHobby` function, en 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. +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`. -Last, we invoke the `addHobby` function, en pass `"bdaking"` as the value for `hobby`, en the `person.hobbies` array as the value for `hobbies`. We push the hobby `baking` to the `person.hobbies` array. +Als laatste roepen we de functie `addHobby` aan en geven `"baking"` als de waarde voor `hobby` en de array `person.hobbies` als de waarde voor `hobbies`. We pushen de hobby `baking` naar de array `person.hobbies`. -After pushing `dancing` en `baking`, the value of `person.hobbies` is `["coding", "dancing", "baking"]` +Na het pushen van `dancing` en `baking` is de waarde van `person.hobbies` gelijk aan `["coding", "dancing", "baking"]`.

From 517b2e28d27e0769307510e0663dc9acaa2be40d Mon Sep 17 00:00:00 2001 From: Tarabass Date: Sun, 16 Feb 2020 12:44:24 +0100 Subject: [PATCH 573/915] Question 142 --- nl-NL/README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/nl-NL/README.md b/nl-NL/README.md index f207b04c..00a4d5b7 100644 --- a/nl-NL/README.md +++ b/nl-NL/README.md @@ -4625,7 +4625,7 @@ Na het pushen van `dancing` en `baking` is de waarde van `person.hobbies` gelijk --- -###### 143. Wat is de uitkomst? +###### 142. Wat is de uitkomst? ```javascript class Bird { @@ -4654,7 +4654,7 @@ const pet = new Flamingo(); #### Antwoord: 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, en logs `"I'm a bird. 🦢"`. +We declareren de variabele `pet`, wat een instantie is van de class `Flamingo`. Wanneer we deze instantie instantiëren wordt de `constructor` op `Flamingo` aangeroepen. Als eerste wordt `"I'm pink. 🌸"` gelogd, waarna we `super()` aanroepen. `super()` roept de constructor van de bovenliggende class aan, `Bird` in dit geval. De constructor op `Bird` wordt aangeroepen en logt `"I'm a bird. 🦢"`.

From 37aafa0fb45636f38ef02c751db3d458c0d0acd4 Mon Sep 17 00:00:00 2001 From: Tarabass Date: Sun, 16 Feb 2020 12:47:00 +0100 Subject: [PATCH 574/915] Question 143 --- nl-NL/README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/nl-NL/README.md b/nl-NL/README.md index 00a4d5b7..72fe813d 100644 --- a/nl-NL/README.md +++ b/nl-NL/README.md @@ -4661,7 +4661,7 @@ We declareren de variabele `pet`, wat een instantie is van de class `Flamingo`. --- -###### 144. Welke van onderstaande opties zal resulteren in een error? +###### 143. Welke van onderstaande opties zal resulteren in een error? ```javascript const emojis = ["🎄", "🎅🏼", "🎁", "⭐"]; @@ -4682,7 +4682,7 @@ const emojis = ["🎄", "🎅🏼", "🎁", "⭐"]; #### Antwoord: 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 propeties on the `emojis` array can be modified, for example by pushing new values, splicing them, or setting the length of the array to 0. +Het keyword `const` betekent simpelweg dat we de waarde van de variabele niet opnieuw kunnen _declareren_. Het is _read-only_. Echter, de waarde zelf is niet onaanpasbaar. De properties van de array `emojis` kunnen worden aangepast, bijvoorbeeld door nieuwe waarden te pushen, te splicen of door de lengte van de array op 0 te zetten.

From 9b0da14f3b95f9f2714487f814d1be04e9740245 Mon Sep 17 00:00:00 2001 From: Tarabass Date: Sun, 16 Feb 2020 12:51:25 +0100 Subject: [PATCH 575/915] Question 144 --- nl-NL/README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/nl-NL/README.md b/nl-NL/README.md index 72fe813d..635dcd30 100644 --- a/nl-NL/README.md +++ b/nl-NL/README.md @@ -4689,7 +4689,7 @@ Het keyword `const` betekent simpelweg dat we de waarde van de variabele niet op --- -###### 145. Wat moeten we aan het `person` object toevoegen om `["Lydia Hallie", 21]` als uitkomst te krijgen van `[...person]`? +###### 144. Wat moeten we aan het `person` object toevoegen om `["Lydia Hallie", 21]` als uitkomst te krijgen van `[...person]`? ```javascript const person = { @@ -4710,7 +4710,7 @@ const person = { #### Antwoord: 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)`. +Objecten zijn standaard niet itereerbaar. Een _iterable_ is een _iterable_ als het _iterator protocol_ aanwezig is. We kunnen dit met de iterator symbol `[Symbol.iterator]` handmatig toevoegen, wat een generator object zal moeten teruggeven. Bijvoorbeeld door het een generator functie te maken: `*[Symbol.iterator]() {}`. Deze generator functie moet de `Object.values` afgeven van het object `person` als we de array `["Lydia Hallie", 21]`: `yield* Object.values(this)` terug willen geven.

\ No newline at end of file From 8614b5a40010b462cf3d27ad9ebd6427054ea1da Mon Sep 17 00:00:00 2001 From: mingrui <474562318@qq.com> Date: Fri, 28 Feb 2020 20:41:57 +0800 Subject: [PATCH 576/915] fix: fix a typo in #122, remove duplicate question --- zh-CN/README-zh_CN.md | 48 ++++++++----------------------------------- 1 file changed, 8 insertions(+), 40 deletions(-) diff --git a/zh-CN/README-zh_CN.md b/zh-CN/README-zh_CN.md index 0ab3735b..5869c0e2 100644 --- a/zh-CN/README-zh_CN.md +++ b/zh-CN/README-zh_CN.md @@ -3930,7 +3930,7 @@ console.log(!typeof name === "string"); `typeof name` 返回 `"string"`。字符串 `"string"` 是一个 truthy 的值,因此 `!typeof name` 返回一个布尔值 `false`。 `false === "object"` 和 `false === "string"` 都返回 `false`。 -(如果我们想检测一个值的类型,我们不应该用 `!==` 而不是 `!typeof`) +(如果我们想检测一个值的类型,我们应该用 `!==` 而不是 `!typeof`)

@@ -4458,39 +4458,7 @@ Object.freeze(person); --- -###### 138. 以下哪一项会对对象 `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` 中的属性没有被冻结,仍然可以被修改。 - -

-
- ---- - -###### 139. 输出什么? +###### 138. 输出什么? ```javascript const add = x => x + x; @@ -4522,7 +4490,7 @@ myFunc(3); --- -###### 140. 输出什么? +###### 139. 输出什么? ```javascript class Counter { @@ -4560,7 +4528,7 @@ console.log(counter.#number) --- -###### 141. 选择哪一个? +###### 140. 选择哪一个? ```javascript const teams = [ @@ -4604,7 +4572,7 @@ obj.next(); // { value: "Lisa", done: false } --- -###### 142. 输出什么? +###### 141. 输出什么? ```javascript const person = { @@ -4649,7 +4617,7 @@ pushing `dancing` 和 `baking` 之后,`person.hobbies` 的值为 `["coding", " --- -###### 143. 输出什么? +###### 142. 输出什么? ```javascript class Bird { @@ -4685,7 +4653,7 @@ const pet = new Flamingo(); --- -###### 144. 哪一个选项会导致报错? +###### 143. 哪一个选项会导致报错? ```javascript const emojis = ["🎄", "🎅🏼", "🎁", "⭐"]; @@ -4713,7 +4681,7 @@ const emojis = ["🎄", "🎅🏼", "🎁", "⭐"]; --- -###### 145. 我们需要向对象 `person` 添加什么,以致执行 `[...person]` 时获得形如 `["Lydia Hallie", 21]` 的输出? +###### 144. 我们需要向对象 `person` 添加什么,以致执行 `[...person]` 时获得形如 `["Lydia Hallie", 21]` 的输出? ```javascript const person = { From 1c1f34cfd13747f6b368b892ee231316b7cdc1ce Mon Sep 17 00:00:00 2001 From: Reg Date: Mon, 2 Mar 2020 09:40:46 +0800 Subject: [PATCH 577/915] Correct No.140 question As title. --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index a4870a77..d2d19f1e 100644 --- a/README.md +++ b/README.md @@ -4534,7 +4534,7 @@ In ES2020, we can add private variables in classes by using the `#`. We cannot a --- -###### 140. What's the output? +###### 140. What's missing? ```javascript const teams = [ From 09744c5fb721a92198f5ae6d57c064fdc8aa7769 Mon Sep 17 00:00:00 2001 From: carpacciao <43958708+carpacciao@users.noreply.github.com> Date: Wed, 4 Mar 2020 14:47:21 +0100 Subject: [PATCH 578/915] Correction du nom de la constante "numberes". (line - 1806) Faute de frappe dans le code de la question 59. --- 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 9af4c3b6..3f42160f 100644 --- a/fr-FR/README_fr-FR.md +++ b/fr-FR/README_fr-FR.md @@ -1803,7 +1803,7 @@ La variable `name` a été déclarée avec un mot-clé `const`. Par conséquent, ```javascript const numbers = [1, 2, 3, 4, 5]; -const [y] = numberes; +const [y] = numbers; console.log(y); ``` From 216914df05d263b1a4c4ccfea1900f075baa17e0 Mon Sep 17 00:00:00 2001 From: Reg Date: Thu, 12 Mar 2020 09:46:18 +0800 Subject: [PATCH 579/915] Update README.md --- en-EN/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/en-EN/README.md b/en-EN/README.md index 1f408fa5..55090d3d 100644 --- a/en-EN/README.md +++ b/en-EN/README.md @@ -4534,7 +4534,7 @@ In ES2020, we can add private variables in classes by using the `#`. We cannot a --- -###### 140. What's the output? +###### 140. What's the missing? ```javascript const teams = [ From 34c4f4f757887f684acd55d0940ad2157c12662a Mon Sep 17 00:00:00 2001 From: Nusendra Hanggarawan Date: Fri, 13 Mar 2020 09:51:30 +0700 Subject: [PATCH 580/915] improve: added link to indonesian in both english readme --- README.md | 869 +++++++++++++++++++++++------------------------ en-EN/README.md | 870 ++++++++++++++++++++++++------------------------ 2 files changed, 871 insertions(+), 868 deletions(-) diff --git a/README.md b/README.md index d3d60814..73a95844 100644 --- a/README.md +++ b/README.md @@ -2,14 +2,15 @@

JavaScript Questions

- --- +--- + +I post multiple choice JavaScript questions on my [Instagram](https://www.instagram.com/theavocoder) **stories**, which I'll also post here! Last updated: December 24th - I post multiple choice JavaScript questions on my [Instagram](https://www.instagram.com/theavocoder) **stories**, which I'll also post here! Last updated: December 24th +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! 😊
+Instagram || Twitter || LinkedIn || Blog - Feel free to reach out to me! 😊
- Instagram || Twitter || LinkedIn || Blog --- @@ -17,22 +18,23 @@
See 16 Available Translations 🇪🇸🇮🇹🇩🇪 🇫🇷🇷🇺🇨🇳🇵🇹

-* [English](./en-EN/README.md) -* [العربية](./ar-AR/README_AR.md) -* [اللغة العامية - Egyptian Arabic](./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) -* [日本語](./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) -* [Українська мова](./ua-UA/README-ua_UA.md) -* [Tiếng Việt](./vi-VI/README-vi.md) -* [中文版本](./zh-CN/README-zh_CN.md) -* [Türkçe](./tr-TR/README-tr_TR.md) -* [ไทย](./th-TH/README-th_TH.md) +- [English](./en-EN/README.md) +- [العربية](./ar-AR/README_AR.md) +- [اللغة العامية - Egyptian Arabic](./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) +- [日本語](./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) +- [Українська мова](./ua-UA/README-ua_UA.md) +- [Tiếng Việt](./vi-VI/README-vi.md) +- [中文版本](./zh-CN/README-zh_CN.md) +- [Türkçe](./tr-TR/README-tr_TR.md) +- [ไทย](./th-TH/README-th_TH.md) +- [Indonesia](./id-ID/README.md)

@@ -45,7 +47,7 @@ function sayHi() { console.log(name); console.log(age); - var name = "Lydia"; + var name = 'Lydia'; let age = 21; } @@ -109,7 +111,7 @@ const shape = { diameter() { return this.radius * 2; }, - perimeter: () => 2 * Math.PI * this.radius + perimeter: () => 2 * Math.PI * this.radius, }; console.log(shape.diameter()); @@ -141,7 +143,7 @@ There is no value `radius` on that object, which returns `undefined`. ```javascript +true; -!"Lydia"; +!'Lydia'; ``` - A: `1` and `false` @@ -166,12 +168,12 @@ 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", - small: true + name: 'Mickey', + small: true, }; ``` @@ -198,15 +200,14 @@ 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); ``` @@ -276,13 +277,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` @@ -332,10 +333,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! @@ -365,7 +366,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}`; }; @@ -406,8 +407,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); @@ -477,7 +478,7 @@ function sum(a, b) { return a + b; } -sum(1, "2"); +sum(1, '2'); ``` - A: `NaN` @@ -544,7 +545,7 @@ function getPersonInfo(one, two, three) { console.log(three); } -const person = "Lydia"; +const person = 'Lydia'; const age = 21; getPersonInfo`${person} is ${age} years old`; @@ -571,9 +572,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`); } @@ -633,7 +634,7 @@ The rest parameter (`...args`.) lets us "collect" all remaining arguments into a ```javascript function getAge() { - "use strict"; + 'use strict'; age = 21; console.log(age); } @@ -661,7 +662,7 @@ With `"use strict"`, you can make sure that you don't accidentally declare globa ###### 21. What's value of `sum`? ```javascript -const sum = eval("10*10+5"); +const sum = eval('10*10+5'); ``` - A: `105` @@ -684,7 +685,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. @@ -737,12 +738,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); ``` @@ -768,7 +769,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); ``` @@ -837,10 +838,10 @@ 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'; name.giveLydiaPizza(); ``` @@ -866,8 +867,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; @@ -899,9 +900,9 @@ Then, we log `a[b]`, which is actually `a["object Object"]`. We just set that to ###### 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(); @@ -1008,7 +1009,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}`; @@ -1060,6 +1061,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`, and `symbol`. `"function"` is not a type, since functions are objects, it's of type `"object"`. +

@@ -1070,8 +1072,8 @@ FYI: there are only 7 built-in types: `null`, `undefined`, `boolean`, `number`, ```javascript 0; new Number(0); -(""); -(" "); +(''); +(' '); new Boolean(false); undefined; ``` @@ -1222,7 +1224,7 @@ What differentiates a primitive from an object is that primitives do not have an (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 @@ 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"]` @@ -1359,11 +1361,11 @@ 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)); @@ -1389,7 +1391,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; @@ -1429,8 +1431,8 @@ We are only modifying the value of the `person` variable, and not the first elem ```javascript const person = { - name: "Lydia", - age: 21 + name: 'Lydia', + age: 21, }; for (const item in person) { @@ -1458,7 +1460,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"` @@ -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` @@ -1511,7 +1513,7 @@ Only the first numbers in the string is returned. Based on the _radix_ (the seco ```javascript [1, 2, 3].map(num => { - if (typeof num === "number") return; + 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(); @@ -1691,7 +1693,7 @@ 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; @@ -1785,7 +1787,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); @@ -1856,7 +1858,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); @@ -1882,9 +1884,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)); @@ -1913,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 + health: 90, }; -const data = JSON.stringify(settings, ["level", "health"]); +const data = JSON.stringify(settings, ['level', 'health']); console.log(data); ``` @@ -2006,9 +2008,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`.

@@ -2031,17 +2033,18 @@ The fourth time, we pass the `value` object again. `x.number` was previously mod #### Answer: 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` 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 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. +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. +

@@ -2057,7 +2060,7 @@ class Dog { }; class Labrador extends Dog { - // 1 + // 1 constructor(name, size) { this.size = size; } @@ -2071,7 +2074,7 @@ class Labrador extends Dog { super(name); this.size = size; } - // 4 + // 4 constructor(name, size) { this.name = name; this.size = size; @@ -2092,9 +2095,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`, 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. -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.

@@ -2125,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.

@@ -2135,9 +2139,9 @@ This is a difference between `require()` in CommonJS and `import`! With `require ###### 68. What's the output? ```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,7 +2154,7 @@ console.log(Symbol('foo') === Symbol('foo')) #### Answer: 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`.

@@ -2160,15 +2164,15 @@ Every Symbol is entirely unique. The purpose of the argument passed to the Symbo ###### 69. What's the output? ```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"`,
Answer

@@ -2187,7 +2191,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: `"🥑💻"` @@ -2211,11 +2215,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(); @@ -2283,7 +2287,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(); @@ -2320,7 +2324,7 @@ function addToList(item, list) { return list.push(item); } -const result = addToList("apple", ["banana"]); +const result = addToList('apple', ['banana']); console.log(result); ``` @@ -2380,7 +2384,7 @@ 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 { name: myName } = { name: 'Lydia' }; console.log(name); ``` @@ -2481,21 +2485,21 @@ 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) + 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: "🍫"}` +- 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

@@ -2508,7 +2512,7 @@ With a _for-in_ loop, we can iterate over **enumerable** properties. In an array 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. +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.

@@ -2518,14 +2522,14 @@ With a _for-of_ loop, we can iterate over **iterables**. An array is an iterable ###### 80. What is the output? ```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]`
Answer

@@ -2534,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`, and `1 / 2` returns `0.5`. +The element will be equal to the returned value. `1 + 2` returns `3`, `1 * 2` returns `2`, and `1 / 2` returns `0.5`.

@@ -2545,16 +2549,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, ` +- A: `Hi there,` - B: `Hi there, undefined` - C: `Hi there, null` -- D: `ReferenceError` +- D: `ReferenceError`
Answer

@@ -2577,21 +2581,21 @@ 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 - } - } + 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 `"😍"` @@ -2608,7 +2612,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. -

@@ -2618,14 +2621,14 @@ With the `call` method, we can change the object to which the `this` keyword ref ```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 }` @@ -2638,13 +2641,13 @@ console.log(person) #### Answer: 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.

@@ -2656,15 +2659,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."` @@ -2689,13 +2692,13 @@ Variables with the `const` and `let` keyword are _block-scoped_. A block is anyt ```javascript fetch('https://www.website.com/api/user/1') .then(res => res.json()) - .then(res => console.log(res)) + .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.
Answer

@@ -2743,7 +2746,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: `"""` @@ -2769,10 +2772,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` @@ -2785,9 +2788,9 @@ sum(10) #### Answer: 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.

@@ -2797,14 +2800,14 @@ If you're trying to set a default parameter's value equal to a parameter which i ###### 89. What's the output? ```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" }` @@ -2817,9 +2820,9 @@ 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 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.

@@ -2831,12 +2834,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"` @@ -2853,11 +2856,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"`.

@@ -2867,9 +2870,9 @@ Calling a function constructor with `new` results in the creation of an instance ###### 91. What's the output? ```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]` @@ -2882,7 +2885,7 @@ console.log(newList.push(5)) #### Answer: 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. @@ -2895,17 +2898,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` @@ -2914,7 +2918,7 @@ console.log(giveLydiaChocolate.prototype) #### Answer: 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`.

@@ -2925,17 +2929,17 @@ Regular functions, such as the `giveLydiaPizza` function, have a `prototype` pro ```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` and `age` `21` -- B: `["name", "Lydia"]` and `["age", 21]` +- B: `["name", "Lydia"]` and `["age", 21]` - C: `["name", "age"]` and `undefined` - D: `Error` @@ -2946,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"`, 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. @@ -2969,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` @@ -2978,17 +2982,18 @@ getItems(["banana", "apple"], "pear", "orange") #### Answer: 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' ]` +

@@ -2998,17 +3003,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` and `b is bigger`, `3` @@ -3021,13 +3023,13 @@ console.log(nums(1, 2)) #### Answer: 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! @@ -3042,18 +3044,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"` @@ -3077,11 +3079,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'}` and `["{Symbol('a')"]` @@ -3128,13 +3130,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` 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. +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 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`. @@ -3146,9 +3148,9 @@ Since no value gets returned in this case, the function returns `undefined`. ###### 99. What's the output? ```javascript -const name = "Lydia" +const name = 'Lydia'; -console.log(name()) +console.log(name()); ``` - A: `SyntaxError` @@ -3161,11 +3163,11 @@ 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, 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.

@@ -3179,7 +3181,7 @@ ReferenceErrors get thrown when JavaScript isn't able to find a reference to a v // 🎉✨ This is my 100th question! ✨🎉 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` @@ -3204,11 +3206,11 @@ You should${'' && `n't`} see a therapist after so much JavaScript lol` ###### 101. What's the value of 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` `[]` @@ -3237,20 +3239,20 @@ 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(await myPromise()); + console.log('second'); } -firstFunction() -secondFunction() +firstFunction(); +secondFunction(); ``` - A: `I have resolved!`, `second` and `I have resolved!`, `second` @@ -3265,13 +3267,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` and `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` 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. +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 befoer 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.

@@ -3281,14 +3283,14 @@ This means that it waited for the `myPromise` to resolve with the value `I have ###### 103. What's the value of 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); } ``` @@ -3302,11 +3304,11 @@ for (let item of set) { #### Answer: 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 `+` 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"`. +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"`. @@ -3318,7 +3320,7 @@ However, the second one is a string `"Lydia"`. `"Lydia"` is a string and `2` is ###### 104. What's its value? ```javascript -Promise.resolve(5) +Promise.resolve(5); ``` - A: `5` @@ -3333,7 +3335,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`.

@@ -3345,15 +3347,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!` @@ -3366,13 +3368,13 @@ compareMembers(person) #### Answer: 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.

@@ -3388,11 +3390,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` @@ -3405,11 +3407,11 @@ console.log(colorConfig.colors[1]) #### Answer: 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 `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. +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.

@@ -3419,7 +3421,7 @@ JavaScript interprets (or unboxes) statements. When we use bracket notation, it ###### 107. What's its value? ```javascript -console.log('❤️' === '❤️') +console.log('❤️' === '❤️'); ``` - A: `true` @@ -3430,7 +3432,7 @@ console.log('❤️' === '❤️') #### Answer: 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.

@@ -3440,19 +3442,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`
Answer @@ -3460,7 +3462,7 @@ emojis.splice(1, 2, '✨') #### Answer: 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. +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. @@ -3472,17 +3474,17 @@ With `splice` method, we modify the original array by deleting, replacing or add ###### 109. What's the output? ```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`
Answer @@ -3490,7 +3492,7 @@ console.log(food) #### Answer: 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 act by reference +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 act 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) @@ -3504,7 +3506,7 @@ Then, we change the value of the `favoriteFood` property on the `info` object. T ###### 110. What does this method do? ```javascript -JSON.parse() +JSON.parse(); ``` - A: Parses JSON to a JavaScript value @@ -3517,20 +3519,20 @@ JSON.parse() #### Answer: A -With the `JSON.parse()` method, we can parse JSON string to a JavaScript value. +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 +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' } ```

@@ -3538,17 +3540,17 @@ JSON.parse(jsonArray) // { name: 'Lydia' } --- -###### 111. What's the output? +###### 111. What's the output? ```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 @@ -3561,20 +3563,20 @@ getName() #### Answer: 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'`. +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`. +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`. +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) + console.log(name); } -getName() // Lydia +getName(); // Lydia ```

@@ -3593,11 +3595,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` and `a` @@ -3615,17 +3617,17 @@ With the `yield` keyword, we `yield` values in a generator function. With the `y 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 +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. +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 +console.log(two.next().value); // 'a' +console.log(two.next().value); // 'b' +console.log(two.next().value); // 'c' +console.log(two.next().value); // undefined ```

@@ -3636,7 +3638,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` @@ -3649,7 +3651,7 @@ console.log(`${(x => x)('I love')} to program`) #### Answer: 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`. +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`.

@@ -3661,11 +3663,11 @@ Expressions within template literals are evaluated first. This means that the st ```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 @@ -3688,17 +3690,17 @@ Normally when we set objects equal to `null`, those objects get _garbage collect ###### 115. Which method(s) will return the value `'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 @@ -3711,10 +3713,10 @@ myMap.get(() => 'greeting') #### Answer: 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!' }`. +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 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.

@@ -3725,20 +3727,20 @@ When adding a key/value pair using the `set` method, the key will be the value o ```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}` @@ -3751,7 +3753,7 @@ console.log(person) #### Answer: 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. +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 }`. @@ -3766,7 +3768,7 @@ Then, we invoke the `changeAgeAndName` function, however we don't pass a paramet ```javascript function sumValues(x, y, z) { - return x + y + z; + return x + y + z; } ``` @@ -3791,7 +3793,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,15 +3819,15 @@ With the `+=` operand, we're incrementing the value of `num` by `1`. `num` had t ```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); @@ -3859,12 +3861,12 @@ 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!`); + console.log(`We don't have to buy bananas!`); } ``` @@ -3889,10 +3891,10 @@ We passed the condition `groceries.indexOf("banana")` to the if-statement. `groc ```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); @@ -3918,10 +3920,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` @@ -3947,8 +3949,8 @@ console.log(!typeof name === "string"); ```javascript const add = x => y => z => { - console.log(x, y, z); - return x + y + z; + console.log(x, y, z); + return x + y + z; }; add(4)(5)(6); @@ -3975,16 +3977,16 @@ The `add` function returns an arrow function, which returns an arrow function, w ```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); + } })(); ``` @@ -4009,7 +4011,7 @@ The generator function `range` returns an async object with promises for each it ```javascript const myFunc = ({ x, y, z }) => { - console.log(x, y, z); + console.log(x, y, z); }; myFunc(1, 2, 3); @@ -4072,8 +4074,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); ``` @@ -4098,7 +4100,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)); @@ -4133,8 +4135,8 @@ With the `isNaN` method, you can check if the value you pass is not a number. `n const randomValue = 21; function getInfo() { - console.log(typeof randomValue); - const randomValue = "Lydia Hallie"; + console.log(typeof randomValue); + const randomValue = 'Lydia Hallie'; } getInfo(); @@ -4160,16 +4162,16 @@ Variables declared with the `const` keyword are not referencable before their in ###### 130. What's the output? ```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!'); + } })(); ``` @@ -4193,7 +4195,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)); ``` @@ -4219,13 +4221,13 @@ With the `flat` method, we can create a new, flattened array. The depth of the f ```javascript class Counter { - constructor() { - this.count = 0; - } + constructor() { + this.count = 0; + } - increment() { - this.count++; - } + increment() { + this.count++; + } } const counterOne = new Counter(); @@ -4266,19 +4268,19 @@ 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!"); + 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(); @@ -4315,11 +4317,11 @@ We get to the last line of `funcTwo`, which logs `Last line!` to the console. No ```javascript // sum.js export default function sum(x) { - return x + x; + return x + x; } // index.js -import * as sum from "./sum"; +import * as sum from './sum'; ``` - A: `sum(4)` @@ -4336,12 +4338,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 +4374,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 +4410,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,10 +4438,10 @@ However, you can still modify the value of existing properties. ```javascript const person = { - name: "Lydia Hallie", - address: { - street: "100 Main St" - } + name: 'Lydia Hallie', + address: { + street: '100 Main St', + }, }; Object.freeze(person); @@ -4468,10 +4470,10 @@ However, it only _shallowly_ freezes the object, meaning that only _direct_ prop ```javascript const person = { - name: "Lydia Hallie", - address: { - street: "100 Main St" - } + name: 'Lydia Hallie', + address: { + street: '100 Main St', + }, }; Object.freeze(person); @@ -4502,7 +4504,7 @@ However, it only _shallowly_ freezes the object, meaning that only _direct_ prop const add = x => x + x; function myFunc(num = 2, value = add(num)) { - console.log(num, value); + console.log(num, value); } myFunc(); @@ -4570,20 +4572,20 @@ 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) { - 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); @@ -4614,18 +4616,18 @@ 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) { - hobbies.push(hobby); - return hobbies; + hobbies.push(hobby); + return hobbies; } -addHobby("running", []); -addHobby("dancing"); -addHobby("baking", person.hobbies); +addHobby('running', []); +addHobby('dancing'); +addHobby('baking', person.hobbies); console.log(person.hobbies); ``` @@ -4659,16 +4661,16 @@ After pushing `dancing` and `baking`, the value of `person.hobbies` is `["coding ```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(); @@ -4694,11 +4696,11 @@ We create the variable `pet` which is an instance of the `Flamingo` class. When ###### 144. 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; ``` @@ -4744,4 +4746,3 @@ Objects aren't iterable by default. An iterable is an iterable if the iterator p

- diff --git a/en-EN/README.md b/en-EN/README.md index ddf67054..e4f393f7 100644 --- a/en-EN/README.md +++ b/en-EN/README.md @@ -2,14 +2,15 @@

JavaScript Questions

- --- +--- + +I post multiple choice JavaScript questions on my [Instagram](https://www.instagram.com/theavocoder) **stories**, which I'll also post here! Last updated: December 24th - I post multiple choice JavaScript questions on my [Instagram](https://www.instagram.com/theavocoder) **stories**, which I'll also post here! Last updated: December 24th +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! 😊
+Instagram || Twitter || LinkedIn || Blog - Feel free to reach out to me! 😊
- Instagram || Twitter || LinkedIn || Blog --- @@ -17,22 +18,23 @@
See 16 Available Translations 🇪🇸🇮🇹🇩🇪 🇫🇷🇷🇺🇨🇳🇵🇹

-* [English](../en-EN/README.md) -* [العربية](../ar-AR/README_AR.md) -* [اللغة العامية - Egyptian Arabic](../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) -* [日本語](../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) -* [Українська мова](../ua-UA/README-ua_UA.md) -* [Tiếng Việt](../vi-VI/README-vi.md) -* [中文版本](../zh-CN/README-zh_CN.md) -* [Türkçe](../tr-TR/README-tr_TR.md) -* [ไทย](../th-TH/README-th_TH.md) +- [English](../en-EN/README.md) +- [العربية](../ar-AR/README_AR.md) +- [اللغة العامية - Egyptian Arabic](../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) +- [日本語](../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) +- [Українська мова](../ua-UA/README-ua_UA.md) +- [Tiếng Việt](../vi-VI/README-vi.md) +- [中文版本](../zh-CN/README-zh_CN.md) +- [Türkçe](../tr-TR/README-tr_TR.md) +- [ไทย](../th-TH/README-th_TH.md) +- [Indonesia](../id-ID/README.md)

@@ -45,7 +47,7 @@ function sayHi() { console.log(name); console.log(age); - var name = "Lydia"; + var name = 'Lydia'; let age = 21; } @@ -109,7 +111,7 @@ const shape = { diameter() { return this.radius * 2; }, - perimeter: () => 2 * Math.PI * this.radius + perimeter: () => 2 * Math.PI * this.radius, }; console.log(shape.diameter()); @@ -141,7 +143,7 @@ There is no value `radius` on that object, which returns `undefined`. ```javascript +true; -!"Lydia"; +!'Lydia'; ``` - A: `1` and `false` @@ -166,12 +168,12 @@ 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", - small: true + name: 'Mickey', + small: true, }; ``` @@ -198,15 +200,14 @@ 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); ``` @@ -276,13 +277,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` @@ -332,10 +333,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! @@ -365,7 +366,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}`; }; @@ -406,8 +407,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); @@ -477,7 +478,7 @@ function sum(a, b) { return a + b; } -sum(1, "2"); +sum(1, '2'); ``` - A: `NaN` @@ -544,7 +545,7 @@ function getPersonInfo(one, two, three) { console.log(three); } -const person = "Lydia"; +const person = 'Lydia'; const age = 21; getPersonInfo`${person} is ${age} years old`; @@ -571,9 +572,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`); } @@ -633,7 +634,7 @@ The rest parameter (`...args`.) lets us "collect" all remaining arguments into a ```javascript function getAge() { - "use strict"; + 'use strict'; age = 21; console.log(age); } @@ -661,7 +662,7 @@ With `"use strict"`, you can make sure that you don't accidentally declare globa ###### 21. What's value of `sum`? ```javascript -const sum = eval("10*10+5"); +const sum = eval('10*10+5'); ``` - A: `105` @@ -684,7 +685,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. @@ -737,12 +738,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); ``` @@ -768,7 +769,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); ``` @@ -837,10 +838,10 @@ 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'; name.giveLydiaPizza(); ``` @@ -866,8 +867,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; @@ -899,9 +900,9 @@ Then, we log `a[b]`, which is actually `a["object Object"]`. We just set that to ###### 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(); @@ -1008,7 +1009,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}`; @@ -1060,6 +1061,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`, and `symbol`. `"function"` is not a type, since functions are objects, it's of type `"object"`. +

@@ -1070,8 +1072,8 @@ FYI: there are only 7 built-in types: `null`, `undefined`, `boolean`, `number`, ```javascript 0; new Number(0); -(""); -(" "); +(''); +(' '); new Boolean(false); undefined; ``` @@ -1222,7 +1224,7 @@ What differentiates a primitive from an object is that primitives do not have an (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 @@ 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"]` @@ -1359,11 +1361,11 @@ 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)); @@ -1389,7 +1391,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; @@ -1429,8 +1431,8 @@ We are only modifying the value of the `person` variable, and not the first elem ```javascript const person = { - name: "Lydia", - age: 21 + name: 'Lydia', + age: 21, }; for (const item in person) { @@ -1458,7 +1460,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"` @@ -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` @@ -1511,7 +1513,7 @@ Only the first numbers in the string is returned. Based on the _radix_ (the seco ```javascript [1, 2, 3].map(num => { - if (typeof num === "number") return; + 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(); @@ -1691,7 +1693,7 @@ 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; @@ -1785,7 +1787,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); @@ -1856,7 +1858,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); @@ -1882,9 +1884,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)); @@ -1913,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 + health: 90, }; -const data = JSON.stringify(settings, ["level", "health"]); +const data = JSON.stringify(settings, ['level', 'health']); console.log(data); ``` @@ -2006,9 +2008,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`.

@@ -2031,17 +2033,18 @@ The fourth time, we pass the `value` object again. `x.number` was previously mod #### Answer: 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` 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 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. +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. +

@@ -2057,7 +2060,7 @@ class Dog { }; class Labrador extends Dog { - // 1 + // 1 constructor(name, size) { this.size = size; } @@ -2071,7 +2074,7 @@ class Labrador extends Dog { super(name); this.size = size; } - // 4 + // 4 constructor(name, size) { this.name = name; this.size = size; @@ -2092,9 +2095,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`, 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. -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.

@@ -2125,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.

@@ -2135,9 +2139,9 @@ This is a difference between `require()` in CommonJS and `import`! With `require ###### 68. What's the output? ```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,7 +2154,7 @@ console.log(Symbol('foo') === Symbol('foo')) #### Answer: 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`.

@@ -2160,15 +2164,15 @@ Every Symbol is entirely unique. The purpose of the argument passed to the Symbo ###### 69. What's the output? ```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"`,
Answer

@@ -2187,7 +2191,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: `"🥑💻"` @@ -2211,11 +2215,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(); @@ -2283,7 +2287,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(); @@ -2320,7 +2324,7 @@ function addToList(item, list) { return list.push(item); } -const result = addToList("apple", ["banana"]); +const result = addToList('apple', ['banana']); console.log(result); ``` @@ -2380,7 +2384,7 @@ 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 { name: myName } = { name: 'Lydia' }; console.log(name); ``` @@ -2481,21 +2485,21 @@ 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) + 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: "🍫"}` +- 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

@@ -2508,7 +2512,7 @@ With a _for-in_ loop, we can iterate over **enumerable** properties. In an array 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. +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.

@@ -2518,14 +2522,14 @@ With a _for-of_ loop, we can iterate over **iterables**. An array is an iterable ###### 80. What is the output? ```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]`
Answer

@@ -2534,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`, and `1 / 2` returns `0.5`. +The element will be equal to the returned value. `1 + 2` returns `3`, `1 * 2` returns `2`, and `1 / 2` returns `0.5`.

@@ -2545,16 +2549,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, ` +- A: `Hi there,` - B: `Hi there, undefined` - C: `Hi there, null` -- D: `ReferenceError` +- D: `ReferenceError`
Answer

@@ -2577,21 +2581,21 @@ 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 - } - } + 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 `"😍"` @@ -2608,7 +2612,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. -

@@ -2618,14 +2621,14 @@ With the `call` method, we can change the object to which the `this` keyword ref ```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 }` @@ -2638,13 +2641,13 @@ console.log(person) #### Answer: 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.

@@ -2656,15 +2659,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."` @@ -2689,13 +2692,13 @@ Variables with the `const` and `let` keyword are _block-scoped_. A block is anyt ```javascript fetch('https://www.website.com/api/user/1') .then(res => res.json()) - .then(res => console.log(res)) + .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.
Answer

@@ -2743,7 +2746,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: `"""` @@ -2769,10 +2772,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` @@ -2785,9 +2788,9 @@ sum(10) #### Answer: 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.

@@ -2797,14 +2800,14 @@ If you're trying to set a default parameter's value equal to a parameter which i ###### 89. What's the output? ```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" }` @@ -2817,9 +2820,9 @@ 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 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.

@@ -2831,12 +2834,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"` @@ -2853,11 +2856,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"`.

@@ -2867,9 +2870,9 @@ Calling a function constructor with `new` results in the creation of an instance ###### 91. What's the output? ```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]` @@ -2882,7 +2885,7 @@ console.log(newList.push(5)) #### Answer: 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. @@ -2895,17 +2898,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` @@ -2914,7 +2918,7 @@ console.log(giveLydiaChocolate.prototype) #### Answer: 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`.

@@ -2925,17 +2929,17 @@ Regular functions, such as the `giveLydiaPizza` function, have a `prototype` pro ```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` and `age` `21` -- B: `["name", "Lydia"]` and `["age", 21]` +- B: `["name", "Lydia"]` and `["age", 21]` - C: `["name", "age"]` and `undefined` - D: `Error` @@ -2946,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"`, 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. @@ -2969,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` @@ -2978,17 +2982,18 @@ getItems(["banana", "apple"], "pear", "orange") #### Answer: 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' ]` +

@@ -2998,17 +3003,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` and `b is bigger`, `3` @@ -3021,13 +3023,13 @@ console.log(nums(1, 2)) #### Answer: 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! @@ -3042,18 +3044,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"` @@ -3077,11 +3079,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'}` and `["{Symbol('a')"]` @@ -3128,13 +3130,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` 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. +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 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`. @@ -3146,9 +3148,9 @@ Since no value gets returned in this case, the function returns `undefined`. ###### 99. What's the output? ```javascript -const name = "Lydia" +const name = 'Lydia'; -console.log(name()) +console.log(name()); ``` - A: `SyntaxError` @@ -3161,11 +3163,11 @@ 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, 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.

@@ -3179,7 +3181,7 @@ ReferenceErrors get thrown when JavaScript isn't able to find a reference to a v // 🎉✨ This is my 100th question! ✨🎉 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` @@ -3204,11 +3206,11 @@ You should${'' && `n't`} see a therapist after so much JavaScript lol` ###### 101. What's the value of 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` `[]` @@ -3237,20 +3239,20 @@ 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(await myPromise()); + console.log('second'); } -firstFunction() -secondFunction() +firstFunction(); +secondFunction(); ``` - A: `I have resolved!`, `second` and `I have resolved!`, `second` @@ -3265,13 +3267,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` and `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` 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. +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 befoer 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.

@@ -3281,14 +3283,14 @@ This means that it waited for the `myPromise` to resolve with the value `I have ###### 103. What's the value of 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); } ``` @@ -3302,11 +3304,11 @@ for (let item of set) { #### Answer: 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 `+` 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"`. +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"`. @@ -3318,7 +3320,7 @@ However, the second one is a string `"Lydia"`. `"Lydia"` is a string and `2` is ###### 104. What's its value? ```javascript -Promise.resolve(5) +Promise.resolve(5); ``` - A: `5` @@ -3333,7 +3335,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`.

@@ -3345,15 +3347,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!` @@ -3366,13 +3368,13 @@ compareMembers(person) #### Answer: 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.

@@ -3388,11 +3390,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` @@ -3405,11 +3407,11 @@ console.log(colorConfig.colors[1]) #### Answer: 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 `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. +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.

@@ -3419,7 +3421,7 @@ JavaScript interprets (or unboxes) statements. When we use bracket notation, it ###### 107. What's its value? ```javascript -console.log('❤️' === '❤️') +console.log('❤️' === '❤️'); ``` - A: `true` @@ -3430,7 +3432,7 @@ console.log('❤️' === '❤️') #### Answer: 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.

@@ -3440,19 +3442,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`
Answer @@ -3460,7 +3462,7 @@ emojis.splice(1, 2, '✨') #### Answer: 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. +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. @@ -3472,17 +3474,17 @@ With `splice` method, we modify the original array by deleting, replacing or add ###### 109. What's the output? ```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`
Answer @@ -3490,7 +3492,7 @@ console.log(food) #### Answer: 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 act by reference +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 act 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) @@ -3504,7 +3506,7 @@ Then, we change the value of the `favoriteFood` property on the `info` object. T ###### 110. What does this method do? ```javascript -JSON.parse() +JSON.parse(); ``` - A: Parses JSON to a JavaScript value @@ -3517,20 +3519,20 @@ JSON.parse() #### Answer: A -With the `JSON.parse()` method, we can parse JSON string to a JavaScript value. +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 +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' } ```

@@ -3538,17 +3540,17 @@ JSON.parse(jsonArray) // { name: 'Lydia' } --- -###### 111. What's the output? +###### 111. What's the output? ```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 @@ -3561,20 +3563,20 @@ getName() #### Answer: 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'`. +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`. +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`. +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) + console.log(name); } -getName() // Lydia +getName(); // Lydia ```

@@ -3593,11 +3595,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` and `a` @@ -3615,17 +3617,17 @@ With the `yield` keyword, we `yield` values in a generator function. With the `y 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 +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. +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 +console.log(two.next().value); // 'a' +console.log(two.next().value); // 'b' +console.log(two.next().value); // 'c' +console.log(two.next().value); // undefined ```

@@ -3636,7 +3638,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` @@ -3649,7 +3651,7 @@ console.log(`${(x => x)('I love')} to program`) #### Answer: 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`. +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`.

@@ -3661,11 +3663,11 @@ Expressions within template literals are evaluated first. This means that the st ```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 @@ -3688,17 +3690,17 @@ Normally when we set objects equal to `null`, those objects get _garbage collect ###### 115. Which method(s) will return the value `'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 @@ -3711,10 +3713,10 @@ myMap.get(() => 'greeting') #### Answer: 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!' }`. +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 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.

@@ -3725,20 +3727,20 @@ When adding a key/value pair using the `set` method, the key will be the value o ```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}` @@ -3751,7 +3753,7 @@ console.log(person) #### Answer: 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. +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 }`. @@ -3766,7 +3768,7 @@ Then, we invoke the `changeAgeAndName` function, however we don't pass a paramet ```javascript function sumValues(x, y, z) { - return x + y + z; + return x + y + z; } ``` @@ -3791,7 +3793,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,15 +3819,15 @@ With the `+=` operand, we're incrementing the value of `num` by `1`. `num` had t ```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); @@ -3859,12 +3861,12 @@ 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!`); + console.log(`We don't have to buy bananas!`); } ``` @@ -3889,10 +3891,10 @@ We passed the condition `groceries.indexOf("banana")` to the if-statement. `groc ```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); @@ -3918,10 +3920,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` @@ -3947,8 +3949,8 @@ console.log(!typeof name === "string"); ```javascript const add = x => y => z => { - console.log(x, y, z); - return x + y + z; + console.log(x, y, z); + return x + y + z; }; add(4)(5)(6); @@ -3975,16 +3977,16 @@ The `add` function returns an arrow function, which returns an arrow function, w ```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); + } })(); ``` @@ -4009,7 +4011,7 @@ The generator function `range` returns an async object with promises for each it ```javascript const myFunc = ({ x, y, z }) => { - console.log(x, y, z); + console.log(x, y, z); }; myFunc(1, 2, 3); @@ -4072,8 +4074,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); ``` @@ -4098,7 +4100,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)); @@ -4133,8 +4135,8 @@ With the `isNaN` method, you can check if the value you pass is not a number. `n const randomValue = 21; function getInfo() { - console.log(typeof randomValue); - const randomValue = "Lydia Hallie"; + console.log(typeof randomValue); + const randomValue = 'Lydia Hallie'; } getInfo(); @@ -4160,16 +4162,16 @@ Variables declared with the `const` keyword are not referencable before their in ###### 130. What's the output? ```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!'); + } })(); ``` @@ -4193,7 +4195,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)); ``` @@ -4219,13 +4221,13 @@ With the `flat` method, we can create a new, flattened array. The depth of the f ```javascript class Counter { - constructor() { - this.count = 0; - } + constructor() { + this.count = 0; + } - increment() { - this.count++; - } + increment() { + this.count++; + } } const counterOne = new Counter(); @@ -4266,19 +4268,19 @@ 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!"); + 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(); @@ -4315,11 +4317,11 @@ We get to the last line of `funcTwo`, which logs `Last line!` to the console. No ```javascript // sum.js export default function sum(x) { - return x + x; + return x + x; } // index.js -import * as sum from "./sum"; +import * as sum from './sum'; ``` - A: `sum(4)` @@ -4336,12 +4338,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 +4374,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 +4410,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,10 +4438,10 @@ However, you can still modify the value of existing properties. ```javascript const person = { - name: "Lydia Hallie", - address: { - street: "100 Main St" - } + name: 'Lydia Hallie', + address: { + street: '100 Main St', + }, }; Object.freeze(person); @@ -4468,10 +4470,10 @@ However, it only _shallowly_ freezes the object, meaning that only _direct_ prop ```javascript const person = { - name: "Lydia Hallie", - address: { - street: "100 Main St" - } + name: 'Lydia Hallie', + address: { + street: '100 Main St', + }, }; Object.freeze(person); @@ -4502,7 +4504,7 @@ However, it only _shallowly_ freezes the object, meaning that only _direct_ prop const add = x => x + x; function myFunc(num = 2, value = add(num)) { - console.log(num, value); + console.log(num, value); } myFunc(); @@ -4570,20 +4572,20 @@ 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) { - 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); @@ -4614,18 +4616,18 @@ 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) { - hobbies.push(hobby); - return hobbies; + hobbies.push(hobby); + return hobbies; } -addHobby("running", []); -addHobby("dancing"); -addHobby("baking", person.hobbies); +addHobby('running', []); +addHobby('dancing'); +addHobby('baking', person.hobbies); console.log(person.hobbies); ``` @@ -4659,16 +4661,16 @@ After pushing `dancing` and `baking`, the value of `person.hobbies` is `["coding ```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(); @@ -4694,11 +4696,11 @@ We create the variable `pet` which is an instance of the `Flamingo` class. When ###### 144. 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; ``` @@ -4743,4 +4745,4 @@ const person = { 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)`.

- \ No newline at end of file + From 08e306bda912fa8e41ead120fd566ab1da70be68 Mon Sep 17 00:00:00 2001 From: Alexandr Makeev Date: Tue, 17 Mar 2020 14:19:21 +0300 Subject: [PATCH 581/915] ru-RU: Update type list in question 34 --- 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 eb6be283..52e55146 100644 --- a/ru-RU/README.md +++ b/ru-RU/README.md @@ -1052,7 +1052,7 @@ typeof sayHi(); Функция `sayHi` возвращает значение, возвращаемое из немедленно вызываемого функционального выражения (IIFE). Результатом является `0` типа `"number"`. -Для информации: в JS 7 встроенных типов: `null`, `undefined`, `boolean`, `number`, `string`, `object`, и `symbol`. `"function"` не является отдельным типом, т.к. функции являются объектами типа `"object"`. +Для информации: в JS 8 встроенных типов: `null`, `undefined`, `boolean`, `number`, `string`, `object`, `symbol` и `bigint`. `"function"` не является отдельным типом, т.к. функции являются объектами типа `"object"`.

From b79453fad5a04c0a0a941a0f1b455a9ca3176ef1 Mon Sep 17 00:00:00 2001 From: Alexandr Makeev Date: Tue, 17 Mar 2020 14:19:21 +0300 Subject: [PATCH 582/915] Update type list in question 34 --- ar-AR/README_AR.md | 2 +- de-DE/README.md | 2 +- en-EN/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 | 4 ++-- nl-NL/README.md | 4 ++-- pt-BR/README_pt_BR.md | 2 +- th-TH/README.md | 2 +- tr-TR/README-tr_TR.md | 2 +- ua-UA/README-ua_UA.md | 2 +- vi-VI/README-vi.md | 3 +-- zh-CN/README-zh_CN.md | 2 +- 15 files changed, 17 insertions(+), 18 deletions(-) diff --git a/ar-AR/README_AR.md b/ar-AR/README_AR.md index 8b33a246..b9f66e02 100644 --- a/ar-AR/README_AR.md +++ b/ar-AR/README_AR.md @@ -1088,7 +1088,7 @@ console.log(typeof sayHi()); دالة `sayHi` تقوم بإرجاع القيمة المرجعة من الدالة المناداة في اللحظة (IIFE). هذه الدالة تقوم بإرجاع `0`, و الذي نوعه عبارة عن `"number"`. -لمعلوماتك: لدينا فقط سبعة أنواع من ال built-in و هي : `null`, `undefined`, `boolean`, `number`, `string`, `object`, و `symbol`.`"function"` هي ليست نوع, وبما أن الدوال عبارة عن objects, ف هي ليست من النوع `"object"`. +لمعلوماتك: لدينا فقط سبعة أنواع من ال built-in و هي : `null`, `undefined`, `boolean`, `number`, `string`, `object`, و `symbol`, و `bigint`.`"function"` هي ليست نوع, وبما أن الدوال عبارة عن objects, ف هي ليست من النوع `"object"`.

diff --git a/de-DE/README.md b/de-DE/README.md index a8e775de..42a3827a 100644 --- a/de-DE/README.md +++ b/de-DE/README.md @@ -1047,7 +1047,7 @@ typeof sayHi(); Die `sayHi` Funktion gibt den Wert der sofort ausgeführten Funktion (IIFE) zurück. Die Funktion gibt `0` zurück, was vom Typ `"number"` ist. -Es gibt nur 7 eingebaute Typen in JavaScript: `null`, `undefined`, `boolean`, `number`, `string`, `object`, und `symbol`. `"function"` ist kein Typ, weil Funktionen Objekte sind und daher dem Typ `"object"` entsprechen. +Es gibt nur 7 eingebaute Typen in JavaScript: `null`, `undefined`, `boolean`, `number`, `string`, `object`, `symbol`, und `bigint`. `"function"` ist kein Typ, weil Funktionen Objekte sind und daher dem Typ `"object"` entsprechen.

diff --git a/en-EN/README.md b/en-EN/README.md index acd7e2c1..b200a5ed 100644 --- a/en-EN/README.md +++ b/en-EN/README.md @@ -1060,7 +1060,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`, and `symbol`. `"function"` is not a type, since functions are objects, it's of type `"object"`. +FYI: there are only 7 built-in types: `null`, `undefined`, `boolean`, `number`, `string`, `object`, `symbol`, and `bigint`. `"function"` is not a type, since functions are objects, it's of type `"object"`.

diff --git a/es-ES/README-ES.md b/es-ES/README-ES.md index a6247c9f..290efbd1 100644 --- a/es-ES/README-ES.md +++ b/es-ES/README-ES.md @@ -1050,7 +1050,7 @@ typeof sayHi(); La función `sayHi` devuelve el valor devuelto de la función invocada inmediatamente ([IIFE](https://developer.mozilla.org/es/docs/Glossary/IIFE)). Esta función devuelve `0`, que es el tipo `"number"`. -En JS solo hay 7 tipos incorporados (En inglés se llaman _built-in types_, y pueden identificarse con el operador `typeof`. Más información [aquí](https://www.oreilly.com/library/view/you-dont-know/9781491905159/ch01.html)): `null`,` undefined`, `boolean`,` number`, `string`,` object` y `symbol`. `"function"` no es un tipo, ya que las funciones son objetos, es de tipo `"object"`. +En JS solo hay 7 tipos incorporados (En inglés se llaman _built-in types_, y pueden identificarse con el operador `typeof`. Más información [aquí](https://www.oreilly.com/library/view/you-dont-know/9781491905159/ch01.html)): `null`,` undefined`, `boolean`,` number`, `string`,` object`, `symbol` y `bigint`. `"function"` no es un tipo, ya que las funciones son objetos, es de tipo `"object"`.

diff --git a/fr-FR/README_fr-FR.md b/fr-FR/README_fr-FR.md index fc3a906a..3e5f2f58 100644 --- a/fr-FR/README_fr-FR.md +++ b/fr-FR/README_fr-FR.md @@ -1047,7 +1047,7 @@ typeof sayHi(); La fonction `sayHi` renvoie la valeur renvoyée par la fonction immédiatement appelée (IIFE). Cette fonction a renvoyé `0`, qui est du type `"nombre"`. -Pour info : il n'y a que 7 types natifs : `null`, `undefined`, `boolean`, `number`, `string`, `object` et `symbol`. `"function"` n'est pas un type, puisque les fonctions sont des objets, il est de type `"object"`. +Pour info : il n'y a que 7 types natifs : `null`, `undefined`, `boolean`, `number`, `string`, `object`, `symbol` et `bigint`. `"function"` n'est pas un type, puisque les fonctions sont des objets, il est de type `"object"`.

diff --git a/id-ID/README.md b/id-ID/README.md index a5c0becb..24184506 100644 --- a/id-ID/README.md +++ b/id-ID/README.md @@ -1062,7 +1062,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`, and `symbol`. `"function"` is not a type, since functions are objects, it's of type `"object"`. +FYI: there are only 7 built-in types: `null`, `undefined`, `boolean`, `number`, `string`, `object`, `symbol`, and `bigint`. `"function"` is not a type, since functions are objects, it's of type `"object"`.

diff --git a/ja-JA/README-ja_JA.md b/ja-JA/README-ja_JA.md index 7d42eeeb..7a171692 100644 --- a/ja-JA/README-ja_JA.md +++ b/ja-JA/README-ja_JA.md @@ -1080,7 +1080,7 @@ typeof sayHi(); `sayHi`関数は、即時呼び出し関数式(IIFE)の戻り値を返します。この関数は`0`を返しました。それは`"number"`型です。 -参考:7つの組み込み型しかありません: `null`, `undefined`, `boolean`, `number`, `string`, `object`, そして`symbol`。関数はオブジェクトなので、`"function"`型ではなく`"object"`型です。 +参考:7つの組み込み型しかありません: `null`, `undefined`, `boolean`, `number`, `string`, `object`, `symbol`, そして `bigint`。関数はオブジェクトなので、`"function"`型ではなく`"object"`型です。

diff --git a/ko-KR/README-ko_KR.md b/ko-KR/README-ko_KR.md index 8ed66536..a5c5c60f 100644 --- a/ko-KR/README-ko_KR.md +++ b/ko-KR/README-ko_KR.md @@ -1050,7 +1050,7 @@ console.log(typeof sayHi()); `sayHi`함수는 즉시 호출 함수(IIFE)로서 리턴된 값을 리턴해요. 이 함수는 `0`을 리턴하고, 형은 `"number"`이에요. -참고: 단 7개의 내장형이 있어요: `null`, `undefined`, `boolean`, `number`, `string`, `object` 그리고 `symbol`. `"function"`은 객체이기 때문에 형이 아니라 `"object"`형이에요. +참고: 단 7개의 내장형이 있어요: `null`, `undefined`, `boolean`, `number`, `string`, `object`, `symbol` 그리고 `bigint`. `"function"`은 객체이기 때문에 형이 아니라 `"object"`형이에요.

@@ -3753,4 +3753,4 @@ console.log(person) 그리고나서, `changeAgeAndName` 함수를 호출 했지만, 파라미터를 전달하지 않았어요. 대신에, `x`의 값은 _새로운_ 객체와 같아요: `{ ...person }`. 새로운 객체이기 때문에, `person`객체의 속성들의 값에 영향을 주지 않아요. `person`은 여전히 `{ name: "Lydia", age: 22 }`와 같아요.

- \ No newline at end of file + diff --git a/nl-NL/README.md b/nl-NL/README.md index 635dcd30..81cb88a7 100644 --- a/nl-NL/README.md +++ b/nl-NL/README.md @@ -1060,7 +1060,7 @@ console.log(typeof sayHi()); De `sayHi` functie geeft de waarde terug van de direct aangeroepen functie (IIFE). Deze functie geeft `0` terug, die het type `number` heeft. -FYI: er zijn slechts 7 ingebouwde types: `null`, `undefined`, `boolean`, `number`, `string`, `object`, en `symbol`. `"function"` is geen type omdat functies objecten zijn, en dus van het type `"object"`. +FYI: er zijn slechts 7 ingebouwde types: `null`, `undefined`, `boolean`, `number`, `string`, `object`, `symbol` en `bigint`. `"function"` is geen type omdat functies objecten zijn, en dus van het type `"object"`.

@@ -4713,4 +4713,4 @@ const person = { Objecten zijn standaard niet itereerbaar. Een _iterable_ is een _iterable_ als het _iterator protocol_ aanwezig is. We kunnen dit met de iterator symbol `[Symbol.iterator]` handmatig toevoegen, wat een generator object zal moeten teruggeven. Bijvoorbeeld door het een generator functie te maken: `*[Symbol.iterator]() {}`. Deze generator functie moet de `Object.values` afgeven van het object `person` als we de array `["Lydia Hallie", 21]`: `yield* Object.values(this)` terug willen geven.

- \ No newline at end of file + diff --git a/pt-BR/README_pt_BR.md b/pt-BR/README_pt_BR.md index e53887dc..0c1552dc 100644 --- a/pt-BR/README_pt_BR.md +++ b/pt-BR/README_pt_BR.md @@ -1051,7 +1051,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`, e `symbol`. `"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"`.

diff --git a/th-TH/README.md b/th-TH/README.md index 7f27af3b..3f253af9 100644 --- a/th-TH/README.md +++ b/th-TH/README.md @@ -1052,7 +1052,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`. `"function"` is not a type, since functions are objects, it's of type `"object"`. +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"`.

diff --git a/tr-TR/README-tr_TR.md b/tr-TR/README-tr_TR.md index eb2908df..caecdd69 100644 --- a/tr-TR/README-tr_TR.md +++ b/tr-TR/README-tr_TR.md @@ -1042,7 +1042,7 @@ console.log(typeof sayHi()); `sayHi` fonksiyonu, anında çalıştırılan fonksiyonun, "immediately invoked function (IIFE)", döndürdüğü değeri döndürür. Bu fonksiyon `0` döndürdü, k, tipi `"number"`'dır. -Bilginize; 7 tane tümleşik tip vardır: `null`, `undefined`, `boolean`, `number`, `string`, `object`, ve `symbol`. Fonksiyonlar nesne olduklarından, `"function"` tip değildir. Fonksiyonun tipi `"object"`'dir. +Bilginize; 7 tane tümleşik tip vardır: `null`, `undefined`, `boolean`, `number`, `string`, `object`, `symbol`, ve `bigint`. Fonksiyonlar nesne olduklarından, `"function"` tip değildir. Fonksiyonun tipi `"object"`'dir.

diff --git a/ua-UA/README-ua_UA.md b/ua-UA/README-ua_UA.md index 5b0864b6..764d4922 100644 --- a/ua-UA/README-ua_UA.md +++ b/ua-UA/README-ua_UA.md @@ -1045,7 +1045,7 @@ typeof sayHi(); Функція `sayHi` повертає значення, що повертається з _негайно викликаного функціонального вираза_ (IIFE). Результатом є `0` типу `"number"`. -Для інформації: в JS 7 вбудованих типів: `null`, `undefined`, `boolean`, `number`, `string`, `object`, та `symbol`. `"Function"` не є окремим типом, тому що функції є об'єктами типу `"object"`. +Для інформації: в JS 7 вбудованих типів: `null`, `undefined`, `boolean`, `number`, `string`, `object`, `symbol`, та `bigint`. `"Function"` не є окремим типом, тому що функції є об'єктами типу `"object"`.

diff --git a/vi-VI/README-vi.md b/vi-VI/README-vi.md index 473a540c..1e163ffd 100644 --- a/vi-VI/README-vi.md +++ b/vi-VI/README-vi.md @@ -1048,7 +1048,7 @@ typeof sayHi(); `sayHi` function trả về giá trị của một _hàm gọi ngay lập tức_ (immediately invoked function - IIFE). Function này trả về `0`, kiểu dữ liệu `"number"`. -FYI: chỉ có 7 kiểu dữ liệu built-in: `null`, `undefined`, `boolean`, `number`, `string`, `object`, and `symbol`. `"function"` không phải là một kiểu, mà là objects, kiểu dữ liệu là `"object"`. +FYI: chỉ có 7 kiểu dữ liệu built-in: `null`, `undefined`, `boolean`, `number`, `string`, `object`, `symbol`, and `bigint`. `"function"` không phải là một kiểu, mà là objects, kiểu dữ liệu là `"object"`.

@@ -4705,4 +4705,3 @@ Mặc định ta không thể duyệt qua được object. Trừ phi nó đượ

- diff --git a/zh-CN/README-zh_CN.md b/zh-CN/README-zh_CN.md index 5869c0e2..4bfa8eef 100644 --- a/zh-CN/README-zh_CN.md +++ b/zh-CN/README-zh_CN.md @@ -1028,7 +1028,7 @@ typeof sayHi() `sayHi` 方法返回的是立即执行函数(IIFE)的返回值.此立即执行函数的返回值是 `0`, 类型是 `number` -参考:只有7种内置类型:`null`,`undefined`,`boolean`,`number`,`string`,`object` 和 `symbol`。 ``function`` 不是一种类型,函数是对象,它的类型是``object``。 +参考:只有7种内置类型:`null`,`undefined`,`boolean`,`number`,`string`,`object`, `symbol` 和 `bigint`。 ``function`` 不是一种类型,函数是对象,它的类型是``object``。

From b45d143b388f8609bed887748e54d8eff682729f Mon Sep 17 00:00:00 2001 From: Nidelson Gimenes Date: Sat, 21 Mar 2020 16:45:08 -0300 Subject: [PATCH 583/915] Question 1 - Fix brazilian translation --- 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 e53887dc..d60b0925 100644 --- a/pt-BR/README_pt_BR.md +++ b/pt-BR/README_pt_BR.md @@ -52,7 +52,7 @@ sayHi(); Dentro da função, nós primeiro declaramos a variável `name` usando a palavra-chave `var`. Isso significa que a variavel é elevada(hoisted) (O espaço na memória é separado durante a fase de criação) com o valor padrão `undefined`, até que chegue na linha onde definimos a variável. Ainda não definimos a variável na linha onde tentamos usar colocar no log o valor da variável `name`, portanto ela ainda tem o valor `undefined`. -Variáveis com a palavra-chave `let` (e `const`) são elevadas, mas diferente de `var`, não são inicializadas. Elas não acessíveis antes da linha em que as declaramos (ou inicializamos). Esse é um conceito chamado de "temporal dead zone". Quando tentamos acessar essas variáveis antes de serem declaradas, o JavaScript lança um `ReferenceError` +Variáveis com a palavra-chave `let` (e `const`) são elevadas, mas diferente de `var`, não são inicializadas. Elas não estão acessíveis antes da linha em que as declaramos (ou inicializamos). Esse é um conceito chamado de "temporal dead zone". Quando tentamos acessar essas variáveis antes de serem declaradas, o JavaScript lança um `ReferenceError`.

@@ -614,7 +614,7 @@ getAge(21); #### Resposta: C -O operador _spread_ (`...args`.) retorna um array com os argumentos. Um array é um objeto, então `typeof args` retorna `"object"` +O operador _spread_ (`...args`.) retorna um array com os argumentos. Um array é um objeto, então `typeof args` retorna `"object"`.

From b0bbdd53022e350e5eb4336f397bb896a4344db2 Mon Sep 17 00:00:00 2001 From: Jan Date: Sun, 29 Mar 2020 12:51:07 +0200 Subject: [PATCH 584/915] Update README-tr_TR.md --- tr-TR/README-tr_TR.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tr-TR/README-tr_TR.md b/tr-TR/README-tr_TR.md index eb2908df..90c21ee8 100644 --- a/tr-TR/README-tr_TR.md +++ b/tr-TR/README-tr_TR.md @@ -4,7 +4,7 @@ Temelden ileri düzeye: Javascript'i ne kadar iyi bildiğinizi test edin, bilginizi biraz tazeleyin ya da mülakatanıza hazırlanın! :muscle: :rocket: Repoyu haftalık olarak yeni sorularla güncelliyorum. Son güncelleme: 17 Ağustos -Cevaplar, soruların altında gizlenmiştir. Görmek için sadece tıklayın. İyi şanşlar :heart: +Cevaplar, soruların altında gizlenmiştir. Görmek için sadece tıklayın. İyi şanslar :heart: Daha fazla soru eklendikçe eposta almak ister misiniz?
✨✉Eposta bildirimlerine abone olun✉✨ From 1c036f4caa47cd327a754ba3d7b6dbe5043748e9 Mon Sep 17 00:00:00 2001 From: Lydia Hallie Date: Sun, 7 Jun 2020 11:05:19 -0700 Subject: [PATCH 585/915] Add questions 146-150 --- README.md | 171 ++++++++++++++++++++++++++++++++++++++++++++++++ en-EN/README.md | 171 ++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 342 insertions(+) diff --git a/README.md b/README.md index bf8240b6..64ebd923 100644 --- a/README.md +++ b/README.md @@ -4745,3 +4745,174 @@ Objects aren't iterable by default. An iterable is an iterable if the iterator p

+--- + +###### 146. What's the 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 + +
Answer +

+ +#### 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`. + +

+
+ +--- + +###### 147. What's the output? + +```javascript +function getFruit(fruits) { + console.log(fruits?.[1]?.[1]) +} + +getFruit([['🍊', '🍌'], ['🍍']]) +getFruit() +getFruit([['🍍'], ['🍊', '🍌']]) +``` + +- A: `null`, `undefined`, 🍌 +- B: `[]`, `null`, 🍌 +- C: `[]`, `[]`, 🍌 +- D: `undefined`, `undefined`, 🍌 + +
Answer +

+ +#### 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`. + +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. + +

+
+ +--- + +###### 148. What's the 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` + +
Answer +

+ +#### Answer: 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`. + +

+
+ +--- + +###### 149. What's the 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` + +
Answer +

+ +#### Answer: 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`. + +

+
+ +--- + +###### 150. What's the output? + +```javascript +const fruit = ['🍌', '🍊', '🍎'] + +fruit.slice(0, 1) +fruit.splice(0, 1) +fruit.unshift('🍇') +``` + +- A: `['🍌', '🍊', '🍎']` +- B: `['🍊', '🍎']` +- C: `['🍇', '🍊', '🍎']` +- D: `['🍇', '🍌', '🍊', '🍎']` + +
Answer +

+ +#### Answer: 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 `['🍇', '🍊', '🍎']`. + +

+
diff --git a/en-EN/README.md b/en-EN/README.md index 58e42c6d..db9f7305 100644 --- a/en-EN/README.md +++ b/en-EN/README.md @@ -4745,3 +4745,174 @@ Objects aren't iterable by default. An iterable is an iterable if the iterator p

+----- + +###### 146. What's the 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 + +
Answer +

+ +#### 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`. + +

+
+ +--- + +###### 147. What's the output? + +```javascript +function getFruit(fruits) { + console.log(fruits?.[1]?.[1]) +} + +getFruit([['🍊', '🍌'], ['🍍']]) +getFruit() +getFruit([['🍍'], ['🍊', '🍌']]) +``` + +- A: `null`, `undefined`, 🍌 +- B: `[]`, `null`, 🍌 +- C: `[]`, `[]`, 🍌 +- D: `undefined`, `undefined`, 🍌 + +
Answer +

+ +#### 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`. + +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. + +

+
+ +--- + +###### 148. What's the 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` + +
Answer +

+ +#### Answer: 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`. + +

+
+ +--- + +###### 149. What's the 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` + +
Answer +

+ +#### Answer: 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`. + +

+
+ +--- + +###### 150. What's the output? + +```javascript +const fruit = ['🍌', '🍊', '🍎'] + +fruit.slice(0, 1) +fruit.splice(0, 1) +fruit.unshift('🍇') +``` + +- A: `['🍌', '🍊', '🍎']` +- B: `['🍊', '🍎']` +- C: `['🍇', '🍊', '🍎']` +- D: `['🍇', '🍌', '🍊', '🍎']` + +
Answer +

+ +#### Answer: 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 `['🍇', '🍊', '🍎']`. + +

+
From fce2d16135ad311fc144bc0e82f0745ca5a51116 Mon Sep 17 00:00:00 2001 From: Lydia Hallie Date: Sun, 7 Jun 2020 11:10:04 -0700 Subject: [PATCH 586/915] Update date --- README.md | 6 +++--- en-EN/README.md | 6 +++--- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/README.md b/README.md index 432aa558..7944a494 100644 --- a/README.md +++ b/README.md @@ -4,7 +4,7 @@ --- -I post multiple choice JavaScript questions on my [Instagram](https://www.instagram.com/theavocoder) **stories**, which I'll also post here! Last updated: December 24th +I post multiple choice JavaScript questions on my [Instagram](https://www.instagram.com/theavocoder) **stories**, which I'll also post here! Last updated: June 7th 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: @@ -4217,7 +4217,7 @@ With the `flat` method, we can create a new, flattened array. The depth of the f --- -###### 132. What's the output? +###### 132. What's the output? ```javascript class Counter { @@ -4717,7 +4717,7 @@ Objects aren't iterable by default. An iterable is an iterable if the iterator p --- -###### 146. What's the output? +###### 146. What's the output? ```javascript let count = 0; diff --git a/en-EN/README.md b/en-EN/README.md index 88d2dff2..77c83dd8 100644 --- a/en-EN/README.md +++ b/en-EN/README.md @@ -4,7 +4,7 @@ --- -I post multiple choice JavaScript questions on my [Instagram](https://www.instagram.com/theavocoder) **stories**, which I'll also post here! Last updated: December 24th +I post multiple choice JavaScript questions on my [Instagram](https://www.instagram.com/theavocoder) **stories**, which I'll also post here! Last updated: June 7th 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: @@ -3471,7 +3471,7 @@ With `splice` method, we modify the original array by deleting, replacing or add --- -###### 109. What's the output? +###### 109. What's the output? ```javascript const food = ['🍕', '🍫', '🥑', '🍔']; @@ -4717,7 +4717,7 @@ Objects aren't iterable by default. An iterable is an iterable if the iterator p ----- -###### 146. What's the output? +###### 146. What's the output? ```javascript let count = 0; From c8739787aec49aeaee692884300ce29435145fcb Mon Sep 17 00:00:00 2001 From: Lydia Hallie Date: Mon, 8 Jun 2020 22:38:17 -0700 Subject: [PATCH 587/915] Add questions 151 - 153 --- README.md | 105 +++++++++++++++++++++++++++++++++++++++++++++++- en-EN/README.md | 105 +++++++++++++++++++++++++++++++++++++++++++++++- 2 files changed, 208 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 432aa558..073c9414 100644 --- a/README.md +++ b/README.md @@ -4,7 +4,7 @@ --- -I post multiple choice JavaScript questions on my [Instagram](https://www.instagram.com/theavocoder) **stories**, which I'll also post here! Last updated: December 24th +I post multiple choice JavaScript questions on my [Instagram](https://www.instagram.com/theavocoder) **stories**, which I'll also post here! Last updated: June 8th 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: @@ -4886,3 +4886,106 @@ At last, we invoke the `unshift` method on the `fruit` array, which modifies the

+ +--- + +###### 151. What's the 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` + +
Answer +

+ +#### Answer: 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" }`. + +

+
+ +--- + +###### 152. What's the 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` + +
Answer +

+ +#### 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. + +

+
+ +--- + +###### 153. 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 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'` + +
Answer +

+ +#### 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. + +

+
\ No newline at end of file diff --git a/en-EN/README.md b/en-EN/README.md index 88d2dff2..b9a9345d 100644 --- a/en-EN/README.md +++ b/en-EN/README.md @@ -4,7 +4,7 @@ --- -I post multiple choice JavaScript questions on my [Instagram](https://www.instagram.com/theavocoder) **stories**, which I'll also post here! Last updated: December 24th +I post multiple choice JavaScript questions on my [Instagram](https://www.instagram.com/theavocoder) **stories**, which I'll also post here! Last updated: June 8th 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: @@ -4886,3 +4886,106 @@ At last, we invoke the `unshift` method on the `fruit` array, which modifies the

+ +--- + +###### 151. What's the 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` + +
Answer +

+ +#### Answer: 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" }`. + +

+
+ +--- + +###### 152. What's the 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` + +
Answer +

+ +#### 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. + +

+
+ +--- + +###### 153. 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 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'` + +
Answer +

+ +#### 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. + +

+
\ No newline at end of file From 9b4186ceb85fdb414ce737931d2ab0c5bc97d107 Mon Sep 17 00:00:00 2001 From: Lydia Hallie Date: Fri, 12 Jun 2020 15:21:45 -0700 Subject: [PATCH 588/915] Add questions 154 - 156 --- README.md | 103 ++++++++++++++++++++++++++++++++++++++++++++++-- en-EN/README.md | 101 ++++++++++++++++++++++++++++++++++++++++++++++- 2 files changed, 199 insertions(+), 5 deletions(-) diff --git a/README.md b/README.md index 073c9414..2ad90863 100644 --- a/README.md +++ b/README.md @@ -4,7 +4,7 @@ --- -I post multiple choice JavaScript questions on my [Instagram](https://www.instagram.com/theavocoder) **stories**, which I'll also post here! Last updated: June 8th +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: @@ -4217,7 +4217,7 @@ With the `flat` method, we can create a new, flattened array. The depth of the f --- -###### 132. What's the output? +###### 132. What's the output? ```javascript class Counter { @@ -4889,7 +4889,7 @@ At last, we invoke the `unshift` method on the `fruit` array, which modifies the --- -###### 151. What's the output? +###### 151. What's the output? ```javascript const animals = {}; @@ -4987,5 +4987,102 @@ runPromises() 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. +

+ + +--- + +###### 154. 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` + +
Answer +

+ +#### 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. + +This creates an array of subarrays containing the correct keys and values, which results in `{ name: "Lydia", age: 22 }` + +

+
+ +--- + +###### 155. What's the 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 }` + +
Answer +

+ +#### 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 `{}`. + +

+
+ +--- + +###### 156. What's the 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` + +
Answer +

+ +#### Answer: 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 `"string"`, 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. +

\ No newline at end of file diff --git a/en-EN/README.md b/en-EN/README.md index b9a9345d..cd541e82 100644 --- a/en-EN/README.md +++ b/en-EN/README.md @@ -4,7 +4,7 @@ --- -I post multiple choice JavaScript questions on my [Instagram](https://www.instagram.com/theavocoder) **stories**, which I'll also post here! Last updated: June 8th +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: @@ -4889,7 +4889,7 @@ At last, we invoke the `unshift` method on the `fruit` array, which modifies the --- -###### 151. What's the output? +###### 151. What's the output? ```javascript const animals = {}; @@ -4987,5 +4987,102 @@ runPromises() 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. +

+ + +--- + +###### 154. 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` + +
Answer +

+ +#### 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. + +This creates an array of subarrays containing the correct keys and values, which results in `{ name: "Lydia", age: 22 }` + +

+
+ +--- + +###### 155. What's the 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 }` + +
Answer +

+ +#### 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 `{}`. + +

+
+ +--- + +###### 156. What's the 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` + +
Answer +

+ +#### Answer: 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 `"string"`, 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. +

\ No newline at end of file From 7b34c3c9623168d6faada10673b45174128e500a Mon Sep 17 00:00:00 2001 From: tangbenda Date: Sun, 14 Jun 2020 14:48:11 +0800 Subject: [PATCH 589/915] zh_CN: fix a typo in 129 --- 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 5869c0e2..86899ccd 100644 --- a/zh-CN/README-zh_CN.md +++ b/zh-CN/README-zh_CN.md @@ -4144,7 +4144,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` 变量。

From 22976716b0bcb06fb029b9df154f520d2be6f1d4 Mon Sep 17 00:00:00 2001 From: lvadla Date: Sun, 14 Jun 2020 18:43:25 +0000 Subject: [PATCH 590/915] Update README.md --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 2ad90863..77d9be49 100644 --- a/README.md +++ b/README.md @@ -5080,9 +5080,9 @@ if (!typeof randomValue === "string") { #### Answer: 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 `"string"`, meaning that the value of `!typeof randomValue` is the boolean value `false`. +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.

- \ No newline at end of file + From ed230344f3104673211f4a17fa99b89873d566ad Mon Sep 17 00:00:00 2001 From: Andrew Dollard Date: Mon, 15 Jun 2020 10:53:45 -0700 Subject: [PATCH 591/915] Clarify answer for number 12 --- README.md | 2 +- en-EN/README.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 2ad90863..8621e291 100644 --- a/README.md +++ b/README.md @@ -424,7 +424,7 @@ console.log(sarah); #### Answer: A -For `sarah`, we didn't use the `new` keyword. When using `new`, it refers to the new empty object we create. However, if you don't add `new` it refers to the **global object**! +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. diff --git a/en-EN/README.md b/en-EN/README.md index 3d82f618..82d84fdc 100644 --- a/en-EN/README.md +++ b/en-EN/README.md @@ -424,7 +424,7 @@ console.log(sarah); #### Answer: A -For `sarah`, we didn't use the `new` keyword. When using `new`, it refers to the new empty object we create. However, if you don't add `new` it refers to the **global object**! +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. From 04fa2a9bbe0b7e94c3ed9bb0c7721a250a23bc19 Mon Sep 17 00:00:00 2001 From: Sleekr Date: Tue, 16 Jun 2020 11:24:41 +0700 Subject: [PATCH 592/915] Fix typo ID: pertanyaan instead of pertannyaan --- 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 397f875d..33fded25 100644 --- a/id-ID/README.md +++ b/id-ID/README.md @@ -1,4 +1,4 @@ -

Pertannyaan JavaScript

+

Pertanyaan JavaScript

--- @@ -2044,7 +2044,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? From af46f172697aaf778ff7445f4690ffdf5a9274be Mon Sep 17 00:00:00 2001 From: Sleekr Date: Tue, 16 Jun 2020 11:26:41 +0700 Subject: [PATCH 593/915] revert new line --- id-ID/README.md | 1 - 1 file changed, 1 deletion(-) diff --git a/id-ID/README.md b/id-ID/README.md index 33fded25..20234347 100644 --- a/id-ID/README.md +++ b/id-ID/README.md @@ -2044,7 +2044,6 @@ 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? From ac1fc96fd0fb130af4b498d5b0946266d4cf3d52 Mon Sep 17 00:00:00 2001 From: Lydia Hallie Date: Mon, 15 Jun 2020 21:32:34 -0700 Subject: [PATCH 594/915] Update README.md --- README.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/README.md b/README.md index 2a08aa0e..199cd479 100644 --- a/README.md +++ b/README.md @@ -12,6 +12,9 @@ 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! | +|---| + ---
See 17 Available Translations 🇪🇸🇮🇹🇩🇪 🇫🇷🇷🇺🇨🇳🇵🇹 From 3e3d35843dce0cad8db9ec0501faf9dc0085c58e Mon Sep 17 00:00:00 2001 From: Kitravee Siwatkittisuk <50334192+kitravee@users.noreply.github.com> Date: Wed, 17 Jun 2020 03:41:11 +0700 Subject: [PATCH 595/915] Translate New Header Section and question 1 - 4 I translate TH version reference to the latest Eng versions. I will try to translate and pull request every month (base on available Time) Thank you for the good resources --- th-TH/README.md | 37 ++++++++++++++++++++++--------------- 1 file changed, 22 insertions(+), 15 deletions(-) diff --git a/th-TH/README.md b/th-TH/README.md index 3f253af9..a4bd5c55 100644 --- a/th-TH/README.md +++ b/th-TH/README.md @@ -1,13 +1,20 @@ -# รายการคำถามเกี่ยวกับ JavaScript (ขั้นสูง) +
+ +

JavaScript Questions

-ผมโพสต์โจทย์ JavaScript แบบตัวเลือกทุกวันบน [Instagram](https://www.instagram.com/theavocoder) ของผม ซึ่งผมก็ได้นำมาโพสต์ไว้ที่นี่ด้วย +--- + +สวัสดีพวกเราได้โพสคำถามเกี่ยวกับ Javascript เอาไว้ใน [Instagram](https://www.instagram.com/theavocoder) **stories** และก็จะโพสเอาไว้ในนี้ด้วย! +อัปเดตล่าสุด: 24 ธันวาคม -จากขั้นพื้นฐานสู่ขั้นสูง มาทดสอบกันว่าคุณมีความรู้เรื่อง JavaScript ดีขนาดไหน มาทบทวนความรู้ของคุณกันหน่อย หรือเตรียมตัวสำหรับการสัมภาษณ์เกี่ยวกับการเขียนโปรแกรม :muscle: :rocket: ผมอัพเดทคำถามใหม่ๆ ใน repo นี้ทุกๆ สัปดาห์ อัพเดทล่าสุดวันที่ September 27th +คำถามประกอบไปด้วยตั้งแต่ระดับเริ่มต้นถึงขั้นสูง: จุดประสงค์เพื่อวัดความรู้ภาษา Javascript ทบทวนความรู้ เตรียมตัวสำหรับการสัมภาษณ์ :muscle: :rocket: Reposentory นี้มีการ Update อย่างสม่ำเสมอกรณีที่มีคำถามใหม่ๆเข้ามา เราได้ใส่คำตอบเอาไว้ในส่วนที่ซ่อนอยู่ **collapsed sections** ข้างใต้คำถามอย่าลืมคลิกมันนะมันจะขยายออก โชคดีจ้า :heart: -คำตอบจะอยู่ในหมวดที่ซ่อนไว้ใต้คำถาม เพียงแค่คลิก คำตอบก็จะแสดงขึ้นมา ขอให้โชคดีครับ :heart: +สามารถติดต่อผู้พัฒนาได้ที่ 😊
+Instagram || Twitter || LinkedIn || Blog
-หากต้องการได้รับอีเมลล์แจ้งหากผมมีการเพิ่มโจทย์ใหม่ๆ
-✨✉กรุณาลงทะเบียนรับอีเมลล์อัพเดท✉✨ +**_Note_**: เพิ่มเติมสำหรับนักพัฒนาไทยสามารถร่วมพัฒนาโดยการแปลภาษาหรือแก้ไขคำได้นะครับ + +
ลิสต์ภาษาอื่นๆ: @@ -55,9 +62,9 @@ sayHi(); #### คำตอบ: D -Within the function, we first declare the `name` variable with the `var` keyword. This means that the variable gets hoisted (memory space is set up during the creation phase) with the default value of `undefined`, until we actually get to the line where we define the variable. We haven't defined the variable yet on the line where we try to log the `name` variable, so it still holds the value of `undefined`. +ในฟังก์ชันดังกล่าวได้ทำการประกาศตัวแปร `name` ด้วย `var` คีย์เวิร์ด หมายความว่าตัวแปรได้รับการ Hoisted (คือส่วนของหน่วยความจำจะถูกจองไว้ในขั้นตอน creation phase) ด้วยค่าเริ่มต้น `undefined` จนกว่าจะถึงบรรทัดที่กำหนดค่าให้กับตัวแปร เนื่องจากเราไม่ได้กำหนดค่าให้กับตัวแปรในบรรทัดที่เราแสดงผล ดังนั้นค่าของตัวแปร `name` จึงเป็น `undefined` -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`. +ตัวแปรที่ประกาศโดยใช้คีย์เวิร์ด `let` (และ `const`) ถูก Hoisted เช่นกัน แต่มันจะไม่ถูกตั้งค่าเริ่มต้น (initialize) เหมือนกับคีย์เวิร์ด `var` พวกมันไม่สามารถเข้าถึงได้หากยังไม่ถึงบรรทัดที่ถูกประกาศ (initialize) เรียกว่า "temporal dead zone" ดังนั้นเมื่อเราพยายามเข้าถึงตัวแปรก่อนที่จะมีการประกาศ JavaScript จะส่งข้อความ `ReferenceError`

@@ -85,9 +92,9 @@ for (let i = 0; i < 3; i++) { #### คำตอบ: C -Because of the event queue in JavaScript, the `setTimeout` callback function is called _after_ the loop has been executed. Since the variable `i` in the first loop was declared using the `var` keyword, this value was global. During the loop, we incremented the value of `i` by `1` each time, using the unary operator `++`. By the time the `setTimeout` callback function was invoked, `i` was equal to `3` in the first example. +เพราะว่าลำดับเหตุการที่เกิดขึ้นใน Javascript ฟังก์ชัน `setTimeout` ที่เป็น callback ถูกเรียก _หลังจาก_ loop รันเสร็จ เนื่องจากตัวแปร `i` ใน loop แรกถูกประกาศด้วยคีย์เวิร์ด `var` จึงทำให้มันเป็น global scope ระหว่างการวนรอบ loop เป็นการเพิ่มค่า `i` ที่ละ `1` ในแต่ละครั้งด้วย unary operator `++`. ในเวลาที่ `setTimeout` callback ถูกเรียก แต่ว่าค่า `i` มีค่าเท่ากับ `3` แล้วดังตัวอย่างแรก -In the second loop, the variable `i` was declared using the `let` keyword: variables declared with the `let` (and `const`) keyword are block-scoped (a block is anything between `{ }`). During each iteration, `i` will have a new value, and each value is scoped inside the loop. +ใน loop ที่สอง ตัวแปร `i` ถูกประกาศโดยใช้คีย์เวิร์ด `let` : ตัวแปรที่ประกาศด้วยคีย์เวิร์ด `let` (และ `const`) เป็น block-scope (block คืออะไรก็ตามที่อยู่ภายใน `{ }`) ค่า `i` แต่ละค่าจะถูกกำหนดขอบเขตภายใน loop ในเวลาที่ `setTimeout` callback ถูกเรียก ค่า `i` แต่ละค่าจะเป็นค่าเฉพาะของแต่ละ callback `1 2 และ 3` ตามละดับ

@@ -119,11 +126,11 @@ console.log(shape.perimeter()); #### คำตอบ: B -Note that the value of `diameter` is a regular function, whereas the value of `perimeter` is an arrow function. +Note ค่าของ `diameter` เป็น regular function แต่ว่าค่าของ `perimeter` เป็น arrow function. -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). +ด้วย arrow functions คีย์เวิร์ด `this` อ้างอิงไปที่ขอบเขตโดยรอบ (Statis scope หรือ Lexical scope) มันจะไม่เหมือนกับ regular functions! นั้นหมายถึงว่าเมื่อเราเรียก `perimeter` คำว่า `this` มันไม่ได้อ้างอิงไปที่ตัว shape object แต่มันอ้างอิงไปที่ขอบเขตโดยรอบ(ในตัวอย่าง `this` จะอ้างอิงไปที่ window object). -There is no value `radius` on that object, which returns `undefined`. +ไม่มีค่าของ `radius` ที่ window object ดังนั้น `this.radius` จึงมีค่าเป็น `undefined`

@@ -146,9 +153,9 @@ There is no value `radius` on that object, which returns `undefined`. #### คำตอบ: A -The unary plus tries to convert an operand to a number. `true` is `1`, และ `false` is `0`. +เครื่องหมายบวกจะพยายามแปลงตัวถูกดำเนินการเป็นตัวเลข `true` เป็น `1`, และ `false` เป็น `0` -The string `'Lydia'` is a truthy value. What we're actually asking, is "is this truthy value falsy?". This returns `false`. +String `'Lydia'` เป็นค่าความจริง สิ่งที่เราถามคือ "ค่าความจริงนี้เป็นเท็จหรือไม่?" (ซึ่งคำตอบก็คือ "ไม่") ค่าจึงเป็น `false`

From a89768a3c3ea46493e8110e0da0aa15adac50151 Mon Sep 17 00:00:00 2001 From: rciupei Date: Thu, 18 Jun 2020 19:29:19 +0300 Subject: [PATCH 596/915] Fixed numbering issue Question no.145 was missing (after 144, came 146) --- README.md | 22 +++++++++++----------- 1 file changed, 11 insertions(+), 11 deletions(-) diff --git a/README.md b/README.md index 199cd479..3f2ea8bc 100644 --- a/README.md +++ b/README.md @@ -4721,7 +4721,7 @@ Objects aren't iterable by default. An iterable is an iterable if the iterator p --- -###### 146. What's the output? +###### 145. What's the output? ```javascript let count = 0; @@ -4751,7 +4751,7 @@ The `if` condition within the `forEach` loop checks whether the value of `num` i --- -###### 147. What's the output? +###### 146. What's the output? ```javascript function getFruit(fruits) { @@ -4786,7 +4786,7 @@ Lastly, we're trying to log the second item in the `['🍊', '🍌']` subarray o --- -###### 148. What's the output? +###### 147. What's the output? ```javascript class Calc { @@ -4822,7 +4822,7 @@ We set the variable `calc` equal to a new instance of the `Calc` class. Then, we --- -###### 149. What's the output? +###### 148. What's the output? ```javascript const user = { @@ -4864,7 +4864,7 @@ The `updateUser` function updates the values of the `email` and `password` prope --- -###### 150. What's the output? +###### 149. What's the output? ```javascript const fruit = ['🍌', '🍊', '🍎'] @@ -4893,7 +4893,7 @@ At last, we invoke the `unshift` method on the `fruit` array, which modifies the --- -###### 151. What's the output? +###### 150. What's the output? ```javascript const animals = {}; @@ -4929,7 +4929,7 @@ Logging `animals[dog]`, or actually `animals["object Object"]` since converting --- -###### 152. What's the output? +###### 151. What's the output? ```javascript const user = { @@ -4960,7 +4960,7 @@ The `updateEmail` function is an arrow function, and is not bound to the `user` --- -###### 153. What's the output? +###### 152. What's the output? ```javascript const promise1 = Promise.resolve('First') @@ -4996,7 +4996,7 @@ The `Promise.all` method runs the passed promises in parallel. If one promise fa --- -###### 154. 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"] @@ -5027,7 +5027,7 @@ This creates an array of subarrays containing the correct keys and values, which --- -###### 155. What's the output? +###### 154. What's the output? ```javascript const createMember = ({ email, address = {}}) => { @@ -5061,7 +5061,7 @@ The default value of `address` is an empty object `{}`. When we set the variable --- -###### 156. What's the output? +###### 155. What's the output? ```javascript let randomValue = { name: "Lydia" } From f4345f5818a6a173c0425b3d78596ad92ea92d9f Mon Sep 17 00:00:00 2001 From: Kitravee Siwatkittisuk <50334192+kitravee@users.noreply.github.com> Date: Sat, 20 Jun 2020 22:27:20 +0700 Subject: [PATCH 597/915] Changed Thai document PATH --- th-TH/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/th-TH/README.md b/th-TH/README.md index a4bd5c55..b57741a2 100644 --- a/th-TH/README.md +++ b/th-TH/README.md @@ -34,7 +34,7 @@ * [Tiếng Việt](../vi-VI/README-vi.md) * [中文版本](../zh-CN/README-zh_CN.md) * [Türkçe](../tr-TR/README-tr_TR.md) -* [ไทย](../th-TH/README-th_TH.md) +* [ไทย](../th-TH/README.md) --- From 90d1e5d325a78862ef5d2cebdfbeaf2de24ee8a3 Mon Sep 17 00:00:00 2001 From: Leon Lafayette Date: Sun, 21 Jun 2020 15:15:46 +0100 Subject: [PATCH 598/915] Update README.md --- README.md | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 199cd479..dad5b6c0 100644 --- a/README.md +++ b/README.md @@ -1092,14 +1092,16 @@ undefined; #### Answer: A -There are only six falsy values: +There are 8 falsy values: - `undefined` - `null` - `NaN` -- `0` -- `''` (empty string) - `false` +- `''` (empty string) +- `0` +- `-0` +- `0n` (BigInt(0)) Function constructors, like `new Number` and `new Boolean` are truthy. From 29cd1f99a7147eafea2cb7b620642077eefa726f Mon Sep 17 00:00:00 2001 From: William Firmino <55267752+Willwf@users.noreply.github.com> Date: Wed, 24 Jun 2020 13:38:06 -0300 Subject: [PATCH 599/915] Translation of question 63 Translation of question 63 to PT-BR --- pt-BR/README_pt_BR.md | 35 ++++++++++++++++++++++++++++++++++- 1 file changed, 34 insertions(+), 1 deletion(-) diff --git a/pt-BR/README_pt_BR.md b/pt-BR/README_pt_BR.md index 0fab2208..f3c2b703 100644 --- a/pt-BR/README_pt_BR.md +++ b/pt-BR/README_pt_BR.md @@ -1904,7 +1904,7 @@ console.log(data);
Resposta

-#### Answer: A +#### Resposta: A O segundo argumento de `JSON.stringify` é o _substituo_. O substituto pode ser uma função ou um array, e deixa você controlar o que deve ser "stringfied", isto é, ser usado pelo método `JSON.stringfy`. @@ -1915,3 +1915,36 @@ Se o substituto (replacer) for uma _função_, essa função é chamada em c ada

--- +###### 63. Qual é a saída? + +```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` + +
Resposta +

+ +#### Resposta: A + +O operador unário `++` primeiro _retorna_ o valor do operando, depois _incrementa_ esse valor. O valor de `num1` é `10`, pois a função `increaseNumber` retorna primeiro o valor de` num`, que é `10`, e apenas incrementa o valor de `num` posteriormente. + +`num2` é `10`, já que passamos `num1` para o `increasePassedNumber`. `number` é igual a` 10` (o valor de `num1`. Novamente, o operador unário `++` primeiro _retorna_ o valor do operando, depois _aumenta_ esse valor. O valor de` number` é `10`, então `num2` é igual a `10`. + +

+
+ +--- From ed9139f165b78baa155cc49e0336a65eb0f44449 Mon Sep 17 00:00:00 2001 From: William Firmino <55267752+Willwf@users.noreply.github.com> Date: Wed, 24 Jun 2020 13:58:04 -0300 Subject: [PATCH 600/915] Translation of question 64 Translation of question 64 to PT-BR --- pt-BR/README_pt_BR.md | 39 ++++++++++++++++++++++++++++++++++++++- 1 file changed, 38 insertions(+), 1 deletion(-) diff --git a/pt-BR/README_pt_BR.md b/pt-BR/README_pt_BR.md index f3c2b703..2a0091bf 100644 --- a/pt-BR/README_pt_BR.md +++ b/pt-BR/README_pt_BR.md @@ -666,7 +666,7 @@ const sum = eval("10*10+5"); #### Resposta: A -`eval` executa o código mesmo se passado como string. Se é uma expressão, como nesse caso, ele cálcula a expressão. A expressão é `10 * 10 + 5`. Isso retorna o número `105`. +`eval` executa o código mesmo se passado como string. Se é uma expressão, como nesse caso, ele calcula a expressão. A expressão é `10 * 10 + 5`. Isso retorna o número `105`.

@@ -1948,3 +1948,40 @@ O operador unário `++` primeiro _retorna_ o valor do operando, depois _incremen --- +###### 64. Qual é a saída? + +```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` + +
Resposta +

+ +#### Resposta: C + +No ES6, podemos inicializar parâmetros com um valor padrão. O valor do parâmetro será o valor padrão, se nenhum outro valor tiver sido passado para a função ou se o valor do parâmetro for `"undefined"`. Nesse caso, espalhamos (spread) as propriedades do objeto `value` para um novo objeto, para que `x` tenha o valor padrão de `{number: 10}`. + +O argumento padrão é executado _a cada chamada_! Toda vez que chamamos a função, um _novo_ objeto é criado. Invocamos a função `multiply` as duas primeiras vezes sem passar um valor: `x` tem o valor padrão de `{number: 10}`. Em seguida, registramos (log) o valor multiplicado desse número, que é `20`. + +Na terceira vez que invocamos multiply, passamos um argumento: o objeto chamado `value`. O operador `*=` é na verdade uma abreviação de `x.number = x.number * 2`: modificamos o valor de `x.number` e registramos (log) o valor multiplicado `20`. + +Na quarta vez, passamos o objeto `value` novamente. `x.number` foi modificado anteriormente para `20`, então `x.number *= 2` registra `40`. + +

+
+ +--- From dceea9d6059067b1fde13fa776b9f6ac02f392c9 Mon Sep 17 00:00:00 2001 From: William Firmino <55267752+Willwf@users.noreply.github.com> Date: Wed, 24 Jun 2020 14:09:43 -0300 Subject: [PATCH 601/915] Translation of question 65 Translation of question 65 to PT-BR --- pt-BR/README_pt_BR.md | 32 ++++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) diff --git a/pt-BR/README_pt_BR.md b/pt-BR/README_pt_BR.md index 2a0091bf..40cb08e7 100644 --- a/pt-BR/README_pt_BR.md +++ b/pt-BR/README_pt_BR.md @@ -1985,3 +1985,35 @@ Na quarta vez, passamos o objeto `value` novamente. `x.number` foi modificado an --- +###### 65. Qual é a saída? + +```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` + +
Resposta +

+ +#### Resposta: D + +O primeiro argumento que o método `reduce` recebe é o _acumulador_, `x` neste caso. O segundo argumento é o _valor atual_, `y`. Com o método `reduce`, executamos uma função de retorno de chamada (callback function) em todos os elementos da matriz, o que pode resultar em um único valor. + +Neste exemplo, não estamos retornando nenhum valor, estamos simplesmente registrando os valores do acumulador e o valor atual. + +O valor do acumulador é igual ao valor retornado anteriormente da função de retorno de chamada (callback function). Se você não passar o argumento opcional `initialValue` para o método `reduce`, o acumulador será igual ao primeiro elemento na primeira chamada. + +Na primeira chamada, o acumulador (`x`) é `1` e o valor atual (`y`) é `2`. Não retornamos da função de retorno de chamada, registramos o acumulador e o valor atual: `1` e` 2` são registrados. + +Se você não retornar um valor de uma função, ele retornará `undefined`. Na próxima chamada, o acumulador é "undefined" e o valor atual é "3". `undefined` e `3` são registrados. + +Na quarta chamada, novamente não retornamos nada da função de retorno de chamada. O acumulador é novamente `undefined` e o valor atual é `4`. `undefined` e `4` são registrados. + +

+
+ +--- From 28c515fe2402896184f05334efe13eddaecfbf6f Mon Sep 17 00:00:00 2001 From: William Firmino <55267752+Willwf@users.noreply.github.com> Date: Wed, 24 Jun 2020 14:16:32 -0300 Subject: [PATCH 602/915] Translation of question 66 Translation of question 66 to PT-BR --- pt-BR/README_pt_BR.md | 53 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 53 insertions(+) diff --git a/pt-BR/README_pt_BR.md b/pt-BR/README_pt_BR.md index 40cb08e7..19810225 100644 --- a/pt-BR/README_pt_BR.md +++ b/pt-BR/README_pt_BR.md @@ -2017,3 +2017,56 @@ Na quarta chamada, novamente não retornamos nada da função de retorno de cham --- +###### 66. Com qual construtor podemos estender com sucesso a 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 + +
Resposta +

+ +#### Resposta: B + +Em uma classe derivada, você não pode acessar a palavra-chave `this` antes de chamar `super`. Se você tentar fazer isso, ele lançará um erro de referência (ReferenceError): 1 e 4 lançará um erro de referência. + +Com a palavra-chave `super`, chamamos o construtor dessa classe pai com os argumentos fornecidos. O construtor do pai recebe o argumento `name`, portanto, precisamos passar `name` para `super`. + +A classe `Labrador` recebe dois argumentos, `name`, pois estende `Dog`, e `size` como uma propriedade extra na classe `Labrador`. Ambos precisam ser passados para a função construtora no `Labrador`, que é feita corretamente usando o construtor 2. + +

+
+ +--- From e8691556e65a549320da6a02ffbb33bd4e83ee9c Mon Sep 17 00:00:00 2001 From: William Firmino <55267752+Willwf@users.noreply.github.com> Date: Wed, 24 Jun 2020 14:32:27 -0300 Subject: [PATCH 603/915] Translation of question 67 Translation of question 67 to PT-BR --- pt-BR/README_pt_BR.md | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) diff --git a/pt-BR/README_pt_BR.md b/pt-BR/README_pt_BR.md index 19810225..22f99cdc 100644 --- a/pt-BR/README_pt_BR.md +++ b/pt-BR/README_pt_BR.md @@ -2070,3 +2070,34 @@ A classe `Labrador` recebe dois argumentos, `name`, pois estende `Dog`, e `size` --- +###### 67. Qual é a saída? + +```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` + +
Resposta +

+ +#### Resposta: B + +Com a palavra-chave `import`, todos os módulos importados são _pre-parsed_. Isso significa que os módulos importados são executados _primeiro_, o código no arquivo que importa o módulo é executado _depois_. + +Esta é uma diferença entre `require()` no CommonJS e `import`! Com `require()`, você pode carregar dependências sob demanda enquanto o código está sendo executado. Se tivéssemos usado `require` em vez de `import`, `running index.js`,` running sum.js`, `3` teriam sido registrados no console. + +

+
+ +--- From aa44c143037e6dabc037a0b0b711f79ecd64e26a Mon Sep 17 00:00:00 2001 From: William Firmino <55267752+Willwf@users.noreply.github.com> Date: Wed, 24 Jun 2020 14:35:25 -0300 Subject: [PATCH 604/915] Translation of question 68 Translation of question 68 to PT-BR --- pt-BR/README_pt_BR.md | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/pt-BR/README_pt_BR.md b/pt-BR/README_pt_BR.md index 22f99cdc..dfb982a9 100644 --- a/pt-BR/README_pt_BR.md +++ b/pt-BR/README_pt_BR.md @@ -2101,3 +2101,27 @@ Esta é uma diferença entre `require()` no CommonJS e `import`! Com `require()` --- +###### 68. Qual é a saída? + +```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` + +
Resposta +

+ +#### Resposta: A + +Todo símbolo (Symbol) é totalmente único. O objetivo do argumento passado ao símbolo é fornecer uma descrição ao símbolo. O valor do símbolo não depende do argumento passado. Ao testarmos a igualdade, estamos criando dois símbolos totalmente novos: o primeiro `Symbol('foo')` e o segundo `Symbol('foo')`. Esses dois valores são únicos e não são iguais entre si, `Symbol('foo') === Symbol('foo')` retorna `false`. + +

+
+ +--- From 2b4b8d0da1131f4c16acd6ede092b3c416472b37 Mon Sep 17 00:00:00 2001 From: William Firmino <55267752+Willwf@users.noreply.github.com> Date: Wed, 24 Jun 2020 14:38:12 -0300 Subject: [PATCH 605/915] Translation of question 69 Translation of question 69 to PT-BR --- pt-BR/README_pt_BR.md | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) diff --git a/pt-BR/README_pt_BR.md b/pt-BR/README_pt_BR.md index dfb982a9..560880ab 100644 --- a/pt-BR/README_pt_BR.md +++ b/pt-BR/README_pt_BR.md @@ -2125,3 +2125,29 @@ Todo símbolo (Symbol) é totalmente único. O objetivo do argumento passado ao --- +###### 69. Qual é a saída? + +```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"`, + +
Resposta +

+ +#### Resposta: C + +Com o método `padStart`, podemos adicionar preenchimento (padding) ao início de uma string. O valor passado para esse método é o comprimento _total_ da string junto com o preenchimento. A string `"Lydia Hallie"` tem um comprimento de `12`. `name.padStart(13)` insere 1 espaço no início da string, porque 12 + 1 é 13. + +Se o argumento passado para o método `padStart` for menor que o comprimento da matriz, nenhum preenchimento será adicionado. + +

+
+ +--- From 5ec477faa7f0e848455c853d5cf2f34a84a007d5 Mon Sep 17 00:00:00 2001 From: William Firmino <55267752+Willwf@users.noreply.github.com> Date: Wed, 24 Jun 2020 14:40:19 -0300 Subject: [PATCH 606/915] Translation of question 70 Translation of question 70 to PT-BR --- pt-BR/README_pt_BR.md | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/pt-BR/README_pt_BR.md b/pt-BR/README_pt_BR.md index 560880ab..7eb9706d 100644 --- a/pt-BR/README_pt_BR.md +++ b/pt-BR/README_pt_BR.md @@ -2151,3 +2151,25 @@ Se o argumento passado para o método `padStart` for menor que o comprimento da --- +###### 70. Qual é a saída? + +```javascript +console.log('🥑' + '💻'); +``` + +- A: `"🥑💻"` +- B: `257548` +- C: A string containing their code points +- D: Error + +
Resposta +

+ +#### Resposta: A + +Com o operador `+`, você pode concatenar seqüências de caracteres (strings). Neste caso, estamos concatenando a string `"🥑"` com a string `"💻"`, resultando em `"🥑💻"`. + +

+
+ +--- From d71f6d1d51348c438264ae9661e1ef492b51604f Mon Sep 17 00:00:00 2001 From: CrazyTim Date: Wed, 8 Jul 2020 12:41:15 +1000 Subject: [PATCH 607/915] Reword answer (see issue #355) --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 199cd479..08462958 100644 --- a/README.md +++ b/README.md @@ -388,7 +388,7 @@ console.log(member.getFullName()); #### Answer: A -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, +Adding a method to a constructor function means the method will only be available to new object instances - any old instances won't have the new method. If you want a method to be available to all instances then add it to the prototype property instead: ```js Person.prototype.getFullName = function() { @@ -396,7 +396,7 @@ Person.prototype.getFullName = function() { }; ``` -would have made `member.getFullName()` work. Why is this beneficial? Say that we added this method to the constructor itself. Maybe not every `Person` instance needed this method. This would waste a lot of memory space, since they would still have that property, which takes of memory space for each instance. Instead, if we only add it to the prototype, we just have it at one spot in memory, yet they all have access to it! +This has the added effect of using memory more efficiently. If it was added to the constructor, each `Person` instance would have a separate copy of the method and this would waste memory. Instead, if we only add it to the prototype, we just have it at one spot in memory, yet they all have access to it!

From b6ff14955f9dc1472f71784b724d828acf55d3e0 Mon Sep 17 00:00:00 2001 From: Tom Byrer Date: Sat, 11 Jul 2020 15:34:45 -0500 Subject: [PATCH 608/915] fix q154 had extra link in header I caught this while building an API for your quiz. --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 199cd479..d5f5438b 100644 --- a/README.md +++ b/README.md @@ -4996,7 +4996,7 @@ The `Promise.all` method runs the passed promises in parallel. If one promise fa --- -###### 154. What should the value of `method` be to log `{ name: "Lydia", age: 22 }`? +###### 154. What should the value of `method` be to log `{ name: "Lydia", age: 22 }`? ```javascript const keys = ["name", "age"] From 53fbf7501148c3b7069c52e1f90671747cb8b0a9 Mon Sep 17 00:00:00 2001 From: Kitravee Siwatkittisuk <50334192+kitravee@users.noreply.github.com> Date: Wed, 15 Jul 2020 01:38:03 +0700 Subject: [PATCH 609/915] Translate question 5 --- th-TH/README.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/th-TH/README.md b/th-TH/README.md index b57741a2..85353eff 100644 --- a/th-TH/README.md +++ b/th-TH/README.md @@ -185,13 +185,13 @@ const mouse = { #### คำตอบ: A -In JavaScript, all object keys are strings (unless it's a Symbol). Even though we might not _type_ them as strings, they are always converted into strings under the hood. +ในภาษา Javascript, ทุกๆ object keys เป็น strings (unless it's a Symbol). แม้ว่าเราไม่ได้กำหนด _type_ ของมันให้เป็น strings, object keys มันจะถูกแปลงเป็น strings หลังบ้านขอภาษา Javscript. -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. +JavaScript interprets (or unboxes) statements. เมื่อเราใช้ bracket notation, มันจะมองไปที่ opening bracket `[` และมองไปจนถึง closing bracket `]`. หลังจากนั้นมันจะประเมินค่า statement. -`mouse[bird.size]`: First it evaluates `bird.size`, which is `"small"`. `mouse["small"]` returns `true` +`mouse[bird.size]`: การประเมิณลำดับแรก `bird.size`, มีค่าเท่ากับ `"small"`. `mouse["small"]` returns `true` -However, with dot notation, this doesn't happen. `mouse` does not have a key called `bird`, which means that `mouse.bird` is `undefined`. Then, we ask for the `size` using dot notation: `mouse.bird.size`. Since `mouse.bird` is `undefined`, we're actually asking `undefined.size`. This isn't valid, and will throw an error similar to `Cannot read property "size" of undefined`. +อย่างไรก็ตามด้วย dot notation, สิ่งนี้ไม่มีทางเกิดขึ้น. `mouse` ไม่มี key `bird`, ซึ่งหมายความว่า `mouse.bird` มีค่าเป็น `undefined`. เมื่อเราเรียกหา `size` โดยใช้ dot notation: `mouse.bird.size`. เนื่องจาก `mouse.bird` มีค่าเป็น `undefined`, มันเลยเป็นการเรียก `undefined.size`. ซึ่งไม่ valid (isn't valid), และจะมี error แจ้งขึ้นมา `Cannot read property "size" of undefined`.

From 9a3f4e6a0b6da847977ec96ce3ac3dc30e77a946 Mon Sep 17 00:00:00 2001 From: Gitravs Date: Wed, 15 Jul 2020 02:11:22 +0700 Subject: [PATCH 610/915] Translate question 6 and 7 --- th-TH/README.md | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/th-TH/README.md b/th-TH/README.md index 85353eff..0cfe2b62 100644 --- a/th-TH/README.md +++ b/th-TH/README.md @@ -221,13 +221,13 @@ console.log(d.greeting); #### คำตอบ: A -In JavaScript, all objects interact by _reference_ when setting them equal to each other. +ในภาษา Javascript, ทุก Object จะ interact โดย _reference_ เมื่อมีการตั้งค่าให้เท่ากัน. -First, variable `c` holds a value to an object. Later, we assign `d` with the same reference that `c` has to the object. +จากคำถามลำดับแรก `c` เก็บค่าที่เป็น object. หลังจากนั้นทำการกำหนดค่า `d` ไปที่ Reference ที่ค่า `c` เนื่องจากค่า `c` เป็น object การกำหนดค่าจึงเป็นการ Reference -When you change one object, you change all of them. +เมื่อมีการเปลี่ยนแปลงค่า object ตัวใดตัวหนึ่งค่าตัวอื่นจึงเปลี่ยนตามไปด้วย

@@ -256,11 +256,11 @@ console.log(b === c); #### คำตอบ: 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. +`new Number()` เป็น built-in function constructor. แม้ว่ามันจะคล้ายกับ number, แต่มันไม่ได้เป็น number จริงๆ: มันมีคุณสมบัติพิเศษมากมายเนื่องจากมันเป็น 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`. +เมื่อใช้เครื่องหมาย `==` , มันเป็นแค่การตรวจสอบว่าข้อมูลสองค่ามีค่าเท่ากันหรือไม่ _value_. ซึ่งค่าทั้งสองมีค่าเท่ากับ `3`, จึง 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.` +อย่างไรก็ตามเมื่อใช้เครื่องหมาย `===` , ทั้งค่าของมัน _และ_ type ของมันควรเหมือนกันจึงจะ return `true`. เนื่องจาก `new Number()` ไม่ใช่ number, มันเป็น **object**. `a === b` _และ_ `b === c` จึง return `false.`

From 776327362b94fb830ea9595c35f99600ffa36c29 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E2=99=9A=20PH=E2=91=A6=20de=20Soria=E2=84=A2=E2=99=9B?= Date: Fri, 17 Jul 2020 15:40:30 +0000 Subject: [PATCH 611/915] =?UTF-8?q?Fixed=20typo=20=F0=9F=87=AB=F0=9F=87=B7?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- 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 3e5f2f58..8ff2122d 100644 --- a/fr-FR/README_fr-FR.md +++ b/fr-FR/README_fr-FR.md @@ -685,7 +685,7 @@ sessionStorage.setItem("cool_secret", 123); #### Réponse : B -La donnée stocké dans le `sessionStorage` est supprimée après la fermeture de l'onglet. +La donnée stockée dans le `sessionStorage` est supprimée après la fermeture de l'onglet. Si vous utilisez le `localStorage`, la donnée sera là pour toujours, jusqu'à ce que, par exemple, `localStorage.clear()` soit invoquée. From 8fc8c67f70f1241cdefedad69fc6bd41b72f446d Mon Sep 17 00:00:00 2001 From: CrazyTim Date: Mon, 20 Jul 2020 20:42:14 +1000 Subject: [PATCH 612/915] Apply suggestions from code review --- README.md | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 08462958..c08fc2bf 100644 --- a/README.md +++ b/README.md @@ -388,7 +388,9 @@ console.log(member.getFullName()); #### Answer: A -Adding a method to a constructor function means the method will only be available to new object instances - any old instances won't have the new method. If you want a method to be available to all instances then add it to the prototype property instead: +In JavaScript, functions are objects, and this actually adds the method `getFullName` to the constructor function object itself! Meaning we can call `Person.getFullName()`, but `member.getFullName` gives a `TypeError`. + +If you want a method to be available to all object instances then add it to the prototype property: ```js Person.prototype.getFullName = function() { @@ -396,7 +398,6 @@ Person.prototype.getFullName = function() { }; ``` -This has the added effect of using memory more efficiently. If it was added to the constructor, each `Person` instance would have a separate copy of the method and this would waste memory. Instead, if we only add it to the prototype, we just have it at one spot in memory, yet they all have access to it!

From aa06aec8df2ab21e493fb354e4c5cad531aeec1e Mon Sep 17 00:00:00 2001 From: CrazyTim Date: Mon, 20 Jul 2020 20:48:20 +1000 Subject: [PATCH 613/915] Remove blank line --- README.md | 1 - 1 file changed, 1 deletion(-) diff --git a/README.md b/README.md index c08fc2bf..7ff51d58 100644 --- a/README.md +++ b/README.md @@ -398,7 +398,6 @@ Person.prototype.getFullName = function() { }; ``` -

From d5f92efbafe94c6f411a56e59cde053eb85ff436 Mon Sep 17 00:00:00 2001 From: AlexxBoro <42293775+AlexxBoro@users.noreply.github.com> Date: Mon, 20 Jul 2020 13:55:50 +0200 Subject: [PATCH 614/915] Update README.md --- en-EN/README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/en-EN/README.md b/en-EN/README.md index 109a2876..9d430b7b 100644 --- a/en-EN/README.md +++ b/en-EN/README.md @@ -3492,7 +3492,7 @@ console.log(food); #### Answer: 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 act by reference +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) @@ -5085,4 +5085,4 @@ The condition within the `if` statement checks whether the value of `!typeof ran `!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.

- \ No newline at end of file + From c700f03cd7b29257e08fb927c3a4f877d29b8aba Mon Sep 17 00:00:00 2001 From: AlexxBoro <42293775+AlexxBoro@users.noreply.github.com> Date: Mon, 20 Jul 2020 13:58:06 +0200 Subject: [PATCH 615/915] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 199cd479..cd4d4930 100644 --- a/README.md +++ b/README.md @@ -3496,7 +3496,7 @@ console.log(food); #### Answer: 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 act by reference +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) From 3b795c3037e1adee37c7b5c3c2c3f14097a9897c Mon Sep 17 00:00:00 2001 From: Lionad Date: Tue, 21 Jul 2020 11:24:29 +0800 Subject: [PATCH 616/915] =?UTF-8?q?Fix:=20Q77=EF=BC=88README-zh=5FCN.md?= =?UTF-8?q?=EF=BC=89&=20Need=20Help?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ```js const sum = (a, b) => a + b // this is not a pure function, in some case, it could have side effects. ``` Lint to issue: https://github.com/lydiahallie/javascript-questions/issues/369 Need help: translate to english --- zh-CN/README-zh_CN.md | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/zh-CN/README-zh_CN.md b/zh-CN/README-zh_CN.md index 4bfa8eef..614df116 100644 --- a/zh-CN/README-zh_CN.md +++ b/zh-CN/README-zh_CN.md @@ -2401,11 +2401,19 @@ function sum(a, b) {
答案

-#### 答案: A +#### 答案: B 纯函数一种若输入参数相同,则永远会得到相同输出的函数。 -`sum`函数总是返回相同的结果。 如果我们传递`1`和`2`,它将总是返回`3`而没有副作用。 如果我们传递`5`和`10`,它将总是返回`15`,依此类推,这是纯函数的定义。 +在特定情况下,即使输入相同参数,也不能得到相同的返回值: + +

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

From b537e6492a760b6726550d46039ebca8e8c38637 Mon Sep 17 00:00:00 2001 From: Oli Oak <61263618+olioak@users.noreply.github.com> Date: Tue, 21 Jul 2020 19:50:51 +0200 Subject: [PATCH 617/915] Add expression to IIFE definition. --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 199cd479..7782b560 100644 --- a/README.md +++ b/README.md @@ -1062,7 +1062,7 @@ console.log(typeof sayHi()); #### Answer: B -The `sayHi` function returns the returned value of the immediately invoked function (IIFE). This function returned `0`, which is type `"number"`. +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"`. @@ -1675,7 +1675,7 @@ 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 (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"`. +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"`. From 6cb68328b98dcfebd3e4b14064e4a5d18841a881 Mon Sep 17 00:00:00 2001 From: Oli Oak <61263618+olioak@users.noreply.github.com> Date: Tue, 21 Jul 2020 19:55:45 +0200 Subject: [PATCH 618/915] Fix typos --- README.md | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/README.md b/README.md index 7782b560..be118ee3 100644 --- a/README.md +++ b/README.md @@ -627,7 +627,7 @@ getAge(21); #### Answer: C -The rest parameter (`...args`.) lets us "collect" all remaining arguments into an array. An array is an object, so `typeof args` returns `"object"` +The rest parameter (`...args`) lets us "collect" all remaining arguments into an array. An array is an object, so `typeof args` returns `"object"`

@@ -663,7 +663,7 @@ With `"use strict"`, you can make sure that you don't accidentally declare globa --- -###### 21. What's value of `sum`? +###### 21. What's the value of `sum`? ```javascript const sum = eval('10*10+5'); @@ -1513,7 +1513,7 @@ Only the first numbers in the string is returned. Based on the _radix_ (the seco --- -###### 50. What's the output`? +###### 50. What's the output? ```javascript [1, 2, 3].map(num => { @@ -4398,7 +4398,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 tis 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 to 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. @@ -4686,7 +4686,7 @@ const emojis = ['🎄', '🎅🏼', '🎁', '⭐']; #### Answer: 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 propeties on the `emojis` array can be modified, for example by pushing new values, splicing them, or setting the length of the array to 0. +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.

From ca0a24b6cbb36af080b0d594e6747842e5010303 Mon Sep 17 00:00:00 2001 From: Dima Tsoy Date: Thu, 30 Jul 2020 13:40:56 +0600 Subject: [PATCH 619/915] Question #52 - Fix russian translation --- 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 52e55146..ce8925d4 100644 --- a/ru-RU/README.md +++ b/ru-RU/README.md @@ -1596,7 +1596,7 @@ sayHi(); С помощью оператора `throw` мы можем создавать собственные ошибки. С этим оператором вы можете генерировать исключения. Исключением может быть строка, число, логическое значение или объект. В этом случае нашим исключением является строка `'Hello world'`. -С помощью оператора `catch` мы можем указать, что делать, если в блоке` try` выдается исключение. Исключение: строка `'Hello world'`. `e` теперь равно той строке, которую мы записываем. Это приводит к `'Oh error: Hello world'`. +С помощью оператора `catch` мы можем указать, что делать, если в блоке` try` выдается исключение. Исключение: строка `'Hello world'`. `e` теперь равно той строке, которую мы записываем. Это приводит к `'Oh no an error: Hello world'`.

From 2c5c7f94fce7ba65cb388757c8e22eb4e03a8b36 Mon Sep 17 00:00:00 2001 From: Dima Tsoy Date: Fri, 31 Jul 2020 12:11:44 +0600 Subject: [PATCH 620/915] Question #70 - Fix russian translation --- 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 ce8925d4..11b796a0 100644 --- a/ru-RU/README.md +++ b/ru-RU/README.md @@ -2193,7 +2193,7 @@ console.log("🥑" + "💻"); #### Ответ: A -С помощью оператора `+` вы можете объединять строки. В этом случае мы объединяем строку `""` со строкой `"💻"`, что приводит к `"💻"`. +С помощью оператора `+` вы можете объединять строки. В этом случае мы объединяем строку `"🥑"` со строкой `"💻"`, что приводит к `"🥑💻"`.

From 25395123ba8f1d40aedf35fb5d6b7ab6672deccf Mon Sep 17 00:00:00 2001 From: Dima Tsoy Date: Fri, 31 Jul 2020 14:57:50 +0600 Subject: [PATCH 621/915] Question #90 - Fix russian translation --- 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 11b796a0..bcc5a635 100644 --- a/ru-RU/README.md +++ b/ru-RU/README.md @@ -2850,7 +2850,7 @@ function Person() { } ``` -Вызов конструктора функции с `new` приводит к созданию экземпляра `Person`, ключевое слово `typeof` возвращает `"object"` для экземпляра. `typeof member` возвращает `"объект"`. +Вызов конструктора функции с `new` приводит к созданию экземпляра `Person`, ключевое слово `typeof` возвращает `"object"` для экземпляра. `typeof member` возвращает `"object"`.

From ace3e926f9cfc0f6ceed5aa688cb447433a551c7 Mon Sep 17 00:00:00 2001 From: Dima Tsoy Date: Fri, 31 Jul 2020 16:24:00 +0600 Subject: [PATCH 622/915] Question #101 - Fix russian translation --- 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 bcc5a635..22974910 100644 --- a/ru-RU/README.md +++ b/ru-RU/README.md @@ -3218,9 +3218,9 @@ console.log(one, two, three) `(false || {} || null)`: пустой объект `{}` является истинным значением. Это первое (и единственное) истинное значение, которое возвращается. `one` содержит `{}`. -`(null || false ||" ")`: все операнды являются ложными значениями. Это означает, что прошедший операнд `""` возвращается. `two` содержит `""`. +`(null || false || "")`: все операнды являются ложными значениями. Это означает, что прошедший операнд `""` возвращается. `two` содержит `""`. -`([] || 0 ||" ")`: пустой массив `[]` является истинным значением. Это первое истинное значение, которое возвращается. `three` присвоено `[]`. +`([] || 0 || "")`: пустой массив `[]` является истинным значением. Это первое истинное значение, которое возвращается. `three` присвоено `[]`.

From 098aaeea319b23342b84958c19f94bf9a6372c82 Mon Sep 17 00:00:00 2001 From: Dima Tsoy Date: Fri, 31 Jul 2020 20:40:31 +0600 Subject: [PATCH 623/915] Question #106 - Fix russian translation --- 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 22974910..b7388c7b 100644 --- a/ru-RU/README.md +++ b/ru-RU/README.md @@ -3400,7 +3400,7 @@ console.log(colorConfig.colors[1]) В JavaScript у нас есть два способа доступа к свойствам объекта: нотация в скобках или нотация в точках. В этом примере мы используем точечную нотацию (`colorConfig.colors`) вместо скобочной нотации (`colorConfig["colors"]`). -В точечной нотации JavaScript пытается найти свойство объекта с таким точным именем. В этом примере JavaScript пытается найти свойство с именем `colors` в объекте `colorConfig`. Не существует свойства с именем `colorConfig`, поэтому возвращается `undefined`. Затем мы пытаемся получить доступ к значению первого элемента, используя `[1]`. Мы не можем сделать это для значения, которое `undefined`, поэтому оно выдает `TypeError`: `Cannot read свойство '1' of undefined`. +В точечной нотации JavaScript пытается найти свойство объекта с таким точным именем. В этом примере JavaScript пытается найти свойство с именем `colors` в объекте `colorConfig`. Не существует свойства с именем `colors`, поэтому возвращается `undefined`. Затем мы пытаемся получить доступ к значению первого элемента, используя `[1]`. Мы не можем сделать это для значения, которое `undefined`, поэтому оно выдает `TypeError`: `Cannot read свойство '1' of undefined`. JavaScript интерпретирует (или распаковывает) операторы. Когда мы используем скобочные обозначения, он видит первую открывающую скобку `[` и продолжает работать, пока не найдет закрывающую скобку `]`. Только тогда он оценит утверждение. Если бы мы использовали `colorConfig[colors [1]]`, он бы возвратил значение свойства `red` объекта `colorConfig`. From 17361f1d92250f3d25d3627c2d4c4ddc9737bcd9 Mon Sep 17 00:00:00 2001 From: Dima Tsoy Date: Fri, 31 Jul 2020 21:04:01 +0600 Subject: [PATCH 624/915] Question #111 - Fix russian translation --- 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 b7388c7b..5722d385 100644 --- a/ru-RU/README.md +++ b/ru-RU/README.md @@ -3558,7 +3558,7 @@ getName() Переменные с ключевым словом `let` (и `const`) поднимаются в начало функции, в отличие от `var`, которые не инициализируется. Они недоступны до того, как мы объявим (инициализируем) их строку. Это называется "временной мертвой зоной". Когда мы пытаемся получить доступ к переменным до их объявления, JavaScript выдает `ReferenceError`. -Если бы мы не объявили переменную `name` в функции `getName`, движок javascript посмотрел бы вниз по _цепочки области действия_. Внешняя область имеет переменную с именем `name` со значением `Lydia`. В этом случае он бы записал "Лидию". +Если бы мы не объявили переменную `name` в функции `getName`, движок javascript посмотрел бы вниз по _цепочки области действия_. Внешняя область имеет переменную с именем `name` со значением `Lydia`. В этом случае он бы записал `Lydia`. ```javascript let name = 'Lydia' From 11618c63353beccf05113076b46bb4a6e3d52ee5 Mon Sep 17 00:00:00 2001 From: Dima Tsoy Date: Fri, 31 Jul 2020 21:06:43 +0600 Subject: [PATCH 625/915] Question #112 - Fix russian translation --- 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 5722d385..d595f0a9 100644 --- a/ru-RU/README.md +++ b/ru-RU/README.md @@ -3605,7 +3605,7 @@ console.log(two.next().value) Используя ключевое слово `yield`, мы получаем значения в функции генератора. С помощью ключевого слова `yield*` мы можем получить значения из другой функции-генератора или итерируемого объекта (например, массива). -В `generatorOne` мы получаем весь массив `[' a ',' b ',' c ']`, используя ключевое слово `yield`. Значение свойства `value` для объекта, возвращаемого методом `next` для `one` (`one.next().value`), равно всему массиву `['a', 'b', 'c']`. +В `generatorOne` мы получаем весь массив `['a', 'b', 'c']`, используя ключевое слово `yield`. Значение свойства `value` для объекта, возвращаемого методом `next` для `one` (`one.next().value`), равно всему массиву `['a', 'b', 'c']`. ```javascript console.log(one.next().value) // ['a', 'b', 'c'] From 5dabbed606e81b34d037133e685a70cfd09859cb Mon Sep 17 00:00:00 2001 From: Dima Tsoy Date: Fri, 31 Jul 2020 21:39:58 +0600 Subject: [PATCH 626/915] Question #114 - Fix russian translation --- 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 d595f0a9..fd68a620 100644 --- a/ru-RU/README.md +++ b/ru-RU/README.md @@ -3671,7 +3671,7 @@ config = null #### Ответ: C -Обычно, когда мы устанавливаем объекты равными `null`, эти объекты получают метку _собрано в мусор_, так как больше нет ссылок на этот объект. Однако, поскольку функция обратного вызова в `setInterval` является стрелочной функцией стрелки (таким образом, привязанной к объекту `config`), функция обратного вызова все еще содержит ссылку на объект `config`. Пока есть ссылка, объект не будет собран в мусор. Поскольку сборщик мусора не отрабатывает, функция обратного вызова `setInterval` будет по-прежнему вызываться каждые 1000 мс (1с). +Обычно, когда мы устанавливаем объекты равными `null`, эти объекты получают метку _собрано в мусор_, так как больше нет ссылок на этот объект. Однако, поскольку функция обратного вызова в `setInterval` является стрелочной функцией (таким образом, привязанной к объекту `config`), функция обратного вызова все еще содержит ссылку на объект `config`. Пока есть ссылка, объект не будет собран в мусор. Поскольку сборщик мусора не отрабатывает, функция обратного вызова `setInterval` будет по-прежнему вызываться каждые 1000 мс (1с).

From 2eac114389c32e9e5035246a5e778cc0d8935716 Mon Sep 17 00:00:00 2001 From: vladimirschneider <42021006+vladimirschneider@users.noreply.github.com> Date: Tue, 4 Aug 2020 10:28:55 +0700 Subject: [PATCH 627/915] Fixed typo: missing a space --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 199cd479..16bc7985 100644 --- a/README.md +++ b/README.md @@ -421,7 +421,7 @@ 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` +- D: `Person {firstName: "Lydia", lastName: "Hallie"}` and `ReferenceError`
Answer

From 7498dbd7069ffef5252827e0f02345653659709c Mon Sep 17 00:00:00 2001 From: David Sint <44842045+DavidSint@users.noreply.github.com> Date: Fri, 21 Aug 2020 10:12:24 +0100 Subject: [PATCH 628/915] Fix: Q39 terminology The question should say that the primitive is wrapped in an object. Not an object wrapped in an object. --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 199cd479..0ccf7471 100644 --- a/README.md +++ b/README.md @@ -1214,7 +1214,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 object 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 behaviour.

From a2d8827dcc433a4ad0681b2980f792340a735882 Mon Sep 17 00:00:00 2001 From: Ahmed Fathy Date: Thu, 27 Aug 2020 13:21:19 +0400 Subject: [PATCH 629/915] Update README.md Error in stringifying object it must be a["[object Object]"] not a["object Object"] --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 199cd479..5729a2fa 100644 --- a/README.md +++ b/README.md @@ -892,9 +892,9 @@ console.log(a[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`. +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`. +Then, we log `a[b]`, which is actually `a["[object Object]"]`. We just set that to `456`, so it returns `456`.

From f21e723cd3b0e2e4178fd56be3d391509dc27f36 Mon Sep 17 00:00:00 2001 From: Luke Loreti Date: Thu, 27 Aug 2020 15:58:20 -0400 Subject: [PATCH 630/915] Extra trailing square bracket deleted --- README.md | 2 +- en-EN/README.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 199cd479..908e622a 100644 --- a/README.md +++ b/README.md @@ -4775,7 +4775,7 @@ getFruit([['🍍'], ['🍊', '🍌']]) 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`. +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. diff --git a/en-EN/README.md b/en-EN/README.md index 109a2876..26ea6306 100644 --- a/en-EN/README.md +++ b/en-EN/README.md @@ -4771,7 +4771,7 @@ getFruit([['🍍'], ['🍊', '🍌']]) 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`. +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. From 8e0abce83c41badfc9c5fc80efff3b63e90bc9cc Mon Sep 17 00:00:00 2001 From: CrazyTim Date: Mon, 7 Sep 2020 21:59:29 +1000 Subject: [PATCH 631/915] Remove filler words Co-authored-by: Jacob Herper --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 7ff51d58..70df818b 100644 --- a/README.md +++ b/README.md @@ -388,9 +388,9 @@ console.log(member.getFullName()); #### Answer: A -In JavaScript, functions are objects, and this actually adds the method `getFullName` to the constructor function object itself! Meaning we can call `Person.getFullName()`, but `member.getFullName` gives 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 then add it to the prototype property: +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() { From b2ec4f3c514abe946ec941e5cd9ce2847ae38f5d Mon Sep 17 00:00:00 2001 From: Adarsh Lilha Date: Wed, 9 Sep 2020 03:15:26 +0530 Subject: [PATCH 632/915] Q142: Fix capitalization In answer of 142 - Changed `THe` to `The` --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index f9630dde..9242f771 100644 --- a/README.md +++ b/README.md @@ -4660,7 +4660,7 @@ const pet = new Flamingo(); #### Answer: 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. 🦢"`. +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. 🦢"`.

From 3a607706f10954122eed43614e321d3aba564b9d Mon Sep 17 00:00:00 2001 From: Ramtin <31255934+rradfar@users.noreply.github.com> Date: Wed, 9 Sep 2020 14:20:05 +0400 Subject: [PATCH 633/915] Q149 - Add console log statement --- README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/README.md b/README.md index f9630dde..bc2f8335 100644 --- a/README.md +++ b/README.md @@ -4874,6 +4874,8 @@ const fruit = ['🍌', '🍊', '🍎'] fruit.slice(0, 1) fruit.splice(0, 1) fruit.unshift('🍇') + +console.log(fruit) ``` - A: `['🍌', '🍊', '🍎']` From 5d8ac14d70a1a46415fae30fcaa7c91dda03b1d6 Mon Sep 17 00:00:00 2001 From: MenaiAla Date: Thu, 10 Sep 2020 00:20:36 -0700 Subject: [PATCH 634/915] :beetle: Replace undefined with NaN --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index f9630dde..7d89acd8 100644 --- a/README.md +++ b/README.md @@ -136,7 +136,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 `undefined`. +There is no value `radius` on that object, which returns `NaN`.

From 068350a35d2ff1fa5c3b279061de4cafcf412d7e Mon Sep 17 00:00:00 2001 From: Byron Date: Fri, 11 Sep 2020 14:25:07 +0900 Subject: [PATCH 635/915] Add translation of zh-TW 31 ~ 35 --- zh-TW/README_zh-TW.md | 153 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 153 insertions(+) diff --git a/zh-TW/README_zh-TW.md b/zh-TW/README_zh-TW.md index 2c9f600c..796b53eb 100644 --- a/zh-TW/README_zh-TW.md +++ b/zh-TW/README_zh-TW.md @@ -924,3 +924,156 @@ WebAPI 不能隨時向堆疊内新增内容。相反,它會將回呼函式彈 --- + +###### 31. 點擊按鈕時,event.target 指的是哪個元件? + +```html +
+
+ +
+
+``` + +- A: 第一層的 `div` +- B: 第二層的 `div` +- C: `button` 本身 +- D: 一個包含此巢狀元件的陣列. + +
答案 +

+ +#### 答案: C + +產生事件(event)的元件即為此事件的 target,您可以透過 `event.stopPropagation` 來停止事件的冒泡(bubbling) + +

+
+ +--- + +###### 32. 點擊標籤 p(paragraph)時, 將會輸出什麼內容? + +```html +
+

+ Click here! +

+
+``` + +- A: `p` `div` +- B: `div` `p` +- C: `p` +- D: `div` + +
答案 +

+ +#### 答案: A + +輸出內容是 `p` 及 `div`。在事件傳播(event propagation) 期間,分為三個階段:捕獲(capturing),目標(target) 和冒泡(bubbling)。 +默認情況下,事件處理(event handlers) 在冒泡階段執行(除非您將useCapture設置為true)。 它從巢狀元素的最深層向外層。 + +

+
+ +--- + +###### 33. 將會輸出什麽內容? + +```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` + +
答案 +

+ +#### 答案: D + +通過 `.call` 及 `.bind`,我們可以將想要 `this` 關鍵字引用的物件傳遞給它。 +然而,`.call` 會 _立即執行_! `.bind.` 則是會回傳一份函式(function)的 _複製_ 且不會立即執行。 + +

+
+ +--- + +###### 34. 將會輸出什麽內容? + +```javascript +function sayHi() { + return (() => 0)(); +} + +console.log(typeof sayHi()); +``` + +- A: `"object"` +- B: `"number"` +- C: `"function"` +- D: `"undefined"` + +
答案 +

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

+
+ +--- + +###### 35. 下列項目哪些是 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 + +
答案 +

+ +#### 答案: A + +只有六個值是 falsy + +- `undefined` +- `null` +- `NaN` +- `0` +- `''` (空字串) +- `false` + +函式建構式(Function constructors) 如 `new Number` 和 `new Boolean` 都為 truthy。 + +

+
+ +--- From 76c33abb2097365084a8138f84a285fffcd9cc75 Mon Sep 17 00:00:00 2001 From: Byron Date: Fri, 11 Sep 2020 14:43:13 +0900 Subject: [PATCH 636/915] Add Traditional Chinese link into menu MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 1. Add Traditional Chinese link into menu 2. Change Simplified Chinese from 中文 to 简体中文 --- en-EN/README.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/en-EN/README.md b/en-EN/README.md index 1d258e99..d19871b7 100644 --- a/en-EN/README.md +++ b/en-EN/README.md @@ -31,7 +31,8 @@ Feel free to reach out to me! 😊
* [Русский](../ru-RU/README.md) * [Українська мова](../ua-UA/README-ua_UA.md) * [Tiếng Việt](../vi-VI/README-vi.md) -* [中文版本](../zh-CN/README-zh_CN.md) +* [简体中文](../zh-CN/README-zh_CN.md) +* [繁體中文](../zh-TW/README-zh_TW.md) * [Türkçe](../tr-TR/README-tr_TR.md) * [ไทย](../th-TH/README-th_TH.md) * [Indonesia](../id-ID/README.md) From a6de6cbf552efa4fc69d2855cb15eb1545bbca3a Mon Sep 17 00:00:00 2001 From: Byron Date: Tue, 15 Sep 2020 11:05:41 +0900 Subject: [PATCH 637/915] Add new translation to zh-TW add 36~40 --- zh-TW/README_zh-TW.md | 146 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 146 insertions(+) diff --git a/zh-TW/README_zh-TW.md b/zh-TW/README_zh-TW.md index 796b53eb..88cc2611 100644 --- a/zh-TW/README_zh-TW.md +++ b/zh-TW/README_zh-TW.md @@ -1077,3 +1077,149 @@ undefined; --- + +###### 36. 將會輸出什麽內容? + +```javascript +console.log(typeof typeof 1); +``` + +- A: `"number"` +- B: `"string"` +- C: `"object"` +- D: `"undefined"` + +
答案 +

+ +#### 答案: B + +`typeof 1` 回傳 `"number"` +`typeof "number"` 回傳 `"string"` + +

+
+ +--- + +###### 37. 將會輸出什麽內容? + +```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` + +
答案 +

+ +#### 答案: C + +當您設置的元素其位置大過陣列長度時,JavaScript 會建立一個叫做 "empty slots" 的物件, 它們的值實際上為 `undefined` 但您會看到類似下面的輸出內容 : + +`[1, 2, 3, 7 x empty, 11]` + +實際執行環境會使其輸出內容略微不同 (瀏覽器, node... 等) + +

+
+ +--- + + +###### 38. 將會輸出什麽內容? + +```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` + +
答案 +

+ +#### 答案: A + +程式中的 `catch` 區塊捕獲了一個例外情況且賦殖予 argument `x`。這個 `x` 是在區塊內產生的,其有效範圍只在區塊內(block-scoped),它跟 `console.log` 中所傳入的 `x` 並不是同一個。 + +接著我們將此區塊變數 `x` 設置為等於 `1`,並設置變量 `y` 的值, 現在我們 console.log 區塊變數 `x`,無意外地它輸出 `1`。 + +而在 `catch` 區塊之外的 `x` 仍然是 `undefined` 且 `y` 是 `2`。 因此當我們想在 `catch` 區塊之外使用 `console.log(x)` 時,它回傳 `undefined`,而 `y` 回傳 `2`。 + +

+
+ +--- + +###### 39. 關於 JavaScript 的敘述何者正確? + +- A: JavaScript 的世界中不是 primitive 就是 object +- B: JavaScript 的世界中不是 function 就是 object +- C: JavaScript 的世界中只有 object +- D: JavaScript 的世界中不是 number 就是 object + +
答案 +

+ +#### 答案: 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。 +例如使用了 `String` 包裝 primitive type `string`, 接著在 expression 被 evaluates 後拋棄該包裝。 所有 primitives 除了 `null` 和 `undefined` 外都是遵循此行為。 + +

+
+ +--- + +###### 40. 將會輸出什麽內容? + +```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]` + +
答案 +

+ +#### 答案: C + +`[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]` + +

+
+ +--- From 0fff5f485f5e99aae9e1c287ce07f094132ad417 Mon Sep 17 00:00:00 2001 From: Byron Date: Tue, 15 Sep 2020 11:08:33 +0900 Subject: [PATCH 638/915] Update translation for zh-TW Update translation for 36~40 --- zh-TW/README_zh-TW.md | 13 ++++++------- 1 file changed, 6 insertions(+), 7 deletions(-) diff --git a/zh-TW/README_zh-TW.md b/zh-TW/README_zh-TW.md index 88cc2611..030b4241 100644 --- a/zh-TW/README_zh-TW.md +++ b/zh-TW/README_zh-TW.md @@ -1120,11 +1120,9 @@ console.log(numbers); #### 答案: 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... 等)

@@ -1186,8 +1184,9 @@ 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。 -例如使用了 `String` 包裝 primitive type `string`, 接著在 expression 被 evaluates 後拋棄該包裝。 所有 primitives 除了 `null` 和 `undefined` 外都是遵循此行為。 +這是因為當您嘗試訪問 primitive types (例如字串) 的屬性或方法時,JavaScript會使用其中一個 wrapper classes 包裝該 primitive type。 + +例如使用了 `String` 包裝 primitive type `string`, 接著在 expression 被 evaluates 後拋棄該包裝。 所有 primitives 除了 `null` 和 `undefined` 外都是遵循此行為。

@@ -1215,7 +1214,7 @@ Primitive 不同於 object 的是它沒有任何的屬性(properties) 和方法( #### 答案: 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]` From 6ded990ddf66db3bff9c7ec7c364fd68066f460c Mon Sep 17 00:00:00 2001 From: Byron Date: Tue, 15 Sep 2020 13:46:18 +0900 Subject: [PATCH 639/915] Add translation for zh-TW Add 41~45 --- zh-TW/README_zh-TW.md | 157 ++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 151 insertions(+), 6 deletions(-) diff --git a/zh-TW/README_zh-TW.md b/zh-TW/README_zh-TW.md index 030b4241..f4efe61a 100644 --- a/zh-TW/README_zh-TW.md +++ b/zh-TW/README_zh-TW.md @@ -1094,8 +1094,8 @@ console.log(typeof typeof 1); #### 答案: B -`typeof 1` 回傳 `"number"` -`typeof "number"` 回傳 `"string"` +`typeof 1` 返回 `"number"` +`typeof "number"` 返回 `"string"`

@@ -1160,7 +1160,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`。

@@ -1183,7 +1183,7 @@ JavaScript 只有 primitive types 和 objects. 而 Primitive types 包含 `boolean`, `null`, `undefined`, `bigint`, `number`, `string`, 和 `symbol`. -Primitive 不同於 object 的是它沒有任何的屬性(properties) 和方法(methods); 那您一定會好奇為何 `'foo'.toUpperCase()` (string) 是輸出 `'FOO'` 而不是 `TypeError` ? +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` 外都是遵循此行為。 @@ -1214,9 +1214,154 @@ Primitive 不同於 object 的是它沒有任何的屬性(properties) 和方法( #### 答案: 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]`。 + +

+ + +--- + +###### 41. 將會輸出什麽內容? + +```javascript +!!null; +!!''; +!!1; +``` + +- A: `false` `true` `false` +- B: `false` `false` `true` +- C: `false` `true` `true` +- D: `true` `true` `false` + +
答案 +

+ +#### 答案: B + +`null` 是 falsy. `!null` 返回 `true`. `!true` 返回 `false`. + +`""` 是 falsy. `!""` 返回 `true`. `!true` 返回 `false`. + +`1` 是 truthy. `!1` 返回 `false`. `!false` 返回 `true`. + +

+
+ +--- + +###### 42. 在瀏覽器中 `setInterval` 方法會返回什麼? + +```javascript +setInterval(() => console.log('Hi'), 1000); +``` + +- A: 一個唯一的 id +- B: 指定的毫秒數 +- C: 被傳遞的函式 +- D: `undefined` + +
答案 +

+ +#### 答案: A + +會返回一個唯一的 id,並可用於 `clearInterval()` 以清除該 interval。 + +

+
+ +--- + +###### 43. 將會返回何種結果? + +```javascript +[...'Lydia']; +``` + +- A: `["L", "y", "d", "i", "a"]` +- B: `["Lydia"]` +- C: `[[], "Lydia"]` +- D: `[["L", "y", "d", "i", "a"]]` + +
答案 +

+ +#### 答案: A + +字串(string) 類別是可以被迭代的(iterable), 展開運算子(spread operator) 將可迭代的字元(character) 映射(map) 置一個元素(element) 上。 + +

+
+ +--- + +###### 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` + +
答案 +

+ +#### 答案: C + +一般函式不能在被調用後中途停止。但是, 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。 + +

+
+ +--- + +###### 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"` + +
答案 +

+ +#### 答案: B + +當我們向 Promise.race 方法傳遞多個 promise 時,它將 resolves / rejects _最先的_ promise。 +在 setTimeout 方法中,我們傳遞了一個計時器:第一個 promise(firstPromise)為500毫秒,第二個 promise(secondPromise)為100毫秒。 這意味著 "secondPromise" 將先用 "two" 的值進行resolves。 現在, `res` 擁有 'two' 的值且該值被 console.log。

From 1933b9c5b1624829819ad02e1f04df7495f7f745 Mon Sep 17 00:00:00 2001 From: Byron Date: Wed, 16 Sep 2020 10:45:45 +0900 Subject: [PATCH 640/915] Update translation of zh-TW Add 46~50 --- zh-TW/README_zh-TW.md | 155 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 155 insertions(+) diff --git a/zh-TW/README_zh-TW.md b/zh-TW/README_zh-TW.md index f4efe61a..49f37ec1 100644 --- a/zh-TW/README_zh-TW.md +++ b/zh-TW/README_zh-TW.md @@ -1367,3 +1367,158 @@ Promise.race([firstPromise, secondPromise]).then(res => console.log(res)); --- + +###### 46. 將會輸出什麽內容? + +```javascript +let person = { name: 'Lydia' }; +const members = [person]; +person = null; + +console.log(members); +``` + +- A: `null` +- B: `[null]` +- C: `[{}]` +- D: `[{ name: "Lydia" }]` + +
答案 +

+ +#### 答案: D + +首先,我們宣告一個物件變數 `person` 包含 `name` 屬性以及值 `Lydia`。 + + + +接著我們宣告另一個陣列變數 `members`。我們將該陣列的第一個元素設置等於 `person` 變數的值。 +當我們將它們設置為相等時,物件透過 _reference_ 互相關聯。當我們將一個物件變數的 reference 賦值給另一個變數時,實際上我們是 _複製_ 該 reference (它們沒有 _相同_ 的 reference !) + + + +接著我們將變數 `person` 賦予 `null`。 + + + +我們僅修改變數 `person` 的值,並無修改陣列中的第一個元素。 +基於該元素有份不同的 reference (一份複製的),故 `members` 陣列中第一位元素仍保有對物件的指向,於是當我們 console.log `members` 陣列時,輸出內容為物件。 + +

+
+ +--- + +###### 47. 將會輸出什麽內容? + +```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]` + +
答案 +

+ +#### 答案: B + +通過 `for-in` 循環,我們可以遍歷對象的鍵,在這個題目中的鍵是 `name` 和 `age`。 在內部,對象鍵是字串(strings)(如果它們不是 Symbol)。 +在每次循環中,我們將 `item` 的值設置為等於其迭代的當前鍵。 第一輪循環中,`item` 等於 `name`,並輸出內容。 接著, `item` 等於 `age`,並輸出內容。 + +

+
+ +--- + +###### 48. 將會輸出什麽內容? + +```javascript +console.log(3 + 4 + '5'); +``` + +- A: `"345"` +- B: `"75"` +- C: `12` +- D: `"12"` + +
答案 +

+ +#### 答案: B + +運算子關聯性是編譯器計算表達式的順序,從左到右或從右到左。僅適用於所有運算子具有 _相同_ 優先級時,才會發生這種情況。 +在這裡我們只有一種類型的運算子:+。 而其關聯性是從左到右。 + +首先計算 `3 + 4`。 結果為數字7。 + +由於強制(coercion) ,`7 +'5'` 會導致結果為 `75`。JavaScript將數字 `7` 轉換型態成字串,請參閱問題15。我們可以使用 `+` 運算子將兩個字串連接起來。 `7` + `5` 產生 `75`。 + +

+
+ +--- + +###### 49. `num` 的值會是什麼? + +```javascript +const num = parseInt('7*6', 10); +``` + +- A: `42` +- B: `"42"` +- C: `7` +- D: `NaN` + +
答案 +

+ +#### 答案: C + +僅會返回字串中的第一個數字。 基於 _radix_ (第二個參數,用於指定我們要將其解析為哪種類型的數字:以10為基數,十六進制,八進制,二進制等),`parseInt` 檢查字串中的字元是否有效。 +一旦遇到基數中無效數字的字元,它將停止解析並忽略以下字元。 + +`*` 不是合法的 `number`,所以程式僅將字串形態的 `"7"` 轉換至 decimal 形態的 `7`,故 `num` 現在的值為 `7`。 + +

+
+ +--- + +###### 50. 將會輸出什麽內容? + +```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 ]` + +
答案 +

+ +#### 答案: C + +當對陣列做映射時,`num` 的值等同於它當前正在循環的元素。在這種情況中元素均為 numbers,所以條件式 `typeof num === "number"` 會返回 `true` 的值。 +map 函式會建立一個新陣列,並插入該函式返回的值。 + +但是我們不返回任何值。當我們不從函式返回值時,函式將返回 `undefined`。由於陣列中的每個元素都會呼叫該函式,因此對於每個元素,我們都返回 `undefined`。 + +

+
+ +--- From 3e884016b31f10ca64ec3d0edcabc8ee279e38a0 Mon Sep 17 00:00:00 2001 From: Byron Date: Wed, 16 Sep 2020 15:43:08 +0900 Subject: [PATCH 641/915] Update translation for zh-TW Add 51~55 --- zh-TW/README_zh-TW.md | 193 +++++++++++++++++++++++++++++++++++++++++- 1 file changed, 192 insertions(+), 1 deletion(-) diff --git a/zh-TW/README_zh-TW.md b/zh-TW/README_zh-TW.md index 49f37ec1..3969f300 100644 --- a/zh-TW/README_zh-TW.md +++ b/zh-TW/README_zh-TW.md @@ -1513,7 +1513,7 @@ const num = parseInt('7*6', 10); #### 答案: C -當對陣列做映射時,`num` 的值等同於它當前正在循環的元素。在這種情況中元素均為 numbers,所以條件式 `typeof num === "number"` 會返回 `true` 的值。 +當對陣列做映射(map) 時,`num` 的值等同於它當前正在循環的元素。在這種情況中元素均為 numbers,所以條件式 `typeof num === "number"` 會返回 `true` 的值。 map 函式會建立一個新陣列,並插入該函式返回的值。 但是我們不返回任何值。當我們不從函式返回值時,函式將返回 `undefined`。由於陣列中的每個元素都會呼叫該函式,因此對於每個元素,我們都返回 `undefined`。 @@ -1522,3 +1522,194 @@ map 函式會建立一個新陣列,並插入該函式返回的值。 --- + +###### 51. 將會輸出什麽內容? + +```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"` + +
答案 +

+ +#### 答案: A + +參數是透過 _value_ 傳遞,除非它們是一個物件(object),物件則由透過 _reference_ 傳遞。 `birthYear` 是透過值傳遞的,因為它是字串不是物件。 當我們按值傳遞參數時,將建立該值的 _copy_ (請參閱問題46)。 + +變數 `birthYear` 具有對值 `1997` 的 reference。參數 `year` 也有對值 `1997` 的 reference,但與變數 `birthYear` 所 reference 的不同。 +因此當我們通過將 `year` 設置為等於 `1998` 來更新 `year` 的值時,我們僅更新了 `year` 的值。 `birthYear` 仍然等於 `"1997"`。 + +`person` 的值是一個物件。 參數 `member` 具有(複製的)reference 指向 _相同_ 物件。 +因此當我們修改物件 `member` 的屬性時, `person` 的值也會被修改,因為它們都 reference 了相同的物件。 `person` 的 `name` 屬性現在等於值 `"Lydia"`。 + +

+
+ +--- + +###### 52. 將會輸出什麽內容? + +```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!` + +
答案 +

+ +#### 答案: D + +使用 `throw` 語句,我們可以建立自定義的錯誤。 使用此語句,您可以觸發例外(exception)。例外可以是 stringnumberbooleanobject。 +在這種情況下,我們的例外是字符串 `Hello world`。 + +通過 `catch` 語句,我們可以指定如果在 `try` 的程式區塊中拋出例外時該怎麼辦。 例如拋出例外:字串 `'Hello world'`。 +現在, `e` 等於我們記錄的字串。 因此輸出結果將會是 `'Oh an error: Hello world'`。 + +

+
+ +--- + +###### 53. 將會輸出什麽內容? + +```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` + +
答案 +

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

+
+ +--- + +###### 54. 將會輸出什麽內容? + +```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"` + +
答案 +

+ +#### 答案: A + +`let x = y = 10;` 實際上是 shorthand for: + +```javascript +y = 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"`。 + +但是,當將 `y` 設置為 `10` 時,我們創建了global variable `y`。 在我們程式中的任何位置均可訪問此值。 +`y` 被定義,並且為類型 `number` 的值。 因此 `console.log(typeof y` 返回 `"number"`。 + +

+
+ +--- + +###### 55. 將會輸出什麽內容? + +```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` + +
答案 +

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

+
+ +--- From 7bf64e599ab92436f3219da2e5634505dc3916f5 Mon Sep 17 00:00:00 2001 From: Byron Date: Wed, 16 Sep 2020 15:46:00 +0900 Subject: [PATCH 642/915] Fix bold issue --- zh-TW/README_zh-TW.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/zh-TW/README_zh-TW.md b/zh-TW/README_zh-TW.md index 3969f300..36e6223e 100644 --- a/zh-TW/README_zh-TW.md +++ b/zh-TW/README_zh-TW.md @@ -1591,7 +1591,7 @@ sayHi(); #### 答案: D -使用 `throw` 語句,我們可以建立自定義的錯誤。 使用此語句,您可以觸發例外(exception)。例外可以是 stringnumberbooleanobject。 +使用 `throw` 語句,我們可以建立自定義的錯誤。 使用此語句,您可以觸發例外(exception)。例外可以是 `string`,`number`,`boolean` 或 `object`。 在這種情況下,我們的例外是字符串 `Hello world`。 通過 `catch` 語句,我們可以指定如果在 `try` 的程式區塊中拋出例外時該怎麼辦。 例如拋出例外:字串 `'Hello world'`。 From e6fc59af5a3b0100cc409d822f045cd3545ef91c Mon Sep 17 00:00:00 2001 From: mootooki <56878226+mootooki@users.noreply.github.com> Date: Wed, 16 Sep 2020 15:10:39 +0200 Subject: [PATCH 643/915] Update README.md Remove semi-colon after return on question 95 --- en-EN/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/en-EN/README.md b/en-EN/README.md index d19871b7..3db2b3b3 100644 --- a/en-EN/README.md +++ b/en-EN/README.md @@ -3006,7 +3006,7 @@ The above example works. This returns the array `[ 'banana', 'apple', 'orange', function nums(a, b) { if (a > b) console.log('a is bigger'); else console.log('b is bigger'); - return; + return a + b; } From 1dd241d730f52e85519d2ac43326b04c020b4cc5 Mon Sep 17 00:00:00 2001 From: mootooki <56878226+mootooki@users.noreply.github.com> Date: Thu, 17 Sep 2020 07:39:38 +0200 Subject: [PATCH 644/915] Remove semi-colon on question 95 --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 6424b101..e06ea3a7 100644 --- a/README.md +++ b/README.md @@ -3011,7 +3011,7 @@ The above example works. This returns the array `[ 'banana', 'apple', 'orange', function nums(a, b) { if (a > b) console.log('a is bigger'); else console.log('b is bigger'); - return; + return a + b; } From 6200beb3d6f42f72cfd0e51d02f474ffa398f785 Mon Sep 17 00:00:00 2001 From: Byron Date: Thu, 17 Sep 2020 15:06:22 +0900 Subject: [PATCH 645/915] Update translation of zh-TW Add number 56~60 --- zh-TW/README_zh-TW.md | 161 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 161 insertions(+) diff --git a/zh-TW/README_zh-TW.md b/zh-TW/README_zh-TW.md index 36e6223e..38593a80 100644 --- a/zh-TW/README_zh-TW.md +++ b/zh-TW/README_zh-TW.md @@ -1713,3 +1713,164 @@ pet.bark(); --- + +###### 56. 將會輸出什麽內容? + +```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}` + +
答案 +

+ +#### 答案: D + +`Set` 物件是 _唯一_ 值的集合: 任何存在於 `Set` 的值均為唯一的,不會存在相同的值(重複的值將會由後出現的覆蓋已出現的)。 + +陣列 `[1, 1, 2, 3, 4]` 中有重複的值 `1`,因此結果會是 `{1, 2, 3, 4}`。 + +

+
+ +--- + +###### 57. 將會輸出什麽內容? + +```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` + +
答案 +

+ +#### 答案: C + +被引用(imported) 的模組(module) 是 _唯讀_ 的: 您無法修改被引用模組中項目,只有輸出(export) 該項目的模組可以更改它的值。 + +因此當我們嘗試增加 `myCounter` 的值時,他將拋出錯誤: `myCounter` is read-only and cannot be modified。 + +

+
+ +--- + +###### 58. 將會輸出什麽內容? + +```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` + +
答案 +

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

+
+ +--- + +###### 59. 將會輸出什麽內容? + +```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]` + +
答案 +

+ +#### 答案: C + +我們可以通過解構(destructuring) 從陣列或物件的屬性中獲得值。例如: + +```javascript +[a, b] = [1, 2]; +``` + + + +a 的值現在為 `1` 且b 的值現在為`2`。我們針對此問題所做的動作為: + +```javascript +[y] = [1, 2, 3, 4, 5]; +``` + + + +這代表著 `y` 的值等同於陣列中第一個元素的值,即為 `1`。因此我們執行 `console.log(y)` 時, `1` 將被輸出。 + +

+
+ +--- + +###### 60. 將會輸出什麽內容? + +```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 }` + +
答案 +

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

+
+ +--- From 3bebaa4a2d2c691e038ce9db2738ff2e2a2f72db Mon Sep 17 00:00:00 2001 From: Byron Date: Wed, 23 Sep 2020 15:53:51 +0900 Subject: [PATCH 646/915] Add translation to zh-TW Add number 61~65 --- zh-TW/README_zh-TW.md | 173 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 173 insertions(+) diff --git a/zh-TW/README_zh-TW.md b/zh-TW/README_zh-TW.md index 38593a80..e230b5c5 100644 --- a/zh-TW/README_zh-TW.md +++ b/zh-TW/README_zh-TW.md @@ -1874,3 +1874,176 @@ console.log(admin); --- + +###### 61. 將會輸出什麽內容? + +```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"]` + +
答案 +

+ +#### 答案: B + +透過 `defineProperty`,我們可以對物件增加新的屬性或是修改已經存在的屬性。當我們使用 `defineProperty` 增加物件的屬性時,它們被預設為 _不可 enumerable_ 。 + `Object.keys` 方法僅回傳物件中所有 _可 enumerable_ 的屬性名稱,這個案例中只有 `"name"`。 + +預設下,使用 `defineProperty `方法增加的屬性是不可變的。但您可以覆蓋這個行為透過 `writable`,`configurable` 及 `enumerable` 屬性。 +於是,`defineProperty` 方法可以使您對要增加到物件的屬性進行更多的控制。 + +

+
+ +--- + +###### 62. 將會輸出什麽內容? + +```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}"` + +
答案 +

+ +#### 答案: A + +`JSON.stringify` 的第二個參數是 _替換者 (replacer)_ ,替換者可以是函式,也可以是陣列,並允許您控制值要如何獲怎麼串化(stringified)。 + +如果替換者是 _陣列_ ,僅將陣列中包含的屬性名稱加到 JSON 字串中。 +此案例中,僅有 `"level"` and `"health"` 被包含,`"username"` 沒有被包含在內,因此 `data` 的值將為 `"{"level":19, "health":90}"`。 + +如果替換者是 _函式_ ,在要字串化的每個物件屬性上將會呼叫此函式。從此函式返回的值將是加到 JSON 字串中的屬性的值。如果值為 `undefined`,則此屬性從 JSON 字串中排除。 + +

+
+ +--- + +###### 63. 將會輸出什麽內容? + +```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` + +
答案 +

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

+
+ +--- + +###### 64. 將會輸出什麽內容? + +```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` + +
答案 +

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

+
+ +--- + +###### 65. 將會輸出什麽內容? + +```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` + +
答案 +

+ +#### 答案: D + +`reduce` 方法接收的第一個參數是 _累加器(accumulator)_ ,在這種情況下是 `x`。 第二個參數是 _current value_ `y`。 使用 `reduce` 方法,我們對陣列中的每個元素執行一個 callback 函式,並在最終回一個值。 + +在此示例中,我們不返回任何值,僅記錄了累加器的值和當前值。 + +累加器的值等於 callback 函式先前返回的值。 如果沒有 `initialValue` 參數傳遞給 `reduce` 方法,則累加器的初始值將會等於第一個元素。 + +在第一個呼叫中,累加器(`x`)為`1`,當前值(`y`)為`2`。 我們不從 callback 函式返回,而是輸出累加器和當前值:`1` 和 `2`。 + +如果您不從 callback 函式返回值,則它將返回 `undefined`。 在下一次呼叫時,累加器為 `undefined`,當前值為 `3`。 於是 `undefined` 和 `3` 被輸出。 + +在第四次呼叫中,我們再次不從 callback 函式返回。 累加器再次為 `undefined`,當前值為 `4`。於是 `undefined` 和 `4` 被輸出。 + +

+
+ +--- From 06e27d08fedbfcbebed58fcb3172cc30f0b3a930 Mon Sep 17 00:00:00 2001 From: Jacob Herper Date: Thu, 24 Sep 2020 15:37:44 +0100 Subject: [PATCH 647/915] Clean up language links --- README.md | 646 +++--- en-EN/README.md | 5089 ----------------------------------------------- 2 files changed, 324 insertions(+), 5411 deletions(-) delete mode 100644 en-EN/README.md diff --git a/README.md b/README.md index 4be13a73..227b61d7 100644 --- a/README.md +++ b/README.md @@ -10,35 +10,36 @@ 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! | +| ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | + --- -
See 17 Available Translations 🇪🇸🇮🇹🇩🇪 🇫🇷🇷🇺🇨🇳🇵🇹 +
See 18 Available Translations 🇸🇦🇪🇬🇧🇦🇩🇪🇪🇸🇫🇷🇮🇩🇯🇵🇰🇷🇳🇱🇧🇷🇷🇺🇹🇭🇹🇷🇺🇦🇻🇳🇨🇳🇹🇼

-* [English](./en-EN/README.md) -* [العربية](./ar-AR/README_AR.md) -* [اللغة العامية - Egyptian Arabic](./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) -* [日本語](./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) -* [Українська мова](./ua-UA/README-ua_UA.md) -* [Tiếng Việt](./vi-VI/README-vi.md) -* [简体中文](./zh-CN/README-zh_CN.md) -* [繁體中文](./zh-TW/README_zh-TW.md) -* [Türkçe](./tr-TR/README-tr_TR.md) -* [ไทย](./th-TH/README-th_TH.md) -* [Indonesia](./id-ID/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) +- [🇪🇸 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) +- [🇺🇦 Українська мова](./ua-UA/README-ua_UA.md) +- [🇻🇳 Tiếng Việt](./vi-VI/README-vi.md) +- [🇨🇳 简体中文](./zh-CN/README-zh_CN.md) +- [🇹🇼 繁體中文](./zh-TW/README_zh-TW.md)

@@ -51,7 +52,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; } @@ -147,7 +148,7 @@ There is no value `radius` on that object, which returns `NaN`. ```javascript +true; -!'Lydia'; +!"Lydia"; ``` - A: `1` and `false` @@ -172,11 +173,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, }; ``` @@ -207,11 +208,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); ``` @@ -281,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` @@ -337,10 +338,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! @@ -370,8 +371,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,12 +389,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}`; }; ``` @@ -411,8 +412,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); @@ -482,7 +483,7 @@ function sum(a, b) { return a + b; } -sum(1, '2'); +sum(1, "2"); ``` - A: `NaN` @@ -549,7 +550,7 @@ function getPersonInfo(one, two, three) { console.log(three); } -const person = 'Lydia'; +const person = "Lydia"; const age = 21; getPersonInfo`${person} is ${age} years old`; @@ -576,9 +577,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`); } @@ -638,7 +639,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); } @@ -666,7 +667,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` @@ -689,7 +690,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. @@ -742,12 +743,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); ``` @@ -773,7 +774,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); ``` @@ -842,10 +843,10 @@ 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"; name.giveLydiaPizza(); ``` @@ -871,8 +872,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; @@ -904,9 +905,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(); @@ -959,9 +960,7 @@ This is where an event loop starts to work. An **event loop** looks at the stack ```html
- +
``` @@ -987,9 +986,7 @@ The deepest nested element that caused the event is the target of the event. You ```html
-

- Click here! -

+

Click here!

``` @@ -1013,7 +1010,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}`; @@ -1076,8 +1073,8 @@ FYI: there are only 7 built-in types: `null`, `undefined`, `boolean`, `number`, ```javascript 0; new Number(0); -(''); -(' '); +(""); +(" "); new Boolean(false); undefined; ``` @@ -1226,11 +1223,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] ); ``` @@ -1257,7 +1257,7 @@ Then, `[1, 2, 0, 1]` is `acc` and `[2, 3]` is `cur`. We concatenate them, and ge ```javascript !!null; -!!''; +!!""; !!1; ``` @@ -1285,7 +1285,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 @@ -1308,7 +1308,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"]` @@ -1367,14 +1367,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"` @@ -1397,7 +1397,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; @@ -1437,7 +1437,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, }; @@ -1466,7 +1466,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"` @@ -1493,7 +1493,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` @@ -1518,8 +1518,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; }); ``` @@ -1547,12 +1547,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); @@ -1584,15 +1584,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); } } @@ -1622,8 +1622,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(); @@ -1695,11 +1695,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(); @@ -1764,7 +1764,7 @@ export default counter; ```javascript // index.js -import myCounter from './counter'; +import myCounter from "./counter"; myCounter += 1; @@ -1793,7 +1793,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); @@ -1864,7 +1864,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); @@ -1890,9 +1890,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)); @@ -1921,12 +1921,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); ``` @@ -1957,7 +1957,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); @@ -2063,7 +2063,7 @@ class Dog { constructor(name) { this.name = name; } -}; +} class Labrador extends Dog { // 1 @@ -2085,8 +2085,7 @@ class Labrador extends Dog { this.name = name; this.size = size; } - -}; +} ``` - A: 1 @@ -2114,12 +2113,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; ``` @@ -2147,7 +2146,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` @@ -2170,7 +2169,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)); ``` @@ -2197,7 +2196,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: `"🥑💻"` @@ -2221,11 +2220,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(); @@ -2293,7 +2292,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(); @@ -2330,7 +2329,7 @@ function addToList(item, list) { return list.push(item); } -const result = addToList('apple', ['banana']); +const result = addToList("apple", ["banana"]); console.log(result); ``` @@ -2390,7 +2389,7 @@ 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 { name: myName } = { name: "Lydia" }; console.log(name); ``` @@ -2446,7 +2445,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 { @@ -2491,7 +2490,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); @@ -2587,13 +2586,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; }, @@ -2627,12 +2626,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); ``` @@ -2696,9 +2695,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. @@ -2752,7 +2751,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: `"""` @@ -2807,11 +2806,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); ``` @@ -2844,7 +2843,7 @@ class Person { } } -const member = new Person('John'); +const member = new Person("John"); console.log(typeof member); ``` @@ -2904,7 +2903,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 = () => @@ -2935,7 +2934,7 @@ Regular functions, such as the `giveLydiaPizza` function, have a `prototype` pro ```javascript const person = { - name: 'Lydia', + name: "Lydia", age: 21, }; @@ -2995,7 +2994,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' ]` @@ -3009,9 +3008,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; } @@ -3050,13 +3049,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"; } }; @@ -3085,7 +3084,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); @@ -3154,7 +3153,7 @@ Since no value gets returned in this case, the function returns `undefined`. ###### 99. What's the output? ```javascript -const name = 'Lydia'; +const name = "Lydia"; console.log(name()); ``` @@ -3186,8 +3185,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` @@ -3213,7 +3212,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); @@ -3245,16 +3244,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(); @@ -3292,8 +3291,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); @@ -3353,13 +3352,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); ``` @@ -3398,7 +3397,7 @@ const colorConfig = { yellow: false, }; -const colors = ['pink', 'red', 'blue']; +const colors = ["pink", "red", "blue"]; console.log(colorConfig.colors[1]); ``` @@ -3427,7 +3426,7 @@ JavaScript interprets (or unboxes) statements. When we use bracket notation, it ###### 107. What's its value? ```javascript -console.log('❤️' === '❤️'); +console.log("❤️" === "❤️"); ``` - A: `true` @@ -3448,14 +3447,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` @@ -3480,10 +3479,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); ``` @@ -3537,7 +3536,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' } ``` @@ -3549,11 +3548,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(); @@ -3576,7 +3575,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); @@ -3594,11 +3593,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(); @@ -3644,7 +3643,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` @@ -3669,7 +3668,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), }; @@ -3697,16 +3696,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 @@ -3733,14 +3732,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); @@ -3799,7 +3798,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)]); ``` @@ -3825,11 +3824,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}`; @@ -3867,10 +3866,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!`); } @@ -3926,10 +3925,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` @@ -3954,7 +3953,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; }; @@ -4044,20 +4043,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 @@ -4080,8 +4079,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); ``` @@ -4106,7 +4105,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)); @@ -4142,7 +4141,7 @@ const randomValue = 21; function getInfo() { console.log(typeof randomValue); - const randomValue = 'Lydia Hallie'; + const randomValue = "Lydia Hallie"; } getInfo(); @@ -4168,7 +4167,7 @@ Variables declared with the `const` keyword are not referencable before their in ###### 130. What's the output? ```javascript -const myPromise = Promise.resolve('Woah some cool data'); +const myPromise = Promise.resolve("Woah some cool data"); (async () => { try { @@ -4176,7 +4175,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!"); } })(); ``` @@ -4201,7 +4200,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)); ``` @@ -4274,19 +4273,19 @@ 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!'); + 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(); @@ -4327,7 +4326,7 @@ export default function sum(x) { } // index.js -import * as sum from './sum'; +import * as sum from "./sum"; ``` - A: `sum(4)` @@ -4344,12 +4343,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); ``` @@ -4380,13 +4379,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; ``` @@ -4416,7 +4415,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); ``` @@ -4444,9 +4443,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", }, }; @@ -4475,7 +4474,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); @@ -4508,21 +4507,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` @@ -4546,8 +4545,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) { @@ -4590,8 +4589,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) { @@ -4599,9 +4598,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); ``` @@ -4670,11 +4669,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; ``` @@ -4729,11 +4728,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 @@ -4757,12 +4756,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`, 🍌 @@ -4775,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,19 +4791,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` @@ -4828,25 +4827,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` @@ -4869,13 +4868,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: `['🍌', '🍊', '🍎']` @@ -4890,7 +4889,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 `['🍇', '🍊', '🍎']`.

@@ -4901,13 +4900,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" }` @@ -4920,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"}`. +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" }`. @@ -4937,14 +4936,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` @@ -4957,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.

@@ -4967,20 +4966,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']]` @@ -4993,23 +4992,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` @@ -5022,7 +5024,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 }` @@ -5034,18 +5036,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 }` @@ -5068,13 +5070,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/en-EN/README.md b/en-EN/README.md deleted file mode 100644 index 3db2b3b3..00000000 --- a/en-EN/README.md +++ /dev/null @@ -1,5089 +0,0 @@ -
- -

JavaScript Questions

- ---- - -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: - -Feel free to reach out to me! 😊
- Instagram || Twitter || LinkedIn || Blog -
- ---- - -
See 16 Available Translations 🇪🇸🇮🇹🇩🇪 🇫🇷🇷🇺🇨🇳🇵🇹 -

- -* [English](../en-EN/README.md) -* [العربية](../ar-AR/README_AR.md) -* [اللغة العامية - Egyptian Arabic](../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) -* [日本語](../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) -* [Українська мова](../ua-UA/README-ua_UA.md) -* [Tiếng Việt](../vi-VI/README-vi.md) -* [简体中文](../zh-CN/README-zh_CN.md) -* [繁體中文](../zh-TW/README-zh_TW.md) -* [Türkçe](../tr-TR/README-tr_TR.md) -* [ไทย](../th-TH/README-th_TH.md) -* [Indonesia](../id-ID/README.md) - -

-
- ---- - -###### 1. What's the output? - -```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` - -
Answer -

- -#### Answer: D - -Within the function, we first declare the `name` variable with the `var` keyword. This means that the variable gets hoisted (memory space is set up during the creation phase) with the default value of `undefined`, until we actually get to the line where we define the variable. We haven't defined the variable yet on the line where we try to log the `name` variable, so it still holds the value of `undefined`. - -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`. - -

-
- ---- - -###### 2. What's the 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` and `0 1 2` -- B: `0 1 2` and `3 3 3` -- C: `3 3 3` and `0 1 2` - -
Answer -

- -#### Answer: C - -Because of the event queue in JavaScript, the `setTimeout` callback function is called _after_ the loop has been executed. Since the variable `i` in the first loop was declared using the `var` keyword, this value was global. During the loop, we incremented the value of `i` by `1` each time, using the unary operator `++`. By the time the `setTimeout` callback function was invoked, `i` was equal to `3` in the first example. - -In the second loop, the variable `i` was declared using the `let` keyword: variables declared with the `let` (and `const`) keyword are block-scoped (a block is anything between `{ }`). During each iteration, `i` will have a new value, and each value is scoped inside the loop. - -

-
- ---- - -###### 3. What's the 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` and `62.83185307179586` -- B: `20` and `NaN` -- C: `20` and `63` -- D: `NaN` and `63` - -
Answer -

- -#### Answer: B - -Note that the value of `diameter` is a regular function, whereas the value of `perimeter` is an arrow function. - -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 `undefined`. - -

-
- ---- - -###### 4. What's the output? - -```javascript -+true; -!'Lydia'; -``` - -- A: `1` and `false` -- B: `false` and `NaN` -- C: `false` and `false` - -
Answer -

- -#### Answer: A - -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`. - -

-
- ---- - -###### 5. Which one is true? - -```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 - -
Answer -

- -#### Answer: A - -In JavaScript, all object keys are strings (unless it's a Symbol). Even though we might not _type_ them as strings, they are always converted into strings under the hood. - -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. - -`mouse[bird.size]`: First it evaluates `bird.size`, which is `"small"`. `mouse["small"]` returns `true` - -However, with dot notation, this doesn't happen. `mouse` does not have a key called `bird`, which means that `mouse.bird` is `undefined`. Then, we ask for the `size` using dot notation: `mouse.bird.size`. Since `mouse.bird` is `undefined`, we're actually asking `undefined.size`. This isn't valid, and will throw an error similar to `Cannot read property "size" of undefined`. - -

-
- ---- - -###### 6. What's the 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` - -
Answer -

- -#### Answer: A - -In JavaScript, all objects interact by _reference_ when setting them equal to each other. - -First, variable `c` holds a value to an object. Later, we assign `d` with the same reference that `c` has to the object. - - - -When you change one object, you change all of them. - -

-
- ---- - -###### 7. What's the 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` - -
Answer -

- -#### Answer: 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`. - -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.` - -

-
- ---- - -###### 8. What's the 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` - -
Answer -

- -#### 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. - -

-
- ---- - -###### 9. What's the output? - -```javascript -let greeting; -greetign = {}; // Typo! -console.log(greetign); -``` - -- A: `{}` -- B: `ReferenceError: greetign is not defined` -- C: `undefined` - -
Answer -

- -#### 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). - -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. - -

-
- ---- - -###### 10. What happens when we do this? - -```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` - -
Answer -

- -#### Answer: A - -This is possible in JavaScript, because functions are objects! (Everything besides primitive types are objects) - -A function is a special type of object. The code you write yourself isn't the actual function. The function is an object with properties. This property is invocable. - -

-
- ---- - -###### 11. What's the 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` - -
Answer -

- -#### Answer: A - -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() { - return `${this.firstName} ${this.lastName}`; -}; -``` - -would have made `member.getFullName()` work. Why is this beneficial? Say that we added this method to the constructor itself. Maybe not every `Person` instance needed this method. This would waste a lot of memory space, since they would still have that property, which takes of memory space for each instance. Instead, if we only add it to the prototype, we just have it at one spot in memory, yet they all have access to it! - -

-
- ---- - -###### 12. What's the 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` - -
Answer -

- -#### Answer: 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 - -
Answer -

- -#### Answer: 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 - -
Answer -

- -#### Answer: 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. What's the output? - -```javascript -function sum(a, b) { - return a + b; -} - -sum(1, '2'); -``` - -- A: `NaN` -- B: `TypeError` -- C: `"12"` -- D: `3` - -
Answer -

- -#### Answer: 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. What's the 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` - -
Answer -

- -#### Answer: 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. What's the 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` - -
Answer -

- -#### Answer: 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. What's the 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` - -
Answer -

- -#### Answer: 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. What's the output? - -```javascript -function getAge(...args) { - console.log(typeof args); -} - -getAge(21); -``` - -- A: `"number"` -- B: `"array"` -- C: `"object"` -- D: `"NaN"` - -
Answer -

- -#### Answer: 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. What's the output? - -```javascript -function getAge() { - 'use strict'; - age = 21; - console.log(age); -} - -getAge(); -``` - -- A: `21` -- B: `undefined` -- C: `ReferenceError` -- D: `TypeError` - -
Answer -

- -#### Answer: 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 value of `sum`? - -```javascript -const sum = eval('10*10+5'); -``` - -- A: `105` -- B: `"105"` -- C: `TypeError` -- D: `"10*10+5"` - -
Answer -

- -#### 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`. - -

-
- ---- - -###### 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. - -
Answer -

- -#### Answer: 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. What's the output? - -```javascript -var num = 8; -var num = 10; - -console.log(num); -``` - -- A: `8` -- B: `10` -- C: `SyntaxError` -- D: `ReferenceError` - -
Answer -

- -#### Answer: 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. What's the 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` - -
Answer -

- -#### Answer: 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. What's the 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` - -
Answer -

- -#### Answer: 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 - -
Answer -

- -#### Answer: A - -The base execution context is the global execution context: it's what's accessible everywhere in your code. - -

-
- ---- - -###### 27. What's the 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` - -
Answer -

- -#### Answer: C - -The `continue` statement skips an iteration if a certain condition returns `true`. - -

-
- ---- - -###### 28. What's the 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` - -
Answer -

- -#### 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! - -

-
- ---- - -###### 29. What's the 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` - -
Answer -

- -#### Answer: 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. What's the 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` - -
Answer -

- -#### Answer: 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. - -
Answer -

- -#### Answer: 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` - -
Answer -

- -#### 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. - -

-
- ---- - -###### 33. What's the 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` - -
Answer -

- -#### Answer: 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. What's the output? - -```javascript -function sayHi() { - return (() => 0)(); -} - -console.log(typeof sayHi()); -``` - -- A: `"object"` -- B: `"number"` -- C: `"function"` -- D: `"undefined"` - -
Answer -

- -#### Answer: B - -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`, and `bigint`. `"function"` is not a type, since functions are objects, it's of type `"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 - -
Answer -

- -#### Answer: A - -There are only six falsy values: - -- `undefined` -- `null` -- `NaN` -- `0` -- `''` (empty string) -- `false` - -Function constructors, like `new Number` and `new Boolean` are truthy. - -

-
- ---- - -###### 36. What's the output? - -```javascript -console.log(typeof typeof 1); -``` - -- A: `"number"` -- B: `"string"` -- C: `"object"` -- D: `"undefined"` - -
Answer -

- -#### Answer: B - -`typeof 1` returns `"number"`. -`typeof "number"` returns `"string"` - -

-
- ---- - -###### 37. What's the 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` - -
Answer -

- -#### Answer: 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, 7 x empty, 11]` - -depending on where you run it (it's different for every browser, node, etc.) - -

-
- ---- - -###### 38. What's the 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` - -
Answer -

- -#### Answer: 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 - -
Answer -

- -#### Answer: 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 object 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. What's the 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]` - -
Answer -

- -#### Answer: 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. What's the output? - -```javascript -!!null; -!!''; -!!1; -``` - -- A: `false` `true` `false` -- B: `false` `false` `true` -- C: `false` `true` `true` -- D: `true` `true` `false` - -
Answer -

- -#### Answer: 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` - -
Answer -

- -#### Answer: 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"]]` - -
Answer -

- -#### Answer: A - -A string is an iterable. The spread operator maps every character of an iterable to one element. - -

-
- ---- - -###### 44. What's the 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` - -
Answer -

- -#### Answer: 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"` - -
Answer -

- -#### Answer: 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. What's the output? - -```javascript -let person = { name: 'Lydia' }; -const members = [person]; -person = null; - -console.log(members); -``` - -- A: `null` -- B: `[null]` -- C: `[{}]` -- D: `[{ name: "Lydia" }]` - -
Answer -

- -#### Answer: 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. What's the 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]` - -
Answer -

- -#### Answer: 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. What's the output? - -```javascript -console.log(3 + 4 + '5'); -``` - -- A: `"345"` -- B: `"75"` -- C: `12` -- D: `"12"` - -
Answer -

- -#### Answer: 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` - -
Answer -

- -#### 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. - -`*` is not a valid number. It only parses `"7"` into the decimal `7`. `num` now holds the value of `7`. - -

-
- ---- - -###### 50. What's the 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 ]` - -
Answer -

- -#### Answer: 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. What's the 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"` - -
Answer -

- -#### Answer: 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. What's the 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!` - -
Answer -

- -#### Answer: 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. What's the 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` - -
Answer -

- -#### 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"`. - -

-
- ---- - -###### 54. What's the 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"` - -
Answer -

- -#### Answer: 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 (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. What's the 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` - -
Answer -

- -#### Answer: 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. What's the 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}` - -
Answer -

- -#### Answer: 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. What's the 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` - -
Answer -

- -#### Answer: 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. What's the 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` - -
Answer -

- -#### 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 `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. What's the 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]` - -
Answer -

- -#### Answer: 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. What's the 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 }` - -
Answer -

- -#### Answer: 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. What's the 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"]` - -
Answer -

- -#### Answer: 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. What's the 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}"` - -
Answer -

- -#### Answer: 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. What's the 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` - -
Answer -

- -#### 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. - -`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. What's the 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` - -
Answer -

- -#### Answer: 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. What's the 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` - -
Answer -

- -#### Answer: 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 - -
Answer -

- -#### Answer: 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. What's the 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` - -
Answer -

- -#### 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_. - -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. What's the 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` - -
Answer -

- -#### Answer: 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. What's the 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"`, - -
Answer -

- -#### Answer: 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. What's the output? - -```javascript -console.log('🥑' + '💻'); -``` - -- A: `"🥑💻"` -- B: `257548` -- C: A string containing their code points -- D: Error - -
Answer -

- -#### Answer: 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 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")` - -
Answer -

- -#### Answer: 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. What's the output? - -```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` 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. What's the 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` - -
Answer -

- -#### Answer: 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. What's the 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` - -
Answer -

- -#### Answer: 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. What's the 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` - -
Answer -

- -#### Answer: 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)` returns 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. What's the output? - -```javascript -const { name: myName } = { name: 'Lydia' }; - -console.log(name); -``` - -- A: `"Lydia"` -- B: `"myName"` -- C: `undefined` -- D: `ReferenceError` - -
Answer -

- -#### 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, a ReferenceError gets thrown. - -

-
- ---- - -###### 77. Is this a pure function? - -```javascript -function sum(a, b) { - return a + b; -} -``` - -- A: Yes -- B: No - -
Answer -

- -#### Answer: 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` - -
Answer -

- -#### Answer: 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: "🍫"}` - -
Answer -

- -#### Answer: 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]` - -
Answer -

- -#### Answer: 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` - -
Answer -

- -#### Answer: 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 `"😎"` - -
Answer -

- -#### Answer: 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"` - -
Answer -

- -#### Answer: 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` - -
Answer -

- -#### 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. - -

-
- ---- - -###### 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. - -
Answer -

- -#### Answer: 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` - -
Answer -

- -#### 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`. - -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. What's the output? - -```javascript -console.log('I want pizza'[0]); -``` - -- A: `"""` -- B: `"I"` -- C: `SyntaxError` -- D: `undefined` - -
Answer -

- -#### 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. - -Note that this method is not supported in IE7 and below. In that case, use `.charAt()` - -

-
- ---- - -###### 88. What's the output? - -```javascript -function sum(num1, num2 = num1) { - console.log(num1 + num2); -} - -sum(10); -``` - -- A: `NaN` -- B: `20` -- C: `ReferenceError` -- D: `undefined` - -
Answer -

- -#### Answer: 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. What's the 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` - -
Answer -

- -#### 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"`. - -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. What's the 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"` - -
Answer -

- -#### Answer: C - -Classes are syntactical sugar for function constructors. The equivalent of the `Person` class as a function constructor would be: - -```javascript -function Person() { - 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. What's the 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` - -
Answer -

- -#### Answer: 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. What's the 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` - -
Answer -

- -#### Answer: 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. What's the output? - -```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` - -
Answer -

- -#### Answer: 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. What's the 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` - -
Answer -

- -#### Answer: 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. What's the 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` - -
Answer -

- -#### Answer: 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. What's the 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` - -
Answer -

- -#### Answer: 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. What's the output? - -```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 `[]` - -
Answer -

- -#### Answer: 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. What's the 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]]` 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 }` - -
Answer -

- -#### Answer: 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 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 })` - -Since no value gets returned in this case, the function returns `undefined`. - -

-
- ---- - -###### 99. What's the output? - -```javascript -const name = 'Lydia'; - -console.log(name()); -``` - -- A: `SyntaxError` -- B: `ReferenceError` -- C: `TypeError` -- D: `undefined` - -
Answer -

- -#### Answer: 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` - -
Answer -

- -#### Answer: 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` - -
Answer -

- -#### Answer: 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` - -
Answer -

- -#### Answer: 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` - -
Answer -

- -#### Answer: 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` - -
Answer -

- -#### Answer: 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` - -
Answer -

- -#### Answer: 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` - -
Answer -

- -#### Answer: 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` - -
Answer -

- -#### Answer: 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` - -
Answer -

- -#### Answer: 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. What's the output? - -```javascript -const food = ['🍕', '🍫', '🥑', '🍔']; -const info = { favoriteFood: food[0] }; - -info.favoriteFood = '🍝'; - -console.log(food); -``` - -- A: `['🍕', '🍫', '🥑', '🍔']` -- B: `['🍝', '🍫', '🥑', '🍔']` -- C: `['🍝', '🍕', '🍫', '🥑', '🍔']` -- D: `ReferenceError` - -
Answer -

- -#### Answer: 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 - -
Answer -

- -#### Answer: 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. What's the output? - -```javascript -let name = 'Lydia'; - -function getName() { - console.log(name); - let name = 'Sarah'; -} - -getName(); -``` - -- A: Lydia -- B: Sarah -- C: `undefined` -- D: `ReferenceError` - -
Answer -

- -#### Answer: 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. What's the 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` and `a` -- B: `a` and `undefined` -- C: `['a', 'b', 'c']` and `a` -- D: `a` and `['a', 'b', 'c']` - -
Answer -

- -#### Answer: 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. What's the 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` - -
Answer -

- -#### Answer: 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` - -
Answer -

- -#### 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). - -

-
- ---- - -###### 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 - -
Answer -

- -#### Answer: 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. What's the 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}` - -
Answer -

- -#### Answer: 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])` - -
Answer -

- -#### Answer: 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. What's the output? - -```javascript -let num = 1; -const list = ['🥳', '🤠', '🥰', '🤪']; - -console.log(list[(num += 1)]); -``` - -- A: `🤠` -- B: `🥰` -- C: `SyntaxError` -- D: `ReferenceError` - -
Answer -

- -#### 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 🥰. - -

-
- ---- - -###### 119. What's the 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` - -
Answer -

- -#### Answer: 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?.()`: `member` is not defined: `member.getLastName()` is nullish. The expression returns `undefined`. - -

-
- ---- - -###### 120. What's the 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` - -
Answer -

- -#### Answer: 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. What's the 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` - -
Answer -

- -#### Answer: 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. What's the 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` - -
Answer -

- -#### Answer: 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. What's the 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` - -
Answer -

- -#### Answer: 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. What's the 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` - -
Answer -

- -#### 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`. - -

-
- ---- - -###### 125. What's the 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` - -
Answer -

- -#### Answer: 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. What's the 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 - -
Answer -

- -#### Answer: 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 `currentcy` in `USD` results in `$300.00`. - -

-
- ---- - -###### 127. What's the output? - -```javascript -const spookyItems = ['👻', '🎃', '🕸']; -({ item: spookyItems[3] } = { item: '💀' }); - -console.log(spookyItems); -``` - -- A: `["👻", "🎃", "🕸"]` -- B: `["👻", "🎃", "🕸", "💀"]` -- C: `["👻", "🎃", "🕸", { item: "💀" }]` -- D: `["👻", "🎃", "🕸", "[object Object]"]` - -
Answer -

- -#### Answer: 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. What's the 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` - -
Answer -

- -#### Answer: 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. What's the output? - -```javascript -const randomValue = 21; - -function getInfo() { - console.log(typeof randomValue); - const randomValue = 'Lydia Hallie'; -} - -getInfo(); -``` - -- A: `"number"` -- B: `"string"` -- C: `undefined` -- D: `ReferenceError` - -
Answer -

- -#### 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. - -

-
- ---- - -###### 130. What's the 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!` - -
Answer -

- -#### Answer: 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. What's the output? - -```javascript -const emojis = ['🥑', ['✨', '✨', ['🍕', '🍕']]]; - -console.log(emojis.flat(1)); -``` - -- A: `['🥑', ['✨', '✨', ['🍕', '🍕']]]` -- B: `['🥑', '✨', '✨', ['🍕', '🍕']]` -- C: `['🥑', ['✨', '✨', '🍕', '🍕']]` -- D: `['🥑', '✨', '✨', '🍕', '🍕']` - -
Answer -

- -#### Answer: 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. What's the 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` - -
Answer -

- -#### Answer: 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 the `counterTwo.increment()`, which sets the `count` to `3`. Then, we log the count on `counterOne`, which logs `3`. - - - -

-
- ---- - -###### 133. What's the output? - -```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!` - -
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.) - -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. - -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!`. - -The next line is the _asynchronous_ `setTimeout` function, from which the callback is sent to the Web API. - -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!` - -

-
- ---- - -###### 134. How can we invoke `sum` in `index.js` from `sum.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 - -
Answer -

- -#### Answer: 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. What's the 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: Nothing gets logged - -
Answer -

- -#### Answer: C - -With a Proxy object, we can add custom behavior to an object that we pass to it as the second argument. In tis 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. - -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 })` - -
Answer -

- -#### Answer: A - -With `Object.seal` we can prevent new properies 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" }` - -
Answer -

- -#### Answer: 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. What's the 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` - -
Answer -

- -#### 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`. - -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. What's the 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` - -
Answer -

- -#### 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! - -

-
- ---- - -###### 140. What's the 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)` - -
Answer -

- -#### Answer: 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. What's the 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"]` - -
Answer -

- -#### Answer: 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 `y`, `"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 `"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. - -After pushing `dancing` and `baking`, the value of `person.hobbies` is `["coding", "dancing", "baking"]` - -

-
- ---- - -###### 142. What's the 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: Nothing, we didn't call any method - -
Answer -

- -#### Answer: 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 - -
Answer -

- -#### Answer: 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 propeties 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 }` - -
Answer -

- -#### Answer: 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)`. - -

-
- ------ - -###### 146. What's the 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 - -
Answer -

- -#### 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`. - -

-
- ---- - -###### 147. What's the output? - -```javascript -function getFruit(fruits) { - console.log(fruits?.[1]?.[1]) -} - -getFruit([['🍊', '🍌'], ['🍍']]) -getFruit() -getFruit([['🍍'], ['🍊', '🍌']]) -``` - -- A: `null`, `undefined`, 🍌 -- B: `[]`, `null`, 🍌 -- C: `[]`, `[]`, 🍌 -- D: `undefined`, `undefined`, 🍌 - -
Answer -

- -#### 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`. - -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. - -

-
- ---- - -###### 148. What's the 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` - -
Answer -

- -#### Answer: 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`. - -

-
- ---- - -###### 149. What's the 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` - -
Answer -

- -#### Answer: 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`. - -

-
- ---- - -###### 150. What's the output? - -```javascript -const fruit = ['🍌', '🍊', '🍎'] - -fruit.slice(0, 1) -fruit.splice(0, 1) -fruit.unshift('🍇') -``` - -- A: `['🍌', '🍊', '🍎']` -- B: `['🍊', '🍎']` -- C: `['🍇', '🍊', '🍎']` -- D: `['🍇', '🍌', '🍊', '🍎']` - -
Answer -

- -#### Answer: 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 `['🍇', '🍊', '🍎']`. - -

-
- ---- - -###### 151. What's the 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` - -
Answer -

- -#### Answer: 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" }`. - -

-
- ---- - -###### 152. What's the 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` - -
Answer -

- -#### 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. - -

-
- ---- - -###### 153. 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 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'` - -
Answer -

- -#### 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. - -

-
- ---- - -###### 154. 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` - -
Answer -

- -#### 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. - -This creates an array of subarrays containing the correct keys and values, which results in `{ name: "Lydia", age: 22 }` - -

-
- ---- - -###### 155. What's the 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 }` - -
Answer -

- -#### 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 `{}`. - -

-
- ---- - -###### 156. What's the 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` - -
Answer -

- -#### Answer: 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 `"string"`, 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 e818a5b0e8788755393d30a6a2dbd893b9c65b1d Mon Sep 17 00:00:00 2001 From: Jacob Herper Date: Thu, 24 Sep 2020 15:41:37 +0100 Subject: [PATCH 648/915] Cleans up German translation --- de-DE/README.md | 1101 ++++++++++++++++++++++++----------------------- 1 file changed, 553 insertions(+), 548 deletions(-) diff --git a/de-DE/README.md b/de-DE/README.md index 42a3827a..d2601056 100644 --- a/de-DE/README.md +++ b/de-DE/README.md @@ -1,49 +1,60 @@ -# JavaScript Fragen (für Fortgeschrittene) - +
+ +

JavaScript Fragen

Täglich poste ich mehrere Multiple-Choice-Fragen über JavaScript auf meinem [Instagram](https://www.instagram.com/theavocoder), die ich nun auch hier veröffentlichen werde. Von einfach bis fortgeschritten: teste wie gut du JavaScript kennst, frische dein Wissen auf oder bereite dich auf ein Vorstellungsgespräch vor! :muscle: :rocket: Ich werde dieses Repo wöchentlich mit neuen Fragen erweitern. Die Antworten sind unterhalb der Fragen versteckt. Du kannst einfach darauf klicken um die Antworten anzuzeigen. Viel Glück :heart: -### Alle verfügbaren Sprachen -* [English](../en-EN/README.md) -* [العربية](../ar-AR/README_AR.md) -* [اللغة العامية - Egyptian Arabic](../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) -* [日本語](../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) -* [Українська мова](../ua-UA/README-ua_UA.md) -* [Tiếng Việt](../vi-VI/README-vi.md) -* [中文版本](../zh-CN/README-zh_CN.md) -* [Türkçe](../tr-TR/README-tr_TR.md) -* [ไทย](../th-TH/README-th_TH.md) +
--- -###### 1. Was ist der Output? +
Alle 18 Übersetzungen anzeigen 🇸🇦🇪🇬🇧🇦🇩🇪🇪🇸🇫🇷🇮🇩🇯🇵🇰🇷🇳🇱🇧🇷🇷🇺🇹🇭🇹🇷🇺🇦🇻🇳🇨🇳🇹🇼 +

+ +- [🇸🇦 العربية](./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) +- [🇯🇵 日本語](./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) +- [🇺🇦 Українська мова](./ua-UA/README-ua_UA.md) +- [🇻🇳 Tiếng Việt](./vi-VI/README-vi.md) +- [🇨🇳 简体中文](./zh-CN/README-zh_CN.md) +- [🇹🇼 繁體中文](./zh-TW/README_zh-TW.md) + +

+
+ +--- + +###### 1. Was wird ausgegeben? ```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

@@ -59,21 +70,21 @@ Variablen mit dem `let` (oder `const`) Keyword werden ebenfalls gehoisted, aber --- -###### 2. Was ist der Output? +###### 2. Was wird ausgegeben? ```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

@@ -89,25 +100,25 @@ In der zweiten Schleife wurde die Variable `i` mit dem `let` Keyword definiert: --- -###### 3. Was ist der Output? +###### 3. Was wird ausgegeben? ```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

@@ -125,16 +136,16 @@ Es gibt keinen Wert `radius` in dem Object, daher wird `undefined` zurückgegebe --- -###### 4. Was ist der Output? +###### 4. Was wird ausgegeben? ```javascript +true; !"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

@@ -154,19 +165,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

@@ -186,7 +197,7 @@ Mit der Dot Notation ist das nicht der Fall. `mouse` hat keinen Key namens `bird --- -###### 6. Was ist der Output? +###### 6. Was wird ausgegeben? ```javascript let c = { greeting: "Hey!" }; @@ -197,11 +208,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

@@ -221,7 +232,7 @@ Wenn ein Object geändert wird, werden alle Referenzen zu diesem Object ebenfall --- -###### 7. Was ist der Output? +###### 7. Was wird ausgegeben? ```javascript let a = 3; @@ -233,10 +244,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

@@ -254,28 +265,28 @@ Wenn wir aber `===` nutzen müssen sowohl der Wert _als auch_ der Typ übereinst --- -###### 8. Was ist der Output? +###### 8. Was wird ausgegeben? ```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

@@ -289,7 +300,7 @@ Die `colorChange` Funktion ist statisch (`static`). Statische Methoden existiere --- -###### 9. Was ist der Output? +###### 9. Was wird ausgegeben? ```javascript let greeting; @@ -297,9 +308,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

@@ -319,16 +330,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

@@ -344,26 +355,26 @@ Eine Funktion ist ein spezieller Typ eines Objekts. Der Code, den wir schreiben --- -###### 11. Was ist der Output? +###### 11. Was wird ausgegeben? ```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

@@ -373,8 +384,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}`; }; ``` @@ -386,12 +397,12 @@ Stattdessen haben wir sie nur dem Prototype zugewiesen, sodass sie nur an einer --- -###### 12. Was ist der Output? +###### 12. Was wird ausgegeben? ```javascript function Person(firstName, lastName) { - this.firstName = firstName; - this.lastName = lastName; + this.firstName = firstName; + this.lastName = lastName; } const lydia = new Person("Lydia", "Hallie"); @@ -401,10 +412,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

@@ -422,10 +433,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

@@ -443,8 +454,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

@@ -458,20 +469,20 @@ Alle Objekte haben Prototypes, außer dem **Basis Objekt**. Das Basis Objekt hat --- -###### 15. Was ist der Output? +###### 15. Was wird ausgegeben? ```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

@@ -487,7 +498,7 @@ In diesem Beispiel wandelt JavaScript die Nummer `1` in einem String um, sodass --- -###### 16. Was ist der Output? +###### 16. Was wird ausgegeben? ```javascript let number = 0; @@ -496,10 +507,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

@@ -523,13 +534,13 @@ Der Output ist daher `0 2 2`. --- -###### 17. Was ist der Output? +###### 17. Was wird ausgegeben? ```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"; @@ -538,9 +549,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

@@ -554,25 +565,25 @@ Wenn man Template Literals verwendet ist das erste Argument immer ein Array der --- -###### 18. Was ist der Output? +###### 18. Was wird ausgegeben? ```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

@@ -590,20 +601,20 @@ Deshalb werfen sowohl `{ age: 18 } === { age: 18 }` als auch `{ age: 18 } == { a --- -###### 19. Was ist der Output? +###### 19. Was wird ausgegeben? ```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

@@ -617,22 +628,22 @@ Der Spread Operator (`...args`) gibt ein Array mit Argumenten zurück. Ein Array --- -###### 20. Was ist der Output? +###### 20. Was wird ausgegeben? ```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

@@ -652,10 +663,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

@@ -675,10 +686,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

@@ -694,7 +705,7 @@ Wenn man stattdessen `localStorage` verwendet, bleibt der Wert für immer besteh --- -###### 23. Was ist der Output? +###### 23. Was wird ausgegeben? ```javascript var num = 8; @@ -703,10 +714,10 @@ var num = 10; console.log(num); ``` -- A: `8` -- B: `10` -- C: `SyntaxError` -- D: `ReferenceError` +- A: `8` +- B: `10` +- C: `SyntaxError` +- D: `ReferenceError`

Antwort

@@ -722,7 +733,7 @@ Das ist nicht möglich mit `let` oder `const`, da diese dem Block Scope unterlie --- -###### 24. Was ist der Output? +###### 24. Was wird ausgegeben? ```javascript const obj = { 1: "a", 2: "b", 3: "c" }; @@ -734,10 +745,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

@@ -753,17 +764,17 @@ Das funktioniert nicht für Set. Da wir keine `'1'` in unserem Set haben wirft ` --- -###### 25. Was ist der Output? +###### 25. Was wird ausgegeben? ```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` +- A: `{ a: "one", b: "two" }` +- B: `{ b: "two", a: "three" }` +- C: `{ a: "three", b: "two" }` +- D: `SyntaxError`

Antwort

@@ -779,9 +790,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

@@ -795,19 +806,19 @@ Der Base Execution Context entspricht dem Global Execution Context und ist über --- -###### 27. Was ist der Output? +###### 27. Was wird ausgegeben? ```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

@@ -821,11 +832,11 @@ for (let i = 1; i < 5; i++) { --- -###### 28. Was ist der Output? +###### 28. Was wird ausgegeben? ```javascript String.prototype.giveLydiaPizza = () => { - return "Just give Lydia pizza already!"; + return "Just give Lydia pizza already!"; }; const name = "Lydia"; @@ -833,10 +844,10 @@ const name = "Lydia"; 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

@@ -850,7 +861,7 @@ name.giveLydiaPizza(); --- -###### 29. Was ist der Output? +###### 29. Was wird ausgegeben? ```javascript const a = {}; @@ -863,10 +874,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

@@ -884,7 +895,7 @@ Dann loggen wir `a[b]`, was eigentlich `a["object Object"]` ist und gerade von u --- -###### 30. Was ist der Output? +###### 30. Was wird ausgegeben? ```javascript const foo = () => console.log("First"); @@ -896,10 +907,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

@@ -941,18 +952,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

@@ -970,16 +979,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

@@ -993,23 +1000,23 @@ Wenn wir auf den Paragraph klicken, sehen wir zwei logs: `p` und `div`. Während --- -###### 33. Was ist der Output? +###### 33. Was wird ausgegeben? ```javascript 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

@@ -1025,20 +1032,20 @@ In beiden Fällen können wir das Objekt weiter reichen, auf welches sich das `t --- -###### 34. Was ist der Output? +###### 34. Was wird ausgegeben? ```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

@@ -1065,10 +1072,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

@@ -1077,12 +1084,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. @@ -1091,16 +1098,16 @@ Funktions-Constructor, wie `new Number` und `new Boolean` sind truthy. --- -###### 36. Was ist der Output? +###### 36. Was wird ausgegeben? ```javascript console.log(typeof typeof 1); ``` -- A: `"number"` -- B: `"string"` -- C: `"object"` -- D: `"undefined"` +- A: `"number"` +- B: `"string"` +- C: `"object"` +- D: `"undefined"`

Antwort

@@ -1115,7 +1122,7 @@ console.log(typeof typeof 1); --- -###### 37. Was ist der Output? +###### 37. Was wird ausgegeben? ```javascript const numbers = [1, 2, 3]; @@ -1123,10 +1130,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

@@ -1144,26 +1151,26 @@ abhängig davon wo das Array ausgeführt wird (die Ausgabe ist unterschiedlich f --- -###### 38. Was ist der Output? +###### 38. Was wird ausgegeben? ```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

@@ -1183,10 +1190,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

@@ -1204,21 +1211,24 @@ Was einen primitiven Typ von einem Objekt unterscheidet ist, dass Primitive kein --- -###### 40. Was ist der Output? +###### 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

@@ -1234,7 +1244,7 @@ Dann entspricht `acc` gleich `[1, 2, 0, 1]` und `cur` ist gleich `[2, 3]`. Wir v --- -###### 41. Was ist der Output? +###### 41. Was wird ausgegeben? ```javascript !!null; @@ -1242,10 +1252,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

@@ -1269,10 +1279,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

@@ -1292,10 +1302,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

@@ -1309,7 +1319,7 @@ Ein String ist ein Iterable. Der Spread Operator mappt jedes Zeichen eines Itera --- -###### 44. Was ist der Output? +###### 44. Was wird ausgegeben? ```javascript function* generator(i) { @@ -1355,7 +1365,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"` @@ -1375,7 +1385,7 @@ Wenn wir mehrere Promises in die `Promice.race` Methode eingegeben, wird das Pro --- -###### 46. Was ist der Output? +###### 46. Was wird ausgegeben? ```javascript let person = { name: "Lydia" }; @@ -1414,12 +1424,12 @@ Wir ändern nur den Wert der Variable `person` und nicht das erste Element im Ar --- -###### 47. Was ist der Output? +###### 47. Was wird ausgegeben? ```javascript const person = { name: "Lydia", - age: 21 + age: 21, }; for (const item in person) { @@ -1444,7 +1454,7 @@ Mit einer `for-in` Schleife können wir über Objekt Keys iterieren - in diesem --- -###### 48. Was ist der Output? +###### 48. Was wird ausgegeben? ```javascript console.log(3 + 4 + "5"); @@ -1496,10 +1506,10 @@ Nur die erste Zahl im String wird ausgegeben. Aufgrund des _radix_ (das zweite A --- -###### 50. Was ist der Output? +###### 50. Was wird ausgegeben? ```javascript -[1, 2, 3].map(num => { +[1, 2, 3].map((num) => { if (typeof num === "number") return; return num * 2; }); @@ -1524,7 +1534,7 @@ Allerdings geben wir keinen Wert aus. Wenn unsere Funktion keinen Wert ausgibt, --- -###### 51. Was ist der Output? +###### 51. Was wird ausgegeben? ```javascript function getInfo(member, year) { @@ -1561,7 +1571,7 @@ Der Wert von `person` ist ein Objekt, sodass das Argument `member` eine Kopie de --- -###### 52. Was ist der Output? +###### 52. Was wird ausgegeben? ```javascript function greeting() { @@ -1599,7 +1609,7 @@ Mit dem `catch` Statement können wir definieren, was passiert, wenn die Excepti --- -###### 53. Was ist der Output? +###### 53. Was wird ausgegeben? ```javascript function Car() { @@ -1628,7 +1638,7 @@ Wenn man eine Property ausgibt ist der Wert der Property gleich dem ausgegeben W --- -###### 54. Was ist der Output? +###### 54. Was wird ausgegeben? ```javascript (() => { @@ -1665,10 +1675,9 @@ Da wir die Variable `y` aber global erstellt haben ist ihr Wert `10` auch hier v

- --- -###### 55. Was ist der Output? +###### 55. Was wird ausgegeben? ```javascript class Dog { @@ -1677,7 +1686,7 @@ class Dog { } } -Dog.prototype.bark = function() { +Dog.prototype.bark = function () { console.log(`Woof I am ${this.name}`); }; @@ -1709,7 +1718,7 @@ Wenn wir versuchen etwas auszuführen, was keine Funktion ist, wird ein `TypeErr --- -###### 56. Was ist der Output? +###### 56. Was wird ausgegeben? ```javascript const set = new Set([1, 1, 2, 3, 4]); @@ -1736,7 +1745,7 @@ Wir übergeben `[1, 1, 2, 3, 4]` mit einer doppelten `1`. Da wir keine doppelten --- -###### 57. Was ist der Output? +###### 57. Was wird ausgegeben? ```javascript // counter.js @@ -1772,7 +1781,7 @@ Wenn wir also den Wert von `myCounter` erhöhen bekommen wir den Fehler `myCount --- -###### 58. Was ist der Output? +###### 58. Was wird ausgegeben? ```javascript const name = "Lydia"; @@ -1792,7 +1801,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. @@ -1801,7 +1810,7 @@ Der Wert von `name` wurde mit `const` deklariert, weshalb `delete` nicht möglic --- -###### 59. Was ist der Output? +###### 59. Was wird ausgegeben? ```javascript const numbers = [1, 2, 3, 4, 5]; @@ -1843,7 +1852,7 @@ Das bedeutet, dass der Wert von `y` gleich des ersten Wertes im Array ist, spric --- -###### 60. Was ist der Output? +###### 60. Was wird ausgegeben? ```javascript const user = { name: "Lydia", age: 21 }; @@ -1869,7 +1878,7 @@ Es ist möglich Objekte mit dem Spread Operator `...` zu verbinden. Dieser erste --- -###### 61. Was ist der Output? +###### 61. Was wird ausgegeben? ```javascript const person = { name: "Lydia" }; @@ -1899,13 +1908,13 @@ Properties, die mit `defineProperty` erstellt wurden sind standardmäßig unver --- -###### 62. Was ist der Output? +###### 62. Was wird ausgegeben? ```javascript const settings = { username: "lydiahallie", level: 19, - health: 90 + health: 90, }; const data = JSON.stringify(settings, ["level", "health"]); @@ -1933,13 +1942,13 @@ Wenn der Replacer eine _Funktion_ ist, so wird diese Funktion für jede Property --- -###### 63. Was ist der Output? +###### 63. Was wird ausgegeben? ```javascript let num = 10; const increaseNumber = () => num++; -const increasePassedNumber = number => number++; +const increasePassedNumber = (number) => number++; const num1 = increaseNumber(); const num2 = increasePassedNumber(num1); @@ -1965,11 +1974,9 @@ Der unäre Operator `++` _gibt zuerst_ den Wert des Operanden aus und _erhöht d

- - --- -###### 64. Was ist der Output? +###### 64. Was wird ausgegeben? ```javascript const value = { number: 10 }; @@ -2007,7 +2014,7 @@ Beim vierten Mal übergeben wir wieder eine `value`. `x.number` wurde zuvor in ` --- -###### 65. Was ist der Output? +###### 65. Was wird ausgegeben? ```javascript [1, 2, 3, 4].reduce((x, y) => console.log(x, y)); @@ -2034,6 +2041,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. +

@@ -2046,10 +2054,10 @@ class Dog { constructor(name) { this.name = name; } -}; +} class Labrador extends Dog { - // 1 + // 1 constructor(name, size) { this.size = size; } @@ -2063,13 +2071,12 @@ class Labrador extends Dog { super(name); this.size = size; } - // 4 + // 4 constructor(name, size) { this.name = name; this.size = size; } - -}; +} ``` - A: 1 @@ -2087,6 +2094,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. +

@@ -2124,12 +2132,12 @@ Das ist der große Unterschied zwischen `require()` in CommonJS und `import`. Mi --- -###### 68. Was ist der Output? +###### 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` @@ -2142,25 +2150,25 @@ console.log(Symbol('foo') === Symbol('foo')) #### Antwort: A -Jedes Symbol ist eindeutig. Der Sinn des Argumentes, welches an das Symbol weitergegeben wird, ist dem Symbol eine Beschreibung zu geben. Der Wert des Symbols hängt nicht von diesem Argument ab. Beim vergleichen der Symbole werden zwei komplett neue Symbole erstellt: das erste `Symbol('foo')` und das zweite `Symbol('foo')`. Diese beiden Werte sind eindeutig und nicht identisch, weshalb `Symbol('foo') === Symbol('foo')` `false` ausgibt. +Jedes Symbol ist eindeutig. Der Sinn des Argumentes, welches an das Symbol weitergegeben wird, ist dem Symbol eine Beschreibung zu geben. Der Wert des Symbols hängt nicht von diesem Argument ab. Beim vergleichen der Symbole werden zwei komplett neue Symbole erstellt: das erste `Symbol('foo')` und das zweite `Symbol('foo')`. Diese beiden Werte sind eindeutig und nicht identisch, weshalb `Symbol('foo') === Symbol('foo')` `false` ausgibt.

--- -###### 69. Was ist der Output? +###### 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"` -- 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"`,
Antwort

@@ -2176,7 +2184,7 @@ Falls der Wert, der an `padStart` übergeben wurde kleiner ist, als die Länge d --- -###### 70. Was ist der Output? +###### 70. Was wird ausgegeben? ```javascript console.log("🥑" + "💻"); @@ -2236,7 +2244,7 @@ Wenn wir `game.next("Yes").value` aufrufen wird das vorhergehende `yield` durch --- -###### 72. Was ist der Output? +###### 72. Was wird ausgegeben? ```javascript console.log(String.raw`Hello\nworld`); @@ -2271,7 +2279,7 @@ In unserem Fall ist das Ergebnis `Hello\nworld`, was geloggt wird. --- -###### 73. Was ist der Output? +###### 73. Was wird ausgegeben? ```javascript async function getData() { @@ -2305,7 +2313,7 @@ Das hätte `"I made it!"` ausgegeben. --- -###### 74. Was ist der Output? +###### 74. Was wird ausgegeben? ```javascript function addToList(item, list) { @@ -2335,7 +2343,7 @@ Die `push` Methode verändert das ursprüngliche Array. Wenn wir das _Array_ der --- -###### 75. Was ist der Output? +###### 75. Was wird ausgegeben? ```javascript const box = { x: 10, y: 20 }; @@ -2370,7 +2378,7 @@ Da `shape` eingefroren ist und der Wert von `x` kein Objekt ist, können wir den --- -###### 76. Was ist der Output? +###### 76. Was wird ausgegeben? ```javascript const { name: myName } = { name: "Lydia" }; @@ -2424,12 +2432,12 @@ Die `sum` Funktion gibt daher immer das gleiche Ergebnis aus. Wenn wir `1` und ` --- -###### 78. Was ist der Output? +###### 78. Was wird ausgegeben? ```javascript const add = () => { const cache = {}; - return num => { + return (num) => { if (num in cache) { return `From cache! ${cache[num]}`; } else { @@ -2471,24 +2479,24 @@ Beim dritten Mal geben wir `5 * 2` als Argument in die Funktion ein, was `10` er --- -###### 79. Was ist der Output? +###### 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

@@ -2508,17 +2516,17 @@ Mit einer _for-of_ Schleife können wir über **wiederholbare** Elemente iterier --- -###### 80. Was ist der Output? +###### 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

@@ -2534,20 +2542,20 @@ Das Element ist gleich dem ausgegebenen Wert. `1 + 2` ergibt `3`, `1 * 2` ergibt --- -###### 81. Was ist der Output? +###### 81. Was wird ausgegeben? ```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

@@ -2567,24 +2575,24 @@ In diesem Fall, falls wir kein Argument oder `undefined` eingeben ist `name` imm --- -###### 82. Was ist der Output? +###### 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 `"😍"` @@ -2601,24 +2609,23 @@ 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. -

--- -###### 83. Was ist der Output? +###### 83. Was wird ausgegeben? ```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 }` @@ -2644,20 +2651,20 @@ Wenn wir `person` loggen bekommen wir daher das unveränderte Objekt angezeigt. --- -###### 84. Was ist der Output? +###### 84. Was wird ausgegeben? ```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 +2687,15 @@ 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. - B: Das Ergebnis des zweiten Aufrufs der `fetch` Methode. - C: Das Ergebnis des Callbacks im vorhergehenden `.then()`. -- D: Immer `undefined`. +- D: Immer `undefined`.
Antwort

@@ -2727,16 +2734,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 ist der Output? +###### 87. Was wird ausgegeben? ```javascript -console.log("I want pizza"[0]) +console.log("I want pizza"[0]); ``` - A: `"""` @@ -2758,14 +2765,14 @@ Diese Methode funktioniert nicht in IE7 und davor. Hier muss `.charAt()` verwend --- -###### 88. Was ist der Output? +###### 88. Was wird ausgegeben? ```javascript function sum(num1, num2 = num1) { - console.log(num1 + num2) + console.log(num1 + num2); } -sum(10) +sum(10); ``` - A: `NaN` @@ -2787,17 +2794,17 @@ Wenn man den Wert des Standard Paramenters gleich dem Parameter setztm der _dana --- -###### 89. Was ist der Output? +###### 89. Was wird ausgegeben? ```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" }` @@ -2819,17 +2826,17 @@ Das `data` Objekt hat eine Standard Property für alle Standard Exporte, andere --- -###### 90. Was ist der Output? +###### 90. Was wird ausgegeben? ```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,7 +2853,7 @@ Klassen sind syntaktischer Zucker für Funktionskontruktoren. Das Equivalent der ```javascript function Person() { - this.name = name + this.name = name; } ``` @@ -2857,12 +2864,12 @@ Das Aufrufen eines Funktionskonstruktors mit `new` hat zur Folge, dass eine Inst --- -###### 91. Was ist der Output? +###### 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]` @@ -2884,21 +2891,22 @@ Dann versuchen wir die `.push` Methode auf `newList` anzuwenden. Da `newList` de --- -###### 92. Was ist der Output? +###### 92. Was wird ausgegeben? ```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,28 +2915,28 @@ console.log(giveLydiaChocolate.prototype) #### Antwort: D -Reguläre Funktionen wie `giveLydiaPizza` haben eine `prototype` Property, die ein Objekt (Prototype Object) mit einem `constructor` ist. Arrow Funktionen dagegen (wie `giveLydiaChocolate`) haben keinen `prototype`. `undefined` wird ausgegeben, wenn wir versuchen den `prototype` mit `giveLydiaChocolate.prototype` aufzurufen. +Reguläre Funktionen wie `giveLydiaPizza` haben eine `prototype` Property, die ein Objekt (Prototype Object) mit einem `constructor` ist. Arrow Funktionen dagegen (wie `giveLydiaChocolate`) haben keinen `prototype`. `undefined` wird ausgegeben, wenn wir versuchen den `prototype` mit `giveLydiaChocolate.prototype` aufzurufen.

--- -###### 93. Was ist der Output? +###### 93. Was wird ausgegeben? ```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` und `age` `21` -- B: `["name", "Lydia"]` und `["age", 21]` +- B: `["name", "Lydia"]` und `["age", 21]` - C: `["name", "age"]` und `undefined` - D: `Error` @@ -2939,7 +2947,7 @@ for (const [x, y] of Object.entries(person)) { `Object.entries(person)` gibt ein Array mit verschachtelten Arrays der Keys aus: -`[ [ 'name', 'Lydia' ], [ 'age', 21 ] ]` +`[ [ 'name', 'Lydia' ], [ 'age', 21 ] ]` Mit der `for-of` Schleife iterieren wir über jedes Element in dem Array, in diesem Fall die verschachtelten Arrays. Wir können die verschachtelten Arrays mit `const [x, y]` in der for-of Schleife destrukturieren. `x` ist gleich dem ersten Element, `y` ist gleich dem zweiten Element in dem verschachtelten Array. @@ -2951,7 +2959,7 @@ Das zweite verschachtelte Array ist `[ "age", 21 ]`. `x` ist gleich `"age"` und --- -###### 94. Was ist der Output? +###### 94. Was wird ausgegeben? ```javascript function getItems(fruitList, ...args, favoriteFruit) { @@ -2962,7 +2970,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` @@ -2975,33 +2983,31 @@ 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. +

--- -###### 95. Was ist der Output? +###### 95. Was wird ausgegeben? ```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` @@ -3019,8 +3025,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. @@ -3031,23 +3037,23 @@ Bedenke: Semikolons werden **nicht** automatisch nach `if/else` Statements geset --- -###### 96. Was ist der Output? +###### 96. Was wird ausgegeben? ```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"` @@ -3067,15 +3073,15 @@ Wir können Klassen gleich anderen Klassen oder Funktions Konstruktoren setzen. --- -###### 97. Was ist der Output? +###### 97. Was wird ausgegeben? ```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')"]` @@ -3098,7 +3104,7 @@ Bedenke: Man kann die Symbole dennoch mit der `Object.getOwnPropertySymbols()` M --- -###### 98. Was ist der Output? +###### 98. Was wird ausgegeben? ```javascript const getList = ([x, ...y]) => [x, y] @@ -3123,13 +3129,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. @@ -3138,12 +3144,12 @@ Da kein Wert ausgegeben wird, gibt die Funktion `undefined` aus. --- -###### 99. Was ist der Output? +###### 99. Was wird ausgegeben? ```javascript -const name = "Lydia" +const name = "Lydia"; -console.log(name()) +console.log(name()); ``` - A: `SyntaxError` @@ -3169,13 +3175,13 @@ ReferenceErrors werden ausgeworfen, wenn JavaScript eine Referenz zu einem Wert --- -###### 100. Was ist der Output? +###### 100. Was wird ausgegeben? ```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` @@ -3197,14 +3203,14 @@ You should${'' && `n't`} see a therapist after so much JavaScript lol` --- -###### 101. Was ist der Output? +###### 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` `[]` @@ -3233,16 +3239,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"); } ``` @@ -3260,29 +3266,29 @@ Mit einem Promise sagen wir _Ich möchte diese Funktion ausführen, aber ich leg Wir können auf den Wert mit `.then()` oder `await` in einer `async` Funktion zugreifen, aber `.then()` und `await` unterscheiden sich in einem bestimmten Punkt. -In `firstFunction` legen wir `myPromise` beiseite, während die Funktion durchläuft, aber wir arbeiten anderen Code ab, hier `console.log('second')`. -Dann wird die Funktion abgeschlossen und der String `I have resolved` wird ausgegeben, nachdem sich der Call Stack geleert hat. +In `firstFunction` legen wir `myPromise` beiseite, während die Funktion durchläuft, aber wir arbeiten anderen Code ab, hier `console.log('second')`. +Dann wird die Funktion abgeschlossen und der String `I have resolved` wird ausgegeben, nachdem sich der Call Stack geleert hat. Mit dem `await` Keyword in `secondFunction` wird die Funktion gestoppt bis der Wert ausgegeben wurde, erst dann wird die nächste Zeile ausgeführt. -Das bedeutet, dass auf `myPromise` gewartet und dann der Wert `I have resolved` ausgegeben wird und erst dann wird die nächste Zeile ausgeführt und `second` wird geloggt. +Das bedeutet, dass auf `myPromise` gewartet und dann der Wert `I have resolved` ausgegeben wird und erst dann wird die nächste Zeile ausgeführt und `second` wird geloggt.

--- -###### 103. Was ist der Output? +###### 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); } ``` @@ -3300,7 +3306,7 @@ Der `+` Operator wird nicht nur für numerische Werte verwendet, wir können mit Der erste Wert ist `1`, was ein numerischer Wert ist. `1 + 2` ergibt die Zahl `3`. -Der zweite Wert hingegen ist der String `"Lydia"`. `"Lydia"` ist ein String und `2` ist eine Nummer: `2` wird in einem String umgewandelt. `"Lydia"` und `"2"` werden zusammengesetzt, was den String `"Lydia2"` ausgibt. +Der zweite Wert hingegen ist der String `"Lydia"`. `"Lydia"` ist ein String und `2` ist eine Nummer: `2` wird in einem String umgewandelt. `"Lydia"` und `"2"` werden zusammengesetzt, was den String `"Lydia2"` ausgibt. `{ name: "Lydia" }` ist ein Objekt. Weder eine Nummer, noch ein Objekt sind ein String, aber beide werden zu Strings konvertiert und `"[object Object]"` wird ausgegeben. `"[object Object]"` zusammengesetzt mit `"2"` wird `"[object Object]2"`. @@ -3312,7 +3318,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` @@ -3327,7 +3333,7 @@ Promise.resolve(5) Wir können jeden Wert an `Promise.resolve` übergeben, es muss nicht unbedingt ein Promise sein. Die Methode selbst gibt ein Promise zurück, was einen Wert ausgibt. Wenn man eine normale Funktion übergibt wird das Promise einen normalen Wert ausgeben. Wenn ein Promise übergeben wird so wird ein Promise gelöst und der Wert des gelösten Promises ausgegeben. -In diesem Fall haben wir nur die Zahl `5` übergeben und diese wird genauso ausgegeben: `5`. +In diesem Fall haben wir nur die Zahl `5` übergeben und diese wird genauso ausgegeben: `5`.

@@ -3339,15 +3345,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!` @@ -3366,7 +3372,7 @@ Wir setzen den Standardwert für `person2` gleich dem `person` Objekt und überg Das bedeutet, dass beide Werte eine Referenz zum gleichen Ort im Speicher aufweisen und daher gleich sind. -Der Code im `else` Statement wird aufgerufen und `They are the same!` wird geloggt. +Der Code im `else` Statement wird aufgerufen und `They are the same!` wird geloggt.

@@ -3382,11 +3388,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` @@ -3399,7 +3405,7 @@ console.log(colorConfig.colors[1]) #### Antwort: D -In JavaScript gibt es zwei Wege auf Properties an Objekten zuzugreifen: Punkt-Notation oder Klammern-Notation. In diesem Beispiel nutzen wir Punkt-Notation (`colorConfig.colors`) anstelle von Klammern-Notation (`colorConfig["colors"]`). +In JavaScript gibt es zwei Wege auf Properties an Objekten zuzugreifen: Punkt-Notation oder Klammern-Notation. In diesem Beispiel nutzen wir Punkt-Notation (`colorConfig.colors`) anstelle von Klammern-Notation (`colorConfig["colors"]`). Mit Punkt-Notation versucht JavaScript die Property am Objekt mit diesem exakten Namen zu finden. In unserem Beispiel `colors` im `colorConfig` Objekt. Da es keine Property `colorConfig` gibt wird `undefined` ausgegeben. Dann versuchen wir den Wert des ersten Elements mit `[1]` aufzurufen, was an `undefined` nicht möglich ist, wodurch wir `TypeError: Cannot read property '1' of undefined` ausgegeben bekommen. @@ -3413,7 +3419,7 @@ JavaScript interpretiert Statements. Wenn wir Klammern-Notation verwenden wird d ###### 107. Was wird ausgegeben? ```javascript -console.log('❤️' === '❤️') +console.log("❤️" === "❤️"); ``` - A: `true` @@ -3431,22 +3437,22 @@ 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? +###### 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` - B: `map` `reduce` `slice` `splice` -- C: `map` `slice` `splice` +- C: `map` `slice` `splice` - D: `splice`
Antwort @@ -3454,30 +3460,29 @@ emojis.splice(1, 2, '✨') #### Antwort: D -Mit der `splice` Methode ändern wir das ursprüngliche Array durch löschen, ersetzen oder ergänzen von Elementen. In diesem Fall haben wir 2 Elemente vom Index 1 (`'🥑'` und `'😍'`) entfernt und ✨ stattdessen eingefügt. +Mit der `splice` Methode ändern wir das ursprüngliche Array durch löschen, ersetzen oder ergänzen von Elementen. In diesem Fall haben wir 2 Elemente vom Index 1 (`'🥑'` und `'😍'`) entfernt und ✨ stattdessen eingefügt. `map`, `filter` und `slice` geben ein neues Array aus, `find` gibt ein Element aus und `reduce` gibt einen neuen Wert aus.

- --- -###### 109. Was ist der Output? +###### 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: `['🍕', '🍫', '🥑', '🍔']` - B: `['🍝', '🍫', '🥑', '🍔']` -- C: `['🍝', '🍕', '🍫', '🥑', '🍔']` +- C: `['🍝', '🍕', '🍫', '🥑', '🍔']` - D: `ReferenceError`
Antwort @@ -3497,7 +3502,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 @@ -3514,16 +3519,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' } ```

@@ -3531,17 +3536,17 @@ JSON.parse(jsonArray) // { name: 'Lydia' } --- -###### 111. Was ist der Output? +###### 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 @@ -3561,13 +3566,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 ```

@@ -3575,22 +3580,22 @@ getName() // Lydia --- -###### 112. Was ist der Output? +###### 112. Was wird ausgegeben? ```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` @@ -3608,17 +3613,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 ```

@@ -3626,10 +3631,10 @@ console.log(two.next().value) // undefined --- -###### 113. Was ist der Output? +###### 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` @@ -3642,7 +3647,7 @@ console.log(`${(x => x)('I love')} to program`) #### Antwort: A -Expressions innerhalb von Template Literals werden zuerst berechnet. Das bedeutet, dass der String den ausgegebenen Wert der Expression beinhaltet, hier die IIFE (immediately invoked Function) `(x => x)('I love')`. Wir geben den Wert `'I love'` als Argument an die `x => x` Arrow Funktion. `x` ist gleich `'I love'` und wird ausgegeben. Das Ergebnis ist `I love to program`. +Expressions innerhalb von Template Literals werden zuerst berechnet. Das bedeutet, dass der String den ausgegebenen Wert der Expression beinhaltet, hier die IIFE (immediately invoked Function) `(x => x)('I love')`. Wir geben den Wert `'I love'` als Argument an die `x => x` Arrow Funktion. `x` ist gleich `'I love'` und wird ausgegeben. Das Ergebnis ist `I love to program`.

@@ -3704,7 +3709,7 @@ myMap.get(() => 'greeting')) #### Antwort: B -Beim Setzen eines Key/Wert Paars mit der `set` Methode wird der Key als erstes Argument an die `set` Funktion übergeben und der Wert wird als zweites Argument eingegeben. Der Key ist die _Funktion_ `() => 'greeting'` und der Wert ist `'Hello world'`. `myMap` ist jetzt `{ () => 'greeting' => 'Hello world!' }`. +Beim Setzen eines Key/Wert Paars mit der `set` Methode wird der Key als erstes Argument an die `set` Funktion übergeben und der Wert wird als zweites Argument eingegeben. Der Key ist die _Funktion_ `() => 'greeting'` und der Wert ist `'Hello world'`. `myMap` ist jetzt `{ () => 'greeting' => 'Hello world!' }`. 1 ist falsch, weil der Key nicht `'greeting'`, sondern `() => 'greeting'` ist. 3 ist falsch, weil wir eine neue Funktion erstellen, indem wir sie als Argument übergeben. Objekte interagieren anhand von _Referenzen_. Funktionen sind Objekte, weshalb zwei Funktionen streng gesehen nie gleich sind, selbst wenn sie sich nicht unterscheiden. @@ -3714,24 +3719,24 @@ Beim Setzen eines Key/Wert Paars mit der `set` Methode wird der Key als erstes A --- -###### 116. Was ist der Output? +###### 116. Was wird ausgegeben? ```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}` From 6342675c63212e6a93a75ec4f82b4439f463dd60 Mon Sep 17 00:00:00 2001 From: Jacob Herper Date: Thu, 24 Sep 2020 15:47:23 +0100 Subject: [PATCH 649/915] fixed indentation --- README.md | 700 +++++++++++++++++++++++++++--------------------------- 1 file changed, 350 insertions(+), 350 deletions(-) diff --git a/README.md b/README.md index 227b61d7..c17e87e3 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@
- -

JavaScript Questions

+ +

JavaScript Questions

--- @@ -50,10 +50,10 @@ Feel free to reach out to me! 😊
```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(); @@ -82,11 +82,11 @@ Variables with the `let` keyword (and `const`) are hoisted, but unlike `var`, do ```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); } ``` @@ -112,11 +112,11 @@ In the second loop, the variable `i` was declared using the `let` keyword: varia ```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, }; console.log(shape.diameter()); @@ -173,12 +173,12 @@ 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", - small: true, + name: "Mickey", + small: true, }; ``` @@ -277,14 +277,14 @@ However, when we use the `===` operator, both value _and_ type should be the sam ```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" }); @@ -338,7 +338,7 @@ 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"; @@ -367,13 +367,13 @@ A function is a special type of object. The code you write yourself isn't the ac ```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}`; + return `${this.firstName} ${this.lastName}`; }; console.log(member.getFullName()); @@ -395,7 +395,7 @@ If you want a method to be available to all object instances, you have to add it ```js Person.prototype.getFullName = function () { - return `${this.firstName} ${this.lastName}`; + return `${this.firstName} ${this.lastName}`; }; ``` @@ -408,8 +408,8 @@ 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"); @@ -480,7 +480,7 @@ All objects have prototypes, except for the **base object**. The base object is ```javascript function sum(a, b) { - return a + b; + return a + b; } sum(1, "2"); @@ -545,9 +545,9 @@ This returns `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"; @@ -576,13 +576,13 @@ 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!"); - } 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 }); @@ -612,7 +612,7 @@ This is why both `{ age: 18 } === { age: 18 }` and `{ age: 18 } == { age: 18 }` ```javascript function getAge(...args) { - console.log(typeof args); + console.log(typeof args); } getAge(21); @@ -639,9 +639,9 @@ The rest parameter (`...args`) lets us "collect" all remaining arguments into an ```javascript function getAge() { - "use strict"; - age = 21; - console.log(age); + "use strict"; + age = 21; + console.log(age); } getAge(); @@ -817,8 +817,8 @@ The base execution context is the global execution context: it's what's accessib ```javascript for (let i = 1; i < 5; i++) { - if (i === 3) continue; - console.log(i); + if (i === 3) continue; + console.log(i); } ``` @@ -843,7 +843,7 @@ 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"; @@ -959,9 +959,9 @@ This is where an event loop starts to work. An **event loop** looks at the stack ```html
-
- -
+
+ +
``` @@ -986,7 +986,7 @@ The deepest nested element that caused the event is the target of the event. You ```html
-

Click here!

+

Click here!

``` @@ -1013,7 +1013,7 @@ If we click `p`, we see two logs: `p` and `div`. During event propagation, there const person = { name: "Lydia" }; function sayHi(age) { - return `${this.name} is ${age}`; + return `${this.name} is ${age}`; } console.log(sayHi.call(person, 21)); @@ -1043,7 +1043,7 @@ With both, we can pass the object to which we want the `this` keyword to refer t ```javascript function sayHi() { - return (() => 0)(); + return (() => 0)(); } console.log(typeof sayHi()); @@ -1164,15 +1164,15 @@ depending on where you run it (it's different for every browser, node, etc.) ```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); })(); ``` @@ -1224,13 +1224,13 @@ What differentiates a primitive from an object is that primitives do not have an ```javascript [ - [0, 1], - [2, 3], + [0, 1], + [2, 3], ].reduce( - (acc, cur) => { - return acc.concat(cur); - }, - [1, 2] + (acc, cur) => { + return acc.concat(cur); + }, + [1, 2] ); ``` @@ -1332,8 +1332,8 @@ A string is an iterable. The spread operator maps every character of an iterable ```javascript function* generator(i) { - yield i; - yield i * 2; + yield i; + yield i * 2; } const gen = generator(10); @@ -1367,11 +1367,11 @@ 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)); @@ -1437,12 +1437,12 @@ We are only modifying the value of the `person` variable, and not the first elem ```javascript const person = { - name: "Lydia", - age: 21, + name: "Lydia", + age: 21, }; for (const item in person) { - console.log(item); + console.log(item); } ``` @@ -1519,8 +1519,8 @@ Only the first numbers in the string is returned. Based on the _radix_ (the seco ```javascript [1, 2, 3].map((num) => { - if (typeof num === "number") return; - return num * 2; + if (typeof num === "number") return; + return num * 2; }); ``` @@ -1547,8 +1547,8 @@ 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" }; @@ -1584,16 +1584,16 @@ 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); - } catch (e) { - console.log("Oh no an error:", e); - } + try { + const data = greeting(); + console.log("It worked!", data); + } catch (e) { + console.log("Oh no an error:", e); + } } sayHi(); @@ -1622,8 +1622,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(); @@ -1651,7 +1651,7 @@ When you return a property, the value of the property is equal to the _returned_ ```javascript (() => { - let x = (y = 10); + let x = (y = 10); })(); console.log(typeof x); @@ -1690,13 +1690,13 @@ However, we created a global variable `y` when setting `y` equal to `10`. This v ```javascript class Dog { - constructor(name) { - this.name = name; - } + constructor(name) { + this.name = name; + } } Dog.prototype.bark = function () { - console.log(`Woof I am ${this.name}`); + console.log(`Woof I am ${this.name}`); }; const pet = new Dog("Mara"); @@ -1921,9 +1921,9 @@ Properties added using the `defineProperty` method are immutable by default. You ```javascript const settings = { - username: "lydiahallie", - level: 19, - health: 90, + username: "lydiahallie", + level: 19, + health: 90, }; const data = JSON.stringify(settings, ["level", "health"]); @@ -1991,7 +1991,7 @@ The unary operator `++` _first returns_ the value of the operand, _then incremen const value = { number: 10 }; const multiply = (x = { ...value }) => { - console.log((x.number *= 2)); + console.log((x.number *= 2)); }; multiply(); @@ -2053,38 +2053,38 @@ 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? ```javascript class Dog { - constructor(name) { - this.name = name; - } + 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; - } + // 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; + } } ``` @@ -2220,11 +2220,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") { - return "Oh wow... Guess we're gone here"; - } - return "JavaScript loves you back ❤️"; + 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(); @@ -2292,7 +2292,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(); @@ -2326,7 +2326,7 @@ This would've logged `"I made it!"` ```javascript function addToList(item, list) { - return list.push(item); + return list.push(item); } const result = addToList("apple", ["banana"]); @@ -2419,7 +2419,7 @@ Since we try to log `name`, a variable that is not defined, a ReferenceError get ```javascript function sum(a, b) { - return a + b; + return a + b; } ``` @@ -2444,16 +2444,16 @@ The `sum` function always returns the same result. If we pass `1` and `2`, it wi ```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 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(); @@ -2493,11 +2493,11 @@ The third time, we pass `5 * 2` to the function which gets evaluated to `10`. Th const myLifeSummedUp = ["☕", "💻", "🍷", "🍫"]; for (let item in myLifeSummedUp) { - console.log(item); + console.log(item); } for (let item of myLifeSummedUp) { - console.log(item); + console.log(item); } ``` @@ -2554,7 +2554,7 @@ 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()); @@ -2589,17 +2589,17 @@ In this case, if we didn't pass a value or if we passed `undefined`, `name` woul var status = "😎"; setTimeout(() => { - const status = "😍"; + const status = "😍"; - const data = { - status: "🥑", - getStatus() { - return this.status; - }, - }; + const data = { + status: "🥑", + getStatus() { + return this.status; + }, + }; - console.log(data.getStatus()); - console.log(data.getStatus.call(this)); + console.log(data.getStatus()); + console.log(data.getStatus.call(this)); }, 0); ``` @@ -2626,8 +2626,8 @@ With the `call` method, we can change the object to which the `this` keyword ref ```javascript const person = { - name: "Lydia", - age: 21, + name: "Lydia", + age: 21, }; let city = person.city; @@ -2663,13 +2663,13 @@ When logging the `person` object, the unmodified object gets returned. ```javascript function checkAge(age) { - if (age < 18) { - const message = "Sorry, you're too young."; - } else { - const message = "Yay! You're old enough!"; - } + if (age < 18) { + const message = "Sorry, you're too young."; + } else { + const message = "Yay! You're old enough!"; + } - return message; + return message; } console.log(checkAge(21)); @@ -2696,8 +2696,8 @@ Variables with the `const` and `let` keyword are _block-scoped_. A block is anyt ```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: The result of the `fetch` method. @@ -2721,7 +2721,7 @@ The value of `res` in the second `.then` is equal to the returned value of the p ```javascript function getName(name) { - const hasName = // + const hasName = // } ``` @@ -2777,7 +2777,7 @@ 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); @@ -2838,9 +2838,9 @@ The `data` object has a `default` property for the default export, other propert ```javascript class Person { - constructor(name) { - this.name = name; - } + constructor(name) { + this.name = name; + } } const member = new Person("John"); @@ -2861,7 +2861,7 @@ Classes are syntactical sugar for function constructors. The equivalent of the ` ```javascript function Person() { - this.name = name; + this.name = name; } ``` @@ -2903,11 +2903,11 @@ 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."; + "Here's chocolate... now go hit the gym already."; console.log(giveLydiaPizza.prototype); console.log(giveLydiaChocolate.prototype); @@ -2934,12 +2934,12 @@ Regular functions, such as the `giveLydiaPizza` function, have a `prototype` pro ```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); } ``` @@ -2971,7 +2971,7 @@ The second subarray is `[ "age", 21 ]`, with `x` equal to `"age"`, and `y` equal ```javascript function getItems(fruitList, ...args, favoriteFruit) { - return [...fruitList, ...args, favoriteFruit] + return [...fruitList, ...args, favoriteFruit] } getItems(["banana", "apple"], "pear", "orange") @@ -2991,7 +2991,7 @@ getItems(["banana", "apple"], "pear", "orange") ```javascript function getItems(fruitList, favoriteFruit, ...args) { - return [...fruitList, ...args, favoriteFruit]; + return [...fruitList, ...args, favoriteFruit]; } getItems(["banana", "apple"], "pear", "orange"); @@ -3008,10 +3008,10 @@ 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)); @@ -3048,15 +3048,15 @@ This means that `a + b` is never reached, since a function stops running after t ```javascript class Person { - constructor() { - this.name = "Lydia"; - } + constructor() { + this.name = "Lydia"; + } } Person = class AnotherPerson { - constructor() { - this.name = "Sarah"; - } + constructor() { + this.name = "Sarah"; + } }; const member = new Person(); @@ -3084,7 +3084,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); @@ -3247,13 +3247,13 @@ With the `||` operator, we can return the first truthy operand. If all values ar 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(); @@ -3295,7 +3295,7 @@ set.add("Lydia"); set.add({ name: "Lydia" }); for (let item of set) { - console.log(item + 2); + console.log(item + 2); } ``` @@ -3351,11 +3351,11 @@ 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!"); - } else { - console.log("They are the same!"); - } + if (person1 !== person2) { + console.log("Not the same!"); + } else { + console.log("They are the same!"); + } } const person = { name: "Lydia" }; @@ -3390,11 +3390,11 @@ The code block in the `else` statement gets run, and `They are the same!` gets l ```javascript const colorConfig = { - red: true, - blue: false, - green: true, - black: true, - yellow: false, + red: true, + blue: false, + green: true, + black: true, + yellow: false, }; const colors = ["pink", "red", "blue"]; @@ -3535,7 +3535,7 @@ JSON.parse(jsonNumber); // 4 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: +// 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' } ``` @@ -3551,8 +3551,8 @@ JSON.parse(jsonArray); // { name: 'Lydia' } let name = "Lydia"; function getName() { - console.log(name); - let name = "Sarah"; + console.log(name); + let name = "Sarah"; } getName(); @@ -3578,7 +3578,7 @@ If we wouldn't have declared the `name` variable within the `getName` function, let name = "Lydia"; function getName() { - console.log(name); + console.log(name); } getName(); // Lydia @@ -3593,11 +3593,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(); @@ -3667,9 +3667,9 @@ Expressions within template literals are evaluated first. This means that the st ```javascript let config = { - alert: setInterval(() => { - console.log("Alert!"); - }, 1000), + alert: setInterval(() => { + console.log("Alert!"); + }, 1000), }; config = null; @@ -3732,14 +3732,14 @@ When adding a key/value pair using the `set` method, the key will be the value o ```javascript const person = { - name: "Lydia", - age: 21, + name: "Lydia", + age: 21, }; 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); @@ -3773,7 +3773,7 @@ Then, we invoke the `changeAgeAndName` function, however we don't pass a paramet ```javascript function sumValues(x, y, z) { - return x + y + z; + return x + y + z; } ``` @@ -3824,15 +3824,15 @@ With the `+=` operand, we're incrementing the value of `num` by `1`. `num` had t ```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); @@ -3869,9 +3869,9 @@ With the optional chaining operator `?.`, we no longer have to explicitly check 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 +3896,10 @@ We passed the condition `groceries.indexOf("banana")` to the if-statement. `groc ```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); @@ -3954,8 +3954,8 @@ console.log(!typeof name === "string"); ```javascript const add = (x) => (y) => (z) => { - console.log(x, y, z); - return x + y + z; + console.log(x, y, z); + return x + y + z; }; add(4)(5)(6); @@ -3982,16 +3982,16 @@ The `add` function returns an arrow function, which returns an arrow function, w ```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 +4016,7 @@ The generator function `range` returns an async object with promises for each it ```javascript const myFunc = ({ x, y, z }) => { - console.log(x, y, z); + console.log(x, y, z); }; myFunc(1, 2, 3); @@ -4043,17 +4043,17 @@ myFunc(1, 2, 3); ```javascript function getFine(speed, amount) { - const formattedSpeed = new Intl.NumberFormat("en-US", { - style: "unit", - unit: "mile-per-hour", - }).format(speed); + 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); + const formattedAmount = new Intl.NumberFormat("en-US", { + style: "currency", + currency: "USD", + }).format(amount); - return `The driver drove ${formattedSpeed} and has to pay ${formattedAmount}`; + return `The driver drove ${formattedSpeed} and has to pay ${formattedAmount}`; } console.log(getFine(130, 300)); @@ -4140,8 +4140,8 @@ With the `isNaN` method, you can check if the value you pass is not a number. `n const randomValue = 21; function getInfo() { - console.log(typeof randomValue); - const randomValue = "Lydia Hallie"; + console.log(typeof randomValue); + const randomValue = "Lydia Hallie"; } getInfo(); @@ -4170,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!"); + } })(); ``` @@ -4226,13 +4226,13 @@ With the `flat` method, we can create a new, flattened array. The depth of the f ```javascript class Counter { - constructor() { - this.count = 0; - } + constructor() { + this.count = 0; + } - increment() { - this.count++; - } + increment() { + this.count++; + } } const counterOne = new Counter(); @@ -4276,16 +4276,16 @@ We invoke the `counterTwo.increment()`, which sets the `count` to `3`. Then, 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(); @@ -4322,7 +4322,7 @@ We get to the last line of `funcTwo`, which logs `Last line!` to the console. No ```javascript // sum.js export default function sum(x) { - return x + x; + return x + x; } // index.js @@ -4356,9 +4356,9 @@ The following would get logged: ```javascript { - default: "I love JavaScript", - name: "Lydia", - age: 21 + default: "I love JavaScript", + name: "Lydia", + age: 21 } ``` @@ -4379,8 +4379,8 @@ 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); @@ -4443,10 +4443,10 @@ However, you can still modify the value of existing properties. ```javascript const person = { - name: "Lydia Hallie", - address: { - street: "100 Main St", - }, + name: "Lydia Hallie", + address: { + street: "100 Main St", + }, }; Object.freeze(person); @@ -4477,7 +4477,7 @@ However, it only _shallowly_ freezes the object, meaning that only _direct_ prop const add = (x) => x + x; function myFunc(num = 2, value = add(num)) { - console.log(num, value); + console.log(num, value); } myFunc(); @@ -4507,15 +4507,15 @@ 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++; - } + increment() { + this.#number++; + } - getNum() { - return this.#number; - } + getNum() { + return this.#number; + } } const counter = new Counter(); @@ -4545,20 +4545,20 @@ 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) { - 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 +4589,13 @@ 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) { - hobbies.push(hobby); - return hobbies; + hobbies.push(hobby); + return hobbies; } addHobby("running", []); @@ -4634,16 +4634,16 @@ After pushing `dancing` and `baking`, the value of `person.hobbies` is `["coding ```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(); @@ -4698,8 +4698,8 @@ The `const` keyword simply means we cannot _redeclare_ the value of that variabl ```javascript const person = { - name: "Lydia Hallie", - age: 21 + name: "Lydia Hallie", + age: 21 } [...person] // ["Lydia Hallie", 21] @@ -4729,7 +4729,7 @@ let count = 0; const nums = [0, 1, 2, 3]; nums.forEach((num) => { - if (num) count += 1; + if (num) count += 1; }); console.log(count); @@ -4756,7 +4756,7 @@ 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([["🍊", "🍌"], ["🍍"]]); @@ -4791,13 +4791,13 @@ 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(); @@ -4827,20 +4827,20 @@ 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" }); @@ -4936,10 +4936,10 @@ 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"); @@ -4972,14 +4972,14 @@ 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']]` @@ -5006,12 +5006,12 @@ const keys = ["name", "age"]; const values = ["Lydia", 22]; const method = - /* ?? */ - Object[method]( - keys.map((_, i) => { - return [keys[i], values[i]]; - }) - ); // { name: "Lydia", age: 22 } + /* ?? */ + Object[method]( + keys.map((_, i) => { + return [keys[i], values[i]]; + }) + ); // { name: "Lydia", age: 22 } ``` - A: `entries` @@ -5037,13 +5037,13 @@ This creates an array of subarrays containing the correct keys and values, which ```javascript const createMember = ({ email, address = {} }) => { - const validEmail = /.+\@.+\..+/.test(email); - if (!validEmail) throw new Error("Valid email pls"); + 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" }); @@ -5074,9 +5074,9 @@ 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 34207cac8554b2974f9589411c220ff0bcadde11 Mon Sep 17 00:00:00 2001 From: Jacob Herper Date: Thu, 24 Sep 2020 16:12:01 +0100 Subject: [PATCH 650/915] fixed formatting --- README.md | 1035 ++++++++++++++++++++++++++--------------------------- 1 file changed, 516 insertions(+), 519 deletions(-) diff --git a/README.md b/README.md index c17e87e3..14c025ad 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@
- -

JavaScript Questions

+ +

JavaScript Questions

--- @@ -10,12 +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! | +|---| --- @@ -50,10 +48,10 @@ Feel free to reach out to me! 😊
```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(); @@ -82,11 +80,11 @@ Variables with the `let` keyword (and `const`) are hoisted, but unlike `var`, do ```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); } ``` @@ -112,11 +110,11 @@ In the second loop, the variable `i` was declared using the `let` keyword: varia ```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, }; console.log(shape.diameter()); @@ -148,7 +146,7 @@ There is no value `radius` on that object, which returns `NaN`. ```javascript +true; -!"Lydia"; +!'Lydia'; ``` - A: `1` and `false` @@ -173,12 +171,12 @@ 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", - small: true, + name: 'Mickey', + small: true, }; ``` @@ -208,11 +206,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); ``` @@ -277,18 +275,18 @@ However, when we use the `===` operator, both value _and_ type should be the sam ```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" }); -console.log(freddie.colorChange("orange")); +const freddie = new Chameleon({ newColor: 'purple' }); +console.log(freddie.colorChange('orange')); ``` - A: `orange` @@ -338,10 +336,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! @@ -367,13 +365,13 @@ A function is a special type of object. The code you write yourself isn't the ac ```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()); @@ -389,13 +387,13 @@ 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 () { - return `${this.firstName} ${this.lastName}`; +Person.prototype.getFullName = function() { + return `${this.firstName} ${this.lastName}`; }; ``` @@ -408,12 +406,12 @@ 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); @@ -480,10 +478,10 @@ All objects have prototypes, except for the **base object**. The base object is ```javascript function sum(a, b) { - return a + b; + return a + b; } -sum(1, "2"); +sum(1, '2'); ``` - A: `NaN` @@ -545,12 +543,12 @@ This returns `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"; +const person = 'Lydia'; const age = 21; getPersonInfo`${person} is ${age} years old`; @@ -576,13 +574,13 @@ 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!"); - } 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 }); @@ -612,7 +610,7 @@ This is why both `{ age: 18 } === { age: 18 }` and `{ age: 18 } == { age: 18 }` ```javascript function getAge(...args) { - console.log(typeof args); + console.log(typeof args); } getAge(21); @@ -639,9 +637,9 @@ The rest parameter (`...args`) lets us "collect" all remaining arguments into an ```javascript function getAge() { - "use strict"; - age = 21; - console.log(age); + 'use strict'; + age = 21; + console.log(age); } getAge(); @@ -667,7 +665,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` @@ -690,7 +688,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. @@ -743,12 +741,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); ``` @@ -774,7 +772,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); ``` @@ -817,8 +815,8 @@ The base execution context is the global execution context: it's what's accessib ```javascript for (let i = 1; i < 5; i++) { - if (i === 3) continue; - console.log(i); + if (i === 3) continue; + console.log(i); } ``` @@ -843,10 +841,10 @@ 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'; name.giveLydiaPizza(); ``` @@ -872,8 +870,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; @@ -905,9 +903,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(); @@ -959,9 +957,11 @@ This is where an event loop starts to work. An **event loop** looks at the stack ```html
-
- -
+
+ +
``` @@ -986,7 +986,9 @@ The deepest nested element that caused the event is the target of the event. You ```html
-

Click here!

+

+ Click here! +

``` @@ -1010,10 +1012,10 @@ 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}`; + return `${this.name} is ${age}`; } console.log(sayHi.call(person, 21)); @@ -1043,7 +1045,7 @@ With both, we can pass the object to which we want the `this` keyword to refer t ```javascript function sayHi() { - return (() => 0)(); + return (() => 0)(); } console.log(typeof sayHi()); @@ -1073,8 +1075,8 @@ FYI: there are only 7 built-in types: `null`, `undefined`, `boolean`, `number`, ```javascript 0; new Number(0); -(""); -(" "); +(''); +(' '); new Boolean(false); undefined; ``` @@ -1164,15 +1166,15 @@ depending on where you run it (it's different for every browser, node, etc.) ```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); })(); ``` @@ -1223,14 +1225,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( - (acc, cur) => { - return acc.concat(cur); - }, - [1, 2] +[[0, 1], [2, 3]].reduce( + (acc, cur) => { + return acc.concat(cur); + }, + [1, 2], ); ``` @@ -1257,7 +1256,7 @@ Then, `[1, 2, 0, 1]` is `acc` and `[2, 3]` is `cur`. We concatenate them, and ge ```javascript !!null; -!!""; +!!''; !!1; ``` @@ -1285,7 +1284,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 @@ -1308,7 +1307,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"]` @@ -1332,8 +1331,8 @@ A string is an iterable. The spread operator maps every character of an iterable ```javascript function* generator(i) { - yield i; - yield i * 2; + yield i; + yield i * 2; } const gen = generator(10); @@ -1367,14 +1366,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"` @@ -1397,7 +1396,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; @@ -1437,12 +1436,12 @@ We are only modifying the value of the `person` variable, and not the first elem ```javascript const person = { - name: "Lydia", - age: 21, + name: 'Lydia', + age: 21, }; for (const item in person) { - console.log(item); + console.log(item); } ``` @@ -1466,7 +1465,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"` @@ -1493,7 +1492,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` @@ -1518,9 +1517,9 @@ 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; - return num * 2; +[1, 2, 3].map(num => { + if (typeof num === 'number') return; + return num * 2; }); ``` @@ -1547,12 +1546,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); @@ -1584,16 +1583,16 @@ 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); - } catch (e) { - console.log("Oh no an error:", e); - } + try { + const data = greeting(); + console.log('It worked!', data); + } catch (e) { + console.log('Oh no an error:', e); + } } sayHi(); @@ -1622,8 +1621,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(); @@ -1651,7 +1650,7 @@ When you return a property, the value of the property is equal to the _returned_ ```javascript (() => { - let x = (y = 10); + let x = (y = 10); })(); console.log(typeof x); @@ -1690,16 +1689,16 @@ However, we created a global variable `y` when setting `y` equal to `10`. This v ```javascript class Dog { - constructor(name) { - this.name = name; - } + constructor(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(); @@ -1764,7 +1763,7 @@ export default counter; ```javascript // index.js -import myCounter from "./counter"; +import myCounter from './counter'; myCounter += 1; @@ -1793,7 +1792,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); @@ -1864,7 +1863,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); @@ -1890,9 +1889,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)); @@ -1921,12 +1920,12 @@ Properties added using the `defineProperty` method are immutable by default. You ```javascript const settings = { - username: "lydiahallie", - level: 19, - health: 90, + username: 'lydiahallie', + level: 19, + health: 90, }; -const data = JSON.stringify(settings, ["level", "health"]); +const data = JSON.stringify(settings, ['level', 'health']); console.log(data); ``` @@ -1957,7 +1956,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); @@ -1991,7 +1990,7 @@ The unary operator `++` _first returns_ the value of the operand, _then incremen const value = { number: 10 }; const multiply = (x = { ...value }) => { - console.log((x.number *= 2)); + console.log((x.number *= 2)); }; multiply(); @@ -2053,39 +2052,40 @@ 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? ```javascript class Dog { - constructor(name) { - this.name = name; - } -} + 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; - } -} + // 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 @@ -2113,12 +2113,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; ``` @@ -2146,7 +2146,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` @@ -2169,7 +2169,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)); ``` @@ -2196,7 +2196,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: `"🥑💻"` @@ -2220,11 +2220,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") { - return "Oh wow... Guess we're gone here"; - } - return "JavaScript loves you back ❤️"; + 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(); @@ -2292,7 +2292,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(); @@ -2326,10 +2326,10 @@ This would've logged `"I made it!"` ```javascript function addToList(item, list) { - return list.push(item); + return list.push(item); } -const result = addToList("apple", ["banana"]); +const result = addToList('apple', ['banana']); console.log(result); ``` @@ -2389,7 +2389,7 @@ 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 { name: myName } = { name: 'Lydia' }; console.log(name); ``` @@ -2419,7 +2419,7 @@ Since we try to log `name`, a variable that is not defined, a ReferenceError get ```javascript function sum(a, b) { - return a + b; + return a + b; } ``` @@ -2444,16 +2444,16 @@ The `sum` function always returns the same result. If we pass `1` and `2`, it wi ```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 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(); @@ -2490,14 +2490,14 @@ 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); + console.log(item); } for (let item of myLifeSummedUp) { - console.log(item); + console.log(item); } ``` @@ -2554,7 +2554,7 @@ 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()); @@ -2586,20 +2586,20 @@ 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: "🥑", - getStatus() { - return this.status; - }, - }; + const data = { + status: '🥑', + getStatus() { + return this.status; + }, + }; - console.log(data.getStatus()); - console.log(data.getStatus.call(this)); + console.log(data.getStatus()); + console.log(data.getStatus.call(this)); }, 0); ``` @@ -2626,12 +2626,12 @@ With the `call` method, we can change the object to which the `this` keyword ref ```javascript const person = { - name: "Lydia", - age: 21, + name: 'Lydia', + age: 21, }; let city = person.city; -city = "Amsterdam"; +city = 'Amsterdam'; console.log(person); ``` @@ -2663,13 +2663,13 @@ When logging the `person` object, the unmodified object gets returned. ```javascript function checkAge(age) { - if (age < 18) { - const message = "Sorry, you're too young."; - } else { - const message = "Yay! You're old enough!"; - } + if (age < 18) { + const message = "Sorry, you're too young."; + } else { + const message = "Yay! You're old enough!"; + } - return message; + return message; } console.log(checkAge(21)); @@ -2695,9 +2695,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. @@ -2721,7 +2721,7 @@ The value of `res` in the second `.then` is equal to the returned value of the p ```javascript function getName(name) { - const hasName = // + const hasName = // } ``` @@ -2751,7 +2751,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: `"""` @@ -2777,7 +2777,7 @@ 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); @@ -2806,11 +2806,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); ``` @@ -2838,12 +2838,12 @@ The `data` object has a `default` property for the default export, other propert ```javascript class Person { - constructor(name) { - this.name = name; - } + constructor(name) { + this.name = name; + } } -const member = new Person("John"); +const member = new Person('John'); console.log(typeof member); ``` @@ -2861,7 +2861,7 @@ Classes are syntactical sugar for function constructors. The equivalent of the ` ```javascript function Person() { - this.name = name; + this.name = name; } ``` @@ -2903,11 +2903,11 @@ 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."; + "Here's chocolate... now go hit the gym already."; console.log(giveLydiaPizza.prototype); console.log(giveLydiaChocolate.prototype); @@ -2934,12 +2934,12 @@ Regular functions, such as the `giveLydiaPizza` function, have a `prototype` pro ```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); } ``` @@ -2971,7 +2971,7 @@ The second subarray is `[ "age", 21 ]`, with `x` equal to `"age"`, and `y` equal ```javascript function getItems(fruitList, ...args, favoriteFruit) { - return [...fruitList, ...args, favoriteFruit] + return [...fruitList, ...args, favoriteFruit] } getItems(["banana", "apple"], "pear", "orange") @@ -2991,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'); ``` The above example works. This returns the array `[ 'banana', 'apple', 'orange', 'pear' ]` @@ -3008,10 +3008,10 @@ 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)); @@ -3048,15 +3048,15 @@ This means that `a + b` is never reached, since a function stops running after t ```javascript class Person { - constructor() { - this.name = "Lydia"; - } + constructor() { + this.name = 'Lydia'; + } } Person = class AnotherPerson { - constructor() { - this.name = "Sarah"; - } + constructor() { + this.name = 'Sarah'; + } }; const member = new Person(); @@ -3084,7 +3084,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); @@ -3153,7 +3153,7 @@ Since no value gets returned in this case, the function returns `undefined`. ###### 99. What's the output? ```javascript -const name = "Lydia"; +const name = 'Lydia'; console.log(name()); ``` @@ -3185,8 +3185,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` @@ -3212,7 +3212,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); @@ -3244,16 +3244,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(await myPromise()); + console.log('second'); } firstFunction(); @@ -3291,11 +3291,11 @@ 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); + console.log(item + 2); } ``` @@ -3351,14 +3351,14 @@ 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!"); - } else { - console.log("They are the same!"); - } + if (person1 !== person2) { + console.log('Not the same!'); + } else { + console.log('They are the same!'); + } } -const person = { name: "Lydia" }; +const person = { name: 'Lydia' }; compareMembers(person); ``` @@ -3390,14 +3390,14 @@ The code block in the `else` statement gets run, and `They are the same!` gets l ```javascript const colorConfig = { - red: true, - blue: false, - green: true, - black: true, - yellow: false, + red: true, + blue: false, + green: true, + black: true, + yellow: false, }; -const colors = ["pink", "red", "blue"]; +const colors = ['pink', 'red', 'blue']; console.log(colorConfig.colors[1]); ``` @@ -3426,7 +3426,7 @@ JavaScript interprets (or unboxes) statements. When we use bracket notation, it ###### 107. What's its value? ```javascript -console.log("❤️" === "❤️"); +console.log('❤️' === '❤️'); ``` - A: `true` @@ -3447,14 +3447,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` @@ -3479,10 +3479,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); ``` @@ -3535,8 +3535,8 @@ JSON.parse(jsonNumber); // 4 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"}' +// 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' } ``` @@ -3548,11 +3548,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"; + console.log(name); + let name = 'Sarah'; } getName(); @@ -3575,10 +3575,10 @@ 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); + console.log(name); } getName(); // Lydia @@ -3593,11 +3593,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(); @@ -3643,7 +3643,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` @@ -3667,9 +3667,9 @@ Expressions within template literals are evaluated first. This means that the st ```javascript let config = { - alert: setInterval(() => { - console.log("Alert!"); - }, 1000), + alert: setInterval(() => { + console.log('Alert!'); + }, 1000), }; config = null; @@ -3696,16 +3696,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 @@ -3732,14 +3732,14 @@ When adding a key/value pair using the `set` method, the key will be the value o ```javascript const person = { - name: "Lydia", - age: 21, + name: 'Lydia', + age: 21, }; 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); @@ -3773,7 +3773,7 @@ Then, we invoke the `changeAgeAndName` function, however we don't pass a paramet ```javascript function sumValues(x, y, z) { - return x + y + z; + return x + y + z; } ``` @@ -3798,7 +3798,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)]); ``` @@ -3824,15 +3824,15 @@ With the `+=` operand, we're incrementing the value of `num` by `1`. `num` had t ```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); @@ -3866,12 +3866,12 @@ 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!`); + console.log(`We don't have to buy bananas!`); } ``` @@ -3896,10 +3896,10 @@ We passed the condition `groceries.indexOf("banana")` to the if-statement. `groc ```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); @@ -3925,10 +3925,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` @@ -3953,9 +3953,9 @@ console.log(!typeof name === "string"); ###### 123. What's the 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); @@ -3982,16 +3982,16 @@ The `add` function returns an arrow function, which returns an arrow function, w ```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 +4016,7 @@ The generator function `range` returns an async object with promises for each it ```javascript const myFunc = ({ x, y, z }) => { - console.log(x, y, z); + console.log(x, y, z); }; myFunc(1, 2, 3); @@ -4043,20 +4043,20 @@ myFunc(1, 2, 3); ```javascript function getFine(speed, amount) { - const formattedSpeed = new Intl.NumberFormat("en-US", { - style: "unit", - unit: "mile-per-hour", - }).format(speed); + 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); + const formattedAmount = new Intl.NumberFormat('en-US', { + style: 'currency', + currency: 'USD' + }).format(amount); - return `The driver drove ${formattedSpeed} and has to pay ${formattedAmount}`; + 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 @@ -4079,8 +4079,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); ``` @@ -4105,7 +4105,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)); @@ -4140,8 +4140,8 @@ With the `isNaN` method, you can check if the value you pass is not a number. `n const randomValue = 21; function getInfo() { - console.log(typeof randomValue); - const randomValue = "Lydia Hallie"; + console.log(typeof randomValue); + const randomValue = 'Lydia Hallie'; } getInfo(); @@ -4167,16 +4167,16 @@ Variables declared with the `const` keyword are not referencable before their in ###### 130. What's the output? ```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!'); + } })(); ``` @@ -4200,7 +4200,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)); ``` @@ -4226,13 +4226,13 @@ With the `flat` method, we can create a new, flattened array. The depth of the f ```javascript class Counter { - constructor() { - this.count = 0; - } + constructor() { + this.count = 0; + } - increment() { - this.count++; - } + increment() { + this.count++; + } } const counterOne = new Counter(); @@ -4273,19 +4273,19 @@ 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!"); + 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(); @@ -4322,11 +4322,11 @@ We get to the last line of `funcTwo`, which logs `Last line!` to the console. No ```javascript // sum.js export default function sum(x) { - return x + x; + return x + x; } // index.js -import * as sum from "./sum"; +import * as sum from './sum'; ``` - A: `sum(4)` @@ -4343,12 +4343,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); ``` @@ -4356,9 +4356,9 @@ The following would get logged: ```javascript { - default: "I love JavaScript", - name: "Lydia", - age: 21 + default: "I love JavaScript", + name: "Lydia", + age: 21 } ``` @@ -4379,13 +4379,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; ``` @@ -4415,7 +4415,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); ``` @@ -4443,10 +4443,10 @@ However, you can still modify the value of existing properties. ```javascript const person = { - name: "Lydia Hallie", - address: { - street: "100 Main St", - }, + name: 'Lydia Hallie', + address: { + street: '100 Main St', + }, }; Object.freeze(person); @@ -4474,10 +4474,10 @@ 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); + console.log(num, value); } myFunc(); @@ -4507,21 +4507,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++; - } + increment() { + this.#number++ + } - getNum() { - return this.#number; - } + getNum() { + 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 +4545,20 @@ 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) { - 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,18 +4589,18 @@ 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) { - hobbies.push(hobby); - return hobbies; + hobbies.push(hobby); + return hobbies; } -addHobby("running", []); -addHobby("dancing"); -addHobby("baking", person.hobbies); +addHobby('running', []); +addHobby('dancing'); +addHobby('baking', person.hobbies); console.log(person.hobbies); ``` @@ -4634,16 +4634,16 @@ After pushing `dancing` and `baking`, the value of `person.hobbies` is `["coding ```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(); @@ -4669,11 +4669,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; ``` @@ -4698,8 +4698,8 @@ The `const` keyword simply means we cannot _redeclare_ the value of that variabl ```javascript const person = { - name: "Lydia Hallie", - age: 21 + name: "Lydia Hallie", + age: 21 } [...person] // ["Lydia Hallie", 21] @@ -4728,11 +4728,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 @@ -4756,12 +4756,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`, 🍌 @@ -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,18 +4792,18 @@ Lastly, we're trying to log the second item in the `['🍊', '🍌']` subarray o ```javascript class Calc { constructor() { - this.count = 0; + this.count = 0 } increase() { - this.count++; + 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` @@ -4828,24 +4828,24 @@ 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", -}; + password: "12345" +} const updateUser = ({ email, password }) => { if (email) { - Object.assign(user, { email }); + Object.assign(user, { email }) } if (password) { - user.password = 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` @@ -4868,13 +4868,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: `['🍌', '🍊', '🍎']` @@ -4889,7 +4889,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 `['🍇', '🍊', '🍎']`.

@@ -4900,13 +4900,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" }` @@ -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"}`. +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" }`. @@ -4937,13 +4937,13 @@ Logging `animals[dog]`, or actually `animals["object Object"]` since converting ```javascript const user = { email: "my@email.com", - updateEmail: (email) => { - this.email = email; - }, -}; + 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` @@ -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.

@@ -4966,20 +4966,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']]` @@ -4992,26 +4992,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` @@ -5024,7 +5021,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 }` @@ -5036,18 +5033,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, - }; -}; + 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 }` @@ -5070,13 +5067,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 ff49b4a4517dfda49137d9c1411a6b3c57dce8e5 Mon Sep 17 00:00:00 2001 From: Jacob Herper Date: Thu, 24 Sep 2020 16:16:06 +0100 Subject: [PATCH 651/915] fixed formatting for german translation --- de-DE/README.md | 880 ++++++++++++++++++++++++------------------------ 1 file changed, 443 insertions(+), 437 deletions(-) diff --git a/de-DE/README.md b/de-DE/README.md index d2601056..516171f7 100644 --- a/de-DE/README.md +++ b/de-DE/README.md @@ -42,19 +42,19 @@ Die Antworten sind unterhalb der Fragen versteckt. Du kannst einfach darauf klic ```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

@@ -74,17 +74,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

@@ -104,21 +104,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

@@ -143,9 +143,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

@@ -165,19 +165,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

@@ -208,11 +208,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

@@ -244,10 +244,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

@@ -269,24 +269,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

@@ -308,9 +308,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

@@ -330,16 +330,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

@@ -359,22 +359,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

@@ -384,8 +384,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}`; }; ``` @@ -401,8 +401,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"); @@ -412,10 +412,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

@@ -433,10 +433,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

@@ -454,8 +454,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

@@ -473,16 +473,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

@@ -507,10 +507,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

@@ -538,9 +538,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"; @@ -549,9 +549,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

@@ -569,21 +569,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

@@ -605,16 +605,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

@@ -632,18 +632,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

@@ -663,10 +663,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

@@ -686,10 +686,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

@@ -714,10 +714,10 @@ var num = 10; console.log(num); ``` -- A: `8` -- B: `10` -- C: `SyntaxError` -- D: `ReferenceError` +- A: `8` +- B: `10` +- C: `SyntaxError` +- D: `ReferenceError`

Antwort

@@ -745,10 +745,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

@@ -771,10 +771,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

@@ -790,9 +790,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

@@ -810,15 +810,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

@@ -836,7 +836,7 @@ 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"; @@ -844,10 +844,10 @@ const name = "Lydia"; 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

@@ -874,10 +874,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

@@ -907,10 +907,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

@@ -952,16 +952,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

@@ -979,14 +981,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

@@ -1006,17 +1010,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

@@ -1036,16 +1040,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

@@ -1072,10 +1076,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

@@ -1084,12 +1088,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. @@ -1104,10 +1108,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

@@ -1130,10 +1134,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

@@ -1155,22 +1159,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

@@ -1190,10 +1194,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

@@ -1214,21 +1218,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

@@ -1252,10 +1253,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

@@ -1279,10 +1280,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

@@ -1302,10 +1303,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

@@ -1365,7 +1366,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"` @@ -1429,7 +1430,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) { @@ -1509,7 +1510,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; }); @@ -1675,6 +1676,7 @@ Da wir die Variable `y` aber global erstellt haben ist ihr Wert `10` auch hier v

+ --- ###### 55. Was wird ausgegeben? @@ -1686,7 +1688,7 @@ class Dog { } } -Dog.prototype.bark = function () { +Dog.prototype.bark = function() { console.log(`Woof I am ${this.name}`); }; @@ -1801,7 +1803,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. @@ -1914,7 +1916,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"]); @@ -1948,7 +1950,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); @@ -1974,6 +1976,8 @@ Der unäre Operator `++` _gibt zuerst_ den Wert des Operanden aus und _erhöht d

+ + --- ###### 64. Was wird ausgegeben? @@ -2041,7 +2045,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. -

@@ -2054,10 +2057,10 @@ class Dog { constructor(name) { this.name = name; } -} +}; class Labrador extends Dog { - // 1 + // 1 constructor(name, size) { this.size = size; } @@ -2071,12 +2074,13 @@ class Labrador extends Dog { super(name); this.size = size; } - // 4 + // 4 constructor(name, size) { this.name = name; this.size = size; } -} + +}; ``` - A: 1 @@ -2094,7 +2098,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. -

@@ -2135,9 +2138,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` @@ -2150,7 +2153,7 @@ console.log(Symbol("foo") === Symbol("foo")); #### Antwort: A -Jedes Symbol ist eindeutig. Der Sinn des Argumentes, welches an das Symbol weitergegeben wird, ist dem Symbol eine Beschreibung zu geben. Der Wert des Symbols hängt nicht von diesem Argument ab. Beim vergleichen der Symbole werden zwei komplett neue Symbole erstellt: das erste `Symbol('foo')` und das zweite `Symbol('foo')`. Diese beiden Werte sind eindeutig und nicht identisch, weshalb `Symbol('foo') === Symbol('foo')` `false` ausgibt. +Jedes Symbol ist eindeutig. Der Sinn des Argumentes, welches an das Symbol weitergegeben wird, ist dem Symbol eine Beschreibung zu geben. Der Wert des Symbols hängt nicht von diesem Argument ab. Beim vergleichen der Symbole werden zwei komplett neue Symbole erstellt: das erste `Symbol('foo')` und das zweite `Symbol('foo')`. Diese beiden Werte sind eindeutig und nicht identisch, weshalb `Symbol('foo') === Symbol('foo')` `false` ausgibt.

@@ -2160,15 +2163,15 @@ 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"` -- 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"`,
Antwort

@@ -2437,7 +2440,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 { @@ -2482,21 +2485,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

@@ -2519,14 +2522,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

@@ -2546,16 +2549,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

@@ -2578,21 +2581,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 `"😍"` @@ -2609,6 +2612,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. +

@@ -2619,13 +2623,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 }` @@ -2656,15 +2660,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."` @@ -2687,15 +2691,15 @@ 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. - B: Das Ergebnis des zweiten Aufrufs der `fetch` Methode. - C: Das Ergebnis des Callbacks im vorhergehenden `.then()`. -- D: Immer `undefined`. +- D: Immer `undefined`.
Antwort

@@ -2734,16 +2738,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: `"""` @@ -2769,10 +2773,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` @@ -2797,14 +2801,14 @@ Wenn man den Wert des Standard Paramenters gleich dem Parameter setztm der _dana ###### 89. Was wird ausgegeben? ```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" }` @@ -2831,12 +2835,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"` @@ -2853,7 +2857,7 @@ Klassen sind syntaktischer Zucker für Funktionskontruktoren. Das Equivalent der ```javascript function Person() { - this.name = name; + this.name = name } ``` @@ -2867,9 +2871,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]` @@ -2895,18 +2899,17 @@ 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: ...}` -- B: `{}` `{ constructor: ...}` +- A: `{ constructor: ...}` `{ constructor: ...}` +- B: `{}` `{ constructor: ...}` - C: `{ constructor: ...}` `{}` - D: `{ constructor: ...}` `undefined` @@ -2915,7 +2918,7 @@ console.log(giveLydiaChocolate.prototype); #### Antwort: D -Reguläre Funktionen wie `giveLydiaPizza` haben eine `prototype` Property, die ein Objekt (Prototype Object) mit einem `constructor` ist. Arrow Funktionen dagegen (wie `giveLydiaChocolate`) haben keinen `prototype`. `undefined` wird ausgegeben, wenn wir versuchen den `prototype` mit `giveLydiaChocolate.prototype` aufzurufen. +Reguläre Funktionen wie `giveLydiaPizza` haben eine `prototype` Property, die ein Objekt (Prototype Object) mit einem `constructor` ist. Arrow Funktionen dagegen (wie `giveLydiaChocolate`) haben keinen `prototype`. `undefined` wird ausgegeben, wenn wir versuchen den `prototype` mit `giveLydiaChocolate.prototype` aufzurufen.

@@ -2927,16 +2930,16 @@ 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) } ``` - A: `name` `Lydia` und `age` `21` -- B: `["name", "Lydia"]` und `["age", 21]` +- B: `["name", "Lydia"]` und `["age", 21]` - C: `["name", "age"]` und `undefined` - D: `Error` @@ -2947,7 +2950,7 @@ for (const [x, y] of Object.entries(person)) { `Object.entries(person)` gibt ein Array mit verschachtelten Arrays der Keys aus: -`[ [ 'name', 'Lydia' ], [ 'age', 21 ] ]` +`[ [ 'name', 'Lydia' ], [ 'age', 21 ] ]` Mit der `for-of` Schleife iterieren wir über jedes Element in dem Array, in diesem Fall die verschachtelten Arrays. Wir können die verschachtelten Arrays mit `const [x, y]` in der for-of Schleife destrukturieren. `x` ist gleich dem ersten Element, `y` ist gleich dem zweiten Element in dem verschachtelten Array. @@ -2970,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,14 +2986,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. -

@@ -3000,14 +3002,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` @@ -3025,8 +3030,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. @@ -3042,18 +3047,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"` @@ -3077,11 +3082,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')"]` @@ -3129,13 +3134,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. @@ -3147,9 +3152,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` @@ -3180,8 +3185,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` @@ -3206,11 +3211,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` `[]` @@ -3239,16 +3244,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') } ``` @@ -3266,12 +3271,12 @@ Mit einem Promise sagen wir _Ich möchte diese Funktion ausführen, aber ich leg Wir können auf den Wert mit `.then()` oder `await` in einer `async` Funktion zugreifen, aber `.then()` und `await` unterscheiden sich in einem bestimmten Punkt. -In `firstFunction` legen wir `myPromise` beiseite, während die Funktion durchläuft, aber wir arbeiten anderen Code ab, hier `console.log('second')`. -Dann wird die Funktion abgeschlossen und der String `I have resolved` wird ausgegeben, nachdem sich der Call Stack geleert hat. +In `firstFunction` legen wir `myPromise` beiseite, während die Funktion durchläuft, aber wir arbeiten anderen Code ab, hier `console.log('second')`. +Dann wird die Funktion abgeschlossen und der String `I have resolved` wird ausgegeben, nachdem sich der Call Stack geleert hat. Mit dem `await` Keyword in `secondFunction` wird die Funktion gestoppt bis der Wert ausgegeben wurde, erst dann wird die nächste Zeile ausgeführt. -Das bedeutet, dass auf `myPromise` gewartet und dann der Wert `I have resolved` ausgegeben wird und erst dann wird die nächste Zeile ausgeführt und `second` wird geloggt. +Das bedeutet, dass auf `myPromise` gewartet und dann der Wert `I have resolved` ausgegeben wird und erst dann wird die nächste Zeile ausgeführt und `second` wird geloggt.

@@ -3281,14 +3286,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) } ``` @@ -3306,7 +3311,7 @@ Der `+` Operator wird nicht nur für numerische Werte verwendet, wir können mit Der erste Wert ist `1`, was ein numerischer Wert ist. `1 + 2` ergibt die Zahl `3`. -Der zweite Wert hingegen ist der String `"Lydia"`. `"Lydia"` ist ein String und `2` ist eine Nummer: `2` wird in einem String umgewandelt. `"Lydia"` und `"2"` werden zusammengesetzt, was den String `"Lydia2"` ausgibt. +Der zweite Wert hingegen ist der String `"Lydia"`. `"Lydia"` ist ein String und `2` ist eine Nummer: `2` wird in einem String umgewandelt. `"Lydia"` und `"2"` werden zusammengesetzt, was den String `"Lydia2"` ausgibt. `{ name: "Lydia" }` ist ein Objekt. Weder eine Nummer, noch ein Objekt sind ein String, aber beide werden zu Strings konvertiert und `"[object Object]"` wird ausgegeben. `"[object Object]"` zusammengesetzt mit `"2"` wird `"[object Object]2"`. @@ -3318,7 +3323,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` @@ -3333,7 +3338,7 @@ Promise.resolve(5); Wir können jeden Wert an `Promise.resolve` übergeben, es muss nicht unbedingt ein Promise sein. Die Methode selbst gibt ein Promise zurück, was einen Wert ausgibt. Wenn man eine normale Funktion übergibt wird das Promise einen normalen Wert ausgeben. Wenn ein Promise übergeben wird so wird ein Promise gelöst und der Wert des gelösten Promises ausgegeben. -In diesem Fall haben wir nur die Zahl `5` übergeben und diese wird genauso ausgegeben: `5`. +In diesem Fall haben wir nur die Zahl `5` übergeben und diese wird genauso ausgegeben: `5`.

@@ -3345,15 +3350,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!` @@ -3372,7 +3377,7 @@ Wir setzen den Standardwert für `person2` gleich dem `person` Objekt und überg Das bedeutet, dass beide Werte eine Referenz zum gleichen Ort im Speicher aufweisen und daher gleich sind. -Der Code im `else` Statement wird aufgerufen und `They are the same!` wird geloggt. +Der Code im `else` Statement wird aufgerufen und `They are the same!` wird geloggt.

@@ -3388,11 +3393,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` @@ -3405,7 +3410,7 @@ console.log(colorConfig.colors[1]); #### Antwort: D -In JavaScript gibt es zwei Wege auf Properties an Objekten zuzugreifen: Punkt-Notation oder Klammern-Notation. In diesem Beispiel nutzen wir Punkt-Notation (`colorConfig.colors`) anstelle von Klammern-Notation (`colorConfig["colors"]`). +In JavaScript gibt es zwei Wege auf Properties an Objekten zuzugreifen: Punkt-Notation oder Klammern-Notation. In diesem Beispiel nutzen wir Punkt-Notation (`colorConfig.colors`) anstelle von Klammern-Notation (`colorConfig["colors"]`). Mit Punkt-Notation versucht JavaScript die Property am Objekt mit diesem exakten Namen zu finden. In unserem Beispiel `colors` im `colorConfig` Objekt. Da es keine Property `colorConfig` gibt wird `undefined` ausgegeben. Dann versuchen wir den Wert des ersten Elements mit `[1]` aufzurufen, was an `undefined` nicht möglich ist, wodurch wir `TypeError: Cannot read property '1' of undefined` ausgegeben bekommen. @@ -3419,7 +3424,7 @@ JavaScript interpretiert Statements. Wenn wir Klammern-Notation verwenden wird d ###### 107. Was wird ausgegeben? ```javascript -console.log("❤️" === "❤️"); +console.log('❤️' === '❤️') ``` - A: `true` @@ -3437,22 +3442,22 @@ 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? +###### 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` - B: `map` `reduce` `slice` `splice` -- C: `map` `slice` `splice` +- C: `map` `slice` `splice` - D: `splice`
Antwort @@ -3460,29 +3465,30 @@ emojis.splice(1, 2, "✨"); #### Antwort: D -Mit der `splice` Methode ändern wir das ursprüngliche Array durch löschen, ersetzen oder ergänzen von Elementen. In diesem Fall haben wir 2 Elemente vom Index 1 (`'🥑'` und `'😍'`) entfernt und ✨ stattdessen eingefügt. +Mit der `splice` Methode ändern wir das ursprüngliche Array durch löschen, ersetzen oder ergänzen von Elementen. In diesem Fall haben wir 2 Elemente vom Index 1 (`'🥑'` und `'😍'`) entfernt und ✨ stattdessen eingefügt. `map`, `filter` und `slice` geben ein neues Array aus, `find` gibt ein Element aus und `reduce` gibt einen neuen Wert aus.

+ --- ###### 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: `['🍕', '🍫', '🥑', '🍔']` - B: `['🍝', '🍫', '🥑', '🍔']` -- C: `['🍝', '🍕', '🍫', '🥑', '🍔']` +- C: `['🍝', '🍕', '🍫', '🥑', '🍔']` - D: `ReferenceError`
Antwort @@ -3502,7 +3508,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 @@ -3519,16 +3525,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' } ```

@@ -3536,17 +3542,17 @@ JSON.parse(jsonArray); // { name: 'Lydia' } --- -###### 111. Was wird ausgegeben? +###### 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 @@ -3566,13 +3572,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 ```

@@ -3584,18 +3590,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` @@ -3613,17 +3619,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 ```

@@ -3634,7 +3640,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` @@ -3647,7 +3653,7 @@ console.log(`${((x) => x)("I love")} to program`); #### Antwort: A -Expressions innerhalb von Template Literals werden zuerst berechnet. Das bedeutet, dass der String den ausgegebenen Wert der Expression beinhaltet, hier die IIFE (immediately invoked Function) `(x => x)('I love')`. Wir geben den Wert `'I love'` als Argument an die `x => x` Arrow Funktion. `x` ist gleich `'I love'` und wird ausgegeben. Das Ergebnis ist `I love to program`. +Expressions innerhalb von Template Literals werden zuerst berechnet. Das bedeutet, dass der String den ausgegebenen Wert der Expression beinhaltet, hier die IIFE (immediately invoked Function) `(x => x)('I love')`. Wir geben den Wert `'I love'` als Argument an die `x => x` Arrow Funktion. `x` ist gleich `'I love'` und wird ausgegeben. Das Ergebnis ist `I love to program`.

@@ -3709,7 +3715,7 @@ myMap.get(() => 'greeting')) #### Antwort: B -Beim Setzen eines Key/Wert Paars mit der `set` Methode wird der Key als erstes Argument an die `set` Funktion übergeben und der Wert wird als zweites Argument eingegeben. Der Key ist die _Funktion_ `() => 'greeting'` und der Wert ist `'Hello world'`. `myMap` ist jetzt `{ () => 'greeting' => 'Hello world!' }`. +Beim Setzen eines Key/Wert Paars mit der `set` Methode wird der Key als erstes Argument an die `set` Funktion übergeben und der Wert wird als zweites Argument eingegeben. Der Key ist die _Funktion_ `() => 'greeting'` und der Wert ist `'Hello world'`. `myMap` ist jetzt `{ () => 'greeting' => 'Hello world!' }`. 1 ist falsch, weil der Key nicht `'greeting'`, sondern `() => 'greeting'` ist. 3 ist falsch, weil wir eine neue Funktion erstellen, indem wir sie als Argument übergeben. Objekte interagieren anhand von _Referenzen_. Funktionen sind Objekte, weshalb zwei Funktionen streng gesehen nie gleich sind, selbst wenn sie sich nicht unterscheiden. @@ -3724,19 +3730,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}` From 7571f2b046cb2730a4d71e23f49501047a5386b1 Mon Sep 17 00:00:00 2001 From: Jacob Herper Date: Sun, 27 Sep 2020 14:53:58 +0100 Subject: [PATCH 652/915] changed links to other lanugages --- ar-AR/README_AR.md | 35 ++++++++++++++++++----------------- bs-BS/README-bs_BS.md | 35 ++++++++++++++++++----------------- es-ES/README-ES.md | 35 ++++++++++++++++++----------------- fr-FR/README_fr-FR.md | 35 ++++++++++++++++++----------------- id-ID/README.md | 35 ++++++++++++++++++----------------- ja-JA/README-ja_JA.md | 36 ++++++++++++++++++------------------ ko-KR/README-ko_KR.md | 35 ++++++++++++++++++----------------- nl-NL/README.md | 35 ++++++++++++++++++----------------- pt-BR/README_pt_BR.md | 35 ++++++++++++++++++----------------- ru-RU/README.md | 35 ++++++++++++++++++----------------- th-TH/README.md | 35 ++++++++++++++++++----------------- tr-TR/README-tr_TR.md | 35 ++++++++++++++++++----------------- ua-UA/README-ua_UA.md | 35 ++++++++++++++++++----------------- vi-VI/README-vi.md | 35 ++++++++++++++++++----------------- 14 files changed, 252 insertions(+), 239 deletions(-) diff --git a/ar-AR/README_AR.md b/ar-AR/README_AR.md index b9f66e02..49d410c4 100644 --- a/ar-AR/README_AR.md +++ b/ar-AR/README_AR.md @@ -14,23 +14,24 @@ اللغات المتوفرة: -* [English](../en-EN/README.md) -* [العربية](../ar-AR/README_AR.md) -* [اللغة العامية - Egyptian Arabic](../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) -* [日本語](../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) -* [Українська мова](../ua-UA/README-ua_UA.md) -* [Tiếng Việt](../vi-VI/README-vi.md) -* [中文版本](../zh-CN/README-zh_CN.md) -* [Türkçe](../tr-TR/README-tr_TR.md) -* [ไทย](../th-TH/README-th_TH.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) +- [🇺🇦 Українська мова](./ua-UA/README-ua_UA.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 e040e6cb..28ebdfd1 100644 --- a/bs-BS/README-bs_BS.md +++ b/bs-BS/README-bs_BS.md @@ -12,23 +12,24 @@ Ovaj tjedni repo ažuriram s novim pitanjima. Odgovori su jednostavno dijelovima ispod pitanja kliknite na njih da biste ih proširili. Sretno :heart: -* [English](../en-EN/README.md) -* [العربية](../ar-AR/README_AR.md) -* [اللغة العامية - Egyptian Arabic](../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) -* [日本語](../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) -* [Українська мова](../ua-UA/README-ua_UA.md) -* [Tiếng Việt](../vi-VI/README-vi.md) -* [中文版本](../zh-CN/README-zh_CN.md) -* [Türkçe](../tr-TR/README-tr_TR.md) -* [ไทย](../th-TH/README-th_TH.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) +- [🇯🇵 日本語](./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) +- [🇺🇦 Українська мова](./ua-UA/README-ua_UA.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 290efbd1..009b394d 100644 --- a/es-ES/README-ES.md +++ b/es-ES/README-ES.md @@ -12,23 +12,24 @@ Lista de lenguajes disponibles: -* [English](../en-EN/README.md) -* [العربية](../ar-AR/README_AR.md) -* [اللغة العامية - Egyptian Arabic](../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) -* [日本語](../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) -* [Українська мова](../ua-UA/README-ua_UA.md) -* [Tiếng Việt](../vi-VI/README-vi.md) -* [中文版本](../zh-CN/README-zh_CN.md) -* [Türkçe](../tr-TR/README-tr_TR.md) -* [ไทย](../th-TH/README-th_TH.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) +- [🇯🇵 日本語](./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) +- [🇺🇦 Українська мова](./ua-UA/README-ua_UA.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 8ff2122d..f7aa5fb0 100644 --- a/fr-FR/README_fr-FR.md +++ b/fr-FR/README_fr-FR.md @@ -6,23 +6,24 @@ 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: -* [English](../en-EN/README.md) -* [العربية](../ar-AR/README_AR.md) -* [اللغة العامية - Egyptian Arabic](../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) -* [日本語](../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) -* [Українська мова](../ua-UA/README-ua_UA.md) -* [Tiếng Việt](../vi-VI/README-vi.md) -* [中文版本](../zh-CN/README-zh_CN.md) -* [Türkçe](../tr-TR/README-tr_TR.md) -* [ไทย](../th-TH/README-th_TH.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) +- [🇯🇵 日本語](./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) +- [🇺🇦 Українська мова](./ua-UA/README-ua_UA.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 20234347..e5c340a8 100644 --- a/id-ID/README.md +++ b/id-ID/README.md @@ -16,23 +16,24 @@ Jangan sungkan untuk terhubung dengan saya! 😊
Lihat 17 Terjemahan yang tersedia 🇪🇸🇮🇹🇩🇪 🇫🇷🇷🇺🇨🇳🇵🇹

-- [English](../en-EN/README.md) -- [العربية](../ar-AR/README_AR.md) -- [اللغة العامية - Egyptian Arabic](../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) -- [日本語](../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) -- [Українська мова](../ua-UA/README-ua_UA.md) -- [Tiếng Việt](../vi-VI/README-vi.md) -- [中文版本](../zh-CN/README-zh_CN.md) -- [Türkçe](../tr-TR/README-tr_TR.md) -- [ไทย](../th-TH/README-th_TH.md) -- [Indonesia](../id-ID/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) +- [🇯🇵 日本語](./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) +- [🇺🇦 Українська мова](./ua-UA/README-ua_UA.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 7a171692..0695cfea 100644 --- a/ja-JA/README-ja_JA.md +++ b/ja-JA/README-ja_JA.md @@ -8,24 +8,24 @@ 利用可能な言語リスト: -* [English](../en-EN/README.md) -* [العربية](../ar-AR/README_AR.md) -* [اللغة العامية - Egyptian Arabic](../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) -* [日本語](../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) -* [Українська мова](../ua-UA/README-ua_UA.md) -* [Tiếng Việt](../vi-VI/README-vi.md) -* [中文版本](../zh-CN/README-zh_CN.md) -* [Türkçe](../tr-TR/README-tr_TR.md) -* [ไทย](../th-TH/README-th_TH.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) +- [🇺🇦 Українська мова](./ua-UA/README-ua_UA.md) +- [🇻🇳 Tiếng Việt](./vi-VI/README-vi.md) +- [🇨🇳 简体中文](./zh-CN/README-zh_CN.md) +- [🇹🇼 繁體中文](./zh-TW/README_zh-TW.md) --- ###### 1. 何が出力されるでしょうか? diff --git a/ko-KR/README-ko_KR.md b/ko-KR/README-ko_KR.md index a5c5c60f..6d7b65dc 100644 --- a/ko-KR/README-ko_KR.md +++ b/ko-KR/README-ko_KR.md @@ -10,23 +10,24 @@ JavaScript 에 관한 객관식 문제를 [Instagram](https://www.instagram.com/ ✨✉이메일 업데이트 구독 ✉✨ 사용 가능한 언어 목록: -* [English](../en-EN/README.md) -* [العربية](../ar-AR/README_AR.md) -* [اللغة العامية - Egyptian Arabic](../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) -* [日本語](../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) -* [Українська мова](../ua-UA/README-ua_UA.md) -* [Tiếng Việt](../vi-VI/README-vi.md) -* [中文版本](../zh-CN/README-zh_CN.md) -* [Türkçe](../tr-TR/README-tr_TR.md) -* [ไทย](../th-TH/README-th_TH.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) +- [🇳🇱 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) +- [🇺🇦 Українська мова](./ua-UA/README-ua_UA.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 81cb88a7..727f64f9 100644 --- a/nl-NL/README.md +++ b/nl-NL/README.md @@ -17,23 +17,24 @@
Zie alle 17 beschikbare vertalingen

-* [English](../en-EN/README.md) -* [العربية](../ar-AR/README_AR.md) -* [اللغة العامية - Egyptian Arabic](../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) -* [日本語](../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) -* [Українська мова](../ua-UA/README-ua_UA.md) -* [Tiếng Việt](../vi-VI/README-vi.md) -* [中文版本](../zh-CN/README-zh_CN.md) -* [Türkçe](../tr-TR/README-tr_TR.md) -* [ไทย](../th-TH/README-th_TH.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) +- [🇧🇷 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) +- [🇺🇦 Українська мова](./ua-UA/README-ua_UA.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 7eb9706d..5fc396be 100644 --- a/pt-BR/README_pt_BR.md +++ b/pt-BR/README_pt_BR.md @@ -6,23 +6,24 @@ 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: -* [English](../en-EN/README.md) -* [العربية](../ar-AR/README_AR.md) -* [اللغة العامية - Egyptian Arabic](../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) -* [日本語](../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) -* [Українська мова](../ua-UA/README-ua_UA.md) -* [Tiếng Việt](../vi-VI/README-vi.md) -* [中文版本](../zh-CN/README-zh_CN.md) -* [Türkçe](../tr-TR/README-tr_TR.md) -* [ไทย](../th-TH/README-th_TH.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) +- [🇷🇺 Русский](./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) +- [🇻🇳 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 4eb94ea5..61383dbf 100644 --- a/ru-RU/README.md +++ b/ru-RU/README.md @@ -11,23 +11,24 @@ Список доступных переводов: -* [English](../en-EN/README.md) -* [العربية](../ar-AR/README_AR.md) -* [اللغة العامية - Egyptian Arabic](../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) -* [日本語](../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) -* [Українська мова](../ua-UA/README-ua_UA.md) -* [Tiếng Việt](../vi-VI/README-vi.md) -* [中文版本](../zh-CN/README-zh_CN.md) -* [Türkçe](../tr-TR/README-tr_TR.md) -* [ไทย](../th-TH/README-th_TH.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) +- [🇹🇭 ไทย](./th-TH/README-th_TH.md) +- [🇹🇷 Türkçe](./tr-TR/README-tr_TR.md) +- [🇺🇦 Українська мова](./ua-UA/README-ua_UA.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 0cfe2b62..ddb94410 100644 --- a/th-TH/README.md +++ b/th-TH/README.md @@ -18,23 +18,24 @@ ลิสต์ภาษาอื่นๆ: -* [English](../en-EN/README.md) -* [العربية](../ar-AR/README_AR.md) -* [اللغة العامية - Egyptian Arabic](../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) -* [日本語](../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) -* [Українська мова](../ua-UA/README-ua_UA.md) -* [Tiếng Việt](../vi-VI/README-vi.md) -* [中文版本](../zh-CN/README-zh_CN.md) -* [Türkçe](../tr-TR/README-tr_TR.md) -* [ไทย](../th-TH/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) +- [🇹🇷 Türkçe](./tr-TR/README-tr_TR.md) +- [🇺🇦 Українська мова](./ua-UA/README-ua_UA.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 8f8e2d8b..716038cb 100644 --- a/tr-TR/README-tr_TR.md +++ b/tr-TR/README-tr_TR.md @@ -12,23 +12,24 @@ Daha fazla soru eklendikçe eposta almak ister misiniz?
Mevcut dillerin listesi: -* [English](../en-EN/README.md) -* [العربية](../ar-AR/README_AR.md) -* [اللغة العامية - Egyptian Arabic](../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) -* [日本語](../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) -* [Українська мова](../ua-UA/README-ua_UA.md) -* [Tiếng Việt](../vi-VI/README-vi.md) -* [中文版本](../zh-CN/README-zh_CN.md) -* [Türkçe](../tr-TR/README-tr_TR.md) -* [ไทย](../th-TH/README-th_TH.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) +- [🇺🇦 Українська мова](./ua-UA/README-ua_UA.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/ua-UA/README-ua_UA.md index 764d4922..63789f59 100644 --- a/ua-UA/README-ua_UA.md +++ b/ua-UA/README-ua_UA.md @@ -6,23 +6,24 @@ Відповіді знаходяться в згорнутої секції нижче питань. Просто натисни на відповідь, щоб розгорнути. Успіхів! :heart: -* [English](../en-EN/README.md) -* [العربية](../ar-AR/README_AR.md) -* [اللغة العامية - Egyptian Arabic](../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) -* [日本語](../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) -* [Українська мова](../ua-UA/README-ua_UA.md) -* [Tiếng Việt](../vi-VI/README-vi.md) -* [中文版本](../zh-CN/README-zh_CN.md) -* [Türkçe](../tr-TR/README-tr_TR.md) -* [ไทย](../th-TH/README-th_TH.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) +- [🇻🇳 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 1e163ffd..bea67813 100644 --- a/vi-VI/README-vi.md +++ b/vi-VI/README-vi.md @@ -7,23 +7,24 @@ 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: -* [English](../en-EN/README.md) -* [العربية](../ar-AR/README_AR.md) -* [اللغة العامية - Egyptian Arabic](../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) -* [日本語](../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) -* [Українська мова](../ua-UA/README-ua_UA.md) -* [Tiếng Việt](../vi-VI/README-vi.md) -* [中文版本](../zh-CN/README-zh_CN.md) -* [Türkçe](../tr-TR/README-tr_TR.md) -* [ไทย](../th-TH/README-th_TH.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) +- [🇺🇦 Українська мова](./ua-UA/README-ua_UA.md) +- [🇨🇳 简体中文](./zh-CN/README-zh_CN.md) +- [🇹🇼 繁體中文](./zh-TW/README_zh-TW.md) --- From a843603b3347557abb22ca1d632c1237898c6d23 Mon Sep 17 00:00:00 2001 From: Oleksii <33310590+Seruf-Che@users.noreply.github.com> Date: Tue, 29 Sep 2020 10:59:00 +0300 Subject: [PATCH 653/915] Question 132 was added Question 132 was added. Question 123 - typo fixed. --- ru-RU/README.md | 51 ++++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 50 insertions(+), 1 deletion(-) diff --git a/ru-RU/README.md b/ru-RU/README.md index 4eb94ea5..e80e67ab 100644 --- a/ru-RU/README.md +++ b/ru-RU/README.md @@ -3957,7 +3957,7 @@ add(4)(5)(6); #### Ответ: A -Функция `add` возвращает стрелочную функцию, которая возвращает стрелочную функцию, которая возвращает стрелочную функцию (все еще у тут?). Первая функция получает аргумент `x` со значением `4`. Мы вызываем вторую функцию, которая получает аргумент `y` со значением `5`. Затем мы вызываем третью функцию, которая получает аргумент `z` со значением `6`. Когда мы пытаемся получить доступ к значениям `x`, `y` и `z` в функции последней стрелки, движок JS поднимается вверх по цепочке областей видимости, чтобы найти значения для `x` и `y` соответственно. Это возвращает `4` `5` `6`. +Функция `add` возвращает стрелочную функцию, которая возвращает стрелочную функцию, которая возвращает стрелочную функцию (все еще тут?). Первая функция получает аргумент `x` со значением `4`. Мы вызываем вторую функцию, которая получает аргумент `y` со значением `5`. Затем мы вызываем третью функцию, которая получает аргумент `z` со значением `6`. Когда мы пытаемся получить доступ к значениям `x`, `y` и `z` в функции последней стрелки, движок JS поднимается вверх по цепочке областей видимости, чтобы найти значения для `x` и `y` соответственно. Это возвращает `4` `5` `6`.

@@ -4205,3 +4205,52 @@ console.log(emojis.flat(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 класс содержит метод `increment` и свойство `count` в конструкторе. Сперва, при помощи `counterOne.increment()`, мы дважды вызываем метод `increment`. `counterOne.count` становится `2`. + + + +Затем, мы создаем новую переменную `counterTwo`, и присваиваем ей `counterOne`. Поскольку объекты передаются по ссылке, мы просто создаем новую ссылку на то же место в памяти, на которое указывает `counterOne`. Поскольку переменные ссылаются на то же место в памяти, любые изменения, внесенные в объект, на который ссылается `counterTwo`, также применяются к` counterOne`. Теперь `counterTwo.count` равно `2`. + +Мы вызываем `counterTwo.increment()`, что устанавливает значение `count` равное `3`. Затем мы выводим в консоль значение переменной `counterOne`, которое равно `3`. + + + +

+
+ From fbcbf3fcd0e9171de1606fbb63f6e0b7bc1da2fd Mon Sep 17 00:00:00 2001 From: Andrew I Date: Wed, 30 Sep 2020 21:25:51 +0600 Subject: [PATCH 654/915] fix promise.resolve status(104 question) --- README.md | 4 ++-- de-DE/README.md | 4 ++-- en-EN/README.md | 4 ++-- es-ES/README-ES.md | 4 ++-- id-ID/README.md | 4 ++-- ko-KR/README-ko_KR.md | 4 ++-- nl-NL/README.md | 4 ++-- ru-RU/README.md | 4 ++-- th-TH/README.md | 4 ++-- vi-VI/README-vi.md | 2 +- zh-CN/README-zh_CN.md | 4 ++-- 11 files changed, 21 insertions(+), 21 deletions(-) diff --git a/README.md b/README.md index 4be13a73..e9ea8de1 100644 --- a/README.md +++ b/README.md @@ -3331,7 +3331,7 @@ Promise.resolve(5); - A: `5` - B: `Promise {: 5}` -- C: `Promise {: 5}` +- C: `Promise {: 5}` - D: `Error`
Answer @@ -3339,7 +3339,7 @@ Promise.resolve(5); #### Answer: 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. +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`. diff --git a/de-DE/README.md b/de-DE/README.md index a7dc257d..71b5401d 100644 --- a/de-DE/README.md +++ b/de-DE/README.md @@ -3317,7 +3317,7 @@ Promise.resolve(5) - A: `5` - B: `Promise {: 5}` -- C: `Promise {: 5}` +- C: `Promise {: 5}` - D: `Error`
Antwort @@ -3325,7 +3325,7 @@ Promise.resolve(5) #### Antwort: C -Wir können jeden Wert an `Promise.resolve` übergeben, es muss nicht unbedingt ein Promise sein. Die Methode selbst gibt ein Promise zurück, was einen Wert ausgibt. Wenn man eine normale Funktion übergibt wird das Promise einen normalen Wert ausgeben. Wenn ein Promise übergeben wird so wird ein Promise gelöst und der Wert des gelösten Promises ausgegeben. +Wir können jeden Wert an `Promise.resolve` übergeben, es muss nicht unbedingt ein Promise sein. Die Methode selbst gibt ein Promise zurück, was einen Wert ausgibt (``). Wenn man eine normale Funktion übergibt wird das Promise einen normalen Wert ausgeben. Wenn ein Promise übergeben wird so wird ein Promise gelöst und der Wert des gelösten Promises ausgegeben. In diesem Fall haben wir nur die Zahl `5` übergeben und diese wird genauso ausgegeben: `5`. diff --git a/en-EN/README.md b/en-EN/README.md index 3db2b3b3..613e4a1a 100644 --- a/en-EN/README.md +++ b/en-EN/README.md @@ -3326,7 +3326,7 @@ Promise.resolve(5); - A: `5` - B: `Promise {: 5}` -- C: `Promise {: 5}` +- C: `Promise {: 5}` - D: `Error`
Answer @@ -3334,7 +3334,7 @@ Promise.resolve(5); #### Answer: 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. +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`. diff --git a/es-ES/README-ES.md b/es-ES/README-ES.md index 290efbd1..44f54b0b 100644 --- a/es-ES/README-ES.md +++ b/es-ES/README-ES.md @@ -3318,7 +3318,7 @@ Promise.resolve(5) - A: `5` - B: `Promise {: 5}` -- C: `Promise {: 5}` +- C: `Promise {: 5}` - D: `Error`
Solución @@ -3326,7 +3326,7 @@ Promise.resolve(5) #### Answer: C -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. +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`. diff --git a/id-ID/README.md b/id-ID/README.md index 20234347..a4c6aaaa 100644 --- a/id-ID/README.md +++ b/id-ID/README.md @@ -3321,7 +3321,7 @@ Promise.resolve(5); - A: `5` - B: `Promise {: 5}` -- C: `Promise {: 5}` +- C: `Promise {: 5}` - D: `Error`
Jawaban @@ -3329,7 +3329,7 @@ Promise.resolve(5); #### Jawaban: 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. +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`. diff --git a/ko-KR/README-ko_KR.md b/ko-KR/README-ko_KR.md index a5c5c60f..526abb58 100644 --- a/ko-KR/README-ko_KR.md +++ b/ko-KR/README-ko_KR.md @@ -3318,7 +3318,7 @@ Promise.resolve(5) - A: `5` - B: `Promise {: 5}` -- C: `Promise {: 5}` +- C: `Promise {: 5}` - D: `Error`
정답 @@ -3326,7 +3326,7 @@ 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를 리턴해요. diff --git a/nl-NL/README.md b/nl-NL/README.md index 81cb88a7..3e2d36e3 100644 --- a/nl-NL/README.md +++ b/nl-NL/README.md @@ -3325,7 +3325,7 @@ Promise.resolve(5) - A: `5` - B: `Promise {: 5}` -- C: `Promise {: 5}` +- C: `Promise {: 5}` - D: `Error`
Antwoord @@ -3333,7 +3333,7 @@ Promise.resolve(5) #### Antwoord: C -We kunnen elk type of waarde meegeven aan `Promise.resolve`, zowel een promise als een niet-promise. De methode zelf retourneert een promise met een opgeloste waarde. Als je een reguliere functie meegeeft zal het een opgeloste promise zijn met een reguliere waarde. Als je een promise meegeeft zal het een opgeloste promise zijn met een opgeloste waarde, of de doorgegeven promise. +We kunnen elk type of waarde meegeven aan `Promise.resolve`, zowel een promise als een niet-promise. De methode zelf retourneert een promise met een opgeloste waarde (``). Als je een reguliere functie meegeeft zal het een opgeloste promise zijn met een reguliere waarde. Als je een promise meegeeft zal het een opgeloste promise zijn met een opgeloste waarde, of de doorgegeven promise. In dit geval geven we alleen de numerieke waarde `5` mee. Het geeft de opgeloste promise terug met de waarde `5`. diff --git a/ru-RU/README.md b/ru-RU/README.md index e80e67ab..9bcd1c6a 100644 --- a/ru-RU/README.md +++ b/ru-RU/README.md @@ -3316,7 +3316,7 @@ Promise.resolve(5) - A: `5` - B: `Promise {: 5}` -- C: `Promise {: 5}` +- C: `Promise {: 5}` - D: `Error`
Ответ @@ -3324,7 +3324,7 @@ Promise.resolve(5) #### Ответ: C -Мы можем передать любой тип значения, которое мы хотим, в `Promise.resolve`, либо обещание, либо не обещание. Сам метод возвращает обещание с разрешенным значением. Если вы передадите обычную функцию, это будет разрешенное обещание с обычным значением. Если вы передадите обещание, это будет разрешенное обещание с разрешенным значением этого пройденного обещания. +Мы можем передать любой тип значения, которое мы хотим, в `Promise.resolve`, либо обещание, либо не обещание. Сам метод возвращает обещание с разрешенным значением (``). Если вы передадите обычную функцию, это будет разрешенное обещание с обычным значением. Если вы передадите обещание, это будет разрешенное обещание с разрешенным значением этого пройденного обещания. В этом случае мы просто передали числовое значение `5`. Возвращается разрешенное обещание со значением `5`. diff --git a/th-TH/README.md b/th-TH/README.md index 0cfe2b62..90d27f7c 100644 --- a/th-TH/README.md +++ b/th-TH/README.md @@ -3323,7 +3323,7 @@ Promise.resolve(5) - A: `5` - B: `Promise {: 5}` -- C: `Promise {: 5}` +- C: `Promise {: 5}` - D: `Error`
คำตอบ @@ -3331,7 +3331,7 @@ Promise.resolve(5) #### คำตอบ: 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. +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`. diff --git a/vi-VI/README-vi.md b/vi-VI/README-vi.md index 1e163ffd..86824a2d 100644 --- a/vi-VI/README-vi.md +++ b/vi-VI/README-vi.md @@ -3313,7 +3313,7 @@ Promise.resolve(5) - A: `5` - B: `Promise {: 5}` -- C: `Promise {: 5}` +- C: `Promise {: 5}` - D: `Error`
Đáp án diff --git a/zh-CN/README-zh_CN.md b/zh-CN/README-zh_CN.md index 7af022ad..1d096e91 100644 --- a/zh-CN/README-zh_CN.md +++ b/zh-CN/README-zh_CN.md @@ -3324,7 +3324,7 @@ Promise.resolve(5) - A: `5` - B: `Promise {: 5}` -- C: `Promise {: 5}` +- C: `Promise {: 5}` - D: `Error`
答案 @@ -3332,7 +3332,7 @@ 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` From 09afd1c4daa38402cb6a7cda15da223a96669c72 Mon Sep 17 00:00:00 2001 From: Muhammad Fauzan <50759463+fauzan121002@users.noreply.github.com> Date: Thu, 1 Oct 2020 14:45:37 +0700 Subject: [PATCH 655/915] Fix id-ID translation Fix 145. translate --- id-ID/README.md | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/id-ID/README.md b/id-ID/README.md index 20234347..93cc8bf2 100644 --- a/id-ID/README.md +++ b/id-ID/README.md @@ -4717,7 +4717,7 @@ Deklarasi `const` pada dasarnya berarti tidak dapat _mengubah_ nilai dari variab --- -###### 145. What do we need to add to the `person` object to get `["Lydia Hallie", 21]` as the output of `[...person]`? +###### 145. Apa yang harus kita tambahkan ke objek `person` untuk mendapatkan `["Lydia Hallie", 21]` sebagai output dari `[...person]`? ```javascript const person = { @@ -4728,7 +4728,7 @@ const person = { [...person] // ["Lydia Hallie", 21] ``` -- A: Nothing, object are iterable by default +- A: Tidak ada, objek adalah iterable secara default - 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 }` @@ -4738,7 +4738,8 @@ const person = { #### Jawaban: 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)`. +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)`.

From 0e8bdba21fbda5205f0ff355b4aa3916dfd079f9 Mon Sep 17 00:00:00 2001 From: Hiskia Anggi Date: Thu, 1 Oct 2020 16:00:40 +0700 Subject: [PATCH 656/915] Fix id-ID translation --- id-ID/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/id-ID/README.md b/id-ID/README.md index dbc141a4..90ae7b75 100644 --- a/id-ID/README.md +++ b/id-ID/README.md @@ -4682,7 +4682,7 @@ const pet = new Flamingo(); #### Jawaban: 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. 🦢"`. +Kita membuat variabel `pet` yang merupakan turunan dari class `Flamingo`. Saat kita membuat turunan, `constructor` pada `Flamingo` dipanggil. Pertama, `"I'm pink. 🌸"` ditampilkan, setelah itu kita memanggil `super()`. `super()` memanggil konstruktor class induk, `Bird`. Constructor pada `Bird` dipanggil, dan menampilkan `"I'm a bird. 🦢"`.

From f60bfd757177c0ac49f9b73002109c2dde3bed50 Mon Sep 17 00:00:00 2001 From: Miftachul Arzak <72002866+miftachularzak@users.noreply.github.com> Date: Thu, 1 Oct 2020 16:24:58 +0700 Subject: [PATCH 657/915] update id-ID translation --- id-ID/README.md | 32 ++++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) diff --git a/id-ID/README.md b/id-ID/README.md index dbc141a4..b8fb1862 100644 --- a/id-ID/README.md +++ b/id-ID/README.md @@ -4743,3 +4743,35 @@ Objek tidak dapat diulang secara default. Sebuah iterable adalah sebuah iterable

+ +--- + +###### 146. Apa yang akan tampil? + +```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 + +
Answer +

+ +#### Answer: C + +Pernyataan `if` didalam perulangan `forEach` akan mengecek apakah nilai dari `num` benar atau salah. Sejak nilai pertama dari array `nums` adalah `0`, yang merupakan nilai salah, pernyataan `if` tidak akan dieksekusi. maka `count` yang mendapat increment hanya untuk 3 nomor yang lain di array `nums`, `1`, `2` dan `3`. sejak `count` mendapat increment `1` 3 kali, maka nilai dari `count` adalah `3`. + +

+
+ +--- From 8f1edefb0c290804d627142c002aaad334a03105 Mon Sep 17 00:00:00 2001 From: Tryo Asnafi Date: Thu, 1 Oct 2020 16:55:07 +0700 Subject: [PATCH 658/915] fix numbering from 145 to 155 on en-EN README.md --- en-EN/README.md | 22 +++++++++++----------- 1 file changed, 11 insertions(+), 11 deletions(-) diff --git a/en-EN/README.md b/en-EN/README.md index 613e4a1a..48c9920f 100644 --- a/en-EN/README.md +++ b/en-EN/README.md @@ -4718,7 +4718,7 @@ Objects aren't iterable by default. An iterable is an iterable if the iterator p ----- -###### 146. What's the output? +###### 145. What's the output? ```javascript let count = 0; @@ -4748,7 +4748,7 @@ The `if` condition within the `forEach` loop checks whether the value of `num` i --- -###### 147. What's the output? +###### 146. What's the output? ```javascript function getFruit(fruits) { @@ -4783,7 +4783,7 @@ Lastly, we're trying to log the second item in the `['🍊', '🍌']` subarray o --- -###### 148. What's the output? +###### 147. What's the output? ```javascript class Calc { @@ -4819,7 +4819,7 @@ We set the variable `calc` equal to a new instance of the `Calc` class. Then, we --- -###### 149. What's the output? +###### 148. What's the output? ```javascript const user = { @@ -4861,7 +4861,7 @@ The `updateUser` function updates the values of the `email` and `password` prope --- -###### 150. What's the output? +###### 149. What's the output? ```javascript const fruit = ['🍌', '🍊', '🍎'] @@ -4890,7 +4890,7 @@ At last, we invoke the `unshift` method on the `fruit` array, which modifies the --- -###### 151. What's the output? +###### 115. What's the output? ```javascript const animals = {}; @@ -4926,7 +4926,7 @@ Logging `animals[dog]`, or actually `animals["object Object"]` since converting --- -###### 152. What's the output? +###### 151. What's the output? ```javascript const user = { @@ -4957,7 +4957,7 @@ The `updateEmail` function is an arrow function, and is not bound to the `user` --- -###### 153. What's the output? +###### 152. What's the output? ```javascript const promise1 = Promise.resolve('First') @@ -4993,7 +4993,7 @@ The `Promise.all` method runs the passed promises in parallel. If one promise fa --- -###### 154. 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"] @@ -5024,7 +5024,7 @@ This creates an array of subarrays containing the correct keys and values, which --- -###### 155. What's the output? +###### 154. What's the output? ```javascript const createMember = ({ email, address = {}}) => { @@ -5058,7 +5058,7 @@ The default value of `address` is an empty object `{}`. When we set the variable --- -###### 156. What's the output? +###### 155. What's the output? ```javascript let randomValue = { name: "Lydia" } From 0da2a647d9367786caa4375ac35587450ee354be Mon Sep 17 00:00:00 2001 From: Ahmad Alfarizki <54702541+AhmdFarzki@users.noreply.github.com> Date: Thu, 1 Oct 2020 16:55:48 +0700 Subject: [PATCH 659/915] Update README.md --- id-ID/README.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/id-ID/README.md b/id-ID/README.md index dbc141a4..b63dbb8c 100644 --- a/id-ID/README.md +++ b/id-ID/README.md @@ -125,11 +125,11 @@ console.log(shape.perimeter()); #### Jawaban: B -Note that the value of `diameter` is a regular function, whereas the value of `perimeter` is an arrow function. +Perhatikan pada nilai 'diameter' adalah fungsi biasa, sedangkan nilai 'perimeter' yaitu fungsi panah. -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). +Dengan fungsi panah, kata kunci 'this' merujuk ke cakupan sekitarnya saat ini, tidak seperti fungsi biasa. Ini berarti bahwa ketika kita memanggil 'perimeter' itu tidak mengacu pada objek bentuk, tetapi pada lingkup sekitarnya. -There is no value `radius` on that object, which returns `undefined`. +Tidak ada nilai 'radius' pada objek itu, yang mengembalikan 'tidak ditentukan'.

From 6647a79814385ea0e60c5ebb0485dd3ea2356ae3 Mon Sep 17 00:00:00 2001 From: Ramli Pathurahman <62465764+Rifars@users.noreply.github.com> Date: Thu, 1 Oct 2020 10:24:10 +0000 Subject: [PATCH 660/915] Update README.md --- id-ID/README.md | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/id-ID/README.md b/id-ID/README.md index dbc141a4..d0a82577 100644 --- a/id-ID/README.md +++ b/id-ID/README.md @@ -91,10 +91,9 @@ for (let i = 0; i < 3; i++) { #### Jawaban: C -Because of the event queue in JavaScript, the `setTimeout` callback function is called _after_ the loop has been executed. Since the variable `i` in the first loop was declared using the `var` keyword, this value was global. During the loop, we incremented the value of `i` by `1` each time, using the unary operator `++`. By the time the `setTimeout` callback function was invoked, `i` was equal to `3` in the first example. - -In the second loop, the variable `i` was declared using the `let` keyword: variables declared with the `let` (and `const`) keyword are block-scoped (a block is anything between `{ }`). During each iteration, `i` will have a new value, and each value is scoped inside the loop. +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.

From 5910364b903e298660ac7f811b445f797ae70e71 Mon Sep 17 00:00:00 2001 From: Tryo Asnafi <61939827+tryoasnafi@users.noreply.github.com> Date: Thu, 1 Oct 2020 18:20:39 +0700 Subject: [PATCH 661/915] fix typo 150 --- en-EN/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/en-EN/README.md b/en-EN/README.md index 48c9920f..4ba3fe7f 100644 --- a/en-EN/README.md +++ b/en-EN/README.md @@ -4890,7 +4890,7 @@ At last, we invoke the `unshift` method on the `fruit` array, which modifies the --- -###### 115. What's the output? +###### 150. What's the output? ```javascript const animals = {}; From 360d9e70b781a62280141a7509f551a907f74edf Mon Sep 17 00:00:00 2001 From: ibnusyawall Date: Thu, 1 Oct 2020 18:37:56 +0700 Subject: [PATCH 662/915] Translation of question 9-10 --- id-ID/README.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/id-ID/README.md b/id-ID/README.md index b4680926..508898fa 100644 --- a/id-ID/README.md +++ b/id-ID/README.md @@ -316,9 +316,9 @@ console.log(greetign); #### Jawaban: 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). +Ini mencatat objek, karena kita baru saja membuat objek kosong di objek global! Saat kita salah mengetik `greeting` sebagai` greetign`, interpreter JS sebenarnya melihat ini sebagai `global.greetign = {}` (atau `window.greetign = {}` di browser). -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. +Untuk menghindari hal ini, kita bisa menggunakan `" use strict "`. Ini memastikan bahwa Anda telah mendeklarasikan variabel sebelum menetapkannya dengan apa pun.

@@ -345,9 +345,9 @@ bark.animal = 'dog'; #### Jawaban: A -This is possible in JavaScript, because functions are objects! (Everything besides primitive types are objects) +Ini dimungkinkan dalam JavaScript, karena fungsi adalah objek! (Segala sesuatu selain tipe primitif adalah objek) -A function is a special type of object. The code you write yourself isn't the actual function. The function is an object with properties. This property is invocable. +Fungsi adalah jenis objek khusus. Kode yang Anda tulis sendiri bukanlah fungsi sebenarnya. Fungsinya adalah objek dengan properti. Properti ini tidak dapat dipanggil.

From 20f3218b767e9438da132502eec87b6cd28a9f00 Mon Sep 17 00:00:00 2001 From: sharath3001 <52591235+sharath3001@users.noreply.github.com> Date: Thu, 1 Oct 2020 17:14:28 +0530 Subject: [PATCH 663/915] Fixed numbering in en-EN\README.md Fixed numbering from 145 to 155 and added one missing line from main README.md to en-EN\README.md in question 149 --- en-EN/README.md | 24 +++++++++++++----------- 1 file changed, 13 insertions(+), 11 deletions(-) diff --git a/en-EN/README.md b/en-EN/README.md index 613e4a1a..8d8bf005 100644 --- a/en-EN/README.md +++ b/en-EN/README.md @@ -4718,7 +4718,7 @@ Objects aren't iterable by default. An iterable is an iterable if the iterator p ----- -###### 146. What's the output? +###### 145. What's the output? ```javascript let count = 0; @@ -4748,7 +4748,7 @@ The `if` condition within the `forEach` loop checks whether the value of `num` i --- -###### 147. What's the output? +###### 146. What's the output? ```javascript function getFruit(fruits) { @@ -4783,7 +4783,7 @@ Lastly, we're trying to log the second item in the `['🍊', '🍌']` subarray o --- -###### 148. What's the output? +###### 147. What's the output? ```javascript class Calc { @@ -4819,7 +4819,7 @@ We set the variable `calc` equal to a new instance of the `Calc` class. Then, we --- -###### 149. What's the output? +###### 148. What's the output? ```javascript const user = { @@ -4861,7 +4861,7 @@ The `updateUser` function updates the values of the `email` and `password` prope --- -###### 150. What's the output? +###### 149. What's the output? ```javascript const fruit = ['🍌', '🍊', '🍎'] @@ -4869,6 +4869,8 @@ const fruit = ['🍌', '🍊', '🍎'] fruit.slice(0, 1) fruit.splice(0, 1) fruit.unshift('🍇') + +console.log(fruit) ``` - A: `['🍌', '🍊', '🍎']` @@ -4890,7 +4892,7 @@ At last, we invoke the `unshift` method on the `fruit` array, which modifies the --- -###### 151. What's the output? +###### 150. What's the output? ```javascript const animals = {}; @@ -4926,7 +4928,7 @@ Logging `animals[dog]`, or actually `animals["object Object"]` since converting --- -###### 152. What's the output? +###### 151. What's the output? ```javascript const user = { @@ -4957,7 +4959,7 @@ The `updateEmail` function is an arrow function, and is not bound to the `user` --- -###### 153. What's the output? +###### 152. What's the output? ```javascript const promise1 = Promise.resolve('First') @@ -4993,7 +4995,7 @@ The `Promise.all` method runs the passed promises in parallel. If one promise fa --- -###### 154. 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"] @@ -5024,7 +5026,7 @@ This creates an array of subarrays containing the correct keys and values, which --- -###### 155. What's the output? +###### 154. What's the output? ```javascript const createMember = ({ email, address = {}}) => { @@ -5058,7 +5060,7 @@ The default value of `address` is an empty object `{}`. When we set the variable --- -###### 156. What's the output? +###### 155. What's the output? ```javascript let randomValue = { name: "Lydia" } From 6ae0f351a46a76564af6ffc651088ddef02f0877 Mon Sep 17 00:00:00 2001 From: Hiskia Anggi Date: Thu, 1 Oct 2020 19:27:40 +0700 Subject: [PATCH 664/915] Fix id-ID translation --- 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 90ae7b75..7cf23480 100644 --- a/id-ID/README.md +++ b/id-ID/README.md @@ -152,9 +152,9 @@ There is no value `radius` on that object, which returns `undefined`. #### Jawaban: A -The unary plus tries to convert an operand to a number. `true` is `1`, and `false` is `0`. +Operasi unary plus (+) mencoba mengonversi operan menjadi angka. `true` adalah `1`, and `false` adalah `0`. -The string `'Lydia'` is a truthy value. What we're actually asking, is "is this truthy value falsy?". This returns `false`. +String `'Lydia'` adalah nilai yang benar. Apa yang sebenarnya kita tanyakan adalah "apakah nilai kebenaran ini false?". Ini `false`.

From c6eb15e4b68e9fbc9e869010fdced50c9f488305 Mon Sep 17 00:00:00 2001 From: Naufal Hanif <66030265+nahansans@users.noreply.github.com> Date: Thu, 1 Oct 2020 19:45:16 +0700 Subject: [PATCH 665/915] 147 - 151 --- id-ID/README.md | 181 ++++++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 177 insertions(+), 4 deletions(-) diff --git a/id-ID/README.md b/id-ID/README.md index 8561d6f5..03f702f8 100644 --- a/id-ID/README.md +++ b/id-ID/README.md @@ -151,9 +151,9 @@ Tidak ada nilai 'radius' pada objek itu, yang mengembalikan 'tidak ditentukan'. #### Jawaban: A -Operasi unary plus (+) mencoba mengonversi operan menjadi angka. `true` adalah `1`, and `false` adalah `0`. +The unary plus tries to convert an operand to a number. `true` is `1`, and `false` is `0`. -String `'Lydia'` adalah nilai yang benar. Apa yang sebenarnya kita tanyakan adalah "apakah nilai kebenaran ini false?". Ini `false`. +The string `'Lydia'` is a truthy value. What we're actually asking, is "is this truthy value falsy?". This returns `false`.

@@ -4763,10 +4763,10 @@ console.log(count) - C: 3 - D: 4 -
Answer +
Jawaban

-#### Answer: C +#### Jawaban: C Pernyataan `if` didalam perulangan `forEach` akan mengecek apakah nilai dari `num` benar atau salah. Sejak nilai pertama dari array `nums` adalah `0`, yang merupakan nilai salah, pernyataan `if` tidak akan dieksekusi. maka `count` yang mendapat increment hanya untuk 3 nomor yang lain di array `nums`, `1`, `2` dan `3`. sejak `count` mendapat increment `1` 3 kali, maka nilai dari `count` adalah `3`. @@ -4774,3 +4774,176 @@ Pernyataan `if` didalam perulangan `forEach` akan mengecek apakah nilai dari `nu

--- + +###### 147. Apa hasilnya? + +```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` + +
Jawaban +

+ +#### Jawaban: A + +Kami mengatur variabel `calc` sama dengan instance baru dari class `Calc`. Kemudian, kami membuat instance baru dari `Calc`, dan memanggil metode `increase` pada contoh ini. Karena properti count berada dalam konstruktor dari class `Calc`, properti count tidak dibagikan pada prototipe `Calc`. Ini berarti bahwa nilai hitungan belum diperbarui untuk contoh yang ditunjukkan kalk, hitung masih `0`. + +

+
+ +--- + +###### 148. Apa hasilnya? + +```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` + +
Jawaban +

+ +#### Jawaban: B + +Fungsi `updateUser` memperbarui nilai properti `email` dan `password` pada pengguna, jika nilainya diteruskan ke fungsi, setelah itu fungsi mengembalikan objek `user`. Nilai yang dikembalikan dari fungsi `updateUser` adalah objek `user`, yang berarti bahwa nilai updatedUser adalah referensi ke objek `user` yang sama dengan yang ditunjuk oleh `user`. `updatedUser === user` sama dengan `true`. + +

+
+ +--- + +###### 149. Apa hasilnya? +```javascript +const fruit = ['🍌', '🍊', '🍎'] + +fruit.slice(0, 1) +fruit.splice(0, 1) +fruit.unshift('🍇') +``` + +- A: `['🍌', '🍊', '🍎']` +- B: `['🍊', '🍎']` +- C: `['🍇', '🍊', '🍎']` +- D: `['🍇', '🍌', '🍊', '🍎']` + +
Jawaban +

+ +#### Jawaban: C + +Pertama, kita memanggil metode `slice` pada array fruit. Metode slice tidak mengubah array asli, tetapi mengembalikan nilai yang dipotongnya dari array: banana emoji. +Kemudian, kita memanggil metode `splice` pada array fruit. Metode splice memang mengubah array asli, yang berarti array fruit sekarang terdiri dari `['🍊', '🍎']`. +Akhirnya, kita memanggil metode `unshift` pada array `fruit`, yang memodifikasi array asli dengan menambahkan nilai yang diberikan, ‘🍇’ dalam hal ini, sebagai elemen pertama dalam array. Susunan fruit sekarang terdiri dari `['🍇', '🍊', '🍎']`. + +

+
+ +--- + +###### 150. Apa hasilnya? + +```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` + +
Jawaban +

+ +#### Jawaban: B + +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"}`. + +`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"}`. + +

+
+ +--- + +###### 151. Apa hasilnya? + +```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` + +
Jawaban +

+ +#### Jawaban: A + +Fungsi `updateEmail` adalah fungsi panah, dan tidak terikat ke objek `user`. Artinya, kata kunci `this` tidak merujuk ke objek `user`, tetapi merujuk pada cakupan global dalam kasus ini. Nilai `email` dalam objek `user` tidak diperbarui. Saat memasukkan nilai `user.email`, nilai asli `my@email.com` akan dikembalikan. +

+
+ +--- + From bb3707e8152c2c1780c6bc4bdbb01ab9d2487bfc Mon Sep 17 00:00:00 2001 From: Muhammad Nazir Azhari <71949980+nazaraito@users.noreply.github.com> Date: Thu, 1 Oct 2020 19:50:55 +0700 Subject: [PATCH 666/915] translate the discussion of questions 35, 36 --- id-ID/README.md | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/id-ID/README.md b/id-ID/README.md index 508898fa..892dbf63 100644 --- a/id-ID/README.md +++ b/id-ID/README.md @@ -1084,16 +1084,16 @@ undefined; #### Jawaban: A -There are only six falsy values: +Hanya ada enam nilai yang salah: - `undefined` - `null` - `NaN` - `0` -- `''` (empty string) +- `''` (string kosong) - `false` -Function constructors, like `new Number` and `new Boolean` are truthy. +Konstruktor fungsi, seperti Number baru dan Boolean baru, benar.

@@ -1142,11 +1142,11 @@ console.log(numbers); #### Jawaban: 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: +Saat Anda menyetel nilai ke elemen dalam larik yang melebihi panjang larik, JavaScript membuat sesuatu yang disebut "slot kosong". Ini sebenarnya memiliki nilai `tidak terdefinisi`, tetapi Anda akan melihat sesuatu seperti: `[1, 2, 3, 7 x empty, 11]` -depending on where you run it (it's different for every browser, node, etc.) +tergantung di mana Anda menjalankannya (berbeda untuk setiap browser, node, dll.)

From 87cff1357ac4b533823c1761523a2307111ea6b5 Mon Sep 17 00:00:00 2001 From: Naufal Hanif <66030265+nahansans@users.noreply.github.com> Date: Thu, 1 Oct 2020 20:04:57 +0700 Subject: [PATCH 667/915] fix typo in question 152 EN --- en-EN/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/en-EN/README.md b/en-EN/README.md index 4ba3fe7f..344af9ec 100644 --- a/en-EN/README.md +++ b/en-EN/README.md @@ -4986,7 +4986,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 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.

From 9d1f4eb9eef48e317d07ca6d765f35cbf9deb681 Mon Sep 17 00:00:00 2001 From: Naufal Hanif <66030265+nahansans@users.noreply.github.com> Date: Thu, 1 Oct 2020 20:14:16 +0700 Subject: [PATCH 668/915] 64 --- fr-FR/README_fr-FR.md | 40 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 40 insertions(+) diff --git a/fr-FR/README_fr-FR.md b/fr-FR/README_fr-FR.md index 8ff2122d..681b4b68 100644 --- a/fr-FR/README_fr-FR.md +++ b/fr-FR/README_fr-FR.md @@ -1963,3 +1963,43 @@ L'opérateur arithmétique `++` _renvoie en premier_ la valeur de l'opérande, _

+ +--- + +###### 64. Quelle est la sortie? + +```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épondre +

+ +#### Répondre: C + +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`. + +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`. + +La quatrième fois, nous passons à nouveau l'objet `value`. `x.number` a été précédemment modifié en `20`, donc `x.number * = 2` enregistre «40». + +

+
+ +--- From b22f0d6bc4dafe63fb03c2f347a242e9f65c6a96 Mon Sep 17 00:00:00 2001 From: Munawir <46591537+Munawir712@users.noreply.github.com> Date: Thu, 1 Oct 2020 20:24:31 +0700 Subject: [PATCH 669/915] Menambah yang belum di terjemah --- id-ID/README.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/id-ID/README.md b/id-ID/README.md index 8561d6f5..81d2d4db 100644 --- a/id-ID/README.md +++ b/id-ID/README.md @@ -160,7 +160,7 @@ String `'Lydia'` adalah nilai yang benar. Apa yang sebenarnya kita tanyakan adal --- -###### 5. Which one is true? +###### 5. Mana yang benar? ```javascript const bird = { @@ -325,7 +325,7 @@ Untuk menghindari hal ini, kita bisa menggunakan `" use strict "`. Ini memastika --- -###### 10. What happens when we do this? +###### 10. Apa yang terjadi jika kita melakukan ini? ```javascript function bark() { @@ -450,7 +450,7 @@ During the **capturing** phase, the event goes through the ancestor elements dow --- -###### 14. All object have prototypes. +###### 14. Semua objek memiliki prototypes. - A: true - B: false From 7cc8c614ea6e43f8778b4201c59ffbe4382571ec Mon Sep 17 00:00:00 2001 From: Andika Tulus Pangestu <62005221+andikatuluspangestu@users.noreply.github.com> Date: Thu, 1 Oct 2020 20:48:30 +0700 Subject: [PATCH 670/915] Update README.md --- 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 24bb2ae9..cb980f90 100644 --- a/id-ID/README.md +++ b/id-ID/README.md @@ -1288,7 +1288,7 @@ setInterval(() => console.log('Hi'), 1000); #### Jawaban: A -It returns a unique id. This id can be used to clear that interval with the `clearInterval()` function. +Itu adalah mengembalikan sebuah id unik. id unik dapat digunakan untuk menghapus interval dengan menggunakan fungsi clearInterval()

@@ -1311,7 +1311,7 @@ It returns a unique id. This id can be used to clear that interval with the `cle #### Jawaban: A -A string is an iterable. The spread operator maps every character of an iterable to one element. +Sebuah string adalah iterable. Operator memetakan setiap karakter dari sebuah iterable ke dalam satu elemen.

From 82fe1e8241c9f5e3a1950e532d4aee3b3db4ba1c Mon Sep 17 00:00:00 2001 From: Munawir <46591537+Munawir712@users.noreply.github.com> Date: Thu, 1 Oct 2020 21:35:22 +0700 Subject: [PATCH 671/915] add translate --- id-ID/README.md | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/id-ID/README.md b/id-ID/README.md index 81d2d4db..5b48f8d4 100644 --- a/id-ID/README.md +++ b/id-ID/README.md @@ -218,13 +218,13 @@ console.log(d.greeting); #### Jawaban: A -In JavaScript, all objects interact by _reference_ when setting them equal to each other. +Dalam JavaScript, semua objek berinteraksi dengan _referensi_ saat menyetelnya agar sama satu sama lain. -First, variable `c` holds a value to an object. Later, we assign `d` with the same reference that `c` has to the object. +Pertama, variabel `c` memiliki nilai untuk sebuah objek. Kemudian, kami menetapkan `d` dengan referensi yang sama yang dimiliki `c` ke objek. -When you change one object, you change all of them. +Saat Anda mengubah satu objek, Anda mengubah semuanya.

@@ -380,7 +380,7 @@ console.log(member.getFullName()); #### Jawaban: A -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, +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() { @@ -388,7 +388,7 @@ Person.prototype.getFullName = function() { }; ``` -would have made `member.getFullName()` work. Why is this beneficial? Say that we added this method to the constructor itself. Maybe not every `Person` instance needed this method. This would waste a lot of memory space, since they would still have that property, which takes of memory space for each instance. Instead, if we only add it to the prototype, we just have it at one spot in memory, yet they all have access to it! +akan membuat `member.getFullName()` berfungsi. Mengapa ini bermanfaat? Katakanlah kita menambahkan metode ini ke konstruktor itu sendiri. Mungkin tidak setiap instance `Person` membutuhkan metode ini. Ini akan membuang banyak ruang memori, karena mereka masih memiliki properti itu, yang mengambil ruang memori untuk setiap instance. Sebaliknya, jika kita hanya menambahkannya ke prototipe, kita hanya memilikinya di satu tempat di memori, namun mereka semua memiliki akses ke sana!

From 0bbd59410f5e8edc12ece4583571835e44292310 Mon Sep 17 00:00:00 2001 From: zainul arifin Date: Fri, 2 Oct 2020 00:16:53 +0700 Subject: [PATCH 672/915] translate indonesia --- 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 cb980f90..8fbf277d 100644 --- a/id-ID/README.md +++ b/id-ID/README.md @@ -151,9 +151,9 @@ Tidak ada nilai 'radius' pada objek itu, yang mengembalikan 'tidak ditentukan'. #### Jawaban: A -The unary plus tries to convert an operand to a number. `true` is `1`, and `false` is `0`. +Unary plus mencoba mengonversi operan menjadi angka. `benar` adalah `1`, dan `salah` adalah `0`. -The string `'Lydia'` is a truthy value. What we're actually asking, is "is this truthy value falsy?". This returns `false`. +stringnya `'Lydia'` adalah nilai kebenaran. Apa yang sebenarnya kami tanyakan adalah "apakah nilai kebenaran ini salah?". pengembalian ini `salah`.

From 5c02d658be0fa7d68668ab1f3aa8c6a432148a7a Mon Sep 17 00:00:00 2001 From: Ramli Pathurahman <62465764+Rifars@users.noreply.github.com> Date: Fri, 2 Oct 2020 06:40:28 +0700 Subject: [PATCH 673/915] translate English into Indonesian translating answer no 4,5,6,7 --- id-ID/README.md | 27 +++++++++++++-------------- 1 file changed, 13 insertions(+), 14 deletions(-) diff --git a/id-ID/README.md b/id-ID/README.md index cb980f90..0a01a718 100644 --- a/id-ID/README.md +++ b/id-ID/README.md @@ -151,9 +151,9 @@ Tidak ada nilai 'radius' pada objek itu, yang mengembalikan 'tidak ditentukan'. #### Jawaban: A -The unary plus tries to convert an operand to a number. `true` is `1`, and `false` is `0`. +Tia unary plus mencoba mengonversi operan menjadi angka. `true` adalah` 1`, dan `false` adalah` 0`. -The string `'Lydia'` is a truthy value. What we're actually asking, is "is this truthy value falsy?". This returns `false`. +String "'Lydia'` adalah nilai yang benar. Apa yang sebenarnya kami tanyakan adalah "apakah nilai kebenaran ini salah?". Ini mengembalikan `salah`.

@@ -183,13 +183,13 @@ const mouse = { #### Jawaban: A -In JavaScript, all object keys are strings (unless it's a Symbol). Even though we might not _type_ them as strings, they are always converted into strings under the hood. +Dalam JavaScript, semua kunci objek adalah string (kecuali jika itu Simbol). Meskipun kita mungkin tidak _type_ mereka sebagai string, mereka selalu diubah menjadi string di bawah tenda. -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. +JavaScript menginterpretasikan (atau membuka kotak) pernyataan. Saat kita menggunakan notasi kurung siku, ia melihat kurung buka pertama `[` dan terus berjalan sampai menemukan kurung tutup `]`. Baru setelah itu, itu akan mengevaluasi pernyataan itu. -`mouse[bird.size]`: First it evaluates `bird.size`, which is `"small"`. `mouse["small"]` returns `true` +`mouse [bird.size]`: Pertama, ia mengevaluasi `bird.size`, yang mana` "small" `. `mouse [" small "]` mengembalikan `true` -However, with dot notation, this doesn't happen. `mouse` does not have a key called `bird`, which means that `mouse.bird` is `undefined`. Then, we ask for the `size` using dot notation: `mouse.bird.size`. Since `mouse.bird` is `undefined`, we're actually asking `undefined.size`. This isn't valid, and will throw an error similar to `Cannot read property "size" of undefined`. +Namun, dengan notasi titik, hal ini tidak terjadi. `mouse` tidak memiliki kunci bernama` bird`, yang berarti `mouse.bird` adalah` undefined`. Kemudian, kami meminta `ukuran` menggunakan notasi titik:` mouse.bird.size`. Karena `mouse.bird` adalah ʻundefined`, kami sebenarnya menanyakan ʻundefined.size`. Ini tidak valid, dan akan memunculkan kesalahan yang mirip dengan `Tidak dapat membaca properti" ukuran "dari tidak ditentukan`.

@@ -218,13 +218,13 @@ console.log(d.greeting); #### Jawaban: A -In JavaScript, all objects interact by _reference_ when setting them equal to each other. +Dalam JavaScript, semua objek berinteraksi dengan _reference_ saat menyetelnya agar sama satu sama lain. -First, variable `c` holds a value to an object. Later, we assign `d` with the same reference that `c` has to the object. +Pertama, variabel `c` menyimpan nilai ke sebuah objek. Nanti, kita menetapkan `d` dengan referensi yang sama yang dimiliki` c` ke objek. -When you change one object, you change all of them. +Saat Anda mengubah satu objek, Anda mengubah semuanya.

@@ -253,12 +253,11 @@ console.log(b === c); #### Jawaban: 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. +`new Number ()` adalah konstruktor fungsi bawaan. Meskipun terlihat seperti angka, sebenarnya ini bukan angka: ia memiliki banyak fitur tambahan dan merupakan objek. -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`. - -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.` +Saat kita menggunakan operator `==`, ini hanya memeriksa apakah ia memiliki _value_ yang sama. Keduanya memiliki nilai `3`, sehingga mengembalikan` true`. +Namun, saat kita menggunakan operator `===`, kedua nilai _and_ type harus sama. Ini bukan: `new Number ()` bukan angka, ini adalah ** objek **. Keduanya mengembalikan `false.`

@@ -292,7 +291,7 @@ console.log(freddie.colorChange('orange')); #### Jawaban: 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. +Fungsi `colorChange` bersifat statis. Metode statis dirancang untuk hidup hanya pada konstruktor tempat mereka dibuat, dan tidak dapat diturunkan ke turunan mana pun. Karena `freddie` adalah anak, fungsinya tidak diturunkan, dan tidak tersedia pada instance` freddie`: `TypeError` dilempar.

From 2c66d6175590e42b84d56294113efa43243a0409 Mon Sep 17 00:00:00 2001 From: MAKSS <32557358+SMAKSS@users.noreply.github.com> Date: Fri, 2 Oct 2020 04:31:25 +0330 Subject: [PATCH 674/915] Typo in answer to question 152, got fixed. --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index e9ea8de1..591e0cb4 100644 --- a/README.md +++ b/README.md @@ -4993,7 +4993,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` 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.

From 1ec3c22b6f41bf5c120068a21a496d8b33065318 Mon Sep 17 00:00:00 2001 From: Naufal Hanif <66030265+nahansans@users.noreply.github.com> Date: Fri, 2 Oct 2020 08:22:38 +0700 Subject: [PATCH 675/915] 152 - 153 --- id-ID/README.md | 66 +++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 66 insertions(+) diff --git a/id-ID/README.md b/id-ID/README.md index cb980f90..f811267b 100644 --- a/id-ID/README.md +++ b/id-ID/README.md @@ -4947,3 +4947,69 @@ 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 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'` + +
Jawaban +

+ +#### Jawaban: D + +Metode `Promise.all` menjalankan promise yang diberikan secara paralel. Jika satu promise gagal, metode `Promise.all` dengan nilai promise yang ditolak. Dalam kasus ini, `promise3` ditolak dengan nilai `"Third"`. Kami menangkap nilai yang ditolak dalam metode `catch` yang dirantai pada pemanggilan `runPromises` untuk menangkap setiap kesalahan dalam fungsi `runPromises`. Hanya `"Third"` yang dicatat, karena `promise3` ditolak dengan nilai ini. + +

+
+ +--- + +###### 153.Berapa nilai `method` untuk mencatat `{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` + +
Jawaban +

+ +#### Jawaban: C + +Metode `fromEntries` mengubah array 2d menjadi objek. Elemen pertama di setiap subarray akan menjadi kuncinya, dan elemen kedua di setiap subarray akan menjadi nilainya. Dalam hal ini, kami memetakan di atas array `keys`, yang mengembalikan array yang elemen pertamanya adalah item pada array kunci pada indeks saat ini, dan elemen kedua adalah item dari array nilai pada indeks saat ini. + +Ini membuat array subarray yang berisi kunci dan nilai yang benar, yang menghasilkan `{name:" Lydia ", age: 22}` + +

+
+ +--- From abd4cd5f1991696cb82358ab6b142132cddd100b Mon Sep 17 00:00:00 2001 From: Irvan Ahmad Prasetya Date: Fri, 2 Oct 2020 10:23:02 +0700 Subject: [PATCH 676/915] translate question 154 English into Indonesian --- id-ID/README.md | 35 ++++++++++++++++++++++++++++++++++- 1 file changed, 34 insertions(+), 1 deletion(-) diff --git a/id-ID/README.md b/id-ID/README.md index cb980f90..73aca741 100644 --- a/id-ID/README.md +++ b/id-ID/README.md @@ -4780,7 +4780,7 @@ Pernyataan `if` didalam perulangan `forEach` akan mengecek apakah nilai dari `nu ```javascript class Calc { constructor() { - this.count = 0 + this.count = 0 } increase() { @@ -4947,3 +4947,36 @@ Fungsi `updateEmail` adalah fungsi panah, dan tidak terikat ke objek `user`. Art --- +###### 154. Apa hasilnya? + +```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 }` + +
Answer +

+ +#### Answer: C + +Nilai default dari `address` adalah sebuah objek kosong `{}`. Saat ketika mengatur variable `member` sama dengan objek yang dikembalikan oleh fungsi `createMember`, kita tidak mengirimkan nilai untuk address, yang berarti bahwa nilai address adalah objek default kosong `{}`. Objek kosong adalah nilai kebenaran, yang berarti kondisi dari `address ? address : null` mengembalikan `true`. Nilai address adalah objek kosong`{}`. + +

+
+ +--- From 006895ec160b84569358b43f5688aee0d13153bd Mon Sep 17 00:00:00 2001 From: Sami Kalammallah Date: Fri, 2 Oct 2020 10:47:19 +0700 Subject: [PATCH 677/915] enchanment and adding translations for 71, 107,108, and 141 --- id-ID/README.md | 21 ++++++++++----------- 1 file changed, 10 insertions(+), 11 deletions(-) diff --git a/id-ID/README.md b/id-ID/README.md index cb980f90..cfeb4cf9 100644 --- a/id-ID/README.md +++ b/id-ID/README.md @@ -91,7 +91,7 @@ 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.

@@ -2206,7 +2206,7 @@ With the `+` operator, you can concatenate strings. In this case, we are concate --- -###### 71. How can we log the values that are commented out after the console.log statement? +###### 71. Bagaimana cara mencatat nilai yang diberikan komentar pada perintah console.log? ```javascript function* startGame() { @@ -3413,7 +3413,7 @@ JavaScript interprets (or unboxes) statements. When we use bracket notation, it --- -###### 107. What's its value? +###### 107. Apakah hasil nilai dibawah ini ? ```javascript console.log('❤️' === '❤️'); @@ -3427,14 +3427,14 @@ console.log('❤️' === '❤️'); #### Jawaban: 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. +Di belakang layar, emoji adalah sebuah unicode. Unicode untuk emoji hati adalah `"U+2764 U+FE0F"`. Keduanya akan selalu sama untuk emoji yang sama, jadi sebetulnya kita telah membandingkan dua string yang sama satu sama lain, yang mana akan menghasilkan true.

--- -###### 108. Which of these methods modifies the original array? +###### 108. Manakah metode berikut yang akan memodifikasi array aslinya? ```javascript const emojis = ['✨', '🥑', '😍']; @@ -3457,9 +3457,9 @@ emojis.splice(1, 2, '✨'); #### Jawaban: 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. +Metode `splice`, akan memodifikasi array aslinya dengan cara menghapus, mengganti atau menambahkan elemen. Dalam kasus ini, kami menghapus 2 item dari indeks 1 (kami menghapus `'🥑'` dan`' 😍'`) dan menambahkan emoji ✨ sebagai penggantinya. -`map`, `filter` and `slice` return a new array, `find` returns an element, and `reduce` returns a reduced value. +`map`,` filter` dan `slice` akan mengembalikan array baru,` find` akan mengembalikan elemen yang dicari, dan `reduce` akan mengembalikan nilai yang telah dikurangi.

@@ -4598,9 +4598,9 @@ obj.next(); // { value: "Lisa", done: false } #### Jawaban: 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*`. +Untuk melakukan pengulangan pada `members` dalam setiap elemen array `tim`, kita perlu melemparkan `tim[i].members` ke fungsi generator `getMembers`. Fungsi generator akan mengembalikan objek hasil generator. Untuk mengulang setiap elemen dalam objek generator ini, kita perlu menggunakan `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. +Jika kita telah menulis `yield`, `return yield`, atau `return`, maka seluruh fungsi generator akan dikembalikan saat pertama kali kita memanggil metode `next`.

@@ -4780,7 +4780,7 @@ Pernyataan `if` didalam perulangan `forEach` akan mengecek apakah nilai dari `nu ```javascript class Calc { constructor() { - this.count = 0 + this.count = 0 } increase() { @@ -4946,4 +4946,3 @@ Fungsi `updateEmail` adalah fungsi panah, dan tidak terikat ke objek `user`. Art
--- - From 0704b8010348a4a826a743f952c15e9ba3a47d44 Mon Sep 17 00:00:00 2001 From: sharath3001 <52591235+sharath3001@users.noreply.github.com> Date: Fri, 2 Oct 2020 10:50:18 +0530 Subject: [PATCH 678/915] Removed an unwanted tag in que 153 of en_EN\README.md --- en-EN/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/en-EN/README.md b/en-EN/README.md index a8c0ede0..e243050b 100644 --- a/en-EN/README.md +++ b/en-EN/README.md @@ -4995,7 +4995,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"] From d5683f7807cac01d6cef00b66e241c30dbf2470a Mon Sep 17 00:00:00 2001 From: Sami Kalammallah Date: Fri, 2 Oct 2020 15:29:01 +0700 Subject: [PATCH 679/915] update latest and prettifier --- id-ID/README.md | 582 +++++++++++++++++++++++++++--------------------- 1 file changed, 327 insertions(+), 255 deletions(-) diff --git a/id-ID/README.md b/id-ID/README.md index cfeb4cf9..ed5b950f 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 @@ -45,7 +45,7 @@ Jangan sungkan untuk terhubung dengan saya! 😊
function sayHi() { console.log(name); console.log(age); - var name = 'Lydia'; + var name = "Lydia"; let age = 21; } @@ -65,6 +65,7 @@ sayHi(); 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` 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`. +

@@ -91,9 +92,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. +

@@ -139,7 +141,7 @@ Tidak ada nilai 'radius' pada objek itu, yang mengembalikan 'tidak ditentukan'. ```javascript +true; -!'Lydia'; +!"Lydia"; ``` - A: `1` and `false` @@ -164,11 +166,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, }; ``` @@ -199,11 +201,11 @@ However, with dot notation, this doesn't happen. `mouse` does not have a key cal ###### 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); ``` @@ -273,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` @@ -329,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! @@ -362,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}`; }; @@ -383,7 +385,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}`; }; ``` @@ -403,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); @@ -474,7 +476,7 @@ function sum(a, b) { return a + b; } -sum(1, '2'); +sum(1, "2"); ``` - A: `NaN` @@ -541,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`; @@ -568,9 +570,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`); } @@ -630,7 +632,7 @@ The rest parameter (`...args`.) lets us "collect" all remaining arguments into a ```javascript function getAge() { - 'use strict'; + "use strict"; age = 21; console.log(age); } @@ -658,7 +660,7 @@ With `"use strict"`, you can make sure that you don't accidentally declare globa ###### 21. What's value of `sum`? ```javascript -const sum = eval('10*10+5'); +const sum = eval("10*10+5"); ``` - A: `105` @@ -681,7 +683,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. @@ -734,12 +736,12 @@ You cannot do this with `let` or `const` since they're block-scoped. ###### 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); ``` @@ -765,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); ``` @@ -834,10 +836,10 @@ 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"; name.giveLydiaPizza(); ``` @@ -863,8 +865,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; @@ -896,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(); @@ -951,9 +953,7 @@ This is where an event loop starts to work. An **event loop** looks at the stack ```html
- +
``` @@ -979,9 +979,7 @@ The deepest nested element that caused the event is the target of the event. You ```html
-

- Click here! -

+

Click here!

``` @@ -1005,7 +1003,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}`; @@ -1068,8 +1066,8 @@ FYI: there are only 7 built-in types: `null`, `undefined`, `boolean`, `number`, ```javascript 0; new Number(0); -(''); -(' '); +(""); +(" "); new Boolean(false); undefined; ``` @@ -1216,11 +1214,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] ); ``` @@ -1247,7 +1248,7 @@ Then, `[1, 2, 0, 1]` is `acc` and `[2, 3]` is `cur`. We concatenate them, and ge ```javascript !!null; -!!''; +!!""; !!1; ``` @@ -1275,7 +1276,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 @@ -1298,7 +1299,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"]` @@ -1357,14 +1358,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"` @@ -1387,7 +1388,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; @@ -1427,7 +1428,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, }; @@ -1456,7 +1457,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"` @@ -1483,7 +1484,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` @@ -1508,8 +1509,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; }); ``` @@ -1537,12 +1538,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); @@ -1574,15 +1575,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); } } @@ -1612,8 +1613,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(); @@ -1685,11 +1686,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(); @@ -1754,7 +1755,7 @@ export default counter; ```javascript // index.js -import myCounter from './counter'; +import myCounter from "./counter"; myCounter += 1; @@ -1783,7 +1784,7 @@ When we try to increment the value of `myCounter`, it throws an error: `myCounte ###### 58. Apa yang akan tampil? ```javascript -const name = 'Lydia'; +const name = "Lydia"; age = 21; console.log(delete name); @@ -1854,7 +1855,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); @@ -1880,9 +1881,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)); @@ -1911,12 +1912,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); ``` @@ -1947,7 +1948,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); @@ -2052,7 +2053,7 @@ class Dog { constructor(name) { this.name = name; } -}; +} class Labrador extends Dog { // 1 @@ -2074,8 +2075,7 @@ class Labrador extends Dog { this.name = name; this.size = size; } - -}; +} ``` - A: 1 @@ -2103,12 +2103,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; ``` @@ -2136,7 +2136,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` @@ -2159,7 +2159,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)); ``` @@ -2186,7 +2186,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: `"🥑💻"` @@ -2210,11 +2210,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(); @@ -2282,7 +2282,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(); @@ -2319,7 +2319,7 @@ function addToList(item, list) { return list.push(item); } -const result = addToList('apple', ['banana']); +const result = addToList("apple", ["banana"]); console.log(result); ``` @@ -2379,7 +2379,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); ``` @@ -2435,7 +2435,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 { @@ -2480,7 +2480,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); @@ -2576,13 +2576,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; }, @@ -2616,12 +2616,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); ``` @@ -2685,9 +2685,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. @@ -2741,7 +2741,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: `"""` @@ -2796,11 +2796,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); ``` @@ -2833,7 +2833,7 @@ class Person { } } -const member = new Person('John'); +const member = new Person("John"); console.log(typeof member); ``` @@ -2893,7 +2893,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 = () => @@ -2924,7 +2924,7 @@ Regular functions, such as the `giveLydiaPizza` function, have a `prototype` pro ```javascript const person = { - name: 'Lydia', + name: "Lydia", age: 21, }; @@ -2984,7 +2984,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' ]` @@ -2998,8 +2998,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; } @@ -3039,13 +3039,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"; } }; @@ -3074,7 +3074,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); @@ -3143,7 +3143,7 @@ Since no value gets returned in this case, the function returns `undefined`. ###### 99. Apa yang akan tampil? ```javascript -const name = 'Lydia'; +const name = "Lydia"; console.log(name()); ``` @@ -3175,8 +3175,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` @@ -3202,7 +3202,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); @@ -3234,16 +3234,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(); @@ -3281,8 +3281,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); @@ -3342,13 +3342,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); ``` @@ -3387,7 +3387,7 @@ const colorConfig = { yellow: false, }; -const colors = ['pink', 'red', 'blue']; +const colors = ["pink", "red", "blue"]; console.log(colorConfig.colors[1]); ``` @@ -3416,7 +3416,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` @@ -3437,14 +3437,14 @@ Di belakang layar, emoji adalah sebuah unicode. Unicode untuk emoji hati adalah ###### 108. Manakah metode berikut yang akan memodifikasi array aslinya? ```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` @@ -3469,10 +3469,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); ``` @@ -3526,7 +3526,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' } ``` @@ -3538,11 +3538,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(); @@ -3565,7 +3565,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); @@ -3583,11 +3583,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(); @@ -3633,7 +3633,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` @@ -3658,7 +3658,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), }; @@ -3686,16 +3686,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 @@ -3722,14 +3722,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); @@ -3788,7 +3788,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)]); ``` @@ -3814,11 +3814,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}`; @@ -3856,10 +3856,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!`); } @@ -3915,10 +3915,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` @@ -3943,7 +3943,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; }; @@ -4069,8 +4069,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); ``` @@ -4095,7 +4095,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)); @@ -4131,7 +4131,7 @@ const randomValue = 21; function getInfo() { console.log(typeof randomValue); - const randomValue = 'Lydia Hallie'; + const randomValue = "Lydia Hallie"; } getInfo(); @@ -4157,7 +4157,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 { @@ -4165,7 +4165,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!"); } })(); ``` @@ -4190,7 +4190,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)); ``` @@ -4263,19 +4263,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(); @@ -4316,7 +4316,7 @@ export default function sum(x) { } // index.js -import * as sum from './sum'; +import * as sum from "./sum"; ``` - A: `sum(4)` @@ -4333,12 +4333,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); ``` @@ -4369,13 +4369,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; ``` @@ -4405,7 +4405,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); ``` @@ -4433,9 +4433,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", }, }; @@ -4465,9 +4465,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", }, }; @@ -4496,7 +4496,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); @@ -4529,21 +4529,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` @@ -4567,8 +4567,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) { @@ -4611,8 +4611,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) { @@ -4620,9 +4620,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); ``` @@ -4691,11 +4691,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; ``` @@ -4738,7 +4738,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)`.

@@ -4751,11 +4751,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 @@ -4779,19 +4779,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` @@ -4815,25 +4815,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` @@ -4854,12 +4854,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: `['🍌', '🍊', '🍎']` @@ -4885,13 +4886,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" }` @@ -4906,9 +4907,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"}`. @@ -4921,14 +4922,14 @@ 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") -console.log(user.email) +user.updateEmail("new@email.com"); +console.log(user.email); ``` - A: `my@email.com` @@ -4942,6 +4943,77 @@ console.log(user.email) #### Jawaban: A Fungsi `updateEmail` adalah fungsi panah, dan tidak terikat ke objek `user`. Artinya, kata kunci `this` tidak merujuk ke objek `user`, tetapi merujuk pada cakupan global dalam kasus ini. Nilai `email` dalam objek `user` tidak diperbarui. Saat memasukkan nilai `user.email`, nilai asli `my@email.com` akan dikembalikan. + +

+
+ +--- + +###### 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 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'` + +
Jawaban +

+ +#### Jawaban: D + +Metode `Promise.all` menjalankan promise yang diberikan secara paralel. Jika satu promise gagal, metode `Promise.all` dengan nilai promise yang ditolak. Dalam kasus ini, `promise3` ditolak dengan nilai `"Third"`. Kami menangkap nilai yang ditolak dalam metode `catch` yang dirantai pada pemanggilan `runPromises` untuk menangkap setiap kesalahan dalam fungsi `runPromises`. Hanya `"Third"` yang dicatat, karena `promise3` ditolak dengan nilai ini. + +

+
+ +--- + +###### 153.Berapa nilai `method` untuk mencatat `{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` + +
Jawaban +

+ +#### Jawaban: C + +Metode `fromEntries` mengubah array 2d menjadi objek. Elemen pertama di setiap subarray akan menjadi kuncinya, dan elemen kedua di setiap subarray akan menjadi nilainya. Dalam hal ini, kami memetakan di atas array `keys`, yang mengembalikan array yang elemen pertamanya adalah item pada array kunci pada indeks saat ini, dan elemen kedua adalah item dari array nilai pada indeks saat ini. + +Ini membuat array subarray yang berisi kunci dan nilai yang benar, yang menghasilkan `{name:" Lydia ", age: 22}` +

From 26e51986c4f416692cd92c7531c9ee13fc3d6450 Mon Sep 17 00:00:00 2001 From: Sami Kalammallah Date: Fri, 2 Oct 2020 15:44:12 +0700 Subject: [PATCH 680/915] fix merge conflict --- id-ID/README.md | 49 +++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 49 insertions(+) diff --git a/id-ID/README.md b/id-ID/README.md index ed5b950f..37ad12d9 100644 --- a/id-ID/README.md +++ b/id-ID/README.md @@ -4987,6 +4987,55 @@ Metode `Promise.all` menjalankan promise yang diberikan secara paralel. Jika sat ###### 153.Berapa nilai `method` untuk mencatat `{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 } +###### 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 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'` + +
Jawaban +

+ +#### Jawaban: D + +Metode `Promise.all` menjalankan promise yang diberikan secara paralel. Jika satu promise gagal, metode `Promise.all` dengan nilai promise yang ditolak. Dalam kasus ini, `promise3` ditolak dengan nilai `"Third"`. Kami menangkap nilai yang ditolak dalam metode `catch` yang dirantai pada pemanggilan `runPromises` untuk menangkap setiap kesalahan dalam fungsi `runPromises`. Hanya `"Third"` yang dicatat, karena `promise3` ditolak dengan nilai ini. + +

+
+ +--- + +###### 153.Berapa nilai `method` untuk mencatat `{name: "Lydia", age: 22}`? + ```javascript const keys = ["name", "age"]; const values = ["Lydia", 22]; From 9bad27866d540e94819e938aca41b9b9fba88b77 Mon Sep 17 00:00:00 2001 From: Sami Kalammallah Date: Fri, 2 Oct 2020 15:47:15 +0700 Subject: [PATCH 681/915] fix again --- id-ID/README.md | 16 +++++++--------- 1 file changed, 7 insertions(+), 9 deletions(-) diff --git a/id-ID/README.md b/id-ID/README.md index 37ad12d9..21b6f8da 100644 --- a/id-ID/README.md +++ b/id-ID/README.md @@ -4985,6 +4985,7 @@ Metode `Promise.all` menjalankan promise yang diberikan secara paralel. Jika sat --- + ###### 153.Berapa nilai `method` untuk mencatat `{name: "Lydia", age: 22}`? ````javascript @@ -5037,16 +5038,13 @@ Metode `Promise.all` menjalankan promise yang diberikan secara paralel. Jika sat ###### 153.Berapa nilai `method` untuk mencatat `{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` From 385b931ec02b6b3f6d2ec0825b140ef0cee852e9 Mon Sep 17 00:00:00 2001 From: Sami Kalammallah Date: Fri, 2 Oct 2020 16:20:28 +0700 Subject: [PATCH 682/915] update fix --- id-ID/README.md | 36 +++++++++++++++++++----------------- 1 file changed, 19 insertions(+), 17 deletions(-) diff --git a/id-ID/README.md b/id-ID/README.md index 21b6f8da..dcb7dc20 100644 --- a/id-ID/README.md +++ b/id-ID/README.md @@ -153,16 +153,16 @@ Tidak ada nilai 'radius' pada objek itu, yang mengembalikan 'tidak ditentukan'. #### Jawaban: A -The unary plus tries to convert an operand to a number. `true` is `1`, and `false` is `0`. +Unary plus mencoba mengonversi operan menjadi angka. `benar` adalah `1`, dan `salah` adalah `0`. -The string `'Lydia'` is a truthy value. What we're actually asking, is "is this truthy value falsy?". This returns `false`. +stringnya `'Lydia'` adalah nilai kebenaran. Apa yang sebenarnya kami tanyakan adalah "apakah nilai kebenaran ini salah?". pengembalian ini `salah`.

--- -###### 5. Which one is true? +###### 5. Mana yang benar? ```javascript const bird = { @@ -220,13 +220,13 @@ console.log(d.greeting); #### Jawaban: A -In JavaScript, all objects interact by _reference_ when setting them equal to each other. +Dalam JavaScript, semua objek berinteraksi dengan _referensi_ saat menyetelnya agar sama satu sama lain. -First, variable `c` holds a value to an object. Later, we assign `d` with the same reference that `c` has to the object. +Pertama, variabel `c` memiliki nilai untuk sebuah objek. Kemudian, kami menetapkan `d` dengan referensi yang sama yang dimiliki `c` ke objek. -When you change one object, you change all of them. +Saat Anda mengubah satu objek, Anda mengubah semuanya.

@@ -327,7 +327,7 @@ Untuk menghindari hal ini, kita bisa menggunakan `" use strict "`. Ini memastika --- -###### 10. What happens when we do this? +###### 10. Apa yang terjadi jika kita melakukan ini? ```javascript function bark() { @@ -382,7 +382,7 @@ console.log(member.getFullName()); #### Jawaban: A -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, +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 () { @@ -390,7 +390,7 @@ Person.prototype.getFullName = function () { }; ``` -would have made `member.getFullName()` work. Why is this beneficial? Say that we added this method to the constructor itself. Maybe not every `Person` instance needed this method. This would waste a lot of memory space, since they would still have that property, which takes of memory space for each instance. Instead, if we only add it to the prototype, we just have it at one spot in memory, yet they all have access to it! +akan membuat `member.getFullName()` berfungsi. Mengapa ini bermanfaat? Katakanlah kita menambahkan metode ini ke konstruktor itu sendiri. Mungkin tidak setiap instance `Person` membutuhkan metode ini. Ini akan membuang banyak ruang memori, karena mereka masih memiliki properti itu, yang mengambil ruang memori untuk setiap instance. Sebaliknya, jika kita hanya menambahkannya ke prototipe, kita hanya memilikinya di satu tempat di memori, namun mereka semua memiliki akses ke sana!

@@ -452,7 +452,7 @@ During the **capturing** phase, the event goes through the ancestor elements dow --- -###### 14. All object have prototypes. +###### 14. Semua objek memiliki prototypes. - A: true - B: false @@ -4985,7 +4985,6 @@ Metode `Promise.all` menjalankan promise yang diberikan secara paralel. Jika sat --- - ###### 153.Berapa nilai `method` untuk mencatat `{name: "Lydia", age: 22}`? ````javascript @@ -5038,13 +5037,16 @@ Metode `Promise.all` menjalankan promise yang diberikan secara paralel. Jika sat ###### 153.Berapa nilai `method` untuk mencatat `{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` From fd118f27912fccc8d1195a03f1c505d9de1e2d99 Mon Sep 17 00:00:00 2001 From: Antonio Komang Yudistira <46590632+komangss@users.noreply.github.com> Date: Fri, 2 Oct 2020 17:21:28 +0800 Subject: [PATCH 683/915] fix missing translation in some answer and a little bit grammar mistake in line 154 --- id-ID/README.md | 24 ++++++++++++------------ 1 file changed, 12 insertions(+), 12 deletions(-) diff --git a/id-ID/README.md b/id-ID/README.md index 1e906eb5..ff23e703 100644 --- a/id-ID/README.md +++ b/id-ID/README.md @@ -114,10 +114,10 @@ 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` +- A: `20` dan `62.83185307179586` +- B: `20` dan `NaN` +- C: `20` dan `63` +- D: `NaN` dan `63`
Jawaban

@@ -142,16 +142,16 @@ Tidak ada nilai 'radius' pada objek itu, yang mengembalikan 'tidak ditentukan'. !'Lydia'; ``` -- A: `1` and `false` -- B: `false` and `NaN` -- C: `false` and `false` +- A: `1` dan `false` +- B: `false` dan `NaN` +- C: `false` dan `false`

Jawaban

#### Jawaban: A -Unary plus mencoba mengonversi operan menjadi angka. `benar` adalah `1`, dan `salah` adalah `0`. +Unary plus mencoba mengkonversi operan menjadi angka. `benar` adalah `1`, dan `salah` adalah `0`. stringnya `'Lydia'` adalah nilai kebenaran. Apa yang sebenarnya kami tanyakan adalah "apakah nilai kebenaran ini salah?". pengembalian ini `salah`. @@ -410,10 +410,10 @@ 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` +- A: `Person {firstName: "Lydia", lastName: "Hallie"}` dan `undefined` +- B: `Person {firstName: "Lydia", lastName: "Hallie"}` dan `Person {firstName: "Sarah", lastName: "Smith"}` +- C: `Person {firstName: "Lydia", lastName: "Hallie"}` dan `{}` +- D:`Person {firstName: "Lydia", lastName: "Hallie"}` dan `ReferenceError`

Jawaban

From 68e6c54c74d998ad2f9a049c08966a5c9df98dd2 Mon Sep 17 00:00:00 2001 From: Sami Kalammallah Date: Fri, 2 Oct 2020 16:25:15 +0700 Subject: [PATCH 684/915] reupdate --- id-ID/README.md | 36 ++++++++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) diff --git a/id-ID/README.md b/id-ID/README.md index dcb7dc20..06ae6ef8 100644 --- a/id-ID/README.md +++ b/id-ID/README.md @@ -5034,6 +5034,42 @@ Metode `Promise.all` menjalankan promise yang diberikan secara paralel. Jika sat --- +###### 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 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'` + +

Jawaban +

+ +#### Jawaban: D + +Metode `Promise.all` menjalankan promise yang diberikan secara paralel. Jika satu promise gagal, metode `Promise.all` dengan nilai promise yang ditolak. Dalam kasus ini, `promise3` ditolak dengan nilai `"Third"`. Kami menangkap nilai yang ditolak dalam metode `catch` yang dirantai pada pemanggilan `runPromises` untuk menangkap setiap kesalahan dalam fungsi `runPromises`. Hanya `"Third"` yang dicatat, karena `promise3` ditolak dengan nilai ini. + +

+
+ +--- + ###### 153.Berapa nilai `method` untuk mencatat `{name: "Lydia", age: 22}`? ```javascript From cb938df971792459c2d4981c83986809a6bf1420 Mon Sep 17 00:00:00 2001 From: Naufal Hanif <66030265+nahansans@users.noreply.github.com> Date: Fri, 2 Oct 2020 19:27:42 +0700 Subject: [PATCH 685/915] 154-155 --- id-ID/README.md | 63 +++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 63 insertions(+) diff --git a/id-ID/README.md b/id-ID/README.md index ff23e703..25d6c7e1 100644 --- a/id-ID/README.md +++ b/id-ID/README.md @@ -5013,3 +5013,66 @@ 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") + + 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 }` + +
Jawaban +

+ +#### Jawaban: C + +Nilai default dari `address` adalah objek kosong `{}`. Saat kita menyetel variabel `member` sama dengan objek yang dikembalikan oleh fungsi `createMember`, kita tidak meneruskan nilai untuk address, yang berarti bahwa nilai address adalah objek kosong default `{}`.Objek kosong adalah nilai sebenarnya, yang berarti kondisi `address ? address: null` mengembalikan `true`. Nilai address adalah objek kosong `{}`. + +

+
+ +--- + +###### 155. Apa hasilnya? + +```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` + +
Jawaban +

+ +#### Jawaban: B + +Kondisi dalam pernyataan `if` memeriksa apakah nilai dari `!typeof randomValue` sama dengan `"string"`. Operator `!` Mengonversi nilai menjadi nilai boolean. Jika nilainya benar, nilai yang dikembalikan akan menjadi `false`, jika nilainya salah, nilai yang dikembalikan akan menjadi `true`. Dalam kasus ini, nilai yang dikembalikan dari `typeof randomValue` adalah nilai sebenarnya `"string"`, artinya nilai `!typeof randomValue` adalah nilai boolean `false`. + +`!typeof randomValue === "string"` selalu mengembalikan false, karena kita sebenarnya memeriksa `false === "string "`. Karena kondisi mengembalikan `false`, blok kode dari pernyataan `else` dijalankan, dan `Yay it's a string!` Akan dicatat. + +

+
From 64341555effaa3bb96cad7ddd93dec4c69d31c00 Mon Sep 17 00:00:00 2001 From: Sami Kalammallah Date: Fri, 2 Oct 2020 20:50:40 +0700 Subject: [PATCH 686/915] update fix --- id-ID/README.md | 527 ++++++++++++++++++++++++------------------------ 1 file changed, 263 insertions(+), 264 deletions(-) diff --git a/id-ID/README.md b/id-ID/README.md index 5ffbac32..b9aecc4c 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 @@ -45,7 +45,7 @@ Jangan sungkan untuk terhubung dengan saya! 😊
function sayHi() { console.log(name); console.log(age); - var name = "Lydia"; + var name = 'Lydia'; let age = 21; } @@ -65,7 +65,6 @@ sayHi(); 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` 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`. -

@@ -92,10 +91,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. -

@@ -116,10 +114,10 @@ console.log(shape.diameter()); console.log(shape.perimeter()); ``` -- A: `20` dan `62.83185307179586` -- B: `20` dan `NaN` -- C: `20` dan `63` -- D: `NaN` dan `63` +- A: `20` and `62.83185307179586` +- B: `20` and `NaN` +- C: `20` and `63` +- D: `NaN` and `63`
Jawaban

@@ -141,36 +139,36 @@ Tidak ada nilai 'radius' pada objek itu, yang mengembalikan 'tidak ditentukan'. ```javascript +true; -!"Lydia"; +!'Lydia'; ``` -- A: `1` dan `false` -- B: `false` dan `NaN` -- C: `false` dan `false` +- A: `1` and `false` +- B: `false` and `NaN` +- C: `false` and `false`

Jawaban

#### Jawaban: A -Unary plus mencoba mengkonversi operan menjadi angka. `benar` adalah `1`, dan `salah` adalah `0`. +The unary plus tries to convert an operand to a number. `true` is `1`, and `false` is `0`. -stringnya `'Lydia'` adalah nilai kebenaran. Apa yang sebenarnya kami tanyakan adalah "apakah nilai kebenaran ini salah?". pengembalian ini `salah`. +The string `'Lydia'` is a truthy value. What we're actually asking, is "is this truthy value falsy?". This returns `false`.

--- -###### 5. Mana yang benar? +###### 5. Which one is true? ```javascript const bird = { - size: "small", + size: 'small', }; const mouse = { - name: "Mickey", + name: 'Mickey', small: true, }; ``` @@ -201,11 +199,11 @@ However, with dot notation, this doesn't happen. `mouse` does not have a key cal ###### 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); ``` @@ -220,13 +218,13 @@ console.log(d.greeting); #### Jawaban: A -Dalam JavaScript, semua objek berinteraksi dengan _referensi_ saat menyetelnya agar sama satu sama lain. +In JavaScript, all objects interact by _reference_ when setting them equal to each other. -Pertama, variabel `c` memiliki nilai untuk sebuah objek. Kemudian, kami menetapkan `d` dengan referensi yang sama yang dimiliki `c` ke objek. +First, variable `c` holds a value to an object. Later, we assign `d` with the same reference that `c` has to the object. -Saat Anda mengubah satu objek, Anda mengubah semuanya. +When you change one object, you change all of them.

@@ -275,13 +273,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` @@ -327,14 +325,14 @@ Untuk menghindari hal ini, kita bisa menggunakan `" use strict "`. Ini memastika --- -###### 10. Apa yang terjadi jika kita melakukan ini? +###### 10. What happens when we do this? ```javascript function bark() { - console.log("Woof!"); + console.log('Woof!'); } -bark.animal = "dog"; +bark.animal = 'dog'; ``` - A: Nothing, this is totally fine! @@ -364,8 +362,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}`; }; @@ -382,15 +380,15 @@ console.log(member.getFullName()); #### Jawaban: A -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, +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}`; }; ``` -akan membuat `member.getFullName()` berfungsi. Mengapa ini bermanfaat? Katakanlah kita menambahkan metode ini ke konstruktor itu sendiri. Mungkin tidak setiap instance `Person` membutuhkan metode ini. Ini akan membuang banyak ruang memori, karena mereka masih memiliki properti itu, yang mengambil ruang memori untuk setiap instance. Sebaliknya, jika kita hanya menambahkannya ke prototipe, kita hanya memilikinya di satu tempat di memori, namun mereka semua memiliki akses ke sana! +would have made `member.getFullName()` work. Why is this beneficial? Say that we added this method to the constructor itself. Maybe not every `Person` instance needed this method. This would waste a lot of memory space, since they would still have that property, which takes of memory space for each instance. Instead, if we only add it to the prototype, we just have it at one spot in memory, yet they all have access to it!

@@ -405,17 +403,17 @@ 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); ``` -- A: `Person {firstName: "Lydia", lastName: "Hallie"}` dan `undefined` -- B: `Person {firstName: "Lydia", lastName: "Hallie"}` dan `Person {firstName: "Sarah", lastName: "Smith"}` -- C: `Person {firstName: "Lydia", lastName: "Hallie"}` dan `{}` -- D:`Person {firstName: "Lydia", lastName: "Hallie"}` dan `ReferenceError` +- 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`
Jawaban

@@ -452,7 +450,7 @@ During the **capturing** phase, the event goes through the ancestor elements dow --- -###### 14. Semua objek memiliki prototypes. +###### 14. All object have prototypes. - A: true - B: false @@ -476,7 +474,7 @@ function sum(a, b) { return a + b; } -sum(1, "2"); +sum(1, '2'); ``` - A: `NaN` @@ -543,7 +541,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 +568,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`); } @@ -632,7 +630,7 @@ The rest parameter (`...args`.) lets us "collect" all remaining arguments into a ```javascript function getAge() { - "use strict"; + 'use strict'; age = 21; console.log(age); } @@ -660,7 +658,7 @@ With `"use strict"`, you can make sure that you don't accidentally declare globa ###### 21. What's value of `sum`? ```javascript -const sum = eval("10*10+5"); +const sum = eval('10*10+5'); ``` - A: `105` @@ -683,7 +681,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. @@ -736,12 +734,12 @@ You cannot do this with `let` or `const` since they're block-scoped. ###### 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 +765,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,10 +834,10 @@ 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'; name.giveLydiaPizza(); ``` @@ -865,8 +863,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; @@ -898,9 +896,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,7 +951,9 @@ This is where an event loop starts to work. An **event loop** looks at the stack ```html

- +
``` @@ -979,7 +979,9 @@ The deepest nested element that caused the event is the target of the event. You ```html
-

Click here!

+

+ Click here! +

``` @@ -1003,7 +1005,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}`; @@ -1066,8 +1068,8 @@ FYI: there are only 7 built-in types: `null`, `undefined`, `boolean`, `number`, ```javascript 0; new Number(0); -(""); -(" "); +(''); +(' '); new Boolean(false); undefined; ``` @@ -1214,14 +1216,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], ); ``` @@ -1248,7 +1247,7 @@ Then, `[1, 2, 0, 1]` is `acc` and `[2, 3]` is `cur`. We concatenate them, and ge ```javascript !!null; -!!""; +!!''; !!1; ``` @@ -1276,7 +1275,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 @@ -1299,7 +1298,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"]` @@ -1358,14 +1357,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"` @@ -1388,7 +1387,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; @@ -1428,7 +1427,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, }; @@ -1457,7 +1456,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"` @@ -1484,7 +1483,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` @@ -1509,8 +1508,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; }); ``` @@ -1538,12 +1537,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); @@ -1575,15 +1574,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); } } @@ -1613,8 +1612,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(); @@ -1686,11 +1685,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(); @@ -1755,7 +1754,7 @@ export default counter; ```javascript // index.js -import myCounter from "./counter"; +import myCounter from './counter'; myCounter += 1; @@ -1784,7 +1783,7 @@ When we try to increment the value of `myCounter`, it throws an error: `myCounte ###### 58. Apa yang akan tampil? ```javascript -const name = "Lydia"; +const name = 'Lydia'; age = 21; console.log(delete name); @@ -1855,7 +1854,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); @@ -1881,9 +1880,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)); @@ -1912,12 +1911,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); ``` @@ -1948,7 +1947,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); @@ -2053,7 +2052,7 @@ class Dog { constructor(name) { this.name = name; } -} +}; class Labrador extends Dog { // 1 @@ -2075,7 +2074,8 @@ class Labrador extends Dog { this.name = name; this.size = size; } -} + +}; ``` - A: 1 @@ -2103,12 +2103,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; ``` @@ -2136,7 +2136,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` @@ -2159,7 +2159,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)); ``` @@ -2186,7 +2186,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: `"🥑💻"` @@ -2206,15 +2206,15 @@ With the `+` operator, you can concatenate strings. In this case, we are concate --- -###### 71. Bagaimana cara mencatat nilai yang diberikan komentar pada perintah console.log? +###### 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") { + 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(); @@ -2282,7 +2282,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(); @@ -2319,7 +2319,7 @@ function addToList(item, list) { return list.push(item); } -const result = addToList("apple", ["banana"]); +const result = addToList('apple', ['banana']); console.log(result); ``` @@ -2379,7 +2379,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); ``` @@ -2435,7 +2435,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 { @@ -2480,7 +2480,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); @@ -2576,13 +2576,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; }, @@ -2616,12 +2616,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); ``` @@ -2685,9 +2685,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. @@ -2741,7 +2741,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: `"""` @@ -2796,11 +2796,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); ``` @@ -2833,7 +2833,7 @@ class Person { } } -const member = new Person("John"); +const member = new Person('John'); console.log(typeof member); ``` @@ -2893,7 +2893,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 = () => @@ -2924,7 +2924,7 @@ Regular functions, such as the `giveLydiaPizza` function, have a `prototype` pro ```javascript const person = { - name: "Lydia", + name: 'Lydia', age: 21, }; @@ -2984,7 +2984,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' ]` @@ -2998,8 +2998,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; } @@ -3039,13 +3039,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'; } }; @@ -3074,7 +3074,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); @@ -3143,7 +3143,7 @@ Since no value gets returned in this case, the function returns `undefined`. ###### 99. Apa yang akan tampil? ```javascript -const name = "Lydia"; +const name = 'Lydia'; console.log(name()); ``` @@ -3175,8 +3175,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` @@ -3202,7 +3202,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); @@ -3234,16 +3234,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(); @@ -3281,8 +3281,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); @@ -3342,13 +3342,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); ``` @@ -3387,7 +3387,7 @@ const colorConfig = { yellow: false, }; -const colors = ["pink", "red", "blue"]; +const colors = ['pink', 'red', 'blue']; console.log(colorConfig.colors[1]); ``` @@ -3416,7 +3416,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` @@ -3469,10 +3469,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); ``` @@ -3526,7 +3526,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' } ``` @@ -3538,11 +3538,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(); @@ -3565,7 +3565,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); @@ -3583,11 +3583,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(); @@ -3633,7 +3633,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` @@ -3658,7 +3658,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), }; @@ -3686,16 +3686,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 @@ -3722,14 +3722,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); @@ -3788,7 +3788,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)]); ``` @@ -3814,11 +3814,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}`; @@ -3856,10 +3856,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!`); } @@ -3915,10 +3915,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` @@ -3943,7 +3943,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; }; @@ -4069,8 +4069,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); ``` @@ -4095,7 +4095,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)); @@ -4131,7 +4131,7 @@ const randomValue = 21; function getInfo() { console.log(typeof randomValue); - const randomValue = "Lydia Hallie"; + const randomValue = 'Lydia Hallie'; } getInfo(); @@ -4157,7 +4157,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 { @@ -4165,7 +4165,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!'); } })(); ``` @@ -4190,7 +4190,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)); ``` @@ -4263,19 +4263,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(); @@ -4316,7 +4316,7 @@ export default function sum(x) { } // index.js -import * as sum from "./sum"; +import * as sum from './sum'; ``` - A: `sum(4)` @@ -4333,12 +4333,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); ``` @@ -4369,13 +4369,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; ``` @@ -4405,7 +4405,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); ``` @@ -4433,9 +4433,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', }, }; @@ -4465,9 +4465,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', }, }; @@ -4496,7 +4496,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); @@ -4529,21 +4529,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` @@ -4567,8 +4567,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) { @@ -4611,8 +4611,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) { @@ -4620,9 +4620,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); ``` @@ -4691,11 +4691,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; ``` @@ -4738,7 +4738,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)`.

@@ -4751,11 +4751,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 @@ -4779,19 +4779,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` @@ -4815,25 +4815,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` @@ -4854,13 +4854,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: `['🍌', '🍊', '🍎']` @@ -4886,13 +4885,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" }` @@ -4907,9 +4906,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"}`. From b50e91742db8f856b14dbc881488f35f73ba1de1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bj=C3=B6rn=20Schmidt?= Date: Fri, 2 Oct 2020 22:28:23 +0200 Subject: [PATCH 687/915] Updated introduction (german) --- de-DE/README.md | 87 +++++++++++++++++++++++++++++-------------------- 1 file changed, 51 insertions(+), 36 deletions(-) diff --git a/de-DE/README.md b/de-DE/README.md index 71b5401d..3e2ce3f2 100644 --- a/de-DE/README.md +++ b/de-DE/README.md @@ -1,12 +1,23 @@ -# JavaScript Fragen (für Fortgeschrittene) +
+ +

JavaScript Fragen (für Fortgeschrittene)

-Täglich poste ich mehrere Multiple-Choice-Fragen über JavaScript auf meinem [Instagram](https://www.instagram.com/theavocoder), die ich nun auch hier veröffentlichen werde. +--- + +Ich veröffentliche jeden Tag mehrere Multiple-Choice-Fragen über JavaScript auf meinem [Instagram-Account](https://www.instagram.com/theavocoder), die ich nun auch hier veröffentliche. + +Von einfach bis fortgeschritten: teste, wie gut du JavaScript kennst, frische dein Wissen auf oder bereite dich auf ein Vorstellungsgespräch vor! :muscle: :rocket: Ich werde dieses Repo regelmäßig mit neuen Fragen erweitern. Die Antworten sind unterhalb der Fragen **versteckt**. Du kannst einfach darauf klicken, um die Antworten anzuzeigen. Viel Glück :heart: -Von einfach bis fortgeschritten: teste wie gut du JavaScript kennst, frische dein Wissen auf oder bereite dich auf ein Vorstellungsgespräch vor! :muscle: :rocket: Ich werde dieses Repo wöchentlich mit neuen Fragen erweitern. +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ß! | +|---| -Die Antworten sind unterhalb der Fragen versteckt. Du kannst einfach darauf klicken um die Antworten anzuzeigen. Viel Glück :heart: +
Alle 17 verfügbaren Sprachen +

-### Alle verfügbaren Sprachen * [English](../en-EN/README.md) * [العربية](../ar-AR/README_AR.md) * [اللغة العامية - Egyptian Arabic](../ar-EG/README_ar-EG.md) @@ -24,6 +35,10 @@ Die Antworten sind unterhalb der Fragen versteckt. Du kannst einfach darauf klic * [中文版本](../zh-CN/README-zh_CN.md) * [Türkçe](../tr-TR/README-tr_TR.md) * [ไทย](../th-TH/README-th_TH.md) +* [Indonesia](../id-ID/README.md) + +

+
--- @@ -2036,7 +2051,7 @@ Wenn wir keinen Wert einer Funktion ausgeben wird `undefined` ausgegeben. Beim n Beim vierten Call geben wir wieder nichts aus, sodass der Akkumulator wieder `undefined` ist und der aktuelle Wert `4`. `undefined` und `4` werden geloggt.

- + --- ###### 66. Mit welchem Constructor können wir die `Dog` Klasse erweitern? @@ -2049,7 +2064,7 @@ class Dog { }; class Labrador extends Dog { - // 1 + // 1 constructor(name, size) { this.size = size; } @@ -2063,7 +2078,7 @@ class Labrador extends Dog { super(name); this.size = size; } - // 4 + // 4 constructor(name, size) { this.name = name; this.size = size; @@ -2142,7 +2157,7 @@ console.log(Symbol('foo') === Symbol('foo')) #### Antwort: A -Jedes Symbol ist eindeutig. Der Sinn des Argumentes, welches an das Symbol weitergegeben wird, ist dem Symbol eine Beschreibung zu geben. Der Wert des Symbols hängt nicht von diesem Argument ab. Beim vergleichen der Symbole werden zwei komplett neue Symbole erstellt: das erste `Symbol('foo')` und das zweite `Symbol('foo')`. Diese beiden Werte sind eindeutig und nicht identisch, weshalb `Symbol('foo') === Symbol('foo')` `false` ausgibt. +Jedes Symbol ist eindeutig. Der Sinn des Argumentes, welches an das Symbol weitergegeben wird, ist dem Symbol eine Beschreibung zu geben. Der Wert des Symbols hängt nicht von diesem Argument ab. Beim vergleichen der Symbole werden zwei komplett neue Symbole erstellt: das erste `Symbol('foo')` und das zweite `Symbol('foo')`. Diese beiden Werte sind eindeutig und nicht identisch, weshalb `Symbol('foo') === Symbol('foo')` `false` ausgibt.

@@ -2160,7 +2175,7 @@ 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"`,
Antwort

@@ -2688,7 +2703,7 @@ fetch('https://www.website.com/api/user/1') - A: Das Ergebnis der `fetch` Methode. - B: Das Ergebnis des zweiten Aufrufs der `fetch` Methode. - C: Das Ergebnis des Callbacks im vorhergehenden `.then()`. -- D: Immer `undefined`. +- D: Immer `undefined`.

Antwort

@@ -2790,11 +2805,11 @@ Wenn man den Wert des Standard Paramenters gleich dem Parameter setztm der _dana ###### 89. Was ist der Output? ```javascript -// module.js +// module.js export default () => "Hello world" export const name = "Lydia" -// index.js +// index.js import * as data from "./module" console.log(data) @@ -2897,8 +2912,8 @@ 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 +2922,7 @@ console.log(giveLydiaChocolate.prototype) #### Antwort: D -Reguläre Funktionen wie `giveLydiaPizza` haben eine `prototype` Property, die ein Objekt (Prototype Object) mit einem `constructor` ist. Arrow Funktionen dagegen (wie `giveLydiaChocolate`) haben keinen `prototype`. `undefined` wird ausgegeben, wenn wir versuchen den `prototype` mit `giveLydiaChocolate.prototype` aufzurufen. +Reguläre Funktionen wie `giveLydiaPizza` haben eine `prototype` Property, die ein Objekt (Prototype Object) mit einem `constructor` ist. Arrow Funktionen dagegen (wie `giveLydiaChocolate`) haben keinen `prototype`. `undefined` wird ausgegeben, wenn wir versuchen den `prototype` mit `giveLydiaChocolate.prototype` aufzurufen.

@@ -2928,7 +2943,7 @@ for (const [x, y] of Object.entries(person)) { ``` - A: `name` `Lydia` und `age` `21` -- B: `["name", "Lydia"]` und `["age", 21]` +- B: `["name", "Lydia"]` und `["age", 21]` - C: `["name", "age"]` und `undefined` - D: `Error` @@ -2939,7 +2954,7 @@ for (const [x, y] of Object.entries(person)) { `Object.entries(person)` gibt ein Array mit verschachtelten Arrays der Keys aus: -`[ [ 'name', 'Lydia' ], [ 'age', 21 ] ]` +`[ [ 'name', 'Lydia' ], [ 'age', 21 ] ]` Mit der `for-of` Schleife iterieren wir über jedes Element in dem Array, in diesem Fall die verschachtelten Arrays. Wir können die verschachtelten Arrays mit `const [x, y]` in der for-of Schleife destrukturieren. `x` ist gleich dem ersten Element, `y` ist gleich dem zweiten Element in dem verschachtelten Array. @@ -2962,7 +2977,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` @@ -2994,9 +3009,9 @@ function nums(a, b) { if (a > b) console.log('a is bigger') - else + else console.log('b is bigger') - return + return a + b } @@ -3260,12 +3275,12 @@ Mit einem Promise sagen wir _Ich möchte diese Funktion ausführen, aber ich leg Wir können auf den Wert mit `.then()` oder `await` in einer `async` Funktion zugreifen, aber `.then()` und `await` unterscheiden sich in einem bestimmten Punkt. -In `firstFunction` legen wir `myPromise` beiseite, während die Funktion durchläuft, aber wir arbeiten anderen Code ab, hier `console.log('second')`. -Dann wird die Funktion abgeschlossen und der String `I have resolved` wird ausgegeben, nachdem sich der Call Stack geleert hat. +In `firstFunction` legen wir `myPromise` beiseite, während die Funktion durchläuft, aber wir arbeiten anderen Code ab, hier `console.log('second')`. +Dann wird die Funktion abgeschlossen und der String `I have resolved` wird ausgegeben, nachdem sich der Call Stack geleert hat. Mit dem `await` Keyword in `secondFunction` wird die Funktion gestoppt bis der Wert ausgegeben wurde, erst dann wird die nächste Zeile ausgeführt. -Das bedeutet, dass auf `myPromise` gewartet und dann der Wert `I have resolved` ausgegeben wird und erst dann wird die nächste Zeile ausgeführt und `second` wird geloggt. +Das bedeutet, dass auf `myPromise` gewartet und dann der Wert `I have resolved` ausgegeben wird und erst dann wird die nächste Zeile ausgeführt und `second` wird geloggt.

@@ -3300,7 +3315,7 @@ Der `+` Operator wird nicht nur für numerische Werte verwendet, wir können mit Der erste Wert ist `1`, was ein numerischer Wert ist. `1 + 2` ergibt die Zahl `3`. -Der zweite Wert hingegen ist der String `"Lydia"`. `"Lydia"` ist ein String und `2` ist eine Nummer: `2` wird in einem String umgewandelt. `"Lydia"` und `"2"` werden zusammengesetzt, was den String `"Lydia2"` ausgibt. +Der zweite Wert hingegen ist der String `"Lydia"`. `"Lydia"` ist ein String und `2` ist eine Nummer: `2` wird in einem String umgewandelt. `"Lydia"` und `"2"` werden zusammengesetzt, was den String `"Lydia2"` ausgibt. `{ name: "Lydia" }` ist ein Objekt. Weder eine Nummer, noch ein Objekt sind ein String, aber beide werden zu Strings konvertiert und `"[object Object]"` wird ausgegeben. `"[object Object]"` zusammengesetzt mit `"2"` wird `"[object Object]2"`. @@ -3327,7 +3342,7 @@ Promise.resolve(5) Wir können jeden Wert an `Promise.resolve` übergeben, es muss nicht unbedingt ein Promise sein. Die Methode selbst gibt ein Promise zurück, was einen Wert ausgibt (``). Wenn man eine normale Funktion übergibt wird das Promise einen normalen Wert ausgeben. Wenn ein Promise übergeben wird so wird ein Promise gelöst und der Wert des gelösten Promises ausgegeben. -In diesem Fall haben wir nur die Zahl `5` übergeben und diese wird genauso ausgegeben: `5`. +In diesem Fall haben wir nur die Zahl `5` übergeben und diese wird genauso ausgegeben: `5`.

@@ -3366,7 +3381,7 @@ Wir setzen den Standardwert für `person2` gleich dem `person` Objekt und überg Das bedeutet, dass beide Werte eine Referenz zum gleichen Ort im Speicher aufweisen und daher gleich sind. -Der Code im `else` Statement wird aufgerufen und `They are the same!` wird geloggt. +Der Code im `else` Statement wird aufgerufen und `They are the same!` wird geloggt.

@@ -3399,7 +3414,7 @@ console.log(colorConfig.colors[1]) #### Antwort: D -In JavaScript gibt es zwei Wege auf Properties an Objekten zuzugreifen: Punkt-Notation oder Klammern-Notation. In diesem Beispiel nutzen wir Punkt-Notation (`colorConfig.colors`) anstelle von Klammern-Notation (`colorConfig["colors"]`). +In JavaScript gibt es zwei Wege auf Properties an Objekten zuzugreifen: Punkt-Notation oder Klammern-Notation. In diesem Beispiel nutzen wir Punkt-Notation (`colorConfig.colors`) anstelle von Klammern-Notation (`colorConfig["colors"]`). Mit Punkt-Notation versucht JavaScript die Property am Objekt mit diesem exakten Namen zu finden. In unserem Beispiel `colors` im `colorConfig` Objekt. Da es keine Property `colorConfig` gibt wird `undefined` ausgegeben. Dann versuchen wir den Wert des ersten Elements mit `[1]` aufzurufen, was an `undefined` nicht möglich ist, wodurch wir `TypeError: Cannot read property '1' of undefined` ausgegeben bekommen. @@ -3431,7 +3446,7 @@ 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? +###### 108. Welche Methode verändert das ursprüngliche Array? ```javascript const emojis = ['✨', '🥑', '😍'] @@ -3440,13 +3455,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`
Antwort @@ -3454,7 +3469,7 @@ emojis.splice(1, 2, '✨') #### Antwort: D -Mit der `splice` Methode ändern wir das ursprüngliche Array durch löschen, ersetzen oder ergänzen von Elementen. In diesem Fall haben wir 2 Elemente vom Index 1 (`'🥑'` und `'😍'`) entfernt und ✨ stattdessen eingefügt. +Mit der `splice` Methode ändern wir das ursprüngliche Array durch löschen, ersetzen oder ergänzen von Elementen. In diesem Fall haben wir 2 Elemente vom Index 1 (`'🥑'` und `'😍'`) entfernt und ✨ stattdessen eingefügt. `map`, `filter` und `slice` geben ein neues Array aus, `find` gibt ein Element aus und `reduce` gibt einen neuen Wert aus. @@ -3477,7 +3492,7 @@ console.log(food) - A: `['🍕', '🍫', '🥑', '🍔']` - B: `['🍝', '🍫', '🥑', '🍔']` -- C: `['🍝', '🍕', '🍫', '🥑', '🍔']` +- C: `['🍝', '🍕', '🍫', '🥑', '🍔']` - D: `ReferenceError`
Antwort @@ -3531,7 +3546,7 @@ JSON.parse(jsonArray) // { name: 'Lydia' } --- -###### 111. Was ist der Output? +###### 111. Was ist der Output? ```javascript let name = 'Lydia' @@ -3642,7 +3657,7 @@ console.log(`${(x => x)('I love')} to program`) #### Antwort: A -Expressions innerhalb von Template Literals werden zuerst berechnet. Das bedeutet, dass der String den ausgegebenen Wert der Expression beinhaltet, hier die IIFE (immediately invoked Function) `(x => x)('I love')`. Wir geben den Wert `'I love'` als Argument an die `x => x` Arrow Funktion. `x` ist gleich `'I love'` und wird ausgegeben. Das Ergebnis ist `I love to program`. +Expressions innerhalb von Template Literals werden zuerst berechnet. Das bedeutet, dass der String den ausgegebenen Wert der Expression beinhaltet, hier die IIFE (immediately invoked Function) `(x => x)('I love')`. Wir geben den Wert `'I love'` als Argument an die `x => x` Arrow Funktion. `x` ist gleich `'I love'` und wird ausgegeben. Das Ergebnis ist `I love to program`.

@@ -3704,7 +3719,7 @@ myMap.get(() => 'greeting')) #### Antwort: B -Beim Setzen eines Key/Wert Paars mit der `set` Methode wird der Key als erstes Argument an die `set` Funktion übergeben und der Wert wird als zweites Argument eingegeben. Der Key ist die _Funktion_ `() => 'greeting'` und der Wert ist `'Hello world'`. `myMap` ist jetzt `{ () => 'greeting' => 'Hello world!' }`. +Beim Setzen eines Key/Wert Paars mit der `set` Methode wird der Key als erstes Argument an die `set` Funktion übergeben und der Wert wird als zweites Argument eingegeben. Der Key ist die _Funktion_ `() => 'greeting'` und der Wert ist `'Hello world'`. `myMap` ist jetzt `{ () => 'greeting' => 'Hello world!' }`. 1 ist falsch, weil der Key nicht `'greeting'`, sondern `() => 'greeting'` ist. 3 ist falsch, weil wir eine neue Funktion erstellen, indem wir sie als Argument übergeben. Objekte interagieren anhand von _Referenzen_. Funktionen sind Objekte, weshalb zwei Funktionen streng gesehen nie gleich sind, selbst wenn sie sich nicht unterscheiden. From f69e4f86b80bcf22aac5b3bf9f0a53430118c09a Mon Sep 17 00:00:00 2001 From: Irvan Ahmad Prasetya Date: Sat, 3 Oct 2020 08:21:52 +0700 Subject: [PATCH 688/915] fix translate 154 ID --- id-ID/README.md | 4 ---- 1 file changed, 4 deletions(-) diff --git a/id-ID/README.md b/id-ID/README.md index 04485f5d..cc17986f 100644 --- a/id-ID/README.md +++ b/id-ID/README.md @@ -5041,10 +5041,6 @@ console.log(member) #### Answer: C -<<<<<<< HEAD -Nilai default dari `address` adalah sebuah objek kosong `{}`. Saat ketika mengatur variable `member` sama dengan objek yang dikembalikan oleh fungsi `createMember`, kita tidak mengirimkan nilai untuk address, yang berarti bahwa nilai address adalah objek default kosong `{}`. Objek kosong adalah nilai kebenaran, yang berarti kondisi dari `address ? address : null` mengembalikan `true`. Nilai address adalah objek kosong`{}`. -======= Nilai default dari `address` adalah sebuah objek kosong `{}`. Saat ketika mengatur variable `member` sama dengan objek yang dikembalikan oleh fungsi `createMember`, kita tidak mengirimkan nilai untuk address, yang berarti bahwa nilai address adalah objek default kosong `{}`. Objek kosong adalah nilai kebenaran, yang berarti kondisi dari `address ? address : null` mengembalikan `true`. Nilai address adalah objek kosong`{}`. --- ->>>>>>> c3c09485e63fd28ecbce7fc4f94fb73d42152544 From 98733d242bbc82a7c610413631b63196b614ec5a Mon Sep 17 00:00:00 2001 From: Irvan Ahmad Prasetya Date: Sat, 3 Oct 2020 08:33:24 +0700 Subject: [PATCH 689/915] update translate --- id-ID/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/id-ID/README.md b/id-ID/README.md index cc17986f..1b9c1043 100644 --- a/id-ID/README.md +++ b/id-ID/README.md @@ -5041,6 +5041,6 @@ console.log(member) #### Answer: C -Nilai default dari `address` adalah sebuah objek kosong `{}`. Saat ketika mengatur variable `member` sama dengan objek yang dikembalikan oleh fungsi `createMember`, kita tidak mengirimkan nilai untuk address, yang berarti bahwa nilai address adalah objek default kosong `{}`. Objek kosong adalah nilai kebenaran, yang berarti kondisi dari `address ? address : null` mengembalikan `true`. Nilai address adalah objek kosong`{}`. +Nilai default dari `address` adalah objek kosong `{}`. Ketika kita mengatur variable `member` sama dengan objek yang dikembalikan oleh fungsi `createMember`, kita tidak meneruskan nilai untuk address, yang berarti bahwa nilai address adalah objek kosong secara default `{}`. Objek kosong adalah nilai kebenaran, yang berarti kondisi `address ? address : null` mengembalikan `true`. Nilai address adalah objek kosong`{}`. --- From 8743b3f1b02535b23fdc7629cf42f965d55a9568 Mon Sep 17 00:00:00 2001 From: Miftachul Arzak <72002866+miftachularzak@users.noreply.github.com> Date: Sat, 3 Oct 2020 09:03:42 +0700 Subject: [PATCH 690/915] fix id-ID translation --- id-ID/README.md | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/id-ID/README.md b/id-ID/README.md index ff23e703..6ddd4475 100644 --- a/id-ID/README.md +++ b/id-ID/README.md @@ -2514,7 +2514,7 @@ With a _for-of_ loop, we can iterate over **iterables**. An array is an iterable --- -###### 80. What is the output? +###### 80. Apa yang akan tampil? ```javascript const list = [1 + 2, 1 * 2, 1 / 2]; @@ -2531,16 +2531,16 @@ console.log(list); #### Jawaban: 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. +Elemen array dapat berisi beberapa nilai. angka, string, objek, array lain, null, nilai boolean, undefined, dan lainnya seperti tanggal, fungsi, dan kalkulasi. -The element will be equal to the returned value. `1 + 2` returns `3`, `1 * 2` returns `2`, and `1 / 2` returns `0.5`. +elemen akan sama dengan nilai hasilnya. `1 + 2` menghasilkan `3`, `1 * 2` menghasilkan `2`, dan `1 / 2` menghasilkan `0.5`.

--- -###### 81. What is the output? +###### 81. Apa yang akan tampil? ```javascript function sayHi(name) { @@ -2560,13 +2560,13 @@ console.log(sayHi()); #### Jawaban: 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. +Secara default, arguments memiliki nilai `undefined`, kecuali nilai telah diisi ke fungsi. Pada kasus ini, kita tidak mengisi nilai untuk argument `name`. `name` sama dengan `undefined` yang mana mendapat catatan. -In ES6, we can overwrite this default `undefined` value with default parameters. For example: +Di ES6, kita dapat menulis ulang nilai default `undefined` dengan parameter default. Sebagai contoh: `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` +Pada kasus ini, juka kita tidak mengisi nilai atau mengisi `undefined`, `name` akan selalu sama dengan string `Lydia`

From 2d2b236b40d1ff3a9842cf7f7cc79bda9b4ba5bd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bj=C3=B6rn=20Schmidt?= Date: Sat, 3 Oct 2020 09:38:04 +0200 Subject: [PATCH 691/915] Fixed typo in Q126 Fixed spelling of `currency` --- README.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 591e0cb4..0c6394ea 100644 --- a/README.md +++ b/README.md @@ -1,5 +1,6 @@
+

JavaScript Questions

--- @@ -4070,7 +4071,7 @@ console.log(getFine(130, 300)) #### Answer: 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 `currentcy` in `USD` results in `$300.00`. +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`.

From 7c9467e1adc5a8945ef376145fdb744ed67ae89b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bj=C3=B6rn=20Schmidt?= Date: Sat, 3 Oct 2020 12:31:07 +0200 Subject: [PATCH 692/915] Translated Q126 + Q127 (german) --- de-DE/README.md | 95 +++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 95 insertions(+) diff --git a/de-DE/README.md b/de-DE/README.md index 3e2ce3f2..e3fa5f1f 100644 --- a/de-DE/README.md +++ b/de-DE/README.md @@ -4037,3 +4037,98 @@ myFunc(1, 2, 3);

+ +--- + +###### 126. Was ist der 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 + +
Antwort +

+ +#### Antwort: B + +Mit der Methode `Intl.NumberFormat` können wir einen numerischen Wert in einen sprachabhängigen Wert formatieren. Wir formatieren den Zahlenwert `130` zu einem Wert der Sprache `en-US` mit der Einheit (`unit`) in `mile-per-hour`, was `130 mph` ergibt. Analog formatieren wir `300` als eine Währung (`currency`) der Sprache `en-US` in `USD`, was `$300.00` ergibt. + +

+
+ +--- + +###### 127. Was ist der Output? + +```javascript +const spookyItems = ['👻', '🎃', '🕸']; +({ item: spookyItems[3] } = { item: '💀' }); + +console.log(spookyItems); +``` + +- A: `["👻", "🎃", "🕸"]` +- B: `["👻", "🎃", "🕸", "💀"]` +- C: `["👻", "🎃", "🕸", { item: "💀" }]` +- D: `["👻", "🎃", "🕸", "[object Object]"]` + +
Antwort +

+ +#### Antwort: B + +Durch die destrukturierende Zuweisung können wir Werte des Ojekts von der rechten Seite der Zuweisung extrahieren und diese Werte einem Property mit dem selben Namen dem Objekt auf der linken Seite zuweisen. In diesem Fall wird der Wert "💀" an `spookyItems[3]` zugewiesen. Das bedeutet, dass wir das Array `spookyItems` modifizieren, in dem wir "💀" hinzufügen. Beim Loggen von `spookyItems` wird darum `["👻", "🎃", "🕸", "💀"]` ausgegeben. + +

+
+ +--- + +###### 128. Was ist der 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` + +
Antwort +

+ +#### 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. + +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. + +

+
\ No newline at end of file From c2f523132a6ff1b9c267aedaa58f798e56c931a3 Mon Sep 17 00:00:00 2001 From: marzukiberg Date: Sat, 3 Oct 2020 21:06:19 +0700 Subject: [PATCH 693/915] Added Translation to id-ID for answers: 5, 7, and 8 --- id-ID/README.md | 26 ++++++++++++-------------- 1 file changed, 12 insertions(+), 14 deletions(-) diff --git a/id-ID/README.md b/id-ID/README.md index ff23e703..ae569388 100644 --- a/id-ID/README.md +++ b/id-ID/README.md @@ -173,23 +173,22 @@ const mouse = { }; ``` -- 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 +- A: `mouse.bird.size` tidak benar +- B: `mouse[bird.size]` tidak benar +- C: `mouse[bird["size"]]` tidak benar +- D: Semua jawaban benar
Jawaban

#### 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. -In JavaScript, all object keys are strings (unless it's a Symbol). Even though we might not _type_ them as strings, they are always converted into strings under the hood. +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 penyataannya. -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. +`mouse[bird.size]`: Pertama, ini mengevaluasi `bird.size`, yang mana `"small"`. `mouse["small"]` mengembalikan nilai `true` -`mouse[bird.size]`: First it evaluates `bird.size`, which is `"small"`. `mouse["small"]` returns `true` - -However, with dot notation, this doesn't happen. `mouse` does not have a key called `bird`, which means that `mouse.bird` is `undefined`. Then, we ask for the `size` using dot notation: `mouse.bird.size`. Since `mouse.bird` is `undefined`, we're actually asking `undefined.size`. This isn't valid, and will throw an error similar to `Cannot read property "size" of undefined`. +Namun, dengan notasi dot (.), hal ini tidak terjadi. `mouse` tidak memiliki kunci dengan nama `bird`, yang menyebabkan `mouse.bird` bernilai `undefined`. Kemudian, kita meminta `size` untuk menggunakan notasi dot (.): `mouse.bird.size`. Kita mengetahui bahwa `mouse.bird` bernilai `undefined`, yang sebenarnya kita minta adalah `undefined.size`. Yang mana hal ini tidak valid, dan akan memunculkan kesalahan yang mirip dengan `Cannot read property "size" of undefined`.

@@ -253,11 +252,11 @@ console.log(b === c); #### Jawaban: 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. +`new Number()` adalah konstruktor fungsi bawaan pada JavaScript. Meskipun hasilnya terlihat seperti integer, namun sebenarnya itu bukan integer: aslinya memiliki banyak fitur tambahan dan merupakan sebuah objek. -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`. +Saat kita menggunakan operator `==`, hal ini hanya akan memeriksa bahwa keduanya memiliki nilai yang sama. Pada kasus ini kedua variabel tersebut memiliki nilai yang sama, yaitu `3`, maka akan mengembalikan nilai `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.` +Namun, saat kita menggunakan operator `===`, operator ini memeriksa bahwa kedua variabel memiliki nilai dan tipe yang sama. Bagaimanapun: `new Number()` bukanlah sebuah integer, ini adalah sebuah **object**. Keduanya akan mengembalikan nilai `false.`

@@ -292,8 +291,7 @@ console.log(freddie.colorChange('orange')); #### Jawaban: 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. - +Fungsi `colorChange` adalah statis. Metode statis dirancang hanya dapat aktif pada kontruktor dimana fungsi itu dibuat, dan tidak bisa dibawa ke-turunannya. Kita tahu bahwa `freddie` adalah sebuah turunan, maka fungsi itu tidak bisa turun, dan tidak tersedia pada instance `freddie`: sebuah pesan `TypeError` akan dikembalikan.

From 4a1831fd4258ed1673c036aa12b8274c6f1abeac Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bj=C3=B6rn=20Schmidt?= Date: Sat, 3 Oct 2020 22:52:38 +0200 Subject: [PATCH 694/915] Translated Q129 (german) Addtional note: translated Q128 in the previous commit and forgot to mention that --- de-DE/README.md | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) diff --git a/de-DE/README.md b/de-DE/README.md index e3fa5f1f..8441f755 100644 --- a/de-DE/README.md +++ b/de-DE/README.md @@ -4130,5 +4130,35 @@ Mit der Methode `Number.isNaN` kann geprüft werden, ob der übergebene Paramete 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. +

+
+ +--- + +###### 129. Was ist der Output? + +```javascript +const randomValue = 21; + +function getInfo() { + console.log(typeof randomValue); + const randomValue = 'Lydia Hallie'; +} + +getInfo(); +``` + +- A: `"number"` +- B: `"string"` +- C: `undefined` +- D: `ReferenceError` + +
Antwort +

+ +#### Antwort: D + +Variablen die mit `const` deklariert werden, können nicht vor ihrer Initialisierung referenziert werden, das ist die so genannte "zeitweilige tote Zone" (_temporal dead zone_). In der Funktion `getInfo` befindet sich die Variable `randomValue` im Geltungsbereich der Funktion. In der Zeile, in welcher der Wert von `typeof randomValue` geloggt werden soll, ist die Variable noch nicht initialisiert. Entsprechend wird ein `ReferenceError` geworfen! Die Engine versucht nicht in der Kette der Geltungsbereiche hinab zu steigen, da die Variable `randomValue` im Geltungsbereich von `getInfo` deklariert und damit gefunden wurde. +

\ No newline at end of file From 97b0f7083617ab71809dd7722ecec8b8dba91ef1 Mon Sep 17 00:00:00 2001 From: ganiaaldi Date: Sun, 4 Oct 2020 10:27:16 +0700 Subject: [PATCH 695/915] translate answer number 96-99 --- id-ID/README.md | 22 +++++++++++----------- 1 file changed, 11 insertions(+), 11 deletions(-) diff --git a/id-ID/README.md b/id-ID/README.md index ff23e703..ac3cac63 100644 --- a/id-ID/README.md +++ b/id-ID/README.md @@ -3063,7 +3063,7 @@ console.log(member.name); #### Jawaban: 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"`. +Kita dapat mengatur kelas yang sama dengan kelas / fungsi konstruktor lainnya. Dalam kasus ini, kita mengatur `Person` sama dengan `AnotherPerson`. Nama pada konstruktor ini adalah `Sarah`, jadi nama properti yang baru pada `Person` instance `member` adalah `"Sarah"`.

@@ -3091,9 +3091,9 @@ console.log(Object.keys(info)); #### Jawaban: 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. +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. -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). +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()`).

@@ -3123,17 +3123,17 @@ console.log(getUser(user)) #### Jawaban: 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: +Fungsi `getList` menerima array sebagai argumennya. Di antara tanda kurung pada fungsi `getList`, Kita akan menstruktur ulang. Anda dapat melihat ini sebagai: `[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. +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]]`. -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: +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: `const getUser = user => ({ name: user.name, age: user.age })` -Since no value gets returned in this case, the function returns `undefined`. +Karena tidak ada nilai yang dikembalikan dalam kasus ini, maka fungsi akan mengembalikan `undefined`.

@@ -3158,12 +3158,12 @@ console.log(name()); #### Jawaban: C -The variable `name` holds the value of a string, which is not a function, thus cannot invoke. +Variabel `name` menyimpan nilai string, yang bukan merupakan suatu fungsi, sehingga tidak dapat dipanggil. -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! +TypeErrors dilemparkan ketika nilai yang didapatkan bukan dari jenis yang kita harapkan. JavaScript mengharapkan `name` menjadi sebuah fungsi karena kita mencoba untuk memanggilnya. Namun itu adalah sebuah string, sehingga akan muncul 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. +SyntaxErrors muncul ketika anda salah menulis suatu Javascript, seperti `return` menjadi `retrun`. +ReferenceErrors muncul ketika JavaScript tidak dapat menemukan nilai referensi ke nilai yang anda coba akses.

From 8468d037203590adac42d51f5da29b0342784a9c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bj=C3=B6rn=20Schmidt?= Date: Sun, 4 Oct 2020 09:20:08 +0200 Subject: [PATCH 696/915] Translated Q130-133 (german) --- de-DE/README.md | 153 ++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 153 insertions(+) diff --git a/de-DE/README.md b/de-DE/README.md index 8441f755..9f8727ec 100644 --- a/de-DE/README.md +++ b/de-DE/README.md @@ -4160,5 +4160,158 @@ getInfo(); Variablen die mit `const` deklariert werden, können nicht vor ihrer Initialisierung referenziert werden, das ist die so genannte "zeitweilige tote Zone" (_temporal dead zone_). In der Funktion `getInfo` befindet sich die Variable `randomValue` im Geltungsbereich der Funktion. In der Zeile, in welcher der Wert von `typeof randomValue` geloggt werden soll, ist die Variable noch nicht initialisiert. Entsprechend wird ein `ReferenceError` geworfen! Die Engine versucht nicht in der Kette der Geltungsbereiche hinab zu steigen, da die Variable `randomValue` im Geltungsbereich von `getInfo` deklariert und damit gefunden wurde. +

+
+ +--- + +###### 130. Was ist der 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!` + +
Antwort +

+ +#### Antwort: C + +Im `try`-Block loggen wir den mit dem `await`-Operator den Wert der Variable `myPromise`: `"Woah some cool data"`. Da in diesem Block kein Fehler geworfen wird, wird der Code im `catch`-Block nicht ausgeführt. Der Code im `finally`-Block wird _immer_ ausgeführt, `"Oh finally!"` wird geloggt. + +

+
+ +--- + +###### 131. Was ist der Output? + +```javascript +const emojis = ['🥑', ['✨', '✨', ['🍕', '🍕']]]; + +console.log(emojis.flat(1)); +``` + +- A: `['🥑', ['✨', '✨', ['🍕', '🍕']]]` +- B: `['🥑', '✨', '✨', ['🍕', '🍕']]` +- C: `['🥑', ['✨', '✨', '🍕', '🍕']]` +- D: `['🥑', '✨', '✨', '🍕', '🍕']` + +
Antwort +

+ +#### Antwort: B + +Mit der Methode `flat` erzeugen wir ein neues, "flacheres" Array. Die Tiefe des neuen Arrays hängt vom Parameter ab, den wir an `flat` übergeben. In diesem Fall wird der Wert `1` übergeben (welcher der Standardwert der Funktion ist, wir hätten ihn in diesem Fall also nicht explizit übergeben müssen). Das bedeutet, das alle Arrays bis zur ersten Tiefe zusammengefügt werden: `['🥑']` und `['✨', '✨', ['🍕', '🍕']]` in diesem Fall. Das Zusammenfügen dieser beiden Arrays resultiert in: `['🥑', '✨', '✨', ['🍕', '🍕']]`. + +

+
+ +--- + +###### 132. Was ist der 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` + +
Antwort +

+ +#### Antwort: D + +`counterOne` ist eine Instanz der Klasse `Counter`. Diese Klasse enthält ein Property `count` in seinem Konstruktor, sowie eine Methode `increment`. Zuerst wird die Methode `increment` zweimal durch `counterOne.increment()` aufgerufen. Der Wert von `counterOne.count` ist danach `2`. + + + +Danach erzeugen wir eine neue Variable `counterTwo` und setzen sie gleich `counterOne`. Da Objekte via Referenz übergeben werden, erzeugen wir somit lediglich eine neue Referenz auf den selben Bereich im Speicher, auf den auch `counterOne` zeigt. Da der gleiche Speicherbereich verwendet wird, haben alle Änderungen, die am Objekt vorgenommen werden, auf das `counterTwo` zeigt, auch Auswirkungen auf `counterOne`. Aktuell ist `counterTwo.count` somit `2`. + +Wir rufen nun `counterTwo.increment()` auf, wodurch der Wert von `count` auf `3` gesetzt wird. Danach loggen wir den Zustand von `counterOne`, wodurch `3` ausgegeben wird. + + + +

+
+ +--- + +###### 133. Was ist der Output? + +```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!` + +
Antwort +

+ +#### Antwort: D + +Zuerst rufen wir die Funktion `funcOne()` auf. In der ersten Zeile in `funcOne` wird das Promise `myPromise` aufgerufen, was eine _asynchrone_ Operation ist. Während die Engine damit beschäftigt ist dieses Promise zu erfüllen, wird die Funktion `funcOne` weiter ausgeführt. Die nächste Zeile ist die _asynchrone_ Funktion `setTimeout`, von welcher der Callback an die Web API geschickt wird (siehe mein Artikel zu Event Loops). + +Sowohl Promise als auch Timeout sind asynchrone Operationen. Die Funktion läuft also weiter, während sie parallel damit beschäfigt ist diese beiden Operationen zu bearbeiten. Das bedeutet, dass `Last line!` zuerst geloggt wird, da dies keine asynchrone Operation ist. Es ist die letzte Zeile von `funcOne`, das Promise wird erfüllt und `Promise!` geloggt. Da wir jedoch auch `funcTwo()` aufrufen, ist der Call Stack nicht leer und der Callback der Funktion `setTimeout` kann noch nicht zum Call Stack hinzugefügt werden. + +In `funcTwo` warten wir zuerst auf das Promise von `myPromise`. Mit dem `await`-Operator pausieren wir die Ausführung der Funktion bis das Promise erfüllt (oder zurück gewiesen) wurde. Anschließend loggen wir (wieder mit dem `await-Operator`, da das Promise selbst ein Promise zurückgibt) den Wert von `res`. Dadurch wird `Promise!` geloggt. + +Die nächste Zeile ist die _asynchrone_ Funktion `setTimeout`, deren Callback an die Web API gesendet wird. + +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 From 4c56f4e178643d0913e6dc557d9cc1a02b46f2e8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bj=C3=B6rn=20Schmidt?= Date: Sun, 4 Oct 2020 09:24:29 +0200 Subject: [PATCH 697/915] Fixed accidential duplicate line Error was introduced by me in a previous commit --- README.md | 1 - 1 file changed, 1 deletion(-) diff --git a/README.md b/README.md index 0c6394ea..b92153f3 100644 --- a/README.md +++ b/README.md @@ -1,5 +1,4 @@
-

JavaScript Questions

From b0527bb6d7f9f13064fad7bf7f9586a106670415 Mon Sep 17 00:00:00 2001 From: Ryan Nathaniel <68687179+Reihen-afk@users.noreply.github.com> Date: Sun, 4 Oct 2020 20:36:33 +0800 Subject: [PATCH 698/915] Updated New Translation --- id-ID/README.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/id-ID/README.md b/id-ID/README.md index ff23e703..6c28a7c1 100644 --- a/id-ID/README.md +++ b/id-ID/README.md @@ -4506,10 +4506,10 @@ 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: `2` `4` dan `3` `6` +- B: `2` `NaN` dan `3` `NaN` +- C: `2` `Error` dan `3` `6` +- D: `2` `4` dan `3` `Error`
Jawaban

From d801ccd020fc0fef59d897af5439b15f3f1c05d5 Mon Sep 17 00:00:00 2001 From: Ryan Nathaniel <68687179+Reihen-afk@users.noreply.github.com> Date: Sun, 4 Oct 2020 20:56:52 +0800 Subject: [PATCH 699/915] Added Translation and = dan --- id-ID/README.md | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/id-ID/README.md b/id-ID/README.md index 6c28a7c1..e8618517 100644 --- a/id-ID/README.md +++ b/id-ID/README.md @@ -1335,7 +1335,7 @@ console.log(gen.next().value); - A: `[0, 10], [10, 20]` - B: `20, 20` - C: `10, 20` -- D: `0, 10 and 10, 20` +- D: `0, 10 dan 10, 20`

Jawaban

@@ -2222,10 +2222,10 @@ 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")` +- A: `game.next("Yes").value` dan `game.next().value` +- B: `game.next.value("Yes")` dan `game.next.value()` +- C: `game.next().value` dan `game.next("Yes").value` +- D: `game.next.value()` dan `game.next.value("Yes")`

Jawaban

From 7ab32fbd57c1b958456ec05ff01af1e34caf681c Mon Sep 17 00:00:00 2001 From: Maily Santos Date: Sun, 4 Oct 2020 10:12:02 -0300 Subject: [PATCH 700/915] Translate the question 71 to Portuguese --- pt-BR/README_pt_BR.md | 37 +++++++++++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) diff --git a/pt-BR/README_pt_BR.md b/pt-BR/README_pt_BR.md index 7eb9706d..a2127e4b 100644 --- a/pt-BR/README_pt_BR.md +++ b/pt-BR/README_pt_BR.md @@ -2173,3 +2173,40 @@ Com o operador `+`, você pode concatenar seqüências de caracteres (strings).

--- + +###### 71. Como podemos registrar os valores comentados após a instrução console.log? + +```javascript +function* iniciarJogo() { + const resposta = yield 'Você ama JavaScript?'; + if (resposta !== 'Sim') { + return "Uau... Acho que entramos aqui"; + } + return 'O JavaScript também ama você ❤️'; +} + +const jogo = iniciarJogo(); +console.log(/* 1 */); // Você ama JavaScript? +console.log(/* 2 */); // O JavaScript também ama você ❤️ +``` + +- A: `jogo.next("Sim").value` and `jogo.next().value` +- B: `jogo.next.value("Sim")` and `jogo.next.value()` +- C: `jogo.next().value` and `jogo.next("Sim").value` +- D: `jogo.next.value()` and `jogo.next.value("Sim")` + +
Resposta +

+ +#### 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`. + +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. + +

+
+ +--- \ No newline at end of file From 94e6b5b6e6d46483c6386da796706ca0c238a4bd Mon Sep 17 00:00:00 2001 From: Jacob Herper Date: Mon, 5 Oct 2020 08:27:45 +0100 Subject: [PATCH 701/915] fix layout after merge conflict --- de-DE/README.md | 3 --- 1 file changed, 3 deletions(-) diff --git a/de-DE/README.md b/de-DE/README.md index bf8391a1..47ddf131 100644 --- a/de-DE/README.md +++ b/de-DE/README.md @@ -15,9 +15,6 @@ Kontaktiert mich, wenn ihr möchtet! 😊
| 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ß! | |---| -
Alle 17 verfügbaren Sprachen -

-

--- From bfe86214100c639cd3fc884cdbd1e69a9d953543 Mon Sep 17 00:00:00 2001 From: Sami Kalammallah Date: Mon, 5 Oct 2020 17:37:02 +0700 Subject: [PATCH 702/915] update --- id-ID/README.md | 12 ------------ 1 file changed, 12 deletions(-) diff --git a/id-ID/README.md b/id-ID/README.md index c8c77676..928703bf 100644 --- a/id-ID/README.md +++ b/id-ID/README.md @@ -152,16 +152,10 @@ Tidak ada nilai 'radius' pada objek itu, yang mengembalikan 'tidak ditentukan'. #### Jawaban: A -<<<<<<< HEAD -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`. -======= 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`. ->>>>>>> af42bcd7c6066395a68ef91dc3eb0783b6b1bd77

@@ -223,15 +217,9 @@ console.log(d.greeting); #### Jawaban: A -<<<<<<< HEAD -In JavaScript, all objects interact by _reference_ when setting them equal to each other. - -First, variable `c` holds a value to an object. Later, we assign `d` with the same reference that `c` has to the object. -======= Dalam JavaScript, semua objek berinteraksi dengan _reference_ saat menyetelnya agar sama satu sama lain. Pertama, variabel `c` menyimpan nilai ke sebuah objek. Nanti, kita menetapkan `d` dengan referensi yang sama yang dimiliki` c` ke objek. ->>>>>>> af42bcd7c6066395a68ef91dc3eb0783b6b1bd77 From 3332b078b9e83778cd6a7169955cb3d3acbb374a Mon Sep 17 00:00:00 2001 From: Sami Kalammallah Date: Mon, 5 Oct 2020 17:45:15 +0700 Subject: [PATCH 703/915] update fix some duplicate questions --- id-ID/README.md | 87 +------------------------------------------------ 1 file changed, 1 insertion(+), 86 deletions(-) diff --git a/id-ID/README.md b/id-ID/README.md index 928703bf..dcfe056c 100644 --- a/id-ID/README.md +++ b/id-ID/README.md @@ -4983,92 +4983,7 @@ Metode `Promise.all` menjalankan promise yang diberikan secara paralel. Jika sat --- -###### 153.Berapa nilai `method` untuk mencatat `{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 } -###### 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 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'` - -
Jawaban -

- -#### Jawaban: D - -Metode `Promise.all` menjalankan promise yang diberikan secara paralel. Jika satu promise gagal, metode `Promise.all` dengan nilai promise yang ditolak. Dalam kasus ini, `promise3` ditolak dengan nilai `"Third"`. Kami menangkap nilai yang ditolak dalam metode `catch` yang dirantai pada pemanggilan `runPromises` untuk menangkap setiap kesalahan dalam fungsi `runPromises`. Hanya `"Third"` yang dicatat, karena `promise3` ditolak dengan nilai ini. - -

-
- ---- - -###### 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 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'` - -
Jawaban -

- -#### Jawaban: D - -Metode `Promise.all` menjalankan promise yang diberikan secara paralel. Jika satu promise gagal, metode `Promise.all` dengan nilai promise yang ditolak. Dalam kasus ini, `promise3` ditolak dengan nilai `"Third"`. Kami menangkap nilai yang ditolak dalam metode `catch` yang dirantai pada pemanggilan `runPromises` untuk menangkap setiap kesalahan dalam fungsi `runPromises`. Hanya `"Third"` yang dicatat, karena `promise3` ditolak dengan nilai ini. - -

-
- ---- - -###### 153.Berapa nilai `method` untuk mencatat `{name: "Lydia", age: 22}`? +###### 153.Berapa nilai `method` untuk mencatat `{name: "Lydia", age: 22}`? ```javascript const keys = ["name", "age"]; From a153c79589cbfdcaa5dd69cd381931790939f96f Mon Sep 17 00:00:00 2001 From: Sami Kalammallah Date: Mon, 5 Oct 2020 18:02:21 +0700 Subject: [PATCH 704/915] revert some translation --- id-ID/README.md | 34 +++++++++++++++++----------------- 1 file changed, 17 insertions(+), 17 deletions(-) diff --git a/id-ID/README.md b/id-ID/README.md index dcfe056c..572cd06b 100644 --- a/id-ID/README.md +++ b/id-ID/README.md @@ -115,10 +115,10 @@ 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` +- A: `20` dan `62.83185307179586` +- B: `20` dan `NaN` +- C: `20` dan `63` +- D: `NaN` dan `63`
Jawaban

@@ -143,9 +143,9 @@ Tidak ada nilai 'radius' pada objek itu, yang mengembalikan 'tidak ditentukan'. !'Lydia'; ``` -- A: `1` and `false` -- B: `false` and `NaN` -- C: `false` and `false` +- A: `1` dan `false` +- B: `false` dan `NaN` +- C: `false` dan `false`

Jawaban

@@ -162,7 +162,7 @@ String "'Lydia'` adalah nilai yang benar. Apa yang sebenarnya kami tanyakan adal --- -###### 5. Which one is true? +###### 5. Mana yang benar? ```javascript const bird = { @@ -223,7 +223,7 @@ Pertama, variabel `c` menyimpan nilai ke sebuah objek. Nanti, kita menetapkan `d -When you change one object, you change all of them. +Saat Anda mengubah satu objek, Anda mengubah semuanya.

@@ -324,7 +324,7 @@ Untuk menghindari hal ini, kita bisa menggunakan `" use strict "`. Ini memastika --- -###### 10. What happens when we do this? +###### 10. Apa yang terjadi jika kita melakukan ini? ```javascript function bark() { @@ -379,7 +379,7 @@ console.log(member.getFullName()); #### Jawaban: A -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, +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() { @@ -387,7 +387,7 @@ Person.prototype.getFullName = function() { }; ``` -would have made `member.getFullName()` work. Why is this beneficial? Say that we added this method to the constructor itself. Maybe not every `Person` instance needed this method. This would waste a lot of memory space, since they would still have that property, which takes of memory space for each instance. Instead, if we only add it to the prototype, we just have it at one spot in memory, yet they all have access to it! +Akan membuat `member.getFullName()` berfungsi. Mengapa ini bermanfaat? Katakanlah kita menambahkan metode ini ke konstruktor itu sendiri. Mungkin tidak setiap instance `Person` membutuhkan metode ini. Ini akan membuang banyak ruang memori, karena mereka masih memiliki properti itu, yang mengambil ruang memori untuk setiap instance. Sebaliknya, jika kita hanya menambahkannya ke prototipe, kita hanya memilikinya di satu tempat di memori, namun mereka semua memiliki akses ke sana!

@@ -409,10 +409,10 @@ 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` +- A: `Person {firstName: "Lydia", lastName: "Hallie"}` dan `undefined` +- B: `Person {firstName: "Lydia", lastName: "Hallie"}` dan `Person {firstName: "Sarah", lastName: "Smith"}` +- C: `Person {firstName: "Lydia", lastName: "Hallie"}` dan `{}` +- D:`Person {firstName: "Lydia", lastName: "Hallie"}` dan `ReferenceError`
Jawaban

@@ -449,7 +449,7 @@ During the **capturing** phase, the event goes through the ancestor elements dow --- -###### 14. All object have prototypes. +###### 14. Semua objek memiliki prototypes. - A: true - B: false From ffa254beee49f553d46f5b6154dee51fdf062044 Mon Sep 17 00:00:00 2001 From: Sami Kalammallah Date: Mon, 5 Oct 2020 18:15:21 +0700 Subject: [PATCH 705/915] fix tab indentation as mentioned --- id-ID/README.md | 32 ++++++++++++++++---------------- 1 file changed, 16 insertions(+), 16 deletions(-) diff --git a/id-ID/README.md b/id-ID/README.md index 572cd06b..55609aed 100644 --- a/id-ID/README.md +++ b/id-ID/README.md @@ -2685,8 +2685,8 @@ Variables with the `const` and `let` keyword are _block-scoped_. A block is anyt ```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: The result of the `fetch` method. @@ -4920,10 +4920,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"); @@ -4950,20 +4950,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']]` From 36abf1f5c5e3a24f6003239732915991f0425c2e Mon Sep 17 00:00:00 2001 From: ACEZ Date: Tue, 6 Oct 2020 20:10:56 +0700 Subject: [PATCH 706/915] Fix id-ID translation (22.) I translated question and answer number 22. --- id-ID/README.md | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/id-ID/README.md b/id-ID/README.md index 0df8e6b9..c0f40bd6 100644 --- a/id-ID/README.md +++ b/id-ID/README.md @@ -677,25 +677,25 @@ const sum = eval('10*10+5'); --- -###### 22. How long is cool_secret accessible? +###### 22. Sampai berapa lama kah cool_secret dapat diakses? ```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. +- A: Selamanya, data tersebut tidak akan hilang. +- B: Saat pengguna menutup tab browser. +- C: Saat pengguna menutup seluruh browser, tidak hanya tab. +- D: Saat pengguna mematikan komputernya.

Jawaban

#### Jawaban: B -The data stored in `sessionStorage` is removed after closing the _tab_. +Data yang disimpan di `sessionStorage` akan dihapus setelah menutup _tab_. -If you used `localStorage`, the data would've been there forever, unless for example `localStorage.clear()` is invoked. +Jika anda menggunakan `localStorage`, data tersebut akan tersimpan selamanya, kecuali misalnya _method_ `localStorage.clear()` dipanggil.

From 91f56a6974db8100ffe2d24307fa8da0e1acdd5b Mon Sep 17 00:00:00 2001 From: insomness <58702720+insomness@users.noreply.github.com> Date: Tue, 6 Oct 2020 20:37:22 +0700 Subject: [PATCH 707/915] translate number 12 and 15 --- id-ID/README.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/id-ID/README.md b/id-ID/README.md index 0df8e6b9..197777b1 100644 --- a/id-ID/README.md +++ b/id-ID/README.md @@ -419,9 +419,9 @@ console.log(sarah); #### Jawaban: A -For `sarah`, we didn't use the `new` keyword. When using `new`, it refers to the new empty object we create. However, if you don't add `new` it refers to the **global object**! +Pada `sarah`, kita tidak menggunakan kata kunci `new`. Saat menggunakan `new`, Ini mengacu pada object kosong yang kita buat. Namun, jika Anda tidak menambahkan `new` ini merujuk pada **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. +Kita tahu bahwa `this.firstName` setara dengan `"Sarah"` dan `this.lastName` sama dengan `"Smith"`. Apa yang sebenarnya kami lakukan adalah mendefinisikan `global.firstName = 'Sarah'` dan `global.lastName = 'Smith'`. `sarah` sendiri dibiarkan `undefined`, karena kita tidak mengembalikan nilai dari fungsi `Person`.

@@ -486,9 +486,9 @@ sum(1, '2'); #### Jawaban: 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. +JavaScript adalah **Bahasa yang bersifat dinamis**: yang tidak menentukan jenis variabel tertentu. Values dapat secara otomatis diubah menjadi jenis lain tanpa Anda sadari, yang disebut _implicit type coercion_. **Coercion** adalah mengubah dari satu jenis ke jenis lainnya. -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"`. +Pada contoh ini, JavaScript mengubah number `1` menjadi sebuah string, agar fungsi tersebut masuk akal dan mengembalikan nilai. Selama penambahan tipe numerik (`1`) dan tipe string (`'2'`), angka tersebut diperlakukan sebagai string. Kita bisa menggabungkan string seperti `"Hello" + "World"`, jadi yang terjadi di sini adalah `"1" + "2"` yang mengembalikan `"12"`.

From 0fd89aa881ba64afa0ede95256dde10eebcb9da2 Mon Sep 17 00:00:00 2001 From: Irvan Ahmad Prasetya Date: Tue, 6 Oct 2020 21:55:42 +0700 Subject: [PATCH 708/915] translate number 27 and 57 id-ID --- id-ID/README.md | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/id-ID/README.md b/id-ID/README.md index 0df8e6b9..e456b3af 100644 --- a/id-ID/README.md +++ b/id-ID/README.md @@ -186,7 +186,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 penyataannya. `mouse[bird.size]`: Pertama, ini mengevaluasi `bird.size`, yang mana `"small"`. `mouse["small"]` mengembalikan nilai `true`. +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 penyataannya. `mouse[bird.size]`: Pertama, ini mengevaluasi `bird.size`, yang mana `"small"`. `mouse["small"]` mengembalikan nilai `true`. Namun, dengan notasi dot (.), hal ini tidak terjadi. `mouse` tidak memiliki kunci dengan nama `bird`, yang menyebabkan `mouse.bird` bernilai `undefined`. Kemudian, kita meminta `size` untuk menggunakan notasi dot (.): `mouse.bird.size`. Kita mengetahui bahwa `mouse.bird` bernilai `undefined`, yang sebenarnya kita minta adalah `undefined.size`. Yang mana hal ini tidak valid, dan akan memunculkan kesalahan yang mirip dengan `Cannot read property "size" of undefined`. @@ -822,7 +822,7 @@ for (let i = 1; i < 5; i++) { #### Jawaban: C -The `continue` statement skips an iteration if a certain condition returns `true`. +Pernyataan `continue` melewatkan iterasi jika kondisi tertentu mengembalikan` true`.

@@ -1770,9 +1770,10 @@ console.log(myCounter); #### Jawaban: C -An imported module is _read-only_: you cannot modify the imported module. Only the module that exports them can change its value. +Modul yang diimpor adalah _read-only_: Anda tidak dapat mengubah modul yang diimpor. Hanya modul yang mengekspornya yang dapat mengubah nilainya. + +Ketika kita mencoba untuk menambah nilai `myCounter`, itu melemparkan kesalahan: `myCounter` adalah baca-saja dan tidak dapat dimodifikasi. -When we try to increment the value of `myCounter`, it throws an error: `myCounter` is read-only and cannot be modified.

From c33df049fd33e93124c0018887bbf66e5ba20757 Mon Sep 17 00:00:00 2001 From: Irvan Ahmad Prasetya Date: Tue, 6 Oct 2020 22:00:48 +0700 Subject: [PATCH 709/915] fix answer 27 --- id-ID/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/id-ID/README.md b/id-ID/README.md index e456b3af..c78615a5 100644 --- a/id-ID/README.md +++ b/id-ID/README.md @@ -822,7 +822,7 @@ for (let i = 1; i < 5; i++) { #### Jawaban: C -Pernyataan `continue` melewatkan iterasi jika kondisi tertentu mengembalikan` true`. +Pernyataan `continue` melewatkan iterasi jika kondisi tertentu mengembalikan `true`.

From 50d4764cf5105963ae3e27c34177d705b3de0044 Mon Sep 17 00:00:00 2001 From: Irvan Ahmad Prasetya Date: Wed, 7 Oct 2020 02:53:56 +0700 Subject: [PATCH 710/915] fix type answer number 5 ID --- id-ID/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/id-ID/README.md b/id-ID/README.md index c78615a5..75640e92 100644 --- a/id-ID/README.md +++ b/id-ID/README.md @@ -186,7 +186,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 penyataannya. `mouse[bird.size]`: Pertama, ini mengevaluasi `bird.size`, yang mana `"small"`. `mouse["small"]` mengembalikan nilai `true`. +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`. Namun, dengan notasi dot (.), hal ini tidak terjadi. `mouse` tidak memiliki kunci dengan nama `bird`, yang menyebabkan `mouse.bird` bernilai `undefined`. Kemudian, kita meminta `size` untuk menggunakan notasi dot (.): `mouse.bird.size`. Kita mengetahui bahwa `mouse.bird` bernilai `undefined`, yang sebenarnya kita minta adalah `undefined.size`. Yang mana hal ini tidak valid, dan akan memunculkan kesalahan yang mirip dengan `Cannot read property "size" of undefined`. From 1e060b1e1456e3a5ba7c2ecf04112cfdc7e52242 Mon Sep 17 00:00:00 2001 From: danangekal Date: Tue, 13 Oct 2020 15:56:25 +0700 Subject: [PATCH 711/915] Translation id-ID question & answer 13 --- 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 26f660ad..b50f49c0 100644 --- a/id-ID/README.md +++ b/id-ID/README.md @@ -428,7 +428,7 @@ Kita tahu bahwa `this.firstName` setara dengan `"Sarah"` dan `this.lastName` sam --- -###### 13. What are the three phases of event propagation? +###### 13. Apa tiga fase dari event propagation? - A: Target > Capturing > Bubbling - B: Bubbling > Target > Capturing @@ -440,7 +440,7 @@ Kita tahu bahwa `this.firstName` setara dengan `"Sarah"` dan `this.lastName` sam #### Jawaban: 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. +Selama fase **capturing**, event melewati elemen ancestor hingga ke elemen target. Kemudian mencapai element **target**, dan **bubbling** dimulai. From 81cedfa4e586afe792cc27778b0f2c79b2961602 Mon Sep 17 00:00:00 2001 From: danangekal Date: Tue, 13 Oct 2020 15:57:19 +0700 Subject: [PATCH 712/915] Translation id-ID answer 14 --- id-ID/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/id-ID/README.md b/id-ID/README.md index b50f49c0..b8963a97 100644 --- a/id-ID/README.md +++ b/id-ID/README.md @@ -459,7 +459,7 @@ Selama fase **capturing**, event melewati elemen ancestor hingga ke elemen targe #### Jawaban: 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. +Semua objek memiliki prototypes, kecuali **objek dasar**. Objek dasar adalah objek yang dibuat oleh pengguna, atau objek yang dibuat dengan menggunakan kata kunci `baru`. Objek dasar memiliki akses ke beberapa metode dan properti, seperti `.toString`. Inilah alasan mengapa Anda dapat menggunakan metode JavaScript bawaan! Semua metode tersebut tersedia di prototipe. Meskipun JavaScript tidak dapat menemukannya secara langsung di objek Anda, JavaScript berada di rantai prototipe dan menemukannya di sana, yang membuatnya dapat diakses untuk Anda.

From 773e23d9fb1a29d61d464ddecc6ba0519b8afa28 Mon Sep 17 00:00:00 2001 From: danangekal Date: Tue, 13 Oct 2020 16:03:38 +0700 Subject: [PATCH 713/915] Translation id-ID answer 16 --- id-ID/README.md | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/id-ID/README.md b/id-ID/README.md index b8963a97..ef9c56f3 100644 --- a/id-ID/README.md +++ b/id-ID/README.md @@ -514,17 +514,17 @@ console.log(number); #### Jawaban: C -The **postfix** unary operator `++`: +**Akhiran** operator unary `++`: -1. Returns the value (this returns `0`) -2. Increments the value (number is now `1`) +1. Mengembalikan nilai (ini mengembalikan `0`) +2. Menambahkan nilai (angkanya sekarang `1`) -The **prefix** unary operator `++`: +**Awalan** operator unary `++`: -1. Increments the value (number is now `2`) -2. Returns the value (this returns `2`) +1. Menambah nilai (angkanya sekarang `2`) +2. Mengembalikan nilai (ini mengembalikan `2`) -This returns `0 2 2`. +Ini mengembalikan `0 2 2`.

From 644b77900e232b17b399a937082012188f2d5eb4 Mon Sep 17 00:00:00 2001 From: danangekal Date: Tue, 13 Oct 2020 16:07:43 +0700 Subject: [PATCH 714/915] Translation id-ID answer 17 --- id-ID/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/id-ID/README.md b/id-ID/README.md index ef9c56f3..863ca966 100644 --- a/id-ID/README.md +++ b/id-ID/README.md @@ -555,7 +555,7 @@ getPersonInfo`${person} is ${age} years old`; #### Jawaban: 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! +Jika Anda menggunakan literal template yang diberi tag, nilai argumen pertama selalu berupa array bernilai string. Argumen yang tersisa mendapatkan nilai dari ekspresi yang diteruskan!

From d0dcf6b5f9caccb71449b780fc8eb52762b1f99e Mon Sep 17 00:00:00 2001 From: danangekal Date: Tue, 13 Oct 2020 16:15:09 +0700 Subject: [PATCH 715/915] Translation id-ID answer 18 --- id-ID/README.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/id-ID/README.md b/id-ID/README.md index 863ca966..b74b5580 100644 --- a/id-ID/README.md +++ b/id-ID/README.md @@ -587,11 +587,11 @@ checkAge({ age: 18 }); #### Jawaban: 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. +Saat menguji persamaan, primitif dibandingkan dengan nilainya, sedangkan objek dibandingkan dengan referensinya. JavaScript memeriksa apakah objek memiliki referensi ke lokasi yang sama di memori. -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. +Dua objek yang kita bandingkan tidak memiliki itu: objek yang kita lewati sebagai parameter merujuk ke lokasi yang berbeda dalam memori dari objek yang kita gunakan untuk memeriksa persamaan. -This is why both `{ age: 18 } === { age: 18 }` and `{ age: 18 } == { age: 18 }` return `false`. +Inilah mengapa `{age: 18} === {age: 18}` dan `{age: 18} == {age: 18}` mengembalikan nilai `false`.

From 59dc511dee38971f72830d4c7aac21dd3e8d46d9 Mon Sep 17 00:00:00 2001 From: danangekal Date: Tue, 13 Oct 2020 16:22:19 +0700 Subject: [PATCH 716/915] Translation id-ID answer 19 --- id-ID/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/id-ID/README.md b/id-ID/README.md index b74b5580..8b785310 100644 --- a/id-ID/README.md +++ b/id-ID/README.md @@ -618,7 +618,7 @@ getAge(21); #### Jawaban: C -The rest parameter (`...args`.) lets us "collect" all remaining arguments into an array. An array is an object, so `typeof args` returns `"object"` +Parameter sisanya (`... args`.) Memungkinkan kita "mengumpulkan" semua argumen yang tersisa ke dalam sebuah array. Array adalah sebuah objek, jadi `typeof args` mengembalikan "objek"

From 7587741a0e3397f8e5b2af0b581c7cf8d8cbc9e3 Mon Sep 17 00:00:00 2001 From: danangekal Date: Tue, 13 Oct 2020 16:24:29 +0700 Subject: [PATCH 717/915] Translation id-ID answer 20 --- id-ID/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/id-ID/README.md b/id-ID/README.md index 8b785310..c8a35d41 100644 --- a/id-ID/README.md +++ b/id-ID/README.md @@ -647,7 +647,7 @@ getAge(); #### Jawaban: 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. +Dengan `" use strict "`, Anda dapat memastikan bahwa Anda tidak mendeklarasikan variabel global secara tidak sengaja. Kita tidak pernah mendeklarasikan variabel `age`, dan karena kita menggunakan `" use strict "`, ini akan memunculkan kesalahan referensi. Jika kita tidak menggunakan `" use strict "`, ini akan berhasil, karena properti `age` akan ditambahkan ke objek global.

From a640e576de5446e2d337fdd7c5a4a5cddc7b4ede Mon Sep 17 00:00:00 2001 From: YafiAzka <72979354+YafiAzka@users.noreply.github.com> Date: Fri, 16 Oct 2020 22:32:22 +0700 Subject: [PATCH 718/915] Udah di translate 21,23,25,28,30 correct me if i'm wrong --- id-ID/README.md | 26 +++++++++++++------------- 1 file changed, 13 insertions(+), 13 deletions(-) diff --git a/id-ID/README.md b/id-ID/README.md index c8a35d41..00a06524 100644 --- a/id-ID/README.md +++ b/id-ID/README.md @@ -670,7 +670,7 @@ const sum = eval('10*10+5'); #### Jawaban: 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` mengevaluasi kode yang berlalu sebagai string. Jika itu adalah ekspresi, seperti dalam kasus ini, itu mengevaluasi ekspresi. Ungkapannya adalah `10 * 10 + 5`. Ini kembali nomor `105`.

@@ -721,9 +721,9 @@ console.log(num); #### Jawaban: B -With the `var` keyword, you can declare multiple variables with the same name. The variable will then hold the latest value. +Dengan kata kunci `var`, anda dapat menyatakan beberapa variabel dengan nama yang sama. Variabelnya akan memegang nilai terakhir. -You cannot do this with `let` or `const` since they're block-scoped. +Anda tidak dapat melakukan ini dengan `let` atau `const` karena mereka block-scoped.

@@ -778,7 +778,7 @@ console.log(obj); #### Jawaban: 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. +Jika anda memiliki dua kunci dengan nama yang sama, kunci akan diganti. Ini masih dalam posisi pertama, tetapi dengan nilai terakhir yang ditentukan.

@@ -851,7 +851,7 @@ name.giveLydiaPizza(); #### Jawaban: 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` adalah konstruksi dibangun, yang dapat kita tambahkan properti ke. Aku hanya menambahkan metode ke prototipe. String primitif string secara otomatis dikonversi menjadi objek string, dihasilkan oleh fungsi prototipe string. Jadi, semua string (objek string) memiliki akses ke metode itu!

@@ -914,31 +914,31 @@ baz(); #### Jawaban: B -We have a `setTimeout` function and invoked it first. Yet, it was logged last. +Kami memiliki fungsi `setTimeout` dan dimohonkan terlebih dahulu. Namun, itu login terakhir. -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. +Hal ini karena di browsers, kita tidak hanya memiliki mesin waktu runtime, kita juga memiliki sesuatu yang disebut `WebAPI`. `WebAPI` memberi kita fungsi `setTimeout`, dan misalnya DOM. -After the _callback_ is pushed to the WebAPI, the `setTimeout` function itself (but not the callback!) is popped off the stack. +Setelah _callback_ (panggilan balik) didorong ke WebAPI, fungsi `setTimeout` itu sendiri (tetapi tidak panggilan balik) muncul dari tumpukan. -Now, `foo` gets invoked, and `"First"` is being logged. +Sekarang, `foo` mendapat hambatan, dan `"First"` yang login. -`foo` is popped off the stack, and `baz` gets invoked. `"Third"` gets logged. +`foo` yang muncul dari tumpukan, dan `baz` mendapat perantara. `"Third"` akan login. -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_. +WebAPI tidak bisa hanya menambahkan barang-barang ke tumpukan setiap kali siap. Sebaliknya, ia mendorong fungsi panggilan balik ke sesuatu yang disebut _queue_ (antrian). -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. +Di sinilah serangkaian acara mulai bekerja. Sebuah **event loop** (putaran kejadian/peristiwa) melihat tumpukan dan antrian tugas. Jika tumpukan kosong, itu mengambil hal pertama pada antrian dan mendorong ke tumpukan. -`bar` gets invoked, `"Second"` gets logged, and it's popped off the stack. +`bar` bisa dipanggil, `"Second"` akan login, dan itu muncul dari tumpukan.

From 767dc1d8f3cf70fc47975db72f152e391372c8c8 Mon Sep 17 00:00:00 2001 From: FrankKai Date: Mon, 19 Oct 2020 17:07:50 +0800 Subject: [PATCH 719/915] add zh-CN version 145~155 translations --- zh-CN/README-zh_CN.md | 372 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 372 insertions(+) diff --git a/zh-CN/README-zh_CN.md b/zh-CN/README-zh_CN.md index 1d096e91..af29ca7d 100644 --- a/zh-CN/README-zh_CN.md +++ b/zh-CN/README-zh_CN.md @@ -4714,3 +4714,375 @@ const person = {

+ +--- + +###### 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 ef0d46c0d79cf73f1d045c7c6f9103e694556582 Mon Sep 17 00:00:00 2001 From: Mogeli lortkipanidze Date: Wed, 4 Nov 2020 22:17:36 +0400 Subject: [PATCH 720/915] Fixed small mistake --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 4b7ea9a3..47ba81d6 100644 --- a/README.md +++ b/README.md @@ -551,7 +551,7 @@ function getPersonInfo(one, two, three) { const person = 'Lydia'; const age = 21; -getPersonInfo`${person} is ${age} years old`; +getPersonInfo(`${person} is ${age} years old`); ``` - A: `"Lydia"` `21` `["", " is ", " years old"]` From ef2ca1b235fd8c933645640d392e47208a253ba2 Mon Sep 17 00:00:00 2001 From: Matiiv Vasyl <51299968+vmatiiv@users.noreply.github.com> Date: Thu, 12 Nov 2020 22:21:52 +0200 Subject: [PATCH 721/915] Update README-ua_UA.md Fix grammatical typos. UA --- ua-UA/README-ua_UA.md | 52 +++++++++++++++++++++---------------------- 1 file changed, 26 insertions(+), 26 deletions(-) diff --git a/ua-UA/README-ua_UA.md b/ua-UA/README-ua_UA.md index 63789f59..003a372e 100644 --- a/ua-UA/README-ua_UA.md +++ b/ua-UA/README-ua_UA.md @@ -2,9 +2,9 @@ Я публікую щодня завдання з JavaScript в моєму [Instagram](https://www.instagram.com/theavocoder), які також додаю тут! -Від базового до просунутого: перевірте, наскільки добре ви знаєте JavaScript, трохи оновлюйте свої знання або підготуйтеся до інтерв'ю! :muscle: :rocket: Щотижня я доповнюю цей репозиторій новими питаннями. +Від базового до просунутого: перевірте, наскільки добре ви знаєте JavaScript, трохи оновіть свої знання або підготуйтеся до інтерв'ю! :muscle: :rocket: Щотижня я доповнюю цей репозиторій новими питаннями. -Відповіді знаходяться в згорнутої секції нижче питань. Просто натисни на відповідь, щоб розгорнути. Успіхів! :heart: +Відповіді знаходяться в згорнутій секції нижче питань. Просто натисни на відповідь, щоб розгорнути. Успіхів! :heart: - [🇸🇦 العربية](./ar-AR/README_AR.md) - [🇪🇬 اللغة العامية](./ar-EG/README_ar-EG.md) @@ -50,7 +50,7 @@ sayHi(); #### Відповідь: D -Усередині функції ми спершу визначаємо змінну `name` за допомогою ключового слова `var`. Це означає, що змінна буде знайдена (область пам'яті під змінну буде виділена під час створення) зі значенням `undefined` за замовчуванням, до тих пір поки виконання коду не дійде до рядка, де визначається змінна. Ми ще не визначили значення `name`, коли намагаємося вивести її в консоль, тому в консолі буде `undefined`. +Всередині функції ми спершу визначаємо змінну `name` за допомогою ключового слова `var`. Це означає, що змінна буде знайдена (область пам'яті під змінну буде виділена під час створення) зі значенням `undefined` за замовчуванням, до тих пір поки виконання коду не дійде до рядка, де визначається змінна. Ми ще не визначили значення `name`, коли намагаємося вивести її в консоль, тому в консолі буде `undefined`. Змінні, визначені за допомогою `let` (і `const`), також знаходяться, але на відміну від `var`, не створюються. Доступ до них неможливий до тих пір, поки не виконається рядок їх визначення (ініціалізації). Це називається "тимчасова мертва зона". Коли ми намагаємося звернутися до змінних до того моменту як вони визначені, JavaScript видає `ReferenceError`. @@ -82,7 +82,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` матиме нове значення, і кожне значення буде замкнуто в своїй області видимості всередині циклу.

@@ -114,9 +114,9 @@ shape.perimeter(); #### Відповідь: B -Зауваж, що `diameter` це звичайна функція, в той час як `perimeter` це функція стрілки. +Зауваж, що `diameter` це звичайна функція, в той час як `perimeter` це стрілкова функція. -У стрілочних функцій значення `this` вказує на навколишню область видимості, на відміну від звичайних функцій! Це означає, що при виклику `perimeter` значення `this` у цій функції вказує не на об'єкт `shape`, а на зовнішню область видимості (наприклад, window). +У стрілкових функцій значення `this` вказує на навколишню область видимості, на відміну від звичайних функцій! Це означає, що при виклику `perimeter` значення `this` у цій функції вказує не на об'єкт `shape`, а на зовнішню область видимості (наприклад, window). У цього об'єкта немає ключа `radius`, тому повертається `undefined`. @@ -179,7 +179,7 @@ JavaScript інтерпретує (або розпаковує) оператор `mouse[bird.size]`: Спершу визначається `bird.size`, що дорівнює `"small"`. `mouse["small"]` повертає `true`. -Але із записом через точку так не відбувається. У `mouse` немає ключа `bird`. Таким чином, `mouse.bird` дорівнює `undefined`. Потім ми запитуємо ключ `size`, використовуючи точкову нотацію: `mouse.bird.size`. Так як `mouse.bird` це `undefined`, ми запитуємо `undefined.size`. Це не є дійсним, і ми отримуємо помилку типу: `Can not read property "size" of undefined`. +Але із записом через крапку так не відбувається. У `mouse` немає ключа `bird`. Таким чином, `mouse.bird` дорівнює `undefined`. Потім ми запитуємо ключ `size`, використовуючи крапкову нотацію: `mouse.bird.size`. Так як `mouse.bird` це `undefined`, ми запитуємо `undefined.size`. Це не є дійсним, тому ми отримуємо помилку типу: `Can not read property "size" of undefined`.

@@ -306,9 +306,9 @@ console.log(greetign); #### Відповідь: A -В консолі виведеться об'єкт, тому що ми тільки що створили порожній об'єкт в глобальному об'єкті! Коли ми замість `greeting` написали `greetign`, інтерпретатор JS насправді виконав `global.greetign = {}` (або `window.greetign = {}` в браузері). +В консолі виведеться об'єкт, тому що ми щойно створили порожній об'єкт в глобальному об'єкті! Коли ми замість `greeting` написали `greetign`, інтерпретатор JS насправді виконав `global.greetign = {}` (або `window.greetign = {}` в браузері). -Потрібно використовувати `"use strict"`, щоб уникнути такої поведінки. Ця запис допоможе бути впевненим в тому, що змінна була визначена перед тим як їй присвоїли значення. +Потрібно використовувати `"use strict"`, щоб уникнути такої поведінки. Цей запис допоможе бути впевненим в тому, що змінна була визначена перед тим як їй присвоїли значення.

@@ -370,7 +370,7 @@ console.log(member.getFullName()); #### Відповідь: A -Не можна додавати властивості конструктору, як звичайному об'єкту. Якщо потрібно додати фичу всіх об'єктах, то необхідно використовувати прототипи. В даному випадку, +Не можна додавати властивості конструктору, як звичайному об'єкту. Якщо потрібно додати фічу до всіх об'єктів, то необхідно використовувати прототипи. В даному випадку, ```js Person.prototype.getFullName = function() { @@ -431,7 +431,7 @@ console.log(sarah); #### Відповідь: D -Під час фази **захоплення** подія поширюється з елементів батьків до елемента мети. Після досягнення **мети** починається фаза **спливання**. +Під час фази **захоплення** подія поширюється від батьківського елемента до елемента мети. Після досягнення **мети** починається фаза **спливання**. @@ -440,7 +440,7 @@ console.log(sarah); --- -###### 14. Все объекты имеют прототипы? +###### 14. Всі об'єкти мають прототипи? - A: Так - B: Ні @@ -479,7 +479,7 @@ sum(1, "2"); JavaScript це **динамічно тіпізірованна мова**: ми не визначаємо тип змінних. Змінні можуть автоматично бути перетворені з одного типу в інший без нашої участі, що називається _неявним приведенням типів_. **Приведення** це перетворення з одного типу в інший. -У цьому прикладі, JavaScript конвертувати число `1` в рядок, щоб операція усередині функції мала сенс і повернула значення. Під час складання числа (`1`) і рядки (`'2'`) число перетворюється до рядка. Ми можемо конкатеніровать рядки ось так: `"Hello" + "World"`. Таким чином, "`1"` + `"2"` повертає "`12"`. +У цьому прикладі, JavaScript конвертувати число `1` в рядок, щоб операція всередині функції мала сенс і повернула значення. Під час складання числа (`1`) і рядки (`'2'`) число перетворюється до рядка. Ми можемо додавати рядки ось так: `"Hello" + "World"`. Таким чином, "`1"` + `"2"` повертає "`12"`.

@@ -512,8 +512,8 @@ console.log(number); **Префіксний** унарний оператор `++`: -1. Інкрементує значення (тепер число дорівнює `1`) -2. Повертає значення (`0`) +1. Інкрементує значення (тепер число дорівнює `2`) +2. Повертає значення (`2`) Результат: `0 2 2`. @@ -546,7 +546,7 @@ getPersonInfo`${person} is ${age} years old`; #### Відповідь: B -При використанні тегованих шаблонних литералов першим аргументом завжди буде масив строкових значень. Залишилися аргументами будуть значення переданих виразів! +При використанні тегованих шаблонних літералів першим аргументом завжди буде масив строкових значень. Решта аргументів будуть значення мати переданих виразів!

@@ -578,9 +578,9 @@ checkAge({ age: 18 }); #### Відповідь: C -В операціях порівняння примітиви порівнюються за їх _значенням_, а об'єкти по _посиланнях_. JavaScript перевіряє, щоб об'єкти вказували на одну і ту ж область пам'яті. +В операціях порівняння примітиви порівнюються за їх _значенням_, а об'єкти за _посиланнями_. JavaScript перевіряє, щоб об'єкти вказували на одну і ту ж область пам'яті. -Порівнянні об'єкти в нашому прикладі не такі: об'єкт, переданий як параметр, вказує на іншу область пам'яті, ніж об'єкти, що використовуються в порівняннях. +Порівнювані об'єкти в нашому прикладі не такі: об'єкт, переданий як параметр, вказує на іншу область пам'яті, ніж об'єкти, що використовуються в порівнянні. Тому `{age: 18} === {age: 18}` і `{age: 18} == {age: 18}` повертають `false`. @@ -661,7 +661,7 @@ const sum = eval("10*10+5"); #### Відповідь: A -`eval` виконує код, переданий у вигляді рядка. Якщо цей вислів (як в даному випадку), то обчислюється вираз. Вираз `10 * 10 + 5` поверне число `105`. +`eval` виконує код, переданий у вигляді рядка. Якщо це рядок (як в даному випадку), то обчислюється вираз. Вираз `10 * 10 + 5` поверне число `105`.

@@ -712,7 +712,7 @@ console.log(num); #### Відповідь: B -За допомогою ключового слова `var`, можна визначати скільки завгодно змінних з одним і тим же ім'ям. Змінна зберігатиме останнім присвоєне значення. +За допомогою ключового слова `var`, можна визначати скільки завгодно змінних з одним і тим же ім'ям. Змінна зберігатиме останнє присвоєне значення. Ви не можете зробити це з `let` або` const`, оскільки вони блочні. @@ -769,7 +769,7 @@ console.log(obj); #### Відповідь: C -Якщо є два ключі з однаковим ім'ям, то ключ буде перезаписан. Його позиція збережеться, але значенням буде встановлено останнім. +Якщо є два ключі з однаковим ім'ям, то ключ буде перезаписаний. Його позиція збережеться, але значенням буде встановлено останнім.

@@ -905,7 +905,7 @@ baz(); #### Відповідь: B -Ми викликаємо функцію `setTimeout` першої. Тим не менш, вона виводиться в консоль останньої +Ми викликаємо функцію `setTimeout` першою. Тим не менш, вона виводиться в консоль останньою. Це відбувається через те, що в браузерах у нас є не тільки рантайм движок, але і `WebAPI`. `WebAPI` надає нам функцію `setTimeout` і багато інших можливостей. Наприклад, DOM. @@ -1171,7 +1171,7 @@ console.log(numbers); Блок `catch` отримує аргумент `x`. Це не той же `x`, який визначено в якості змінної перед рядком `try`. -Потім ми присвоюємо цього аргументу значення `1` та встановлюємо значення для змінної `y`. Потім виводимо в консоль значення аргументу `x`, що дорівнює `1`. +Потім ми присвоюємо даному аргументу значення `1` та встановлюємо значення для змінної `y`. Потім виводимо в консоль значення аргументу `x`, що дорівнює `1`. За межами блоку `catch` змінна `x` все ще `undefined`, а `y` дорівнює `2`. Коли ми викликаємо` console.log(x)` за межами блоку `catch`, цей виклик повертає `undefined`, а `y` повертає `2`. @@ -1224,7 +1224,7 @@ console.log(numbers); #### Відповідь: 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]`. Потім `acc` дорівнює `[1, 2, 0, 1]`, а cur `[2, 3]`. Після злиття отримаємо `[1, 2, 0, 1, 2, 3]`. @@ -1278,7 +1278,7 @@ setInterval(() => console.log("Hi"), 1000); #### Відповідь: A -Це метод повертає унікальний id. Цей id може бути використаний для очищення інтервалу за допомогою функції `clearInterval()`. +Цей метод повертає унікальний id, який може бути використаний для очищення інтервалу за допомогою функції `clearInterval()`.

@@ -1301,7 +1301,7 @@ setInterval(() => console.log("Hi"), 1000); #### Відповідь: A -Рядок є ітеріруемой сутністю. Оператор поширення перетворює кожен символ в окремий елемент. +Рядок є ітерабельною сутністю. Оператор поширення перетворює кожен символ в окремий елемент.

From e789f67fa80ef9ce622e624a0d20711329da97da Mon Sep 17 00:00:00 2001 From: Alexey Ryabov Date: Sat, 14 Nov 2020 10:15:54 +0300 Subject: [PATCH 722/915] Fix code example for Q.17 (eng) --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 47ba81d6..4b7ea9a3 100644 --- a/README.md +++ b/README.md @@ -551,7 +551,7 @@ function getPersonInfo(one, two, three) { const person = 'Lydia'; const age = 21; -getPersonInfo(`${person} is ${age} years old`); +getPersonInfo`${person} is ${age} years old`; ``` - A: `"Lydia"` `21` `["", " is ", " years old"]` From 817694aaa3e67c3c05c263d1e64c1ef872120365 Mon Sep 17 00:00:00 2001 From: Glen Padua Date: Thu, 10 Dec 2020 05:53:50 +0530 Subject: [PATCH 723/915] 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 724/915] 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 725/915] 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 726/915] 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 727/915] 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 728/915] 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 729/915] 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 730/915] 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 731/915] 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 732/915] 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 733/915] 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 734/915] 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 735/915] 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 736/915] 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 737/915] 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 738/915] 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 739/915] 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 740/915] 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 741/915] 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 742/915] 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 743/915] 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 744/915] 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 745/915] 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 746/915] 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 747/915] 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 748/915] 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 749/915] 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 750/915] 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 751/915] 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 752/915] 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 753/915] 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 754/915] 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 755/915] 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 756/915] 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 757/915] 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 758/915] 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 759/915] 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 760/915] =?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 761/915] =?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 762/915] =?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 763/915] 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 764/915] =?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 765/915] 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 766/915] 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 767/915] 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 768/915] 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 769/915] 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 770/915] 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 771/915] 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 772/915] 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 773/915] 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 774/915] 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 775/915] 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 776/915] 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 777/915] 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 778/915] 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 779/915] 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 780/915] 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 781/915] 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 782/915] 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 783/915] 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 784/915] 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 785/915] 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 786/915] 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 787/915] 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 788/915] 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 789/915] 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 790/915] 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 791/915] 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 792/915] 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 793/915] 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 794/915] 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 795/915] 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 796/915] =?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 797/915] 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 798/915] 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 799/915] 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 800/915] 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 801/915] 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 802/915] 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 803/915] 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 804/915] 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 805/915] 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 806/915] 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 807/915] 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 808/915] 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 809/915] 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 810/915] 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 811/915] 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 812/915] 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 813/915] 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 814/915] 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 815/915] 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 816/915] 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 817/915] 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 818/915] 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 819/915] 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 820/915] 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 821/915] 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 822/915] 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 823/915] 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 824/915] 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 825/915] 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 826/915] 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 827/915] 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 828/915] 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 829/915] =?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 830/915] 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 831/915] 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 832/915] 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 833/915] 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 834/915] 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 835/915] 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 836/915] 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 837/915] 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 838/915] 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 839/915] 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 840/915] 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 841/915] 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 842/915] 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 843/915] 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 844/915] 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 845/915] 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 846/915] 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 847/915] 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 848/915] 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 849/915] 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 850/915] 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 851/915] =?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 852/915] 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 853/915] 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 854/915] 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 855/915] 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 856/915] 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 857/915] :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 858/915] :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 859/915] 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 860/915] 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 861/915] 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 862/915] 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 863/915] 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 864/915] 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 865/915] 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 866/915] 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 867/915] 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 868/915] 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 869/915] #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 870/915] 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 871/915] 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 872/915] 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 873/915] 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 874/915] 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 875/915] 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 876/915] 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 877/915] 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 878/915] 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 879/915] 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 880/915] 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 881/915] 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 882/915] 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 883/915] 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 884/915] 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 885/915] 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 886/915] 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 887/915] 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 888/915] 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 889/915] 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 890/915] 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 891/915] 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 892/915] 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 893/915] 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 894/915] 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 895/915] 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 896/915] 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 897/915] 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 898/915] 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 899/915] 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 900/915] 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 901/915] 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 902/915] 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 903/915] 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 904/915] 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 905/915] 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 906/915] 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 907/915] 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 908/915] 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 909/915] 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 910/915] 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 911/915] 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 912/915] 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 913/915] 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 914/915] 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 915/915] 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 +