Ответ
-#### 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 b> summary>
-#### 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`.
-
+ details>
----
+* * * * *
-###### 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 b> summary>
+
-#### 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.
-
-
+ p>
+ details>
----
+* * * * *
-###### 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 b> summary>
+
-#### 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`.
-
-
+ p>
+ details>
----
+* * * * *
-###### 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 b> summary>
+
-#### 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".
-
-
+ p>
+ details>
----
+* * * * *
-###### 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 b> summary>
+
-#### 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`.
-
-
+ P>
+ details>
----
+* * * * *
----
+* * * * *
-###### 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 b> summary>
+
-#### 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.
-
-
+ p>
+ details>
----
+* * * * *
-###### 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 b> summary>
+
-#### 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"
-
-
+ P>
+ details>
----
+* * * * *
-###### 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 b> summary>
+
-#### 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`.
-
-
+ P>
+ details>
----
+* * * * *
-###### 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 b> summary>
+
-#### 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.
-
-
+ P>
+ details>
----
+* * * * *
-###### 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 b> summary>
+
-#### 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.
-
-
+ P>
+ details>
----
+* * * * *
-###### 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 b> summary>
+
-#### 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!
-
-
+ P>
+ details>
----
+* * * * *
-###### 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 b> summary>
+
-#### 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'.
-
-
+ P>
+ details>
----
+* * * * *
-###### 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 b> summary>
+
-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 **.
-
-
+
----
+ P>
+ details>
-###### 14. All object have prototypes.
+* * * * *
-- A: true
-- B: false
+###### 14. Svi objekti imaju prototipove.
-Answer
-
+- Istinito
+- B: lažno
-#### Answer: B
+ Odgovor b> summary>
+
-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.
----
+ P>
+ details>
-###### 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 b> summary>
+
-#### 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 "`.
-
-
+ P>
+ details>
----
+* * * * *
-###### 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 b> summary>
+
-#### 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`.
-
-
+ P>
+ details>
----
+* * * * *
-###### 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 b> summary>
+
-#### 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!
-
-
+ P>
+ details>
----
+* * * * *
-###### 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 b> summary>
+
-#### 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 '.
-
-
+ P>
+ details>
----
+* * * * *
-###### 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 b> summary>
+
-#### 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 '`
-
-
+ P>
+ details>
----
+* * * * *
-###### 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 b> summary>
+
-#### 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.
-
-
+ P>
+ details>
----
+* * * * *
-###### 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 b> summary>
+
-#### 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".
-
-
+ P>
+ details>
----
+* * * * *
-###### 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 b> summary>
+
-#### 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.
-
-
+ P>
+ details>
----
+* * * * *
-###### 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 b> summary>
+
-#### 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.
-
-
+ P>
+ details>
----
+* * * * *
-###### 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 b> summary>
+
-#### 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`.
-
-
+ P>
+ details>
----
+* * * * *
-###### 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 b> summary>
+
-#### 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.
-
-
+ P>
+ details>
----
+* * * * *
-###### 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 b> summary>
+
-#### 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.
-
-
+ P>
+ details>
----
+* * * * *
-###### 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 b> summary>
+
-#### 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".
-
-
+ P>
+ details>
----
+* * * * *
-###### 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 b> summary>
+
-#### 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!
-
-
+ P>
+ details>
----
+* * * * *
-###### 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 b> summary>
+
-#### 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`.
-
-
+ P>
+ details>
----
+* * * * *
-###### 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 b> summary>
+
-#### 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.
-
-
+ P>
+ details>
----
+* * * * *
-###### 31. What is the event.target when clicking the button?
+###### 31. Što je event.target kada kliknete na gumb?
-```html
-
-```
+`` `{.html}
+
+
+
+ Klik!
+ Tipka>
+ Div>
+ Div>
+`` `
-- A: Outer `div`
-- B: Inner `div`
-- C: `button`
-- D: An array of all nested elements.
+- A: Vanjski 'div'
+- B: Unutarnji 'div'
+- C: `gumb '
+- D: Niz svih ugniježđenih elemenata.
-Answer
-
+ Odgovor b> summary>
+
-#### Answer: C
+#### Odgovor: C
-The deepest nested element that caused the event is the target of the event. You can stop bubbling by `event.stopPropagation`
+Najdublji ugniježđeni element koji je uzrokovao događaj je cilj
+događaj. Možete zaustaviti mjehuriće 'event.stopPropagation'
-
-
+ P>
+ details>
----
+* * * * *
-###### 32. When you click the paragraph, what's the logged output?
+###### 32. Kada kliknete na paragraf, što je zapisani izlaz?
-```html
-
-```
+`` `{.html}
+
+
+ Kliknite ovdje!
+ P>
+ Div>
+`` `
-- A: `p` `div`
-- B: `div` `p`
-- C: `p`
-- D: `div`
+- A: `p`` div`
+- B: `div`` p`
+- C: p
+- D: "div"
-Answer
-
+ Odgovor b> summary>
+
-#### Answer: A
+#### Odgovor: 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.
+Ako kliknemo `p`, vidimo dva zapisa:` p` i `div`. Tijekom događaja
+razmnožavanje, postoje 3 faze: hvatanje, ciljanje i mjehuriće. Po
+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.
-
-
+ P>
+ details>
----
+* * * * *
-###### 33. What's the output?
+###### 33. Što je izlaz?
-```javascript
-const person = { name: "Lydia" };
+`` `{.javascript}
+const Person = {ime: "Lydia"};
-function sayHi(age) {
- console.log(`${this.name} is ${age}`);
+function sayHi (dob) {
+ console.log (`$ {this.name} je $ {age}`);
}
-sayHi.call(person, 21);
-sayHi.bind(person, 21);
-```
+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 je 21`
+- B: function funkcije
+- C: `Lydia je 21`` Lydia je 21`
+- D: `Lydia je 21`` function`
-Answer
-
+ Odgovor b> summary>
+
-#### Answer: D
+#### Odgovor: D
-With both, we can pass the object to which we want the `this` keyword to refer to. However, `.call` is also _executed immediately_!
+S oba, možemo proslijediti objekt kojem želimo ključnu riječ "this"
+odnosi se na. Međutim, `.call` se također * izvršava odmah *!
-`.bind.` returns a _copy_ of the function, but with a bound context! It is not executed immediately.
+`.bind.` vraća * copy * funkcije, ali s vezanim kontekstom! To
+se ne izvršava odmah.
-
-
+ P>
+ details>
----
+* * * * *
-###### 34. What's the output?
+###### 34. Što je izlaz?
-```javascript
-function sayHi() {
- return (() => 0)();
+`` `{.javascript}
+function sayHi () {
+ return (() => 0) ();
}
-typeof sayHi();
-```
+vrsta rečiHi ();
+`` `
-- A: `"object"`
-- B: `"number"`
-- C: `"function"`
-- D: `"undefined"`
+- A: `" objekt "`
+- B: `" broj "
+- C: function ""
+- D: `" undefined "`
-Answer
-
+ Odgovor b> summary>
+
-#### Answer: B
+#### Odgovor: B
-The `sayHi` function returns the returned value of the immediately invoked function (IIFE). This function returned `0`, which is type `"number"`.
+function `sayHi` vraća vraćenu vrijednost odmah
+pozvana function (IIFE). Ova function vratila je `0`, što je tip
+` "Broj"`.
-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: 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 '`.
-
-
+ P>
+ details>
----
+* * * * *
-###### 35. Which of these values are falsy?
+###### 35. Koja od ovih vrijednosti su neistinite?
-```javascript
+`` `{.javascript}
0;
-new Number(0);
+new broj (0);
+( "");
("");
-(" ");
-new Boolean(false);
-undefined;
-```
+new logički (false);
+nedefiniran;
+`` `
-- 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: `0`,` `` `,` undefined`
+- B: `0`,` new Number (0) `,` '' `,` new Boolean (false) `,` undefined '
+- C: `0`,` '' `,` new Boolean (false) `,` undefined`
+- D: Svi su oni lažni
-Answer
-
+ Odgovor b> summary>
+
-#### Answer: A
+#### Odgovor: A
-There are only six falsy values:
+Postoji samo šest krivotvorenih vrijednosti:
- `undefined`
-- `null`
-- `NaN`
+- "null"
+- "NaN"
- `0`
-- `''` (empty string)
-- `false`
+- `''` (prazan niz)
+- "false"
-Function constructors, like `new Number` and `new Boolean` are truthy.
+Konstruktori function, kao što su 'new Number' i 'new Boolean' su istiniti.
-
-
+ P>
+ details>
----
+* * * * *
-###### 36. What's the output?
+###### 36. Što je izlaz?
-```javascript
-console.log(typeof typeof 1);
-```
+`` `{.javascript}
+console.log (vrsta tipa 1);
+`` `
-- A: `"number"`
-- B: `"string"`
-- C: `"object"`
-- D: `"undefined"`
+- A: `" broj "
+- B: niz ""
+- C: `` objekt ''
+- D: `" undefined "`
-Answer
-
+ Odgovor b> summary>
+
-#### Answer: B
+#### Odgovor: B
-`typeof 1` returns `"number"`.
-`typeof "number"` returns `"string"`
+`typeof 1` vraća` `broj ''. `typeof" number "` return `` string "`
-
-
+ P>
+ details>
----
+* * * * *
-###### 37. What's the output?
+###### 37. Što je izlaz?
-```javascript
-const numbers = [1, 2, 3];
-numbers[10] = 11;
-console.log(numbers);
-```
+`` `{.javascript}
+const brojevi = [1, 2, 3];
+brojevi [10] = 11;
+console.log (br);
+`` `
- A: `[1, 2, 3, 7 x null, 11]`
- B: `[1, 2, 3, 11]`
-- C: `[1, 2, 3, 7 x empty, 11]`
+- C: `[1, 2, 3, 7 x prazno, 11]`
- D: `SyntaxError`
-Answer
-
+ Odgovor b> summary>
+
-#### Answer: C
+#### Odgovor: 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:
+Kada postavite vrijednost na element u nizu koji premašuje duljinu
+iz niza, JavaScript stvara nešto što se naziva "prazni utori". To
+zapravo imaju vrijednost `undefined`, ali vidjet ćete nešto poput:
-`[1, 2, 3, 7 x empty, 11]`
+`[1, 2, 3, 7 x prazno, 11]`
-depending on where you run it (it's different for every browser, node, etc.)
+ovisno o tome gdje ga pokrećete (razlikuje se za svaki preglednik, čvor,
+itd)
-
-
+ P>
+ details>
----
+* * * * *
-###### 38. What's the output?
+###### 38. Što je izlaz?
-```javascript
+`` `{.javascript}
(() => {
let x, y;
- try {
- throw new Error();
+ pokušaj {
+ baciti novu pogrešku ();
} 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`
-- 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`
-Answer
-
+ Odgovor b> summary>
+
-#### Answer: A
+#### Odgovor: 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.
+Blok `catch` prima argument` x`. To nije isti `x` kao
+varijablu kada proslijedimo argumente. Ova varijabla `x` je blokirana.
-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`.
+Kasnije smo postavili ovu varijablu bloka koja je jednaka `1` i postavili vrijednost
+varijable `y '. Sada, zapisujemo blok-scoped varijablu `x`, koja je
+jednako "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`.
+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`.
-
-
+ P>
+ details>
----
+* * * * *
-###### 39. Everything in JavaScript is either a...
+###### 39. Sve u JavaScriptu je ili ...
-- A: primitive or object
-- B: function or object
-- C: trick question! only objects
-- D: number or object
+- A: primitivni ili objektni
+- B: function ili objekt
+- C: trik pitanje! samo objekti
+- D: broj ili objekt
-Answer
-
+ Odgovor b> summary>
+
-#### Answer: A
+#### Odgovor: A
-JavaScript only has primitive types and objects.
+JavaScript ima samo primitivne tipove i objekte.
-Primitive types are `boolean`, `null`, `undefined`, `bigint`, `number`, `string`, and `symbol`.
+Primitivni tipovi su "boolean", "null", "undefined", "bigint", "number",
+'string' i 'simbol'.
-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.
+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
+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
+osim "null" i "undefined" pokazuju ovo ponašanje.
-
-
+ P>
+ details>
----
+* * * * *
-###### 40. What's the output?
+###### 40. Što je izlaz?
-```javascript
-[[0, 1], [2, 3]].reduce(
+`` `{.javascript}
+[[0, 1], [2, 3]].
(acc, cur) => {
- return acc.concat(cur);
- },
+ povratak acc.concat (cur);
+ }
[1, 2]
);
-```
+`` `
- A: `[0, 1, 2, 3, 1, 2]`
- B: `[6, 1, 2]`
-- C: `[1, 2, 0, 1, 2, 3]`
+- C: "[1, 2, 0, 1, 2, 3]"
- D: `[1, 2, 6]`
-Answer
-
+ Odgovor b> summary>
+
-#### Answer: C
+#### Odgovor: 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]" 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
+`[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]`
+Tada je `[1, 2, 0, 1]` `acc` i` [2, 3] `` `` `. Ulančavamo se
+i dobiti `[1, 2, 0, 1, 2, 3]`
-
-
+ P>
+ details>
----
+* * * * *
-###### 41. What's the output?
+###### 41. Što je izlaz?
-```javascript
-!!null;
-!!"";
-!!1;
-```
+`` `{.javascript}
+!! null;
+!! "";
+!! 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`
-Answer
-
+ Odgovor b> summary>
+
-#### Answer: B
+#### Odgovor: B
-`null` is falsy. `!null` returns `true`. `!true` returns `false`.
+`null` je lažan. `! null` vraća 'true'. `! true 'vraća" false ".
-`""` is falsy. `!""` returns `true`. `!true` returns `false`.
+`` `` je neistinit. `!" `` vraća `true '. `! true 'vraća" false ".
-`1` is truthy. `!1` returns `false`. `!false` returns `true`.
+"1" je istina. `! 1` vraća 'false'. `! false 'vraća' true '.
-
-
+ P>
+ details>
----
+* * * * *
-###### 42. What does the `setInterval` method return?
+###### 42. Što se vraća metoda `setInterval`?
-```javascript
-setInterval(() => console.log("Hi"), 1000);
-```
+`` `{.javascript}
+setInterval (() => console.log ("Hi"), 1000);
+`` `
-- A: a unique id
-- B: the amount of milliseconds specified
-- C: the passed function
+- A: jedinstveni ID
+- B: određena količina milisekundi
+- C: prošla function
- D: `undefined`
-Answer
-
+ Odgovor b> summary>
+
-#### Answer: A
+#### Odgovor: A
-It returns a unique id. This id can be used to clear that interval with the `clearInterval()` function.
+Vraća jedinstveni ID. Taj se ID može koristiti za brisanje tog intervala
+`clearInterval ()` function.
-
-
+ P>
+ details>
----
+* * * * *
-###### 43. What does this return?
+###### 43. Što se to vraća?
-```javascript
-[..."Lydia"];
-```
+`` `{.javascript}
+[... "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 "]]`
-Answer
-
+ Odgovor b> summary>
+
-#### Answer: A
+#### Odgovor: A
-A string is an iterable. The spread operator maps every character of an iterable to one element.
+Niz je iterabilan. Operator širenja mapira svaki znak
+iterabilan na jedan element.
-
-
+ P>
+ details>
From ee5cf9b6e9bea0fe350006aaa176a664312e925b Mon Sep 17 00:00:00 2001
From: nedimf <24845593+nedimf@users.noreply.github.com>
Date: Tue, 18 Jun 2019 19:52:12 +0200
Subject: [PATCH 018/915] Update README.md
---
README.md | 184 +++++++++++++++++++++++++++---------------------------
1 file changed, 92 insertions(+), 92 deletions(-)
diff --git a/README.md b/README.md
index 3c980a03..a7d855b2 100644
--- a/README.md
+++ b/README.md
@@ -1,24 +1,24 @@
-Popis (naprednih) JavaScript pitanja
+# 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
-znanje malo, ili pripremiti za svoj intervju! : :: rocket:
-Ovaj tjedni repo ažuriram s newm pitanjima.
+znanje malo, ili pripremiti za svoj intervju! :muscle: :rocket:
+Ovaj tjedni repo ažuriram s novim pitanjima.
Odgovori su jednostavno dijelovima ispod pitanja
-kliknite na njih da biste ih proširili. Sretno: srce:
+kliknite na njih da biste ih proširili. Sretno :heart:
-[中文 版本] (./ README-zh_CN.md)
+[中文版本](./README-zh_CN.md)
* * * * *
###### 1. Što je izlaz?
-`` `{.javascript}
+```javascript
function sayHi () {
console.log (ime);
console.log (starosti);
@@ -27,14 +27,14 @@ function sayHi () {
}
sayHi();
-`` `
+```
- A: "Lydia" i "undefined"
- B: "Lydia" i "ReferenceError"
- C: "ReferenceError" i "21"
- D: `undefined` i` ReferenceError`
- Odgovor b> summary>
+Odgovor
#### Odgovor: D
@@ -53,13 +53,13 @@ Kada pokušamo pristupiti varijablama prije nego što budu deklarirane,
JavaScript iz bacuje `ReferenceError`.
- details>
+
* * * * *
###### 2. Što je izlaz?
-`` `{.javascript}
+```javascript
za (var i = 0; i <3; i ++) {
setTimeout (() => console.log (i), 1);
}
@@ -67,7 +67,7 @@ za (var i = 0; i <3; i ++) {
za (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"
@@ -98,7 +98,7 @@ block-scoped (blok je sve između `{}`). Tijekom svake iteracije,
###### 3. Što je izlaz?
-`` `{.javascript}
+```javascript
const oblik = {
radijus: 10,
promjer() {
@@ -109,7 +109,7 @@ const oblik = {
oblik.radijus ();
oblik.promjer ();
-`` `
+```
- A: "20" i "62.83185307179586"
- B: "20" i "NaN"
@@ -138,10 +138,10 @@ Na tom objektu nema vrijednosti `radius` koja vraća` undefined`.
###### 4. Što je izlaz?
-`` `{.javascript}
+```javascript
+ True;
! "Lydia";
-`` `
+```
- A: "1" i "false"
- B: "false" i "NaN"
@@ -165,7 +165,7 @@ Niz '' Lydia '' je istinita vrijednost. Ono što zapravo tražimo jest
###### 5. Koja je istina?
-`` `{.javascript}
+```javascript
const bird = {
size: "small"
};
@@ -174,7 +174,7 @@ const mouse = {
ime: "Mickey",
small: true
};
-`` `
+```
- A: `mouse.bird.size 'nije valjan
- B: `mouse [bird.size]` nije važeća
@@ -191,7 +191,7 @@ 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 otvarnu zagradu ```i nastavlja dalje do nje
pronalazi završnu zagradu `]`. Tek tada će procijeniti
izjava.
@@ -214,14 +214,14 @@ To nije valjano, a bit će u pitanju pogreška slična onoj
###### 6. Što je izlaz?
-`` `{.javascript}
+```javascript
let c = {greeting: "Hej!" };
let d;
d = c;
c.greeting = "Pozdrav";
console.log (d.greeting);
-`` `
+```
- A: "Zdravo"
- B: 'Hej'
@@ -251,7 +251,7 @@ Kada promijenite jedan objekt, mijenjate ih sve.
###### 7. Što je izlaz?
-`` `{.javascript}
+```javascript
let je a = 3;
let je b = new broj (3);
let je c = 3;
@@ -259,7 +259,7 @@ let je c = 3;
console.log (a == b);
console.log (a === b);
console.log (b === c);
-`` `
+```
- A: `true`` false` `true`
- B: `false`` false` `true`
@@ -328,11 +328,11 @@ Izbačen je `TypeError`.
###### 9. Što je izlaz?
-`` `{.javascript}
+```javascript
let pozdravi;
greeting = {}; // Typo!
console.log (greetign);
-`` `
+```
- A: `{}`
- B: `ReferenceError: greetign nije definiran '
@@ -390,7 +390,7 @@ Ova nekretnina je nepovratna.
###### 11. Kakav je rezultat?
-`` `{.javascript}
+```javascript
function Person (ime, prezime) {
this.ime = ime;
this.prezime = prezime;
@@ -402,7 +402,7 @@ Person.getFullName = function () {
};
console.log (member.getFullName ());
-`` `
+```
- A: `TypeError`
- B: `SyntaxError`
@@ -418,11 +418,11 @@ 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}
+```{.js}
Person.prototype.getFullName = function () {
return `$ {this.ime} $ {this.prezime}`;
};
-`` `
+```
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
@@ -438,7 +438,7 @@ scopa za svaku instancu. Umjesto toga, ako ga samo dodamo prototipu, mi
###### 12. Što je izlaz?
-`` `{.javascript}
+```javascript
function Person (ime, prezime) {
this.ime = ime;
this.prezime = prezime;
@@ -449,7 +449,7 @@ const sarah = Person ("Sara", "Smith");
console.log (Lydia);
console.log (sarah);
-`` `
+```
- A: `Person {ime:" Lydia ", prezime:" Hallie "} i` undefined`
- B: `Person {ime:" Lydia ", prezime:" Hallie "} i
@@ -525,13 +525,13 @@ nalazi ga tamo, što ga čini dostupnim.
###### 15. Što je izlaz?
-`` `{.javascript}
+```javascript
function sum (a, b) {
return a + b;
}
sum (1, "2");
-`` `
+```
- A: "NaN"
- B: `TypeError`
@@ -552,7 +552,7 @@ 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 `` `` `` `` `` `` `` `` ``
+"" Zdravo "+" Svijet "`, tako da se ovdje događa ``````````````````
vraća `" 12 "`.
P>
@@ -562,12 +562,12 @@ vraća `" 12 "`.
###### 16. Što je izlaz?
-`` `{.javascript}
+```javascript
let je broj = 0;
console.log (broj ++);
console.log (++ broj);
console.log (broj);
-`` `
+```
- A: `1`` 1` `2`
- B: `1`` 2` `2`
@@ -598,7 +598,7 @@ Ovo vraća `0 2 2`.
###### 17. Što je izlaz?
-`` `{.javascript}
+```javascript
function getPersonInfo (one, two, tree) {
console.log (one);
console.log (two);
@@ -609,11 +609,11 @@ const Person = "Lydia";
const age = 21;
getPersonInfo` $ {Person} je $ {old} godina ';
-`` `
+```
-- A: `` Lydia` `` `` `` `` `` `` `` `` `` `` `` `` `` `` `` `` `` `` ``
-- B: `` `` `` `` `` `` `` `` `` `` `` `` `` `` `` `` `` `` `` `` `` `` `` `` `` `` `` `` `` `` `` `` `` `` `` `` `` `
-- C: `` Lydia` `` `` `` `` `` `` `` `` `` `` `` `` `` `` `` `` `` `` `` `` `` `` `` `` `` `` `` `` ``
+- A: `` Lydia` ``````````````````````````````````````
+- B: ```````````````````````````````````````````````````````````````````````````
+- C: `` Lydia` ``````````````````````````````````````````````````````````
Odgovor b> summary>
@@ -631,7 +631,7 @@ vrijednosti prošlih izraza!
###### 18. Što je izlaz?
-`` `{.javascript}
+```javascript
function checkAge (podaci) {
ako (podaci === {age: 18}) {
console.log ("Vi ste odrasla osoba!");
@@ -643,7 +643,7 @@ function checkAge (podaci) {
}
checkAge ({age: 18});
-`` `
+```
- A: "Vi ste odrasla osoba!"
- B: "Vi ste još uvijek odrasla osoba."
@@ -672,13 +672,13 @@ Zato i `{age: 18} === {age: 18}` i
###### 19. Što je izlaz?
-`` `{.javascript}
+```javascript
function getAge (... args) {
console.log (vrsta argumenta);
}
getAge (21);
-`` `
+```
- A: `" broj "
- B: `` niz ''
@@ -700,7 +700,7 @@ array je objekt, pa `typeof args` vraća` `objekt '`
###### 20. Što je izlaz?
-`` `{.javascript}
+```javascript
function getAge () {
"koristite strogi";
starost = 21;
@@ -708,7 +708,7 @@ function getAge () {
}
getAge ();
-`` `
+```
- A: `21`
- B: `undefined`
@@ -733,9 +733,9 @@ nije koristio "" strict ", to bi išlo od vlasništva
###### 21. Što je vrijednost `suma '?
-`` `{.javascript}
+```javascript
const sum = eval ("10x10 + 5");
-`` `
+```
- A: "105"
- B: `" 105 "`
@@ -758,9 +758,9 @@ kao u ovom slučaju, on ocjenjuje izraz. Izraz je
###### 22. Koliko dugo je cool \ _secret dostupan?
-`` `{.javascript}
+```javascript
sessionStorage.setItem ("cool_secret", 123);
-`` `
+```
O: Podaci se zauvijek ne izgube.
- B: Kada korisnik zatvori karticu.
@@ -784,12 +784,12 @@ na primjer, `localStorage.clear ()` je pozvan.
###### 23. Što je izlaz?
-`` `{.javascript}
+```javascript
var num = 8;
var num = 10;
console.log (num);
-`` `
+```
- A: `8`
- B: "10"
@@ -813,7 +813,7 @@ To ne možete učiniti s `let` ili` const` jer su blokirani.
###### 24. Što je izlaz?
-`` `{.javascript}
+```javascript
const obj = {1: "a", 2: "b", 3: "c"};
const set = new Set ([1, 2, 3, 4, 5]);
@@ -821,7 +821,7 @@ obj.hasOwnProperty ( "1");
obj.hasOwnProperty (1);
set.has ( "1");
set.has (1);
-`` `
+```
- A: `false`` true` `false`` true`
- B: `false`` true` `true`` true`
@@ -848,10 +848,10 @@ To ne radi tako za skup. U našem setu ne postoji "1":
###### 25. Što je izlaz?
-`` `{.javascript}
+```javascript
const obj = {a: "jedan", b: "dva", a: "tri"};
console.log (obj);
-`` `
+```
- A: `{a:" jedan ", b:" dva "}`
- B: `{b:" dva ", a:" tri "}`
@@ -892,12 +892,12 @@ dostupno svugdje u vašem kodu.
###### 27. Što je izlaz?
-`` `{.javascript}
+```javascript
za (let i = 1; i <5; i ++) {
ako (i === 3) nastavite;
console.log (i);
}
-`` `
+```
- A: `1`` 2`
- B: `1`` 2` `3`
@@ -919,7 +919,7 @@ vraća "true".
###### 28. Što je izlaz?
-`` `{.javascript}
+```javascript
String.prototype.giveLydiaPizza = () => {
povratak "Dajte već picu Lydiju!";
};
@@ -927,7 +927,7 @@ String.prototype.giveLydiaPizza = () => {
const ime = "Lydia";
name.giveLydiaPizza ();
-`` `
+```
- A: `` Već daj Lizijinu pizzu! ``
- B: `TypeError: nije function`
@@ -952,7 +952,7 @@ način!
###### 29. Što je izlaz?
-`` `{.javascript}
+```javascript
const a = {};
const b = {ključ: "b"};
const c = {ključ: "c"};
@@ -961,7 +961,7 @@ a [b] = 123;
a [c] = 456;
console.log (a [b]);
-`` `
+```
- A: '123'
- B: "456"
@@ -991,7 +991,7 @@ da na `456`, tako da se vraća` 456`.
###### 30. Što je izlaz?
-`` `{.javascript}
+```javascript
const foo = () => console.log ("Prvo");
const bar = () => setTimeout (() => console.log ("Drugi"));
const baz = () => console.log ("Treći");
@@ -999,7 +999,7 @@ const baz = () => console.log ("Treći");
bar();
foo ();
baz ();
-`` `
+```
- A: `Prvi`` Drugi` `Treći`
- B: `Prvi`` Treći` `Drugi`
@@ -1054,7 +1054,7 @@ stog.
###### 31. Što je event.target kada kliknete na gumb?
-`` `{.html}
+```{.html}
@@ -1062,7 +1062,7 @@ stog.
Tipka>
Div>
Div>
-`` `
+```
- A: Vanjski 'div'
- B: Unutarnji 'div'
@@ -1084,13 +1084,13 @@ događaj. Možete zaustaviti mjehuriće 'event.stopPropagation'
###### 32. Kada kliknete na paragraf, što je zapisani izlaz?
-`` `{.html}
+```{.html}
Kliknite ovdje!
P>
Div>
-`` `
+```
- A: `p`` div`
- B: `div`` p`
@@ -1115,7 +1115,7 @@ van.
###### 33. Što je izlaz?
-`` `{.javascript}
+```javascript
const Person = {ime: "Lydia"};
function sayHi (dob) {
@@ -1124,7 +1124,7 @@ function sayHi (dob) {
sayHi.call (Person, 21);
sayHi.bind (Person, 21);
-`` `
+```
- A: `undefined is 21`` Lydia je 21`
- B: function funkcije
@@ -1149,13 +1149,13 @@ se ne izvršava odmah.
###### 34. Što je izlaz?
-`` `{.javascript}
+```javascript
function sayHi () {
return (() => 0) ();
}
vrsta rečiHi ();
-`` `
+```
- A: `" objekt "`
- B: `" broj "
@@ -1182,16 +1182,16 @@ budući da su funkcije objekti, to je tipa `` objekta '`.
###### 35. Koja od ovih vrijednosti su neistinite?
-`` `{.javascript}
+```javascript
0;
new broj (0);
( "");
("");
new logički (false);
nedefiniran;
-`` `
+```
-- A: `0`,` `` `,` undefined`
+- A: `0`,` ```,` undefined`
- B: `0`,` new Number (0) `,` '' `,` new Boolean (false) `,` undefined '
- C: `0`,` '' `,` new Boolean (false) `,` undefined`
- D: Svi su oni lažni
@@ -1219,9 +1219,9 @@ Konstruktori function, kao što su 'new Number' i 'new Boolean' su istiniti.
###### 36. Što je izlaz?
-`` `{.javascript}
+```javascript
console.log (vrsta tipa 1);
-`` `
+```
- A: `" broj "
- B: niz ""
@@ -1242,11 +1242,11 @@ console.log (vrsta tipa 1);
###### 37. Što je izlaz?
-`` `{.javascript}
+```javascript
const brojevi = [1, 2, 3];
brojevi [10] = 11;
console.log (br);
-`` `
+```
- A: `[1, 2, 3, 7 x null, 11]`
- B: `[1, 2, 3, 11]`
@@ -1274,7 +1274,7 @@ itd)
###### 38. Što je izlaz?
-`` `{.javascript}
+```javascript
(() => {
let x, y;
pokušaj {
@@ -1286,7 +1286,7 @@ itd)
console.log (x);
console.log (y);
}) ();
-`` `
+```
- A: `1`` undefined `` 2`
- B: `undefined`` undefined` `undefined`
@@ -1347,14 +1347,14 @@ osim "null" i "undefined" pokazuju ovo ponašanje.
###### 40. Što je izlaz?
-`` `{.javascript}
+```javascript
[[0, 1], [2, 3]].
(acc, cur) => {
povratak acc.concat (cur);
}
[1, 2]
);
-`` `
+```
- A: `[0, 1, 2, 3, 1, 2]`
- B: `[6, 1, 2]`
@@ -1371,7 +1371,7 @@ vrijednost prvog `acc`. Tijekom prvog kruga, "acc" je "[1,2]",
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
+Tada je `[1, 2, 0, 1]` `acc` i` [2, 3] `````. Ulančavamo se
i dobiti `[1, 2, 0, 1, 2, 3]`
P>
@@ -1381,11 +1381,11 @@ i dobiti `[1, 2, 0, 1, 2, 3]`
###### 41. Što je izlaz?
-`` `{.javascript}
+```javascript
!! null;
!! "";
!! 1;
-`` `
+```
- A: `false`` true` `false`
- B: `false`` false` `true`
@@ -1399,7 +1399,7 @@ i dobiti `[1, 2, 0, 1, 2, 3]`
`null` je lažan. `! null` vraća 'true'. `! true 'vraća" false ".
-`` `` je neistinit. `!" `` vraća `true '. `! true 'vraća" false ".
+```` je neistinit. `!" `` vraća `true '. `! true 'vraća" false ".
"1" je istina. `! 1` vraća 'false'. `! false 'vraća' true '.
@@ -1410,9 +1410,9 @@ i dobiti `[1, 2, 0, 1, 2, 3]`
###### 42. Što se vraća metoda `setInterval`?
-`` `{.javascript}
+```javascript
setInterval (() => console.log ("Hi"), 1000);
-`` `
+```
- A: jedinstveni ID
- B: određena količina milisekundi
@@ -1434,9 +1434,9 @@ Vraća jedinstveni ID. Taj se ID može koristiti za brisanje tog intervala
###### 43. Što se to vraća?
-`` `{.javascript}
+```javascript
[... "Lydia"];
-`` `
+```
- A: `[" L "," y "," d "," i "," a "]`
- B: `[" Lydia "]`
From 5fda4aaa900cef432920da35efa902e6886bead4 Mon Sep 17 00:00:00 2001
From: nedimf <24845593+nedimf@users.noreply.github.com>
Date: Tue, 18 Jun 2019 19:54:08 +0200
Subject: [PATCH 019/915] Update README.md
---
README.md | 170 +++++++++++++++++++++++++++---------------------------
1 file changed, 85 insertions(+), 85 deletions(-)
diff --git a/README.md b/README.md
index a7d855b2..b7c2095a 100644
--- a/README.md
+++ b/README.md
@@ -91,8 +91,8 @@ 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.
- p>
- details>
+
+
* * * * *
@@ -131,8 +131,8 @@ okruženje (primjerice, prozor).
Na tom objektu nema vrijednosti `radius` koja vraća` undefined`.
- p>
- details>
+
+
* * * * *
@@ -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".
- p>
- details>
+
+
* * * * *
@@ -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`.
- P>
- details>
+
+
* * * * *
@@ -244,8 +244,8 @@ s istom referencom koju `c 'ima na objekt.
Kada promijenite jedan objekt, mijenjate ih sve.
- p>
- details>
+
+
* * * * *
@@ -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"
- P>
- details>
+
+
* * * * *
@@ -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`.
- P>
- details>
+
+
* * * * *
@@ -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.
- P>
- details>
+
+
* * * * *
@@ -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.
- P>
- details>
+
+
* * * * *
@@ -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!
- P>
- details>
+
+
* * * * *
@@ -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'.
- P>
- details>
+
+
* * * * *
@@ -496,8 +496,8 @@ i ** bubbling **.
- P>
- details>
+
+
* * * * *
@@ -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.
- P>
- details>
+
+
* * * * *
@@ -555,8 +555,8 @@ se tretira kao niz. Možemo slično spojiti
"" Zdravo "+" Svijet "`, tako da se ovdje događa ``````````````````
vraća `" 12 "`.
- P>
- details>
+
+
* * * * *
@@ -591,8 +591,8 @@ console.log (broj);
Ovo vraća `0 2 2`.
- P>
- details>
+
+
* * * * *
@@ -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!
- P>
- details>
+
+
* * * * *
@@ -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 '.
- P>
- details>
+
+
* * * * *
@@ -693,8 +693,8 @@ getAge (21);
Operator spread (`... args`.) Vraća niz s argumentima.
array je objekt, pa `typeof args` vraća` `objekt '`
- P>
- details>
+
+
* * * * *
@@ -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.
- P>
- details>
+
+
* * * * *
@@ -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".
- P>
- details>
+
+
* * * * *
@@ -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.
- P>
- details>
+
+
* * * * *
@@ -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.
- P>
- details>
+
+
* * * * *
@@ -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`.
- P>
- details>
+
+
* * * * *
@@ -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.
- P>
- details>
+
+
* * * * *
@@ -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.
- P>
- details>
+
+
* * * * *
@@ -912,8 +912,8 @@ za (let i = 1; i <5; i ++) {
Izjava `continue` preskače iteraciju ako je određeno stanje
vraća "true".
- P>
- details>
+
+
* * * * *
@@ -945,8 +945,8 @@ automatski se pretvara u string objekt, generiran stringom
prototipna function. Dakle, svi nizovi (objekti stringova) imaju pristup tome
način!
- P>
- details>
+
+
* * * * *
@@ -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`.
- P>
- details>
+
+
* * * * *
@@ -1047,8 +1047,8 @@ stvar u redu i gura je u stog.
`bar` se priziva,` `Second`` se bilježi, i on se pojavio
stog.
- P>
- details>
+
+
* * * * *
@@ -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'
- P>
- details>
+
+
* * * * *
@@ -1088,7 +1088,7 @@ događaj. Možete zaustaviti mjehuriće 'event.stopPropagation'
Kliknite ovdje!
- P>
+
Div>
```
@@ -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.
- P>
- details>
+
+
* * * * *
@@ -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.
- P>
- details>
+
+
* * * * *
@@ -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 '`.
- P>
- details>
+
+
* * * * *
@@ -1212,8 +1212,8 @@ Postoji samo šest krivotvorenih vrijednosti:
Konstruktori function, kao što su 'new Number' i 'new Boolean' su istiniti.
- P>
- details>
+
+
* * * * *
@@ -1235,8 +1235,8 @@ console.log (vrsta tipa 1);
`typeof 1` vraća` `broj ''. `typeof" number "` return `` string "`
- P>
- details>
+
+
* * * * *
@@ -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)
- P>
- details>
+
+
* * * * *
@@ -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`.
- P>
- details>
+
+
* * * * *
@@ -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.
- P>
- details>
+
+
* * * * *
@@ -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]`
- P>
- details>
+
+
* * * * *
@@ -1403,8 +1403,8 @@ i dobiti `[1, 2, 0, 1, 2, 3]`
"1" je istina. `! 1` vraća 'false'. `! false 'vraća' true '.
- P>
- details>
+
+
* * * * *
@@ -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.
- P>
- details>
+
+
* * * * *
@@ -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.
- P>
- details>
+
+
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 b> summary>
-
+ Odgovor
+
#### Odgovor: C
@@ -116,8 +116,8 @@ oblik.promjer ();
- C: "20" i "63"
- D: "NaN" i "63"
- Odgovor b> summary>
-
+ 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 b> summary>
-
+ Odgovor
+
#### Odgovor: A
@@ -181,8 +181,8 @@ const mouse = {
- C: `miš [ptica [" veličina "]]` nije važeća
- D: Svi su valjani
- Odgovor b> summary>
-
+ Odgovor
+
#### Odgovor: A
@@ -229,8 +229,8 @@ console.log (d.greeting);
- D: "ReferenceError"
- E: `TypeError`
- Odgovor b> summary>
-
+ Odgovor
+
#### Odgovor: A
@@ -266,8 +266,8 @@ console.log (b === c);
- C: `true`` false` `false`
- D: `false`` true` `true`
- Odgovor b> summary>
-
+ Odgovor
+
#### Odgovor: C
@@ -310,8 +310,8 @@ freddie.colorChange("orange");
- C: "zelena"
- D: `TypeError`
- Odgovor b> summary>
-
+ Odgovor
+
#### Odgovor: D
@@ -338,8 +338,8 @@ console.log (greetign);
- B: `ReferenceError: greetign nije definiran '
- C: `undefined`
- Odgovor b> summary>
-
+ Odgovor
+
#### Odgovor: A
@@ -371,8 +371,8 @@ bark.animal = "dog";
- C: `undefined`
- D: "ReferenceError"
- Odgovor b> summary>
-
+ Odgovor
+
#### Odgovor: A
@@ -409,8 +409,8 @@ console.log (member.getFullName ());
- C: "Lydia Hallie"
- D: `undefined`` undefined`
- Odgovor b> summary>
-
+ Odgovor
+
#### Odgovor: A
@@ -458,8 +458,8 @@ console.log (sarah);
- D: `Person {ime:" Lydia ", prezime:" Hallie "} i
`ReferenceError`
- Odgovor b> summary>
-
+ Odgovor
+
#### Odgovor: A
@@ -485,8 +485,8 @@ sam je ostavljen 'undefined'.
- D: Capturing > Target > Bubbling
- Odgovor b> summary>
-
+ Odgovor
+
#### Odgovor: D
@@ -506,8 +506,8 @@ i ** bubbling **.
- Istinito
- B: lažno
- Odgovor b> summary>
-
+ Odgovor
+
#### Odgovor: B
@@ -538,8 +538,8 @@ sum (1, "2");
- C: "12"
- D: `3`
- Odgovor b> summary>
-
+ Odgovor
+
#### Odgovor: C
@@ -574,8 +574,8 @@ console.log (broj);
- C: `0`` 2` `2`
- D: `0`` 1` `2`
- Odgovor b> summary>
-
+ Odgovor
+
#### Odgovor: C
@@ -615,8 +615,8 @@ getPersonInfo` $ {Person} je $ {old} godina ';
- B: ```````````````````````````````````````````````````````````````````````````
- C: `` Lydia` ``````````````````````````````````````````````````````````
- Odgovor b> summary>
-
+ 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 b> summary>
-
+ Odgovor
+
#### Odgovor: C
@@ -685,8 +685,8 @@ getAge (21);
- C: `` objekt ''
- D: "NaN"
- Odgovor b> summary>
-
+ Odgovor
+
#### Odgovor: C
@@ -715,8 +715,8 @@ getAge ();
- C: "ReferenceError"
- D: `TypeError`
- Odgovor b> summary>
-
+ Odgovor
+
#### Odgovor: C
@@ -742,8 +742,8 @@ const sum = eval ("10x10 + 5");
- C: `TypeError`
- D: `" 10 * 10 + 5 "`
- Odgovor b> summary>
-
+ 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 b> summary>
-
+ Odgovor
+
#### Odgovor: B
@@ -796,8 +796,8 @@ console.log (num);
- C: `SyntaxError`
- D: "ReferenceError"
- Odgovor b> summary>
-
+ Odgovor
+
#### Odgovor: B
@@ -828,8 +828,8 @@ set.has (1);
- C: `true`` true` `false`` true`
- D: `true`` true` `true`` true`
- Odgovor b> summary>
-
+ Odgovor
+
#### Odgovor: C
@@ -858,8 +858,8 @@ console.log (obj);
- C: `{a:" tri ", b:" dva "}`
- D: `SyntaxError`
- Odgovor b> summary>
-
+ 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 b> summary>
-
+ Odgovor
+
#### Odgovor: A
@@ -904,8 +904,8 @@ za (let i = 1; i <5; i ++) {
- C: `1`` 2` `4`
- D: `1`` 3` `4`
- Odgovor b> summary>
-
+ Odgovor
+
#### Odgovor: C
@@ -934,8 +934,8 @@ name.giveLydiaPizza ();
- C: `SyntaxError`
- D: `undefined`
- Odgovor b> summary>
-
+ Odgovor
+
#### Odgovor: A
@@ -968,8 +968,8 @@ console.log (a [b]);
- C: `undefined`
- D: "ReferenceError"
- Odgovor b> summary>
-
+ Odgovor
+
#### Odgovor: B
@@ -1006,8 +1006,8 @@ baz ();
- C: `Drugi`` Prvi` `Treći`
- D: `Drugi`` Treći` `Prvi`
- Odgovor b> summary>
-
+ Odgovor
+
#### Odgovor: B
@@ -1069,8 +1069,8 @@ stog.
- C: `gumb '
- D: Niz svih ugniježđenih elemenata.
- Odgovor b> summary>
-
+ Odgovor
+
#### Odgovor: C
@@ -1097,8 +1097,8 @@ događaj. Možete zaustaviti mjehuriće 'event.stopPropagation'
- C: p
- D: "div"
- Odgovor b> summary>
-
+ Odgovor
+
#### Odgovor: A
@@ -1131,8 +1131,8 @@ sayHi.bind (Person, 21);
- C: `Lydia je 21`` Lydia je 21`
- D: `Lydia je 21`` function`
- Odgovor b> summary>
-
+ Odgovor
+
#### Odgovor: D
@@ -1162,8 +1162,8 @@ vrsta rečiHi ();
- C: function ""
- D: `" undefined "`
- Odgovor b> summary>
-
+ Odgovor
+
#### Odgovor: B
@@ -1196,8 +1196,8 @@ nedefiniran;
- C: `0`,` '' `,` new Boolean (false) `,` undefined`
- D: Svi su oni lažni
- Odgovor b> summary>
-
+ Odgovor
+
#### Odgovor: A
@@ -1228,8 +1228,8 @@ console.log (vrsta tipa 1);
- C: `` objekt ''
- D: `" undefined "`
- Odgovor b> summary>
-
+ Odgovor
+
#### Odgovor: B
@@ -1253,8 +1253,8 @@ console.log (br);
- C: `[1, 2, 3, 7 x prazno, 11]`
- D: `SyntaxError`
- Odgovor b> summary>
-
+ Odgovor
+
#### Odgovor: C
@@ -1293,8 +1293,8 @@ itd)
- C: `1`` 1` `2`
- D: `1`` undefined` `undefined`
- Odgovor b> summary>
-
+ 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 b> summary>
-
+ 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 b> summary>
-
+ Odgovor
+
#### Odgovor: C
@@ -1392,8 +1392,8 @@ i dobiti `[1, 2, 0, 1, 2, 3]`
- C: `false`` true` `true`
- D: `true`` true` `false`
- Odgovor b> summary>
-
+ Odgovor
+
#### Odgovor: B
@@ -1419,8 +1419,8 @@ setInterval (() => console.log ("Hi"), 1000);
- C: prošla function
- D: `undefined`
- Odgovor b> summary>
-
+ 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 b> summary>
-
+ 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.
Klik!
- Tipka>
- Div>
- Div>
+
+
+
```
- A: Vanjski 'div'
@@ -1089,7 +1089,7 @@ događaj. Možete zaustaviti mjehuriće 'event.stopPropagation'
Kliknite ovdje!
- Div>
+
```
- 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
+
+```
+
+- 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
+
+```
+
+- 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
+
+```
+
+- 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
+
+```
+
+- 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}
-
-
-
- Klik!
+
+
+
```
- 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!
+
```
@@ -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
+
+```
+
+- 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
+
+```
+
+- 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
+
+```
+
+- 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
+
+```
+
+- 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
+